@posthog/core 1.70.0 → 1.71.0

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 (117) hide show
  1. package/capture-v1/package.json +6 -0
  2. package/dist/capture-v1/compression.d.ts +18 -0
  3. package/dist/capture-v1/compression.d.ts.map +1 -0
  4. package/dist/capture-v1/compression.js +70 -0
  5. package/dist/capture-v1/compression.mjs +26 -0
  6. package/dist/capture-v1/errors.d.ts +48 -0
  7. package/dist/capture-v1/errors.d.ts.map +1 -0
  8. package/dist/capture-v1/errors.js +82 -0
  9. package/dist/capture-v1/errors.mjs +38 -0
  10. package/dist/capture-v1/index.d.ts +15 -0
  11. package/dist/capture-v1/index.d.ts.map +1 -0
  12. package/dist/capture-v1/index.js +88 -0
  13. package/dist/capture-v1/index.mjs +7 -0
  14. package/dist/capture-v1/sender.d.ts +150 -0
  15. package/dist/capture-v1/sender.d.ts.map +1 -0
  16. package/dist/capture-v1/sender.js +554 -0
  17. package/dist/capture-v1/sender.mjs +507 -0
  18. package/dist/capture-v1/serialize.d.ts +30 -0
  19. package/dist/capture-v1/serialize.d.ts.map +1 -0
  20. package/dist/capture-v1/serialize.js +106 -0
  21. package/dist/capture-v1/serialize.mjs +59 -0
  22. package/dist/capture-v1/transform.d.ts +19 -0
  23. package/dist/capture-v1/transform.d.ts.map +1 -0
  24. package/dist/capture-v1/transform.js +118 -0
  25. package/dist/capture-v1/transform.mjs +77 -0
  26. package/dist/capture-v1/types.d.ts +52 -0
  27. package/dist/capture-v1/types.d.ts.map +1 -0
  28. package/dist/capture-v1/types.js +44 -0
  29. package/dist/capture-v1/types.mjs +3 -0
  30. package/dist/capture-v1/uuid.d.ts +9 -0
  31. package/dist/capture-v1/uuid.d.ts.map +1 -0
  32. package/dist/capture-v1/uuid.js +75 -0
  33. package/dist/capture-v1/uuid.mjs +34 -0
  34. package/dist/featureFlagUtils.d.ts +7 -5
  35. package/dist/featureFlagUtils.d.ts.map +1 -1
  36. package/dist/featureFlagUtils.js +17 -11
  37. package/dist/featureFlagUtils.mjs +14 -11
  38. package/dist/index.d.ts +1 -1
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +27 -16
  41. package/dist/index.mjs +1 -1
  42. package/dist/posthog-core-stateless.d.ts +40 -3
  43. package/dist/posthog-core-stateless.d.ts.map +1 -1
  44. package/dist/posthog-core-stateless.js +87 -19
  45. package/dist/posthog-core-stateless.mjs +87 -19
  46. package/dist/posthog-core.d.ts +138 -53
  47. package/dist/posthog-core.d.ts.map +1 -1
  48. package/dist/posthog-core.js +341 -115
  49. package/dist/posthog-core.mjs +338 -115
  50. package/dist/types.d.ts +24 -1
  51. package/dist/types.d.ts.map +1 -1
  52. package/dist/utils/index.d.ts +1 -1
  53. package/dist/utils/index.d.ts.map +1 -1
  54. package/dist/utils/index.js +25 -12
  55. package/dist/utils/index.mjs +1 -1
  56. package/dist/utils/json-utils.d.ts +11 -1
  57. package/dist/utils/json-utils.d.ts.map +1 -1
  58. package/dist/utils/json-utils.js +50 -2
  59. package/dist/utils/json-utils.mjs +46 -1
  60. package/package.json +12 -2
  61. package/src/capture-v1/compression.ts +50 -0
  62. package/src/capture-v1/errors.ts +91 -0
  63. package/src/capture-v1/index.ts +34 -0
  64. package/src/capture-v1/sender.ts +779 -0
  65. package/src/capture-v1/serialize.ts +113 -0
  66. package/src/capture-v1/transform.ts +135 -0
  67. package/src/capture-v1/types.ts +59 -0
  68. package/src/capture-v1/uuid.ts +53 -0
  69. package/src/featureFlagUtils.ts +22 -10
  70. package/src/index.ts +1 -0
  71. package/src/posthog-core-stateless.ts +166 -30
  72. package/src/posthog-core.ts +615 -178
  73. package/src/types.ts +21 -1
  74. package/src/utils/index.ts +1 -1
  75. package/src/utils/json-utils.ts +64 -1
  76. package/src/error-tracking/chunk-ids.spec.ts +0 -77
  77. package/src/error-tracking/coercers/error-event-coercer.spec.ts +0 -142
  78. package/src/error-tracking/coercers/promise-rejection-event.spec.ts +0 -77
  79. package/src/error-tracking/coercers/string-coercer.spec.ts +0 -26
  80. package/src/error-tracking/error-properties-builder.aggregate-errors.spec.ts +0 -412
  81. package/src/error-tracking/error-properties-builder.coerce.spec.ts +0 -337
  82. package/src/error-tracking/error-properties-builder.metadata.spec.ts +0 -318
  83. package/src/error-tracking/error-properties-builder.parse.spec.ts +0 -37
  84. package/src/error-tracking/exception-steps.spec.ts +0 -115
  85. package/src/error-tracking/parsers/base.spec.ts +0 -156
  86. package/src/error-tracking/parsers/index.spec.ts +0 -270
  87. package/src/error-tracking/parsers/node.spec.ts +0 -34
  88. package/src/error-tracking/release.spec.ts +0 -34
  89. package/src/logs/index.spec.ts +0 -2421
  90. package/src/logs/logs-utils.spec.ts +0 -266
  91. package/src/metrics/index.spec.ts +0 -1249
  92. package/src/surveys/activation.spec.ts +0 -61
  93. package/src/surveys/events.spec.ts +0 -183
  94. package/src/surveys/keys.spec.ts +0 -29
  95. package/src/surveys/property-matching.spec.ts +0 -539
  96. package/src/surveys/shuffling.spec.ts +0 -51
  97. package/src/surveys/translations.spec.ts +0 -274
  98. package/src/surveys/validation.spec.ts +0 -168
  99. package/src/traces/config.spec.ts +0 -271
  100. package/src/traces/ids.spec.ts +0 -115
  101. package/src/traces/index.spec.ts +0 -3287
  102. package/src/traces/live-spans.spec.ts +0 -69
  103. package/src/traces/otlp.spec.ts +0 -368
  104. package/src/traces/span.spec.ts +0 -1137
  105. package/src/traces/traceparent.spec.ts +0 -184
  106. package/src/utils/bot-detection.spec.ts +0 -107
  107. package/src/utils/bucketed-rate-limiter.spec.ts +0 -327
  108. package/src/utils/json-utils.spec.ts +0 -115
  109. package/src/utils/named-error.spec.ts +0 -36
  110. package/src/utils/number-utils.spec.ts +0 -212
  111. package/src/utils/otlp-any-value.spec.ts +0 -376
  112. package/src/utils/otlp-resource.spec.ts +0 -171
  113. package/src/utils/promise-queue.spec.ts +0 -55
  114. package/src/utils/string-utils.spec.ts +0 -158
  115. package/src/utils/type-utils.spec.ts +0 -38
  116. package/src/utils/webview-app-utils.spec.ts +0 -118
  117. package/src/vendor/uuidv7.spec.ts +0 -26
