@rudderstack/analytics-js 3.23.2 → 3.24.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.
- package/CHANGELOG.md +18 -0
- package/dist/npm/index.d.cts +48 -8
- package/dist/npm/index.d.mts +48 -8
- package/dist/npm/legacy/bundled/cjs/index.cjs +80 -32
- package/dist/npm/legacy/bundled/esm/index.mjs +80 -32
- package/dist/npm/legacy/bundled/umd/index.js +80 -32
- package/dist/npm/legacy/cjs/index.cjs +80 -32
- package/dist/npm/legacy/content-script/cjs/index.cjs +80 -32
- package/dist/npm/legacy/content-script/esm/index.mjs +80 -32
- package/dist/npm/legacy/content-script/umd/index.js +80 -32
- package/dist/npm/legacy/esm/index.mjs +80 -32
- package/dist/npm/legacy/umd/index.js +80 -32
- package/dist/npm/modern/bundled/cjs/index.cjs +57 -22
- package/dist/npm/modern/bundled/esm/index.mjs +57 -22
- package/dist/npm/modern/bundled/umd/index.js +57 -22
- package/dist/npm/modern/cjs/index.cjs +63 -24
- package/dist/npm/modern/content-script/cjs/index.cjs +57 -22
- package/dist/npm/modern/content-script/esm/index.mjs +57 -22
- package/dist/npm/modern/content-script/umd/index.js +57 -22
- package/dist/npm/modern/esm/index.mjs +63 -24
- package/dist/npm/modern/umd/index.js +63 -24
- package/package.json +1 -1
@@ -348,7 +348,7 @@
|
|
348
348
|
* @returns Returns the input value if it is a boolean, otherwise returns the default value
|
349
349
|
* @example
|
350
350
|
* getNormalizedBooleanValue(true, false) // returns true
|
351
|
-
*/const getNormalizedBooleanValue=(val,defVal)=>typeof val==='boolean'?val:defVal;
|
351
|
+
*/const getNormalizedBooleanValue=(val,defVal)=>typeof val==='boolean'?val:defVal;const deepFreeze=obj=>{Object.getOwnPropertyNames(obj).forEach(function(prop){if(obj[prop]&&typeof obj[prop]==='object'){deepFreeze(obj[prop]);}});return Object.freeze(obj);};
|
352
352
|
|
353
353
|
const trim=value=>value.replace(/^\s+|\s+$/gm,'');const removeLeadingPeriod=value=>value.replace(/^\.+/,'');/**
|
354
354
|
* A function to convert values to string
|
@@ -435,6 +435,11 @@
|
|
435
435
|
|
436
436
|
const generateUUID=()=>{if(hasCrypto$1()){return v4$1();}return v4();};
|
437
437
|
|
438
|
+
/**
|
439
|
+
* Determines if the SDK is running inside a chrome extension
|
440
|
+
* @returns boolean
|
441
|
+
*/const isSDKRunningInChromeExtension=()=>!!window.chrome?.runtime?.id;const isIE11=()=>isString(globalThis.navigator.userAgent)&&/Trident.*rv:11\./.test(globalThis.navigator.userAgent);
|
442
|
+
|
438
443
|
const onPageLeave=callback=>{// To ensure the callback is only called once even if more than one events
|
439
444
|
// are fired at once.
|
440
445
|
let pageLeft=false;let isAccessible=false;function handleOnLeave(){if(pageLeft){return;}pageLeft=true;callback(isAccessible);// Reset pageLeft on the next tick
|
@@ -444,8 +449,12 @@
|
|
444
449
|
// Includes user actions like clicking a link, entering a new URL,
|
445
450
|
// refreshing the page, or closing the browser tab
|
446
451
|
// Note that 'pagehide' is not supported in IE.
|
447
|
-
//
|
448
|
-
|
452
|
+
// Registering this event conditionally for IE11 also because
|
453
|
+
// it affects bfcache optimization on modern browsers otherwise.
|
454
|
+
if(isIE11()){globalThis.addEventListener('beforeunload',()=>{isAccessible=false;handleOnLeave();});}// This is important for iOS Safari browser as it does not
|
455
|
+
// fire the regular pagehide and visibilitychange events
|
456
|
+
// when user goes to tablist view and closes the tab.
|
457
|
+
globalThis.addEventListener('blur',()=>{isAccessible=true;handleOnLeave();});globalThis.addEventListener('focus',()=>{pageLeft=false;});// Catches the page being hidden, including scenarios like closing the tab.
|
449
458
|
document.addEventListener('pagehide',()=>{isAccessible=document.visibilityState==='hidden';handleOnLeave();});// Catches visibility changes, such as switching tabs or minimizing the browser.
|
450
459
|
document.addEventListener('visibilitychange',()=>{isAccessible=true;if(document.visibilityState==='hidden'){handleOnLeave();}else {pageLeft=false;}});};
|
451
460
|
|
@@ -505,7 +514,7 @@
|
|
505
514
|
error.stacktrace=`${stacktrace}\n${MANUAL_ERROR_IDENTIFIER}`;break;case operaSourceloc:default:// eslint-disable-next-line no-param-reassign
|
506
515
|
error['opera#sourceloc']=`${operaSourceloc}\n${MANUAL_ERROR_IDENTIFIER}`;break;}}}globalThis.dispatchEvent(new ErrorEvent('error',{error,bubbles:true,cancelable:true,composed:true}));};
|
507
516
|
|
508
|
-
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.
|
517
|
+
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.24.0';const APP_NAMESPACE='com.rudderlabs.javascript';const MODULE_TYPE='npm';const ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';const ADBLOCK_PAGE_NAME='ad-block page request';const ADBLOCK_PAGE_PATH='/ad-blocked';const GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';const CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
|
509
518
|
|
510
519
|
const QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';const QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';const QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';const QUERY_PARAM_USER_ID_KEY='ajs_uid';const QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
|
511
520
|
|
@@ -643,9 +652,10 @@
|
|
643
652
|
|
644
653
|
const DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';const DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';const ConsentManagersToPluginNameMap={iubenda:'IubendaConsentManager',oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};const StorageEncryptionVersionsToPluginNameMap={[DEFAULT_STORAGE_ENCRYPTION_VERSION]:'StorageEncryption',legacy:'StorageEncryptionLegacy'};const DataPlaneEventsTransportToPluginNameMap={[DEFAULT_DATA_PLANE_EVENTS_TRANSPORT]:'XhrQueue',beacon:'BeaconQueue'};const DEFAULT_DATA_SERVICE_ENDPOINT='rsaRequest';const METRICS_SERVICE_ENDPOINT='rsaMetrics';const CUSTOM_DEVICE_MODE_DESTINATION_DISPLAY_NAME='Custom Device Mode';
|
645
654
|
|
646
|
-
const defaultLoadOptions={configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS,cutOff:{enabled:false}},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:
|
655
|
+
const defaultLoadOptions={configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS,cutOff:{enabled:false}},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,lockPluginsVersion:false,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:true,cookie:{}},sendAdblockPage:false,sameDomainCookiesOnly:false,secureCookie:false,sendAdblockPageOptions:{},useServerSideCookies:false};const loadOptionsState=d$1(clone(defaultLoadOptions));
|
647
656
|
|
648
|
-
const DEFAULT_USER_SESSION_VALUES={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null};const
|
657
|
+
const DEFAULT_USER_SESSION_VALUES=deepFreeze({userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null});const DEFAULT_RESET_OPTIONS=deepFreeze({entries:{userId:true,userTraits:true,groupId:true,groupTraits:true,sessionInfo:true,authToken:true,// These are not reset by default
|
658
|
+
anonymousId:false,initialReferrer:false,initialReferringDomain:false}});const SERVER_SIDE_COOKIES_DEBOUNCE_TIME=10;// milliseconds
|
649
659
|
|
650
660
|
const sessionState={userId:d$1(DEFAULT_USER_SESSION_VALUES.userId),userTraits:d$1(DEFAULT_USER_SESSION_VALUES.userTraits),anonymousId:d$1(DEFAULT_USER_SESSION_VALUES.anonymousId),groupId:d$1(DEFAULT_USER_SESSION_VALUES.groupId),groupTraits:d$1(DEFAULT_USER_SESSION_VALUES.groupTraits),initialReferrer:d$1(DEFAULT_USER_SESSION_VALUES.initialReferrer),initialReferringDomain:d$1(DEFAULT_USER_SESSION_VALUES.initialReferringDomain),sessionInfo:d$1(DEFAULT_USER_SESSION_VALUES.sessionInfo),authToken:d$1(DEFAULT_USER_SESSION_VALUES.authToken)};
|
651
661
|
|
@@ -2763,10 +2773,13 @@
|
|
2763
2773
|
* The method returns an empty string when the hostname is an ip.
|
2764
2774
|
*/const domain=url=>{const levels=levelsFunc(url);// Lookup the real top level one.
|
2765
2775
|
// eslint-disable-next-line unicorn/no-for-loop
|
2766
|
-
for(let i=0;i<levels.length;i+=1){const domain=levels[i];const cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;const opts={domain:`${domain.indexOf('localhost')!==-1?'':'.'}${domain}`}
|
2776
|
+
for(let i=0;i<levels.length;i+=1){const domain=levels[i];const cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;const opts={domain:`${domain.indexOf('localhost')!==-1?'':'.'}${domain}`};try{// Set cookie on domain
|
2767
2777
|
cookie(cname,1,opts);// If successful
|
2768
2778
|
if(cookie(cname)){// Remove cookie from domain
|
2769
|
-
cookie(cname,null,opts);return domain;}}
|
2779
|
+
cookie(cname,null,opts);return domain;}}catch{// Silently continue to next domain level if cookie access is restricted or setting fails
|
2780
|
+
// Best-effort cleanup to avoid leaking the test cookie
|
2781
|
+
try{cookie(cname,null,opts);}catch{// Ignore if we are unable to delete the cookie
|
2782
|
+
}}}return '';};
|
2770
2783
|
|
2771
2784
|
const getDefaultCookieOptions=()=>{const topDomain=`.${domain(globalThis.location.href)}`;return {maxage:DEFAULT_COOKIE_MAX_AGE_MS,path:'/',domain:!topDomain||topDomain==='.'?undefined:topDomain,samesite:'Lax',enabled:true};};const getDefaultLocalStorageOptions=()=>({enabled:true});const getDefaultSessionStorageOptions=()=>({enabled:true});const getDefaultInMemoryStorageOptions=()=>({enabled:true});
|
2772
2785
|
|
@@ -2787,7 +2800,7 @@
|
|
2787
2800
|
const store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
|
2788
2801
|
|
2789
2802
|
const hasCrypto=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);// eslint-disable-next-line compat/compat -- We are checking for the existence of navigator.userAgentData
|
2790
|
-
const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);
|
2803
|
+
const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);
|
2791
2804
|
|
2792
2805
|
const getUserAgentClientHint=(callback,level='none')=>{if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){navigator.userAgentData?.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(ua=>{callback(ua);}).catch(()=>{callback();});}};
|
2793
2806
|
|
@@ -2931,11 +2944,6 @@
|
|
2931
2944
|
*/const getUrlWithoutHash=url=>{let urlWithoutHash=url;try{const urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
|
2932
2945
|
}return urlWithoutHash;};
|
2933
2946
|
|
2934
|
-
/**
|
2935
|
-
* Determines if the SDK is running inside a chrome extension
|
2936
|
-
* @returns boolean
|
2937
|
-
*/const isSDKRunningInChromeExtension=()=>!!window.chrome?.runtime?.id;
|
2938
|
-
|
2939
2947
|
const DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';const DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
|
2940
2948
|
|
2941
2949
|
const isErrorReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.errors?.enabled===true;const isMetricsReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.metrics?.enabled===true;
|
@@ -3159,7 +3167,9 @@
|
|
3159
3167
|
*/const generateManualTrackingSession=(id,logger)=>{const sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};const isStorageTypeValidForStoringData=storageType=>Boolean(storageType===COOKIE_STORAGE||storageType===LOCAL_STORAGE||storageType===SESSION_STORAGE||storageType===MEMORY_STORAGE);/**
|
3160
3168
|
* Generate a new anonymousId
|
3161
3169
|
* @returns string anonymousID
|
3162
|
-
*/const generateAnonymousId=()=>generateUUID();
|
3170
|
+
*/const generateAnonymousId=()=>generateUUID();const getFinalResetOptions=options=>{// Legacy behavior: toggle only anonymousId without mutating defaults
|
3171
|
+
if(isBoolean(options)){const{entries,...rest}=DEFAULT_RESET_OPTIONS;return {...rest,entries:{...entries,anonymousId:options}};}// Override any defaults with the user provided options
|
3172
|
+
if(isObjectLiteralAndNotNull(options)&&isObjectLiteralAndNotNull(options.entries)){return mergeDeepRight(DEFAULT_RESET_OPTIONS,options);}return {...DEFAULT_RESET_OPTIONS};};
|
3163
3173
|
|
3164
3174
|
/**
|
3165
3175
|
* To get the page properties for context object
|
@@ -3368,13 +3378,11 @@
|
|
3368
3378
|
if(sessionInfo.sessionStart===undefined){sessionInfo={...sessionInfo,sessionStart:true};}else if(sessionInfo.sessionStart){sessionInfo={...sessionInfo,sessionStart:false};}}// Always write to state (in-turn to storage) to keep the session info up to date.
|
3369
3379
|
state.session.sessionInfo.value=sessionInfo;if(state.lifecycle.status.value!=='readyExecuted'){// Force update the storage as the 'effect' blocks are not getting triggered
|
3370
3380
|
// when processing preload buffered requests
|
3371
|
-
this.syncValueToStorage('sessionInfo',sessionInfo);}}/**
|
3381
|
+
this.syncValueToStorage('sessionInfo',sessionInfo);}}resetAndStartNewSession(){const session=state.session;const{manualTrack,autoTrack,timeout,cutOff}=session.sessionInfo.value;if(autoTrack){const sessionInfo={...DEFAULT_USER_SESSION_VALUES.sessionInfo,timeout};if(cutOff){sessionInfo.cutOff={enabled:cutOff.enabled,duration:cutOff.duration};}session.sessionInfo.value=sessionInfo;this.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){this.startManualTrackingInternal();}}/**
|
3372
3382
|
* Reset state values
|
3373
|
-
* @param
|
3374
|
-
* @param noNewSessionStart
|
3383
|
+
* @param options options for reset
|
3375
3384
|
* @returns
|
3376
|
-
*/reset(
|
3377
|
-
this.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){const sessionInfo={...DEFAULT_USER_SESSION_VALUES.sessionInfo,timeout};if(cutOff){sessionInfo.cutOff={enabled:cutOff.enabled,duration:cutOff.duration};}session.sessionInfo.value=sessionInfo;this.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){this.startManualTrackingInternal();}});}/**
|
3385
|
+
*/reset(options){const{session}=state;const opts=getFinalResetOptions(options);r(()=>{Object.keys(DEFAULT_USER_SESSION_VALUES).forEach(key=>{const userSessionKey=key;if(opts.entries[userSessionKey]!==true){return;}switch(key){case 'anonymousId':this.setAnonymousId();break;case 'sessionInfo':this.resetAndStartNewSession();break;default:session[userSessionKey].value=DEFAULT_USER_SESSION_VALUES[userSessionKey];break;}});});}/**
|
3378
3386
|
* Set user Id
|
3379
3387
|
* @param userId
|
3380
3388
|
*/setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
|
@@ -3537,7 +3545,7 @@
|
|
3537
3545
|
// in v3 implementation
|
3538
3546
|
path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions));}}track(payload,isBufferedInvocation=false){const type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event - ${payload.name}`);state.metrics.triggered.value+=1;this.eventManager?.addEvent({type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}identify(payload,isBufferedInvocation=false){const type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;const shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
|
3539
3547
|
if(!isNull(payload.userId)){this.userSessionManager?.setUserId(payload.userId);}this.userSessionManager?.setUserTraits(payload.traits);this.eventManager?.addEvent({type,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback});}alias(payload,isBufferedInvocation=false){const type='alias';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;const previousId=payload.from??(this.getUserId()||this.userSessionManager?.getAnonymousId());this.eventManager?.addEvent({type,to:payload.to,from:previousId,options:payload.options,callback:payload.callback});}group(payload,isBufferedInvocation=false){const type='group';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;// `null` value indicates that previous group ID needs to be retained
|
3540
|
-
if(!isNull(payload.groupId)){this.userSessionManager?.setGroupId(payload.groupId);}this.userSessionManager?.setGroupTraits(payload.traits);this.eventManager?.addEvent({type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}reset(
|
3548
|
+
if(!isNull(payload.groupId)){this.userSessionManager?.setGroupId(payload.groupId);}this.userSessionManager?.setGroupTraits(payload.traits);this.eventManager?.addEvent({type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}reset(options,isBufferedInvocation=false){const type='reset';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,options]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);this.userSessionManager?.reset(options);}getAnonymousId(options){return this.userSessionManager?.getAnonymousId(options);}setAnonymousId(anonymousId,rudderAmpLinkerParam,isBufferedInvocation=false){const type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
|
3541
3549
|
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,anonymousId,rudderAmpLinkerParam]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);this.userSessionManager?.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
|
3542
3550
|
getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
|
3543
3551
|
getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
@@ -3639,7 +3647,34 @@
|
|
3639
3647
|
alias(to,from,options,callback){try{this.getAnalyticsInstance()?.alias(aliasArgumentsToCallOptions(getSanitizedValue(to),getSanitizedValue(from),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
3640
3648
|
* Process group arguments and forward to page call
|
3641
3649
|
*/// These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
3642
|
-
group(groupId,traits,options,callback){try{this.getAnalyticsInstance()?.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}
|
3650
|
+
group(groupId,traits,options,callback){try{this.getAnalyticsInstance()?.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
3651
|
+
* Reset the analytics instance
|
3652
|
+
* @param options Reset options. Except for anonymousId, initialReferrer, and initialReferringDomain
|
3653
|
+
* all other values will be reset by default.
|
3654
|
+
* @example
|
3655
|
+
* ```ts
|
3656
|
+
* reset({
|
3657
|
+
* entries: {
|
3658
|
+
* anonymousId: true,
|
3659
|
+
* }
|
3660
|
+
* });
|
3661
|
+
* ```
|
3662
|
+
* @example
|
3663
|
+
* ```ts
|
3664
|
+
* reset({
|
3665
|
+
* entries: {
|
3666
|
+
* userId: false,
|
3667
|
+
* sessionInfo: false,
|
3668
|
+
* }
|
3669
|
+
* });
|
3670
|
+
* ```
|
3671
|
+
* @returns none
|
3672
|
+
*//**
|
3673
|
+
* Reset the analytics instance
|
3674
|
+
* @param resetAnonymousId Reset anonymous ID
|
3675
|
+
* @returns none
|
3676
|
+
* @deprecated Use reset(options) instead
|
3677
|
+
*/reset(options){try{this.getAnalyticsInstance()?.reset(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}getAnonymousId(options){try{return this.getAnalyticsInstance()?.getAnonymousId(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);return undefined;}}setAnonymousId(anonymousId,rudderAmpLinkerParam){try{this.getAnalyticsInstance()?.setAnonymousId(getSanitizedValue(anonymousId),getSanitizedValue(rudderAmpLinkerParam));}catch(error){dispatchErrorEvent(error);}}getUserId(){try{return this.getAnalyticsInstance()?.getUserId();}catch(error){dispatchErrorEvent(error);return undefined;}}getUserTraits(){try{return this.getAnalyticsInstance()?.getUserTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupId(){try{return this.getAnalyticsInstance()?.getGroupId();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupTraits(){try{return this.getAnalyticsInstance()?.getGroupTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}startSession(sessionId){try{this.getAnalyticsInstance()?.startSession(getSanitizedValue(sessionId));}catch(error){dispatchErrorEvent(error);}}endSession(){try{this.getAnalyticsInstance()?.endSession();}catch(error){dispatchErrorEvent(error);}}getSessionId(){try{return this.getAnalyticsInstance()?.getSessionId();}catch(error){dispatchErrorEvent(error);return undefined;}}setAuthToken(token){try{this.getAnalyticsInstance()?.setAuthToken(getSanitizedValue(token));}catch(error){dispatchErrorEvent(error);}}consent(options){try{this.getAnalyticsInstance()?.consent(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}addCustomIntegration(destinationId,integration){try{this.getAnalyticsInstance()?.addCustomIntegration(getSanitizedValue(destinationId),getSanitizedValue(integration));}catch(error){dispatchErrorEvent(error);}}}
|
3643
3678
|
|
3644
3679
|
exports.RudderAnalytics = RudderAnalytics;
|
3645
3680
|
|
@@ -285,7 +285,11 @@ function _path(pathAr,obj){var val=obj;for(var i=0;i<pathAr.length;i+=1){if(val=
|
|
285
285
|
* Determines if the input is of type error
|
286
286
|
* @param value input value
|
287
287
|
* @returns true if the input is of type error else false
|
288
|
-
*/const isTypeOfError=value=>{switch(Object.prototype.toString.call(value)){case '[object Error]':case '[object Exception]':case '[object DOMException]':return true;default:return value instanceof Error;}}
|
288
|
+
*/const isTypeOfError=value=>{switch(Object.prototype.toString.call(value)){case '[object Error]':case '[object Exception]':case '[object DOMException]':return true;default:return value instanceof Error;}};/**
|
289
|
+
* A function to check given value is a boolean
|
290
|
+
* @param value input value
|
291
|
+
* @returns boolean
|
292
|
+
*/const isBoolean=value=>typeof value==='boolean';
|
289
293
|
|
290
294
|
const getValueByPath=(obj,keyPath)=>{const pathParts=keyPath.split('.');return path(pathParts,obj);};const hasValueByPath=(obj,path)=>Boolean(getValueByPath(obj,path));const isObject=value=>typeof value==='object';/**
|
291
295
|
* Checks if the input is an object literal or built-in object type and not null
|
@@ -338,7 +342,7 @@ mergeDeepRight(mergedArray[index],value):value;});return mergedArray;};/**
|
|
338
342
|
* @returns Returns the input value if it is a boolean, otherwise returns the default value
|
339
343
|
* @example
|
340
344
|
* getNormalizedBooleanValue(true, false) // returns true
|
341
|
-
*/const getNormalizedBooleanValue=(val,defVal)=>typeof val==='boolean'?val:defVal;
|
345
|
+
*/const getNormalizedBooleanValue=(val,defVal)=>typeof val==='boolean'?val:defVal;const deepFreeze=obj=>{Object.getOwnPropertyNames(obj).forEach(function(prop){if(obj[prop]&&typeof obj[prop]==='object'){deepFreeze(obj[prop]);}});return Object.freeze(obj);};
|
342
346
|
|
343
347
|
const trim=value=>value.replace(/^\s+|\s+$/gm,'');const removeLeadingPeriod=value=>value.replace(/^\.+/,'');/**
|
344
348
|
* A function to convert values to string
|
@@ -416,6 +420,11 @@ const hasCrypto$1=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalTh
|
|
416
420
|
|
417
421
|
const generateUUID=()=>{if(hasCrypto$1()){return v4$1();}return v4();};
|
418
422
|
|
423
|
+
/**
|
424
|
+
* Determines if the SDK is running inside a chrome extension
|
425
|
+
* @returns boolean
|
426
|
+
*/const isSDKRunningInChromeExtension=()=>!!window.chrome?.runtime?.id;const isIE11=()=>isString(globalThis.navigator.userAgent)&&/Trident.*rv:11\./.test(globalThis.navigator.userAgent);
|
427
|
+
|
419
428
|
const onPageLeave=callback=>{// To ensure the callback is only called once even if more than one events
|
420
429
|
// are fired at once.
|
421
430
|
let pageLeft=false;let isAccessible=false;function handleOnLeave(){if(pageLeft){return;}pageLeft=true;callback(isAccessible);// Reset pageLeft on the next tick
|
@@ -425,8 +434,12 @@ setTimeout(()=>{pageLeft=false;},0);}// Catches the unloading of the page (e.g.,
|
|
425
434
|
// Includes user actions like clicking a link, entering a new URL,
|
426
435
|
// refreshing the page, or closing the browser tab
|
427
436
|
// Note that 'pagehide' is not supported in IE.
|
428
|
-
//
|
429
|
-
|
437
|
+
// Registering this event conditionally for IE11 also because
|
438
|
+
// it affects bfcache optimization on modern browsers otherwise.
|
439
|
+
if(isIE11()){globalThis.addEventListener('beforeunload',()=>{isAccessible=false;handleOnLeave();});}// This is important for iOS Safari browser as it does not
|
440
|
+
// fire the regular pagehide and visibilitychange events
|
441
|
+
// when user goes to tablist view and closes the tab.
|
442
|
+
globalThis.addEventListener('blur',()=>{isAccessible=true;handleOnLeave();});globalThis.addEventListener('focus',()=>{pageLeft=false;});// Catches the page being hidden, including scenarios like closing the tab.
|
430
443
|
document.addEventListener('pagehide',()=>{isAccessible=document.visibilityState==='hidden';handleOnLeave();});// Catches visibility changes, such as switching tabs or minimizing the browser.
|
431
444
|
document.addEventListener('visibilitychange',()=>{isAccessible=true;if(document.visibilityState==='hidden'){handleOnLeave();}else {pageLeft=false;}});};
|
432
445
|
|
@@ -486,7 +499,7 @@ error.stack=`${stack}\n${MANUAL_ERROR_IDENTIFIER}`;break;case stacktrace:// esli
|
|
486
499
|
error.stacktrace=`${stacktrace}\n${MANUAL_ERROR_IDENTIFIER}`;break;case operaSourceloc:default:// eslint-disable-next-line no-param-reassign
|
487
500
|
error['opera#sourceloc']=`${operaSourceloc}\n${MANUAL_ERROR_IDENTIFIER}`;break;}}}globalThis.dispatchEvent(new ErrorEvent('error',{error,bubbles:true,cancelable:true,composed:true}));};
|
488
501
|
|
489
|
-
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.
|
502
|
+
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.24.0';const APP_NAMESPACE='com.rudderlabs.javascript';const MODULE_TYPE='npm';const ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';const ADBLOCK_PAGE_NAME='ad-block page request';const ADBLOCK_PAGE_PATH='/ad-blocked';const GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';const CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
|
490
503
|
|
491
504
|
const QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';const QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';const QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';const QUERY_PARAM_USER_ID_KEY='ajs_uid';const QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
|
492
505
|
|
@@ -624,9 +637,10 @@ const BUILD_TYPE='modern';const SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';co
|
|
624
637
|
|
625
638
|
const DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';const DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';const ConsentManagersToPluginNameMap={iubenda:'IubendaConsentManager',oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};const StorageEncryptionVersionsToPluginNameMap={[DEFAULT_STORAGE_ENCRYPTION_VERSION]:'StorageEncryption',legacy:'StorageEncryptionLegacy'};const DataPlaneEventsTransportToPluginNameMap={[DEFAULT_DATA_PLANE_EVENTS_TRANSPORT]:'XhrQueue',beacon:'BeaconQueue'};const DEFAULT_DATA_SERVICE_ENDPOINT='rsaRequest';const METRICS_SERVICE_ENDPOINT='rsaMetrics';const CUSTOM_DEVICE_MODE_DESTINATION_DISPLAY_NAME='Custom Device Mode';
|
626
639
|
|
627
|
-
const defaultLoadOptions={configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS,cutOff:{enabled:false}},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:
|
640
|
+
const defaultLoadOptions={configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS,cutOff:{enabled:false}},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,lockPluginsVersion:false,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:true,cookie:{}},sendAdblockPage:false,sameDomainCookiesOnly:false,secureCookie:false,sendAdblockPageOptions:{},useServerSideCookies:false};const loadOptionsState=d(clone(defaultLoadOptions));
|
628
641
|
|
629
|
-
const DEFAULT_USER_SESSION_VALUES={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null};const
|
642
|
+
const DEFAULT_USER_SESSION_VALUES=deepFreeze({userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null});const DEFAULT_RESET_OPTIONS=deepFreeze({entries:{userId:true,userTraits:true,groupId:true,groupTraits:true,sessionInfo:true,authToken:true,// These are not reset by default
|
643
|
+
anonymousId:false,initialReferrer:false,initialReferringDomain:false}});const SERVER_SIDE_COOKIES_DEBOUNCE_TIME=10;// milliseconds
|
630
644
|
|
631
645
|
const sessionState={userId:d(DEFAULT_USER_SESSION_VALUES.userId),userTraits:d(DEFAULT_USER_SESSION_VALUES.userTraits),anonymousId:d(DEFAULT_USER_SESSION_VALUES.anonymousId),groupId:d(DEFAULT_USER_SESSION_VALUES.groupId),groupTraits:d(DEFAULT_USER_SESSION_VALUES.groupTraits),initialReferrer:d(DEFAULT_USER_SESSION_VALUES.initialReferrer),initialReferringDomain:d(DEFAULT_USER_SESSION_VALUES.initialReferringDomain),sessionInfo:d(DEFAULT_USER_SESSION_VALUES.sessionInfo),authToken:d(DEFAULT_USER_SESSION_VALUES.authToken)};
|
632
646
|
|
@@ -883,7 +897,7 @@ destination.config.useNativeSDK===true);const isHybridModeDestination=destinatio
|
|
883
897
|
*/const pluginNamesList=['BeaconQueue','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ExternalAnonymousId','GoogleLinker','IubendaConsentManager','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];const deprecatedPluginsList=['Bugsnag','ErrorReporting'];
|
884
898
|
|
885
899
|
const remotesMap = {
|
886
|
-
'rudderAnalyticsRemotePlugins':{url:()=>Promise.resolve(window.RudderStackGlobals && window.RudderStackGlobals.app && window.RudderStackGlobals.app.pluginsCDNPath ? `${window.RudderStackGlobals.app.pluginsCDNPath}/rsa-plugins.js` : `https://cdn.rudderlabs.com/
|
900
|
+
'rudderAnalyticsRemotePlugins':{url:()=>Promise.resolve(window.RudderStackGlobals && window.RudderStackGlobals.app && window.RudderStackGlobals.app.pluginsCDNPath ? `${window.RudderStackGlobals.app.pluginsCDNPath}/rsa-plugins.js` : `https://cdn.rudderlabs.com/3.23.0//rsa-plugins.js`),format:'esm',from:'vite'}
|
887
901
|
};
|
888
902
|
|
889
903
|
function merge(obj1, obj2) {
|
@@ -1037,10 +1051,13 @@ for(let i=parts.length-2;i>=0;i-=1){levels.push(parts.slice(i).join('.'));}retur
|
|
1037
1051
|
* The method returns an empty string when the hostname is an ip.
|
1038
1052
|
*/const domain=url=>{const levels=levelsFunc(url);// Lookup the real top level one.
|
1039
1053
|
// eslint-disable-next-line unicorn/no-for-loop
|
1040
|
-
for(let i=0;i<levels.length;i+=1){const domain=levels[i];const cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;const opts={domain:`${domain.indexOf('localhost')!==-1?'':'.'}${domain}`}
|
1054
|
+
for(let i=0;i<levels.length;i+=1){const domain=levels[i];const cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;const opts={domain:`${domain.indexOf('localhost')!==-1?'':'.'}${domain}`};try{// Set cookie on domain
|
1041
1055
|
cookie(cname,1,opts);// If successful
|
1042
1056
|
if(cookie(cname)){// Remove cookie from domain
|
1043
|
-
cookie(cname,null,opts);return domain;}}
|
1057
|
+
cookie(cname,null,opts);return domain;}}catch{// Silently continue to next domain level if cookie access is restricted or setting fails
|
1058
|
+
// Best-effort cleanup to avoid leaking the test cookie
|
1059
|
+
try{cookie(cname,null,opts);}catch{// Ignore if we are unable to delete the cookie
|
1060
|
+
}}}return '';};
|
1044
1061
|
|
1045
1062
|
const getDefaultCookieOptions=()=>{const topDomain=`.${domain(globalThis.location.href)}`;return {maxage:DEFAULT_COOKIE_MAX_AGE_MS,path:'/',domain:!topDomain||topDomain==='.'?undefined:topDomain,samesite:'Lax',enabled:true};};const getDefaultLocalStorageOptions=()=>({enabled:true});const getDefaultSessionStorageOptions=()=>({enabled:true});const getDefaultInMemoryStorageOptions=()=>({enabled:true});
|
1046
1063
|
|
@@ -1061,7 +1078,7 @@ var storeExports = requireStore();
|
|
1061
1078
|
const store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
|
1062
1079
|
|
1063
1080
|
const hasCrypto=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);// eslint-disable-next-line compat/compat -- We are checking for the existence of navigator.userAgentData
|
1064
|
-
const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);
|
1081
|
+
const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);
|
1065
1082
|
|
1066
1083
|
const getUserAgentClientHint=(callback,level='none')=>{if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){navigator.userAgentData?.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(ua=>{callback(ua);}).catch(()=>{callback();});}};
|
1067
1084
|
|
@@ -1214,11 +1231,6 @@ const removeDuplicateSlashes=str=>str.replace(/\/{2,}/g,'/');/**
|
|
1214
1231
|
if(isFunction(globalThis.URL)){// eslint-disable-next-line no-new
|
1215
1232
|
new URL(url);}return URL_PATTERN.test(url);}catch(e){return false;}};
|
1216
1233
|
|
1217
|
-
/**
|
1218
|
-
* Determines if the SDK is running inside a chrome extension
|
1219
|
-
* @returns boolean
|
1220
|
-
*/const isSDKRunningInChromeExtension=()=>!!window.chrome?.runtime?.id;
|
1221
|
-
|
1222
1234
|
const DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';const DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
|
1223
1235
|
|
1224
1236
|
const isErrorReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.errors?.enabled===true;const isMetricsReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.metrics?.enabled===true;
|
@@ -1450,7 +1462,9 @@ timeout,autoTrack:true,...(cutOff&&{cutOff})};};/**
|
|
1450
1462
|
*/const generateManualTrackingSession=(id,logger)=>{const sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};const isStorageTypeValidForStoringData=storageType=>Boolean(storageType===COOKIE_STORAGE||storageType===LOCAL_STORAGE||storageType===SESSION_STORAGE||storageType===MEMORY_STORAGE);/**
|
1451
1463
|
* Generate a new anonymousId
|
1452
1464
|
* @returns string anonymousID
|
1453
|
-
*/const generateAnonymousId=()=>generateUUID();
|
1465
|
+
*/const generateAnonymousId=()=>generateUUID();const getFinalResetOptions=options=>{// Legacy behavior: toggle only anonymousId without mutating defaults
|
1466
|
+
if(isBoolean(options)){const{entries,...rest}=DEFAULT_RESET_OPTIONS;return {...rest,entries:{...entries,anonymousId:options}};}// Override any defaults with the user provided options
|
1467
|
+
if(isObjectLiteralAndNotNull(options)&&isObjectLiteralAndNotNull(options.entries)){return mergeDeepRight(DEFAULT_RESET_OPTIONS,options);}return {...DEFAULT_RESET_OPTIONS};};
|
1454
1468
|
|
1455
1469
|
/**
|
1456
1470
|
* To get the page properties for context object
|
@@ -1659,13 +1673,11 @@ this.migrateStorageIfNeeded([store],[sessionKey]);const storageKey=entries[sessi
|
|
1659
1673
|
if(sessionInfo.sessionStart===undefined){sessionInfo={...sessionInfo,sessionStart:true};}else if(sessionInfo.sessionStart){sessionInfo={...sessionInfo,sessionStart:false};}}// Always write to state (in-turn to storage) to keep the session info up to date.
|
1660
1674
|
state.session.sessionInfo.value=sessionInfo;if(state.lifecycle.status.value!=='readyExecuted'){// Force update the storage as the 'effect' blocks are not getting triggered
|
1661
1675
|
// when processing preload buffered requests
|
1662
|
-
this.syncValueToStorage('sessionInfo',sessionInfo);}}/**
|
1676
|
+
this.syncValueToStorage('sessionInfo',sessionInfo);}}resetAndStartNewSession(){const session=state.session;const{manualTrack,autoTrack,timeout,cutOff}=session.sessionInfo.value;if(autoTrack){const sessionInfo={...DEFAULT_USER_SESSION_VALUES.sessionInfo,timeout};if(cutOff){sessionInfo.cutOff={enabled:cutOff.enabled,duration:cutOff.duration};}session.sessionInfo.value=sessionInfo;this.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){this.startManualTrackingInternal();}}/**
|
1663
1677
|
* Reset state values
|
1664
|
-
* @param
|
1665
|
-
* @param noNewSessionStart
|
1678
|
+
* @param options options for reset
|
1666
1679
|
* @returns
|
1667
|
-
*/reset(
|
1668
|
-
this.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){const sessionInfo={...DEFAULT_USER_SESSION_VALUES.sessionInfo,timeout};if(cutOff){sessionInfo.cutOff={enabled:cutOff.enabled,duration:cutOff.duration};}session.sessionInfo.value=sessionInfo;this.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){this.startManualTrackingInternal();}});}/**
|
1680
|
+
*/reset(options){const{session}=state;const opts=getFinalResetOptions(options);r(()=>{Object.keys(DEFAULT_USER_SESSION_VALUES).forEach(key=>{const userSessionKey=key;if(opts.entries[userSessionKey]!==true){return;}switch(key){case 'anonymousId':this.setAnonymousId();break;case 'sessionInfo':this.resetAndStartNewSession();break;default:session[userSessionKey].value=DEFAULT_USER_SESSION_VALUES[userSessionKey];break;}});});}/**
|
1669
1681
|
* Set user Id
|
1670
1682
|
* @param userId
|
1671
1683
|
*/setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
|
@@ -1828,7 +1840,7 @@ if(state.capabilities.isAdBlocked.value===true&&payload.category!==ADBLOCK_PAGE_
|
|
1828
1840
|
// in v3 implementation
|
1829
1841
|
path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions));}}track(payload,isBufferedInvocation=false){const type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event - ${payload.name}`);state.metrics.triggered.value+=1;this.eventManager?.addEvent({type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}identify(payload,isBufferedInvocation=false){const type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;const shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
|
1830
1842
|
if(!isNull(payload.userId)){this.userSessionManager?.setUserId(payload.userId);}this.userSessionManager?.setUserTraits(payload.traits);this.eventManager?.addEvent({type,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback});}alias(payload,isBufferedInvocation=false){const type='alias';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;const previousId=payload.from??(this.getUserId()||this.userSessionManager?.getAnonymousId());this.eventManager?.addEvent({type,to:payload.to,from:previousId,options:payload.options,callback:payload.callback});}group(payload,isBufferedInvocation=false){const type='group';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;// `null` value indicates that previous group ID needs to be retained
|
1831
|
-
if(!isNull(payload.groupId)){this.userSessionManager?.setGroupId(payload.groupId);}this.userSessionManager?.setGroupTraits(payload.traits);this.eventManager?.addEvent({type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}reset(
|
1843
|
+
if(!isNull(payload.groupId)){this.userSessionManager?.setGroupId(payload.groupId);}this.userSessionManager?.setGroupTraits(payload.traits);this.eventManager?.addEvent({type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}reset(options,isBufferedInvocation=false){const type='reset';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,options]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);this.userSessionManager?.reset(options);}getAnonymousId(options){return this.userSessionManager?.getAnonymousId(options);}setAnonymousId(anonymousId,rudderAmpLinkerParam,isBufferedInvocation=false){const type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
|
1832
1844
|
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,anonymousId,rudderAmpLinkerParam]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);this.userSessionManager?.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
|
1833
1845
|
getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
|
1834
1846
|
getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
@@ -1930,6 +1942,33 @@ identify(userId,traits,options,callback){try{this.getAnalyticsInstance()?.identi
|
|
1930
1942
|
alias(to,from,options,callback){try{this.getAnalyticsInstance()?.alias(aliasArgumentsToCallOptions(getSanitizedValue(to),getSanitizedValue(from),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
1931
1943
|
* Process group arguments and forward to page call
|
1932
1944
|
*/// These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
1933
|
-
group(groupId,traits,options,callback){try{this.getAnalyticsInstance()?.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}
|
1945
|
+
group(groupId,traits,options,callback){try{this.getAnalyticsInstance()?.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
1946
|
+
* Reset the analytics instance
|
1947
|
+
* @param options Reset options. Except for anonymousId, initialReferrer, and initialReferringDomain
|
1948
|
+
* all other values will be reset by default.
|
1949
|
+
* @example
|
1950
|
+
* ```ts
|
1951
|
+
* reset({
|
1952
|
+
* entries: {
|
1953
|
+
* anonymousId: true,
|
1954
|
+
* }
|
1955
|
+
* });
|
1956
|
+
* ```
|
1957
|
+
* @example
|
1958
|
+
* ```ts
|
1959
|
+
* reset({
|
1960
|
+
* entries: {
|
1961
|
+
* userId: false,
|
1962
|
+
* sessionInfo: false,
|
1963
|
+
* }
|
1964
|
+
* });
|
1965
|
+
* ```
|
1966
|
+
* @returns none
|
1967
|
+
*//**
|
1968
|
+
* Reset the analytics instance
|
1969
|
+
* @param resetAnonymousId Reset anonymous ID
|
1970
|
+
* @returns none
|
1971
|
+
* @deprecated Use reset(options) instead
|
1972
|
+
*/reset(options){try{this.getAnalyticsInstance()?.reset(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}getAnonymousId(options){try{return this.getAnalyticsInstance()?.getAnonymousId(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);return undefined;}}setAnonymousId(anonymousId,rudderAmpLinkerParam){try{this.getAnalyticsInstance()?.setAnonymousId(getSanitizedValue(anonymousId),getSanitizedValue(rudderAmpLinkerParam));}catch(error){dispatchErrorEvent(error);}}getUserId(){try{return this.getAnalyticsInstance()?.getUserId();}catch(error){dispatchErrorEvent(error);return undefined;}}getUserTraits(){try{return this.getAnalyticsInstance()?.getUserTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupId(){try{return this.getAnalyticsInstance()?.getGroupId();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupTraits(){try{return this.getAnalyticsInstance()?.getGroupTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}startSession(sessionId){try{this.getAnalyticsInstance()?.startSession(getSanitizedValue(sessionId));}catch(error){dispatchErrorEvent(error);}}endSession(){try{this.getAnalyticsInstance()?.endSession();}catch(error){dispatchErrorEvent(error);}}getSessionId(){try{return this.getAnalyticsInstance()?.getSessionId();}catch(error){dispatchErrorEvent(error);return undefined;}}setAuthToken(token){try{this.getAnalyticsInstance()?.setAuthToken(getSanitizedValue(token));}catch(error){dispatchErrorEvent(error);}}consent(options){try{this.getAnalyticsInstance()?.consent(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}addCustomIntegration(destinationId,integration){try{this.getAnalyticsInstance()?.addCustomIntegration(getSanitizedValue(destinationId),getSanitizedValue(integration));}catch(error){dispatchErrorEvent(error);}}}
|
1934
1973
|
|
1935
1974
|
export { RudderAnalytics };
|