@segment/analytics-browser-actions-braze 1.0.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.
@@ -0,0 +1,65 @@
1
+ import { Analytics, Context } from '@segment/analytics-next'
2
+ import brazeDestination, { destination } from '../index'
3
+ const testSdkVersions = ['3.5', '4.1']
4
+
5
+ testSdkVersions.forEach((sdkVersion) => {
6
+ describe(`trackEvent (v${sdkVersion})`, () => {
7
+ test('invokes braze`s logCustomEvent API', async () => {
8
+ const [trackEvent] = await brazeDestination({
9
+ api_key: 'b_123',
10
+ endpoint: 'endpoint',
11
+ sdkVersion,
12
+ doNotLoadFontAwesome: true,
13
+ subscriptions: [
14
+ {
15
+ partnerAction: 'trackEvent',
16
+ name: 'Log Custom Event',
17
+ enabled: true,
18
+ subscribe: 'type = "track"',
19
+ mapping: {
20
+ eventName: {
21
+ '@path': '$.event'
22
+ },
23
+ eventProperties: {
24
+ '@path': '$.properties'
25
+ }
26
+ }
27
+ }
28
+ ]
29
+ })
30
+
31
+ jest.spyOn(destination.actions.trackEvent, 'perform')
32
+ const initializeSpy = jest.spyOn(destination, 'initialize')
33
+
34
+ await trackEvent.load(Context.system(), new Analytics({ writeKey: '123' }))
35
+
36
+ // Spy on the braze APIs now that braze has been loaded.
37
+ const { instance: braze } = await initializeSpy.mock.results[0].value
38
+ const logCustomEventSpy = jest.spyOn(braze, 'logCustomEvent')
39
+
40
+ await trackEvent.track?.(
41
+ new Context({
42
+ type: 'track',
43
+ event: 'UFC',
44
+ properties: {
45
+ goat: 'hasbulla'
46
+ }
47
+ })
48
+ )
49
+
50
+ expect(destination.actions.trackEvent.perform).toHaveBeenCalledWith(
51
+ expect.objectContaining({
52
+ instance: expect.objectContaining({
53
+ logCustomEvent: expect.any(Function)
54
+ })
55
+ }),
56
+
57
+ expect.objectContaining({
58
+ payload: { eventName: 'UFC', eventProperties: { goat: 'hasbulla' } }
59
+ })
60
+ )
61
+
62
+ expect(logCustomEventSpy).toHaveBeenCalledWith('UFC', { goat: 'hasbulla' })
63
+ })
64
+ })
65
+ })
@@ -0,0 +1,65 @@
1
+ import { Analytics, Context } from '@segment/analytics-next'
2
+ import brazeDestination, { destination } from '../index'
3
+
4
+ const testSdkVersions = ['3.5', '4.1']
5
+
6
+ testSdkVersions.forEach((sdkVersion) => {
7
+ test(`reports products when present (v${sdkVersion})`, async () => {
8
+ const initializeSpy = jest.spyOn(destination, 'initialize')
9
+
10
+ const [trackPurchase] = await brazeDestination({
11
+ api_key: 'b_123',
12
+ endpoint: 'endpoint',
13
+ sdkVersion,
14
+ doNotLoadFontAwesome: true,
15
+ subscriptions: [
16
+ {
17
+ partnerAction: 'trackPurchase',
18
+ name: 'Log Purchase',
19
+ enabled: true,
20
+ subscribe: 'type = "track"',
21
+ mapping: {
22
+ purchaseProperties: {
23
+ '@path': '$.properties'
24
+ },
25
+ products: {
26
+ '@path': '$.properties.products'
27
+ }
28
+ }
29
+ }
30
+ ]
31
+ })
32
+
33
+ await trackPurchase.load(Context.system(), new Analytics({ writeKey: '123' }))
34
+
35
+ // Spy on the braze APIs now that braze has been loaded.
36
+ const { instance: braze } = await initializeSpy.mock.results[0].value
37
+ const brazeLogPurchase = jest.spyOn(braze, 'logPurchase').mockReturnValue(true)
38
+
39
+ await trackPurchase.track?.(
40
+ new Context({
41
+ type: 'track',
42
+ properties: {
43
+ banana: 'yellow',
44
+ products: [
45
+ {
46
+ product_id: 'p_123',
47
+ price: 399,
48
+ currency: 'BGP',
49
+ quantity: 2
50
+ },
51
+ {
52
+ product_id: 'p_456',
53
+ price: 0
54
+ }
55
+ ]
56
+ }
57
+ })
58
+ )
59
+
60
+ expect(brazeLogPurchase.mock.calls[0]).toMatchSnapshot()
61
+
62
+ // applying defaults
63
+ expect(brazeLogPurchase.mock.calls[1]).toMatchSnapshot()
64
+ })
65
+ })
@@ -0,0 +1,145 @@
1
+ import { Analytics, Context } from '@segment/analytics-next'
2
+ import brazeDestination, { destination } from '../index'
3
+
4
+ describe('updateUserProfile', () => {
5
+ const subscriptions = [
6
+ {
7
+ partnerAction: 'updateUserProfile',
8
+ name: 'Update User Profile',
9
+ enabled: true,
10
+ subscribe: 'type = "identify"',
11
+ mapping: {
12
+ country: { '@path': '$.traits.country' },
13
+ current_location: { '@path': '$.traits.current_location' },
14
+ custom_attributes: { '@path': '$.traits.custom_attributes' },
15
+ dob: { '@path': '$.traits.dob' },
16
+ email: { '@path': '$.traits.email' },
17
+ email_subscribe: { '@path': '$.traits.email_subscribe' },
18
+ first_name: { '@path': '$.traits.first_name' },
19
+ gender: { '@path': '$.traits.gender' },
20
+ home_city: { '@path': '$.traits.home_city' },
21
+ image_url: { '@path': '$.traits.image_url' },
22
+ language: { '@path': '$.traits.language' },
23
+ last_name: { '@path': '$.traits.last_name' },
24
+ phone: { '@path': '$.traits.phone' },
25
+ push_subscribe: { '@path': '$.traits.push_subscribe' }
26
+ }
27
+ }
28
+ ]
29
+
30
+ beforeEach(async () => {
31
+ destination.actions.updateUserProfile.perform = jest.fn()
32
+ jest.spyOn(destination.actions.trackEvent, 'perform')
33
+ jest.spyOn(destination, 'initialize')
34
+ })
35
+
36
+ test('changes the external_id when present', async () => {
37
+ const [event] = await brazeDestination({
38
+ api_key: 'b_123',
39
+ endpoint: 'endpoint',
40
+ sdkVersion: '3.5',
41
+ doNotLoadFontAwesome: true,
42
+ subscriptions: [
43
+ {
44
+ partnerAction: 'updateUserProfile',
45
+ name: 'Log User',
46
+ enabled: true,
47
+ subscribe: 'type = "identify"',
48
+ mapping: {
49
+ external_id: {
50
+ '@path': '$.traits.external_id'
51
+ }
52
+ }
53
+ }
54
+ ]
55
+ })
56
+
57
+ await event.load(Context.system(), new Analytics({ writeKey: '123' }))
58
+ await event.identify?.(
59
+ new Context({
60
+ type: 'identify',
61
+ traits: {
62
+ external_id: 'xt_123'
63
+ }
64
+ })
65
+ )
66
+
67
+ expect(destination.actions.updateUserProfile.perform).toHaveBeenCalledWith(
68
+ expect.objectContaining({
69
+ instance: expect.objectContaining({
70
+ changeUser: expect.any(Function)
71
+ })
72
+ }),
73
+
74
+ expect.objectContaining({
75
+ payload: { external_id: 'xt_123' }
76
+ })
77
+ )
78
+ })
79
+
80
+ test('can change user traits', async () => {
81
+ const [event] = await brazeDestination({
82
+ api_key: 'b_123',
83
+ endpoint: 'endpoint',
84
+ sdkVersion: '3.5',
85
+ doNotLoadFontAwesome: true,
86
+ subscriptions
87
+ })
88
+
89
+ await event.load(Context.system(), {} as Analytics)
90
+ await event.identify?.(
91
+ new Context({
92
+ type: 'identify',
93
+ traits: {
94
+ external_id: 'xt_123',
95
+ country: 'BRA',
96
+ current_location: {
97
+ latitude: -23.54,
98
+ longitude: -46.65
99
+ },
100
+ custom_attributes: {
101
+ greeting: 'oi'
102
+ },
103
+ dob: '01/01/2000',
104
+ email: 'foo@example.org',
105
+ email_subscribe: true,
106
+ first_name: 'Foo',
107
+ gender: 'M',
108
+ home_city: 'Miami',
109
+ image_url: 'img_url',
110
+ language: 'english',
111
+ last_name: 'Bar',
112
+ phone: '555 5555',
113
+ push_subscribe: true
114
+ }
115
+ })
116
+ )
117
+
118
+ expect(destination.actions.updateUserProfile.perform).toHaveBeenCalledWith(
119
+ expect.objectContaining({
120
+ instance: expect.objectContaining({
121
+ changeUser: expect.any(Function)
122
+ })
123
+ }),
124
+
125
+ expect.objectContaining({
126
+ payload: {
127
+ country: 'BRA',
128
+ current_location: { latitude: -23.54, longitude: -46.65 },
129
+ custom_attributes: { greeting: 'oi' },
130
+ dob: '01/01/2000',
131
+ email: 'foo@example.org',
132
+ email_subscribe: true,
133
+ first_name: 'Foo',
134
+ gender: 'M',
135
+ home_city: 'Miami',
136
+ image_url: 'img_url',
137
+ language: 'english',
138
+ last_name: 'Bar',
139
+ phone: '555 5555',
140
+ push_subscribe: true
141
+ }
142
+ })
143
+ )
144
+ })
145
+ })
@@ -0,0 +1,9 @@
1
+ import type braze from '@braze/web-sdk'
2
+ import type appboy from '@braze/web-sdk-v3'
3
+
4
+ export type BrazeType = typeof braze | typeof appboy
5
+
6
+ export type BrazeDestinationClient = {
7
+ instance: BrazeType
8
+ ready: () => boolean
9
+ }
@@ -0,0 +1,3 @@
1
+ // Generated file. DO NOT MODIFY IT BY HAND.
2
+
3
+ export interface Payload {}
@@ -0,0 +1,67 @@
1
+ import { BrazeDestinationClient } from '../braze-types'
2
+ import type { ID, SegmentEvent, User } from '@segment/analytics-next'
3
+ import type { BrowserActionDefinition } from '@segment/browser-destination-runtime/types'
4
+ import type { Settings } from '../generated-types'
5
+ import type { Payload } from './generated-types'
6
+
7
+ type CachedUser = {
8
+ id: ID
9
+ anonymousId: ID
10
+ traits: ReturnType<User['traits']> | null
11
+ }
12
+
13
+ let cachedUser: CachedUser = {
14
+ id: undefined,
15
+ anonymousId: undefined,
16
+ traits: null
17
+ }
18
+
19
+ export function resetUserCache() {
20
+ cachedUser = {
21
+ id: undefined,
22
+ anonymousId: undefined,
23
+ traits: null
24
+ }
25
+ }
26
+
27
+ function shouldSendToBraze(event: SegmentEvent) {
28
+ if (event.userId && event.userId !== cachedUser.id) {
29
+ return true
30
+ }
31
+
32
+ if (event.anonymousId && event.anonymousId !== cachedUser.anonymousId) {
33
+ return true
34
+ }
35
+
36
+ const traits = event.traits ?? {}
37
+ return JSON.stringify(cachedUser.traits) !== JSON.stringify(traits)
38
+ }
39
+
40
+ const action: BrowserActionDefinition<Settings, BrazeDestinationClient, Payload> = {
41
+ title: 'Debounce Middleware',
42
+ description:
43
+ 'When enabled, it ensures that only events where at least one changed trait value are sent to Braze, and events with duplicate traits are not sent. Debounce functionality requires a frontend client to work. Therefore, it cannot be used with server-side libraries or with Engage.',
44
+ platform: 'web',
45
+ defaultSubscription: 'type = "identify" or type = "group"',
46
+ fields: {},
47
+ lifecycleHook: 'before',
48
+ perform: (_client, data) => {
49
+ const event = data.context.event
50
+ const analyticsUser = data.analytics.user()
51
+ const ctx = data.context
52
+
53
+ // Only send the event to Braze if a trait has changed
54
+ // Target all possible Braze integration names
55
+ const shouldSend = shouldSendToBraze(event)
56
+ ctx.updateEvent('integrations.Braze Web Mode (Actions)', shouldSend)
57
+ ctx.updateEvent('integrations.Braze Cloud Mode (Actions)', shouldSend)
58
+ ctx.updateEvent('integrations.Appboy', shouldSend)
59
+
60
+ // Ensure analytics.user is defined
61
+ cachedUser.id = analyticsUser.id()
62
+ cachedUser.anonymousId = analyticsUser.anonymousId()
63
+ cachedUser.traits = analyticsUser.traits()
64
+ }
65
+ }
66
+
67
+ export default action
@@ -0,0 +1,104 @@
1
+ // Generated file. DO NOT MODIFY IT BY HAND.
2
+
3
+ export interface Settings {
4
+ /**
5
+ * The version of the Braze SDK to use
6
+ */
7
+ sdkVersion: string
8
+ /**
9
+ * Found in the Braze Dashboard under Manage Settings → Apps → Web
10
+ */
11
+ api_key: string
12
+ /**
13
+ * Your Braze SDK endpoint. [See more details](https://www.braze.com/docs/user_guide/administrative/access_braze/sdk_endpoints/)
14
+ */
15
+ endpoint: string
16
+ /**
17
+ * Allow Braze to log activity from crawlers. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)
18
+ */
19
+ allowCrawlerActivity?: boolean
20
+ /**
21
+ * To indicate that you trust the Braze dashboard users to write non-malicious Javascript click actions, set this property to true. If enableHtmlInAppMessages is true, this option will also be set to true. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)
22
+ */
23
+ allowUserSuppliedJavascript?: boolean
24
+ /**
25
+ * If enabled, this setting delays initialization of the Braze SDK until the user has been identified. When enabled, events for anonymous users will no longer be sent to Braze.
26
+ */
27
+ deferUntilIdentified?: boolean
28
+ /**
29
+ * Version to which user events sent to Braze will be associated with. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)
30
+ */
31
+ appVersion?: string
32
+ /**
33
+ * Allows Braze to add the nonce to any <script> and <style> elements created by the SDK. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)
34
+ */
35
+ contentSecurityNonce?: string
36
+ /**
37
+ * By default, the Braze SDK automatically detects and collects all device properties in DeviceProperties. To override this behavior, provide an array of DeviceProperties. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)
38
+ */
39
+ devicePropertyAllowlist?: string[]
40
+ /**
41
+ * By default, users who have already granted web push permission will sync their push token with the Braze backend automatically on new session to ensure deliverability. To disable this behavior, set this option to true
42
+ */
43
+ disablePushTokenMaintenance?: boolean
44
+ /**
45
+ * Braze automatically loads FontAwesome 4.7.0 from the FontAwesome CDN. To disable this behavior set this option to true.
46
+ */
47
+ doNotLoadFontAwesome?: boolean
48
+ /**
49
+ * Set to true to enable logging by default
50
+ */
51
+ enableLogging?: boolean
52
+ /**
53
+ * Set to true to enable the SDK Authentication feature.
54
+ */
55
+ enableSdkAuthentication?: boolean
56
+ /**
57
+ * By default, the Braze SDK will show In-App Messages with a z-index of 1040 for the screen overlay, 1050 for the actual in-app message, and 1060 for the message's close button. Provide a value for this option to override these default z-indexes.
58
+ */
59
+ inAppMessageZIndex?: number
60
+ /**
61
+ * By default, any SDK-generated user-visible messages will be displayed in the user's browser language. Provide a value for this option to override that behavior and force a specific language. The value for this option should be a ISO 639-1 Language Code.
62
+ */
63
+ localization?: string
64
+ /**
65
+ * When this is enabled, all In-App Messages that a user is eligible for are automatically delivered to the user. If you'd like to register your own display subscribers or send soft push notifications to your users, make sure to disable this option.
66
+ */
67
+ automaticallyDisplayMessages?: boolean
68
+ /**
69
+ * If you have your own service worker that you register and control the lifecycle of, set this option to true and the Braze SDK will not register or unregister a service worker. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)
70
+ */
71
+ manageServiceWorkerExternally?: boolean
72
+ /**
73
+ * Provide a value to override the default interval between trigger actions with a value of your own. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)
74
+ */
75
+ minimumIntervalBetweenTriggerActionsInSeconds?: number
76
+ /**
77
+ * By default, the Braze SDK will store small amounts of data (user ids, session ids), in cookies. Pass true for this option to disable cookie storage and rely entirely on HTML 5 localStorage to identify users and sessions. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)
78
+ */
79
+ noCookies?: boolean
80
+ /**
81
+ * By default, links from Card objects load in the current tab or window. Set this option to true to make links from cards open in a new tab or window.
82
+ */
83
+ openCardsInNewTab?: boolean
84
+ /**
85
+ * By default, links from in-app message clicks load in the current tab or a new tab as specified in the dashboard on a message-by-message basis. Set this option to true to force all links from in-app message clicks open in a new tab or window.
86
+ */
87
+ openInAppMessagesInNewTab?: boolean
88
+ /**
89
+ * By default, when an in-app message is showing, pressing the escape button or a click on the greyed-out background of the page will dismiss the message. Set this option to true to prevent this behavior and require an explicit button click to dismiss messages.
90
+ */
91
+ requireExplicitInAppMessageDismissal?: boolean
92
+ /**
93
+ * If you support Safari push, you must specify this option with the website push ID that you provided to Apple when creating your Safari push certificate (starts with "web", e.g. "web.com.example.domain").
94
+ */
95
+ safariWebsitePushId?: string
96
+ /**
97
+ * By default, when registering users for web push notifications Braze will look for the required service worker file in the root directory of your web server at /service-worker.js. If you want to host your service worker at a different path on that server, provide a value for this option that is the absolute path to the file, e.g. /mycustompath/my-worker.js. VERY IMPORTANT: setting a value here limits the scope of push notifications on your site. For instance, in the above example, because the service ,worker file is located within the /mycustompath/ directory, appboy.registerAppboyPushMessages MAY ONLY BE CALLED from web pages that start with http://yoursite.com/mycustompath/.
98
+ */
99
+ serviceWorkerLocation?: string
100
+ /**
101
+ * By default, sessions time out after 30 minutes of inactivity. Provide a value for this configuration option to override that default with a value of your own.
102
+ */
103
+ sessionTimeoutInSeconds?: number
104
+ }