posthog-node 5.72.0 → 5.73.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,280 @@
1
+ import { FeatureFlagValue, minimizeFlagCalledEventProperties } from '@posthog/core'
2
+
3
+ import type { ParsedFlagRecord } from './flags-response'
4
+
5
+ /**
6
+ * The flag events of one flag read: `$feature_flag_called` and, for a config version 2 experiment
7
+ * split, `$experiment_exposure`.
8
+ *
9
+ * {@link buildConfigVersion2FlagEvents} builds both events and their dedupe keys in one step, from
10
+ * the parsed `/flags` record that supplied the read's value and the read's `$feature_flag_called`
11
+ * properties. It never reads the value the read returned, and it never evaluates or fetches flags.
12
+ * A read whose record is not a readable config version 2 record gets no events from it, and the
13
+ * client sends its `$feature_flag_called` event exactly as before.
14
+ */
15
+
16
+ export const FEATURE_FLAG_CALLED_EVENT = '$feature_flag_called'
17
+ export const EXPERIMENT_EXPOSURE_EVENT = '$experiment_exposure'
18
+
19
+ // The reason code and rule type of the one outcome that sends `$experiment_exposure`: a variant
20
+ // assigned by an experiment rule.
21
+ const EXPERIMENT_SPLIT_REASON = 'experiment_split'
22
+ const EXPERIMENT_RULE_TYPE = 'experiment'
23
+
24
+ // The reason codes of a config version 2 record that report the rule that produced the result,
25
+ // and the rule types each one allows. Any other reason code, and any failed record, reports no
26
+ // rule, even when the record names one.
27
+ const RULE_TYPES_BY_REASON_CODE: ReadonlyMap<string, ReadonlySet<string>> = new Map([
28
+ ['targeting_match', new Set(['targeted_release', 'percentage_rollout'])],
29
+ [EXPERIMENT_SPLIT_REASON, new Set([EXPERIMENT_RULE_TYPE])],
30
+ ['rollout_miss', new Set(['percentage_rollout', EXPERIMENT_RULE_TYPE])],
31
+ ['experiment_paused', new Set([EXPERIMENT_RULE_TYPE])],
32
+ ['holdout', new Set([EXPERIMENT_RULE_TYPE])],
33
+ ])
34
+
35
+ /** The attribution a config version 2 `$feature_flag_called` carries, and keeps when minimized. */
36
+ export const CONFIG_VERSION_2_ATTRIBUTION_PROPERTIES: readonly string[] = [
37
+ '$feature_flag_config_version',
38
+ '$feature_flag_reason_code',
39
+ '$feature_flag_rule_id',
40
+ '$feature_flag_rule_type',
41
+ '$feature_flag_variant_key',
42
+ ]
43
+
44
+ // Properties a super or context property must not add to, or change on, a config version 2
45
+ // `$feature_flag_called`: the attribution, which is set again from the record, and the fields such
46
+ // an event never carries.
47
+ const CONFIG_VERSION_2_FLAG_CALLED_REMOVED: ReadonlySet<string> = new Set([
48
+ ...CONFIG_VERSION_2_ATTRIBUTION_PROPERTIES,
49
+ '$feature_flag_reason',
50
+ '$feature_flag_forced_variant',
51
+ '$feature_flag_experiment_id',
52
+ ])
53
+
54
+ // Properties an `$experiment_exposure` never carries, even from a super or context property.
55
+ const EXPOSURE_REMOVED: ReadonlySet<string> = new Set([
56
+ '$feature_flag_config_version',
57
+ '$feature_flag_reason_code',
58
+ '$feature_flag_rule_type',
59
+ '$experiment_exposure_source',
60
+ '$feature_flag_experiment_id',
61
+ '$feature_flag_forced_variant',
62
+ ])
63
+
64
+ // `$experiment_exposure` copies these from the `$feature_flag_called` of the same read, when it has
65
+ // them.
66
+ const EXPOSURE_PROPERTIES_FROM_FLAG_CALLED = [
67
+ '$feature_flag_id',
68
+ '$feature_flag_version',
69
+ '$feature_flag_request_id',
70
+ '$feature_flag_evaluated_at',
71
+ ]
72
+
73
+ // The rule ID's wire format: a hyphenated UUID, as the contract's event schemas require.
74
+ const UUID_PATTERN = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/
75
+
76
+ /**
77
+ * What a config version 2 flag record reports on its flag events.
78
+ *
79
+ * @internal
80
+ */
81
+ export type RuleAttribution = {
82
+ readonly reasonCode: string | undefined
83
+ readonly ruleId: string | undefined
84
+ readonly ruleType: string | undefined
85
+ /** Set only for a complete experiment split, the outcome that sends an exposure. */
86
+ readonly variantKey: string | undefined
87
+ }
88
+
89
+ /**
90
+ * Reads the event attribution of a config version 2 flag record.
91
+ *
92
+ * Returns `undefined` for anything else: no record, an unreadable record, a config version 1
93
+ * record, or a record from a server without typed values.
94
+ *
95
+ * The config version and reason code are always reported. The rule ID and rule type are reported
96
+ * together or not at all, only for a targeting match, a rollout miss, a paused experiment, a
97
+ * holdout and a complete experiment split, and only with a rule type the reason code allows. A
98
+ * record with no rule ID, no rule type or another rule type, such as a targeting match that names
99
+ * an experiment rule, reports neither. A rule ID that is not a UUID counts as missing. A failed
100
+ * record, any other reason code (including one this SDK does not know) and a record without a
101
+ * reason code report neither. The variant key is reported only for a complete experiment split:
102
+ * reason `experiment_split`, rule type `experiment`, a rule ID and a variant key (any string,
103
+ * including an empty one). A split without all of them is malformed: it reports its reason but no
104
+ * rule ID, rule type or variant, and sends no exposure. The SDK never guesses the missing fields
105
+ * from the value, the flag key or an earlier result.
106
+ *
107
+ * @internal
108
+ */
109
+ export function ruleAttribution(record: ParsedFlagRecord | undefined): RuleAttribution | undefined {
110
+ if (record === undefined || record.unreadableField !== undefined || record.metadata.configVersion !== 2) {
111
+ return undefined
112
+ }
113
+ const reasonCode = record.reason?.code || undefined
114
+ const noRule: RuleAttribution = { reasonCode, ruleId: undefined, ruleType: undefined, variantKey: undefined }
115
+ const allowedRuleTypes = reasonCode === undefined ? undefined : RULE_TYPES_BY_REASON_CODE.get(reasonCode)
116
+ if (record.failed || allowedRuleTypes === undefined) {
117
+ return noRule
118
+ }
119
+ const { ruleId, ruleType, variantKey } = record.metadata
120
+ if (ruleId === undefined || !UUID_PATTERN.test(ruleId) || ruleType === undefined || !allowedRuleTypes.has(ruleType)) {
121
+ return noRule
122
+ }
123
+ if (reasonCode !== EXPERIMENT_SPLIT_REASON) {
124
+ // Only an experiment split assigns a variant.
125
+ return { ...noRule, ruleId, ruleType }
126
+ }
127
+ if (variantKey === undefined) {
128
+ return noRule
129
+ }
130
+ return { reasonCode, ruleId, ruleType, variantKey }
131
+ }
132
+
133
+ /**
134
+ * How the client captures a config version 2 flag event, after super and context properties are
135
+ * merged: `removed` names are dropped, then `pinned` properties are set. A super property can
136
+ * therefore neither change the event's attribution nor add a field the event never carries.
137
+ *
138
+ * @internal
139
+ */
140
+ export type FlagEventCapture = {
141
+ readonly removed: ReadonlySet<string>
142
+ readonly pinned: Readonly<Record<string, unknown>>
143
+ }
144
+
145
+ /** @internal */
146
+ export function applyFlagEventCapture(properties: Record<string, any>, capture: FlagEventCapture): Record<string, any> {
147
+ const kept = Object.fromEntries(Object.entries(properties).filter(([name]) => !capture.removed.has(name)))
148
+ return { ...kept, ...capture.pinned }
149
+ }
150
+
151
+ /**
152
+ * The minimal property set of a config version 2 `$feature_flag_called`: the shared allowlist plus
153
+ * the config version 2 attribution. A config version 1 event keeps the shared allowlist alone.
154
+ *
155
+ * @internal
156
+ */
157
+ export function minimizeConfigVersion2FlagCalledProperties(properties: Record<string, any>): Record<string, any> {
158
+ const minimal = minimizeFlagCalledEventProperties(properties)
159
+ for (const name of CONFIG_VERSION_2_ATTRIBUTION_PROPERTIES) {
160
+ if (properties[name] !== undefined) {
161
+ minimal[name] = properties[name]
162
+ }
163
+ }
164
+ return minimal
165
+ }
166
+
167
+ /**
168
+ * One flag event of a read, sent once per key in its own dedupe namespace.
169
+ *
170
+ * @internal
171
+ */
172
+ export type FlagEvent = {
173
+ readonly event: typeof FEATURE_FLAG_CALLED_EVENT | typeof EXPERIMENT_EXPOSURE_EVENT
174
+ readonly dedupeKey: string
175
+ readonly properties: Record<string, any>
176
+ readonly capture: FlagEventCapture
177
+ }
178
+
179
+ /** @internal */
180
+ export type ConfigVersion2FlagEvents = {
181
+ readonly flagCalled: FlagEvent
182
+ /** Present only for a complete experiment split whose record supplied the read's value. */
183
+ readonly exposure: FlagEvent | undefined
184
+ }
185
+
186
+ /**
187
+ * Builds the flag events of a read whose value a config version 2 record supplied.
188
+ *
189
+ * Returns `undefined` when `record` has no config version 2 attribution (see
190
+ * {@link ruleAttribution}), including when it is absent because the value came from local
191
+ * evaluation, an override or no flag at all. The caller then sends its `$feature_flag_called` as
192
+ * before.
193
+ *
194
+ * `$feature_flag_called` gets the record's attribution in place of the human-readable
195
+ * `$feature_flag_reason`. Its dedupe key is the flag key, the response, the groups, the config
196
+ * version and the attribution, so equal-valued A/A variants, successive experiments of one flag
197
+ * and a holdout followed by a split of the same rule are each reported. `$experiment_exposure`
198
+ * is built for a complete experiment split only. Its dedupe key is the groups, the flag key, the
199
+ * config version, the rule ID and the variant key, so one assignment sends one exposure however
200
+ * often it is read. The value, request ID and evaluation time are left out of it.
201
+ *
202
+ * @internal
203
+ */
204
+ export function buildConfigVersion2FlagEvents(params: {
205
+ key: string
206
+ response: FeatureFlagValue | undefined
207
+ groups: Record<string, string | number> | undefined
208
+ properties: Record<string, any>
209
+ record: ParsedFlagRecord | undefined
210
+ }): ConfigVersion2FlagEvents | undefined {
211
+ const { key, response, groups, record } = params
212
+ const attribution = ruleAttribution(record)
213
+ if (attribution === undefined) {
214
+ return undefined
215
+ }
216
+ const { reasonCode, ruleId, ruleType, variantKey } = attribution
217
+ // Sorted by group type, as the `$feature_flag_called` tracker normalizes groups.
218
+ const groupEntries = Object.entries(groups ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
219
+
220
+ const attributionProperties: Record<string, unknown> = { $feature_flag_config_version: 2 }
221
+ if (reasonCode !== undefined) {
222
+ attributionProperties.$feature_flag_reason_code = reasonCode
223
+ }
224
+ if (ruleId !== undefined) {
225
+ attributionProperties.$feature_flag_rule_id = ruleId
226
+ attributionProperties.$feature_flag_rule_type = ruleType
227
+ }
228
+ if (variantKey !== undefined) {
229
+ attributionProperties.$feature_flag_variant_key = variantKey
230
+ }
231
+ const { $feature_flag_reason: _reason, ...flagCalledProperties } = params.properties
232
+ Object.assign(flagCalledProperties, attributionProperties)
233
+
234
+ // A JSON array cannot equal a config version 1 key, which starts with the flag key, so the two
235
+ // kinds of key never collide in one tracker. `null` stands for an absent field.
236
+ const flagCalled: FlagEvent = {
237
+ event: FEATURE_FLAG_CALLED_EVENT,
238
+ dedupeKey: JSON.stringify([
239
+ key,
240
+ response ?? null,
241
+ groupEntries,
242
+ 2,
243
+ reasonCode ?? null,
244
+ ruleId ?? null,
245
+ ruleType ?? null,
246
+ variantKey ?? null,
247
+ ]),
248
+ properties: flagCalledProperties,
249
+ capture: { removed: CONFIG_VERSION_2_FLAG_CALLED_REMOVED, pinned: attributionProperties },
250
+ }
251
+
252
+ if (variantKey === undefined) {
253
+ return { flagCalled, exposure: undefined }
254
+ }
255
+
256
+ const exposureIdentity: Record<string, unknown> = {
257
+ $feature_flag: key,
258
+ $feature_flag_response: response,
259
+ $feature_flag_variant_key: variantKey,
260
+ $feature_flag_rule_id: ruleId,
261
+ locally_evaluated: flagCalledProperties.locally_evaluated === true,
262
+ }
263
+ const exposureProperties: Record<string, any> = {}
264
+ for (const name of EXPOSURE_PROPERTIES_FROM_FLAG_CALLED) {
265
+ if (flagCalledProperties[name] !== undefined) {
266
+ exposureProperties[name] = flagCalledProperties[name]
267
+ }
268
+ }
269
+ Object.assign(exposureProperties, exposureIdentity)
270
+
271
+ return {
272
+ flagCalled,
273
+ exposure: {
274
+ event: EXPERIMENT_EXPOSURE_EVENT,
275
+ dedupeKey: JSON.stringify([key, groupEntries, 2, ruleId, variantKey]),
276
+ properties: exposureProperties,
277
+ capture: { removed: EXPOSURE_REMOVED, pinned: exposureIdentity },
278
+ },
279
+ }
280
+ }
@@ -0,0 +1,340 @@
1
+ import {
2
+ FeatureFlagDetail,
3
+ hasOwnProperty,
4
+ isBoolean,
5
+ isNull,
6
+ isNullish,
7
+ isNumber,
8
+ isPlainObject,
9
+ isString,
10
+ JsonType,
11
+ } from '@posthog/core'
12
+
13
+ /**
14
+ * Reads the flag records of the `/flags?v=4` response.
15
+ *
16
+ * A v4 record carries one typed `value` (boolean, string, number, object or null) instead of
17
+ * `enabled` and `variant`, plus a structured reason and rule metadata. A record without `value`
18
+ * comes from a server that does not serve v4: its value is `variant`, or `enabled` when there is
19
+ * no variant, and its config version is 1.
20
+ *
21
+ * The existing getters and events read the legacy rendering of each record, which is derived
22
+ * from `value` here, in {@link renderValue}. The parsed record is kept for the typed flag API
23
+ * and is internal: {@link parsedFlagRecordOf} returns it.
24
+ */
25
+
26
+ /**
27
+ * A flag's typed value. `null` means the flag has no value.
28
+ *
29
+ * @internal
30
+ */
31
+ export type FlagRecordValue = boolean | string | number | { [key: string]: JsonType } | null
32
+
33
+ /**
34
+ * A `/flags` flag record as this SDK read it. Internal: it is not part of the public API.
35
+ *
36
+ * @internal
37
+ */
38
+ export type ParsedFlagRecord = {
39
+ /**
40
+ * The typed value. `null` for an unreadable record and a failed v4 record. A record without a
41
+ * typed `value` keeps `variant`, or `enabled` when there is no variant, even when it failed.
42
+ */
43
+ readonly value: FlagRecordValue
44
+ /** Whether the flag failed to evaluate, or its record could not be read. */
45
+ readonly failed: boolean
46
+ /**
47
+ * The wire path of the known field with the wrong JSON type that made the record unreadable,
48
+ * such as `metadata.id`. Absent from a readable record, including one the server marks failed.
49
+ */
50
+ readonly unreadableField?: string
51
+ readonly reason?: {
52
+ readonly code?: string
53
+ readonly conditionIndex?: number
54
+ readonly description?: string
55
+ }
56
+ readonly metadata: {
57
+ readonly id?: number
58
+ readonly version?: number
59
+ /** The flag's configuration format: `1` for a record without a typed `value`; absent when a record has none. */
60
+ readonly configVersion?: number
61
+ readonly description?: string
62
+ readonly hasExperiment?: boolean
63
+ /** The rule that produced the result. */
64
+ readonly ruleType?: string
65
+ readonly ruleId?: string
66
+ /** The assigned variant. */
67
+ readonly variantKey?: string
68
+ readonly forcedVariant?: boolean
69
+ }
70
+ }
71
+
72
+ /** Logged once per client, the first time a `/flags` response has a record without a typed value. */
73
+ export const FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE =
74
+ '[FEATURE FLAGS] The /flags response has no typed flag values, so the server may not support /flags?v=4. ' +
75
+ 'Its flags are read as config version 1.'
76
+
77
+ type ReadRecord = { detail: FeatureFlagDetail; record: ParsedFlagRecord }
78
+
79
+ // The parsed record of each legacy rendering this module created, so the public detail type
80
+ // stays unchanged. Details that were not read here, such as those of a v1 response, have none.
81
+ // The lookup is by object identity, so a copy of a detail has none either: look up the detail
82
+ // the reader returned, not a clone of it.
83
+ const parsedRecords = new WeakMap<FeatureFlagDetail, ParsedFlagRecord>()
84
+
85
+ class UnreadableField extends Error {
86
+ readonly field: string
87
+
88
+ constructor(field: string) {
89
+ super(field)
90
+ this.field = field
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Reads the flag records of a `/flags` response body. Each record in `flags` is replaced by its
96
+ * legacy rendering, the shape the shared v2 reader reads, and the rest of the body is returned
97
+ * unchanged. A body without a `flags` object is returned as is.
98
+ *
99
+ * `withoutTypedValues` says whether the body has a record without a typed `value`, or is a v1
100
+ * response with flags, which a server that does not serve v4 sends.
101
+ */
102
+ export function readFlagRecords(body: unknown): { body: unknown; withoutTypedValues: boolean } {
103
+ if (!isPlainObject(body)) {
104
+ return { body, withoutTypedValues: false }
105
+ }
106
+ const flags = body.flags
107
+ if (!isPlainObject(flags)) {
108
+ const featureFlags = body.featureFlags
109
+ return { body, withoutTypedValues: isPlainObject(featureFlags) && Object.keys(featureFlags).length > 0 }
110
+ }
111
+
112
+ let withoutTypedValues = false
113
+ const rendered = Object.fromEntries(
114
+ Object.entries(flags).map(([key, raw]) => {
115
+ if (isPlainObject(raw) && !hasOwnProperty.call(raw, 'value')) {
116
+ withoutTypedValues = true
117
+ }
118
+ const { detail, record } = readRecord(key, raw)
119
+ parsedRecords.set(detail, record)
120
+ return [key, detail]
121
+ })
122
+ )
123
+ return { body: { ...body, flags: rendered }, withoutTypedValues }
124
+ }
125
+
126
+ /**
127
+ * The parsed record of a flag detail from a `/flags` response. A detail that was not read by
128
+ * {@link readFlagRecords}, such as one from a v1 response, reads as a config version 1 record.
129
+ *
130
+ * @internal
131
+ */
132
+ export function parsedFlagRecordOf(detail: FeatureFlagDetail): ParsedFlagRecord {
133
+ const record = parsedRecords.get(detail)
134
+ if (record) {
135
+ return record
136
+ }
137
+ return {
138
+ value: detail.variant ?? detail.enabled ?? null,
139
+ failed: detail.failed === true,
140
+ reason: detail.reason && {
141
+ code: detail.reason.code,
142
+ conditionIndex: detail.reason.condition_index,
143
+ description: detail.reason.description,
144
+ },
145
+ metadata: {
146
+ id: detail.metadata?.id,
147
+ version: detail.metadata?.version,
148
+ configVersion: 1,
149
+ description: detail.metadata?.description,
150
+ hasExperiment: detail.metadata?.has_experiment,
151
+ },
152
+ }
153
+ }
154
+
155
+ /** Whether a flag's record had a known field with the wrong JSON type, so it could not be read. */
156
+ export function isUnreadableFlagRecord(detail: FeatureFlagDetail): boolean {
157
+ return parsedRecords.get(detail)?.unreadableField !== undefined
158
+ }
159
+
160
+ function readRecord(key: string, raw: unknown): ReadRecord {
161
+ try {
162
+ if (isPlainObject(raw) && !hasOwnProperty.call(raw, 'value')) {
163
+ return readOlderRecord(raw)
164
+ }
165
+ return readTypedRecord(key, raw)
166
+ } catch (error) {
167
+ if (error instanceof UnreadableField) {
168
+ return unreadableRecord(key, error.field)
169
+ }
170
+ if (error instanceof RangeError) {
171
+ // A value nested too deeply to encode as a payload fails only its own record.
172
+ return unreadableRecord(key, 'value')
173
+ }
174
+ throw error
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Reads a `/flags?v=4` record. Unknown fields are ignored. An absent or null field reads as
180
+ * absent, except `value`, where null means the flag has no value.
181
+ */
182
+ function readTypedRecord(key: string, raw: unknown): ReadRecord {
183
+ if (!isPlainObject(raw)) {
184
+ throw new UnreadableField('record')
185
+ }
186
+ readRecordKey(raw)
187
+ const sentValue = readValue(raw.value)
188
+ const failed = optional(raw.failed, 'failed', isBoolean) === true
189
+ const reason = readReason(raw.reason)
190
+ const rawMetadata = optional(raw.metadata, 'metadata', isPlainObject)
191
+ const metadata = {
192
+ ...readMetadata(rawMetadata),
193
+ configVersion: optionalInteger(rawMetadata?.config_version, 'metadata.config_version'),
194
+ ruleType: optional(rawMetadata?.rule_type, 'metadata.rule_type', isString),
195
+ ruleId: optional(rawMetadata?.rule_id, 'metadata.rule_id', isString),
196
+ variantKey: optional(rawMetadata?.variant_key, 'metadata.variant_key', isString),
197
+ forcedVariant: optional(rawMetadata?.forced_variant, 'metadata.forced_variant', isBoolean),
198
+ }
199
+ // Only config version 1 records carry an experiment ID. It is checked, like every known field,
200
+ // but not kept.
201
+ optionalInteger(rawMetadata?.experiment_id, 'metadata.experiment_id')
202
+
203
+ // A failed record has no value, whatever it carries.
204
+ const value = failed ? null : sentValue
205
+ const { enabled, variant, payload } = renderValue(value)
206
+
207
+ const detail: FeatureFlagDetail = {
208
+ key,
209
+ enabled,
210
+ variant,
211
+ reason: reason && {
212
+ code: reason.code,
213
+ condition_index: reason.conditionIndex,
214
+ description: reason.description,
215
+ },
216
+ metadata:
217
+ rawMetadata || payload !== undefined
218
+ ? {
219
+ id: metadata.id,
220
+ version: metadata.version,
221
+ description: metadata.description,
222
+ // A number or object value is its own payload; a payload the record also carries
223
+ // is ignored. Other payloads are kept as sent, like a v2 record's. A failed record
224
+ // reads as disabled, so its payload is null, as a failed v2 record's is.
225
+ payload: (failed ? null : (payload ?? rawMetadata?.payload)) as string | undefined,
226
+ has_experiment: metadata.hasExperiment,
227
+ }
228
+ : undefined,
229
+ }
230
+ if (failed) {
231
+ detail.failed = true
232
+ }
233
+ return { detail, record: { value, failed, reason, metadata } }
234
+ }
235
+
236
+ /**
237
+ * Reads a record without a typed `value`, from a server that does not serve v4. Its legacy
238
+ * rendering is the record as sent, which is what the SDK read before. Any rule context in it is
239
+ * ignored. As for a v4 record, a known field with the wrong JSON type fails only this record.
240
+ */
241
+ function readOlderRecord(raw: Record<string, unknown>): ReadRecord {
242
+ readRecordKey(raw)
243
+ const enabled = optional(raw.enabled, 'enabled', isBoolean)
244
+ const variant = optional(raw.variant, 'variant', isString)
245
+ const failed = optional(raw.failed, 'failed', isBoolean) === true
246
+ const reason = readReason(raw.reason)
247
+ const metadata = readMetadata(optional(raw.metadata, 'metadata', isPlainObject))
248
+ return {
249
+ detail: raw as FeatureFlagDetail,
250
+ record: {
251
+ value: variant ?? enabled ?? null,
252
+ failed,
253
+ reason,
254
+ metadata: { ...metadata, configVersion: 1 },
255
+ },
256
+ }
257
+ }
258
+
259
+ function unreadableRecord(key: string, field: string): ReadRecord {
260
+ return {
261
+ detail: { key, enabled: false, variant: undefined, reason: undefined, metadata: undefined, failed: true },
262
+ record: { value: null, failed: true, unreadableField: field, metadata: {} },
263
+ }
264
+ }
265
+
266
+ /**
267
+ * The legacy rendering of a typed value, as responses before `/flags?v=4` carried it: a boolean
268
+ * as is, a string as the variant, `null` as `false`, and a number or object as `true` with the
269
+ * value as its JSON payload.
270
+ */
271
+ function renderValue(value: FlagRecordValue): {
272
+ enabled: boolean
273
+ variant: string | undefined
274
+ payload: string | undefined
275
+ } {
276
+ if (isNull(value) || isBoolean(value)) {
277
+ return { enabled: value === true, variant: undefined, payload: undefined }
278
+ }
279
+ if (isString(value)) {
280
+ return { enabled: true, variant: value, payload: undefined }
281
+ }
282
+ return { enabled: true, variant: undefined, payload: JSON.stringify(value) }
283
+ }
284
+
285
+ function readValue(value: unknown): FlagRecordValue {
286
+ if (isNull(value) || isBoolean(value) || isString(value) || isPlainObject(value)) {
287
+ return value as FlagRecordValue
288
+ }
289
+ if (isNumber(value) && Number.isFinite(value)) {
290
+ return value
291
+ }
292
+ throw new UnreadableField('value')
293
+ }
294
+
295
+ // The flag key is the record's map key. A `key` member of the wrong type fails the record, like
296
+ // any known field; a string that differs from the map key is ignored.
297
+ function readRecordKey(raw: Record<string, unknown>): void {
298
+ optional(raw.key, 'key', isString)
299
+ }
300
+
301
+ function readReason(raw: unknown): ParsedFlagRecord['reason'] {
302
+ const reason = optional(raw, 'reason', isPlainObject)
303
+ if (reason === undefined) {
304
+ return undefined
305
+ }
306
+ return {
307
+ code: optional(reason.code, 'reason.code', isString),
308
+ conditionIndex: optionalInteger(reason.condition_index, 'reason.condition_index'),
309
+ description: optional(reason.description, 'reason.description', isString),
310
+ }
311
+ }
312
+
313
+ function readMetadata(metadata: Record<string, unknown> | undefined): {
314
+ id?: number
315
+ version?: number
316
+ description?: string
317
+ hasExperiment?: boolean
318
+ } {
319
+ return {
320
+ id: optionalInteger(metadata?.id, 'metadata.id'),
321
+ version: optionalInteger(metadata?.version, 'metadata.version'),
322
+ description: optional(metadata?.description, 'metadata.description', isString),
323
+ hasExperiment: optional(metadata?.has_experiment, 'metadata.has_experiment', isBoolean),
324
+ }
325
+ }
326
+
327
+ function optional<T>(value: unknown, field: string, is: (value: unknown) => value is T): T | undefined {
328
+ if (isNullish(value)) {
329
+ return undefined
330
+ }
331
+ if (is(value)) {
332
+ return value
333
+ }
334
+ throw new UnreadableField(field)
335
+ }
336
+
337
+ // JSON has one number type, so an integral number such as 2.0 is an integer.
338
+ function optionalInteger(value: unknown, field: string): number | undefined {
339
+ return optional(value, field, (candidate): candidate is number => isNumber(candidate) && Number.isInteger(candidate))
340
+ }
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = "5.72.0"
1
+ export const version = "5.73.1"