posthog-node 6.2.1 → 6.2.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 (37) hide show
  1. package/dist/client.d.ts +1 -1
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +14 -3
  4. package/dist/client.mjs +14 -3
  5. package/dist/emails/errors.d.ts +8 -1
  6. package/dist/emails/errors.d.ts.map +1 -1
  7. package/dist/emails/types.d.ts +41 -15
  8. package/dist/emails/types.d.ts.map +1 -1
  9. package/dist/extensions/feature-flags/feature-flags-v2.d.ts +254 -0
  10. package/dist/extensions/feature-flags/feature-flags-v2.d.ts.map +1 -0
  11. package/dist/extensions/feature-flags/feature-flags-v2.js +1408 -0
  12. package/dist/extensions/feature-flags/feature-flags-v2.mjs +1331 -0
  13. package/dist/extensions/feature-flags/feature-flags.d.ts +15 -4
  14. package/dist/extensions/feature-flags/feature-flags.d.ts.map +1 -1
  15. package/dist/extensions/feature-flags/feature-flags.js +55 -7
  16. package/dist/extensions/feature-flags/feature-flags.mjs +55 -7
  17. package/dist/feature-flag-evaluations.d.ts +8 -6
  18. package/dist/feature-flag-evaluations.d.ts.map +1 -1
  19. package/dist/flag-events.d.ts +2 -2
  20. package/dist/flag-events.d.ts.map +1 -1
  21. package/dist/flag-events.js +2 -1
  22. package/dist/flag-events.mjs +2 -1
  23. package/dist/types.d.ts +15 -7
  24. package/dist/types.d.ts.map +1 -1
  25. package/dist/version.d.ts +1 -1
  26. package/dist/version.js +1 -1
  27. package/dist/version.mjs +1 -1
  28. package/package.json +2 -2
  29. package/src/client.ts +18 -6
  30. package/src/emails/errors.ts +8 -1
  31. package/src/emails/types.ts +41 -15
  32. package/src/extensions/feature-flags/feature-flags-v2.ts +2086 -0
  33. package/src/extensions/feature-flags/feature-flags.ts +110 -20
  34. package/src/feature-flag-evaluations.ts +8 -6
  35. package/src/flag-events.ts +3 -2
  36. package/src/types.ts +15 -7
  37. package/src/version.ts +1 -1
