Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[HEAP] update browser destination code to load heap js v5 script #2665

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Heap loading 1`] = `
NodeList [
<script
src="https://cdn.us.heap-api.com/v5/heapjs-static/5.2.6/core/heap.js"
type="text/javascript"
/>,
<script
src="https://cdn.us.heap-api.com/config/1/heap_config.js"
status="loaded"
type="text/javascript"
/>,
<script>
// the emptiness
</script>,
]
`;
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Analytics, Context } from '@segment/analytics-next'
import heapDestination, { destination } from '../index'
import { HEAP_TEST_ENV_ID, mockHeapJsHttpRequest } from '../test-utilities'
import { HEAP_TEST_ENV_ID } from '../test-utilities'

const subscriptions = [
{
Expand All @@ -16,19 +16,19 @@ describe('Heap', () => {
test('loading', async () => {
jest.spyOn(destination, 'initialize')

mockHeapJsHttpRequest()

const [event] = await heapDestination({ appId: HEAP_TEST_ENV_ID, subscriptions })

await event.load(Context.system(), {} as Analytics)
expect(destination.initialize).toHaveBeenCalled()
expect(window.heap.appid).toEqual(HEAP_TEST_ENV_ID)

const scripts = window.document.querySelectorAll('script')
expect(scripts).toMatchSnapshot()
})

test('loading with cdn', async () => {
jest.spyOn(destination, 'initialize')

mockHeapJsHttpRequest()

const [event] = await heapDestination({
appId: HEAP_TEST_ENV_ID,
subscriptions,
Expand Down

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

33 changes: 19 additions & 14 deletions packages/browser-destinations/destinations/heap/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import type { Settings } from './generated-types'
import type { BrowserDestinationDefinition } from '@segment/browser-destination-runtime/types'
import { browserDestination } from '@segment/browser-destination-runtime/shim'
import { HeapApi, UserConfig } from './types'
import type { HeapApi, HeapMethods, UserConfig } from './types'
import { defaultValues } from '@segment/actions-core'
import trackEvent from './trackEvent'
import identifyUser from './identifyUser'
import { initScript } from './init-script'
import { isDefined } from './utils'

declare global {
interface Window {
heap: HeapApi
heapReadyCb: Array<{ name: HeapMethods; fn: () => void }>
heap: Record<HeapMethods, (...args: any[]) => void> & HeapApi
}
}

Expand Down Expand Up @@ -58,9 +60,16 @@ export const destination: BrowserDestinationDefinition<Settings, HeapApi> = {
required: false
},
trackingServer: {
label: 'Tracking Server',
label: 'Tracking Server (deprecated)',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hi @cpsoinos looks like you have labeled this as deprecated. Is it still referenced anywhere in code though? i.e is it actually used at all?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @joe-ayoub-segment, I updated my changes so that this setting is still used, though it is still deprecated. Customers that wish to self-host will have set both trackingServer and hostname. When both of these settings are set, Segment will load the Classic SDK (retaining current functionality).

description:
'This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/set-up-first-party-data-collection-in-heap).',
'This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/set-up-first-party-data-collection-in-heap). This field is deprecated in favor of "ingestServer".',
type: 'string',
required: false
},
ingestServer: {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: adding a new 'optional' setting is OK.

label: 'Ingest Server',
description:
'This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/web#ingestserver).',
type: 'string',
required: false
},
Expand Down Expand Up @@ -89,24 +98,20 @@ export const destination: BrowserDestinationDefinition<Settings, HeapApi> = {
disableTextCapture: settings.disableTextCapture || false,
secureCookie: settings.secureCookie || false
}

if (settings.trackingServer) {
config.trackingServer = settings.trackingServer
if (settings.ingestServer) {
config.ingestServer = settings.ingestServer
}

// heap.appid and heap.config must be set before loading heap.js.
window.heap = window.heap || []
window.heap.appid = settings.appId
window.heap.config = config
initScript(settings.appId, config)

if (isDefined(settings.hostname)) {
await deps.loadScript(`https://${settings.hostname}/js/heap-${settings.appId}.js`)
await deps.loadScript(`https://${settings.hostname}/config/${settings.appId}/heap_config.js`)
} else {
await deps.loadScript(`https://cdn.heapanalytics.com/js/heap-${settings.appId}.js`)
await deps.loadScript(`https://cdn.us.heap-api.com/config/${settings.appId}/heap_config.js`)
}

