@uniformdev/context 20.3.1-alpha.7 → 20.4.1-alpha.15

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,4 +1,4 @@
1
- import { aD as paths$7, N as ManifestV2 } from '../types-gu4PVkDD.mjs';
1
+ import { aH as paths$7, _ as ManifestV2 } from '../types-BPchcX4k.mjs';
2
2
  import 'mitt';
3
3
 
4
4
  type LimitPolicy = <ReturnValue>(func: () => Promise<ReturnValue>) => Promise<ReturnValue>;
package/dist/api/api.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { aD as paths$7, N as ManifestV2 } from '../types-gu4PVkDD.js';
1
+ import { aH as paths$7, _ as ManifestV2 } from '../types-BPchcX4k.js';
2
2
  import 'mitt';
3
3
 
4
4
  type LimitPolicy = <ReturnValue>(func: () => Promise<ReturnValue>) => Promise<ReturnValue>;
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { O as OutputSeverity, L as LogDrain, C as ContextPlugin, S as ScoreVector, A as AggregateDimension, T as TransitionDataStore, a as StorageCommands, V as VisitorData, Q as Quirks, b as TransitionDataStoreOptions, D as DecayFunction, c as CriteriaEvaluator, d as StringMatch, e as VariantMatchCriteria, f as LogMessage, g as DevToolsEvents } from './types-gu4PVkDD.mjs';
2
- export { $ as AggregateDimensionInput, a6 as BehaviorTag, h as CONTEXTUAL_EDITING_TEST_NAME, i as CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID, n as Context, l as ContextEvents, m as ContextInstance, j as ContextOptions, aA as ContextState, aB as ContextStateUpdate, J as CriteriaEvaluatorParameters, I as CriteriaEvaluatorResult, ap as DecayOptions, q as DevToolsActions, t as DevToolsDataEvent, r as DevToolsEvent, x as DevToolsForgetEvent, u as DevToolsHelloEvent, s as DevToolsLogEvent, w as DevToolsRawCommandsEvent, p as DevToolsState, o as DevToolsUiVersion, v as DevToolsUpdateEvent, a2 as DimensionMatch, Y as EnrichmentCategory, av as EnrichmentData, ay as EventData, aC as GoalStateUpdate, au as Goals, H as GroupCriteriaEvaluator, ai as IdentifyCommand, F as LogMessageGroup, E as LogMessageSingle, y as LogMessages, G as ManifestInstance, N as ManifestV2, M as MessageCategory, B as MessageFunc, ad as ModifyScoreCommand, ae as ModifySessionScoreCommand, Z as NumberMatch, P as PersonalizationEvent, R as PersonalizationManifest, aw as PersonalizeControlVariant, a4 as PersonalizeOptions, ax as PersonalizeVariants, a8 as PersonalizedResult, a7 as PersonalizedVariant, a3 as QuirkMatch, an as SERVER_STATE_ID, am as ServerToClientTransitionState, af as SetConsentCommand, aj as SetControlGroupCommand, ac as SetGoalCommand, ak as SetPersonalizeVariantControlCommand, ag as SetQuirkCommand, ah as SetTestCommand, z as Severity, U as Signal, X as SignalCriteria, W as SignalCriteriaGroup, K as SignalData, ab as StorageCommand, _ as TestDefinition, k as TestEvent, a0 as TestOptions, aa as TestResult, a9 as TestVariant, at as Tests, ao as TransitionDataStoreEvents, as as VisitorDataStore, ar as VisitorDataStoreEvents, aq as VisitorDataStoreOptions, al as areCommandsEqual, az as emptyVisitorData, a5 as personalizeVariations, a1 as testVariations } from './types-gu4PVkDD.mjs';
1
+ import { O as OutputSeverity, L as LogDrain, C as ContextPlugin, S as ScoreVector, A as AggregateDimension, T as TransitionDataStore, a as StorageCommands, V as VisitorData, Q as Quirks, b as TransitionDataStoreOptions, D as DecayFunction, c as CriteriaEvaluator, d as StringMatch, e as VariantMatchCriteria, f as LogMessage, P as PersonalizedVariant, g as PersonalizeOptions, h as Context, i as PersonalizedResult, j as PersonalizationSelectionAlgorithmOptions, k as DevToolsEvents } from './types-BPchcX4k.mjs';
2
+ export { a6 as AggregateDimensionInput, ac as BehaviorTag, l as CONTEXTUAL_EDITING_TEST_NAME, m as CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID, t as ContextEvents, u as ContextInstance, p as ContextOptions, aE as ContextState, aF as ContextStateUpdate, Y as CriteriaEvaluatorParameters, X as CriteriaEvaluatorResult, at as DecayOptions, x as DevToolsActions, B as DevToolsDataEvent, y as DevToolsEvent, H as DevToolsForgetEvent, E as DevToolsHelloEvent, z as DevToolsLogEvent, G as DevToolsRawCommandsEvent, w as DevToolsState, v as DevToolsUiVersion, F as DevToolsUpdateEvent, aa as DimensionMatch, a3 as EnrichmentCategory, az as EnrichmentData, aC as EventData, aG as GoalStateUpdate, ay as Goals, W as GroupCriteriaEvaluator, am as IdentifyCommand, R as LogMessageGroup, N as LogMessageSingle, I as LogMessages, U as ManifestInstance, _ as ManifestV2, M as MessageCategory, K as MessageFunc, ah as ModifyScoreCommand, ai as ModifySessionScoreCommand, a4 as NumberMatch, r as PersonalizationEvent, q as PersonalizationEventVariantId, $ as PersonalizationManifest, n as PersonalizationSelectionAlgorithm, o as PersonalizationSelectionAlgorithms, aA as PersonalizeControlVariant, aB as PersonalizeVariants, ab as QuirkMatch, ar as SERVER_STATE_ID, aq as ServerToClientTransitionState, aj as SetConsentCommand, an as SetControlGroupCommand, ag as SetGoalCommand, ao as SetPersonalizeVariantControlCommand, ak as SetQuirkCommand, al as SetTestCommand, J as Severity, a0 as Signal, a2 as SignalCriteria, a1 as SignalCriteriaGroup, Z as SignalData, af as StorageCommand, a5 as TestDefinition, s as TestEvent, a7 as TestOptions, ae as TestResult, ad as TestVariant, ax as Tests, as as TransitionDataStoreEvents, a9 as VariantMatchMetadata, aw as VisitorDataStore, av as VisitorDataStoreEvents, au as VisitorDataStoreOptions, ap as areCommandsEqual, aD as emptyVisitorData, a8 as testVariations } from './types-BPchcX4k.mjs';
3
3
  import Cookies from 'js-cookie';
4
4
  import 'mitt';
5
5
 