@@ -0,0 +1,113 @@
1
+ import type { PostHogEventProperties } from '../types'
2
+ import { safeJsonStringify } from '../utils/string-utils'
3
+
4
+ import { buildV1Event } from './transform'
5
+
6
+ const encoder = typeof TextEncoder === 'undefined' ? undefined : new TextEncoder()
7
+
8
+ // TextEncoder where the runtime has it, as it's faster on large events. It is missing on Hermes before
9
+ // React Native 0.74 and on JSC, so the bytes are counted by hand there. A lone surrogate counts 3 bytes,
10
+ // the U+FFFD it becomes when encoded.
11
+ /** UTF-8 size of `value`. */
12
+ export function utf8Length(value: string): number {
13
+ return encoder ? encoder.encode(value).length : countUtf8Bytes(value)
14
+ }
15
+
16
+ function countUtf8Bytes(value: string): number {
17
+ let bytes = 0
18
+ for (let index = 0; index < value.length; index++) {
19
+ const code = value.charCodeAt(index)
20
+ if (code < 0x80) {
21
+ bytes += 1
22
+ } else if (code < 0x800) {
23
+ bytes += 2
24
+ } else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length) {
25
+ const next = value.charCodeAt(index + 1)
26
+ if (next >= 0xdc00 && next <= 0xdfff) {
27
+ bytes += 4
28
+ index++
29
+ } else {
30
+ bytes += 3
31
+ }
32
+ } else {
33
+ bytes += 3
34
+ }
35
+ }
36
+ return bytes
37
+ }
38
+
39
+ // `buildV1Event` puts `properties` last, so the event JSON is the rest of the event with this key and the properties appended.
40
+ const PROPERTIES_KEY = ',"properties":'
41
+ const PROPERTIES_KEY_BYTES = utf8Length(PROPERTIES_KEY)
42
+
43
+ /** One wire event, serialized once and reused verbatim in every request body that carries it. */
44
+ export interface SerializedV1Event {
45
+ uuid: string
46
+ json: string
47
+ /** UTF-8 size of `json`. */
48
+ bytes: number
49
+ /** UTF-8 size of the serialized `properties` object alone, which is what the AI endpoint limits. */
50
+ propertiesBytes: number
51
+ }
52
+
53
+ // No lookbehind: JavaScriptCore before iOS 16.4, and the jsc-android build React Native ships, can't parse it.
54
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/
55
+ // JSON.stringify writes a lone surrogate as a `\udXXX` escape (a valid pair stays raw), which capture rejects for the whole
56
+ // request. Escaped backslashes are matched too and kept, so literal "\\udXXX" text is left alone.
57
+ const LONE_SURROGATE_ESCAPE = /\\\\|\\u[dD][89a-fA-F][0-9a-fA-F]{2}/g
58
+
59
+ /**
60
+ * Why capture would reject this event, or undefined when it can be sent. A name must be a non-empty string, the
61
+ * distinct id a string, and the name and ids well-formed Unicode: a broken id is never repaired, because two broken ids
62
+ * could collapse into one.
63
+ */
64
+ export function wireProblem(message: PostHogEventProperties): string | undefined {
65
+ const { event, distinct_id: distinctId, properties } = message
66
+ if (typeof event !== 'string' || event === '') {
67
+ return 'event name is missing, empty or not a string'
68
+ }
69
+ // Caller ids are already strings, so only a beforeSend hook can leave a non-string here.
70
+ if (typeof distinctId !== 'string') {
71
+ return 'distinct id is missing or not a string'
72
+ }
73
+ const props = (properties ?? {}) as Record<string, unknown>
74
+ const ids = [event, distinctId, props.$session_id, props.$window_id]
75
+ if (ids.some((value) => typeof value === 'string' && LONE_SURROGATE.test(value))) {
76
+ return 'event name or id is not well-formed Unicode'
77
+ }
78
+ return undefined
79
+ }
80
+
81
+ function repairLoneSurrogates(json: string): string {
82
+ return json.includes('\\ud') || json.includes('\\uD')
83
+ ? json.replace(LONE_SURROGATE_ESCAPE, (match) => (match.length === 2 ? match : '\\ufffd'))
84
+ : json
85
+ }
86
+
87
+ export function serializeV1Event(message: PostHogEventProperties): SerializedV1Event {
88
+ const { properties, ...rest } = buildV1Event(message)
89
+ // Property and option strings are repaired to U+FFFD rather than dropping the event. The name and ids
90
+ // in `rest` are well-formed already, because callers send only events `wireProblem` accepts.
91
+ const restJson = repairLoneSurrogates(safeJsonStringify(rest))
92
+ const propertiesJson = repairLoneSurrogates(safeJsonStringify(properties))
93
+ const propertiesBytes = utf8Length(propertiesJson)
94
+ return {
95
+ uuid: rest.uuid,
96
+ json: `${restJson.slice(0, -1)}${PROPERTIES_KEY}${propertiesJson}}`,
97
+ // The closing brace moves from the end of `restJson` to the end of the event, so it is counted once.
98
+ bytes: utf8Length(restJson) + PROPERTIES_KEY_BYTES + propertiesBytes,
99
+ propertiesBytes,
100
+ }
101
+ }
102
+
103
+ /**
104
+ * The Capture V1 batch envelope, built from already-serialized events. Unlike v0 there is no
105
+ * `api_key` (Bearer auth) and no `sent_at`. `historical_migration` is omitted when false.
106
+ */
107
+ export function buildV1Body(
108
+ events: readonly { json: string }[],
109
+ { createdAt, historicalMigration }: { createdAt: string; historicalMigration: boolean }
110
+ ): string {
111
+ const migration = historicalMigration ? ',"historical_migration":true' : ''
112
+ return `{"created_at":${JSON.stringify(createdAt)}${migration},"batch":[${events.map((event) => event.json).join(',')}]}`
113
+ }
@@ -0,0 +1,135 @@
1
+ import { EVENT_OPTION_LEGACY_PROPERTIES } from '../event-options'
2
+ import type { JsonType, PostHogEventProperties } from '../types'
3
+
4
+ import type { V1Event } from './types'
5
+
6
+ /** Property -> top-level string field; any value that is not a string is dropped. */
7
+ const TOPLEVEL_SENTINELS: ReadonlyArray<{ property: string; field: 'session_id' | 'window_id' }> = [
8
+ { property: '$session_id', field: 'session_id' },
9
+ { property: '$window_id', field: 'window_id' },
10
+ ]
11
+
12
+ function isRecord(value: unknown): value is PostHogEventProperties {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
14
+ }
15
+
16
+ function jsonTypeName(value: JsonType): string {
17
+ return Array.isArray(value) ? 'array' : typeof value
18
+ }
19
+
20
+ /**
21
+ * A copy of the caller's per-event options, or undefined when there are none. Any value that
22
+ * is not an object is reported and ignored, so the event is still sent.
23
+ */
24
+ export function readEventOptions(value: unknown): Record<string, JsonType> | undefined {
25
+ if (value === undefined || value === null) {
26
+ return undefined
27
+ }
28
+ if (isRecord(value)) {
29
+ return { ...value }
30
+ }
31
+ // console.error, not the client logger: the logger only prints in debug mode, and the event loses its options.
32
+ console.error(
33
+ `[PostHog] options must be an object, got ${jsonTypeName(value as JsonType)}; sending the event without its options`
34
+ )
35
+ return undefined
36
+ }
37
+
38
+ /**
39
+ * Normalize an event timestamp to an RFC 3339 string. The queued message
40
+ * carries either an ISO string (from `currentISOTime()`) or a `Date` (when the
41
+ * caller passed one); numbers are treated as epoch milliseconds. Invalid values
42
+ * fall back to "now" so a bad timestamp never rejects the whole batch.
43
+ */
44
+ function replaceUnparseableTimestamp(): string {
45
+ // console.warn, not the client logger: the logger only prints in debug mode, and the event's time changes. Never logs the value.
46
+ console.warn('[PostHog] replacing an unparseable event timestamp with the current time')
47
+ return new Date().toISOString()
48
+ }
49
+
50
+ function toRfc3339(timestamp: unknown): string {
51
+ if (typeof timestamp === 'string') {
52
+ const asDate = new Date(timestamp)
53
+ if (Number.isNaN(asDate.getTime())) {
54
+ return replaceUnparseableTimestamp()
55
+ }
56
+
57
+ const normalized = asDate.toISOString()
58
+ const fractionalSeconds = timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]
59
+ return fractionalSeconds && fractionalSeconds.length > 3
60
+ ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`)
61
+ : normalized
62
+ }
63
+ if (timestamp instanceof Date) {
64
+ return Number.isNaN(timestamp.getTime()) ? replaceUnparseableTimestamp() : timestamp.toISOString()
65
+ }
66
+ const asDate = timestamp == null ? new Date() : new Date(timestamp as string | number)
67
+ return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString()
68
+ }
69
+
70
+ /**
71
+ * Relocate a top-level `$set`/`$set_once` value into `properties`. v1 has no
72
+ * top-level form; the server reads them from inside `properties`. An existing
73
+ * `properties` value wins on collision.
74
+ */
75
+ function relocateInto(properties: PostHogEventProperties, key: string, value: JsonType | undefined): void {
76
+ if (value !== undefined && !(key in properties)) {
77
+ properties[key] = value
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Transform one already-normalized queued message into a Capture V1 wire event.
83
+ *
84
+ * The input message is never mutated (events may be retried or handed to
85
+ * callbacks): fresh `options` and `properties` maps are built. Option values are
86
+ * sent unchanged; capture reads them. Each legacy option property is removed from
87
+ * `properties` and fills its option when the caller left that option missing or
88
+ * `null`. `$session_id`/`$window_id` move to the top-level `session_id`/`window_id`
89
+ * fields; top-level `$set`/`$set_once` are relocated into `properties`.
90
+ */
91
+ export function buildV1Event(message: PostHogEventProperties): V1Event {
92
+ const sourceProperties = isRecord(message.properties) ? message.properties : {}
93
+ const properties: PostHogEventProperties = { ...sourceProperties }
94
+
95
+ const options = readEventOptions(message.options) ?? {}
96
+ for (const [optionKey, property] of Object.entries(EVENT_OPTION_LEGACY_PROPERTIES)) {
97
+ if (!(property in properties)) {
98
+ continue
99
+ }
100
+ const legacyValue = properties[property]
101
+ delete properties[property]
102
+ const option = options[optionKey]
103
+ if ((option === undefined || option === null) && legacyValue !== undefined) {
104
+ options[optionKey] = legacyValue
105
+ }
106
+ }
107
+
108
+ const topLevel: { session_id?: string; window_id?: string } = {}
109
+ for (const { property, field } of TOPLEVEL_SENTINELS) {
110
+ if (!(property in properties)) {
111
+ continue
112
+ }
113
+ const value = properties[property]
114
+ delete properties[property]
115
+ if (typeof value === 'string') {
116
+ topLevel[field] = value
117
+ } else if (value !== undefined && value !== null) {
118
+ // console.warn, not the client logger: the logger only prints in debug mode, and the event loses this id.
119
+ console.warn(`[PostHog] dropping ${property}: a ${jsonTypeName(value)} value is not a string`)
120
+ }
121
+ }
122
+
123
+ relocateInto(properties, '$set', message.$set)
124
+ relocateInto(properties, '$set_once', message.$set_once)
125
+
126
+ return {
127
+ event: String(message.event ?? ''),
128
+ uuid: String(message.uuid ?? ''),
129
+ distinct_id: String(message.distinct_id ?? ''),
130
+ timestamp: toRfc3339(message.timestamp),
131
+ ...topLevel,
132
+ options,
133
+ properties,
134
+ }
135
+ }
@@ -0,0 +1,59 @@
1
+ import type { JsonType, PostHogEventProperties } from '../types'
2
+
3
+ /** Capture lane for analytics events. */
4
+ export const ANALYTICS_CAPTURE_ENDPOINT = '/i/v1/analytics/events'
5
+
6
+ /** Capture lane for events sent through `captureAi`. */
7
+ export const AI_CAPTURE_ENDPOINT = '/i/v1/ai/events'
8
+
9
+ export type CaptureEndpoint = typeof ANALYTICS_CAPTURE_ENDPOINT | typeof AI_CAPTURE_ENDPOINT
10
+
11
+ /**
12
+ * The `options` object on a Capture V1 event: the caller's options plus any legacy
13
+ * `$`-prefixed option properties lifted by the transform. Values are sent unchanged.
14
+ * Always serialized as an object (`{}` when empty), never `null`.
15
+ */
16
+ export interface V1EventOptions {
17
+ /** Whether to process this event in cookieless mode. */
18
+ cookieless_mode?: boolean
19
+ /** Whether to disable server-side timestamp skew correction for this event. */
20
+ disable_skew_correction?: boolean
21
+ /** Whether to create or update a person profile for this event. */
22
+ process_person_profile?: boolean
23
+ /** Additional capture options, sent to capture v1 unchanged. */
24
+ [key: string]: JsonType | undefined
25
+ }
26
+
27
+ /**
28
+ * A single event in a Capture V1 batch.
29
+ * `session_id`/`window_id` are promoted from the `$session_id`/`$window_id`
30
+ * sentinels; there is no top-level `api_key`.
31
+ */
32
+ export interface V1Event {
33
+ event: string
34
+ uuid: string
35
+ distinct_id: string
36
+ timestamp: string
37
+ session_id?: string
38
+ window_id?: string
39
+ options: V1EventOptions
40
+ properties: PostHogEventProperties
41
+ }
42
+
43
+ /**
44
+ * Per-event result codes in a v1 2xx response body. Unknown strings are
45
+ * tolerated as terminal success for forward compatibility.
46
+ */
47
+ export type V1ResultCode = 'ok' | 'warning' | 'drop' | 'retry'
48
+
49
+ export interface V1EventResult {
50
+ result: V1ResultCode | string
51
+ details?: string | null
52
+ /** How many later copies of this uuid in the request the server dropped as duplicates. */
53
+ duplicates_dropped?: number
54
+ }
55
+
56
+ /** Shape of a v1 2xx response body: a per-uuid map of results. */
57
+ export interface V1BatchResponse {
58
+ results: Record<string, V1EventResult>
59
+ }
@@ -0,0 +1,53 @@
1
+ import { V7Generator } from '../vendor/uuidv7'
2
+
3
+ const HYPHENATED = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
4
+ const HEX_32 = /^[0-9a-f]{32}$/i
5
+ const URN_PREFIX = 'urn:uuid:'
6
+
7
+ /**
8
+ * The lowercase, hyphenated form of an RFC 4122 uuid string, or undefined for anything else.
9
+ * Accepts 32 hex digits, the hyphenated form, the hyphenated form in braces, and the
10
+ * `urn:uuid:` form, in any case.
11
+ */
12
+ export function canonicalizeUuid(value: string): string | undefined {
13
+ let hyphenated = value
14
+ if (value.length === 38 && value.startsWith('{') && value.endsWith('}')) {
15
+ hyphenated = value.slice(1, -1)
16
+ } else if (value.length === 45 && value.slice(0, URN_PREFIX.length).toLowerCase() === URN_PREFIX) {
17
+ hyphenated = value.slice(URN_PREFIX.length)
18
+ } else if (HEX_32.test(value)) {
19
+ hyphenated = `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`
20
+ }
21
+ return HYPHENATED.test(hyphenated) ? hyphenated.toLowerCase() : undefined
22
+ }
23
+
24
+ type CryptoLike = { getRandomValues(array: Uint32Array): Uint32Array }
25
+
26
+ /** 32-bit words from the platform's cryptographic source, filled eight at a time to keep the per-uuid cost low. */
27
+ class CryptoRandom {
28
+ private readonly words = new Uint32Array(8)
29
+ private cursor = this.words.length
30
+
31
+ constructor(private readonly crypto: CryptoLike) {}
32
+
33
+ nextUint32(): number {
34
+ if (this.cursor >= this.words.length) {
35
+ this.crypto.getRandomValues(this.words)
36
+ this.cursor = 0
37
+ }
38
+ return this.words[this.cursor++]
39
+ }
40
+ }
41
+
42
+ function cryptoRandom(): CryptoRandom | undefined {
43
+ const crypto = (globalThis as { crypto?: Partial<CryptoLike> }).crypto
44
+ return typeof crypto?.getRandomValues === 'function' ? new CryptoRandom(crypto as CryptoLike) : undefined
45
+ }
46
+
47
+ // Without a crypto source (none in supported Node and edge runtimes), the core generator's Math.random source is used.
48
+ const generator = new V7Generator(cryptoRandom())
49
+
50
+ /** A v7 uuid for an event or a personless distinct id, with random bits from `crypto.getRandomValues`. */
51
+ export function eventUuidv7(): string {
52
+ return generator.generate().toString()
53
+ }
@@ -14,12 +14,13 @@ import {
14
14
  export const normalizeFlagsResponse = (
15
15
  flagsResponse:
16
16
  | PartialWithRequired<PostHogV2FlagsResponse, 'flags'>
17
- | PartialWithRequired<PostHogV1FlagsResponse, 'featureFlags' | 'featureFlagPayloads'>
17
+ | PartialWithRequired<PostHogV1FlagsResponse, 'featureFlags' | 'featureFlagPayloads'>,
18
+ decodePayload: (payload: any) => any = parsePayload
18
19
  ): PostHogFeatureFlagsResponse => {
19
20
  if ('flags' in flagsResponse) {
20
21
  // Convert v2 format to v1 format
21
22
  const featureFlags = getFlagValuesFromFlags(flagsResponse.flags)
22
- const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags)
23
+ const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags, decodePayload)
23
24
 
24
25
  return {
25
26
  ...flagsResponse,
@@ -30,7 +31,7 @@ export const normalizeFlagsResponse = (
30
31
  // Convert v1 format to v2 format
31
32
  const featureFlags = flagsResponse.featureFlags ?? {}
32
33
  const featureFlagPayloads = Object.fromEntries(
33
- Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [k, parsePayload(v)])
34
+ Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [k, decodePayload(v)])
34
35
  )
35
36
 
36
37
  const flags = Object.fromEntries(
@@ -87,7 +88,8 @@ export const getFlagValuesFromFlags = (flags: PostHogFlagsResponse['flags']): Po
87
88
  * @returns The payloads
88
89
  */
89
90
  export const getPayloadsFromFlags = (
90
- flags: PostHogFlagsResponse['flags']
91
+ flags: PostHogFlagsResponse['flags'],
92
+ decodePayload: (payload: any) => any = parsePayload
91
93
  ): PostHogFlagsResponse['featureFlagPayloads'] => {
92
94
  const safeFlags = flags ?? {}
93
95
  return Object.fromEntries(
@@ -98,7 +100,7 @@ export const getPayloadsFromFlags = (
98
100
  })
99
101
  .map((flag) => {
100
102
  const payload = safeFlags[flag].metadata?.payload as string
101
- return [flag, payload ? parsePayload(payload) : undefined]
103
+ return [flag, payload ? decodePayload(payload) : undefined]
102
104
  })
103
105
  )
104
106
  }
@@ -131,7 +133,8 @@ export const parsePayload = (response: any): any => {
131
133
  */
132
134
  export const createFlagsResponseFromFlagsAndPayloads = (
133
135
  featureFlags: PostHogV1FlagsResponse['featureFlags'],
134
- featureFlagPayloads: PostHogV1FlagsResponse['featureFlagPayloads']
136
+ featureFlagPayloads: PostHogV1FlagsResponse['featureFlagPayloads'],
137
+ decodePayload: (payload: any) => any = parsePayload
135
138
  ): PostHogFeatureFlagsResponse => {
136
139
  // If a feature flag payload key is not in the feature flags, we treat it as true feature flag.
137
140
  const allKeys = [...new Set([...Object.keys(featureFlags ?? {}), ...Object.keys(featureFlagPayloads ?? {})])]
@@ -144,7 +147,7 @@ export const createFlagsResponseFromFlagsAndPayloads = (
144
147
  featureFlagPayloads: featureFlagPayloads ?? {},
145
148
  }
146
149
 
147
- return normalizeFlagsResponse(flagDetails as PostHogV1FlagsResponse)
150
+ return normalizeFlagsResponse(flagDetails as PostHogV1FlagsResponse, decodePayload)
148
151
  }
149
152
 
150
153
  export const updateFlagValue = (flag: FeatureFlagDetail, value: FeatureFlagValue): FeatureFlagDetail => {
@@ -162,11 +165,20 @@ export function getEnabledFromValue(value: FeatureFlagValue): boolean {
162
165
  return typeof value === 'string' ? true : value
163
166
  }
164
167
 
168
+ /** Whether a flag value is on: `true`, or a variant that isn't an empty string. */
169
+ export function isEnabledFlagValue(value: FeatureFlagValue | undefined): boolean {
170
+ return value === true || (typeof value === 'string' && value !== '')
171
+ }
172
+
165
173
  export function getVariantFromValue(value: FeatureFlagValue): string | undefined {
166
174
  return typeof value === 'string' ? value : undefined
167
175
  }
168
176
 
169
- export const flagDetailsToResults = (flagDetails: Record<string, FeatureFlagDetail>): FeatureFlagResult[] => {
177
+ export const flagDetailsToResults = (
178
+ flagDetails: Record<string, FeatureFlagDetail>,
179
+ decodePayload: (payload: any) => JsonType = parsePayload,
180
+ isEnabled: (value: FeatureFlagValue) => boolean = getEnabledFromValue
181
+ ): FeatureFlagResult[] => {
170
182
  return Object.values(flagDetails)
171
183
  .filter((detail) => !detail.failed)
172
184
  .map((detail) => {
@@ -174,9 +186,9 @@ export const flagDetailsToResults = (flagDetails: Record<string, FeatureFlagDeta
174
186
  const rawPayload = detail.metadata?.payload
175
187
  return {
176
188
  key: detail.key,
177
- enabled: getEnabledFromValue(value),
189
+ enabled: isEnabled(value),
178
190
  variant: getVariantFromValue(value),
179
- payload: rawPayload !== undefined ? parsePayload(rawPayload) : null,
191
+ payload: rawPayload !== undefined ? decodePayload(rawPayload) : null,
180
192
  }
181
193
  })
182
194
  }
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export {
2
2
  getFeatureFlagValue,
3
3
  getEnabledFromValue,
4
+ isEnabledFlagValue,
4
5
  getVariantFromValue,
5
6
  parsePayload,
6
7
  flagDetailsToResults,