@posthog/core 1.59.4 → 1.60.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.
@@ -48,14 +48,41 @@ const NULL_VALUES_ALLOWED_OPERATORS = [
48
48
  // oxlint-disable-next-line no-loss-of-precision
49
49
  const LONG_SCALE = 0xfffffffffffffff
50
50
 
51
+ /**
52
+ * Why local evaluation could not resolve a flag. `experience_continuity` and
53
+ * `unsupported_definition` come from the flag's definition, `missing_context` from the
54
+ * evaluation call, and `unresolved_dependency` from a flag the definition depends on.
55
+ */
56
+ export type UnresolvedFlagReason =
57
+ | 'experience_continuity'
58
+ | 'unsupported_definition'
59
+ | 'missing_context'
60
+ | 'unresolved_dependency'
61
+
51
62
  export class InconclusiveMatchError extends Error {
52
- constructor(message: string) {
63
+ readonly reason: UnresolvedFlagReason
64
+
65
+ constructor(message: string, reason: UnresolvedFlagReason = 'unsupported_definition') {
53
66
  super(message)
54
67
  this.name = this.constructor.name
68
+ this.reason = reason
55
69
  Object.setPrototypeOf(this, InconclusiveMatchError.prototype)
56
70
  }
57
71
  }
58
72
 
73
+ // Values read from the evaluation call rather than the flag definition: failing to use one
74
+ // is a missing-context cause, not an unsupported definition.
75
+ function readContextValue<T>(read: () => T): T {
76
+ try {
77
+ return read()
78
+ } catch (e) {
79
+ if (e instanceof InconclusiveMatchError) {
80
+ throw new InconclusiveMatchError(e.message, 'missing_context')
81
+ }
82
+ throw e
83
+ }
84
+ }
85
+
59
86
  function isTruthyOrFalsyPropertyValue(value: unknown): boolean {
60
87
  if (typeof value === 'boolean') return true
61
88
  if (typeof value === 'string') {
@@ -222,12 +249,110 @@ function exactMatchString(value: unknown): string {
222
249
  return serializeJsonValue(value)
223
250
  }
224
251
 
225
- function isValidRegex(regex: string): boolean {
252
+ // Both engines treat escaped spaces and ASCII punctuation as literals, except Rust's \< and \> word boundaries.
253
+ const LITERAL_ESCAPED_PUNCTUATION = /[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/
254
+
255
+ function getPortableRegexClasses(pattern: string): string[] | null {
256
+ const classes: string[] = []
257
+ let classStart = -1
258
+ let previousToken = ''
259
+ for (let index = 0; index < pattern.length; index++) {
260
+ const character = pattern[index]
261
+ if (character.charCodeAt(0) > 0x7f) return null
262
+ if (character === '\\') {
263
+ const escaped = pattern[++index]
264
+ if (escaped === undefined) break
265
+ if (escaped === 'x') {
266
+ if (!/^[\da-f]{2}$/i.test(pattern.slice(index + 1, index + 3))) return null
267
+ index += 2
268
+ } else if (!'dDsSwWbBfnrtv'.includes(escaped) && !LITERAL_ESCAPED_PUNCTUATION.test(escaped)) {
269
+ return null
270
+ }
271
+ // Word boundaries can exhaust the service's backtracking limit even for short ASCII values.
272
+ if (classStart === -1 && 'bB'.includes(escaped)) return null
273
+ previousToken = 'literal'
274
+ continue
275
+ }
276
+
277
+ if (character === '[') {
278
+ if (classStart !== -1) return null
279
+ classStart = index
280
+ } else if (character === ']' && classStart !== -1) {
281
+ const contentStart = classStart + (pattern[classStart + 1] === '^' ? 2 : 1)
282
+ if (index === contentStart) return null
283
+ classes.push(pattern.slice(classStart, index + 1))
284
+ classStart = -1
285
+ previousToken = 'literal'
286
+ continue
287
+ } else if (classStart !== -1) {
288
+ if (['&&', '--', '~~'].includes(pattern.slice(index, index + 2))) return null
289
+ continue
290
+ } else if (character === '(' && pattern[index + 1] === '?') {
291
+ if (pattern[index + 2] !== ':') return null
292
+ index += 2
293
+ } else if (character === '{') {
294
+ // Rust reads `{n}` with nothing before it as literal text. JavaScript rejects it.
295
+ // The flags service rejects repetition counts above 4,294,967,295. JavaScript accepts them.
296
+ const repetition = /^\{(\d+)(?:,(\d*))?\}/.exec(pattern.slice(index))
297
+ if (
298
+ !repetition ||
299
+ ['', '|', '('].includes(previousToken) ||
300
+ repetition.slice(1).some((count) => Number(count) > 0xffffffff)
301
+ ) {
302
+ return null
303
+ }
304
+ } else if ('*+?}'.includes(character) && (pattern[index + 1] === '+' || pattern[index + 1] === '{')) {
305
+ return null
306
+ }
307
+ // JavaScript rejects a repeated anchor such as `^?`. Rust accepts it.
308
+ // Rust rejects a repeated empty group such as `(?:)*`. JavaScript accepts it.
309
+ if ('*+?{'.includes(character) && ['^', '$', 'empty group'].includes(previousToken)) return null
310
+ previousToken = character === ')' && ['(', 'empty group'].includes(previousToken) ? 'empty group' : character
311
+ }
312
+ return classes
313
+ }
314
+
315
+ // Adapters must preserve regex uncertainty across variant rules without changing missing-context fallback.
316
+ function regexRequiresServerEvaluation(message: string): InconclusiveMatchError {
317
+ const error = new InconclusiveMatchError(message)
318
+ Object.defineProperty(error, Symbol.for('posthog.requiresServerRegexEvaluation'), { value: true })
319
+ return error
320
+ }
321
+
322
+ function matchFeatureFlagRegex(pattern: string, value: string): boolean | null {
323
+ if (pattern === '') return true
324
+
325
+ // Rust uses Unicode scalar semantics and additional syntax. Keep local matching to the shared ASCII subset.
326
+ const characterClasses = getPortableRegexClasses(pattern)
327
+ if (characterClasses === null) {
328
+ throw regexRequiresServerEvaluation('Regex syntax requires server evaluation')
329
+ }
330
+
331
+ let regex: RegExp
226
332
  try {
227
- new RegExp(regex)
228
- return true
333
+ regex = new RegExp(pattern)
334
+ } catch (error) {
335
+ if (error instanceof SyntaxError) return null
336
+ throw regexRequiresServerEvaluation('Regex compilation requires server evaluation')
337
+ }
338
+ for (const characterClass of characterClasses) {
339
+ try {
340
+ // Strict parsing rejects legacy JS ranges such as [\s-9], which the flags service does not accept.
341
+ new RegExp(characterClass, 'u')
342
+ } catch {
343
+ throw regexRequiresServerEvaluation('Regex character class syntax requires server evaluation')
344
+ }
345
+ }
346
+ for (let index = 0; index < value.length; index++) {
347
+ const character = value[index]
348
+ if (character.charCodeAt(0) > 0x7f || character === '\r') {
349
+ throw regexRequiresServerEvaluation('Regex matching for Unicode or carriage returns requires server evaluation')
350
+ }
351
+ }
352
+ try {
353
+ return regex.test(value)
229
354
  } catch {
230
- return false
355
+ throw regexRequiresServerEvaluation('Regex execution requires server evaluation')
231
356
  }
232
357
  }
233
358
 
@@ -360,10 +485,91 @@ export function relativeDateParseForFeatureFlagMatching(value: string): Date | n
360
485
  return parsedDt
361
486
  }
362
487
 
488
+ function parseDateFilter(value: FeatureFlagPropertyValue): Date {
489
+ if (typeof value === 'boolean') {
490
+ throw new InconclusiveMatchError('Date operations cannot be performed on boolean values')
491
+ }
492
+ return relativeDateParseForFeatureFlagMatching(String(value)) ?? convertToDateTime(value)
493
+ }
494
+
495
+ /**
496
+ * Throws an unsupported_definition error when local evaluation cannot use the filter, whatever
497
+ * the context holds: an unknown operator, or a filter value that the operator cannot parse.
498
+ */
499
+ export function assertFeatureFlagFilterSupported(
500
+ property: FeatureFlagProperty,
501
+ options: Pick<MatchFeatureFlagPropertyOptions, 'semverParsingPolicy'> = {}
502
+ ): void {
503
+ const value = property.value
504
+ const parsingPolicy = options.semverParsingPolicy ?? 'strict'
505
+ switch (property.operator || 'exact') {
506
+ case 'exact':
507
+ case 'is_not':
508
+ for (const item of Array.isArray(value) ? value : [value]) {
509
+ exactMatchString(item)
510
+ }
511
+ return
512
+ case 'is_set':
513
+ case 'is_not_set':
514
+ case 'icontains':
515
+ case 'not_icontains':
516
+ case 'starts_with':
517
+ case 'not_starts_with':
518
+ case 'ends_with':
519
+ case 'not_ends_with':
520
+ case 'regex':
521
+ case 'not_regex':
522
+ case 'gt':
523
+ case 'gte':
524
+ case 'lt':
525
+ case 'lte':
526
+ return
527
+ case 'is_date_after':
528
+ case 'is_date_before':
529
+ parseDateFilter(value)
530
+ return
531
+ case 'semver_eq':
532
+ case 'semver_neq':
533
+ case 'semver_gt':
534
+ case 'semver_gte':
535
+ case 'semver_lt':
536
+ case 'semver_lte':
537
+ parseFeatureFlagSemver(String(value), parsingPolicy)
538
+ return
539
+ case 'semver_tilde':
540
+ computeTildeBounds(String(value), parsingPolicy)
541
+ return
542
+ case 'semver_caret':
543
+ computeCaretBounds(String(value), parsingPolicy)
544
+ return
545
+ case 'semver_wildcard':
546
+ computeWildcardBounds(String(value), parsingPolicy)
547
+ return
548
+ default:
549
+ throw new InconclusiveMatchError(`Unknown operator: ${property.operator}`)
550
+ }
551
+ }
552
+
363
553
  export function matchFeatureFlagProperty(
364
554
  property: FeatureFlagProperty,
365
555
  propertyValues: Record<string, any>,
366
556
  options: MatchFeatureFlagPropertyOptions = {}
557
+ ): boolean {
558
+ try {
559
+ return matchPropertyValue(property, propertyValues, options)
560
+ } catch (e) {
561
+ // An unusable filter outranks missing context, so check the filter before blaming the context.
562
+ if (e instanceof InconclusiveMatchError && e.reason === 'missing_context') {
563
+ assertFeatureFlagFilterSupported(property, options)
564
+ }
565
+ throw e
566
+ }
567
+ }
568
+
569
+ function matchPropertyValue(
570
+ property: FeatureFlagProperty,
571
+ propertyValues: Record<string, any>,
572
+ options: MatchFeatureFlagPropertyOptions
367
573
  ): boolean {
368
574
  const key = property.key
369
575
  const value = property.value
@@ -372,7 +578,7 @@ export function matchFeatureFlagProperty(
372
578
 
373
579
  const hasProperty = Object.prototype.hasOwnProperty.call(propertyValues, key)
374
580
  if (!hasProperty) {
375
- throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`)
581
+ throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`, 'missing_context')
376
582
  } else if (operator === 'is_not_set') {
377
583
  return false
378
584
  } else if (operator === 'is_set') {
@@ -395,20 +601,21 @@ export function matchFeatureFlagProperty(
395
601
  (options.propertyMatchingVersion !== 2 && isTruthyOrFalsyPropertyValue(target)) ||
396
602
  (Array.isArray(target) && target.length === 0)
397
603
  ) {
398
- assertJsonRepresentable(actual)
604
+ readContextValue(() => assertJsonRepresentable(actual))
399
605
  return isTruthyPropertyValue(target) === isTruthyPropertyValue(actual)
400
606
  }
401
607
  // Neither integer nor integral-float spelling can equal a boolean-like filter. This
402
608
  // mismatch is conclusive without weakening the numeric ambiguity fallback below.
403
609
  if (options.propertyMatchingVersion === 2 && typeof actual === 'number' && isTruthyOrFalsyPropertyValue(target)) {
404
- assertJsonRepresentable(actual)
610
+ readContextValue(() => assertJsonRepresentable(actual))
405
611
  return false
406
612
  }
407
613
  if (Array.isArray(target)) {
408
- const actualString = exactMatchString(actual).toLowerCase()
614
+ const actualString = readContextValue(() => exactMatchString(actual)).toLowerCase()
409
615
  return target.some((item) => exactMatchString(item).toLowerCase() === actualString)
410
616
  }
411
- return exactMatchString(target).toLowerCase() === exactMatchString(actual).toLowerCase()
617
+ const targetString = exactMatchString(target).toLowerCase()
618
+ return targetString === readContextValue(() => exactMatchString(actual)).toLowerCase()
412
619
  }
413
620
 
414
621
  const compare = (lhs: any, rhs: any, comparisonOperator: string): boolean => {
@@ -419,6 +626,20 @@ export function matchFeatureFlagProperty(
419
626
  throw new Error(`Invalid operator: ${comparisonOperator}`)
420
627
  }
421
628
 
629
+ // Lazy, because only the semver operators may parse either side.
630
+ const parseContextSemver = (): SemverTuple =>
631
+ readContextValue(() => parseFeatureFlagSemver(String(overrideValue), parsingPolicy))
632
+ // Parses the filter before the context, so a bad filter reports unsupported_definition even
633
+ // when the context value is bad too.
634
+ const compareContextSemverToFilter = (): number => {
635
+ const filterParsed = parseFeatureFlagSemver(String(value), parsingPolicy)
636
+ return compareSemverTuples(parseContextSemver(), filterParsed)
637
+ }
638
+ const isContextSemverWithin = ({ lower, upper }: { lower: SemverTuple; upper: SemverTuple }): boolean => {
639
+ const overrideParsed = parseContextSemver()
640
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0
641
+ }
642
+
422
643
  switch (operator) {
423
644
  case 'exact':
424
645
  return computeExactMatch(value, overrideValue)
@@ -439,9 +660,11 @@ export function matchFeatureFlagProperty(
439
660
  case 'not_ends_with':
440
661
  return !asciiLowercase(overrideValue).endsWith(asciiLowercase(value))
441
662
  case 'regex':
442
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null
443
- case 'not_regex':
444
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null
663
+ case 'not_regex': {
664
+ const matched = matchFeatureFlagRegex(String(value), String(overrideValue))
665
+ if (matched === null) return false
666
+ return operator === 'regex' ? matched : !matched
667
+ }
445
668
  case 'gt':
446
669
  case 'gte':
447
670
  case 'lt':
@@ -460,71 +683,28 @@ export function matchFeatureFlagProperty(
460
683
  }
461
684
  case 'is_date_after':
462
685
  case 'is_date_before': {
463
- if (typeof value === 'boolean') {
464
- throw new InconclusiveMatchError('Date operations cannot be performed on boolean values')
465
- }
466
- let parsedDate = relativeDateParseForFeatureFlagMatching(String(value))
467
- if (parsedDate == null) parsedDate = convertToDateTime(value)
468
- const overrideDate = convertToDateTime(overrideValue)
686
+ const parsedDate = parseDateFilter(value)
687
+ const overrideDate = readContextValue(() => convertToDateTime(overrideValue))
469
688
  return operator === 'is_date_before' ? overrideDate < parsedDate : overrideDate > parsedDate
470
689
  }
471
690
  case 'semver_eq':
472
- return (
473
- compareSemverTuples(
474
- parseFeatureFlagSemver(String(overrideValue), parsingPolicy),
475
- parseFeatureFlagSemver(String(value), parsingPolicy)
476
- ) === 0
477
- )
691
+ return compareContextSemverToFilter() === 0
478
692
  case 'semver_neq':
479
- return (
480
- compareSemverTuples(
481
- parseFeatureFlagSemver(String(overrideValue), parsingPolicy),
482
- parseFeatureFlagSemver(String(value), parsingPolicy)
483
- ) !== 0
484
- )
693
+ return compareContextSemverToFilter() !== 0
485
694
  case 'semver_gt':
486
- return (
487
- compareSemverTuples(
488
- parseFeatureFlagSemver(String(overrideValue), parsingPolicy),
489
- parseFeatureFlagSemver(String(value), parsingPolicy)
490
- ) > 0
491
- )
695
+ return compareContextSemverToFilter() > 0
492
696
  case 'semver_gte':
493
- return (
494
- compareSemverTuples(
495
- parseFeatureFlagSemver(String(overrideValue), parsingPolicy),
496
- parseFeatureFlagSemver(String(value), parsingPolicy)
497
- ) >= 0
498
- )
697
+ return compareContextSemverToFilter() >= 0
499
698
  case 'semver_lt':
500
- return (
501
- compareSemverTuples(
502
- parseFeatureFlagSemver(String(overrideValue), parsingPolicy),
503
- parseFeatureFlagSemver(String(value), parsingPolicy)
504
- ) < 0
505
- )
699
+ return compareContextSemverToFilter() < 0
506
700
  case 'semver_lte':
507
- return (
508
- compareSemverTuples(
509
- parseFeatureFlagSemver(String(overrideValue), parsingPolicy),
510
- parseFeatureFlagSemver(String(value), parsingPolicy)
511
- ) <= 0
512
- )
513
- case 'semver_tilde': {
514
- const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy)
515
- const { lower, upper } = computeTildeBounds(String(value), parsingPolicy)
516
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0
517
- }
518
- case 'semver_caret': {
519
- const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy)
520
- const { lower, upper } = computeCaretBounds(String(value), parsingPolicy)
521
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0
522
- }
523
- case 'semver_wildcard': {
524
- const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy)
525
- const { lower, upper } = computeWildcardBounds(String(value), parsingPolicy)
526
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0
527
- }
701
+ return compareContextSemverToFilter() <= 0
702
+ case 'semver_tilde':
703
+ return isContextSemverWithin(computeTildeBounds(String(value), parsingPolicy))
704
+ case 'semver_caret':
705
+ return isContextSemverWithin(computeCaretBounds(String(value), parsingPolicy))
706
+ case 'semver_wildcard':
707
+ return isContextSemverWithin(computeWildcardBounds(String(value), parsingPolicy))
528
708
  default:
529
709
  throw new InconclusiveMatchError(`Unknown operator: ${operator}`)
530
710
  }
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ export {
8
8
  minimizeFlagCalledEventProperties,
9
9
  } from './featureFlagUtils'
10
10
  export {
11
+ assertFeatureFlagFilterSupported,
11
12
  getFeatureFlagHash,
12
13
  getFeatureFlagVariant,
13
14
  getFeatureFlagVariantLookupTable,
@@ -26,6 +27,7 @@ export type {
26
27
  FeatureFlagVariant,
27
28
  FeatureFlagVariantLookupEntry,
28
29
  MatchFeatureFlagPropertyOptions,
30
+ UnresolvedFlagReason,
29
31
  } from './featureFlagLocalEvaluation'
30
32
  export {
31
33
  gzipCompress,
package/src/types.ts CHANGED
@@ -556,6 +556,7 @@ export type FetchLike = (url: string, options: PostHogFetchOptions) => Promise<P
556
556
  * Error values:
557
557
  * ERRORS_WHILE_COMPUTING: Server returned errorsWhileComputingFlags=true
558
558
  * FLAG_MISSING: Requested flag not in API response
559
+ * LOCAL_EVALUATION_INCONCLUSIVE: Flag has a loaded local definition but local evaluation could not resolve it
559
560
  * QUOTA_LIMITED: Rate/quota limit exceeded
560
561
  * TIMEOUT: Request timed out
561
562
  * CONNECTION_ERROR: Network connection failed
@@ -564,6 +565,7 @@ export type FetchLike = (url: string, options: PostHogFetchOptions) => Promise<P
564
565
  export const FeatureFlagError = {
565
566
  ERRORS_WHILE_COMPUTING: 'errors_while_computing_flags',
566
567
  FLAG_MISSING: 'flag_missing',
568
+ LOCAL_EVALUATION_INCONCLUSIVE: 'local_evaluation_inconclusive',
567
569
  QUOTA_LIMITED: 'quota_limited',
568
570
  TIMEOUT: 'timeout',
569
571
  CONNECTION_ERROR: 'connection_error',