@@ -160,6 +160,21 @@ declare function enableDebugConsoleLogDrain(level: OutputSeverity, options?: Con
160
160
 
161
161
  declare function evaluateVariantMatch(variantId: string, match: VariantMatchCriteria | undefined | null, vec: ScoreVector, onLogMessage?: (message: LogMessage) => void, quirks?: Quirks): boolean;
162
162
 
163
+ /**
164
+ * @deprecated Use `topDownCriteriaPersonalizationSelectionAlgorithm` instead
165
+ */
166
+ declare function personalizeVariations<TVariant extends PersonalizedVariant<VariantMatchCriteria>>(options: PersonalizeOptions<TVariant> & {
167
+ context: Context;
168
+ }): PersonalizedResult<TVariant>;
169
+
170
+ /**
171
+ * Implementation of the top-down criteria personalization selection algorithm.
172
+ *
173
+ * In this mode, we evaluate variations in the order they are declared and the first <take>
174
+ * variations whose criteria evaluate to true are selected.
175
+ */
176
+ declare function topDownCriteriaPersonalizationSelectionAlgorithm<TCriteria extends VariantMatchCriteria, TVariation extends PersonalizedVariant<TCriteria>>({ name, context, variations, take, onLogMessage, }: PersonalizationSelectionAlgorithmOptions<TCriteria, TVariation>): PersonalizedResult<TVariation>;
177
+
163
178
  type ContextDevToolOptions = {
164
179
  onAfterMessageReceived?: (message: DevToolsEvents) => void;
165
180
  };
@@ -183,6 +198,7 @@ declare enum ScriptType {
183
198
  type EdgePersonalizeComponentOptions = {
184
199
  name: string;
185
200
  count?: number;
201
+ algorithm?: string;
186
202
  };
187
203
  type EdgeTestComponentOptions = {
188
204
  name: string;
@@ -213,4 +229,4 @@ type QuickConnectConfig = {
213
229
  declare function serializeQuickConnect(config: QuickConnectConfig): string;
214
230
  declare function parseQuickConnect(serialized: string): Required<QuickConnectConfig>;
215
231
 
216
- export { AggregateDimension, type ConsoleDebugLogDrainOptions, type ContextDevToolOptions, ContextPlugin, CookieTransitionDataStore, type CookieTransitionDataStoreOptions, CriteriaEvaluator, DecayFunction, DevToolsEvents, ENR_SEPARATOR, EdgeNodeTagName, type EdgePersonalizeComponentOptions, type EdgeTestComponentOptions, EdgeTransitionDataStore, type EdgeTransitionDataStoreOptions, type EnableUniformInsightsOptions, KV_SEP, type LinearDecayOptions, LogDrain, LogMessage, OutputSeverity, PAIR_SEP, QUIRK_SEP, type QuickConnectConfig, Quirks, ScoreVector, ScriptType, StorageCommands, StringMatch, TYPE_SEP, TransitionDataStore, TransitionDataStoreOptions, UNIFORM_DEFAULT_COOKIE_NAME, UNIFORM_DEFAULT_QUIRK_COOKIE_NAME, VariantMatchCriteria, VisitorData, computeAggregateDimensions, cookieEvaluator, createConsoleLogDrain, createDebugConsoleLogDrain, createLinearDecay, currentPageEvaluator, decodeCookieType, decodePersonalizeVariants, enableConsoleLogDrain, enableContextDevTools, enableDebugConsoleLogDrain, enableUniformInsights, encodeCookieType, evaluateVariantMatch, eventEvaluator, explainStringMatch, explainStringMatchCriteria, getEnrichmentVectorKey, isStringMatch, pageViewCountDimension, pageViewCountEvaluator, parseCookieScores, parseCookieType, parseQuickConnect, parseQuirkCookie, parseScoreCookie, queryStringEvaluator, quirkEvaluator, serializeCookie, serializeCookieType, serializePersonalizeVariants, serializeQuickConnect, serializeQuirks };
232
+ export { AggregateDimension, type ConsoleDebugLogDrainOptions, Context, type ContextDevToolOptions, ContextPlugin, CookieTransitionDataStore, type CookieTransitionDataStoreOptions, CriteriaEvaluator, DecayFunction, DevToolsEvents, ENR_SEPARATOR, EdgeNodeTagName, type EdgePersonalizeComponentOptions, type EdgeTestComponentOptions, EdgeTransitionDataStore, type EdgeTransitionDataStoreOptions, type EnableUniformInsightsOptions, KV_SEP, type LinearDecayOptions, LogDrain, LogMessage, OutputSeverity, PAIR_SEP, PersonalizationSelectionAlgorithmOptions, PersonalizeOptions, PersonalizedResult, PersonalizedVariant, QUIRK_SEP, type QuickConnectConfig, Quirks, ScoreVector, ScriptType, StorageCommands, StringMatch, TYPE_SEP, TransitionDataStore, TransitionDataStoreOptions, UNIFORM_DEFAULT_COOKIE_NAME, UNIFORM_DEFAULT_QUIRK_COOKIE_NAME, VariantMatchCriteria, VisitorData, computeAggregateDimensions, cookieEvaluator, createConsoleLogDrain, createDebugConsoleLogDrain, createLinearDecay, currentPageEvaluator, decodeCookieType, decodePersonalizeVariants, enableConsoleLogDrain, enableContextDevTools, enableDebugConsoleLogDrain, enableUniformInsights, encodeCookieType, evaluateVariantMatch, eventEvaluator, explainStringMatch, explainStringMatchCriteria, getEnrichmentVectorKey, isStringMatch, pageViewCountDimension, pageViewCountEvaluator, parseCookieScores, parseCookieType, parseQuickConnect, parseQuirkCookie, parseScoreCookie, personalizeVariations, queryStringEvaluator, quirkEvaluator, serializeCookie, serializeCookieType, serializePersonalizeVariants, serializeQuickConnect, serializeQuirks, topDownCriteriaPersonalizationSelectionAlgorithm };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { O as OutputSeverity, L as LogDrain, C as ContextPlugin, S as ScoreVector, A as AggregateDimension, T as TransitionDataStore, a as StorageCommands, V as VisitorData, Q as Quirks, b as TransitionDataStoreOptions, D as DecayFunction, c as CriteriaEvaluator, d as StringMatch, e as VariantMatchCriteria, f as LogMessage, g as DevToolsEvents } from './types-gu4PVkDD.js';
2
- export { $ as AggregateDimensionInput, a6 as BehaviorTag, h as CONTEXTUAL_EDITING_TEST_NAME, i as CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID, n as Context, l as ContextEvents, m as ContextInstance, j as ContextOptions, aA as ContextState, aB as ContextStateUpdate, J as CriteriaEvaluatorParameters, I as CriteriaEvaluatorResult, ap as DecayOptions, q as DevToolsActions, t as DevToolsDataEvent, r as DevToolsEvent, x as DevToolsForgetEvent, u as DevToolsHelloEvent, s as DevToolsLogEvent, w as DevToolsRawCommandsEvent, p as DevToolsState, o as DevToolsUiVersion, v as DevToolsUpdateEvent, a2 as DimensionMatch, Y as EnrichmentCategory, av as EnrichmentData, ay as EventData, aC as GoalStateUpdate, au as Goals, H as GroupCriteriaEvaluator, ai as IdentifyCommand, F as LogMessageGroup, E as LogMessageSingle, y as LogMessages, G as ManifestInstance, N as ManifestV2, M as MessageCategory, B as MessageFunc, ad as ModifyScoreCommand, ae as ModifySessionScoreCommand, Z as NumberMatch, P as PersonalizationEvent, R as PersonalizationManifest, aw as PersonalizeControlVariant, a4 as PersonalizeOptions, ax as PersonalizeVariants, a8 as PersonalizedResult, a7 as PersonalizedVariant, a3 as QuirkMatch, an as SERVER_STATE_ID, am as ServerToClientTransitionState, af as SetConsentCommand, aj as SetControlGroupCommand, ac as SetGoalCommand, ak as SetPersonalizeVariantControlCommand, ag as SetQuirkCommand, ah as SetTestCommand, z as Severity, U as Signal, X as SignalCriteria, W as SignalCriteriaGroup, K as SignalData, ab as StorageCommand, _ as TestDefinition, k as TestEvent, a0 as TestOptions, aa as TestResult, a9 as TestVariant, at as Tests, ao as TransitionDataStoreEvents, as as VisitorDataStore, ar as VisitorDataStoreEvents, aq as VisitorDataStoreOptions, al as areCommandsEqual, az as emptyVisitorData, a5 as personalizeVariations, a1 as testVariations } from './types-gu4PVkDD.js';
1
+ import { O as OutputSeverity, L as LogDrain, C as ContextPlugin, S as ScoreVector, A as AggregateDimension, T as TransitionDataStore, a as StorageCommands, V as VisitorData, Q as Quirks, b as TransitionDataStoreOptions, D as DecayFunction, c as CriteriaEvaluator, d as StringMatch, e as VariantMatchCriteria, f as LogMessage, P as PersonalizedVariant, g as PersonalizeOptions, h as Context, i as PersonalizedResult, j as PersonalizationSelectionAlgorithmOptions, k as DevToolsEvents } from './types-BPchcX4k.js';
2
+ export { a6 as AggregateDimensionInput, ac as BehaviorTag, l as CONTEXTUAL_EDITING_TEST_NAME, m as CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID, t as ContextEvents, u as ContextInstance, p as ContextOptions, aE as ContextState, aF as ContextStateUpdate, Y as CriteriaEvaluatorParameters, X as CriteriaEvaluatorResult, at as DecayOptions, x as DevToolsActions, B as DevToolsDataEvent, y as DevToolsEvent, H as DevToolsForgetEvent, E as DevToolsHelloEvent, z as DevToolsLogEvent, G as DevToolsRawCommandsEvent, w as DevToolsState, v as DevToolsUiVersion, F as DevToolsUpdateEvent, aa as DimensionMatch, a3 as EnrichmentCategory, az as EnrichmentData, aC as EventData, aG as GoalStateUpdate, ay as Goals, W as GroupCriteriaEvaluator, am as IdentifyCommand, R as LogMessageGroup, N as LogMessageSingle, I as LogMessages, U as ManifestInstance, _ as ManifestV2, M as MessageCategory, K as MessageFunc, ah as ModifyScoreCommand, ai as ModifySessionScoreCommand, a4 as NumberMatch, r as PersonalizationEvent, q as PersonalizationEventVariantId, $ as PersonalizationManifest, n as PersonalizationSelectionAlgorithm, o as PersonalizationSelectionAlgorithms, aA as PersonalizeControlVariant, aB as PersonalizeVariants, ab as QuirkMatch, ar as SERVER_STATE_ID, aq as ServerToClientTransitionState, aj as SetConsentCommand, an as SetControlGroupCommand, ag as SetGoalCommand, ao as SetPersonalizeVariantControlCommand, ak as SetQuirkCommand, al as SetTestCommand, J as Severity, a0 as Signal, a2 as SignalCriteria, a1 as SignalCriteriaGroup, Z as SignalData, af as StorageCommand, a5 as TestDefinition, s as TestEvent, a7 as TestOptions, ae as TestResult, ad as TestVariant, ax as Tests, as as TransitionDataStoreEvents, a9 as VariantMatchMetadata, aw as VisitorDataStore, av as VisitorDataStoreEvents, au as VisitorDataStoreOptions, ap as areCommandsEqual, aD as emptyVisitorData, a8 as testVariations } from './types-BPchcX4k.js';
3
3
  import Cookies from 'js-cookie';
4
4
  import 'mitt';
5
5
 
@@ -160,6 +160,21 @@ declare function enableDebugConsoleLogDrain(level: OutputSeverity, options?: Con
160
160
 
161
161
  declare function evaluateVariantMatch(variantId: string, match: VariantMatchCriteria | undefined | null, vec: ScoreVector, onLogMessage?: (message: LogMessage) => void, quirks?: Quirks): boolean;
162
162
 
163
+ /**
164
+ * @deprecated Use `topDownCriteriaPersonalizationSelectionAlgorithm` instead
165
+ */
166
+ declare function personalizeVariations<TVariant extends PersonalizedVariant<VariantMatchCriteria>>(options: PersonalizeOptions<TVariant> & {
167
+ context: Context;
168
+ }): PersonalizedResult<TVariant>;
169
+
170
+ /**
171
+ * Implementation of the top-down criteria personalization selection algorithm.
172
+ *
173
+ * In this mode, we evaluate variations in the order they are declared and the first <take>
174
+ * variations whose criteria evaluate to true are selected.
175
+ */
176
+ declare function topDownCriteriaPersonalizationSelectionAlgorithm<TCriteria extends VariantMatchCriteria, TVariation extends PersonalizedVariant<TCriteria>>({ name, context, variations, take, onLogMessage, }: PersonalizationSelectionAlgorithmOptions<TCriteria, TVariation>): PersonalizedResult<TVariation>;
177
+
163
178
  type ContextDevToolOptions = {
164
179
  onAfterMessageReceived?: (message: DevToolsEvents) => void;
165
180
  };
@@ -183,6 +198,7 @@ declare enum ScriptType {
183
198
  type EdgePersonalizeComponentOptions = {
184
199
  name: string;
185
200
  count?: number;
201
+ algorithm?: string;
186
202
  };
187
203
  type EdgeTestComponentOptions = {
188
204
  name: string;
@@ -213,4 +229,4 @@ type QuickConnectConfig = {
213
229
  declare function serializeQuickConnect(config: QuickConnectConfig): string;
214
230
  declare function parseQuickConnect(serialized: string): Required<QuickConnectConfig>;
215
231
 
216
- export { AggregateDimension, type ConsoleDebugLogDrainOptions, type ContextDevToolOptions, ContextPlugin, CookieTransitionDataStore, type CookieTransitionDataStoreOptions, CriteriaEvaluator, DecayFunction, DevToolsEvents, ENR_SEPARATOR, EdgeNodeTagName, type EdgePersonalizeComponentOptions, type EdgeTestComponentOptions, EdgeTransitionDataStore, type EdgeTransitionDataStoreOptions, type EnableUniformInsightsOptions, KV_SEP, type LinearDecayOptions, LogDrain, LogMessage, OutputSeverity, PAIR_SEP, QUIRK_SEP, type QuickConnectConfig, Quirks, ScoreVector, ScriptType, StorageCommands, StringMatch, TYPE_SEP, TransitionDataStore, TransitionDataStoreOptions, UNIFORM_DEFAULT_COOKIE_NAME, UNIFORM_DEFAULT_QUIRK_COOKIE_NAME, VariantMatchCriteria, VisitorData, computeAggregateDimensions, cookieEvaluator, createConsoleLogDrain, createDebugConsoleLogDrain, createLinearDecay, currentPageEvaluator, decodeCookieType, decodePersonalizeVariants, enableConsoleLogDrain, enableContextDevTools, enableDebugConsoleLogDrain, enableUniformInsights, encodeCookieType, evaluateVariantMatch, eventEvaluator, explainStringMatch, explainStringMatchCriteria, getEnrichmentVectorKey, isStringMatch, pageViewCountDimension, pageViewCountEvaluator, parseCookieScores, parseCookieType, parseQuickConnect, parseQuirkCookie, parseScoreCookie, queryStringEvaluator, quirkEvaluator, serializeCookie, serializeCookieType, serializePersonalizeVariants, serializeQuickConnect, serializeQuirks };
232
+ export { AggregateDimension, type ConsoleDebugLogDrainOptions, Context, type ContextDevToolOptions, ContextPlugin, CookieTransitionDataStore, type CookieTransitionDataStoreOptions, CriteriaEvaluator, DecayFunction, DevToolsEvents, ENR_SEPARATOR, EdgeNodeTagName, type EdgePersonalizeComponentOptions, type EdgeTestComponentOptions, EdgeTransitionDataStore, type EdgeTransitionDataStoreOptions, type EnableUniformInsightsOptions, KV_SEP, type LinearDecayOptions, LogDrain, LogMessage, OutputSeverity, PAIR_SEP, PersonalizationSelectionAlgorithmOptions, PersonalizeOptions, PersonalizedResult, PersonalizedVariant, QUIRK_SEP, type QuickConnectConfig, Quirks, ScoreVector, ScriptType, StorageCommands, StringMatch, TYPE_SEP, TransitionDataStore, TransitionDataStoreOptions, UNIFORM_DEFAULT_COOKIE_NAME, UNIFORM_DEFAULT_QUIRK_COOKIE_NAME, VariantMatchCriteria, VisitorData, computeAggregateDimensions, cookieEvaluator, createConsoleLogDrain, createDebugConsoleLogDrain, createLinearDecay, currentPageEvaluator, decodeCookieType, decodePersonalizeVariants, enableConsoleLogDrain, enableContextDevTools, enableDebugConsoleLogDrain, enableUniformInsights, encodeCookieType, evaluateVariantMatch, eventEvaluator, explainStringMatch, explainStringMatchCriteria, getEnrichmentVectorKey, isStringMatch, pageViewCountDimension, pageViewCountEvaluator, parseCookieScores, parseCookieType, parseQuickConnect, parseQuirkCookie, parseScoreCookie, personalizeVariations, queryStringEvaluator, quirkEvaluator, serializeCookie, serializeCookieType, serializePersonalizeVariants, serializeQuickConnect, serializeQuirks, topDownCriteriaPersonalizationSelectionAlgorithm };
package/dist/index.esm.js CHANGED
@@ -633,7 +633,15 @@ function evaluateDimensionMatch(crit, vec, onLogMessage) {
633
633
  explainScore(onLogMessage, result, crit, lhsScore, rhsScore);
634
634
  return result;
635
635
  } else {
636
- throw new Error(`Unknown op: ${op}`);
636
+ onLogMessage == null ? void 0 : onLogMessage([
637
+ "error",
638
+ 302,
639
+ {
640
+ matched: false,
641
+ description: `${crit.l} ${crit.op} ${crit.rDim ? `${crit.rDim}` : crit.r}: Unknown op ${crit.op}.`
642
+ }
643
+ ]);
644
+ return false;
637
645
  }
638
646
  }
639
647
  function evaluateQuirkMatch(crit, quirks, onLogMessage) {
@@ -649,7 +657,15 @@ function evaluateQuirkMatch(crit, quirks, onLogMessage) {
649
657
  explainQuirk(onLogMessage, result, crit, targetQuirkValue);
650
658
  return result;
651
659
  } else {
652
- throw new Error(`Unknown quirk op: ${op}`);
660
+ onLogMessage == null ? void 0 : onLogMessage([
661
+ "error",
662
+ 302,
663
+ {
664
+ matched: false,
665
+ description: `Quirk ${crit.l} ${crit.op} ${crit.r}: Unknown quirk op ${crit.op}.`
666
+ }
667
+ ]);
668
+ return false;
653
669
  }
654
670
  }
655
671
  function explainScore(onLogMessage, result, crit, lhsScore, rhsScore) {
@@ -673,8 +689,8 @@ function explainQuirk(onLogMessage, result, crit, lhs) {
673
689
  ]);
674
690
  }
675
691
 
676
- // src/placement/personalizeVariations.ts
677
- function personalizeVariations({
692
+ // src/placement/topDownCriteriaPersonalizationSelectionAlgorithm.ts
693
+ function topDownCriteriaPersonalizationSelectionAlgorithm({
678
694
  name,
679
695
  context,
680
696
  variations,
@@ -689,12 +705,19 @@ function personalizeVariations({
689
705
  const needsConsent = context.requireConsentForPersonalization;
690
706
  const canEvaluate = !needsConsent || context.storage.data.consent;
691
707
  for (const variant of variations) {
692
- if ((_a = variant.pz) == null ? void 0 : _a.crit.length) {
693
- if (canEvaluate && variantMatches.length !== take && evaluateVariantMatch(variant.id, variant.pz, context.scores, onLogMessage, context.quirks)) {
694
- variantMatches.push(variant);
708
+ const isInvalidFormat = variant.pz && (typeof variant.pz !== "object" || variant.pz === null || !("crit" in variant.pz && Array.isArray(variant.pz.crit)));
709
+ let validVariant;
710
+ if (isInvalidFormat) {
711
+ validVariant = { id: variant.id };
712
+ } else {
713
+ validVariant = variant;
714
+ }
715
+ if ((_a = validVariant.pz) == null ? void 0 : _a.crit.length) {
716
+ if (canEvaluate && variantMatches.length !== take && evaluateVariantMatch(variant.id, validVariant.pz, context.scores, onLogMessage, context.quirks)) {
717
+ variantMatches.push(validVariant);
695
718
  }
696
719
  } else {
697
- defaultVariants.push(variant);
720
+ defaultVariants.push(validVariant);
698
721
  }
699
722
  }
700
723
  const result = [];
@@ -749,6 +772,11 @@ function personalizeVariations({
749
772
  }
750
773
  }
751
774
 
775
+ // src/placement/personalizeVariations.ts
776
+ function personalizeVariations(options) {
777
+ return topDownCriteriaPersonalizationSelectionAlgorithm(options);
778
+ }
779
+
752
780
  // src/placement/normalizeVariationDistributions.ts
753
781
  var normalizeVariationDistributions = (variations) => {
754
782
  const { values, total, missingDistribution } = variations.reduce(
@@ -768,7 +796,12 @@ var normalizeVariationDistributions = (variations) => {
768
796
  }
769
797
  );
770
798
  if (total > 100) {
771
- throw new Error(`Total distribution ${total} is over the maximum 100.`);
799
+ const autoScaleFactor = 100 / total;
800
+ values.forEach((value, index) => {
801
+ if (typeof value === "number") {
802
+ values[index] = value * autoScaleFactor;
803
+ }
804
+ });
772
805
  } else if (total < 100) {
773
806
  const remainder = 100 - total;
774
807
  const missingSlice = remainder / missingDistribution;
@@ -1548,11 +1581,12 @@ import { dequal as dequal5 } from "dequal/lite";
1548
1581
  import mitt3 from "mitt";
1549
1582
  var CONTEXTUAL_EDITING_TEST_NAME = "contextual_editing_test";
1550
1583
  var CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID = "contextual_editing_test_selected_variant";
1551
- var _serverTransitionState, _scores, _state, _pzCache, _plugins, _commands, _requireConsentForPersonalization, _mitt3, _Context_instances, emitTest_fn, updateGoals_fn, updateComputedScores_fn, calculateScores_fn;
1584
+ var _personalizationSelectionAlgorithms, _serverTransitionState, _scores, _state, _pzCache, _plugins, _commands, _requireConsentForPersonalization, _mitt3, _Context_instances, emitTest_fn, updateGoals_fn, updateComputedScores_fn, calculateScores_fn;
1552
1585
  var Context = class {
1553
1586
  constructor(options) {
1554
1587
  __privateAdd(this, _Context_instances);
1555
1588
  __publicField(this, "manifest");
1589
+ __privateAdd(this, _personalizationSelectionAlgorithms);
1556
1590
  __privateAdd(this, _serverTransitionState);
1557
1591
  __privateAdd(this, _scores, {});
1558
1592
  __privateAdd(this, _state);
@@ -1569,7 +1603,7 @@ var Context = class {
1569
1603
  off: __privateGet(this, _mitt3).off
1570
1604
  });
1571
1605
  __publicField(this, "storage");
1572
- var _a, _b;
1606
+ var _a, _b, _c;
1573
1607
  const { manifest, ...storageOptions } = options;
1574
1608
  __privateSet(this, _state, {});
1575
1609
  __privateSet(this, _plugins, options.plugins);
@@ -1577,7 +1611,17 @@ var Context = class {
1577
1611
  if (typeof options.transitionStore !== "undefined") {
1578
1612
  __privateSet(this, _commands, []);
1579
1613
  }
1614
+ __privateSet(this, _personalizationSelectionAlgorithms, { default: topDownCriteriaPersonalizationSelectionAlgorithm });
1580
1615
  (_a = __privateGet(this, _plugins)) == null ? void 0 : _a.forEach((plugin) => {
1616
+ if (!plugin.personalizationSelectionAlgorithms) {
1617
+ return;
1618
+ }
1619
+ __privateSet(this, _personalizationSelectionAlgorithms, {
1620
+ ...__privateGet(this, _personalizationSelectionAlgorithms),
1621
+ ...plugin.personalizationSelectionAlgorithms
1622
+ });
1623
+ });
1624
+ (_b = __privateGet(this, _plugins)) == null ? void 0 : _b.forEach((plugin) => {
1581
1625
  if (!plugin.logDrain) {
1582
1626
  return;
1583
1627
  }
@@ -1628,7 +1672,7 @@ var Context = class {
1628
1672
  __privateGet(this, _mitt3).emit("quirksUpdated", quirks.quirks);
1629
1673
  __privateGet(this, _mitt3).emit("log", ["info", 4, quirks.quirks]);
1630
1674
  });
1631
- (_b = __privateGet(this, _plugins)) == null ? void 0 : _b.forEach((plugin) => {
1675
+ (_c = __privateGet(this, _plugins)) == null ? void 0 : _c.forEach((plugin) => {
1632
1676
  if (!plugin.init) {
1633
1677
  return;
1634
1678
  }
@@ -1878,7 +1922,17 @@ var Context = class {
1878
1922
  }
1879
1923
  /** Executes a personalized placement with a given set of variants */
1880
1924
  personalize(options) {
1881
- const value = personalizeVariations({
1925
+ var _a;
1926
+ const algorithmName = (_a = options.algorithm) != null ? _a : "default";
1927
+ const algorithm = __privateGet(this, _personalizationSelectionAlgorithms)[algorithmName];
1928
+ if (!algorithm) {
1929
+ __privateGet(this, _mitt3).emit("log", ["warn", 304, { algorithm: algorithmName }]);
1930
+ return {
1931
+ personalized: false,
1932
+ variations: []
1933
+ };
1934
+ }
1935
+ const value = algorithm({
1882
1936
  ...options,
1883
1937
  context: this,
1884
1938
  onLogMessage: (message) => __privateGet(this, _mitt3).emit("log", message)
@@ -1952,6 +2006,7 @@ var Context = class {
1952
2006
  __privateGet(this, _mitt3).emit("personalizationResult", event);
1953
2007
  }
1954
2008
  };
2009
+ _personalizationSelectionAlgorithms = new WeakMap();
1955
2010
  _serverTransitionState = new WeakMap();
1956
2011
  _scores = new WeakMap();
1957
2012
  _state = new WeakMap();
@@ -2547,6 +2602,10 @@ var messageContent = {
2547
2602
  301: ({ id, op }) => ["personalization", `testing variation ${id} (${op === "|" ? "OR" : "AND"})`],
2548
2603
  302: ({ matched, description }) => ["personalization", `${description} is ${matched}`],
2549
2604
  303: (selected) => ["personalization", selected ? "selected variation" : "did not select variation"],
2605
+ 304: ({ algorithm }) => [
2606
+ "personalization",
2607
+ `personalization selection algorithm '${algorithm}' not found. Hiding placement.`
2608
+ ],
2550
2609
  // TESTING
2551
2610
  400: (name) => ["testing", `executing A/B test '${name}'`],
2552
2611
  401: (testName) => ["testing", `${testName} is not registered in the manifest; it will not be run.`],
@@ -2693,5 +2752,6 @@ export {
2693
2752
  serializePersonalizeVariants,
2694
2753
  serializeQuickConnect,
2695
2754
  serializeQuirks,
2696
- testVariations
2755
+ testVariations,
2756
+ topDownCriteriaPersonalizationSelectionAlgorithm
2697
2757
  };
package/dist/index.js CHANGED
@@ -95,7 +95,8 @@ __export(src_exports, {
95
95
  serializePersonalizeVariants: () => serializePersonalizeVariants,
96
96
  serializeQuickConnect: () => serializeQuickConnect,
97
97
  serializeQuirks: () => serializeQuirks,
98
- testVariations: () => testVariations
98
+ testVariations: () => testVariations,
99
+ topDownCriteriaPersonalizationSelectionAlgorithm: () => topDownCriteriaPersonalizationSelectionAlgorithm
99
100
  });
100
101
  module.exports = __toCommonJS(src_exports);
101
102
 
@@ -722,7 +723,15 @@ function evaluateDimensionMatch(crit, vec, onLogMessage) {
722
723
  explainScore(onLogMessage, result, crit, lhsScore, rhsScore);
723
724
  return result;
724
725
  } else {
725
- throw new Error(`Unknown op: ${op}`);
726
+ onLogMessage == null ? void 0 : onLogMessage([
727
+ "error",
728
+ 302,
729
+ {
730
+ matched: false,
731
+ description: `${crit.l} ${crit.op} ${crit.rDim ? `${crit.rDim}` : crit.r}: Unknown op ${crit.op}.`
732
+ }
733
+ ]);
734
+ return false;
726
735
  }
727
736
  }
728
737
  function evaluateQuirkMatch(crit, quirks, onLogMessage) {
@@ -738,7 +747,15 @@ function evaluateQuirkMatch(crit, quirks, onLogMessage) {
738
747
  explainQuirk(onLogMessage, result, crit, targetQuirkValue);
739
748
  return result;
740
749
  } else {
741
- throw new Error(`Unknown quirk op: ${op}`);
750
+ onLogMessage == null ? void 0 : onLogMessage([
751
+ "error",
752
+ 302,
753
+ {
754
+ matched: false,
755
+ description: `Quirk ${crit.l} ${crit.op} ${crit.r}: Unknown quirk op ${crit.op}.`
756
+ }
757
+ ]);
758
+ return false;
742
759
  }
743
760
  }
744
761
  function explainScore(onLogMessage, result, crit, lhsScore, rhsScore) {
@@ -762,8 +779,8 @@ function explainQuirk(onLogMessage, result, crit, lhs) {
762
779
  ]);
763
780
  }
764
781
 
765
- // src/placement/personalizeVariations.ts
766
- function personalizeVariations({
782
+ // src/placement/topDownCriteriaPersonalizationSelectionAlgorithm.ts
783
+ function topDownCriteriaPersonalizationSelectionAlgorithm({
767
784
  name,
768
785
  context,
769
786
  variations,
@@ -778,12 +795,19 @@ function personalizeVariations({
778
795
  const needsConsent = context.requireConsentForPersonalization;
779
796
  const canEvaluate = !needsConsent || context.storage.data.consent;
780
797
  for (const variant of variations) {
781
- if ((_a = variant.pz) == null ? void 0 : _a.crit.length) {
782
- if (canEvaluate && variantMatches.length !== take && evaluateVariantMatch(variant.id, variant.pz, context.scores, onLogMessage, context.quirks)) {
783
- variantMatches.push(variant);
798
+ const isInvalidFormat = variant.pz && (typeof variant.pz !== "object" || variant.pz === null || !("crit" in variant.pz && Array.isArray(variant.pz.crit)));
799
+ let validVariant;
800
+ if (isInvalidFormat) {
801
+ validVariant = { id: variant.id };
802
+ } else {
803
+ validVariant = variant;
804
+ }
805
+ if ((_a = validVariant.pz) == null ? void 0 : _a.crit.length) {
806
+ if (canEvaluate && variantMatches.length !== take && evaluateVariantMatch(variant.id, validVariant.pz, context.scores, onLogMessage, context.quirks)) {
807
+ variantMatches.push(validVariant);
784
808
  }
785
809
  } else {
786
- defaultVariants.push(variant);
810
+ defaultVariants.push(validVariant);
787
811
  }
788
812
  }
789
813
  const result = [];
@@ -838,6 +862,11 @@ function personalizeVariations({
838
862
  }
839
863
  }
840
864
 
865
+ // src/placement/personalizeVariations.ts
866
+ function personalizeVariations(options) {
867
+ return topDownCriteriaPersonalizationSelectionAlgorithm(options);
868
+ }
869
+
841
870
  // src/placement/normalizeVariationDistributions.ts
842
871
  var normalizeVariationDistributions = (variations) => {
843
872
  const { values, total, missingDistribution } = variations.reduce(
@@ -857,7 +886,12 @@ var normalizeVariationDistributions = (variations) => {
857
886
  }
858
887
  );
859
888
  if (total > 100) {
860
- throw new Error(`Total distribution ${total} is over the maximum 100.`);
889
+ const autoScaleFactor = 100 / total;
890
+ values.forEach((value, index) => {
891
+ if (typeof value === "number") {
892
+ values[index] = value * autoScaleFactor;
893
+ }
894
+ });
861
895
  } else if (total < 100) {
862
896
  const remainder = 100 - total;
863
897
  const missingSlice = remainder / missingDistribution;
@@ -1637,11 +1671,12 @@ var import_lite5 = require("dequal/lite");
1637
1671
  var import_mitt3 = __toESM(require("mitt"));
1638
1672
  var CONTEXTUAL_EDITING_TEST_NAME = "contextual_editing_test";
1639
1673
  var CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID = "contextual_editing_test_selected_variant";
1640
- var _serverTransitionState, _scores, _state, _pzCache, _plugins, _commands, _requireConsentForPersonalization, _mitt3, _Context_instances, emitTest_fn, updateGoals_fn, updateComputedScores_fn, calculateScores_fn;
1674
+ var _personalizationSelectionAlgorithms, _serverTransitionState, _scores, _state, _pzCache, _plugins, _commands, _requireConsentForPersonalization, _mitt3, _Context_instances, emitTest_fn, updateGoals_fn, updateComputedScores_fn, calculateScores_fn;
1641
1675
  var Context = class {
1642
1676
  constructor(options) {
1643
1677
  __privateAdd(this, _Context_instances);
1644
1678
  __publicField(this, "manifest");
1679
+ __privateAdd(this, _personalizationSelectionAlgorithms);
1645
1680
  __privateAdd(this, _serverTransitionState);
1646
1681
  __privateAdd(this, _scores, {});
1647
1682
  __privateAdd(this, _state);
@@ -1658,7 +1693,7 @@ var Context = class {
1658
1693
  off: __privateGet(this, _mitt3).off
1659
1694
  });
1660
1695
  __publicField(this, "storage");
1661
- var _a, _b;
1696
+ var _a, _b, _c;
1662
1697
  const { manifest, ...storageOptions } = options;
1663
1698
  __privateSet(this, _state, {});
1664
1699
  __privateSet(this, _plugins, options.plugins);
@@ -1666,7 +1701,17 @@ var Context = class {
1666
1701
  if (typeof options.transitionStore !== "undefined") {
1667
1702
  __privateSet(this, _commands, []);
1668
1703
  }
1704
+ __privateSet(this, _personalizationSelectionAlgorithms, { default: topDownCriteriaPersonalizationSelectionAlgorithm });
1669
1705
  (_a = __privateGet(this, _plugins)) == null ? void 0 : _a.forEach((plugin) => {
1706
+ if (!plugin.personalizationSelectionAlgorithms) {
1707
+ return;
1708
+ }
1709
+ __privateSet(this, _personalizationSelectionAlgorithms, {
1710
+ ...__privateGet(this, _personalizationSelectionAlgorithms),
1711
+ ...plugin.personalizationSelectionAlgorithms
1712
+ });
1713
+ });
1714
+ (_b = __privateGet(this, _plugins)) == null ? void 0 : _b.forEach((plugin) => {
1670
1715
  if (!plugin.logDrain) {
1671
1716
  return;
1672
1717
  }
@@ -1717,7 +1762,7 @@ var Context = class {
1717
1762
  __privateGet(this, _mitt3).emit("quirksUpdated", quirks.quirks);
1718
1763
  __privateGet(this, _mitt3).emit("log", ["info", 4, quirks.quirks]);
1719
1764
  });
1720
- (_b = __privateGet(this, _plugins)) == null ? void 0 : _b.forEach((plugin) => {
1765
+ (_c = __privateGet(this, _plugins)) == null ? void 0 : _c.forEach((plugin) => {
1721
1766
  if (!plugin.init) {
1722
1767
  return;
1723
1768
  }
@@ -1967,7 +2012,17 @@ var Context = class {
1967
2012
  }
1968
2013
  /** Executes a personalized placement with a given set of variants */
1969
2014
  personalize(options) {
1970
- const value = personalizeVariations({
2015
+ var _a;
2016
+ const algorithmName = (_a = options.algorithm) != null ? _a : "default";
2017
+ const algorithm = __privateGet(this, _personalizationSelectionAlgorithms)[algorithmName];
2018
+ if (!algorithm) {
2019
+ __privateGet(this, _mitt3).emit("log", ["warn", 304, { algorithm: algorithmName }]);
2020
+ return {
2021
+ personalized: false,
2022
+ variations: []
2023
+ };
2024
+ }
2025
+ const value = algorithm({
1971
2026
  ...options,
1972
2027
  context: this,
1973
2028
  onLogMessage: (message) => __privateGet(this, _mitt3).emit("log", message)
@@ -2041,6 +2096,7 @@ var Context = class {
2041
2096
  __privateGet(this, _mitt3).emit("personalizationResult", event);
2042
2097
  }
2043
2098
  };
2099
+ _personalizationSelectionAlgorithms = new WeakMap();
2044
2100
  _serverTransitionState = new WeakMap();
2045
2101
  _scores = new WeakMap();
2046
2102
  _state = new WeakMap();
@@ -2636,6 +2692,10 @@ var messageContent = {
2636
2692
  301: ({ id, op }) => ["personalization", `testing variation ${id} (${op === "|" ? "OR" : "AND"})`],
2637
2693
  302: ({ matched, description }) => ["personalization", `${description} is ${matched}`],
2638
2694
  303: (selected) => ["personalization", selected ? "selected variation" : "did not select variation"],
2695
+ 304: ({ algorithm }) => [
2696
+ "personalization",
2697
+ `personalization selection algorithm '${algorithm}' not found. Hiding placement.`
2698
+ ],
2639
2699
  // TESTING
2640
2700
  400: (name) => ["testing", `executing A/B test '${name}'`],
2641
2701
  401: (testName) => ["testing", `${testName} is not registered in the manifest; it will not be run.`],
@@ -2783,5 +2843,6 @@ function parseQuickConnect(serialized) {
2783
2843
  serializePersonalizeVariants,
2784
2844
  serializeQuickConnect,
2785
2845
  serializeQuirks,
2786
- testVariations
2846
+ testVariations,
2847
+ topDownCriteriaPersonalizationSelectionAlgorithm
2787
2848
  });
package/dist/index.mjs CHANGED
@@ -633,7 +633,15 @@ function evaluateDimensionMatch(crit, vec, onLogMessage) {
633
633
  explainScore(onLogMessage, result, crit, lhsScore, rhsScore);
634
634
  return result;
635
635
  } else {
636
- throw new Error(`Unknown op: ${op}`);
636
+ onLogMessage == null ? void 0 : onLogMessage([
637
+ "error",
638
+ 302,
639
+ {
640
+ matched: false,
641
+ description: `${crit.l} ${crit.op} ${crit.rDim ? `${crit.rDim}` : crit.r}: Unknown op ${crit.op}.`
642
+ }
643
+ ]);
644
+ return false;
637
645
  }
638
646
  }
639
647
  function evaluateQuirkMatch(crit, quirks, onLogMessage) {
@@ -649,7 +657,15 @@ function evaluateQuirkMatch(crit, quirks, onLogMessage) {
649
657
  explainQuirk(onLogMessage, result, crit, targetQuirkValue);
650
658
  return result;
651
659
  } else {
652
- throw new Error(`Unknown quirk op: ${op}`);
660
+ onLogMessage == null ? void 0 : onLogMessage([
661
+ "error",
662
+ 302,
663
+ {
664
+ matched: false,
665
+ description: `Quirk ${crit.l} ${crit.op} ${crit.r}: Unknown quirk op ${crit.op}.`
666
+ }
667
+ ]);
668
+ return false;
653
669
  }
654
670
  }
655
671
  function explainScore(onLogMessage, result, crit, lhsScore, rhsScore) {
@@ -673,8 +689,8 @@ function explainQuirk(onLogMessage, result, crit, lhs) {
673
689
  ]);
674
690
  }
675
691
 
676
- // src/placement/personalizeVariations.ts
677
- function personalizeVariations({
692
+ // src/placement/topDownCriteriaPersonalizationSelectionAlgorithm.ts
693
+ function topDownCriteriaPersonalizationSelectionAlgorithm({
678
694
  name,
679
695
  context,
680
696
  variations,
@@ -689,12 +705,19 @@ function personalizeVariations({
689
705
  const needsConsent = context.requireConsentForPersonalization;
690
706
  const canEvaluate = !needsConsent || context.storage.data.consent;
691
707
  for (const variant of variations) {
692
- if ((_a = variant.pz) == null ? void 0 : _a.crit.length) {
693
- if (canEvaluate && variantMatches.length !== take && evaluateVariantMatch(variant.id, variant.pz, context.scores, onLogMessage, context.quirks)) {
694
- variantMatches.push(variant);
708
+ const isInvalidFormat = variant.pz && (typeof variant.pz !== "object" || variant.pz === null || !("crit" in variant.pz && Array.isArray(variant.pz.crit)));
709
+ let validVariant;
710
+ if (isInvalidFormat) {
711
+ validVariant = { id: variant.id };
712
+ } else {
713
+ validVariant = variant;
714
+ }
715
+ if ((_a = validVariant.pz) == null ? void 0 : _a.crit.length) {
716
+ if (canEvaluate && variantMatches.length !== take && evaluateVariantMatch(variant.id, validVariant.pz, context.scores, onLogMessage, context.quirks)) {
717
+ variantMatches.push(validVariant);
695
718
  }
696
719
  } else {
697
- defaultVariants.push(variant);
720
+ defaultVariants.push(validVariant);
698
721
  }
699
722
  }
700
723
  const result = [];
@@ -749,6 +772,11 @@ function personalizeVariations({
749
772
  }
750
773
  }
751
774
 
775
+ // src/placement/personalizeVariations.ts
776
+ function personalizeVariations(options) {
777
+ return topDownCriteriaPersonalizationSelectionAlgorithm(options);
778
+ }
779
+
752
780
  // src/placement/normalizeVariationDistributions.ts
753
781
  var normalizeVariationDistributions = (variations) => {
754
782
  const { values, total, missingDistribution } = variations.reduce(
@@ -768,7 +796,12 @@ var normalizeVariationDistributions = (variations) => {
768
796
  }
769
797
  );
770
798
  if (total > 100) {
771
- throw new Error(`Total distribution ${total} is over the maximum 100.`);
799
+ const autoScaleFactor = 100 / total;
800
+ values.forEach((value, index) => {
801
+ if (typeof value === "number") {
802
+ values[index] = value * autoScaleFactor;
803
+ }
804
+ });
772
805
  } else if (total < 100) {
773
806
  const remainder = 100 - total;
774
807
  const missingSlice = remainder / missingDistribution;
@@ -1548,11 +1581,12 @@ import { dequal as dequal5 } from "dequal/lite";
1548
1581
  import mitt3 from "mitt";
1549
1582
  var CONTEXTUAL_EDITING_TEST_NAME = "contextual_editing_test";
1550
1583
  var CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID = "contextual_editing_test_selected_variant";
1551
- var _serverTransitionState, _scores, _state, _pzCache, _plugins, _commands, _requireConsentForPersonalization, _mitt3, _Context_instances, emitTest_fn, updateGoals_fn, updateComputedScores_fn, calculateScores_fn;
1584
+ var _personalizationSelectionAlgorithms, _serverTransitionState, _scores, _state, _pzCache, _plugins, _commands, _requireConsentForPersonalization, _mitt3, _Context_instances, emitTest_fn, updateGoals_fn, updateComputedScores_fn, calculateScores_fn;
1552
1585
  var Context = class {
1553
1586
  constructor(options) {
1554
1587
  __privateAdd(this, _Context_instances);
1555
1588
  __publicField(this, "manifest");
1589
+ __privateAdd(this, _personalizationSelectionAlgorithms);
1556
1590
  __privateAdd(this, _serverTransitionState);
1557
1591
  __privateAdd(this, _scores, {});
1558
1592
  __privateAdd(this, _state);
@@ -1569,7 +1603,7 @@ var Context = class {
1569
1603
  off: __privateGet(this, _mitt3).off
1570
1604
  });
1571
1605
  __publicField(this, "storage");
1572
- var _a, _b;
1606
+ var _a, _b, _c;
1573
1607
  const { manifest, ...storageOptions } = options;
1574
1608
  __privateSet(this, _state, {});
1575
1609
  __privateSet(this, _plugins, options.plugins);
@@ -1577,7 +1611,17 @@ var Context = class {
1577
1611
  if (typeof options.transitionStore !== "undefined") {
1578
1612
  __privateSet(this, _commands, []);
1579
1613
  }
1614
+ __privateSet(this, _personalizationSelectionAlgorithms, { default: topDownCriteriaPersonalizationSelectionAlgorithm });
1580
1615
  (_a = __privateGet(this, _plugins)) == null ? void 0 : _a.forEach((plugin) => {
1616
+ if (!plugin.personalizationSelectionAlgorithms) {
1617
+ return;
1618
+ }
1619
+ __privateSet(this, _personalizationSelectionAlgorithms, {
1620
+ ...__privateGet(this, _personalizationSelectionAlgorithms),
1621
+ ...plugin.personalizationSelectionAlgorithms
1622
+ });
1623
+ });
1624
+ (_b = __privateGet(this, _plugins)) == null ? void 0 : _b.forEach((plugin) => {
1581
1625
  if (!plugin.logDrain) {
1582
1626
  return;
1583
1627
  }
@@ -1628,7 +1672,7 @@ var Context = class {
1628
1672
  __privateGet(this, _mitt3).emit("quirksUpdated", quirks.quirks);
1629
1673
  __privateGet(this, _mitt3).emit("log", ["info", 4, quirks.quirks]);
1630
1674
  });
1631
- (_b = __privateGet(this, _plugins)) == null ? void 0 : _b.forEach((plugin) => {
1675
+ (_c = __privateGet(this, _plugins)) == null ? void 0 : _c.forEach((plugin) => {
1632
1676
  if (!plugin.init) {
1633
1677
  return;
1634
1678
  }
@@ -1878,7 +1922,17 @@ var Context = class {
1878
1922
  }
1879
1923
  /** Executes a personalized placement with a given set of variants */
1880
1924
  personalize(options) {
1881
- const value = personalizeVariations({
1925
+ var _a;
1926
+ const algorithmName = (_a = options.algorithm) != null ? _a : "default";
1927
+ const algorithm = __privateGet(this, _personalizationSelectionAlgorithms)[algorithmName];
1928
+ if (!algorithm) {
1929
+ __privateGet(this, _mitt3).emit("log", ["warn", 304, { algorithm: algorithmName }]);
1930
+ return {
1931
+ personalized: false,
1932
+ variations: []
1933
+ };
1934
+ }
1935
+ const value = algorithm({
1882
1936
  ...options,
1883
1937
  context: this,
1884
1938
  onLogMessage: (message) => __privateGet(this, _mitt3).emit("log", message)
@@ -1952,6 +2006,7 @@ var Context = class {
1952
2006
  __privateGet(this, _mitt3).emit("personalizationResult", event);
1953
2007
  }
1954
2008
  };
2009
+ _personalizationSelectionAlgorithms = new WeakMap();
1955
2010
  _serverTransitionState = new WeakMap();
1956
2011
  _scores = new WeakMap();
1957
2012
  _state = new WeakMap();
@@ -2547,6 +2602,10 @@ var messageContent = {
2547
2602
  301: ({ id, op }) => ["personalization", `testing variation ${id} (${op === "|" ? "OR" : "AND"})`],
2548
2603
  302: ({ matched, description }) => ["personalization", `${description} is ${matched}`],
2549
2604
  303: (selected) => ["personalization", selected ? "selected variation" : "did not select variation"],
2605
+ 304: ({ algorithm }) => [
2606
+ "personalization",
2607
+ `personalization selection algorithm '${algorithm}' not found. Hiding placement.`
2608
+ ],
2550
2609
  // TESTING
2551
2610
  400: (name) => ["testing", `executing A/B test '${name}'`],
2552
2611
  401: (testName) => ["testing", `${testName} is not registered in the manifest; it will not be run.`],
@@ -2693,5 +2752,6 @@ export {
2693
2752
  serializePersonalizeVariants,
2694
2753
  serializeQuickConnect,
2695
2754
  serializeQuirks,
2696
- testVariations
2755
+ testVariations,
2756
+ topDownCriteriaPersonalizationSelectionAlgorithm
2697
2757
  };
@@ -859,6 +859,10 @@ type LogMessages = {
859
859
  }>;
860
860
  /** Final result for a personalized variation */
861
861
  303: MessageFunc<boolean>;
862
+ /** Personalization algorithm not found */
863
+ 304: MessageFunc<{
864
+ algorithm: string;
865
+ }>;
862
866
  /** A/B test placement executing */
863
867
  400: MessageFunc<string>;
864
868
  /** A/B Test definition did not exist */
@@ -898,7 +902,8 @@ type LogMessageSingle<TID extends keyof LogMessages = keyof LogMessages> = [
898
902
  type LogMessageGroup<TID extends keyof LogMessages = keyof LogMessages> = [severity: Severity, id: TID, group: 'GROUP', ...args: Parameters<LogMessages[TID]>] | [severity: Severity, id: TID, group: 'ENDGROUP'];
899
903
  type LogDrain = (message: LogMessage) => void;
900
904
 
901
- type VariantMatchCriteria = {
905
+ /** Data for a personalization variation using the top-down criteria selection algorithm */
906
+ interface VariantMatchCriteria extends VariantMatchMetadata {
902
907
  /**
903
908
  * Operation for match criteria
904
909
  *
@@ -906,15 +911,20 @@ type VariantMatchCriteria = {
906
911
  */
907
912
  op?: '&' | '|';
908
913
  crit: Array<DimensionMatch | QuirkMatch>;
909
- /**
910
- * Name of the variant for analytics tracking.
911
- */
912
- name?: string;
913
914
  /**
914
915
  * Control group percentage for the variant.
915
916
  */
916
917
  control?: number;
917
- };
918
+ }
919
+ /** Data that must exist on a personalization variation regardless of selection algorithm */
920
+ interface VariantMatchMetadata {
921
+ /**
922
+ * Name of the variation for analytics tracking.
923
+ * NOTE: name is optional for backwards compatibility, but it is HIGHLY recommended to specify a name
924
+ * as the default fallback is not helpfully named and is reliant on the order of the variations array.
925
+ */
926
+ name?: string;
927
+ }
918
928
  type DimensionMatch = {
919
929
  /**
920
930
  * Left hand side of the match expression (name of dimension in score vector)
@@ -990,11 +1000,11 @@ type BehaviorTag = {
990
1000
  beh?: EnrichmentData[];
991
1001
  };
992
1002
  /** Defines the shape of a personalized content variant */
993
- type PersonalizedVariant = {
1003
+ type PersonalizedVariant<TCriteria = VariantMatchCriteria> = {
994
1004
  /** A unique identifier for this variation */
995
1005
  id: string;
996
1006
  /** Match criteria for this variation */
997
- pz?: VariantMatchCriteria;
1007
+ pz?: TCriteria;
998
1008
  };
999
1009
  /** The result of computing personalized content from variations */
1000
1010
  type PersonalizedResult<TVariant> = {
@@ -1002,6 +1012,7 @@ type PersonalizedResult<TVariant> = {
1002
1012
  personalized: boolean;
1003
1013
  /** Matching variations */
1004
1014
  variations: Array<TVariant & {
1015
+ /** Whether the visitor is part of this variation's local control group (also true if part of global control group) */
1005
1016
  control: boolean;
1006
1017
  }>;
1007
1018
  };
@@ -1026,19 +1037,28 @@ type TestResult<TVariant> = {
1026
1037
  */
1027
1038
  variantAssigned: boolean;
1028
1039
  };
1029
-
1030
- type PersonalizeOptions<TVariant> = {
1040
+ interface PersonalizeOptions<TVariant> {
1041
+ /** Name of placement (sent to analytics) */
1042
+ name: string;
1043
+ /** Possible variations to place */
1044
+ variations: Iterable<TVariant>;
1045
+ /** Maximum number of variants to place (default: 1) */
1046
+ take?: number;
1047
+ /** Name of the personalization selection algorithm to use. Defaults to top-down criteria when not specified. */
1048
+ algorithm?: string;
1049
+ }
1050
+ interface PersonalizationSelectionAlgorithmOptions<TCriteria, TVariant extends PersonalizedVariant<TCriteria> = PersonalizedVariant<TCriteria>> {
1031
1051
  /** Name of placement (sent to analytics) */
1032
1052
  name: string;
1033
- /** Possible variants to place */
1053
+ /** Possible variations to place */
1034
1054
  variations: Iterable<TVariant>;
1035
1055
  /** Maximum number of variants to place (default: 1) */
1036
1056
  take?: number;
1057
+ /** Callback for logging messages */
1037
1058
  onLogMessage?: (message: LogMessage) => void;
1038
- };
1039
- declare function personalizeVariations<TVariant extends PersonalizedVariant>({ name, context, variations, take, onLogMessage, }: PersonalizeOptions<TVariant> & {
1059
+ /** Context instance */
1040
1060
  context: Context;
1041
- }): PersonalizedResult<TVariant>;
1061
+ }
1042
1062
 
1043
1063
  type TestOptions<TVariant extends TestVariant> = {
1044
1064
  /** The name of the test that is being run, must be included in the manifest. */
@@ -1053,18 +1073,31 @@ declare const testVariations: <TVariant extends TestVariant>({ name, context, va
1053
1073
 
1054
1074
  declare const CONTEXTUAL_EDITING_TEST_NAME = "contextual_editing_test";
1055
1075
  declare const CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID = "contextual_editing_test_selected_variant";
1076
+ type PersonalizationSelectionAlgorithm<TCriteria = unknown> = (options: PersonalizationSelectionAlgorithmOptions<TCriteria>) => PersonalizedResult<PersonalizedVariant<TCriteria>>;
1077
+ type PersonalizationSelectionAlgorithms<TCriteria = unknown> = Record<string, PersonalizationSelectionAlgorithm<TCriteria>>;
1056
1078
  /**
1057
1079
  * Defines a plugin for Uniform Context.
1058
1080
  * The plugin should attach event handlers in its creation function.
1059
1081
  * @returns A function that detaches any event handlers when called
1060
1082
  */
1061
1083
  type ContextPlugin = {
1084
+ /** Defines a log drain for the plugin, which all log messages are sent to */
1062
1085
  logDrain?: LogDrain;
1086
+ /** Initializes the plugin (attach event handlers here if needed) */
1063
1087
  init?: (context: Context) => () => void;
1088
+ /** Plugin-specific actions to perform when a user is forgotten */
1064
1089
  forget?: () => Promise<void> | void;
1090
+ /** Plugin-specific actions to perform when the visitor context is updated */
1065
1091
  update?: (newData: Partial<ContextState>) => Promise<void> | void;
1092
+ /**
1093
+ * Allows the plugin to register named personalization selection algorithms
1094
+ *
1095
+ * Important: the `default` and `strongestMatch` algorithms are automatically registered.
1096
+ * We strongly advise against replacing these.
1097
+ */
1098
+ personalizationSelectionAlgorithms?: PersonalizationSelectionAlgorithms<any>;
1066
1099
  };
1067
- type ContextOptions = {
1100
+ interface ContextOptions extends Omit<VisitorDataStoreOptions, 'manifest' | 'onServerTransitionScoresReceived'> {
1068
1101
  /** The Context Manifest to load (from the Context API) */
1069
1102
  manifest: ManifestV2;
1070
1103
  /**
@@ -1081,16 +1114,19 @@ type ContextOptions = {
1081
1114
  * `true`: personalization is not run at all unless storage consent is given
1082
1115
  */
1083
1116
  requireConsentForPersonalization?: boolean;
1084
- } & Omit<VisitorDataStoreOptions, 'manifest' | 'onServerTransitionScoresReceived'>;
1117
+ }
1118
+ type PersonalizationEventVariantId = {
1119
+ /** The variant ID that was selected */
1120
+ id: string;
1121
+ /** Whether the visitor is part of this variant's local control group (also true if part of global control group) */
1122
+ control: boolean;
1123
+ };
1085
1124
  /** Emitted when a personalization runs */
1086
1125
  type PersonalizationEvent = {
1087
1126
  /** Name of the personalized placement */
1088
1127
  name: string;
1089
1128
  /** Selected variant ID(s) */
1090
- variantIds: {
1091
- id: string;
1092
- control: boolean;
1093
- }[];
1129
+ variantIds: PersonalizationEventVariantId[];
1094
1130
  /** Whether the user was part of the control group (and did not receive any personalization) */
1095
1131
  control: boolean | undefined;
1096
1132
  /**
@@ -1144,7 +1180,7 @@ interface ContextInstance {
1144
1180
  setTestVariantId(testName: string, variantId: string): void;
1145
1181
  log(...message: LogMessage): void;
1146
1182
  test<TVariant extends TestVariant>(options: TestOptions<TVariant>): TestResult<TVariant>;
1147
- personalize<TVariant extends PersonalizedVariant>(options: PersonalizeOptions<TVariant>): PersonalizedResult<TVariant>;
1183
+ personalize<TVariant extends PersonalizedVariant<any>>(options: PersonalizeOptions<TVariant>): PersonalizedResult<TVariant>;
1148
1184
  forget(fromAllDevices: boolean): Promise<void>;
1149
1185
  getServerToClientTransitionState(): ServerToClientTransitionState;
1150
1186
  readonly manifest: ManifestInstance;
@@ -1209,7 +1245,7 @@ declare class Context implements ContextInstance {
1209
1245
  /** 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) */
1210
1246
  test<TVariant extends TestVariant>(options: TestOptions<TVariant>): TestResult<TVariant>;
1211
1247
  /** Executes a personalized placement with a given set of variants */
1212
- personalize<TVariant extends PersonalizedVariant>(options: PersonalizeOptions<TVariant>): PersonalizedResult<TVariant>;
1248
+ personalize<TVariant extends PersonalizedVariant<any>>(options: PersonalizeOptions<TVariant>): PersonalizedResult<TVariant>;
1213
1249
  /**
1214
1250
  * Forgets the visitor's data and resets the Context to its initial state.
1215
1251
  * @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
@@ -1296,4 +1332,4 @@ declare global {
1296
1332
  }
1297
1333
  }
1298
1334
 
1299
- export { type AggregateDimensionInput as $, type AggregateDimension as A, type MessageFunc as B, type ContextPlugin as C, type DecayFunction as D, type LogMessageSingle as E, type LogMessageGroup as F, ManifestInstance as G, GroupCriteriaEvaluator as H, type CriteriaEvaluatorResult as I, type CriteriaEvaluatorParameters as J, type SignalData as K, type LogDrain as L, type MessageCategory as M, type ManifestV2 as N, type OutputSeverity as O, type PersonalizationEvent as P, type Quirks as Q, type PersonalizationManifest as R, type ScoreVector as S, TransitionDataStore as T, type Signal as U, type VisitorData as V, type SignalCriteriaGroup as W, type SignalCriteria as X, type EnrichmentCategory as Y, type NumberMatch as Z, type TestDefinition as _, type StorageCommands as a, type TestOptions as a0, testVariations as a1, type DimensionMatch as a2, type QuirkMatch as a3, type PersonalizeOptions as a4, personalizeVariations as a5, type BehaviorTag as a6, type PersonalizedVariant as a7, type PersonalizedResult as a8, type TestVariant as a9, type ContextState as aA, type ContextStateUpdate as aB, type GoalStateUpdate as aC, type paths as aD, type TestResult as aa, type StorageCommand as ab, type SetGoalCommand as ac, type ModifyScoreCommand as ad, type ModifySessionScoreCommand as ae, type SetConsentCommand as af, type SetQuirkCommand as ag, type SetTestCommand as ah, type IdentifyCommand as ai, type SetControlGroupCommand as aj, type SetPersonalizeVariantControlCommand as ak, areCommandsEqual as al, type ServerToClientTransitionState as am, SERVER_STATE_ID as an, type TransitionDataStoreEvents as ao, type DecayOptions as ap, type VisitorDataStoreOptions as aq, type VisitorDataStoreEvents as ar, VisitorDataStore as as, type Tests as at, type Goals as au, type EnrichmentData as av, type PersonalizeControlVariant as aw, type PersonalizeVariants as ax, type EventData as ay, emptyVisitorData as az, type TransitionDataStoreOptions as b, type CriteriaEvaluator as c, type StringMatch as d, type VariantMatchCriteria as e, type LogMessage as f, type DevToolsEvents as g, CONTEXTUAL_EDITING_TEST_NAME as h, CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID as i, type ContextOptions as j, type TestEvent as k, type ContextEvents as l, type ContextInstance as m, Context as n, type DevToolsUiVersion as o, type DevToolsState as p, type DevToolsActions as q, type DevToolsEvent as r, type DevToolsLogEvent as s, type DevToolsDataEvent as t, type DevToolsHelloEvent as u, type DevToolsUpdateEvent as v, type DevToolsRawCommandsEvent as w, type DevToolsForgetEvent as x, type LogMessages as y, type Severity as z };
1335
+ export { type PersonalizationManifest as $, type AggregateDimension as A, type DevToolsDataEvent as B, type ContextPlugin as C, type DecayFunction as D, type DevToolsHelloEvent as E, type DevToolsUpdateEvent as F, type DevToolsRawCommandsEvent as G, type DevToolsForgetEvent as H, type LogMessages as I, type Severity as J, type MessageFunc as K, type LogDrain as L, type MessageCategory as M, type LogMessageSingle as N, type OutputSeverity as O, type PersonalizedVariant as P, type Quirks as Q, type LogMessageGroup as R, type ScoreVector as S, TransitionDataStore as T, ManifestInstance as U, type VisitorData as V, GroupCriteriaEvaluator as W, type CriteriaEvaluatorResult as X, type CriteriaEvaluatorParameters as Y, type SignalData as Z, type ManifestV2 as _, type StorageCommands as a, type Signal as a0, type SignalCriteriaGroup as a1, type SignalCriteria as a2, type EnrichmentCategory as a3, type NumberMatch as a4, type TestDefinition as a5, type AggregateDimensionInput as a6, type TestOptions as a7, testVariations as a8, type VariantMatchMetadata as a9, type PersonalizeControlVariant as aA, type PersonalizeVariants as aB, type EventData as aC, emptyVisitorData as aD, type ContextState as aE, type ContextStateUpdate as aF, type GoalStateUpdate as aG, type paths as aH, type DimensionMatch as aa, type QuirkMatch as ab, type BehaviorTag as ac, type TestVariant as ad, type TestResult as ae, type StorageCommand as af, type SetGoalCommand as ag, type ModifyScoreCommand as ah, type ModifySessionScoreCommand as ai, type SetConsentCommand as aj, type SetQuirkCommand as ak, type SetTestCommand as al, type IdentifyCommand as am, type SetControlGroupCommand as an, type SetPersonalizeVariantControlCommand as ao, areCommandsEqual as ap, type ServerToClientTransitionState as aq, SERVER_STATE_ID as ar, type TransitionDataStoreEvents as as, type DecayOptions as at, type VisitorDataStoreOptions as au, type VisitorDataStoreEvents as av, VisitorDataStore as aw, type Tests as ax, type Goals as ay, type EnrichmentData as az, type TransitionDataStoreOptions as b, type CriteriaEvaluator as c, type StringMatch as d, type VariantMatchCriteria as e, type LogMessage as f, type PersonalizeOptions as g, Context as h, type PersonalizedResult as i, type PersonalizationSelectionAlgorithmOptions as j, type DevToolsEvents as k, CONTEXTUAL_EDITING_TEST_NAME as l, CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID as m, type PersonalizationSelectionAlgorithm as n, type PersonalizationSelectionAlgorithms as o, type ContextOptions as p, type PersonalizationEventVariantId as q, type PersonalizationEvent as r, type TestEvent as s, type ContextEvents as t, type ContextInstance as u, type DevToolsUiVersion as v, type DevToolsState as w, type DevToolsActions as x, type DevToolsEvent as y, type DevToolsLogEvent as z };
@@ -859,6 +859,10 @@ type LogMessages = {
859
859
  }>;
860
860
  /** Final result for a personalized variation */
861
861
  303: MessageFunc<boolean>;
862
+ /** Personalization algorithm not found */
863
+ 304: MessageFunc<{
864
+ algorithm: string;
865
+ }>;
862
866
  /** A/B test placement executing */
863
867
  400: MessageFunc<string>;
864
868
  /** A/B Test definition did not exist */
@@ -898,7 +902,8 @@ type LogMessageSingle<TID extends keyof LogMessages = keyof LogMessages> = [
898
902
  type LogMessageGroup<TID extends keyof LogMessages = keyof LogMessages> = [severity: Severity, id: TID, group: 'GROUP', ...args: Parameters<LogMessages[TID]>] | [severity: Severity, id: TID, group: 'ENDGROUP'];
899
903
  type LogDrain = (message: LogMessage) => void;
900
904
 
901
- type VariantMatchCriteria = {
905
+ /** Data for a personalization variation using the top-down criteria selection algorithm */
906
+ interface VariantMatchCriteria extends VariantMatchMetadata {
902
907
  /**
903
908
  * Operation for match criteria
904
909
  *
@@ -906,15 +911,20 @@ type VariantMatchCriteria = {
906
911
  */
907
912
  op?: '&' | '|';
908
913
  crit: Array<DimensionMatch | QuirkMatch>;
909
- /**
910
- * Name of the variant for analytics tracking.
911
- */
912
- name?: string;
913
914
  /**
914
915
  * Control group percentage for the variant.
915
916
  */
916
917
  control?: number;
917
- };
918
+ }
919
+ /** Data that must exist on a personalization variation regardless of selection algorithm */
920
+ interface VariantMatchMetadata {
921
+ /**
922
+ * Name of the variation for analytics tracking.
923
+ * NOTE: name is optional for backwards compatibility, but it is HIGHLY recommended to specify a name
924
+ * as the default fallback is not helpfully named and is reliant on the order of the variations array.
925
+ */
926
+ name?: string;
927
+ }
918
928
  type DimensionMatch = {
919
929
  /**
920
930
  * Left hand side of the match expression (name of dimension in score vector)
@@ -990,11 +1000,11 @@ type BehaviorTag = {
990
1000
  beh?: EnrichmentData[];
991
1001
  };
992
1002
  /** Defines the shape of a personalized content variant */
993
- type PersonalizedVariant = {
1003
+ type PersonalizedVariant<TCriteria = VariantMatchCriteria> = {
994
1004
  /** A unique identifier for this variation */
995
1005
  id: string;
996
1006
  /** Match criteria for this variation */
997
- pz?: VariantMatchCriteria;
1007
+ pz?: TCriteria;
998
1008
  };
999
1009
  /** The result of computing personalized content from variations */
1000
1010
  type PersonalizedResult<TVariant> = {
@@ -1002,6 +1012,7 @@ type PersonalizedResult<TVariant> = {
1002
1012
  personalized: boolean;
1003
1013
  /** Matching variations */
1004
1014
  variations: Array<TVariant & {
1015
+ /** Whether the visitor is part of this variation's local control group (also true if part of global control group) */
1005
1016
  control: boolean;
1006
1017
  }>;
1007
1018
  };
@@ -1026,19 +1037,28 @@ type TestResult<TVariant> = {
1026
1037
  */
1027
1038
  variantAssigned: boolean;
1028
1039
  };
1029
-
1030
- type PersonalizeOptions<TVariant> = {
1040
+ interface PersonalizeOptions<TVariant> {
1041
+ /** Name of placement (sent to analytics) */
1042
+ name: string;
1043
+ /** Possible variations to place */
1044
+ variations: Iterable<TVariant>;
1045
+ /** Maximum number of variants to place (default: 1) */
1046
+ take?: number;
1047
+ /** Name of the personalization selection algorithm to use. Defaults to top-down criteria when not specified. */
1048
+ algorithm?: string;
1049
+ }
1050
+ interface PersonalizationSelectionAlgorithmOptions<TCriteria, TVariant extends PersonalizedVariant<TCriteria> = PersonalizedVariant<TCriteria>> {
1031
1051
  /** Name of placement (sent to analytics) */
1032
1052
  name: string;
1033
- /** Possible variants to place */
1053
+ /** Possible variations to place */
1034
1054
  variations: Iterable<TVariant>;
1035
1055
  /** Maximum number of variants to place (default: 1) */
1036
1056
  take?: number;
1057
+ /** Callback for logging messages */
1037
1058
  onLogMessage?: (message: LogMessage) => void;
1038
- };
1039
- declare function personalizeVariations<TVariant extends PersonalizedVariant>({ name, context, variations, take, onLogMessage, }: PersonalizeOptions<TVariant> & {
1059
+ /** Context instance */
1040
1060
  context: Context;
1041
- }): PersonalizedResult<TVariant>;
1061
+ }
1042
1062
 
1043
1063
  type TestOptions<TVariant extends TestVariant> = {
1044
1064
  /** The name of the test that is being run, must be included in the manifest. */
@@ -1053,18 +1073,31 @@ declare const testVariations: <TVariant extends TestVariant>({ name, context, va
1053
1073
 
1054
1074
  declare const CONTEXTUAL_EDITING_TEST_NAME = "contextual_editing_test";
1055
1075
  declare const CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID = "contextual_editing_test_selected_variant";
1076
+ type PersonalizationSelectionAlgorithm<TCriteria = unknown> = (options: PersonalizationSelectionAlgorithmOptions<TCriteria>) => PersonalizedResult<PersonalizedVariant<TCriteria>>;
1077
+ type PersonalizationSelectionAlgorithms<TCriteria = unknown> = Record<string, PersonalizationSelectionAlgorithm<TCriteria>>;
1056
1078
  /**
1057
1079
  * Defines a plugin for Uniform Context.
1058
1080
  * The plugin should attach event handlers in its creation function.
1059
1081
  * @returns A function that detaches any event handlers when called
1060
1082
  */
1061
1083
  type ContextPlugin = {
1084
+ /** Defines a log drain for the plugin, which all log messages are sent to */
1062
1085
  logDrain?: LogDrain;
1086
+ /** Initializes the plugin (attach event handlers here if needed) */
1063
1087
  init?: (context: Context) => () => void;
1088
+ /** Plugin-specific actions to perform when a user is forgotten */
1064
1089
  forget?: () => Promise<void> | void;
1090
+ /** Plugin-specific actions to perform when the visitor context is updated */
1065
1091
  update?: (newData: Partial<ContextState>) => Promise<void> | void;
1092
+ /**
1093
+ * Allows the plugin to register named personalization selection algorithms
1094
+ *
1095
+ * Important: the `default` and `strongestMatch` algorithms are automatically registered.
1096
+ * We strongly advise against replacing these.
1097
+ */
1098
+ personalizationSelectionAlgorithms?: PersonalizationSelectionAlgorithms<any>;
1066
1099
  };
1067
- type ContextOptions = {
1100
+ interface ContextOptions extends Omit<VisitorDataStoreOptions, 'manifest' | 'onServerTransitionScoresReceived'> {
1068
1101
  /** The Context Manifest to load (from the Context API) */
1069
1102
  manifest: ManifestV2;
1070
1103
  /**
@@ -1081,16 +1114,19 @@ type ContextOptions = {
1081
1114
  * `true`: personalization is not run at all unless storage consent is given
1082
1115
  */
1083
1116
  requireConsentForPersonalization?: boolean;
1084
- } & Omit<VisitorDataStoreOptions, 'manifest' | 'onServerTransitionScoresReceived'>;
1117
+ }
1118
+ type PersonalizationEventVariantId = {
1119
+ /** The variant ID that was selected */
1120
+ id: string;
1121
+ /** Whether the visitor is part of this variant's local control group (also true if part of global control group) */
1122
+ control: boolean;
1123
+ };
1085
1124
  /** Emitted when a personalization runs */
1086
1125
  type PersonalizationEvent = {
1087
1126
  /** Name of the personalized placement */
1088
1127
  name: string;
1089
1128
  /** Selected variant ID(s) */
1090
- variantIds: {
1091
- id: string;
1092
- control: boolean;
1093
- }[];
1129
+ variantIds: PersonalizationEventVariantId[];
1094
1130
  /** Whether the user was part of the control group (and did not receive any personalization) */
1095
1131
  control: boolean | undefined;
1096
1132
  /**
@@ -1144,7 +1180,7 @@ interface ContextInstance {
1144
1180
  setTestVariantId(testName: string, variantId: string): void;
1145
1181
  log(...message: LogMessage): void;
1146
1182
  test<TVariant extends TestVariant>(options: TestOptions<TVariant>): TestResult<TVariant>;
1147
- personalize<TVariant extends PersonalizedVariant>(options: PersonalizeOptions<TVariant>): PersonalizedResult<TVariant>;
1183
+ personalize<TVariant extends PersonalizedVariant<any>>(options: PersonalizeOptions<TVariant>): PersonalizedResult<TVariant>;
1148
1184
  forget(fromAllDevices: boolean): Promise<void>;
1149
1185
  getServerToClientTransitionState(): ServerToClientTransitionState;
1150
1186
  readonly manifest: ManifestInstance;
@@ -1209,7 +1245,7 @@ declare class Context implements ContextInstance {
1209
1245
  /** 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) */
1210
1246
  test<TVariant extends TestVariant>(options: TestOptions<TVariant>): TestResult<TVariant>;
1211
1247
  /** Executes a personalized placement with a given set of variants */
1212
- personalize<TVariant extends PersonalizedVariant>(options: PersonalizeOptions<TVariant>): PersonalizedResult<TVariant>;
1248
+ personalize<TVariant extends PersonalizedVariant<any>>(options: PersonalizeOptions<TVariant>): PersonalizedResult<TVariant>;
1213
1249
  /**
1214
1250
  * Forgets the visitor's data and resets the Context to its initial state.
1215
1251
  * @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
@@ -1296,4 +1332,4 @@ declare global {
1296
1332
  }
1297
1333
  }
1298
1334
 
1299
- export { type AggregateDimensionInput as $, type AggregateDimension as A, type MessageFunc as B, type ContextPlugin as C, type DecayFunction as D, type LogMessageSingle as E, type LogMessageGroup as F, ManifestInstance as G, GroupCriteriaEvaluator as H, type CriteriaEvaluatorResult as I, type CriteriaEvaluatorParameters as J, type SignalData as K, type LogDrain as L, type MessageCategory as M, type ManifestV2 as N, type OutputSeverity as O, type PersonalizationEvent as P, type Quirks as Q, type PersonalizationManifest as R, type ScoreVector as S, TransitionDataStore as T, type Signal as U, type VisitorData as V, type SignalCriteriaGroup as W, type SignalCriteria as X, type EnrichmentCategory as Y, type NumberMatch as Z, type TestDefinition as _, type StorageCommands as a, type TestOptions as a0, testVariations as a1, type DimensionMatch as a2, type QuirkMatch as a3, type PersonalizeOptions as a4, personalizeVariations as a5, type BehaviorTag as a6, type PersonalizedVariant as a7, type PersonalizedResult as a8, type TestVariant as a9, type ContextState as aA, type ContextStateUpdate as aB, type GoalStateUpdate as aC, type paths as aD, type TestResult as aa, type StorageCommand as ab, type SetGoalCommand as ac, type ModifyScoreCommand as ad, type ModifySessionScoreCommand as ae, type SetConsentCommand as af, type SetQuirkCommand as ag, type SetTestCommand as ah, type IdentifyCommand as ai, type SetControlGroupCommand as aj, type SetPersonalizeVariantControlCommand as ak, areCommandsEqual as al, type ServerToClientTransitionState as am, SERVER_STATE_ID as an, type TransitionDataStoreEvents as ao, type DecayOptions as ap, type VisitorDataStoreOptions as aq, type VisitorDataStoreEvents as ar, VisitorDataStore as as, type Tests as at, type Goals as au, type EnrichmentData as av, type PersonalizeControlVariant as aw, type PersonalizeVariants as ax, type EventData as ay, emptyVisitorData as az, type TransitionDataStoreOptions as b, type CriteriaEvaluator as c, type StringMatch as d, type VariantMatchCriteria as e, type LogMessage as f, type DevToolsEvents as g, CONTEXTUAL_EDITING_TEST_NAME as h, CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID as i, type ContextOptions as j, type TestEvent as k, type ContextEvents as l, type ContextInstance as m, Context as n, type DevToolsUiVersion as o, type DevToolsState as p, type DevToolsActions as q, type DevToolsEvent as r, type DevToolsLogEvent as s, type DevToolsDataEvent as t, type DevToolsHelloEvent as u, type DevToolsUpdateEvent as v, type DevToolsRawCommandsEvent as w, type DevToolsForgetEvent as x, type LogMessages as y, type Severity as z };
1335
+ export { type PersonalizationManifest as $, type AggregateDimension as A, type DevToolsDataEvent as B, type ContextPlugin as C, type DecayFunction as D, type DevToolsHelloEvent as E, type DevToolsUpdateEvent as F, type DevToolsRawCommandsEvent as G, type DevToolsForgetEvent as H, type LogMessages as I, type Severity as J, type MessageFunc as K, type LogDrain as L, type MessageCategory as M, type LogMessageSingle as N, type OutputSeverity as O, type PersonalizedVariant as P, type Quirks as Q, type LogMessageGroup as R, type ScoreVector as S, TransitionDataStore as T, ManifestInstance as U, type VisitorData as V, GroupCriteriaEvaluator as W, type CriteriaEvaluatorResult as X, type CriteriaEvaluatorParameters as Y, type SignalData as Z, type ManifestV2 as _, type StorageCommands as a, type Signal as a0, type SignalCriteriaGroup as a1, type SignalCriteria as a2, type EnrichmentCategory as a3, type NumberMatch as a4, type TestDefinition as a5, type AggregateDimensionInput as a6, type TestOptions as a7, testVariations as a8, type VariantMatchMetadata as a9, type PersonalizeControlVariant as aA, type PersonalizeVariants as aB, type EventData as aC, emptyVisitorData as aD, type ContextState as aE, type ContextStateUpdate as aF, type GoalStateUpdate as aG, type paths as aH, type DimensionMatch as aa, type QuirkMatch as ab, type BehaviorTag as ac, type TestVariant as ad, type TestResult as ae, type StorageCommand as af, type SetGoalCommand as ag, type ModifyScoreCommand as ah, type ModifySessionScoreCommand as ai, type SetConsentCommand as aj, type SetQuirkCommand as ak, type SetTestCommand as al, type IdentifyCommand as am, type SetControlGroupCommand as an, type SetPersonalizeVariantControlCommand as ao, areCommandsEqual as ap, type ServerToClientTransitionState as aq, SERVER_STATE_ID as ar, type TransitionDataStoreEvents as as, type DecayOptions as at, type VisitorDataStoreOptions as au, type VisitorDataStoreEvents as av, VisitorDataStore as aw, type Tests as ax, type Goals as ay, type EnrichmentData as az, type TransitionDataStoreOptions as b, type CriteriaEvaluator as c, type StringMatch as d, type VariantMatchCriteria as e, type LogMessage as f, type PersonalizeOptions as g, Context as h, type PersonalizedResult as i, type PersonalizationSelectionAlgorithmOptions as j, type DevToolsEvents as k, CONTEXTUAL_EDITING_TEST_NAME as l, CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID as m, type PersonalizationSelectionAlgorithm as n, type PersonalizationSelectionAlgorithms as o, type ContextOptions as p, type PersonalizationEventVariantId as q, type PersonalizationEvent as r, type TestEvent as s, type ContextEvents as t, type ContextInstance as u, type DevToolsUiVersion as v, type DevToolsState as w, type DevToolsActions as x, type DevToolsEvent as y, type DevToolsLogEvent as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniformdev/context",
3
- "version": "20.3.1-alpha.7+bede5bf489",
3
+ "version": "20.4.1-alpha.15+73b27bfcce",
4
4
  "description": "Uniform Context core package",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "main": "./dist/index.js",
@@ -68,5 +68,5 @@
68
68
  "publishConfig": {
69
69
  "access": "public"
70
70
  },
71
- "gitHead": "bede5bf4893bf814af6aba78a558e28efd9f5682"
71
+ "gitHead": "73b27bfcce749c31e7ab50bdc9bb86ac1294903d"
72
72
  }