Skip to content

Commit

Permalink
Merge pull request #188 from CleverTap/task/SDK-3413/remote_config
Browse files Browse the repository at this point in the history
Feature: Product Experiences
  • Loading branch information
KambleSonam authored Mar 22, 2024
2 parents cf915cd + 976630a commit 63ee89c
Show file tree
Hide file tree
Showing 20 changed files with 3,168 additions and 785 deletions.
2,524 changes: 2,017 additions & 507 deletions clevertap.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion clevertap.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion clevertap.min.js

Large diffs are not rendered by default.

627 changes: 480 additions & 147 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "clevertap-web-sdk",
"version": "1.6.10",
"version": "1.7.0",
"description": "",
"main": "clevertap.js",
"scripts": {
Expand Down Expand Up @@ -28,6 +28,7 @@
"@babel/eslint-parser": "^7.12.1",
"@babel/plugin-proposal-class-properties": "^7.10.4",
"@babel/plugin-proposal-private-methods": "^7.12.1",
"@babel/plugin-transform-runtime": "^7.23.7",
"@babel/preset-env": "^7.11.0",
"@rollup/plugin-babel": "^5.2.0",
"@rollup/plugin-node-resolve": "^9.0.0",
Expand All @@ -44,5 +45,8 @@
"rollup-plugin-eslint": "^7.0.0",
"rollup-plugin-sourcemaps": "^0.6.3",
"rollup-plugin-terser": "^7.0.2"
},
"dependencies": {
"regenerator-runtime": "^0.14.1"
}
}
59 changes: 49 additions & 10 deletions src/clevertap.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ import {
COMMAND_ADD,
COMMAND_REMOVE,
COMMAND_DELETE,
EVT_PUSH
EVT_PUSH,
WZRK_FETCH
} from './util/constants'
import { EMBED_ERROR } from './util/messages'
import { StorageManager, $ct } from './util/storage'
Expand All @@ -37,6 +38,8 @@ import { compressData } from './util/encoder'
import Privacy from './modules/privacy'
import NotificationHandler from './modules/notification'
import { hasWebInboxSettingsInLS, checkAndRegisterWebInboxElements, initializeWebInbox, getInboxMessages, saveInboxMessages } from './modules/web-inbox/helper'
import { Variable } from './modules/variables/variable'
import VariableStore from './modules/variables/variableStore'

export default class CleverTap {
#logger
Expand All @@ -46,6 +49,7 @@ export default class CleverTap {
#session
#account
#request
#variableStore
#isSpa
#previousUrl
#boundCheckPageChanged = this.#checkPageChanged.bind(this)
Expand Down Expand Up @@ -84,7 +88,7 @@ export default class CleverTap {
this._isPersonalisationActive = this._isPersonalisationActive.bind(this)
this.raiseNotificationClicked = () => { }
this.#logger = new Logger(logLevels.INFO)
this.#account = new Account(clevertap.account?.[0], clevertap.region || clevertap.account?.[1], clevertap.targetDomain || clevertap.account?.[2])
this.#account = new Account(clevertap.account?.[0], clevertap.region || clevertap.account?.[1], clevertap.targetDomain || clevertap.account?.[2], clevertap.token || clevertap.account?.[3])
this.#device = new DeviceManager({ logger: this.#logger })
this.#dismissSpamControl = clevertap.dismissSpamControl || false
this.#session = new SessionManager({
Expand Down Expand Up @@ -132,6 +136,13 @@ export default class CleverTap {
account: this.#account
}, clevertap.notifications)

this.#variableStore = new VariableStore({
logger: this.#logger,
request: this.#request,
account: this.#account,
event: this.event
})

this.#api = new CleverTapAPI({
logger: this.#logger,
request: this.#request,
Expand Down Expand Up @@ -567,7 +578,7 @@ export default class CleverTap {
}