@@ -0,0 +1,2086 @@
1
+ import { hashSHA1, InconclusiveMatchError, matchFeatureFlagProperty } from '@posthog/core'
2
+ import type { FeatureFlagDetail, FeatureFlagValue, JsonType, UnresolvedFlagReason } from '@posthog/core'
3
+
4
+ import { parsedFlagRecordOf, readFlagRecords } from '../../flags-response'
5
+ import type { FlagRecordValue, ParsedFlagRecord } from '../../flags-response'
6
+ import type { PostHogFeatureFlag } from '../../types'
7
+
8
+ /**
9
+ * Local evaluation of feature flags whose `filters.version` is 2.
10
+ *
11
+ * The poller calls {@link evaluateConfigV2Definition} for every loaded definition whose config
12
+ * version is not 1. Nothing in this module is exported from the package.
13
+ *
14
+ * A config version 2 flag holds an ordered list of rules. The first rule whose targeting matches
15
+ * decides the result, unless its rollout misses and the rule says to continue. The flags service
16
+ * is the reference for every result this module returns, and the evaluator matches
17
+ * posthog-python's local evaluator.
18
+ *
19
+ * {@link parseConfigV2} reads a `filters` document. The parser is closed: an unknown config
20
+ * version, rule type, property type, operator or field rejects the whole document, as does a
21
+ * filter value of a shape its operator does not read, so a document is never partly evaluated.
22
+ * {@link evaluateConfigV2} returns exactly one of:
23
+ *
24
+ * - `evaluated`: the value, its reason code and the rule that produced it.
25
+ * - `inconclusive`: a rule's targeting needs something the evaluator does not have, such as a
26
+ * person property the caller did not pass. Evaluation stops there. It does not skip the rule to
27
+ * try a later one, because an earlier rule that matches is terminal.
28
+ * - `unsupported`: the parser rejected the document.
29
+ * - `error`: a property value or a regular expression is invalid.
30
+ *
31
+ * None of them is a guess. A caller that cannot use the result must fall back to the flags
32
+ * service, not to `false` or to the flag default. {@link evaluateConfigV2Definition} does that for
33
+ * the poller: it turns a result into the record a `/flags?v=4` response gives, and anything else
34
+ * into the unresolved reason of the poller's fallback.
35
+ *
36
+ * Regular expressions use the matcher of the version 1 evaluator, which runs a pattern locally
37
+ * only in the subset where JavaScript and the flags service agree. Text comparisons read a value
38
+ * as the JSON text the flags service compares. A filter that compares text holds strings and
39
+ * booleans, which JSON spells one way. A number the caller passes is sent as JSON, so it is read
40
+ * as an integer when it is one. Where JavaScript cannot reproduce the flags service, such as a
41
+ * date in a form only the service reads, the result is inconclusive.
42
+ */
43
+
44
+ const CONFIG_VERSION = 2
45
+ const ASSIGNMENT_ALGORITHM = 'sha1_60_v1'
46
+ // The 60-bit hash range. As a binary64 literal it rounds to 2^60, as the flags service's does.
47
+ // oxlint-disable-next-line no-loss-of-precision
48
+ const HASH_SCALE = 0xfffffffffffffff
49
+ // An identifier is cut to this many Unicode scalar values before it is hashed.
50
+ const MAX_IDENTIFIER_LENGTH = 200
51
+
52
+ const MAX_RULES = 100
53
+ const MAX_PREDICATES = 100
54
+ const MIN_VARIANTS = 2
55
+ const MAX_VARIANTS = 20
56
+ const MAX_SEED_LENGTH = 400
57
+ const MAX_OBJECT_DEPTH = 20
58
+ // The reference's JSON reader gives up on deeper nesting.
59
+ const MAX_JSON_DEPTH = 127
60
+ const MAX_U64 = BigInt('18446744073709551615')
61
+
62
+ const CONFIG_FIELDS = new Set(['version', 'return_type', 'default_value', 'rules', 'aggregation_group_type_index'])
63
+ const RULE_FIELDS = ['id', 'rule_type', 'targeting', 'description', 'metadata']
64
+ const ROLLOUT_FIELDS = ['rollout_percentage', 'on_rollout_miss', 'assignment_algorithm', 'seed', 'assign_by']
65
+ const FIELDS_BY_RULE_TYPE: Readonly<Record<string, ReadonlySet<string>>> = {
66
+ targeted_release: new Set([...RULE_FIELDS, 'value']),
67
+ percentage_rollout: new Set([...RULE_FIELDS, ...ROLLOUT_FIELDS, 'value']),
68
+ experiment: new Set([...RULE_FIELDS, ...ROLLOUT_FIELDS, 'paused', 'variants', 'holdout']),
69
+ }
70
+ const VARIANT_FIELDS = new Set(['key', 'weight', 'value'])
71
+ const HOLDOUT_FIELDS = new Set(['seed', 'exclusion_percentage'])
72
+ const TARGETING_FIELDS = new Set(['properties'])
73
+ const PROPERTY_FIELDS = new Set([
74
+ 'key',
75
+ 'type',
76
+ 'value',
77
+ 'operator',
78
+ 'negation',
79
+ 'group_type_index',
80
+ 'cohort_name',
81
+ 'group_key_names',
82
+ 'label',
83
+ ])
84
+ // Property types the configuration format defines but this evaluator does not read.
85
+ const UNSUPPORTED_PROPERTY_TYPES = new Set(['cohort', 'group', 'flag'])
86
+
87
+ const EXACT_OPERATORS = new Set(['exact', 'is_not'])
88
+ const PRESENCE_OPERATORS = new Set(['is_set', 'is_not_set'])
89
+ const TEXT_OPERATORS = new Set([
90
+ 'icontains',
91
+ 'not_icontains',
92
+ 'starts_with',
93
+ 'not_starts_with',
94
+ 'ends_with',
95
+ 'not_ends_with',
96
+ ])
97
+ const MULTI_TEXT_OPERATORS = new Set(['icontains_multi', 'not_icontains_multi'])
98
+ const REGEX_OPERATORS = new Set(['regex', 'not_regex'])
99
+ const NUMBER_OPERATORS = new Set(['gt', 'gte', 'lt', 'lte'])
100
+ const SEMVER_COMPARISON_OPERATORS = new Set([
101
+ 'semver_eq',
102
+ 'semver_neq',
103
+ 'semver_gt',
104
+ 'semver_gte',
105
+ 'semver_lt',
106
+ 'semver_lte',
107
+ ])
108
+ const SEMVER_RANGE_OPERATORS = new Set(['semver_tilde', 'semver_caret', 'semver_wildcard'])
109
+ const DATE_OPERATORS = new Set(['is_date_exact', 'is_date_after', 'is_date_before'])
110
+ const OPERATORS: ReadonlySet<string> = new Set([
111
+ ...EXACT_OPERATORS,
112
+ ...PRESENCE_OPERATORS,
113
+ ...TEXT_OPERATORS,
114
+ ...MULTI_TEXT_OPERATORS,
115
+ ...REGEX_OPERATORS,
116
+ ...NUMBER_OPERATORS,
117
+ ...SEMVER_COMPARISON_OPERATORS,
118
+ ...SEMVER_RANGE_OPERATORS,
119
+ ...DATE_OPERATORS,
120
+ ])
121
+ // The operators that match a person who does not have the property.
122
+ const OPERATORS_MATCHING_ABSENCE: ReadonlySet<string> = new Set([
123
+ 'is_not',
124
+ 'not_icontains',
125
+ 'not_starts_with',
126
+ 'not_ends_with',
127
+ 'not_icontains_multi',
128
+ 'not_regex',
129
+ ])
130
+
131
+ // --- Results -------------------------------------------------------------------------------
132
+
133
+ /**
134
+ * The flag has a result. `value` is the typed flag value, or `null` when the flag has no value and
135
+ * the caller's default applies. An object value is the configuration's own object, so it must not
136
+ * be changed. The rule fields name the rule that ended the evaluation, and are absent when no rule
137
+ * did. They are the fields a `/flags?v=4` record carries in `reason` and `metadata`.
138
+ */
139
+ export type ConfigV2Evaluated = {
140
+ readonly outcome: 'evaluated'
141
+ readonly value: FlagRecordValue
142
+ readonly reason: string
143
+ readonly ruleId?: string
144
+ readonly ruleType?: string
145
+ readonly ruleIndex?: number
146
+ readonly variantKey?: string
147
+ }
148
+
149
+ /** A rule that evaluation reached could not be decided. */
150
+ export type ConfigV2Inconclusive = {
151
+ readonly outcome: 'inconclusive'
152
+ readonly reason: UnresolvedFlagReason
153
+ readonly detail: string
154
+ }
155
+
156
+ /**
157
+ * The parser rejected the document. `kind` is `malformed` for a document that breaks the
158
+ * configuration format, and `unsupported` for a format this evaluator does not read. `field` names
159
+ * what was rejected.
160
+ */
161
+ export type ConfigV2Unsupported = {
162
+ readonly outcome: 'unsupported'
163
+ readonly kind: 'malformed' | 'unsupported'
164
+ readonly field: string
165
+ }
166
+
167
+ /** Evaluation reached an invalid value. */
168
+ export type ConfigV2EvaluationError = {
169
+ readonly outcome: 'error'
170
+ readonly kind: 'invalid_property' | 'invalid_regex'
171
+ readonly detail: string
172
+ }
173
+
174
+ export type ConfigV2Outcome = ConfigV2Evaluated | ConfigV2Inconclusive | ConfigV2Unsupported | ConfigV2EvaluationError
175
+
176
+ /** Ends an evaluation with an outcome that is not a value. */
177
+ class Halt extends Error {
178
+ constructor(readonly result: ConfigV2Inconclusive | ConfigV2EvaluationError) {
179
+ super(result.detail)
180
+ }
181
+ }
182
+
183
+ function unusableContext(detail: string): Halt {
184
+ return new Halt({ outcome: 'inconclusive', reason: 'missing_context', detail })
185
+ }
186
+
187
+ function invalidProperty(detail: string): Halt {
188
+ return new Halt({ outcome: 'error', kind: 'invalid_property', detail })
189
+ }
190
+
191
+ // --- Configuration -------------------------------------------------------------------------
192
+
193
+ type Operand = number | VersionKey | Requirement | DateValue | null
194
+
195
+ /**
196
+ * One property filter of a rule. `value` is the filter value as stored. `operand` is what a
197
+ * number, semver or date operator compares with, read from `value` once by the parser.
198
+ */
199
+ type Predicate = {
200
+ readonly key: string
201
+ readonly operator: string
202
+ readonly value: unknown
203
+ readonly negation: boolean
204
+ readonly operand: Operand
205
+ }
206
+
207
+ type Rollout = {
208
+ readonly percentage: number
209
+ readonly returnDefaultOnMiss: boolean
210
+ readonly seed: string
211
+ }
212
+
213
+ type Variant = {
214
+ readonly key: string
215
+ readonly weight: number
216
+ readonly value: FlagRecordValue
217
+ }
218
+
219
+ type Holdout = {
220
+ readonly seed: string
221
+ readonly exclusionPercentage: number
222
+ }
223
+
224
+ type Rule =
225
+ | {
226
+ readonly ruleType: 'targeted_release'
227
+ readonly id: string
228
+ readonly targeting: readonly Predicate[]
229
+ readonly value: FlagRecordValue
230
+ }
231
+ | {
232
+ readonly ruleType: 'percentage_rollout'
233
+ readonly id: string
234
+ readonly targeting: readonly Predicate[]
235
+ readonly value: FlagRecordValue
236
+ readonly rollout: Rollout
237
+ }
238
+ | {
239
+ readonly ruleType: 'experiment'
240
+ readonly id: string
241
+ readonly targeting: readonly Predicate[]
242
+ readonly paused: boolean
243
+ readonly rollout: Rollout
244
+ readonly variants: readonly Variant[]
245
+ readonly holdout: Holdout | undefined
246
+ }
247
+
248
+ /**
249
+ * A parsed `filters` document. `defaultValue` is `null` for a null default. `comparesDates` says
250
+ * whether a rule has a date filter, so that evaluating the document can need the current time.
251
+ */
252
+ export type ConfigV2 = {
253
+ readonly defaultValue: FlagRecordValue
254
+ readonly rules: readonly Rule[]
255
+ readonly comparesDates: boolean
256
+ }
257
+
258
+ /**
259
+ * What a flag is evaluated for.
260
+ *
261
+ * - `identifier`: the person's resolved targeting key, as a string.
262
+ * - `properties`: the person properties, or `null` when there are none to read. A key whose value
263
+ * is `undefined`, a function or a symbol is absent, as it is from the JSON a remote request
264
+ * sends.
265
+ * - `propertiesComplete`: whether `properties` holds every property of the person. A complete map
266
+ * shows that a property is absent. A partial map does not, so a filter on a key it lacks is
267
+ * inconclusive.
268
+ * - `explicitExactMatching`: the project's setting for the `exact` and `is_not` operators. When
269
+ * false, a filter value that looks like a boolean matches by truthiness.
270
+ * - `timeZone`: the project's timezone, as an IANA name. Dates without a UTC offset and relative
271
+ * dates are read in it. Absent, a filter that needs it is inconclusive.
272
+ * - `now`: the time relative dates count back from. Absent, the current time, read once per
273
+ * evaluation.
274
+ */
275
+ export type ConfigV2Context = {
276
+ readonly identifier: string
277
+ readonly properties: Readonly<Record<string, unknown>> | null
278
+ readonly propertiesComplete: boolean
279
+ readonly explicitExactMatching: boolean
280
+ readonly timeZone?: string
281
+ readonly now?: Date
282
+ }
283
+
284
+ /** Draws the hash of one use: `rollout`, `variant` or `holdout`. */
285
+ export type ConfigV2Draw = (use: HashUse, seed: string, subject: string) => number | Promise<number>
286
+ export type HashUse = 'rollout' | 'variant' | 'holdout'
287
+
288
+ // --- Parser ----------------------------------------------------------------------------------
289
+
290
+ class Rejected extends Error {
291
+ constructor(
292
+ readonly kind: 'malformed' | 'unsupported',
293
+ readonly field: string
294
+ ) {
295
+ super(field)
296
+ }
297
+ }
298
+
299
+ const malformed = (field: string): Rejected => new Rejected('malformed', field)
300
+ const unsupported = (field: string): Rejected => new Rejected('unsupported', field)
301
+
302
+ /**
303
+ * Reads the `filters` document of a flag as config version 2.
304
+ *
305
+ * The document is the decoded JSON. Three things the reference rejects in the JSON text cannot be
306
+ * seen here: a repeated object key, a nonzero number that rounds to zero, and a percentage written
307
+ * with more than two decimals that rounds to a two-decimal value. The parser never changes the
308
+ * document.
309
+ */
310
+ export function parseConfigV2(filters: unknown): ConfigV2 | ConfigV2Unsupported {
311
+ try {
312
+ return readConfig(filters)
313
+ } catch (error) {
314
+ if (error instanceof Rejected) {
315
+ return { outcome: 'unsupported', kind: error.kind, field: error.field }
316
+ }
317
+ throw error
318
+ }
319
+ }
320
+
321
+ /** Whether a parse result is a rejected document. */
322
+ export function isConfigV2Unsupported(config: ConfigV2 | ConfigV2Unsupported): config is ConfigV2Unsupported {
323
+ return 'outcome' in config
324
+ }
325
+
326
+ const hasOwn = (target: object, field: string): boolean => Object.prototype.hasOwnProperty.call(target, field)
327
+
328
+ function readConfig(filters: unknown): ConfigV2 {
329
+ const document = object(filters, 'filters')
330
+ const version = optional(document, 'version')
331
+ if (!isNumber(version) || version !== CONFIG_VERSION) {
332
+ throw unsupported('version')
333
+ }
334
+ checkJson(document)
335
+ checkClosed(document, CONFIG_FIELDS, 'filters')
336
+ const returnType = string(document, 'return_type')
337
+ if (!hasOwn(VALUE_CHECKS, returnType)) {
338
+ throw malformed('return_type')
339
+ }
340
+ if (hasOwn(document, 'aggregation_group_type_index')) {
341
+ const group = document.aggregation_group_type_index
342
+ if (!isNumber(group) || !Number.isInteger(group)) {
343
+ throw malformed('aggregation_group_type_index')
344
+ }
345
+ throw unsupported('aggregation_group_type_index')
346
+ }
347
+ const defaultValue = required(document, 'default_value')
348
+ if (defaultValue !== null && !VALUE_CHECKS[returnType](defaultValue)) {
349
+ throw malformed('default_value')
350
+ }
351
+ const rules = array(document, 'rules', MAX_RULES).map((rule) => readRule(rule, returnType))
352
+ if (new Set(rules.map((rule) => rule.id)).size !== rules.length) {
353
+ throw malformed('rule.id')
354
+ }
355
+ const comparesDates = rules.some((rule) => rule.targeting.some((predicate) => DATE_OPERATORS.has(predicate.operator)))
356
+ return { defaultValue: defaultValue as FlagRecordValue, rules, comparesDates }
357
+ }
358
+
359
+ /** Rejects values that the reference's JSON reader does not produce. */
360
+ function checkJson(document: unknown): void {
361
+ const pending: [unknown, number][] = [[document, 1]]
362
+ while (pending.length > 0) {
363
+ const [value, depth] = pending.pop()!
364
+ if (Array.isArray(value) || isJsonObject(value)) {
365
+ if (depth > MAX_JSON_DEPTH) {
366
+ throw malformed('filters')
367
+ }
368
+ if (Array.isArray(value)) {
369
+ // A hole reads as undefined, which is not a JSON value.
370
+ for (let index = 0; index < value.length; index++) {
371
+ pending.push([value[index], depth + 1])
372
+ }
373
+ } else {
374
+ for (const key of Object.keys(value)) {
375
+ if (!isText(key)) {
376
+ throw malformed('filters')
377
+ }
378
+ pending.push([value[key], depth + 1])
379
+ }
380
+ }
381
+ } else if (!isJsonScalar(value)) {
382
+ throw malformed('filters')
383
+ }
384
+ }
385
+ }
386
+
387
+ function isJsonScalar(value: unknown): boolean {
388
+ if (value === null || typeof value === 'boolean') {
389
+ return true
390
+ }
391
+ if (typeof value === 'string') {
392
+ return isText(value)
393
+ }
394
+ return typeof value === 'number' && Number.isFinite(value)
395
+ }
396
+
397
+ /** Whether a string holds only Unicode scalar values, so no lone surrogate. */
398
+ function isText(value: string): boolean {
399
+ for (let index = 0; index < value.length; index++) {
400
+ const unit = value.charCodeAt(index)
401
+ if (unit >= 0xd800 && unit <= 0xdbff) {
402
+ const next = value.charCodeAt(index + 1)
403
+ if (!(next >= 0xdc00 && next <= 0xdfff)) {
404
+ return false
405
+ }
406
+ index++
407
+ } else if (unit >= 0xdc00 && unit <= 0xdfff) {
408
+ return false
409
+ }
410
+ }
411
+ return true
412
+ }
413
+
414
+ /** An object as JSON reads it: not an array, a class instance or a `Date`. */
415
+ function isJsonObject(value: unknown): value is Record<string, unknown> {
416
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
417
+ return false
418
+ }
419
+ const prototype = Object.getPrototypeOf(value)
420
+ return prototype === Object.prototype || prototype === null
421
+ }
422
+
423
+ const isNumber = (value: unknown): value is number => typeof value === 'number' && !Number.isNaN(value)
424
+
425
+ function object(value: unknown, field: string): Record<string, unknown> {
426
+ if (!isJsonObject(value)) {
427
+ throw malformed(field)
428
+ }
429
+ return value
430
+ }
431
+
432
+ function required(mapping: Record<string, unknown>, field: string): unknown {
433
+ if (!hasOwn(mapping, field)) {
434
+ throw malformed(field)
435
+ }
436
+ return mapping[field]
437
+ }
438
+
439
+ function optional(mapping: Record<string, unknown>, field: string): unknown {
440
+ return hasOwn(mapping, field) ? mapping[field] : undefined
441
+ }
442
+
443
+ function string(mapping: Record<string, unknown>, field: string): string {
444
+ const value = required(mapping, field)
445
+ if (typeof value !== 'string') {
446
+ throw malformed(field)
447
+ }
448
+ return value
449
+ }
450
+
451
+ function array(mapping: Record<string, unknown>, field: string, limit: number): unknown[] {
452
+ const value = required(mapping, field)
453
+ if (!Array.isArray(value) || value.length > limit) {
454
+ throw malformed(field)
455
+ }
456
+ return value
457
+ }
458
+
459
+ function checkClosed(mapping: Record<string, unknown>, fields: ReadonlySet<string>, field: string): void {
460
+ if (Object.keys(mapping).some((key) => !fields.has(key))) {
461
+ throw malformed(field)
462
+ }
463
+ }
464
+
465
+ const isSafeNumber = (value: unknown): boolean => isNumber(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER
466
+
467
+ const isObjectValue = (value: unknown): boolean => isJsonObject(value) && isNestedValue(value, 1)
468
+
469
+ /** Depth counts objects and arrays, with the returned object at level 1. */
470
+ function isNestedValue(value: unknown, depth: number): boolean {
471
+ const items = Array.isArray(value) ? value : isJsonObject(value) ? Object.values(value) : undefined
472
+ if (items !== undefined) {
473
+ return depth <= MAX_OBJECT_DEPTH && items.every((item) => isNestedValue(item, depth + 1))
474
+ }
475
+ return !isNumber(value) || isSafeNumber(value)
476
+ }
477
+
478
+ // Whether a value is a non-null value of the flag's return type.
479
+ const VALUE_CHECKS: Readonly<Record<string, (value: unknown) => boolean>> = {
480
+ boolean: (value) => typeof value === 'boolean',
481
+ string: (value) => typeof value === 'string' && value !== '',
482
+ number: isSafeNumber,
483
+ object: isObjectValue,
484
+ }
485
+
486
+ const RULE_ID_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}$/
487
+ const VARIANT_KEY_PATTERN = /^[A-Za-z0-9_-]+$/
488
+
489
+ function readRule(value: unknown, returnType: string): Rule {
490
+ const rule = object(value, 'rule')
491
+ const ruleType = string(rule, 'rule_type')
492
+ if (!hasOwn(FIELDS_BY_RULE_TYPE, ruleType)) {
493
+ throw malformed('rule_type')
494
+ }
495
+ checkClosed(rule, FIELDS_BY_RULE_TYPE[ruleType], 'rule')
496
+ let id = string(rule, 'id')
497
+ if (!RULE_ID_PATTERN.test(id)) {
498
+ throw malformed('rule.id')
499
+ }
500
+ id = id.toLowerCase()
501
+ if (hasOwn(rule, 'description') && typeof rule.description !== 'string') {
502
+ throw malformed('description')
503
+ }
504
+ if (hasOwn(rule, 'metadata') && !isJsonObject(rule.metadata)) {
505
+ throw malformed('metadata')
506
+ }
507
+ const targeting = readTargeting(required(rule, 'targeting'))
508
+ if (ruleType === 'targeted_release') {
509
+ return { ruleType, id, targeting, value: typedValue(rule, returnType) }
510
+ }
511
+ if (ruleType === 'percentage_rollout') {
512
+ const rollout = readRollout(rule)
513
+ return { ruleType, id, targeting, value: typedValue(rule, returnType), rollout }
514
+ }
515
+ const paused = required(rule, 'paused')
516
+ if (typeof paused !== 'boolean') {
517
+ throw malformed('paused')
518
+ }
519
+ const rollout = readRollout(rule)
520
+ const variants = readVariants(rule, returnType)
521
+ const holdout = hasOwn(rule, 'holdout') ? readHoldout(rule.holdout) : undefined
522
+ return { ruleType: 'experiment', id, targeting, paused, rollout, variants, holdout }
523
+ }
524
+
525
+ function typedValue(mapping: Record<string, unknown>, returnType: string): FlagRecordValue {
526
+ const value = required(mapping, 'value')
527
+ if (!VALUE_CHECKS[returnType](value)) {
528
+ throw malformed('value')
529
+ }
530
+ return value as FlagRecordValue
531
+ }
532
+
533
+ function readRollout(rule: Record<string, unknown>): Rollout {
534
+ if (string(rule, 'assignment_algorithm') !== ASSIGNMENT_ALGORITHM) {
535
+ throw malformed('assignment_algorithm')
536
+ }
537
+ if (hasOwn(rule, 'assign_by') && rule.assign_by !== 'person') {
538
+ throw malformed('assign_by')
539
+ }
540
+ const onRolloutMiss = string(rule, 'on_rollout_miss')
541
+ if (onRolloutMiss !== 'continue' && onRolloutMiss !== 'return_default') {
542
+ throw malformed('on_rollout_miss')
543
+ }
544
+ return {
545
+ percentage: percentage(rule, 'rollout_percentage'),
546
+ returnDefaultOnMiss: onRolloutMiss === 'return_default',
547
+ seed: seed(rule),
548
+ }
549
+ }
550
+
551
+ function percentage(mapping: Record<string, unknown>, field: string): number {
552
+ const value = required(mapping, field)
553
+ // A percentage has at most two decimals.
554
+ if (!isNumber(value) || !(value >= 0 && value <= 100) || Number(value.toFixed(2)) !== value) {
555
+ throw malformed(field)
556
+ }
557
+ return value
558
+ }
559
+
560
+ function seed(mapping: Record<string, unknown>): string {
561
+ const value = string(mapping, 'seed')
562
+ const length = codePointLength(value)
563
+ if (length < 1 || length > MAX_SEED_LENGTH) {
564
+ throw malformed('seed')
565
+ }
566
+ return value
567
+ }
568
+
569
+ function readVariants(rule: Record<string, unknown>, returnType: string): Variant[] {
570
+ const items = array(rule, 'variants', MAX_VARIANTS)
571
+ if (items.length < MIN_VARIANTS) {
572
+ throw malformed('variants')
573
+ }
574
+ const variants = items.map((item) => readVariant(item, returnType))
575
+ if (new Set(variants.map((variant) => variant.key)).size !== variants.length) {
576
+ throw malformed('variant.key')
577
+ }
578
+ // Weights have two decimals, so whole hundredths add up exactly.
579
+ if (variants.reduce((sum, variant) => sum + Math.floor(variant.weight * 100 + 0.5), 0) !== 10_000) {
580
+ throw malformed('variants')
581
+ }
582
+ return variants
583
+ }
584
+
585
+ function readVariant(value: unknown, returnType: string): Variant {
586
+ const variant = object(value, 'variant')
587
+ checkClosed(variant, VARIANT_FIELDS, 'variant')
588
+ const key = string(variant, 'key')
589
+ if (!VARIANT_KEY_PATTERN.test(key)) {
590
+ throw malformed('variant.key')
591
+ }
592
+ return { key, weight: percentage(variant, 'weight'), value: typedValue(variant, returnType) }
593
+ }
594
+
595
+ function readHoldout(value: unknown): Holdout {
596
+ const holdout = object(value, 'holdout')
597
+ checkClosed(holdout, HOLDOUT_FIELDS, 'holdout')
598
+ return { seed: seed(holdout), exclusionPercentage: percentage(holdout, 'exclusion_percentage') }
599
+ }
600
+
601
+ function readTargeting(value: unknown): Predicate[] {
602
+ const targeting = object(value, 'targeting')
603
+ checkClosed(targeting, TARGETING_FIELDS, 'targeting')
604
+ return array(targeting, 'properties', MAX_PREDICATES).map(readPredicate)
605
+ }
606
+
607
+ function readPredicate(value: unknown): Predicate {
608
+ const prop = object(value, 'property')
609
+ checkClosed(prop, PROPERTY_FIELDS, 'property')
610
+ const propertyType = string(prop, 'type')
611
+ if (UNSUPPORTED_PROPERTY_TYPES.has(propertyType)) {
612
+ throw unsupported('property.type')
613
+ }
614
+ if (propertyType !== 'person') {
615
+ throw malformed('property.type')
616
+ }
617
+ const key = string(prop, 'key')
618
+ if (key === '') {
619
+ throw malformed('property.key')
620
+ }
621
+ let operator = optional(prop, 'operator') ?? null
622
+ if (operator === null) {
623
+ operator = 'exact'
624
+ } else if (typeof operator !== 'string' || !OPERATORS.has(operator)) {
625
+ throw malformed('property.operator')
626
+ }
627
+ const negation = optional(prop, 'negation') ?? null
628
+ if (negation !== null && typeof negation !== 'boolean') {
629
+ throw malformed('property.negation')
630
+ }
631
+ checkUnreadFields(prop)
632
+ const filterValue = optional(prop, 'value') ?? null
633
+ return {
634
+ key,
635
+ operator: operator as string,
636
+ value: filterValue,
637
+ negation: negation === true,
638
+ operand: readOperand(operator as string, filterValue),
639
+ }
640
+ }
641
+
642
+ /** Checks the fields a person filter may carry but evaluation does not read. */
643
+ function checkUnreadFields(prop: Record<string, unknown>): void {
644
+ if ((optional(prop, 'group_type_index') ?? null) !== null) {
645
+ throw malformed('property.group_type_index')
646
+ }
647
+ for (const field of ['cohort_name', 'label']) {
648
+ const value = optional(prop, field) ?? null
649
+ if (value !== null && typeof value !== 'string') {
650
+ throw malformed('property.presentation')
651
+ }
652
+ }
653
+ const names = optional(prop, 'group_key_names') ?? null
654
+ if (names !== null && !(isJsonObject(names) && Object.values(names).every((name) => typeof name === 'string'))) {
655
+ throw malformed('property.group_key_names')
656
+ }
657
+ }
658
+
659
+ /** Checks a filter value against its operator, and reads what the operator compares with. */
660
+ function readOperand(operator: string, value: unknown): Operand {
661
+ if (NUMBER_OPERATORS.has(operator)) {
662
+ if (typeof value === 'string' || isNumber(value)) {
663
+ // A string that is not a number is an evaluation error, not a parse error.
664
+ return toNumber(value)
665
+ }
666
+ } else if (SEMVER_COMPARISON_OPERATORS.has(operator) || SEMVER_RANGE_OPERATORS.has(operator)) {
667
+ if (typeof value === 'string') {
668
+ return readSemverFilter(operator, value)
669
+ }
670
+ } else if (DATE_OPERATORS.has(operator)) {
671
+ if (typeof value === 'string') {
672
+ return readDateFilter(value)
673
+ }
674
+ } else if (MULTI_TEXT_OPERATORS.has(operator)) {
675
+ if (Array.isArray(value) && value.every((item) => typeof item === 'string')) {
676
+ return null
677
+ }
678
+ } else if (REGEX_OPERATORS.has(operator) || TEXT_OPERATORS.has(operator)) {
679
+ if (typeof value === 'string') {
680
+ return null
681
+ }
682
+ } else if (EXACT_OPERATORS.has(operator)) {
683
+ // The text of a number depends on how the document spells it, `7` or `7.0`, which JavaScript
684
+ // reads as one number. JSON spells a string and a boolean one way.
685
+ if (isStringOrBoolean(value) || (Array.isArray(value) && value.length > 0 && value.every(isStringOrBoolean))) {
686
+ return null
687
+ }
688
+ } else {
689
+ return null
690
+ }
691
+ throw malformed('property.value')
692
+ }
693
+
694
+ const isStringOrBoolean = (value: unknown): value is string | boolean =>
695
+ typeof value === 'string' || typeof value === 'boolean'
696
+
697
+ // --- Evaluation ------------------------------------------------------------------------------
698
+
699
+ /**
700
+ * Evaluates a parsed flag for one person. `active` is the flag's own `active` field. An inactive
701
+ * flag has no value, with the reason `flag_disabled`, whatever its document holds.
702
+ */
703
+ export function evaluateConfigV2(
704
+ config: ConfigV2 | ConfigV2Unsupported,
705
+ context: ConfigV2Context,
706
+ options: { active?: boolean } = {}
707
+ ): Promise<ConfigV2Outcome> {
708
+ return evaluateConfigV2WithHash(config, context, drawHash, options)
709
+ }
710
+
711
+ /**
712
+ * Test seam: `draw(use, seed, subject)` replaces every hash an evaluation draws.
713
+ *
714
+ * @internal
715
+ */
716
+ export async function evaluateConfigV2WithHash(
717
+ config: ConfigV2 | ConfigV2Unsupported,
718
+ context: ConfigV2Context,
719
+ draw: ConfigV2Draw,
720
+ { active = true }: { active?: boolean } = {}
721
+ ): Promise<ConfigV2Outcome> {
722
+ if (!active) {
723
+ return { outcome: 'evaluated', value: null, reason: 'flag_disabled' }
724
+ }
725
+ if (isConfigV2Unsupported(config)) {
726
+ return config
727
+ }
728
+ if (context.now === undefined && config.comparesDates) {
729
+ // Every relative date of one evaluation counts back from the same time.
730
+ context = { ...context, now: new Date() }
731
+ }
732
+ const draws = new Draws(context.identifier, draw)
733
+ try {
734
+ for (let index = 0; index < config.rules.length; index++) {
735
+ const rule = config.rules[index]
736
+ if (!rule.targeting.every((predicate) => matches(predicate, context))) {
737
+ continue
738
+ }
739
+ const result = await applyRule(rule, index, config.defaultValue, draws)
740
+ if (result !== undefined) {
741
+ return result
742
+ }
743
+ // The rollout missed and the rule says to continue.
744
+ }
745
+ } catch (error) {
746
+ if (error instanceof Halt) {
747
+ return error.result
748
+ }
749
+ if (error instanceof InconclusiveMatchError) {
750
+ // The version 1 regular expression matcher leaves the pattern or the value to the server.
751
+ return { outcome: 'inconclusive', reason: error.reason, detail: error.message }
752
+ }
753
+ throw error
754
+ }
755
+ return { outcome: 'evaluated', value: config.defaultValue, reason: 'no_rule_match' }
756
+ }
757
+
758
+ /** The result of a rule whose targeting matched, or `undefined` to try the next rule. */
759
+ async function applyRule(
760
+ rule: Rule,
761
+ index: number,
762
+ defaultValue: FlagRecordValue,
763
+ draws: Draws
764
+ ): Promise<ConfigV2Evaluated | undefined> {
765
+ const result = (reason: string, value: FlagRecordValue, variantKey?: string): ConfigV2Evaluated => ({
766
+ outcome: 'evaluated',
767
+ value,
768
+ reason,
769
+ ruleId: rule.id,
770
+ ruleType: rule.ruleType,
771
+ ruleIndex: index,
772
+ ...(variantKey !== undefined ? { variantKey } : {}),
773
+ })
774
+
775
+ if (rule.ruleType === 'targeted_release') {
776
+ return result('targeting_match', rule.value)
777
+ }
778
+ if (rule.ruleType === 'experiment') {
779
+ // A paused rule and a holdout are terminal whatever the rule says about a miss.
780
+ if (rule.paused) {
781
+ return result('experiment_paused', defaultValue)
782
+ }
783
+ const holdout = rule.holdout
784
+ if (holdout !== undefined && (await draws.includes('holdout', holdout.seed, holdout.exclusionPercentage))) {
785
+ return result('holdout', defaultValue)
786
+ }
787
+ }
788
+ const rollout = rule.rollout
789
+ if (await draws.includes('rollout', rollout.seed, rollout.percentage)) {
790
+ if (rule.ruleType === 'percentage_rollout') {
791
+ return result('targeting_match', rule.value)
792
+ }
793
+ const variant = selectVariant(await draws.draw('variant', rollout.seed), rule.variants)
794
+ return result('experiment_split', variant.value, variant.key)
795
+ }
796
+ if (rollout.returnDefaultOnMiss) {
797
+ return result('rollout_miss', defaultValue)
798
+ }
799
+ return undefined
800
+ }
801
+
802
+ // --- Hashing -------------------------------------------------------------------------------
803
+
804
+ /** The `sha1_60_v1` hash: the first 60 bits of a SHA-1 digest, scaled to 0..1. */
805
+ export async function hash01(prefix: string, identifier: string, salt: string): Promise<number> {
806
+ const digest = await hashSHA1(prefix + identifier + salt)
807
+ // Both operands are binary64 before the one division.
808
+ return parseInt(digest.slice(0, 15), 16) / HASH_SCALE
809
+ }
810
+
811
+ function drawHash(use: HashUse, seed: string, subject: string): Promise<number> {
812
+ if (use === 'holdout') {
813
+ // No ".": the seed is the whole prefix.
814
+ return hash01(seed, subject, '')
815
+ }
816
+ return hash01(`${seed}.`, subject, use === 'variant' ? 'variant' : '')
817
+ }
818
+
819
+ /** 100 percent includes without hashing. Below it, the comparison is inclusive. */
820
+ export async function inRollout(percentage: number, draw: () => number | Promise<number>): Promise<boolean> {
821
+ return percentage === 100 || (await draw()) <= percentage / 100
822
+ }
823
+
824
+ /** Boundaries add left to right. Past the last one, the last variant wins. */
825
+ export function selectVariant<T extends { readonly weight: number }>(hash: number, variants: readonly T[]): T {
826
+ let boundary = 0
827
+ for (const variant of variants) {
828
+ boundary += variant.weight / 100
829
+ if (hash < boundary) {
830
+ return variant
831
+ }
832
+ }
833
+ return variants[variants.length - 1]
834
+ }
835
+
836
+ /** Cuts an identifier to its first 200 Unicode scalar values, as the flags service does. */
837
+ export function truncateIdentifier(identifier: string): string {
838
+ return codePointLength(identifier) <= MAX_IDENTIFIER_LENGTH
839
+ ? identifier
840
+ : Array.from(identifier).slice(0, MAX_IDENTIFIER_LENGTH).join('')
841
+ }
842
+
843
+ function codePointLength(value: string): number {
844
+ let length = 0
845
+ for (const _ of value) {
846
+ length++
847
+ }
848
+ return length
849
+ }
850
+
851
+ /**
852
+ * The hashes one evaluation draws for its identifier. The subject of a hash is the truncated
853
+ * identifier, and a use and seed drawn again share the hash drawn first.
854
+ */
855
+ class Draws {
856
+ private readonly subject: string
857
+ private hashes?: Map<string, number>
858
+
859
+ constructor(
860
+ private readonly identifier: string,
861
+ private readonly drawHash: ConfigV2Draw
862
+ ) {
863
+ this.subject = truncateIdentifier(identifier)
864
+ }
865
+
866
+ async draw(use: HashUse, seed: string): Promise<number> {
867
+ const key = `${use}\0${seed}`
868
+ let hash = this.hashes?.get(key)
869
+ if (hash === undefined) {
870
+ // UTF-8 has no encoding for a lone surrogate, so the flags service rejects a request whose
871
+ // identifier has one anywhere, before it truncates the identifier, and never hashes it.
872
+ if (!isText(this.identifier)) {
873
+ throw unusableContext('The identifier is not valid Unicode, so it cannot be hashed')
874
+ }
875
+ hash = await this.drawHash(use, seed, this.subject)
876
+ this.hashes ??= new Map()
877
+ this.hashes.set(key, hash)
878
+ }
879
+ return hash
880
+ }
881
+
882
+ // An empty subject never enters a rollout or a holdout, so it is never hashed.
883
+ async includes(use: HashUse, seed: string, percentage: number): Promise<boolean> {
884
+ return this.subject !== '' && (await inRollout(percentage, () => this.draw(use, seed)))
885
+ }
886
+ }
887
+
888
+ // --- Property matching ---------------------------------------------------------------------
889
+
890
+ /** Whether a predicate holds for the person, after its negation. */
891
+ function matches(predicate: Predicate, context: ConfigV2Context): boolean {
892
+ const properties = context.properties
893
+ if (properties === null || properties === undefined) {
894
+ throw unusableContext('No person properties were passed')
895
+ }
896
+ const present = hasOwn(properties, predicate.key) && isKeptByJson(properties[predicate.key])
897
+ if (!present && !context.propertiesComplete) {
898
+ throw unusableContext(`The person property '${predicate.key}' was not passed`)
899
+ }
900
+ // An invalid pattern is an error even when the person lacks the property, and negation does
901
+ // not turn it into a match.
902
+ if (REGEX_OPERATORS.has(predicate.operator) && !isValidPattern(predicate.value as string)) {
903
+ throw new Halt({
904
+ outcome: 'error',
905
+ kind: 'invalid_regex',
906
+ detail: `The pattern for '${predicate.key}' is not valid`,
907
+ })
908
+ }
909
+ const matched = matchOperator(predicate, present, present ? properties[predicate.key] : undefined, context)
910
+ return matched !== predicate.negation
911
+ }
912
+
913
+ /** Whether JSON keeps an object member with this value. It leaves out `undefined`, functions and symbols. */
914
+ function isKeptByJson(value: unknown): boolean {
915
+ return value !== undefined && typeof value !== 'function' && typeof value !== 'symbol'
916
+ }
917
+
918
+ function matchOperator(predicate: Predicate, present: boolean, value: unknown, context: ConfigV2Context): boolean {
919
+ const operator = predicate.operator
920
+ if (PRESENCE_OPERATORS.has(operator)) {
921
+ return operator === 'is_set' ? present : !present
922
+ }
923
+ if (!present) {
924
+ return OPERATORS_MATCHING_ABSENCE.has(operator)
925
+ }
926
+ if (EXACT_OPERATORS.has(operator)) {
927
+ const matched = matchExact(predicate.value, value, context.explicitExactMatching)
928
+ return operator === 'exact' ? matched : !matched
929
+ }
930
+ if (TEXT_OPERATORS.has(operator)) {
931
+ return matchText(operator, predicate.value as string, value)
932
+ }
933
+ if (MULTI_TEXT_OPERATORS.has(operator)) {
934
+ return matchAnySubstring(predicate, value)
935
+ }
936
+ if (REGEX_OPERATORS.has(operator)) {
937
+ const found = matchPattern(predicate.value as string, jsonText(value))
938
+ return operator === 'regex' ? found : !found
939
+ }
940
+ if (NUMBER_OPERATORS.has(operator)) {
941
+ return matchNumber(predicate, value)
942
+ }
943
+ if (DATE_OPERATORS.has(operator)) {
944
+ return matchDate(predicate, value, context)
945
+ }
946
+ return matchSemver(predicate, value)
947
+ }
948
+
949
+ function matchExact(filterValue: unknown, value: unknown, explicitExactMatching: boolean): boolean {
950
+ const valueText = jsonText(value).toLowerCase()
951
+ if (!explicitExactMatching && isTruthyOrFalsy(filterValue)) {
952
+ return isTruthy(filterValue) === isTruthy(value)
953
+ }
954
+ // The parser reads only strings and booleans here, and `String` gives their JSON text.
955
+ if (Array.isArray(filterValue)) {
956
+ return filterValue.map((candidate) => String(candidate).toLowerCase()).includes(valueText)
957
+ }
958
+ return String(filterValue).toLowerCase() === valueText
959
+ }
960
+
961
+ function isTruthyOrFalsy(value: unknown): boolean {
962
+ if (typeof value === 'boolean') {
963
+ return true
964
+ }
965
+ if (typeof value === 'string') {
966
+ const lower = value.toLowerCase()
967
+ return lower === 'true' || lower === 'false'
968
+ }
969
+ return Array.isArray(value) && value.every(isTruthyOrFalsy)
970
+ }
971
+
972
+ function isTruthy(value: unknown): boolean {
973
+ if (typeof value === 'boolean') {
974
+ return value
975
+ }
976
+ if (typeof value === 'string') {
977
+ return value.toLowerCase() === 'true'
978
+ }
979
+ return Array.isArray(value) && value.every(isTruthy)
980
+ }
981
+
982
+ function matchText(operator: string, filterValue: string, value: unknown): boolean {
983
+ const valueText = asciiLower(jsonText(value))
984
+ const filterText = asciiLower(filterValue)
985
+ let matched: boolean
986
+ if (operator === 'icontains' || operator === 'not_icontains') {
987
+ matched = valueText.includes(filterText)
988
+ } else if (operator === 'starts_with' || operator === 'not_starts_with') {
989
+ matched = valueText.startsWith(filterText)
990
+ } else {
991
+ matched = valueText.endsWith(filterText)
992
+ }
993
+ return operator.startsWith('not_') ? !matched : matched
994
+ }
995
+
996
+ function matchAnySubstring(predicate: Predicate, value: unknown): boolean {
997
+ const valueText = asciiLower(jsonText(value))
998
+ let found = false
999
+ for (const item of predicate.value as string[]) {
1000
+ if (valueText.includes(asciiLower(item))) {
1001
+ found = true
1002
+ break
1003
+ }
1004
+ }
1005
+ return predicate.operator === 'icontains_multi' ? found : !found
1006
+ }
1007
+
1008
+ /** The flags service folds only ASCII letters for these operators. */
1009
+ function asciiLower(value: string): string {
1010
+ return value.replace(/[A-Z]/g, (character) => character.toLowerCase())
1011
+ }
1012
+
1013
+ /**
1014
+ * Whether a pattern is valid. Throws `InconclusiveMatchError` for a pattern the version 1 matcher
1015
+ * leaves to the server, because JavaScript would read it differently.
1016
+ */
1017
+ function isValidPattern(pattern: string): boolean {
1018
+ if (pattern === '') {
1019
+ return true
1020
+ }
1021
+ // The version 1 matcher throws here for a pattern outside the portable subset.
1022
+ matchPattern(pattern, '')
1023
+ try {
1024
+ new RegExp(pattern)
1025
+ return true
1026
+ } catch (error) {
1027
+ if (error instanceof SyntaxError) {
1028
+ return false
1029
+ }
1030
+ throw new InconclusiveMatchError('Regex compilation requires server evaluation', 'unsupported_definition')
1031
+ }
1032
+ }
1033
+
1034
+ function matchPattern(pattern: string, text: string): boolean {
1035
+ return matchFeatureFlagProperty({ key: 'value', value: pattern, operator: 'regex' }, { value: text })
1036
+ }
1037
+
1038
+ function matchNumber(predicate: Predicate, value: unknown): boolean {
1039
+ const number = toNumber(value)
1040
+ if (number === null) {
1041
+ throw invalidProperty(`The person property '${predicate.key}' is not a number`)
1042
+ }
1043
+ const operand = predicate.operand as number | null
1044
+ if (operand === null) {
1045
+ throw invalidProperty(`The filter value for '${predicate.key}' is not a number`)
1046
+ }
1047
+ switch (predicate.operator) {
1048
+ case 'gt':
1049
+ return number > operand
1050
+ case 'gte':
1051
+ return number >= operand
1052
+ case 'lt':
1053
+ return number < operand
1054
+ default:
1055
+ return number <= operand
1056
+ }
1057
+ }
1058
+
1059
+ // The decimal numbers the reference reads from a string. JavaScript's `Number` also takes
1060
+ // surrounding whitespace, hexadecimal and an empty string. Digits after the integer part follow a
1061
+ // point, so a run of digits splits one way only and a failed match takes linear time.
1062
+ const NUMBER_PATTERN = /^[+-]?(?:inf|infinity|nan|(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:e[+-]?[0-9]+)?)$/i
1063
+
1064
+ function parseNumberText(text: string): number {
1065
+ const unsigned = text.replace(/^[+-]/, '').toLowerCase()
1066
+ if (unsigned === 'nan') {
1067
+ return NaN
1068
+ }
1069
+ if (unsigned === 'inf' || unsigned === 'infinity') {
1070
+ return text.startsWith('-') ? -Infinity : Infinity
1071
+ }
1072
+ return Number(text)
1073
+ }
1074
+
1075
+ /** Reads a JSON number or a numeric string as binary64, or `null` for anything else. */
1076
+ function toNumber(value: unknown): number | null {
1077
+ if (typeof value === 'string') {
1078
+ return NUMBER_PATTERN.test(value) ? parseNumberText(value) : null
1079
+ }
1080
+ if (typeof value !== 'number') {
1081
+ if (value === null || typeof value === 'boolean' || Array.isArray(value) || isJsonObject(value)) {
1082
+ return null
1083
+ }
1084
+ throw unusableContext(`A property value of type ${describeType(value)} is not a JSON value`)
1085
+ }
1086
+ if (!Number.isFinite(value)) {
1087
+ throw unusableContext('A property value is not a finite number')
1088
+ }
1089
+ return value
1090
+ }
1091
+
1092
+ function describeType(value: unknown): string {
1093
+ if (typeof value !== 'object' || value === null) {
1094
+ return typeof value
1095
+ }
1096
+ return Object.getPrototypeOf(value)?.constructor?.name ?? 'object'
1097
+ }
1098
+
1099
+ // --- JSON text -----------------------------------------------------------------------------
1100
+
1101
+ /**
1102
+ * A value the call passed, as the JSON text the flags service compares. A value JSON cannot carry
1103
+ * exactly is a missing context.
1104
+ *
1105
+ * A string is its own text. Objects list their keys in code point order. A number is sent to the
1106
+ * flags service as JSON, which writes an integral number as an integer.
1107
+ */
1108
+ export function jsonText(value: unknown): string {
1109
+ if (typeof value === 'string') {
1110
+ if (!isText(value)) {
1111
+ throw new InconclusiveMatchError('A string with a lone surrogate is not JSON text', 'missing_context')
1112
+ }
1113
+ return value
1114
+ }
1115
+ return jsonValueText(value, 1)
1116
+ }
1117
+
1118
+ /** Depth counts arrays and objects, with the outermost at level 1, as in `checkJson`. */
1119
+ function jsonValueText(value: unknown, depth: number): string {
1120
+ if ((Array.isArray(value) || isJsonObject(value)) && depth > MAX_JSON_DEPTH) {
1121
+ throw new InconclusiveMatchError('A value is nested too deeply to compare', 'missing_context')
1122
+ }
1123
+ if (value === null) {
1124
+ return 'null'
1125
+ }
1126
+ if (typeof value === 'boolean') {
1127
+ return value ? 'true' : 'false'
1128
+ }
1129
+ if (typeof value === 'string') {
1130
+ if (!isText(value)) {
1131
+ throw new InconclusiveMatchError('A string with a lone surrogate is not JSON text', 'missing_context')
1132
+ }
1133
+ return JSON.stringify(value)
1134
+ }
1135
+ if (typeof value === 'number') {
1136
+ return numberText(value)
1137
+ }
1138
+ if (Array.isArray(value)) {
1139
+ const items: string[] = []
1140
+ for (let index = 0; index < value.length; index++) {
1141
+ items.push(jsonValueText(value[index], depth + 1))
1142
+ }
1143
+ return `[${items.join(',')}]`
1144
+ }
1145
+ if (isJsonObject(value)) {
1146
+ const keys = Object.keys(value).sort(compareCodePoints)
1147
+ return `{${keys.map((key) => `${jsonValueText(key, depth + 1)}:${jsonValueText(value[key], depth + 1)}`).join(',')}}`
1148
+ }
1149
+ throw new InconclusiveMatchError(
1150
+ `A property value of type ${describeType(value)} is not a JSON value`,
1151
+ 'missing_context'
1152
+ )
1153
+ }
1154
+
1155
+ function numberText(value: number): string {
1156
+ if (!Number.isFinite(value)) {
1157
+ throw new InconclusiveMatchError('A number that is not finite is not JSON text', 'missing_context')
1158
+ }
1159
+ if (Number.isInteger(value)) {
1160
+ if (Math.abs(value) > Number.MAX_SAFE_INTEGER) {
1161
+ throw new InconclusiveMatchError(
1162
+ `The JSON text of ${value} may be an integer or a decimal, which the flags service compares differently`,
1163
+ 'missing_context'
1164
+ )
1165
+ }
1166
+ return String(value)
1167
+ }
1168
+ return floatText(value)
1169
+ }
1170
+
1171
+ /**
1172
+ * The text the flags service writes for a binary64 that is not an integer: the shortest digits
1173
+ * that read back as the same number, in decimal notation from 1e-5 up to 1e16, and otherwise with
1174
+ * an exponent, such as `1e-7`.
1175
+ */
1176
+ function floatText(value: number): string {
1177
+ const [mantissa, exponentText] = Math.abs(value).toExponential().split('e')
1178
+ const digits = mantissa.replace('.', '')
1179
+ // The number is 0.digits * 10^point.
1180
+ const point = Number(exponentText) + 1
1181
+ let text: string
1182
+ if (point > 0 && point <= 16) {
1183
+ text =
1184
+ digits.length <= point
1185
+ ? `${digits}${'0'.repeat(point - digits.length)}.0`
1186
+ : `${digits.slice(0, point)}.${digits.slice(point)}`
1187
+ } else if (point > -5 && point <= 0) {
1188
+ text = `0.${'0'.repeat(-point)}${digits}`
1189
+ } else {
1190
+ const fraction = digits.length > 1 ? `.${digits.slice(1)}` : ''
1191
+ const exponent = point - 1
1192
+ text = `${digits[0]}${fraction}e${exponent >= 0 ? '+' : ''}${exponent}`
1193
+ }
1194
+ return value < 0 ? `-${text}` : text
1195
+ }
1196
+
1197
+ function compareCodePoints(left: string, right: string): number {
1198
+ const leftPoints = Array.from(left)
1199
+ const rightPoints = Array.from(right)
1200
+ for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index++) {
1201
+ const difference = leftPoints[index].codePointAt(0)! - rightPoints[index].codePointAt(0)!
1202
+ if (difference !== 0) {
1203
+ return difference
1204
+ }
1205
+ }
1206
+ return leftPoints.length - rightPoints.length
1207
+ }
1208
+
1209
+ // --- Semantic versions -----------------------------------------------------------------------
1210
+ //
1211
+ // The reference compares versions with full semantic version ordering, so a pre-release sorts
1212
+ // below its release, and a range matches a pre-release only when the range names one for the same
1213
+ // version.
1214
+
1215
+ // What the reference trims from a version string: the Unicode White_Space characters.
1216
+ const WHITESPACE = new Set(
1217
+ [
1218
+ 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0x85, 0xa0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006,
1219
+ 0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000,
1220
+ ].map((code) => String.fromCharCode(code))
1221
+ )
1222
+ const INTEGER = '(?:0|[1-9][0-9]*)'
1223
+ const PRE_RELEASE_PART = `(?:${INTEGER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)`
1224
+ const PRE_RELEASE = `${PRE_RELEASE_PART}(?:\\.${PRE_RELEASE_PART})*`
1225
+ const BUILD = '[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*'
1226
+ const VERSION_PATTERN = new RegExp(
1227
+ `^(${INTEGER})\\.(${INTEGER})\\.(${INTEGER})(?:-(${PRE_RELEASE}))?(?:\\+(${BUILD}))?$`
1228
+ )
1229
+ // A version requirement: a version that may end early, or in wildcard components.
1230
+ const REQUIREMENT_PATTERN = new RegExp(
1231
+ `^(?<major>${INTEGER})` +
1232
+ `(?:(?<anyMinor>\\.[xX*](?:\\.[xX*])?)` +
1233
+ `|\\.(?<minor>${INTEGER})` +
1234
+ `(?:(?<anyPatch>\\.[xX*])` +
1235
+ `|\\.(?<patch>${INTEGER})(?:-(?<pre>${PRE_RELEASE}))?(?:\\+${BUILD})?)?)?$`
1236
+ )
1237
+ const UNSIGNED_INTEGER_PATTERN = /^\+?([0-9]+)$/
1238
+
1239
+ type Version = {
1240
+ readonly major: bigint
1241
+ readonly minor: bigint
1242
+ readonly patch: bigint
1243
+ readonly pre: string
1244
+ readonly build: string
1245
+ }
1246
+
1247
+ // A sort key: numbers, bigints, strings and nested keys, compared in order.
1248
+ type SortKey = readonly (number | bigint | string | SortKey)[]
1249
+ type VersionKey = { readonly kind: 'version'; readonly key: SortKey }
1250
+
1251
+ /** A version range. `minor` and `patch` are `null` where any number matches. */
1252
+ type Requirement = {
1253
+ readonly kind: 'tilde' | 'caret' | 'wildcard'
1254
+ readonly major: bigint
1255
+ readonly minor: bigint | null
1256
+ readonly patch: bigint | null
1257
+ readonly pre: string
1258
+ }
1259
+
1260
+ function compareKeys(left: SortKey, right: SortKey): number {
1261
+ for (let index = 0; index < Math.min(left.length, right.length); index++) {
1262
+ const a = left[index]
1263
+ const b = right[index]
1264
+ const difference =
1265
+ Array.isArray(a) && Array.isArray(b)
1266
+ ? compareKeys(a, b)
1267
+ : (a as number) < (b as number)
1268
+ ? -1
1269
+ : (a as number) > (b as number)
1270
+ ? 1
1271
+ : 0
1272
+ if (difference !== 0) {
1273
+ return difference
1274
+ }
1275
+ }
1276
+ return left.length - right.length
1277
+ }
1278
+
1279
+ function isU64(digits: string): boolean {
1280
+ const significant = digits.replace(/^0+/, '')
1281
+ return significant.length <= 20 && BigInt(significant || '0') <= MAX_U64
1282
+ }
1283
+
1284
+ function stripWhitespace(text: string): string {
1285
+ let start = 0
1286
+ let end = text.length
1287
+ while (start < end && WHITESPACE.has(text[start])) {
1288
+ start++
1289
+ }
1290
+ while (end > start && WHITESPACE.has(text[end - 1])) {
1291
+ end--
1292
+ }
1293
+ return text.slice(start, end)
1294
+ }
1295
+
1296
+ /**
1297
+ * Reads a version the way the reference does, or `null` when it is not one. One leading `v` is
1298
+ * dropped, a missing minor or patch number is zero, and leading zeros of the three numbers are
1299
+ * ignored.
1300
+ */
1301
+ function parseVersion(text: string): Version | null {
1302
+ const match = VERSION_PATTERN.exec(canonicalVersion(trimVersion(text)))
1303
+ if (match === null || ![match[1], match[2], match[3]].every(isU64)) {
1304
+ return null
1305
+ }
1306
+ return {
1307
+ major: BigInt(match[1]),
1308
+ minor: BigInt(match[2]),
1309
+ patch: BigInt(match[3]),
1310
+ pre: match[4] ?? '',
1311
+ build: match[5] ?? '',
1312
+ }
1313
+ }
1314
+
1315
+ function trimVersion(text: string): string {
1316
+ return stripWhitespace(text.startsWith('v') ? text.slice(1) : text)
1317
+ }
1318
+
1319
+ function canonicalVersion(version: string): string {
1320
+ const suffix = version.search(/[-+]/)
1321
+ const core = suffix === -1 ? version : version.slice(0, suffix)
1322
+ const parts = core.split('.').map(stripLeadingZeros)
1323
+ while (parts.length < 3) {
1324
+ parts.push('0')
1325
+ }
1326
+ return parts.join('.') + version.slice(core.length)
1327
+ }
1328
+
1329
+ function stripLeadingZeros(part: string): string {
1330
+ if (!/^[0-9]+$/.test(part)) {
1331
+ return part
1332
+ }
1333
+ return part.replace(/^0+/, '') || '0'
1334
+ }
1335
+
1336
+ /** Orders pre-releases: a release is above each of its pre-releases. */
1337
+ function preReleaseKey(pre: string): SortKey {
1338
+ if (pre === '') {
1339
+ return [1]
1340
+ }
1341
+ // A numeric part is below a text part, and numeric parts compare as numbers.
1342
+ return [0, pre.split('.').map((part) => (/^[0-9]+$/.test(part) ? [0, part.length, part] : [1, part]))]
1343
+ }
1344
+
1345
+ function buildKey(build: string): SortKey {
1346
+ return build.split('.').map((part) => {
1347
+ if (part === '' || /^[0-9]+$/.test(part)) {
1348
+ const digits = part.replace(/^0+/, '')
1349
+ return [0, digits.length, digits, part.length]
1350
+ }
1351
+ return [1, part]
1352
+ })
1353
+ }
1354
+
1355
+ function versionKey(version: Version): SortKey {
1356
+ return [version.major, version.minor, version.patch, preReleaseKey(version.pre), buildKey(version.build)]
1357
+ }
1358
+
1359
+ /**
1360
+ * Reads a semver filter value, or rejects the document.
1361
+ *
1362
+ * The result is the sort key of the version to compare with, or the range to match. It is `null`
1363
+ * for a wildcard that the configuration format admits but that is not a range, such as `1.2.3.*`.
1364
+ * Evaluation reports that as an invalid property.
1365
+ *
1366
+ * The format requires plain numbers before any pre-release suffix, so it does not admit everything
1367
+ * {@link parseVersion} reads, such as a leading `v`.
1368
+ */
1369
+ function readSemverFilter(operator: string, text: string): VersionKey | Requirement | null {
1370
+ const admitted = operator === 'semver_wildcard' ? trimWildcards(text) : text
1371
+ const parsed = parseVersion(admitted)
1372
+ const numbers = admitted.split('-')[0].split('.').slice(0, 3)
1373
+ if (parsed === null || !numbers.every(isPlainNumber)) {
1374
+ throw malformed('property.value')
1375
+ }
1376
+ if (SEMVER_COMPARISON_OPERATORS.has(operator)) {
1377
+ return { kind: 'version', key: versionKey(parsed) }
1378
+ }
1379
+ const version = trimVersion(text)
1380
+ if (operator === 'semver_wildcard') {
1381
+ // The reference writes "*" as "x", which is a letter inside a pre-release.
1382
+ const parts = version.split('.').map(stripLeadingZeros)
1383
+ return parseRequirement(parts.join('.').replace(/\*/g, 'x'), null)
1384
+ }
1385
+ return parseRequirement(canonicalVersion(version), operator === 'semver_tilde' ? 'tilde' : 'caret')
1386
+ }
1387
+
1388
+ /** Drops the trailing points and `*`. A loop, because the pattern `/[.*]+$/` is quadratic on a long run. */
1389
+ function trimWildcards(text: string): string {
1390
+ let end = text.length
1391
+ while (end > 0 && (text[end - 1] === '.' || text[end - 1] === '*')) {
1392
+ end--
1393
+ }
1394
+ return text.slice(0, end)
1395
+ }
1396
+
1397
+ function isPlainNumber(text: string): boolean {
1398
+ const number = UNSIGNED_INTEGER_PATTERN.exec(stripWhitespace(text))
1399
+ return number !== null && isU64(number[1])
1400
+ }
1401
+
1402
+ function parseRequirement(text: string, kind: Requirement['kind'] | null): Requirement | null {
1403
+ const groups = REQUIREMENT_PATTERN.exec(text)?.groups
1404
+ if (groups === undefined) {
1405
+ return null
1406
+ }
1407
+ const { major, minor, patch } = groups
1408
+ if (![major, minor, patch].every((number) => !number || isU64(number))) {
1409
+ return null
1410
+ }
1411
+ // Without a wildcard the reference reads a bare version as a caret range.
1412
+ const resolvedKind = kind ?? (groups.anyMinor || groups.anyPatch ? 'wildcard' : 'caret')
1413
+ return {
1414
+ kind: resolvedKind,
1415
+ major: BigInt(major),
1416
+ minor: minor ? BigInt(minor) : null,
1417
+ patch: patch ? BigInt(patch) : null,
1418
+ pre: groups.pre ?? '',
1419
+ }
1420
+ }
1421
+
1422
+ function matchSemver(predicate: Predicate, value: unknown): boolean {
1423
+ const version = parseVersion(jsonText(value))
1424
+ if (version === null) {
1425
+ return false
1426
+ }
1427
+ const operand = predicate.operand as VersionKey | Requirement | null
1428
+ if (operand !== null && operand.kind === 'version') {
1429
+ const order = compareKeys(versionKey(version), operand.key)
1430
+ switch (predicate.operator) {
1431
+ case 'semver_eq':
1432
+ return order === 0
1433
+ case 'semver_neq':
1434
+ return order !== 0
1435
+ case 'semver_gt':
1436
+ return order > 0
1437
+ case 'semver_gte':
1438
+ return order >= 0
1439
+ case 'semver_lt':
1440
+ return order < 0
1441
+ default:
1442
+ return order <= 0
1443
+ }
1444
+ }
1445
+ if (operand === null) {
1446
+ throw invalidProperty(`The filter value for '${predicate.key}' is not a version range`)
1447
+ }
1448
+ return satisfies(version, operand)
1449
+ }
1450
+
1451
+ function satisfies(version: Version, requirement: Requirement): boolean {
1452
+ if (!inRange(version, requirement)) {
1453
+ return false
1454
+ }
1455
+ // A pre-release matches only a range that names a pre-release of the same version.
1456
+ return (
1457
+ version.pre === '' ||
1458
+ (requirement.pre !== '' &&
1459
+ version.major === requirement.major &&
1460
+ version.minor === requirement.minor &&
1461
+ version.patch === requirement.patch)
1462
+ )
1463
+ }
1464
+
1465
+ function inRange(version: Version, requirement: Requirement): boolean {
1466
+ const { kind, major, minor, patch, pre } = requirement
1467
+ if (version.major !== major) {
1468
+ return false
1469
+ }
1470
+ if (kind === 'wildcard') {
1471
+ return (
1472
+ (minor === null || minor === version.minor) && (patch === null || patch === version.patch) && version.pre === pre
1473
+ )
1474
+ }
1475
+ const reached = compareKeys(preReleaseKey(version.pre), preReleaseKey(pre)) >= 0
1476
+ if (kind === 'tilde') {
1477
+ if (minor !== null && version.minor !== minor) {
1478
+ return false
1479
+ }
1480
+ if (patch !== null && version.patch !== patch) {
1481
+ return version.patch > patch
1482
+ }
1483
+ return reached
1484
+ }
1485
+ // A caret range keeps the leftmost number that is not zero.
1486
+ if (minor === null) {
1487
+ return true
1488
+ }
1489
+ if (patch === null) {
1490
+ return major > BigInt(0) ? version.minor >= minor : version.minor === minor
1491
+ }
1492
+ if (major > BigInt(0)) {
1493
+ if (version.minor !== minor) {
1494
+ return version.minor > minor
1495
+ }
1496
+ if (version.patch !== patch) {
1497
+ return version.patch > patch
1498
+ }
1499
+ } else if (minor > BigInt(0)) {
1500
+ if (version.minor !== minor) {
1501
+ return false
1502
+ }
1503
+ if (version.patch !== patch) {
1504
+ return version.patch > patch
1505
+ }
1506
+ } else if (version.minor !== minor || version.patch !== patch) {
1507
+ return false
1508
+ }
1509
+ return reached
1510
+ }
1511
+
1512
+ // --- Dates -----------------------------------------------------------------------------------
1513
+ //
1514
+ // An instant is [seconds since the Unix epoch, nanoseconds]. The reference compares with
1515
+ // nanosecond precision, which `Date` does not have.
1516
+
1517
+ type Instant = readonly [number, number]
1518
+
1519
+ /** A wall clock without a timezone, with whole seconds. Months count from 1. */
1520
+ type WallClock = {
1521
+ readonly year: number
1522
+ readonly month: number
1523
+ readonly day: number
1524
+ readonly hour: number
1525
+ readonly minute: number
1526
+ readonly second: number
1527
+ }
1528
+
1529
+ /** A date such as `-7d`: seven days before now. The sign changes nothing. */
1530
+ type RelativeDate = { readonly kind: 'relative'; readonly number: number; readonly interval: string }
1531
+
1532
+ type AbsoluteDate = {
1533
+ readonly kind: 'absolute'
1534
+ readonly wallClock: WallClock
1535
+ readonly nanoseconds: number
1536
+ /** Seconds east of UTC; `null` means the project's timezone. */
1537
+ readonly offset: number | null
1538
+ }
1539
+
1540
+ type DateValue = RelativeDate | AbsoluteDate
1541
+
1542
+ // Epoch seconds that fall in the years 1 to 9999.
1543
+ const MIN_EPOCH_SECONDS = -62_135_596_800
1544
+ const MAX_EPOCH_SECONDS = 253_402_300_799
1545
+ const SECONDS_PER_DAY = 86_400
1546
+ const RELATIVE_DATE_PATTERN = /^-?([0-9]+)([hdwmy])$/
1547
+ const HOURS_PER_INTERVAL: Readonly<Record<string, number>> = { h: 1, d: 24, w: 168 }
1548
+ const DATE_PATTERN =
1549
+ /^(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})(?:(?<separator>[T ])(?<hour>[0-9]{2}):(?<minute>[0-9]{2})(?::(?<second>[0-9]{2})(?:\.(?<fraction>[0-9]{1,9}))?)?(?<offset>Z|[+-][0-9]{2}:[0-9]{2})?)?$/
1550
+
1551
+ /**
1552
+ * Reads a date in one of the forms this evaluator resolves exactly: a relative date, an RFC 3339
1553
+ * timestamp, a bare `YYYY-MM-DD` date, and a date and time without an offset. The reference reads
1554
+ * more forms on a best-effort basis, so `null` does not mean the reference cannot read the text.
1555
+ */
1556
+ function parseDate(text: string): DateValue | null {
1557
+ const relative = RELATIVE_DATE_PATTERN.exec(text)
1558
+ if (relative !== null) {
1559
+ const digits = relative[1].replace(/^0+/, '')
1560
+ if (digits.length > 4) {
1561
+ // 10,000 and above is not a relative date.
1562
+ return null
1563
+ }
1564
+ return { kind: 'relative', number: Number(digits || '0'), interval: relative[2] }
1565
+ }
1566
+ const groups = DATE_PATTERN.exec(text)?.groups
1567
+ if (groups === undefined) {
1568
+ return null
1569
+ }
1570
+ const offset = parseOffset(groups.offset)
1571
+ if (groups.offset !== undefined && (offset === null || groups.separator !== 'T' || groups.second === undefined)) {
1572
+ // A timestamp with an offset is RFC 3339 or nothing.
1573
+ return null
1574
+ }
1575
+ const wallClock: WallClock = {
1576
+ year: Number(groups.year),
1577
+ month: Number(groups.month),
1578
+ day: Number(groups.day),
1579
+ hour: Number(groups.hour ?? 0),
1580
+ minute: Number(groups.minute ?? 0),
1581
+ second: Number(groups.second ?? 0),
1582
+ }
1583
+ if (!isValidWallClock(wallClock)) {
1584
+ return null
1585
+ }
1586
+ const fraction = groups.fraction ?? ''
1587
+ return { kind: 'absolute', wallClock, nanoseconds: Number(fraction.padEnd(9, '0')), offset }
1588
+ }
1589
+
1590
+ function parseOffset(text: string | undefined): number | null {
1591
+ if (text === undefined) {
1592
+ return null
1593
+ }
1594
+ if (text === 'Z') {
1595
+ return 0
1596
+ }
1597
+ const hours = Number(text.slice(1, 3))
1598
+ const minutes = Number(text.slice(4, 6))
1599
+ if (hours > 23 || minutes > 59) {
1600
+ return null
1601
+ }
1602
+ const seconds = hours * 3600 + minutes * 60
1603
+ return text[0] === '-' ? -seconds : seconds
1604
+ }
1605
+
1606
+ function isValidWallClock({ year, month, day, hour, minute, second }: WallClock): boolean {
1607
+ return (
1608
+ year >= 1 &&
1609
+ year <= 9999 &&
1610
+ month >= 1 &&
1611
+ month <= 12 &&
1612
+ day >= 1 &&
1613
+ day <= daysInMonth(year, month) &&
1614
+ hour <= 23 &&
1615
+ minute <= 59 &&
1616
+ second <= 59
1617
+ )
1618
+ }
1619
+
1620
+ function daysInMonth(year: number, month: number): number {
1621
+ if (month === 2) {
1622
+ const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
1623
+ return leap ? 29 : 28
1624
+ }
1625
+ return [4, 6, 9, 11].includes(month) ? 30 : 31
1626
+ }
1627
+
1628
+ /**
1629
+ * Reads a date filter value, or rejects the document. The configuration format does not admit a
1630
+ * date and time joined by `T` without an offset, although the reference would evaluate one.
1631
+ */
1632
+ function readDateFilter(text: string): DateValue {
1633
+ const date = parseDate(text)
1634
+ if (date === null || (date.kind === 'absolute' && date.offset === null && text.includes('T'))) {
1635
+ throw unsupported('property.value')
1636
+ }
1637
+ return date
1638
+ }
1639
+
1640
+ function matchDate(predicate: Predicate, value: unknown, context: ConfigV2Context): boolean {
1641
+ const subject = propertyInstant(value, context)
1642
+ if (subject === null) {
1643
+ return false
1644
+ }
1645
+ const target = resolveDate(predicate.operand as DateValue, context)
1646
+ if (target === null) {
1647
+ return false
1648
+ }
1649
+ const order = subject[0] !== target[0] ? subject[0] - target[0] : subject[1] - target[1]
1650
+ switch (predicate.operator) {
1651
+ case 'is_date_exact':
1652
+ return order === 0
1653
+ case 'is_date_after':
1654
+ return order > 0
1655
+ default:
1656
+ return order < 0
1657
+ }
1658
+ }
1659
+
1660
+ /** The instant a person property holds, or `null` when it holds no date. */
1661
+ function propertyInstant(value: unknown, context: ConfigV2Context): Instant | null {
1662
+ if (value === null || typeof value === 'boolean' || Array.isArray(value) || isJsonObject(value)) {
1663
+ return null
1664
+ }
1665
+ if (typeof value === 'number') {
1666
+ return epochInstant(value)
1667
+ }
1668
+ if (typeof value !== 'string') {
1669
+ throw unusableContext(`A property value of type ${describeType(value)} is not a JSON value`)
1670
+ }
1671
+ // A number, also as a string, is Unix epoch seconds.
1672
+ if (NUMBER_PATTERN.test(value)) {
1673
+ return epochInstant(parseNumberText(value))
1674
+ }
1675
+ const date = parseDate(value)
1676
+ if (date !== null) {
1677
+ return resolveDate(date, context)
1678
+ }
1679
+ if (!/[0-9]/.test(value)) {
1680
+ return null
1681
+ }
1682
+ throw unusableContext('The date property is in a form that needs the flags service to read')
1683
+ }
1684
+
1685
+ /** Unix epoch seconds as an instant. */
1686
+ function epochInstant(value: number): Instant {
1687
+ if (!Number.isFinite(value)) {
1688
+ throw unusableContext('A date property is not a finite number')
1689
+ }
1690
+ const seconds = Math.floor(value)
1691
+ // The reference drops the fraction of a negative number.
1692
+ const nanoseconds = Math.max(0, roundHalfUp((value % 1) * 1e9))
1693
+ if (seconds < MIN_EPOCH_SECONDS || seconds > MAX_EPOCH_SECONDS || nanoseconds >= 1_000_000_000) {
1694
+ throw unusableContext('A date property is outside the supported range')
1695
+ }
1696
+ return [seconds, nanoseconds]
1697
+ }
1698
+
1699
+ function roundHalfUp(value: number): number {
1700
+ const whole = Math.floor(value)
1701
+ return value - whole >= 0.5 ? whole + 1 : whole
1702
+ }
1703
+
1704
+ /**
1705
+ * The instant of a date, or `null` when its wall clock does not exist. A wall clock that a
1706
+ * spring-forward transition skips has no instant. One that a fall-back transition repeats means
1707
+ * its earlier instant.
1708
+ */
1709
+ function resolveDate(date: DateValue, context: ConfigV2Context): Instant | null {
1710
+ if (date.kind === 'relative') {
1711
+ const [wallClock, milliseconds] = relativeWallClock(date, context)
1712
+ return localInstant(wallClock, milliseconds * 1_000_000, context)
1713
+ }
1714
+ if (date.offset === null) {
1715
+ return localInstant(date.wallClock, date.nanoseconds, context)
1716
+ }
1717
+ return [wallClockSeconds(date.wallClock) - date.offset, date.nanoseconds]
1718
+ }
1719
+
1720
+ function timeZoneOf(context: ConfigV2Context): string {
1721
+ if (context.timeZone === undefined) {
1722
+ throw unusableContext("The project's timezone is not known")
1723
+ }
1724
+ return context.timeZone
1725
+ }
1726
+
1727
+ /**
1728
+ * Counts back from now on the wall clock of the project's timezone, and returns the wall clock
1729
+ * and its milliseconds. A day is a calendar day there, not 24 hours. Months and years go back one
1730
+ * at a time, and each step clamps the day to the end of its month.
1731
+ */
1732
+ function relativeWallClock(date: RelativeDate, context: ConfigV2Context): [WallClock, number] {
1733
+ const now = context.now ?? new Date()
1734
+ const nowMilliseconds = now.getTime()
1735
+ if (!Number.isFinite(nowMilliseconds)) {
1736
+ throw unusableContext('The current time is not a valid date')
1737
+ }
1738
+ const milliseconds = ((nowMilliseconds % 1000) + 1000) % 1000
1739
+ const nowSeconds = (nowMilliseconds - milliseconds) / 1000
1740
+ const timeZone = timeZoneOf(context)
1741
+ const local = fromWallClockSeconds(nowSeconds + offsetAt(nowSeconds, timeZone))
1742
+ let moved: WallClock | null
1743
+ if (date.interval === 'm') {
1744
+ moved = subtractMonths(local, date.number)
1745
+ } else if (date.interval === 'y') {
1746
+ moved = subtractYears(local, date.number)
1747
+ } else {
1748
+ const hours = date.number * HOURS_PER_INTERVAL[date.interval]
1749
+ moved = fromWallClockSeconds(wallClockSeconds(local) - hours * 3600)
1750
+ if (moved.year < 1 || moved.year > 9999) {
1751
+ moved = null
1752
+ }
1753
+ }
1754
+ if (moved === null) {
1755
+ throw unusableContext('A relative date is outside the supported range')
1756
+ }
1757
+ return [moved, milliseconds]
1758
+ }
1759
+
1760
+ function subtractMonths(wallClock: WallClock, months: number): WallClock | null {
1761
+ const currentIndex = wallClock.year * 12 + wallClock.month - 1
1762
+ const monthIndex = currentIndex - months
1763
+ const year = Math.floor(monthIndex / 12)
1764
+ const month = (monthIndex % 12) + 1
1765
+ if (year < 1 || year > 9999) {
1766
+ return null
1767
+ }
1768
+ let day = wallClock.day
1769
+ for (let index = currentIndex - 1; index >= monthIndex; index--) {
1770
+ if (day <= 28) {
1771
+ // Every month has at least 28 days, so nothing clamps further.
1772
+ break
1773
+ }
1774
+ day = Math.min(day, daysInMonth(Math.floor(index / 12), (index % 12) + 1))
1775
+ }
1776
+ return { ...wallClock, year, month, day }
1777
+ }
1778
+
1779
+ function subtractYears(wallClock: WallClock, years: number): WallClock | null {
1780
+ const year = wallClock.year - years
1781
+ if (year < 1 || year > 9999) {
1782
+ return null
1783
+ }
1784
+ // The year before a leap year is never a leap year, so February 29 clamps on the first step and
1785
+ // stays on the 28th.
1786
+ const day = years > 0 && wallClock.month === 2 && wallClock.day === 29 ? 28 : wallClock.day
1787
+ return { ...wallClock, year, day }
1788
+ }
1789
+
1790
+ function localInstant(wallClock: WallClock, nanoseconds: number, context: ConfigV2Context): Instant | null {
1791
+ const timeZone = timeZoneOf(context)
1792
+ const local = wallClockSeconds(wallClock)
1793
+ // At most one transition lies within a day of any wall clock, so the offsets a day before and
1794
+ // a day after are the only offsets it can have.
1795
+ const candidates = [offsetAt(local - SECONDS_PER_DAY, timeZone), offsetAt(local + SECONDS_PER_DAY, timeZone)]
1796
+ .map((offset) => local - offset)
1797
+ .filter((instant) => instant + offsetAt(instant, timeZone) === local)
1798
+ if (candidates.length === 0) {
1799
+ // A spring-forward transition skips this wall clock.
1800
+ return null
1801
+ }
1802
+ return [Math.min(...candidates), nanoseconds]
1803
+ }
1804
+
1805
+ /** Seconds since the epoch of a wall clock read as UTC. */
1806
+ function wallClockSeconds({ year, month, day, hour, minute, second }: WallClock): number {
1807
+ return daysFromCivil(year, month, day) * SECONDS_PER_DAY + hour * 3600 + minute * 60 + second
1808
+ }
1809
+
1810
+ function fromWallClockSeconds(seconds: number): WallClock {
1811
+ const days = Math.floor(seconds / SECONDS_PER_DAY)
1812
+ const rest = seconds - days * SECONDS_PER_DAY
1813
+ const [year, month, day] = civilFromDays(days)
1814
+ return { year, month, day, hour: Math.floor(rest / 3600), minute: Math.floor((rest % 3600) / 60), second: rest % 60 }
1815
+ }
1816
+
1817
+ // Days between 1970-01-01 and a date of the proleptic Gregorian calendar, which `Date.UTC` cannot
1818
+ // give for the years 0 to 99.
1819
+ function daysFromCivil(year: number, month: number, day: number): number {
1820
+ const y = month <= 2 ? year - 1 : year
1821
+ const era = Math.floor(y / 400)
1822
+ const yearOfEra = y - era * 400
1823
+ const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1
1824
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear
1825
+ return era * 146097 + dayOfEra - 719468
1826
+ }
1827
+
1828
+ function civilFromDays(days: number): [number, number, number] {
1829
+ const z = days + 719468
1830
+ const era = Math.floor(z / 146097)
1831
+ const dayOfEra = z - era * 146097
1832
+ const yearOfEra = Math.floor(
1833
+ (dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36524) - Math.floor(dayOfEra / 146096)) / 365
1834
+ )
1835
+ const dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100))
1836
+ const monthIndex = Math.floor((5 * dayOfYear + 2) / 153)
1837
+ const day = dayOfYear - Math.floor((153 * monthIndex + 2) / 5) + 1
1838
+ const month = monthIndex < 10 ? monthIndex + 3 : monthIndex - 9
1839
+ return [yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day]
1840
+ }
1841
+
1842
+ const timeZoneFormats = new Map<string, Intl.DateTimeFormat>()
1843
+
1844
+ /** The UTC offset of a timezone at an instant, in seconds east of UTC. */
1845
+ function offsetAt(seconds: number, timeZone: string): number {
1846
+ if (timeZone === 'UTC') {
1847
+ return 0
1848
+ }
1849
+ let format = timeZoneFormats.get(timeZone)
1850
+ if (format === undefined) {
1851
+ try {
1852
+ format = new Intl.DateTimeFormat('en-US', {
1853
+ timeZone,
1854
+ calendar: 'gregory',
1855
+ era: 'short',
1856
+ year: 'numeric',
1857
+ month: 'numeric',
1858
+ day: 'numeric',
1859
+ hour: 'numeric',
1860
+ minute: 'numeric',
1861
+ second: 'numeric',
1862
+ hourCycle: 'h23',
1863
+ })
1864
+ } catch {
1865
+ throw unusableContext(`The timezone '${timeZone}' is not known`)
1866
+ }
1867
+ timeZoneFormats.set(timeZone, format)
1868
+ }
1869
+ const parts: Record<string, string> = {}
1870
+ for (const part of format.formatToParts(new Date(seconds * 1000))) {
1871
+ parts[part.type] = part.value
1872
+ }
1873
+ const year = parts.era === 'BC' || parts.era === 'B' ? 1 - Number(parts.year) : Number(parts.year)
1874
+ const local = wallClockSeconds({
1875
+ year,
1876
+ month: Number(parts.month),
1877
+ day: Number(parts.day),
1878
+ hour: Number(parts.hour),
1879
+ minute: Number(parts.minute),
1880
+ second: Number(parts.second),
1881
+ })
1882
+ return local - seconds
1883
+ }
1884
+
1885
+ // --- Local evaluation in the poller -------------------------------------------------------
1886
+ //
1887
+ // The poller evaluates a loaded definition here when its config version is not 1. The definitions
1888
+ // request does not select config version 2 flags yet, so none arrives from the API; one can still
1889
+ // come from a definition cache that a newer release shares.
1890
+
1891
+ /** The reason description of a locally evaluated record, as for a version 1 flag. */
1892
+ const LOCAL_REASON_DESCRIPTION = 'Evaluated locally'
1893
+
1894
+ /**
1895
+ * Whether a flag definition is config version 1, the format the version 1 evaluator reads. It is
1896
+ * when `filters.version` is absent or the number 1. Any other value, also one that is not a number,
1897
+ * belongs to the config version 2 evaluator, which accepts only version 2.
1898
+ */
1899
+ export function isConfigVersion1(flag: unknown): boolean {
1900
+ const filters = isJsonObject(flag) ? flag.filters : undefined
1901
+ if (!isJsonObject(filters) || filters.version === undefined) {
1902
+ return true
1903
+ }
1904
+ return filters.version === 1
1905
+ }
1906
+
1907
+ /** A loaded definition and its `filters`, parsed once when definitions load. */
1908
+ export type ParsedConfigV2Definition = {
1909
+ readonly definition: PostHogFeatureFlag
1910
+ readonly config: ConfigV2 | ConfigV2Unsupported
1911
+ }
1912
+
1913
+ /** The result of a config version 2 definition: the record a `/flags?v=4` response gives. */
1914
+ export type ConfigV2LocalResult = {
1915
+ /** The legacy rendering of the record, which the existing getters read. */
1916
+ readonly detail: FeatureFlagDetail
1917
+ readonly record: ParsedFlagRecord
1918
+ /** The value the legacy getters return: the variant, or whether the flag is enabled. */
1919
+ readonly value: FeatureFlagValue
1920
+ /** The decoded payload of a number or object value, or `null`. */
1921
+ readonly payload: JsonType | null
1922
+ }
1923
+
1924
+ /** Parses each config version 2 definition of a definitions list, by flag key. */
1925
+ export function parseConfigV2Definitions(
1926
+ flags: readonly PostHogFeatureFlag[]
1927
+ ): ReadonlyMap<string, ParsedConfigV2Definition> {
1928
+ const parsed = new Map<string, ParsedConfigV2Definition>()
1929
+ for (const flag of flags) {
1930
+ if (!isConfigVersion1(flag)) {
1931
+ parsed.set(flag.key, { definition: flag, config: parseConfigV2(flag.filters) })
1932
+ }
1933
+ }
1934
+ return parsed
1935
+ }
1936
+
1937
+ /** The parsed `filters` of a definition, read now if it was not parsed on load. */
1938
+ function configFor(
1939
+ flag: PostHogFeatureFlag,
1940
+ parsed: ReadonlyMap<string, ParsedConfigV2Definition>
1941
+ ): ConfigV2 | ConfigV2Unsupported {
1942
+ const entry = parsed.get(flag.key)
1943
+ return entry !== undefined && entry.definition === flag ? entry.config : parseConfigV2(flag.filters)
1944
+ }
1945
+
1946
+ /**
1947
+ * The `filters.version` of a definition. A definition that is not config version 1 is unsupported
1948
+ * unless this is 2, whether or not its flag is active: another config version can give `active` a
1949
+ * meaning this release does not know.
1950
+ */
1951
+ function configVersionOf(flag: PostHogFeatureFlag): unknown {
1952
+ const filters: unknown = flag.filters
1953
+ return isJsonObject(filters) ? filters.version : undefined
1954
+ }
1955
+
1956
+ /** The reason the definition alone leaves the flag unresolved, known on load. */
1957
+ export function configV2UnresolvedReason(
1958
+ flag: PostHogFeatureFlag,
1959
+ parsed: ReadonlyMap<string, ParsedConfigV2Definition>
1960
+ ): UnresolvedFlagReason | undefined {
1961
+ if (configVersionOf(flag) !== CONFIG_VERSION) {
1962
+ return 'unsupported_definition'
1963
+ }
1964
+ // An inactive config version 2 flag is disabled whatever its document holds.
1965
+ return flag.active && isConfigV2Unsupported(configFor(flag, parsed)) ? 'unsupported_definition' : undefined
1966
+ }
1967
+
1968
+ /**
1969
+ * Whether a config version 2 flag returns a number or an object, the only values with a payload:
1970
+ * the value itself, which the legacy getters render as `true`.
1971
+ */
1972
+ export function configV2HasPayloads(flag: PostHogFeatureFlag): boolean {
1973
+ const filters: unknown = flag.filters
1974
+ return isJsonObject(filters) && (filters.return_type === 'number' || filters.return_type === 'object')
1975
+ }
1976
+
1977
+ /**
1978
+ * Evaluates a config version 2 definition for one person.
1979
+ *
1980
+ * Returns the record a `/flags?v=4` response gives for the same result, so the client reads it and
1981
+ * sends its flag events as for a remote record. Throws `InconclusiveMatchError` with the
1982
+ * unresolved reason when the evaluator gives no value; the caller then falls back as for a
1983
+ * version 1 flag. A definition of another config version is unsupported, also when the flag is
1984
+ * inactive.
1985
+ *
1986
+ * The flags service evaluates these flags with the distinct ID only, so experience continuity and
1987
+ * device bucketing do not apply. The caller never knows that its properties are complete, and
1988
+ * dates without an offset are read in UTC, as version 1 local evaluation reads them.
1989
+ */
1990
+ export async function evaluateConfigV2Definition(
1991
+ flag: PostHogFeatureFlag,
1992
+ parsed: ReadonlyMap<string, ParsedConfigV2Definition>,
1993
+ context: { distinctId: string; properties: Record<string, unknown>; propertyMatchingVersion: number | undefined }
1994
+ ): Promise<ConfigV2LocalResult> {
1995
+ const version = configVersionOf(flag)
1996
+ if (version !== CONFIG_VERSION) {
1997
+ throw new InconclusiveMatchError(
1998
+ `Config version ${JSON.stringify(version)} is not supported`,
1999
+ 'unsupported_definition'
2000
+ )
2001
+ }
2002
+ let outcome: ConfigV2Outcome = await evaluateConfigV2(
2003
+ configFor(flag, parsed),
2004
+ {
2005
+ identifier: String(context.distinctId),
2006
+ properties: context.properties,
2007
+ propertiesComplete: false,
2008
+ explicitExactMatching: context.propertyMatchingVersion === 2,
2009
+ timeZone: 'UTC',
2010
+ },
2011
+ { active: Boolean(flag.active) }
2012
+ )
2013
+ if (outcome.outcome === 'evaluated') {
2014
+ const result = localResult(flag, outcome)
2015
+ if (!result.record.failed) {
2016
+ return result
2017
+ }
2018
+ outcome = { outcome: 'unsupported', kind: 'malformed', field: result.record.unreadableField ?? 'record' }
2019
+ }
2020
+ throw new InconclusiveMatchError(describe(outcome), reasonOf(outcome))
2021
+ }
2022
+
2023
+ /** Builds the `/flags?v=4` record of a result and reads it as the response reader does. */
2024
+ function localResult(flag: PostHogFeatureFlag, outcome: ConfigV2Evaluated): ConfigV2LocalResult {
2025
+ const definition = flag as PostHogFeatureFlag & { version?: unknown }
2026
+ const metadata: Record<string, unknown> = { config_version: CONFIG_VERSION, description: null }
2027
+ // A field the reader would reject is left out, so that it does not fail the whole record.
2028
+ if (Number.isInteger(definition.id)) {
2029
+ metadata.id = definition.id
2030
+ }
2031
+ if (Number.isInteger(definition.version)) {
2032
+ metadata.version = definition.version
2033
+ }
2034
+ if (typeof definition.has_experiment === 'boolean') {
2035
+ metadata.has_experiment = definition.has_experiment
2036
+ }
2037
+ if (outcome.ruleType !== undefined) {
2038
+ metadata.rule_type = outcome.ruleType
2039
+ metadata.rule_id = outcome.ruleId
2040
+ }
2041
+ if (outcome.variantKey !== undefined) {
2042
+ metadata.variant_key = outcome.variantKey
2043
+ }
2044
+ const raw = {
2045
+ key: flag.key,
2046
+ // An object value is the configuration's own object, so the record gets a copy.
2047
+ value: outcome.value === null ? null : JSON.parse(JSON.stringify(outcome.value)),
2048
+ reason: {
2049
+ code: outcome.reason,
2050
+ condition_index: outcome.ruleIndex ?? null,
2051
+ description: LOCAL_REASON_DESCRIPTION,
2052
+ },
2053
+ metadata,
2054
+ }
2055
+ const { body } = readFlagRecords({ flags: { [flag.key]: raw } }) as {
2056
+ body: { flags: Record<string, FeatureFlagDetail> }
2057
+ }
2058
+ const detail = body.flags[flag.key]
2059
+ const record = parsedFlagRecordOf(detail)
2060
+ const rendered = detail.metadata?.payload
2061
+ return {
2062
+ detail,
2063
+ record,
2064
+ value: detail.variant ?? detail.enabled,
2065
+ payload: rendered === undefined || rendered === null ? null : (JSON.parse(rendered) as JsonType),
2066
+ }
2067
+ }
2068
+
2069
+ /** The unresolved reason of an outcome without a value, as the contract maps it. */
2070
+ function reasonOf(outcome: ConfigV2Inconclusive | ConfigV2Unsupported | ConfigV2EvaluationError): UnresolvedFlagReason {
2071
+ if (outcome.outcome === 'inconclusive') {
2072
+ return outcome.reason
2073
+ }
2074
+ if (outcome.outcome === 'error' && outcome.kind === 'invalid_property') {
2075
+ // The person property is not in a form the rule can compare.
2076
+ return 'missing_context'
2077
+ }
2078
+ return 'unsupported_definition'
2079
+ }
2080
+
2081
+ function describe(outcome: ConfigV2Inconclusive | ConfigV2Unsupported | ConfigV2EvaluationError): string {
2082
+ if (outcome.outcome === 'unsupported') {
2083
+ return `The config version 2 document is ${outcome.kind} at '${outcome.field}'`
2084
+ }
2085
+ return outcome.detail
2086
+ }