posthog-node 6.0.6 → 6.1.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 (42) hide show
  1. package/dist/client.d.ts +13 -1
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +23 -1
  4. package/dist/client.mjs +23 -1
  5. package/dist/exports.d.ts +3 -0
  6. package/dist/exports.d.ts.map +1 -1
  7. package/dist/exports.js +73 -51
  8. package/dist/exports.mjs +2 -0
  9. package/dist/extensions/feature-flags/feature-flags.d.ts.map +1 -1
  10. package/dist/extensions/feature-flags/feature-flags.js +8 -0
  11. package/dist/extensions/feature-flags/feature-flags.mjs +8 -0
  12. package/dist/extensions/react-router.d.ts +59 -0
  13. package/dist/extensions/react-router.d.ts.map +1 -0
  14. package/dist/extensions/react-router.js +78 -0
  15. package/dist/extensions/react-router.mjs +40 -0
  16. package/dist/extensions/request-exception.d.ts +22 -0
  17. package/dist/extensions/request-exception.d.ts.map +1 -0
  18. package/dist/extensions/request-exception.js +134 -0
  19. package/dist/extensions/request-exception.mjs +86 -0
  20. package/dist/extensions/tracing-headers.d.ts +13 -5
  21. package/dist/extensions/tracing-headers.d.ts.map +1 -1
  22. package/dist/extensions/tracing-headers.js +36 -12
  23. package/dist/extensions/tracing-headers.mjs +34 -13
  24. package/dist/remote-config-errors.d.ts +20 -0
  25. package/dist/remote-config-errors.d.ts.map +1 -0
  26. package/dist/remote-config-errors.js +44 -0
  27. package/dist/remote-config-errors.mjs +6 -0
  28. package/dist/types.d.ts +8 -2
  29. package/dist/types.d.ts.map +1 -1
  30. package/dist/version.d.ts +1 -1
  31. package/dist/version.js +1 -1
  32. package/dist/version.mjs +1 -1
  33. package/package.json +3 -2
  34. package/src/client.ts +50 -2
  35. package/src/exports.ts +3 -0
  36. package/src/extensions/feature-flags/feature-flags.ts +27 -0
  37. package/src/extensions/react-router.ts +137 -0
  38. package/src/extensions/request-exception.ts +153 -0
  39. package/src/extensions/tracing-headers.ts +61 -16
  40. package/src/remote-config-errors.ts +19 -0
  41. package/src/types.ts +8 -2
  42. package/src/version.ts +1 -1