// starts here
init (accountId, region, targetDomain) {
init (accountId, region, targetDomain, token) {
if (this.#onloadcalled === 1) {
// already initailsed
return
Expand All @@ -588,6 +599,9 @@ export default class CleverTap {
if (targetDomain) {
this.#account.targetDomain = targetDomain
}
if (token) {
this.#account.token = token
}

const currLocation = location.href
const urlParams = getURLParams(currLocation.toLowerCase())
Expand Down Expand Up @@ -630,7 +644,7 @@ export default class CleverTap {
this.notifications._processOldValues()
}

debounce (func, delay) {
#debounce (func, delay = 300) {
let timeout
return function () {
clearTimeout(timeout)
Expand All @@ -639,11 +653,11 @@ export default class CleverTap {
}

#checkPageChanged () {
const debouncedPageChanged = this.debounce(() => {
const debouncedPageChanged = this.#debounce(() => {
if (this.#previousUrl !== location.href) {
this.pageChanged()
}
}, 300)
})
debouncedPageChanged()
}

Expand Down Expand Up @@ -704,14 +718,15 @@ export default class CleverTap {
if (parseInt(data.pg) === 1) {
this.#overrideDSyncFlag(data)
}
let proto = document.location.protocol
proto = proto.replace(':', '')
data.af = { lib: 'web-sdk-v$$PACKAGE_VERSION$$', protocol: proto, ...$ct.flutterVersion }
pageLoadUrl = addToURL(pageLoadUrl, 'type', 'page')
pageLoadUrl = addToURL(pageLoadUrl, 'd', compressData(JSON.stringify(data), this.#logger))

this.#request.saveAndFireRequest(pageLoadUrl, $ct.blockRequest)

if (parseInt(data.pg) === 1) {
this.event.push(WZRK_FETCH, { t: 4 })
}

this.#previousUrl = currLocation
setTimeout(() => {
if (pgCount <= 3) {
Expand Down Expand Up @@ -782,7 +797,7 @@ export default class CleverTap {
if ($ct.location) {
data.af = { ...data.af, ...$ct.location }
}
data = this.#request.addSystemDataToProfileObject(data, undefined)
data = this.#request.addSystemDataToObject(data, undefined)
this.#request.addFlags(data)
const compressedData = compressData(JSON.stringify(data), this.#logger)
let pageLoadUrl = this.#account.dataPostURL
Expand Down Expand Up @@ -811,4 +826,28 @@ export default class CleverTap {
this.#request.processBackupEvents()
}
}

defineVariable (name, defaultValue) {
return Variable.define(name, defaultValue, this.#variableStore)
}

async syncVariables (onSyncSuccess, onSyncFailure) {
if (this.#logger.logLevel === 4) {
return this.#variableStore.syncVariables(onSyncSuccess, onSyncFailure)
} else {
this.#logger.error('App log level is not set to 4')
}
}

async fetchVariables (onFetchCallback) {
return this.#variableStore.fetchVariables(onFetchCallback)
}

addVariablesChangedCallback (callback) {
this.#variableStore.addVariablesChangedCallback(callback)
}

addOneTimeVariablesChangedCallback (callback) {
this.#variableStore.addOneTimeVariablesChangedCallback(callback)
}
}
1 change: 1 addition & 0 deletions src/main.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'regenerator-runtime/runtime.js'
import Clevertap from './clevertap'

const clevertap = new Clevertap(window.clevertap)
Expand Down
18 changes: 17 additions & 1 deletion src/modules/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@ export default class Account {
#region = ''
#targetDomain = TARGET_DOMAIN
#dcSdkversion = ''
#token = ''

constructor ({ id } = {}, region = '', targetDomain = TARGET_DOMAIN) {
constructor ({ id } = {}, region = '', targetDomain = TARGET_DOMAIN, token = '') {
this.id = id
if (region) {
this.region = region
}
if (targetDomain) {
this.targetDomain = targetDomain
}
if (token) {
this.token = token
}
}

get id () {
Expand Down Expand Up @@ -48,6 +52,14 @@ export default class Account {
this.#targetDomain = targetDomain
}

get token () {
return this.#token
}

set token (token) {
this.#token = token
}

get finalTargetDomain () {
if (this.region) {
return `${this.region}.${this.targetDomain}`
Expand All @@ -59,6 +71,10 @@ export default class Account {
}
}

get dataPostPEURL () {
return `${TARGET_PROTOCOL}//${this.finalTargetDomain}/defineVars`
}

get dataPostURL () {
return `${TARGET_PROTOCOL}//${this.finalTargetDomain}/a?t=96`
}
Expand Down
9 changes: 8 additions & 1 deletion src/modules/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ export const logLevels = {
DISABLE: 0,
ERROR: 1,
INFO: 2,
DEBUG: 3
DEBUG: 3,
DEBUG_PE: 4
}

export class Logger {
Expand Down Expand Up @@ -43,6 +44,12 @@ export class Logger {
}
}

debugPE (message) {
if (this.#logLevel >= logLevels.DEBUG_PE) {
this.#log('debug_pe', message)
}
}

reportError (code, description) {
this.wzrkError.c = code
this.wzrkError.d = description
Expand Down
5 changes: 2 additions & 3 deletions src/modules/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export default class ProfileHandler extends Array {
profileObj.tz = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]
}
data.profile = profileObj
data = this.#request.addSystemDataToProfileObject(data, undefined)
data = this.#request.addSystemDataToObject(data, undefined)

this.#request.addFlags(data)
const compressedData = compressData(JSON.stringify(data), this.#logger)
Expand Down Expand Up @@ -212,7 +212,6 @@ export default class ProfileHandler extends Array {
if (typeof propVal === 'string' || typeof propVal === 'number') {
if ($ct.globalProfileMap.hasOwnProperty(propKey)) {
array = $ct.globalProfileMap[propKey]
// Push the value to the array in a more concise way
array.push(typeof propVal === 'number' ? propVal : propVal.toLowerCase())
} else {
$ct.globalProfileMap[propKey] = propVal
Expand Down Expand Up @@ -310,7 +309,7 @@ export default class ProfileHandler extends Array {
profileObj.tz = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]
}
data.profile = profileObj
data = this.#request.addSystemDataToProfileObject(data, undefined)
data = this.#request.addSystemDataToObject(data, undefined)
this.#request.addFlags(data)
const compressedData = compressData(JSON.stringify(data), this.#logger)
let pageLoadUrl = this.#account.dataPostURL
Expand Down
50 changes: 27 additions & 23 deletions src/modules/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export default class RequestManager {

RequestDispatcher.logger = logger
RequestDispatcher.device = device
RequestDispatcher.account = account
}

processBackupEvents () {
Expand Down Expand Up @@ -72,26 +73,9 @@ export default class RequestManager {
const obj = this.#session.getSessionCookieObject()
dataObject.s = obj.s // session cookie
dataObject.pg = (typeof obj.p === 'undefined') ? 1 : obj.p // Page count
if (sessionStorage.hasOwnProperty('WZRK_D')) { dataObject.debug = true }

return dataObject
}

addSystemDataToProfileObject (dataObject, ignoreTrim) {
if (!isObjectEmpty(this.#logger.wzrkError)) {
dataObject.wzrk_error = this.#logger.wzrkError
this.#logger.wzrkError = {}
}

dataObject.id = this.#account.id

if (isValueValid(this.#device.gcookie)) {
dataObject.g = this.#device.gcookie
}

const obj = this.#session.getSessionCookieObject()
dataObject.s = obj.s // session cookie
dataObject.pg = (typeof obj.p === 'undefined') ? 1 : obj.p // Page count
let proto = document.location.protocol
proto = proto.replace(':', '')
dataObject.af = { lib: 'web-sdk-v$$PACKAGE_VERSION$$', protocol: proto, ...$ct.flutterVersion } // app fields
if (sessionStorage.hasOwnProperty('WZRK_D')) { dataObject.debug = true }

return dataObject
Expand Down Expand Up @@ -128,7 +112,7 @@ export default class RequestManager {
* @param {boolean} override whether the request can go through or not
* @param {Boolean} sendOULFlag - true in case of a On User Login request
*/
saveAndFireRequest (url, override, sendOULFlag) {
saveAndFireRequest (url, override, sendOULFlag, evtName) {
const now = getNow()
url = addToURL(url, 'rn', ++$ct.globalCache.REQ_N)
const data = url + '&i=' + now + '&sn=' + seqNo
Expand All @@ -149,7 +133,7 @@ export default class RequestManager {
seqNo = 0
}
window.oulReqN = $ct.globalCache.REQ_N
RequestDispatcher.fireRequest(data, false, sendOULFlag)
RequestDispatcher.fireRequest(data, false, sendOULFlag, evtName)
} else {
this.#logger.debug(`Not fired due to override - ${$ct.blockRequest} or clearCookie - ${this.#clearCookie} or OUL request in progress - ${window.isOULInProgress}`)
}
Expand Down Expand Up @@ -205,7 +189,7 @@ export default class RequestManager {
pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH)
pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData)

this.saveAndFireRequest(pageLoadUrl, $ct.blockRequest)
this.saveAndFireRequest(pageLoadUrl, $ct.blockRequest, false, data.evtName)
}

#addToLocalEventMap (evtName) {
Expand All @@ -232,4 +216,24 @@ export default class RequestManager {
StorageManager.saveToLSorCookie(EV_COOKIE, $ct.globalEventsMap)
}
}

async post (url, body) {
try {
const response = await fetch(url, {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: body
})
if (response.ok) {
const data = await response.json()
this.#logger.debug('Sync data successful', data)
return data
} else {
throw response
}
} catch (e) {
this.#logger.debug('Error in syncing variables', e)
throw e
}
}
}
Loading

0 comments on commit 63ee89c

Please sign in to comment.