flagsmith-nodejs 6.2.0 → 7.0.3

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.
Files changed (100) hide show
  1. package/.github/workflows/publish.yml +8 -5
  2. package/.github/workflows/pull_request.yaml +3 -0
  3. package/.gitmodules +1 -1
  4. package/.husky/pre-commit +1 -0
  5. package/.nvmrc +1 -0
  6. package/.release-please-manifest.json +1 -1
  7. package/CHANGELOG.md +49 -0
  8. package/build/cjs/flagsmith-engine/environments/models.d.ts +2 -1
  9. package/build/cjs/flagsmith-engine/environments/models.js +3 -1
  10. package/build/cjs/flagsmith-engine/environments/util.js +1 -1
  11. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.d.ts +230 -0
  12. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.js +8 -0
  13. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/mappers.d.ts +5 -0
  14. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/mappers.js +156 -0
  15. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/types.d.ts +216 -0
  16. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/types.js +8 -0
  17. package/build/cjs/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.d.ts +68 -0
  18. package/build/cjs/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.js +8 -0
  19. package/build/cjs/flagsmith-engine/evaluation/models.d.ts +50 -0
  20. package/build/cjs/flagsmith-engine/evaluation/models.js +26 -0
  21. package/build/cjs/flagsmith-engine/features/models.js +1 -1
  22. package/build/cjs/flagsmith-engine/features/types.d.ts +5 -0
  23. package/build/cjs/flagsmith-engine/features/types.js +9 -0
  24. package/build/cjs/flagsmith-engine/features/util.d.ts +1 -0
  25. package/build/cjs/flagsmith-engine/features/util.js +5 -1
  26. package/build/cjs/flagsmith-engine/index.d.ts +61 -9
  27. package/build/cjs/flagsmith-engine/index.js +176 -56
  28. package/build/cjs/flagsmith-engine/segments/constants.d.ts +1 -0
  29. package/build/cjs/flagsmith-engine/segments/constants.js +2 -1
  30. package/build/cjs/flagsmith-engine/segments/evaluators.d.ts +41 -7
  31. package/build/cjs/flagsmith-engine/segments/evaluators.js +136 -24
  32. package/build/cjs/flagsmith-engine/segments/models.d.ts +9 -4
  33. package/build/cjs/flagsmith-engine/segments/models.js +115 -13
  34. package/build/cjs/flagsmith-engine/utils/hashing/index.d.ts +1 -1
  35. package/build/cjs/flagsmith-engine/utils/hashing/index.js +4 -4
  36. package/build/cjs/sdk/index.d.ts +1 -3
  37. package/build/cjs/sdk/index.js +22 -19
  38. package/build/cjs/sdk/models.d.ts +8 -1
  39. package/build/cjs/sdk/models.js +29 -1
  40. package/build/esm/flagsmith-engine/environments/models.d.ts +2 -1
  41. package/build/esm/flagsmith-engine/environments/models.js +3 -1
  42. package/build/esm/flagsmith-engine/environments/util.js +1 -1
  43. package/build/esm/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.d.ts +230 -0
  44. package/build/esm/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.js +7 -0
  45. package/build/esm/flagsmith-engine/evaluation/evaluationContext/mappers.d.ts +5 -0
  46. package/build/esm/flagsmith-engine/evaluation/evaluationContext/mappers.js +152 -0
  47. package/build/esm/flagsmith-engine/evaluation/evaluationContext/types.d.ts +216 -0
  48. package/build/esm/flagsmith-engine/evaluation/evaluationContext/types.js +7 -0
  49. package/build/esm/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.d.ts +68 -0
  50. package/build/esm/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.js +7 -0
  51. package/build/esm/flagsmith-engine/evaluation/models.d.ts +50 -0
  52. package/build/esm/flagsmith-engine/evaluation/models.js +9 -0
  53. package/build/esm/flagsmith-engine/features/models.js +2 -2
  54. package/build/esm/flagsmith-engine/features/types.d.ts +5 -0
  55. package/build/esm/flagsmith-engine/features/types.js +6 -0
  56. package/build/esm/flagsmith-engine/features/util.d.ts +1 -0
  57. package/build/esm/flagsmith-engine/features/util.js +3 -0
  58. package/build/esm/flagsmith-engine/index.d.ts +61 -9
  59. package/build/esm/flagsmith-engine/index.js +161 -43
  60. package/build/esm/flagsmith-engine/segments/constants.d.ts +1 -0
  61. package/build/esm/flagsmith-engine/segments/constants.js +1 -0
  62. package/build/esm/flagsmith-engine/segments/evaluators.d.ts +41 -7
  63. package/build/esm/flagsmith-engine/segments/evaluators.js +137 -25
  64. package/build/esm/flagsmith-engine/segments/models.d.ts +9 -4
  65. package/build/esm/flagsmith-engine/segments/models.js +115 -13
  66. package/build/esm/flagsmith-engine/utils/hashing/index.d.ts +1 -1
  67. package/build/esm/flagsmith-engine/utils/hashing/index.js +2 -2
  68. package/build/esm/sdk/index.d.ts +1 -3
  69. package/build/esm/sdk/index.js +21 -18
  70. package/build/esm/sdk/models.d.ts +8 -1
  71. package/build/esm/sdk/models.js +29 -1
  72. package/flagsmith-engine/environments/models.ts +3 -1
  73. package/flagsmith-engine/environments/util.ts +2 -1
  74. package/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.ts +247 -0
  75. package/flagsmith-engine/evaluation/evaluationContext/mappers.ts +204 -0
  76. package/flagsmith-engine/evaluation/evaluationContext/types.ts +233 -0
  77. package/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.ts +71 -0
  78. package/flagsmith-engine/evaluation/models.ts +96 -0
  79. package/flagsmith-engine/features/models.ts +3 -2
  80. package/flagsmith-engine/features/types.ts +5 -0
  81. package/flagsmith-engine/features/util.ts +4 -0
  82. package/flagsmith-engine/index.ts +229 -72
  83. package/flagsmith-engine/segments/constants.ts +1 -0
  84. package/flagsmith-engine/segments/evaluators.ts +178 -62
  85. package/flagsmith-engine/segments/models.ts +171 -23
  86. package/flagsmith-engine/utils/hashing/index.ts +2 -2
  87. package/package.json +13 -2
  88. package/sdk/index.ts +36 -23
  89. package/sdk/models.ts +44 -2
  90. package/tests/engine/e2e/engine.test.ts +43 -38
  91. package/tests/engine/unit/engine.test.ts +306 -59
  92. package/tests/engine/unit/mappers.test.ts +353 -0
  93. package/tests/engine/unit/segments/segment_evaluators.test.ts +391 -49
  94. package/tests/engine/unit/segments/segments_model.test.ts +85 -0
  95. package/tests/engine/unit/utils/utils.test.ts +7 -7
  96. package/tests/engine/unit/utils.ts +1 -1
  97. package/tests/sdk/data/environment.json +1 -0
  98. package/tests/sdk/flagsmith.test.ts +29 -3
  99. package/tests/sdk/offline-handlers.test.ts +3 -1
  100. package/vitest.config.esm.ts +34 -0
