Skip to content

Commit

Permalink
Merge branch 'main' into feat/default-ui-host
Browse files Browse the repository at this point in the history
  • Loading branch information
raquelmsmith authored Aug 26, 2024
2 parents 483288b + 3379ba1 commit 285d09f
Show file tree
Hide file tree
Showing 8 changed files with 100 additions and 38 deletions.
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
## 1.158.1 - 2024-08-26

- fix: event listeners should obey start and stop (#1379)

## 1.158.0 - 2024-08-26

- fix(segment): Posthog can identify after segment identifies a user, not just during bootstrap. (#1373)
- fix: Revert cypress back to 13.6.3 (#1384)

## 1.157.2 - 2024-08-20

- feat: Use NavigatorUAData and navigator.webdriver to improve bot detection (#1359)
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "posthog-js",
"version": "1.157.2",
"version": "1.158.1",
"description": "Posthog-js allows you to automatically capture usage and send events to PostHog.",
"repository": "https://github.com/PostHog/posthog-js",
"author": "[email protected]",
Expand Down Expand Up @@ -68,7 +68,7 @@
"babel-eslint": "10.1.0",
"babel-jest": "^26.6.3",
"compare-versions": "^6.1.0",
"cypress": "13.13.2",
"cypress": "13.6.3",
"cypress-localstorage-commands": "^2.2.6",
"date-fns": "^3.6.0",
"eslint": "8.56.0",
Expand Down
4 changes: 3 additions & 1 deletion playground/nextjs/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ export default function Home() {
Set user properties
</button>

<button onClick={() => posthog?.reset()}>Reset</button>
<button onClick={() => posthog?.reset()} id="set-user-properties">
Reset
</button>
</div>

{isClient && (
Expand Down
3 changes: 2 additions & 1 deletion playground/segment/segment.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
analytics.load("GOEDfA21zZTtR7clsBuDvmBKAtAdZ6Np");

analytics.ready(() => {
posthog.init('phc_mxO23D02CR3QU7V1u95ae3YEGNAFGuvyUlRpVNwX89B', {
posthog.init('phc_lPwXKkvW2VtByfTsibDzFKAxn02rdVgMUiHWkZ5kW31', {
api_host: "http://localhost:8000",
capture_pageview: false,
autocapture: false,
segment: window.analytics,
Expand Down
14 changes: 7 additions & 7 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

43 changes: 41 additions & 2 deletions src/__tests__/segment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@
import { beforeEach, describe, expect, it, jest } from '@jest/globals'

import { PostHog } from '../posthog-core'
import { SegmentContext, SegmentPlugin } from '../extensions/segment-integration'
import { USER_STATE } from '../constants'

describe(`Segment integration`, () => {
let segment: any
let segmentIntegration: any
let segmentIntegration: SegmentPlugin
let posthogName: string

jest.setTimeout(500)
Expand All @@ -28,7 +30,7 @@ describe(`Segment integration`, () => {
anonymousId: () => 'test-anonymous-id',
id: () => 'test-id',
}),
register: (integration: any) => {
register: (integration: SegmentPlugin) => {
// IMPORTANT: the real register function returns a Promise. We
// want to do the same thing and have some way to verify that
// the integration is setup in time for the `loaded` callback.
Expand Down Expand Up @@ -108,4 +110,41 @@ describe(`Segment integration`, () => {
expect(posthog.get_distinct_id()).toBe('test-id')
expect(posthog.get_property('$device_id')).toBe('test-anonymous-id')
})

it('should handle segment.identify after bootstrap', async () => {
segment.user = () => ({
anonymousId: () => 'test-anonymous-id',
id: () => '',
})

const posthog = await new Promise<PostHog>((resolve) => {
return new PostHog().init(
`test-token`,
{
debug: true,
persistence: `memory`,
api_host: `https://test.com`,
segment: segment,
loaded: resolve,
},
posthogName
)
})

expect(posthog.get_distinct_id()).not.toEqual('test-id')
expect(posthog.persistence?.get_property(USER_STATE)).toEqual('anonymous')

if (segmentIntegration && segmentIntegration.identify) {
segmentIntegration.identify({
event: {
event: '$identify',
userId: 'distinguished user',
anonymousId: 'anonymous segment user',
},
} as unknown as SegmentContext)

expect(posthog.get_distinct_id()).toEqual('distinguished user')
expect(posthog.persistence?.get_property(USER_STATE)).toEqual('identified')
}
})
})
50 changes: 31 additions & 19 deletions src/extensions/replay/sessionrecording.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,25 +244,6 @@ export class SessionRecording {
this.stopRrweb = undefined
this.receivedDecide = false

window?.addEventListener('beforeunload', () => {
this._flushBuffer()
})

window?.addEventListener('offline', () => {
this._tryAddCustomEvent('browser offline', {})
})

window?.addEventListener('online', () => {
this._tryAddCustomEvent('browser online', {})
})

window?.addEventListener('visibilitychange', () => {
if (document?.visibilityState) {
const label = 'window ' + document.visibilityState
this._tryAddCustomEvent(label, {})
}
})

if (!this.instance.sessionManager) {
logger.error(LOGGER_PREFIX + ' started without valid sessionManager')
throw new Error(LOGGER_PREFIX + ' started without valid sessionManager. This is a bug.')
Expand All @@ -280,9 +261,34 @@ export class SessionRecording {
this._setupSampling()
}

private _onBeforeUnload = (): void => {
this._flushBuffer()
}

private _onOffline = (): void => {
this._tryAddCustomEvent('browser offline', {})
}

private _onOnline = (): void => {
this._tryAddCustomEvent('browser online', {})
}

private _onVisibilityChange = (): void => {
if (document?.visibilityState) {
const label = 'window ' + document.visibilityState
this._tryAddCustomEvent(label, {})
}
}

startIfEnabledOrStop() {
if (this.isRecordingEnabled) {
this._startCapture()

window?.addEventListener('beforeunload', this._onBeforeUnload)
window?.addEventListener('offline', this._onOffline)
window?.addEventListener('online', this._onOnline)
window?.addEventListener('visibilitychange', this._onVisibilityChange)

logger.info(LOGGER_PREFIX + ' started')
} else {
this.stopRecording()
Expand All @@ -295,6 +301,12 @@ export class SessionRecording {
this.stopRrweb()
this.stopRrweb = undefined
this._captureStarted = false

window?.removeEventListener('beforeunload', this._onBeforeUnload)
window?.removeEventListener('offline', this._onOffline)
window?.removeEventListener('online', this._onOnline)
window?.removeEventListener('visibilitychange', this._onVisibilityChange)

logger.info(LOGGER_PREFIX + ' stopped')
}
}
Expand Down
11 changes: 5 additions & 6 deletions src/extensions/segment-integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export type SegmentAnalytics = {
}

// Loosely based on https://github.com/segmentio/analytics-next/blob/master/packages/core/src/plugins/index.ts
interface SegmentContext {
export interface SegmentContext {
event: {
event: string
userId?: string
Expand All @@ -45,7 +45,7 @@ interface SegmentContext {

type SegmentFunction = (ctx: SegmentContext) => Promise<SegmentContext> | SegmentContext

interface SegmentPlugin {
export interface SegmentPlugin {
name: string
version: string
type: 'enrichment'
Expand All @@ -72,13 +72,12 @@ const createSegmentIntegration = (posthog: PostHog): SegmentPlugin => {
}
if (!ctx.event.userId && ctx.event.anonymousId !== posthog.get_distinct_id()) {
// This is our only way of detecting that segment's analytics.reset() has been called so we also call it
logger.info('Segment integration does not have a userId set, resetting PostHog')
posthog.reset()
}
if (ctx.event.userId && ctx.event.userId !== posthog.get_distinct_id()) {
posthog.register({
distinct_id: ctx.event.userId,
})
posthog.reloadFeatureFlags()
logger.info('Segment integration has a userId set, identifying with PostHog')
posthog.identify(ctx.event.userId)
}

const additionalProperties = posthog._calculate_event_properties(
Expand Down

0 comments on commit 285d09f

Please sign in to comment.