-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjs-split-provider.ts
More file actions
210 lines (193 loc) · 5.79 KB
/
js-split-provider.ts
File metadata and controls
210 lines (193 loc) · 5.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
EvaluationContext,
Provider,
ResolutionDetails,
ParseError,
FlagNotFoundError,
JsonValue,
TargetingKeyMissingError,
StandardResolutionReasons,
Logger,
ProviderEvents,
OpenFeature,
OpenFeatureEventEmitter,
} from "@openfeature/web-sdk";
import type SplitIO from "@splitsoftware/splitio/types/splitio";
type Consumer = {
key: string | undefined;
attributes: SplitIO.Attributes;
};
const CONTROL_VALUE_ERROR_MESSAGE = "Received the 'control' value from Split.";
export class OpenFeatureSplitProvider implements Provider {
metadata = {
name: "split",
};
private client: SplitIO.IBrowserClient;
public readonly events = new OpenFeatureEventEmitter();
constructor(splitFactory: SplitIO.IBrowserSDK) {
this.client = splitFactory.client();
this.client.on(this.client.Event.SDK_UPDATE, () => {
this.events.emit(ProviderEvents.ConfigurationChanged)
});
const onSdkReady = () => {
console.log(`${this.metadata.name} provider initialized`);
this.events.emit(ProviderEvents.Ready)
};
// If client is ready, resolve immediately
if (this.isClientReady()) {
onSdkReady();
} else {
this.client.on(this.client.Event.SDK_READY, onSdkReady);
}
}
// Safe method to check if client is ready
private isClientReady(): boolean {
return (this.client as any).__getStatus().isReady;
}
resolveBooleanEvaluation(
flagKey: string,
defaultValue: boolean,
context: EvaluationContext,
_logger: Logger
): ResolutionDetails<boolean> {
const details = this.evaluateTreatment(
flagKey,
this.transformContext(context),
defaultValue.toString()
);
let value: boolean;
switch (details.value as unknown) {
case "on":
case "true":
case true:
value = true;
break;
case "off":
case "false":
case false:
value = false;
break;
case "control":
throw new FlagNotFoundError(CONTROL_VALUE_ERROR_MESSAGE);
default:
throw new ParseError(`Invalid boolean value for ${details.value}`);
}
return { ...details, value };
}
resolveStringEvaluation(
flagKey: string,
defaultValue: string,
context: EvaluationContext,
_logger: Logger
): ResolutionDetails<string> {
const details = this.evaluateTreatment(
flagKey,
this.transformContext(context),
defaultValue
);
if (details.value === "control") {
throw new FlagNotFoundError(CONTROL_VALUE_ERROR_MESSAGE);
}
return details;
}
resolveNumberEvaluation(
flagKey: string,
defaultValue: number,
context: EvaluationContext,
_logger: Logger
): ResolutionDetails<number> {
const details = this.evaluateTreatment(
flagKey,
this.transformContext(context),
defaultValue.toString()
);
return { ...details, value: this.parseValidNumber(details.value) };
}
resolveObjectEvaluation<U extends JsonValue>(
flagKey: string,
defaultValue: U,
context: EvaluationContext,
_logger: Logger
): ResolutionDetails<U> {
const details = this.evaluateTreatment(
flagKey,
this.transformContext(context),
JSON.stringify(defaultValue)
);
return { ...details, value: this.parseValidJsonObject(details.value) };
}
private evaluateTreatment(
flagKey: string,
consumer: Consumer,
defaultValue: string
): ResolutionDetails<string> {
if (!consumer.key) {
throw new TargetingKeyMissingError(
"The Split provider requires a targeting key."
);
} else {
// The SDK should be ready by now, but if not, return default value
// Use our isClientReady helper to safely check
if (!this.isClientReady()) {
return {
value: defaultValue,
variant: defaultValue,
reason: StandardResolutionReasons.DEFAULT
};
}
const value = this.client.getTreatment(
flagKey,
consumer.attributes
);
// Create resolution details and add flagKey as additional property for tests
const details: ResolutionDetails<string> = {
value: value,
variant: value,
reason: StandardResolutionReasons.TARGETING_MATCH,
};
// Add flagKey for OpenFeature v1 compatibility, using assertion to avoid TypeScript errors
(details as any).flagKey = flagKey;
return details;
}
}
//Transform the context into an object useful for the Split API, an key string with arbitrary Split "Attributes".
private transformContext(context: EvaluationContext): Consumer {
const { targetingKey, ...attributes } = context;
return {
key: targetingKey,
// Stringify context objects include date.
attributes: JSON.parse(JSON.stringify(attributes)),
};
}
private parseValidNumber(stringValue: string | undefined) {
if (stringValue === undefined) {
throw new ParseError(`Invalid 'undefined' value.`);
}
const result = Number.parseFloat(stringValue);
if (Number.isNaN(result)) {
throw new ParseError(`Invalid numeric value ${stringValue}`);
}
return result;
}
private parseValidJsonObject<T extends JsonValue>(
stringValue: string | undefined
): T {
if (stringValue === undefined) {
throw new ParseError(`Invalid 'undefined' JSON value.`);
}
// we may want to allow the parsing to be customized.
try {
const value = JSON.parse(stringValue);
if (typeof value !== "object") {
throw new ParseError(
`Flag value ${stringValue} had unexpected type ${typeof value}, expected "object"`
);
}
return value;
} catch (err) {
throw new ParseError(`Error parsing ${stringValue} as JSON, ${err}`);
}
}
}