@@ -48,6 +48,8 @@ export function getPostHogCookieReadOptions(posthog: {
48
48
  export interface PostHogTracingHeaderValues {
49
49
  sessionId?: string
50
50
  distinctId?: string
51
+ /** The distinct ID is from the cookie and belongs to a visitor posthog-js has not identified. */
52
+ anonymous?: true
51
53
  }
52
54
 
53
55
  export function addProperty(properties: Record<string, any>, key: string, value: unknown): void {
@@ -92,25 +94,25 @@ function isRecent(timestamp: unknown, now: number, maxAgeMs: number): boolean {
92
94
  * Reads the live session ID, and the distinct ID of an identified user, from the cookie that posthog-js writes with its
93
95
  * default persistence. The browser sends it on every same-site request, so backend events link to the browser session
94
96
  * without `tracing_headers`. A session past the posthog-js idle timeout or length cap is not returned, because the
95
- * browser starts a new session on its next activity. An anonymous distinct ID is not returned, so backend events for
96
- * anonymous visitors stay personless. Nothing is returned when the visitor's consent cookie opts out.
97
+ * browser starts a new session on its next activity. An anonymous distinct ID is returned only with
98
+ * `includeAnonymousDistinctId` (marked `anonymous`), so backend events for anonymous visitors otherwise stay
99
+ * personless. Nothing is returned when the visitor's consent cookie opts out.
97
100
  */
98
101
  export function getPostHogCookieValues(
99
102
  cookieHeader: HeaderValue,
100
103
  apiKey: string,
101
104
  now: number = Date.now(),
102
105
  sessionIdleTimeoutMs: number = COOKIE_SESSION_IDLE_TIMEOUT_MS,
103
- optOutCapturingByDefault: boolean = false
106
+ optOutCapturingByDefault: boolean = false,
107
+ includeAnonymousDistinctId: boolean = false
104
108
  ): PostHogTracingHeaderValues {
105
109
  try {
106
110
  if (typeof cookieHeader !== 'string') {
107
111
  return {}
108
112
  }
109
- // The adapter keeps the last duplicate, while the browser reads the first.
110
- const cookies = cookieStoreFromHeader(cookieHeader.split(';').reverse().join(';'))
113
+ const cookies = readCookieStore(cookieHeader)
111
114
  const raw = cookies.get(getPostHogCookieName(apiKey))?.value
112
- const consent = cookies.get(getConsentCookieName(apiKey))?.value ?? ''
113
- if (!raw || isNoLike(consent) || (optOutCapturingByDefault && !isYesLike(consent))) {
115
+ if (!raw || isOptedOutByCookie(cookies, apiKey, optOutCapturingByDefault)) {
114
116
  return {}
115
117
  }
116
118
  const data = JSON.parse(raw)
@@ -118,7 +120,9 @@ export function getPostHogCookieValues(
118
120
  return {}
119
121
  }
120
122
 
121
- const distinctId = data.$user_state === 'identified' ? sanitizeTracingHeaderValue(data.distinct_id) : undefined
123
+ const identified = data.$user_state === 'identified'
124
+ const distinctId =
125
+ identified || includeAnonymousDistinctId ? sanitizeTracingHeaderValue(data.distinct_id) : undefined
122
126
  let sessionId: string | undefined
123
127
  const session = data.$sesid
124
128
  if (Array.isArray(session) && (session.length === 2 || session.length === 3)) {
@@ -135,12 +139,45 @@ export function getPostHogCookieValues(
135
139
  return {
136
140
  ...(sessionId !== undefined ? { sessionId } : {}),
137
141
  ...(distinctId !== undefined ? { distinctId } : {}),
142
+ ...(distinctId !== undefined && !identified ? { anonymous: true } : {}),
138
143
  }
139
144
  } catch {
140
145
  return {}
141
146
  }
142
147
  }
143
148
 
149
+ function readCookieStore(cookieHeader: string): ReturnType<typeof cookieStoreFromHeader> {
150
+ // The adapter keeps the last duplicate, while the browser reads the first.
151
+ return cookieStoreFromHeader(cookieHeader.split(';').reverse().join(';'))
152
+ }
153
+
154
+ function isOptedOutByCookie(
155
+ cookies: ReturnType<typeof cookieStoreFromHeader>,
156
+ apiKey: string,
157
+ optOutCapturingByDefault: boolean
158
+ ): boolean {
159
+ const consent = cookies.get(getConsentCookieName(apiKey))?.value ?? ''
160
+ return isNoLike(consent) || (optOutCapturingByDefault && !isYesLike(consent))
161
+ }
162
+
163
+ /**
164
+ * Whether the visitor's posthog-js consent cookie opts out of capture, or, with `optOutCapturingByDefault`, does not
165
+ * opt in. posthog-js keeps consent in localStorage by default, which the server cannot read.
166
+ */
167
+ export function isPostHogCookieOptedOut(
168
+ cookieHeader: HeaderValue,
169
+ apiKey: string,
170
+ optOutCapturingByDefault: boolean = false
171
+ ): boolean {
172
+ try {
173
+ // A request without a Cookie header has no consent cookie either.
174
+ const header = typeof cookieHeader === 'string' ? cookieHeader : ''
175
+ return isOptedOutByCookie(readCookieStore(header), apiKey, optOutCapturingByDefault)
176
+ } catch {
177
+ return false
178
+ }
179
+ }
180
+
144
181
  function getSessionIdleTimeoutMs(cookie: PostHogCookieReadOptions): number {
145
182
  const seconds = cookie.sessionIdleTimeoutSeconds
146
183
  // Zero falls back to the default, like posthog-js's `session_idle_timeout_seconds || default`.
@@ -151,13 +188,18 @@ function getSessionIdleTimeoutMs(cookie: PostHogCookieReadOptions): number {
151
188
  return Math.min(Math.max(seconds, MIN_SESSION_IDLE_TIMEOUT_SECONDS), MAX_SESSION_IDLE_TIMEOUT_SECONDS) * 1000
152
189
  }
153
190
 
154
- function readCookieValues(headers: IncomingHttpHeaders, cookie: PostHogCookieReadOptions): PostHogTracingHeaderValues {
191
+ function readCookieValues(
192
+ headers: IncomingHttpHeaders,
193
+ cookie: PostHogCookieReadOptions,
194
+ includeAnonymousDistinctId: boolean
195
+ ): PostHogTracingHeaderValues {
155
196
  return getPostHogCookieValues(
156
197
  headers.cookie,
157
198
  cookie.apiKey,
158
199
  Date.now(),
159
200
  getSessionIdleTimeoutMs(cookie),
160
- cookie.optOutCapturingByDefault === true
201
+ cookie.optOutCapturingByDefault === true,
202
+ includeAnonymousDistinctId
161
203
  )
162
204
  }
163
205
 
@@ -168,12 +210,13 @@ function readCookieValues(headers: IncomingHttpHeaders, cookie: PostHogCookieRea
168
210
  export function readPostHogTracingHeaders(
169
211
  options: { captureTracingHeaders?: boolean },
170
212
  headers?: IncomingHttpHeaders,
171
- cookie?: PostHogCookieReadOptions | null
213
+ cookie?: PostHogCookieReadOptions | null,
214
+ includeAnonymousDistinctId: boolean = false
172
215
  ): PostHogTracingHeaderValues {
173
216
  if (options.captureTracingHeaders !== false) {
174
- return getPostHogTracingHeaderValues(headers, cookie)
217
+ return getPostHogTracingHeaderValues(headers, cookie, includeAnonymousDistinctId)
175
218
  }
176
- return headers && cookie ? readCookieValues(headers, cookie) : {}
219
+ return headers && cookie ? readCookieValues(headers, cookie, includeAnonymousDistinctId) : {}
177
220
  }
178
221
 
179
222
  /**
@@ -182,7 +225,8 @@ export function readPostHogTracingHeaders(
182
225
  */
183
226
  export function getPostHogTracingHeaderValues(
184
227
  headers?: IncomingHttpHeaders,
185
- cookie?: PostHogCookieReadOptions | null
228
+ cookie?: PostHogCookieReadOptions | null,
229
+ includeAnonymousDistinctId: boolean = false
186
230
  ): PostHogTracingHeaderValues {
187
231
  if (!headers) {
188
232
  return {}
@@ -190,13 +234,14 @@ export function getPostHogTracingHeaderValues(
190
234
 
191
235
  const headerSessionId = sanitizeTracingHeaderValue(headers[POSTHOG_TRACING_HEADERS.sessionId])
192
236
  const headerDistinctId = sanitizeTracingHeaderValue(headers[POSTHOG_TRACING_HEADERS.distinctId])
193
- const { sessionId, distinctId } =
237
+ const { sessionId, distinctId, anonymous }: PostHogTracingHeaderValues =
194
238
  headerSessionId === undefined && headerDistinctId === undefined && cookie
195
- ? readCookieValues(headers, cookie)
239
+ ? readCookieValues(headers, cookie, includeAnonymousDistinctId)
196
240
  : { sessionId: headerSessionId, distinctId: headerDistinctId }
197
241
 
198
242
  return {
199
243
  ...(sessionId !== undefined ? { sessionId } : {}),
200
244
  ...(distinctId !== undefined ? { distinctId } : {}),
245
+ ...(anonymous ? { anonymous } : {}),
201
246
  }
202
247
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * PostHog answered a `getRemoteConfigPayload` request with a status outside 200 to 299.
3
+ *
4
+ * Emitted on the client's `error` event; the call itself resolves to `undefined`.
5
+ * Branch on `statusCode`, for example `404` when the flag does not exist or is not a remote
6
+ * config flag, versus `429` or `5xx` when the request should be tried again later.
7
+ */
8
+ export class RemoteConfigPayloadError extends Error {
9
+ name = 'RemoteConfigPayloadError'
10
+
11
+ constructor(
12
+ /** The key of the flag whose payload was requested. */
13
+ readonly flagKey: string,
14
+ /** The HTTP status PostHog answered with. */
15
+ readonly statusCode: number
16
+ ) {
17
+ super(`Failed to fetch remote config payload for flag "${flagKey}": status=${statusCode}`)
18
+ }
19
+ }
package/src/types.ts CHANGED
@@ -356,8 +356,9 @@ export type PostHogOptions = Omit<
356
356
  */
357
357
  disableCompression?: boolean
358
358
  /**
359
- * Lets the Express, NestJS, Hono, and `instrumentRequest` integrations read the session ID, and the distinct ID of an identified user, from the
360
- * posthog-js cookie when a request has neither tracing header.
359
+ * Lets the Express, NestJS, Hono and `instrumentRequest` integrations read the session ID, and the distinct ID of an
360
+ * identified user, from the posthog-js cookie when a request has neither tracing header.
361
+ * `createReactRouterErrorHandler` also reads an anonymous visitor's distinct ID, and sends their exceptions personless.
361
362
  *
362
363
  * Turn it on only when posthog-js stores opt-out consent in a cookie, or when you do not use opt-out: the server
363
364
  * cannot read an opt-out that posthog-js keeps in localStorage (its default).
@@ -689,6 +690,11 @@ export type PostHogFeatureFlag = {
689
690
  // group's property filters match but the rollout percentage excludes the user, rather than
690
691
  // continuing to evaluate later groups.
691
692
  early_exit?: boolean
693
+ /**
694
+ * Early-access feature flag. The person's opt-in, stored in the person property
695
+ * `$feature_enrollment/<flag key>`, decides the flag before holdouts and release conditions.
696
+ */
697
+ feature_enrollment?: boolean | null
692
698
  }
693
699
  deleted: boolean
694
700
  active: boolean
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = "6.0.6"
1
+ export const version = "6.1.0"