@@ -1,62 +1,180 @@
1
1
  import { getIdentitySegments } from './segments/evaluators.js';
2
- import { FeatureStateNotFound } from './utils/errors.js';
2
+ import { TARGETING_REASONS } from './features/types.js';
3
+ import { getHashedPercentageForObjIds } from './utils/hashing/index.js';
3
4
  export { EnvironmentModel } from './environments/models.js';
4
- export { FeatureModel, FeatureStateModel } from './features/models.js';
5
5
  export { IdentityModel } from './identities/models.js';
6
6
  export { TraitModel } from './identities/traits/models.js';
7
7
  export { SegmentModel } from './segments/models.js';
8
+ export { FeatureModel, FeatureStateModel } from './features/models.js';
8
9
  export { OrganisationModel } from './organisations/models.js';
9
- function getIdentityFeatureStatesDict(environment, identity, overrideTraits) {
10
- // Get feature states from the environment
11
- const featureStates = {};
12
- for (const fs of environment.featureStates) {
13
- featureStates[fs.feature.id] = fs;
10
+ /**
11
+ * Evaluates flags and segments for the given context.
12
+ *
13
+ * This is the main entry point for the evaluation engine. It processes segments,
14
+ * applies feature overrides based on segment priority, and returns the final flag states with
15
+ * evaluation reasons.
16
+ *
17
+ * @param context - EvaluationContext containing environment, identity, and segment data
18
+ * @returns EvaluationResult with flags, segments, and original context
19
+ */
20
+ export function getEvaluationResult(context) {
21
+ const enrichedContext = getEnrichedContext(context);
22
+ const { segments, segmentOverrides } = evaluateSegments(enrichedContext);
23
+ const flags = evaluateFeatures(enrichedContext, segmentOverrides);
24
+ return { flags, segments };
25
+ }
26
+ function getEnrichedContext(context) {
27
+ const identityKey = getIdentityKey(context);
28
+ if (!identityKey)
29
+ return context;
30
+ return {
31
+ ...context,
32
+ ...(context.identity && {
33
+ identity: {
34
+ identifier: context.identity.identifier,
35
+ key: identityKey,
36
+ traits: context.identity.traits || {}
37
+ }
38
+ })
39
+ };
40
+ }
41
+ /**
42
+ * Evaluates which segments the identity belongs to and collects feature overrides.
43
+ *
44
+ * @param context - EvaluationContext containing identity and segment definitions
45
+ * @returns Object containing segments the identity belongs to and any feature overrides
46
+ */
47
+ export function evaluateSegments(context) {
48
+ if (!context.identity || !context.segments) {
49
+ return {
50
+ segments: [],
51
+ segmentOverrides: {}
52
+ };
14
53
  }
15
- // Override with any feature states defined by matching segments
16
- const identitySegments = getIdentitySegments(environment, identity, overrideTraits);
17
- for (const matchingSegment of identitySegments) {
18
- for (const featureState of matchingSegment.featureStates) {
19
- if (featureStates[featureState.feature.id]) {
20
- if (featureStates[featureState.feature.id].isHigherSegmentPriority(featureState)) {
21
- continue;
54
+ const identitySegments = getIdentitySegments(context);
55
+ const segments = identitySegments.map(segment => ({
56
+ name: segment.name,
57
+ ...(segment.metadata
58
+ ? {
59
+ metadata: {
60
+ ...segment.metadata
22
61
  }
23
62
  }
24
- featureStates[featureState.feature.id] = featureState;
25
- }
26
- }
27
- // Override with any feature states defined directly the identity
28
- for (const fs of identity.identityFeatures) {
29
- if (featureStates[fs.feature.id]) {
30
- featureStates[fs.feature.id] = fs;
63
+ : {})
64
+ }));
65
+ const segmentOverrides = processSegmentOverrides(identitySegments);
66
+ return { segments, segmentOverrides };
67
+ }
68
+ /**
69
+ * Processes feature overrides from segments, applying priority rules.
70
+ *
71
+ * When multiple segments override the same feature, the segment with
72
+ * higher priority (lower numeric value) takes precedence.
73
+ *
74
+ * @param identitySegments - Segments that the identity belongs to
75
+ * @returns Map of feature keys to their highest-priority segment overrides
76
+ */
77
+ export function processSegmentOverrides(identitySegments) {
78
+ const segmentOverrides = {};
79
+ for (const segment of identitySegments) {
80
+ if (!segment.overrides)
81
+ continue;
82
+ const overridesList = Array.isArray(segment.overrides) ? segment.overrides : [];
83
+ for (const override of overridesList) {
84
+ if (shouldApplyOverride(override, segmentOverrides)) {
85
+ segmentOverrides[override.name] = {
86
+ feature: override,
87
+ segmentName: segment.name
88
+ };
89
+ }
31
90
  }
32
91
  }
33
- return featureStates;
92
+ return segmentOverrides;
34
93
  }
35
- export function getIdentityFeatureState(environment, identity, featureName, overrideTraits) {
36
- const featureStates = getIdentityFeatureStatesDict(environment, identity, overrideTraits);
37
- const matchingFeature = Object.values(featureStates).filter(f => f.feature.name === featureName);
38
- if (matchingFeature.length === 0) {
39
- throw new FeatureStateNotFound('Feature State Not Found');
94
+ /**
95
+ * Evaluates all features in the context, applying segment overrides where applicable.
96
+ * For each feature:
97
+ * - Checks if a segment override exists
98
+ * - Uses override values if present, otherwise evaluates the base feature
99
+ * - Determines appropriate evaluation reason
100
+ * - Handles multivariate evaluation for features without overrides
101
+ *
102
+ * @param context - EvaluationContext containing features and identity
103
+ * @param segmentOverrides - Map of feature keys to their segment overrides
104
+ * @returns EvaluationResultFlags containing evaluated flag results
105
+ */
106
+ export function evaluateFeatures(context, segmentOverrides) {
107
+ const flags = {};
108
+ for (const feature of Object.values(context.features || {})) {
109
+ const segmentOverride = segmentOverrides[feature.name];
110
+ const finalFeature = segmentOverride ? segmentOverride.feature : feature;
111
+ const { value: evaluatedValue, reason: evaluatedReason } = evaluateFeatureValue(finalFeature, getIdentityKey(context));
112
+ flags[finalFeature.name] = {
113
+ name: finalFeature.name,
114
+ enabled: finalFeature.enabled,
115
+ value: evaluatedValue,
116
+ ...(finalFeature.metadata ? { metadata: finalFeature.metadata } : {}),
117
+ reason: evaluatedReason ??
118
+ getTargetingMatchReason({ type: 'SEGMENT', override: segmentOverride })
119
+ };
40
120
  }
41
- return matchingFeature[0];
121
+ return flags;
42
122
  }
43
- export function getIdentityFeatureStates(environment, identity, overrideTraits) {
44
- const featureStates = Object.values(getIdentityFeatureStatesDict(environment, identity, overrideTraits));
45
- if (environment.project.hideDisabledFlags) {
46
- return featureStates.filter(fs => !!fs.enabled);
123
+ function evaluateFeatureValue(feature, identityKey) {
124
+ if (!!feature.variants && feature.variants.length > 0 && !!identityKey) {
125
+ return getMultivariateFeatureValue(feature, identityKey);
47
126
  }
48
- return featureStates;
127
+ return { value: feature.value, reason: undefined };
49
128
  }
50
- export function getEnvironmentFeatureState(environment, featureName) {
51
- const featuresStates = environment.featureStates.filter(f => f.feature.name === featureName);
52
- if (featuresStates.length === 0) {
53
- throw new FeatureStateNotFound('Feature State Not Found');
129
+ /**
130
+ * Evaluates a multivariate feature flag to determine which variant value to return for a given identity.
131
+ *
132
+ * Uses deterministic hashing to ensure the same identity always receives the same variant,
133
+ * while distributing variants according to their configured weight percentages.
134
+ *
135
+ * @param feature - The feature context containing variants and their weights
136
+ * @param identityKey - The identity key used for deterministic variant selection
137
+ * @returns The variant value if the identity falls within a variant's range, otherwise the default feature value
138
+ */
139
+ function getMultivariateFeatureValue(feature, identityKey) {
140
+ const percentageValue = getHashedPercentageForObjIds([feature.key, identityKey]);
141
+ const sortedVariants = [...(feature?.variants || [])].sort((a, b) => {
142
+ return (a.priority ?? Infinity) - (b.priority ?? Infinity);
143
+ });
144
+ let startPercentage = 0;
145
+ for (const variant of sortedVariants) {
146
+ const limit = startPercentage + variant.weight;
147
+ if (startPercentage <= percentageValue && percentageValue < limit) {
148
+ return {
149
+ value: variant.value,
150
+ reason: getTargetingMatchReason({ type: 'SPLIT', weight: variant.weight })
151
+ };
152
+ }
153
+ startPercentage = limit;
54
154
  }
55
- return featuresStates[0];
155
+ return { value: feature.value, reason: undefined };
56
156
  }
57
- export function getEnvironmentFeatureStates(environment) {
58
- if (environment.project.hideDisabledFlags) {
59
- return environment.featureStates.filter(fs => !!fs.enabled);
60
- }
61
- return environment.featureStates;
157
+ export function shouldApplyOverride(override, existingOverrides) {
158
+ const currentOverride = existingOverrides[override.name];
159
+ return (!currentOverride || isHigherPriority(override.priority, currentOverride.feature.priority));
62
160
  }
161
+ export function isHigherPriority(priorityA, priorityB) {
162
+ return (priorityA ?? Infinity) < (priorityB ?? Infinity);
163
+ }
164
+ const getTargetingMatchReason = (matchObject) => {
165
+ const { type } = matchObject;
166
+ if (type === 'SEGMENT') {
167
+ return matchObject.override
168
+ ? `${TARGETING_REASONS.TARGETING_MATCH}; segment=${matchObject.override.segmentName}`
169
+ : TARGETING_REASONS.DEFAULT;
170
+ }
171
+ if (type === 'SPLIT') {
172
+ return `${TARGETING_REASONS.SPLIT}; weight=${matchObject.weight}`;
173
+ }
174
+ return TARGETING_REASONS.DEFAULT;
175
+ };
176
+ const getIdentityKey = (context) => {
177
+ if (!context.identity)
178
+ return undefined;
179
+ return context.identity.key || `${context.environment.key}_${context.identity?.identifier}`;
180
+ };
@@ -2,6 +2,7 @@ export declare const ALL_RULE = "ALL";
2
2
  export declare const ANY_RULE = "ANY";
3
3
  export declare const NONE_RULE = "NONE";
4
4
  export declare const RULE_TYPES: string[];
5
+ export declare const IDENTITY_OVERRIDE_SEGMENT_NAME = "identity_overrides";
5
6
  export declare const EQUAL = "EQUAL";
6
7
  export declare const GREATER_THAN = "GREATER_THAN";
7
8
  export declare const LESS_THAN = "LESS_THAN";
@@ -3,6 +3,7 @@ export const ALL_RULE = 'ALL';
3
3
  export const ANY_RULE = 'ANY';
4
4
  export const NONE_RULE = 'NONE';
5
5
  export const RULE_TYPES = [ALL_RULE, ANY_RULE, NONE_RULE];
6
+ export const IDENTITY_OVERRIDE_SEGMENT_NAME = 'identity_overrides';
6
7
  // Segment Condition Operators
7
8
  export const EQUAL = 'EQUAL';
8
9
  export const GREATER_THAN = 'GREATER_THAN';
@@ -1,7 +1,41 @@
1
- import { EnvironmentModel } from '../environments/models.js';
2
- import { IdentityModel } from '../identities/models.js';
3
- import { TraitModel } from '../identities/traits/models.js';
4
- import { SegmentConditionModel, SegmentModel } from './models.js';
5
- export declare function getIdentitySegments(environment: EnvironmentModel, identity: IdentityModel, overrideTraits?: TraitModel[]): SegmentModel[];
6
- export declare function evaluateIdentityInSegment(identity: IdentityModel, segment: SegmentModel, overrideTraits?: TraitModel[]): boolean;
7
- export declare function traitsMatchSegmentCondition(identityTraits: TraitModel[], condition: SegmentConditionModel, segmentId: number | string, identityId: number | string): boolean;
1
+ import { GenericEvaluationContext, InSegmentCondition, SegmentCondition, SegmentContext } from '../evaluation/models.js';
2
+ /**
3
+ * Returns all segments that the identity belongs to based on segment rules evaluation.
4
+ *
5
+ * An identity belongs to a segment if it matches ALL of the segment's rules.
6
+ * If the context has no identity or segments, returns an empty array.
7
+ *
8
+ * @param context - Evaluation context containing identity and segment definitions
9
+ * @returns Array of segments that the identity matches
10
+ */
11
+ export declare function getIdentitySegments(context: GenericEvaluationContext): SegmentContext[];
12
+ /**
13
+ * Evaluates whether a segment condition matches the identity's traits or context values.
14
+ *
15
+ * Handles different types of conditions:
16
+ * - PERCENTAGE_SPLIT: Deterministic percentage-based bucketing using identity key
17
+ * - IS_SET/IS_NOT_SET: Checks for trait existence
18
+ * - Standard operators: EQUAL, NOT_EQUAL, etc. via SegmentConditionModel
19
+ * - JSONPath expressions: $.identity.identifier, $.environment.name, etc.
20
+ *
21
+ * @param condition - The condition to evaluate (property, operator, value)
22
+ * @param segmentKey - Key of the segment (used for percentage split hashing)
23
+ * @param context - Evaluation context containing identity, traits, and environment
24
+ * @returns true if the condition matches
25
+ */
26
+ export declare function traitsMatchSegmentCondition(condition: SegmentCondition | InSegmentCondition, segmentKey: string, context?: GenericEvaluationContext): boolean;
27
+ /**
28
+ * Evaluates JSONPath expressions against the evaluation context.
29
+ *
30
+ * Supports accessing nested context values using JSONPath syntax.
31
+ * Commonly used paths:
32
+ * - $.identity.identifier - User's unique identifier
33
+ * - $.identity.key - User's internal key
34
+ * - $.environment.name - Environment name
35
+ * - $.environment.key - Environment key
36
+ *
37
+ * @param jsonPath - JSONPath expression starting with '$.'
38
+ * @param context - Evaluation context to query against
39
+ * @returns The resolved value, or undefined if path doesn't exist or is invalid
40
+ */
41
+ export declare function getContextValue(jsonPath: string, context?: GenericEvaluationContext): any;
@@ -1,31 +1,143 @@
1
- import { getHashedPercentateForObjIds } from '../utils/hashing/index.js';
2
- import { PERCENTAGE_SPLIT, IS_SET, IS_NOT_SET } from './constants.js';
3
- export function getIdentitySegments(environment, identity, overrideTraits) {
4
- return environment.project.segments.filter(segment => evaluateIdentityInSegment(identity, segment, overrideTraits));
5
- }
6
- export function evaluateIdentityInSegment(identity, segment, overrideTraits) {
7
- return (segment.rules.length > 0 &&
8
- segment.rules.filter(rule => traitsMatchSegmentRule(overrideTraits || identity.identityTraits, rule, segment.id, identity.djangoID || identity.compositeKey)).length === segment.rules.length);
9
- }
10
- function traitsMatchSegmentRule(identityTraits, rule, segmentId, identityId) {
11
- const matchesConditions = rule.conditions.length > 0
12
- ? rule.matchingFunction()(rule.conditions.map(condition => traitsMatchSegmentCondition(identityTraits, condition, segmentId, identityId)))
13
- : true;
14
- return (matchesConditions &&
15
- rule.rules.filter(rule => traitsMatchSegmentRule(identityTraits, rule, segmentId, identityId)).length === rule.rules.length);
16
- }
17
- export function traitsMatchSegmentCondition(identityTraits, condition, segmentId, identityId) {
18
- if (condition.operator == PERCENTAGE_SPLIT) {
19
- var hashedPercentage = getHashedPercentateForObjIds([segmentId, identityId]);
1
+ import * as jsonpathModule from 'jsonpath';
2
+ import { getHashedPercentageForObjIds } from '../utils/hashing/index.js';
3
+ import { SegmentConditionModel } from './models.js';
4
+ import { IS_NOT_SET, IS_SET, PERCENTAGE_SPLIT } from './constants.js';
5
+ // Handle ESM/CJS interop - jsonpath exports default in ESM
6
+ const jsonpath = jsonpathModule.default || jsonpathModule;
7
+ /**
8
+ * Returns all segments that the identity belongs to based on segment rules evaluation.
9
+ *
10
+ * An identity belongs to a segment if it matches ALL of the segment's rules.
11
+ * If the context has no identity or segments, returns an empty array.
12
+ *
13
+ * @param context - Evaluation context containing identity and segment definitions
14
+ * @returns Array of segments that the identity matches
15
+ */
16
+ export function getIdentitySegments(context) {
17
+ if (!context.identity || !context.segments)
18
+ return [];
19
+ return Object.values(context.segments).filter(segment => {
20
+ if (segment.rules.length === 0)
21
+ return false;
22
+ return segment.rules.every(rule => traitsMatchSegmentRule(rule, segment.key, context));
23
+ });
24
+ }
25
+ /**
26
+ * Evaluates whether a segment condition matches the identity's traits or context values.
27
+ *
28
+ * Handles different types of conditions:
29
+ * - PERCENTAGE_SPLIT: Deterministic percentage-based bucketing using identity key
30
+ * - IS_SET/IS_NOT_SET: Checks for trait existence
31
+ * - Standard operators: EQUAL, NOT_EQUAL, etc. via SegmentConditionModel
32
+ * - JSONPath expressions: $.identity.identifier, $.environment.name, etc.
33
+ *
34
+ * @param condition - The condition to evaluate (property, operator, value)
35
+ * @param segmentKey - Key of the segment (used for percentage split hashing)
36
+ * @param context - Evaluation context containing identity, traits, and environment
37
+ * @returns true if the condition matches
38
+ */
39
+ export function traitsMatchSegmentCondition(condition, segmentKey, context) {
40
+ if (condition.operator === PERCENTAGE_SPLIT) {
41
+ let splitKey;
42
+ if (!condition.property) {
43
+ splitKey = context?.identity?.key;
44
+ }
45
+ else {
46
+ splitKey = getContextValue(condition.property, context);
47
+ }
48
+ if (!splitKey) {
49
+ return false;
50
+ }
51
+ const hashedPercentage = getHashedPercentageForObjIds([segmentKey, splitKey]);
20
52
  return hashedPercentage <= parseFloat(String(condition.value));
21
53
  }
22
- const traits = identityTraits.filter(t => t.traitKey === condition.property_);
23
- const trait = traits.length > 0 ? traits[0] : undefined;
54
+ if (!condition.property) {
55
+ return false;
56
+ }
57
+ const traitValue = getTraitValue(condition.property, context);
24
58
  if (condition.operator === IS_SET) {
25
- return !!trait;
59
+ return traitValue !== undefined && traitValue !== null;
60
+ }
61
+ if (condition.operator === IS_NOT_SET) {
62
+ return traitValue === undefined || traitValue === null;
63
+ }
64
+ if (traitValue !== undefined && traitValue !== null) {
65
+ const segmentCondition = new SegmentConditionModel(condition.operator, condition.value, condition.property);
66
+ return segmentCondition.matchesTraitValue(traitValue);
67
+ }
68
+ return false;
69
+ }
70
+ function traitsMatchSegmentRule(rule, segmentKey, context) {
71
+ const matchesConditions = evaluateConditions(rule, segmentKey, context);
72
+ const matchesSubRules = evaluateSubRules(rule, segmentKey, context);
73
+ return matchesConditions && matchesSubRules;
74
+ }
75
+ function evaluateConditions(rule, segmentKey, context) {
76
+ if (!rule.conditions || rule.conditions.length === 0)
77
+ return true;
78
+ const conditionResults = rule.conditions.map((condition) => traitsMatchSegmentCondition(condition, segmentKey, context));
79
+ return evaluateRuleConditions(rule.type, conditionResults);
80
+ }
81
+ function evaluateSubRules(rule, segmentKey, context) {
82
+ if (!rule.rules || rule.rules.length === 0)
83
+ return true;
84
+ return rule.rules.every((subRule) => traitsMatchSegmentRule(subRule, segmentKey, context));
85
+ }
86
+ function evaluateRuleConditions(ruleType, conditionResults) {
87
+ switch (ruleType) {
88
+ case 'ALL':
89
+ return conditionResults.length === 0 || conditionResults.every(result => result);
90
+ case 'ANY':
91
+ return conditionResults.length > 0 && conditionResults.some(result => result);
92
+ case 'NONE':
93
+ return conditionResults.length === 0 || conditionResults.every(result => !result);
94
+ default:
95
+ return false;
96
+ }
97
+ }
98
+ function getTraitValue(property, context) {
99
+ if (property.startsWith('$.')) {
100
+ const contextValue = getContextValue(property, context);
101
+ if (contextValue !== undefined && isPrimitive(contextValue)) {
102
+ return contextValue;
103
+ }
104
+ }
105
+ const traits = context?.identity?.traits || {};
106
+ return traits[property];
107
+ }
108
+ function isPrimitive(value) {
109
+ if (value === null || value === undefined) {
110
+ return true;
111
+ }
112
+ // Objects and arrays are non-primitive
113
+ return typeof value !== 'object';
114
+ }
115
+ /**
116
+ * Evaluates JSONPath expressions against the evaluation context.
117
+ *
118
+ * Supports accessing nested context values using JSONPath syntax.
119
+ * Commonly used paths:
120
+ * - $.identity.identifier - User's unique identifier
121
+ * - $.identity.key - User's internal key
122
+ * - $.environment.name - Environment name
123
+ * - $.environment.key - Environment key
124
+ *
125
+ * @param jsonPath - JSONPath expression starting with '$.'
126
+ * @param context - Evaluation context to query against
127
+ * @returns The resolved value, or undefined if path doesn't exist or is invalid
128
+ */
129
+ export function getContextValue(jsonPath, context) {
130
+ if (!context || !jsonPath?.startsWith('$.'))
131
+ return undefined;
132
+ try {
133
+ const normalizedPath = normalizeJsonPath(jsonPath);
134
+ const results = jsonpath.query(context, normalizedPath);
135
+ return results.length > 0 ? results[0] : undefined;
26
136
  }
27
- else if (condition.operator === IS_NOT_SET) {
28
- return trait == undefined;
137
+ catch (error) {
138
+ return undefined;
29
139
  }
30
- return trait ? condition.matchesTraitValue(trait.traitValue) : false;
140
+ }
141
+ function normalizeJsonPath(jsonPath) {
142
+ return jsonPath.replace(/\.([^.\[\]]+)$/, "['$1']");
31
143
  }
@@ -1,11 +1,13 @@
1
1
  import { FeatureStateModel } from '../features/models.js';
2
+ import { EvaluationContext } from '../evaluation/evaluationContext/evaluationContext.types.js';
3
+ import { EvaluationResultSegments } from '../evaluation/models.js';
2
4
  export declare const all: (iterable: Array<any>) => boolean;
3
5
  export declare const any: (iterable: Array<any>) => boolean;
4
6
  export declare const matchingFunctions: {
5
7
  [x: string]: (thisValue: any, otherValue: any) => any;
6
8
  };
7
9
  export declare const semverMatchingFunction: {
8
- [x: string]: ((thisValue: any, otherValue: any) => any) | ((thisValue: any, otherValue: any) => boolean);
10
+ [x: string]: ((thisValue: any, otherValue: any) => any) | ((conditionValue: any, traitValue: any) => boolean);
9
11
  };
10
12
  export declare const getMatchingFunctions: (semver: boolean) => {
11
13
  [x: string]: (thisValue: any, otherValue: any) => any;
@@ -15,9 +17,9 @@ export declare class SegmentConditionModel {
15
17
  [key: string]: string;
16
18
  };
17
19
  operator: string;
18
- value: string | null | undefined;
19
- property_: string | null | undefined;
20
- constructor(operator: string, value?: string | null | undefined, property?: string | null | undefined);
20
+ value: string | null | undefined | string[];
21
+ property: string | null | undefined;
22
+ constructor(operator: string, value?: string | null | undefined | string[], property?: string | null | undefined);
21
23
  matchesTraitValue(traitValue: any): any;
22
24
  }
23
25
  export declare class SegmentRuleModel {
@@ -34,4 +36,7 @@ export declare class SegmentModel {
34
36
  rules: SegmentRuleModel[];
35
37
  featureStates: FeatureStateModel[];
36
38
  constructor(id: number, name: string);
39
+ static fromSegmentResult(segmentResults: EvaluationResultSegments, evaluationContext: EvaluationContext): SegmentModel[];
40
+ private static createFeatureStatesFromOverrides;
41
+ private static createMultivariateValues;
37
42
  }