All files segmentWrapper.js

91.43% Statements 32/35
70% Branches 7/10
84.62% Functions 11/13
96.88% Lines 31/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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              3x   3x                     3x               26x                   3x                 26x 26x                       3x 26x   26x         26x                     3x 26x   26x           26x                                                     3x 26x 26x 26x 26x         26x 26x 26x   26x 25x           26x                       3x                       3x 4x 4x               3x      
import {syncPixels} from './syncPixels'
import {getPageReferrer, updatePageReferrer} from './referrer'
import {getConfig} from './config'
import {getAdobeMCVisitorID} from './adobeRepository.js'
import {checkGdprIsAccepted, getGdprPrivacyValue} from './tcf'
 
/* Default properties to be sent on all trackings */
const DEFAULT_PROPERTIES = {platform: 'web'}
/* Disabled integrations when no GDPR Privacy Value is true */
export const INTEGRATIONS_WHEN_NO_CONSENTS = {
  'Amazon Lambda': false,
  'Amazon S3': false,
  Braze: false,
  'Facebook Pixel': false,
  'Google Ads (Gtag)': false,
  'Optimizely Full Stack': false,
  'Optimizely Web': false,
  Webhooks: false
}
/* ServerSide Forwarding values */
const SSF = {enabled: 0, disabled: 1}
/* Static anonymousId for users that has not accepted consents */
// const SEGMENT_ID_USER_WITHOUT_CONSENTS = 'id_user_consent_not_agree'
 
/**
 * Get default properties using the constant and the window.__mpi object if available
 * @returns {{[key:string]: any}} Default properties to attach to track
 */
export const getDefaultProperties = () => ({
  ...DEFAULT_PROPERTIES,
  ...getConfig('defaultProperties')
})
 
/**
 * Get user traits from global analytics object and put in the object
 * @param {string} gdprPrivacyValue Determine if we have user consents
 * @returns {object} User traits with to add
 */
const getUserTraits = gdprPrivacyValue => {
  // TODO: Disabled for now
  // If user has not accepted GDPR then we should use a static anonymousId
  // if (checkGdprIsAccepted(gdprPrivacyValue)) {
  //   return {
  //     anonymousId: SEGMENT_ID_USER_WITHOUT_CONSENTS
  //   }
  // }
  // If we have user consents, then create the user using anonymousId cookie
  const user = window.analytics.user()
  return {
    anonymousId: user.anonymousId(),
    userId: user.id()
  }
}
 
/**
 * Get all needed integrations depending on the gdprPrivacy value.
 * One of them is the AdobeMarketingCloudVisitorId for Adobe Analytics integration.
 * @param {string} gdprPrivacyValue Tell if user has consents to be tracked
 * @returns {Promise<object>} Integrations that we need to use on the track
 */
const getTrackIntegrations = async gdprPrivacyValue => {
  const marketingCloudVisitorId = await getAdobeMCVisitorID()
 
  const restOfIntegrations = checkGdprIsAccepted(gdprPrivacyValue)
    ? {}
    : INTEGRATIONS_WHEN_NO_CONSENTS
 
  // if we don't have the user consents we remove all the integrations but Adobe Analytics
  return {
    'Adobe Analytics': {marketingCloudVisitorId},
    ...restOfIntegrations
  }
}
 
/**
 * Get data like traits and integrations to be added to the context object
 * @param {object} context Context object with all the actual info
 * @returns {Promise<object>} New context with all the previous info and the new one
 */
export const decorateContextWithNeededData = async (context = {}) => {
  const gdprPrivacyValue = await getGdprPrivacyValue()
 
  const [integrations, isDMPReady = true] = await Promise.all([
    getTrackIntegrations(gdprPrivacyValue)
    // TODO: Blocking check of DMP is disabled for now
    // checkIsDMPReady()
  ])
 
  return {
    ...context,
    gdpr_privacy: gdprPrivacyValue,
    integrations: {
      ...context.integrations,
      ...integrations
    },
    page: {
      ...context.page,
      referrer: getPageReferrer()
    },
    traits: {
      ...context.traits,
      ssf: isDMPReady ? SSF.enabled : SSF.disabled,
      ...getUserTraits(gdprPrivacyValue)
    }
  }
}
 
/**
 * The track method lets you record any actions your users perform.
 * @param {string} event The name of the event you’re tracking
 * @param {object} [properties] A dictionary of properties for the event.
 * @param {object} [context] A dictionary of options.
 * @param {function} [callback] A function executed after a short timeout, giving the browser time to make outbound requests first.
 * @returns {Promise}
 */
const track = (event, properties, context = {}, callback) =>
  new Promise((resolve, reject) => {
    window.analytics.ready(async function() {
      const newContext = await decorateContextWithNeededData(context)
      const newProperties = {
        ...getDefaultProperties(),
        ...properties
      }
 
      const newCallback = (...args) => {
        Iif (callback) callback(...args) // eslint-disable-line standard/no-callback-literal
        getAdobeMCVisitorID()
          .then(marketingCloudVisitorId =>
            syncPixels(marketingCloudVisitorId).then(() => {
              resolve(...args)
            })
          )
          .catch(reject)
      }
 
      window.analytics.track(event, newProperties, newContext, newCallback)
    })
  })
 
/**
 * Associate your users and their actions to a recognizable userId and traits.
 * @param {string} userId Id to identify the user.
 * @param {object} traits A dictionary of traits you know about the user, like their email or name.
 * @param {object} [options] A dictionary of options.
 * @param {function} [callback] A function executed after a short timeout, giving the browser time to make outbound requests first.
 * @returns {Promise}
 */
const identify = (userId, traits, options, callback) =>
  Promise.resolve(window.analytics.identify(userId, traits, options, callback))
 
/**
 * Record whenever a user sees a page of your website, along with any optional properties about the page.
 * It updates automatically the referrer from the context on SPA navigations.
 * @param {string} event The name of the event you’re tracking
 * @param {object} properties A dictionary of properties for the event.
 * @param {object} [context] A dictionary of options.
 * @param {function} [callback] A function executed after a short timeout, giving the browser time to make outbound requests first.
 * @returns {Promise}
 */
const page = (event, properties, context = {}, callback) => {
  updatePageReferrer()
  return track(event, properties, context, callback)
}
 
/**
 * Resets the id, including anonymousId, and clear traits for the currently identified user and group.
 * NOTE: Only clears the cookies and localStorage set by analytics.
 * @returns {Promise}
 */
const reset = () => Promise.resolve(window.analytics.reset())
 
export default {page, identify, track, reset}