// Explained here: https://stackoverflow.com/questions/14859058/why-does-the-segment-io-loader-script-push-method-names-args-onto-a-queue-which
await deps.resolveWhen(() => Object.prototype.hasOwnProperty.call(window, 'heap'), 100)
await deps.resolveWhen(() => window.heap.loaded === true, 300)

return window.heap
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type { HeapMethods, UserConfig } from './types'

/**
* Initialize the Heap script with the provided environment ID and configuration.
*/
export const initScript = (envId: string, config: UserConfig) => {
// Ensure heapReadyCb exists on the window object
window.heapReadyCb = window.heapReadyCb || []

// Ensure heap exists on the window object
window.heap = window.heap || ({} as any)

window.heap.load = function (
envId: string,
clientConfig: UserConfig = { disableTextCapture: false, secureCookie: false }
): void {
window.heap.envId = envId
window.heap.clientConfig = clientConfig
window.heap.clientConfig.shouldFetchServerConfig = false

// Define all Heap API methods and add them to the heap object
const methods: HeapMethods[] = [
'init',
'startTracking',
'stopTracking',
'track',
'resetIdentity',
'identify',
'identifyHashed',
'getSessionId',
'getUserId',
'getIdentity',
'addUserProperties',
'addEventProperties',
'removeEventProperty',
'clearEventProperties',
'addAccountProperties',
'addAdapter',
'addTransformer',
'addTransformerFn',
'onReady',
'addPageviewProperties',
'removePageviewProperty',
'clearPageviewProperties',
'trackPageview'
]

const createMethodProxy = (methodName: HeapMethods) => {
return function (...args: any[]) {
// Push method calls to heapReadyCb until the script is fully loaded
window.heapReadyCb.push({
name: methodName,
fn: () => {
if (window.heap[methodName]) {
window.heap[methodName](...args)
}
}
})
}
}

// Proxy all methods to heap
for (const method of methods) {
window.heap[method] = createMethodProxy(method)
}
}

window.heap.load(envId, config)
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { HeapApi } from './types'
import { Subscription } from '@segment/browser-destination-runtime/types'
import nock from 'nock'

export const HEAP_TEST_ENV_ID = '1'

export const createMockedHeapJsSdk = (): HeapApi => {
return {
appid: HEAP_TEST_ENV_ID,
envId: HEAP_TEST_ENV_ID,
config: {
disableTextCapture: true,
secureCookie: true
Expand All @@ -17,6 +17,7 @@ export const createMockedHeapJsSdk = (): HeapApi => {
addUserProperties: jest.fn()
}
}

export const trackEventSubscription: Subscription = {
partnerAction: 'trackEvent',
name: 'Track Event',
Expand Down Expand Up @@ -58,7 +59,3 @@ export const identifyUserSubscription: Subscription = {
}
}
}

export const mockHeapJsHttpRequest = (): void => {
nock('https://cdn.heapanalytics.com').get(`/js/heap-${HEAP_TEST_ENV_ID}.js`).reply(200, {})
}
32 changes: 31 additions & 1 deletion packages/browser-destinations/destinations/heap/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export type UserConfig = {
trackingServer?: string
ingestServer?: string
disableTextCapture: boolean
secureCookie: boolean
}
Expand All @@ -14,9 +15,38 @@ type EventProperties = {

export type HeapApi = {
appid: string
envId: string
track: (eventName: string, eventProperties: EventProperties, library?: string) => void
load: () => void
load: (envId: string, clientConfig?: UserConfig) => void
loaded?: boolean
config: UserConfig
clientConfig?: Partial<UserConfig> & { shouldFetchServerConfig?: boolean }
identify: (identity: string) => void
addUserProperties: (properties: UserProperties) => void
}

// Define types for Heap methods
export type HeapMethods =
| 'init'
| 'startTracking'
| 'stopTracking'
| 'track'
| 'resetIdentity'
| 'identify'
| 'identifyHashed'
| 'getSessionId'
| 'getUserId'
| 'getIdentity'
| 'addUserProperties'
| 'addEventProperties'
| 'removeEventProperty'
| 'clearEventProperties'
| 'addAccountProperties'
| 'addAdapter'
| 'addTransformer'
| 'addTransformerFn'
| 'onReady'
| 'addPageviewProperties'
| 'removePageviewProperty'
| 'clearPageviewProperties'
| 'trackPageview'
Loading