-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathbrowser.js
More file actions
398 lines (369 loc) · 15.4 KB
/
Copy pathbrowser.js
File metadata and controls
398 lines (369 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/* eslint-disable class-methods-use-this */
import { equals } from 'ramda';
import { NAME, DISPLAY_NAME } from './constants';
import { Storage } from '@rudderstack/analytics-js-legacy-utilities/storage';
import { stringifyWithoutCircularV1 } from '@rudderstack/analytics-js-legacy-utilities/ObjectUtils';
import Logger from '../../utils/logger';
import { isObject } from '../../utils/utils';
import { isNotEmpty } from '../../utils/commonUtils';
import { handlePurchase, formatGender, handleReservedProperties } from './utils';
import { getEcommerceMapping, buildEcommerceEventProperties } from './ecommerceUtil';
import { loadNativeSdk } from './nativeSdkLoader';
const logger = new Logger(DISPLAY_NAME);
/*
E-commerce support required for logPurchase support & other e-commerce events as track with productId changed
*/
class Braze {
constructor(config, analytics, destinationInfo) {
if (analytics.logLevel) {
logger.setLogLevel(analytics.logLevel);
}
this.analytics = analytics;
this.appIdentifierKey = config.appKey;
this.usePlatformSpecificApiKeys = config.usePlatformSpecificApiKeys === true;
this.trackAnonymousUser = config.trackAnonymousUser;
this.enableBrazeLogging = config.enableBrazeLogging || false;
this.allowUserSuppliedJavascript = config.allowUserSuppliedJavascript || false;
this.enablePushNotification = config.enablePushNotification || false;
if (!config.appKey) this.appIdentifierKey = '';
if (this.usePlatformSpecificApiKeys) {
if (config.webApiKey && typeof config.webApiKey === 'string') {
this.appIdentifierKey = config.webApiKey;
} else {
logger.warn(
`Configured to use platform-specific app identifier key but the web app identifier key (${config.webApiKey}) is not valid. Using the default app identifier key instead.`,
);
}
}
this.endPoint = '';
this.useRecommendedEcommerceEvents = config.useRecommendedEcommerceEvents || false;
this.isHybridModeEnabled = config.connectionMode === 'hybrid';
this.isReadyStatus = {
hasLoggedErrorForAlias: false,
};
this.sdkMetadataAdded = false;
if (config.dataCenter) {
// ref: https://www.braze.com/docs/user_guide/administrative/access_braze/braze_instances
const [dataCenterRegion, dataCenterNumber] = config.dataCenter
.trim()
.toLowerCase()
.split('-');
switch (dataCenterRegion) {
case 'eu':
this.endPoint = `sdk.fra-${dataCenterNumber}.braze.eu`;
break;
case 'us':
this.endPoint = `sdk.iad-${dataCenterNumber}.braze.com`;
break;
case 'au':
this.endPoint = `sdk.au-${dataCenterNumber}.braze.com`;
break;
default:
this.endPoint = `sdk.iad-${dataCenterNumber}.braze.com`;
break;
}
}
this.name = NAME;
this.supportDedup = config.supportDedup || false;
({
shouldApplyDeviceModeTransformation: this.shouldApplyDeviceModeTransformation,
propagateEventsUntransformedOnError: this.propagateEventsUntransformedOnError,
destinationId: this.destinationId,
} = destinationInfo ?? {});
}
logAliasError(message) {
if (!this.isReadyStatus.hasLoggedErrorForAlias) {
logger.error(message);
this.isReadyStatus.hasLoggedErrorForAlias = true;
}
}
addSdkMetadata() {
try {
globalThis.braze.addSdkMetadata([globalThis.braze.BrazeSdkMetadata.CDN]);
this.sdkMetadataAdded = true;
logger.debug('Successfully added Braze SDK metadata');
} catch (error) {
logger.error('Failed to add SDK metadata:', error);
}
}
init() {
loadNativeSdk();
globalThis.braze.initialize(this.appIdentifierKey, {
enableLogging: this.enableBrazeLogging,
baseUrl: this.endPoint,
allowUserSuppliedJavascript: this.allowUserSuppliedJavascript,
});
globalThis.braze.automaticallyShowInAppMessages();
const { userId } = this.analytics;
// send userId if you have it https://js.appboycdn.com/web-sdk/latest/doc/module-appboy.html#.changeUser
if (userId) {
globalThis.braze.changeUser(userId);
}
if (this.enablePushNotification) {
globalThis.braze.requestPushPermission();
}
globalThis.braze.openSession();
}
isLoaded() {
return globalThis.brazeQueue === null;
}
setUserAlias() {
try {
const anonymousId = this.analytics.getAnonymousId();
if (!anonymousId) {
this.logAliasError('Anonymous ID is not available');
return false;
}
const user = globalThis.braze.getUser();
if (!user) {
this.logAliasError('Braze user object is not available');
return false;
}
const aliasSet = user.addAlias(anonymousId, 'rudder_id');
if (!aliasSet) {
this.logAliasError('Failed to set alias for braze');
return false;
}
// Immediately flush the alias to prevent race conditions with cloud mode events
// This ensures the alias is sent immediately instead of waiting for the regular
// interval (10 seconds with localStorage, 3 seconds without)
try {
if (globalThis.braze && typeof globalThis.braze.requestImmediateDataFlush === 'function') {
globalThis.braze.requestImmediateDataFlush();
logger.debug('Braze alias flushed immediately to prevent race conditions');
} else {
logger.warn('Braze requestImmediateDataFlush method not available');
}
} catch (flushError) {
logger.warn('Failed to flush Braze alias immediately:', flushError);
// Don't fail the entire operation if flush fails
}
return true;
} catch (error) {
this.logAliasError(`Error setting alias: ${stringifyWithoutCircularV1(error, true)}`);
return false;
}
}
isReady() {
if (!this.isLoaded()) {
return false;
}
// Add SDK metadata when the integration becomes ready (only once)
if (!this.sdkMetadataAdded) {
this.addSdkMetadata();
}
return this.setUserAlias();
}
/**
* As each users will have unique session, So if the supportDedup is enabled from config,
* then we are comparing from the previous payload and tried to reduce the redundant data.
* If supportDedup is enabled,
* Examples:
* - If userId is different from previous call, then it will make new call and store the payload.
* - It will deeply check all other attributes and pass the unique or changed fields.
* 1st- payload 2nd- payload
* rudderanalytics.identify("rudderUserId100", { rudderanalytics.identify("rudderUserId100", {
* name: "Rudder Keener", name: "Rudder Keener",
* email: "rudder100@example.com", email: "rudder100@example.com",
* primaryEmail: "test350@email.com", primaryEmail: "test350@email.com",
* country: "USA", country: "USA",
* subscription: "youtube-prime-6", subscription: "youtube-prime-6",
* channelName: ["b", "d", "e", "f"], channelName: ["b", "d", "e", "f"],
* gender: "male", gender: "male",
* facebook: "https://www.facebook.com/rudder.123", facebook: "https://www.facebook.com/rudder.345",
* birthday: new Date("2000-10-23"), birthday: new Date("2000-10-24"),
* firstname: "Rudder", firstname: "Rudder",
* lastname: "Keener", lastname: "Usertest",
* phone: "9112345631", phone: "9112345631",
* key1: "value4", key1: "value5",
* address: { address: {
* city: "Manali", city: "Shimla",
* country: "India", country: "India",
* }, },
* }); });
* As both payload have same userId so it will deeply check all other attributes and pass the unique fields
* or the updated fields.
* @param {*} rudderElement
*/
// eslint-disable-next-line sonarjs/cognitive-complexity
identify(rudderElement) {
const { message } = rudderElement;
const { userId } = message;
if (this.isHybridModeEnabled) {
if (userId) {
globalThis.braze.changeUser(userId);
}
return;
}
const { context } = message;
const email = context?.traits?.email;
const firstName = context?.traits?.firstName || context?.traits?.firstname;
const lastName = context?.traits?.lastName || context?.traits?.lastname;
const gender = context?.traits?.gender;
const phone = context?.traits?.phone;
const address = context?.traits?.address;
const birthday = context?.traits?.birthday || context?.traits?.dob;
const reserved = [
'address',
'birthday',
'email',
'id',
'firstname',
'firstName',
'gender',
'lastname',
'lastName',
'phone',
'dob',
'birthday',
'external_id',
'country',
'home_city',
'email_subscribe',
'push_subscribe',
];
// function set Address
function setAddress() {
globalThis.braze.getUser().setCountry(address?.country);
globalThis.braze.getUser().setHomeCity(address?.city);
}
// function set Birthday
function setBirthday() {
try {
const date = new Date(birthday);
if (date.toString() === 'Invalid Date') {
logger.error('Invalid Date for birthday');
return;
}
globalThis.braze
.getUser()
.setDateOfBirth(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate());
} catch (error) {
logger.error(`Error in setting birthday - ${stringifyWithoutCircularV1(error, true)}`);
}
}
// function set Email
function setEmail() {
globalThis.braze.getUser().setEmail(email);
}
// function set firstName
function setFirstName() {
globalThis.braze.getUser().setFirstName(firstName);
}
// function set gender
function setGender(genderName) {
globalThis.braze.getUser().setGender(genderName);
}
// function set lastName
function setLastName() {
globalThis.braze.getUser().setLastName(lastName);
}
function setPhone() {
globalThis.braze.getUser().setPhoneNumber(phone);
}
// eslint-disable-next-line unicorn/consistent-destructuring
const traits = message?.context?.traits;
const previousPayload = Storage.getItem('rs_braze_dedup_attributes') || {};
if (this.supportDedup && isNotEmpty(previousPayload) && userId === previousPayload?.userId) {
const prevTraits = previousPayload?.context?.traits;
const prevAddress = prevTraits?.address;
const prevBirthday = prevTraits?.birthday || prevTraits?.dob;
const prevEmail = prevTraits?.email;
const prevFirstname = prevTraits?.firstname || prevTraits?.firstName;
const prevGender = prevTraits?.gender;
const prevLastname = prevTraits?.lastname || prevTraits?.lastName;
const prevPhone = prevTraits?.phone;
if (email && email !== prevEmail) setEmail();
if (phone && phone !== prevPhone) setPhone();
if (birthday && !equals(birthday, prevBirthday)) setBirthday();
if (firstName && firstName !== prevFirstname) setFirstName();
if (lastName && lastName !== prevLastname) setLastName();
if (gender && formatGender(gender) !== formatGender(prevGender))
setGender(formatGender(gender));
if (address && !equals(address, prevAddress)) setAddress();
if (isObject(traits)) {
Object.keys(traits)
.filter(key => reserved.indexOf(key) === -1)
.forEach(key => {
if (!prevTraits[key] || !equals(prevTraits[key], traits[key])) {
globalThis.braze.getUser().setCustomUserAttribute(key, traits[key]);
}
});
}
} else {
globalThis.braze.changeUser(userId);
// method removed from v4 https://www.braze.com/docs/api/objects_filters/user_attributes_object#braze-user-profile-fields
// globalThis.braze.getUser().setAvatarImageUrl(avatar);
if (email) setEmail();
if (firstName) setFirstName();
if (lastName) setLastName();
if (gender) setGender(formatGender(gender));
if (phone) setPhone();
if (address) setAddress();
if (birthday) setBirthday();
if (isObject(traits)) {
Object.keys(traits)
.filter(key => reserved.indexOf(key) === -1)
.forEach(key => {
globalThis.braze.getUser().setCustomUserAttribute(key, traits[key]);
});
}
}
if (
this.supportDedup &&
isObject(previousPayload) &&
isNotEmpty(previousPayload) &&
userId === previousPayload?.userId
) {
Storage.setItem('rs_braze_dedup_attributes', { ...previousPayload, ...message });
} else if (this.supportDedup) {
Storage.setItem('rs_braze_dedup_attributes', message);
}
}
track(rudderElement) {
if (this.isHybridModeEnabled) {
return;
}
const eventName = rudderElement.message.event;
let { properties } = rudderElement.message;
const { userId } = rudderElement.message;
let canSendCustomEvent = false;
if (userId || this.trackAnonymousUser) {
canSendCustomEvent = true;
}
if (eventName && canSendCustomEvent) {
const ecommerceMapping = this.useRecommendedEcommerceEvents
? getEcommerceMapping(eventName)
: undefined;
if (ecommerceMapping) {
const { brazeEvent, action } = ecommerceMapping;
const ecommerceProperties = buildEcommerceEventProperties(
rudderElement.message,
brazeEvent,
action,
logger,
);
globalThis.braze.logCustomEvent(brazeEvent, ecommerceProperties);
} else if (eventName.toLowerCase() === 'order completed') {
handlePurchase(properties);
} else {
properties = handleReservedProperties(properties);
globalThis.braze.logCustomEvent(eventName, properties);
}
}
}
page(rudderElement) {
if (this.isHybridModeEnabled) {
return;
}
const eventName = rudderElement.message.name;
let { properties } = rudderElement.message;
properties = handleReservedProperties(properties);
if (eventName) {
globalThis.braze.logCustomEvent(eventName, properties);
} else {
globalThis.braze.logCustomEvent('Page View', properties);
}
}
}
export default Braze;