@mparticle/web-rokt-kit 3.2.2 → 3.3.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/dist/Rokt-Kit.common.js +1 -1
- package/dist/Rokt-Kit.esm.js +302 -284
- package/dist/Rokt-Kit.iife.js +1 -1
- package/package.json +1 -1
package/dist/Rokt-Kit.iife.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var RoktKit=(function(F){"use strict";const ke=["active_time_on_site_ms","billingaddress1","billingaddress2","billingcity","billingstate","billingzipcode","cartitems","ccbin","confirmationref","conversiontype","country","couponcode","currency","language","paymentserviceprovider","paymentserviceproviderattribute","paymenttype","shippingaddress1","shippingcity","shippingcountry","shippingmethod","shippingstate","shippingzipcode","totalprice"],be=new Set(ke);function Q(i){return be.has(i.toLowerCase())}function v(i){const e={},t=i||{},n=Object.keys(t);for(let r=0;r<n.length;r++){const s=n[r];Q(s)||(e[s]=t[s])}return e}function f(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function g(i){return typeof i=="string"}function w(i){return typeof i=="function"}function A(i){return i==null?!0:typeof i=="string"?i.length===0:typeof i=="object"?Object.keys(i).length===0:!1}function x(i){try{const e=new URL(i);return e.search="",e.toString()}catch{return i}}function X(i){let e=5381;for(let t=0;t<i.length;t++)e=(e<<5)+e+i.charCodeAt(t),e=e&e;return e}const d="mp-rokt-kit",Z="__rokt_ls_probe__";function Y(){try{return window.localStorage.setItem(Z,"1"),window.localStorage.removeItem(Z),!0}catch{return!1}}function j(i){try{const e=window.localStorage.getItem(i);return e===null?null:JSON.parse(e)}catch{return null}}function ee(i,e){try{return window.localStorage.setItem(i,JSON.stringify(e)),!0}catch{return!1}}function ve(i){try{window.localStorage.removeItem(i)}catch{}}function P(i,e){const t=j(i);return f(t)?t[e]:void 0}function T(i,e,t){const n=j(i),r=f(n)?{...n}:{};return r[e]=t,ee(i,r)}function L(i,e){const t=j(i);if(!f(t)||!(e in t))return;const n={...t};delete n[e],Object.keys(n).length===0?ve(i):ee(i,n)}const G="pageViews",O="utmParams",te=25,we=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"];function ie(i){return i.slice(-te)}function ne(){const i=P(d,G);return Array.isArray(i)?i:[]}function Te(i){const e=ie(i);for(let t=0;t<e.length;t++){const n=e.slice(t);if(T(d,G,n))return n.length}return 0}function re(){L(d,G)}function Le(i){const e=ie(i);return e.map((t,n)=>{const r=t.activeTimeOnSite,s=r!==void 0&&Number.isFinite(r),c=e[n+1]?.activeTimeOnSite,u=c!==void 0&&Number.isFinite(c),l=s&&u?c-r:void 0;return{pageUrl:t.pageUrl,sourceMessageId:t.sourceMessageId,timestamp:t.timestamp,...t.pageTitle!==void 0?{pageTitle:t.pageTitle}:{},...t.canonicalUrl!==void 0?{canonicalUrl:t.canonicalUrl}:{},...s?{activeTimeOnSite:r}:{},...l!==void 0&&l>=0?{activeTimeOnPage:l}:{}}})}function Oe(i){if(P(d,O)!==void 0)return;const e=new URLSearchParams(window.location.search),t={};for(const r of we){const s=e.get(r);s&&(t[r]=s)}if(Object.keys(t).length===0)return;const n=Object.keys(t).join(", ");if(!T(d,O,t)){const r=Y()?"quota":"ls_unavailable";i?.log({message:`Rokt Kit: Failed to persist UTM params [reason: ${r}]`,code:"UTM_CAPTURE_FAILED"});return}i?.log({message:`Rokt Kit: Captured UTM params [${n}]`,code:"UTM_CAPTURE_SUCCESS"})}function Ne(){const i=P(d,O);return f(i)?i:null}function se(){L(d,O)}function Ue(){const e=document.querySelector('link[rel="canonical"]')?.href;if(e)return x(e)}const V=[{accountId:"2919171670744024290",pathname:"/checkout",targetPageIdentifier:"prod.rokt.conf",attributeKeys:["email","amount","concessions_total","customertype","eventvenue","firstname","lastname","member_status","billingzipcode","currency"]}],Ce=6e4;function Ke(i){return f(i)&&typeof i.expiresAt=="number"&&f(i.attributes)}function De(i,e){return`activePreselect:${i}:${e}`}function Me(i){const e=P(d,i);return Ke(e)?e:null}function Fe(i,e){T(d,i,{expiresAt:Date.now()+Ce,attributes:e})}const xe=2*6e4;function Ye(i){return f(i)&&typeof i.expiresAt=="number"&&g(i.pathname)&&g(i.identifier)&&f(i.attributes)&&g(i.mpid)}function W(i){return`pendingPreselect:${i}`}function je(i){const e=W(i),t=P(d,e);return Ye(t)?t.expiresAt<=Date.now()?(L(d,e),null):t:null}function Ge(i,e,t,n,r){T(d,W(i),{expiresAt:Date.now()+xe,pathname:e,identifier:t,attributes:n,mpid:r})}function H(i){L(d,W(i))}function R(i,e){const t={fired:"PRESELECT_FIRED",missed:"PRESELECT_MISSED",queued:"PRESELECT_QUEUED",skipped:"PRESELECT_SKIPPED"};return{message:`Rokt Kit: preselect ${i} [reason=${e}]`,code:t[i]}}function Ve(i,e){if(i)return V.find(t=>t.accountId===i&&t.pathname===e)}function We(i,e){if(!(!i||!g(e)))return V.find(t=>t.accountId===i&&t.targetPageIdentifier===e)}function He(i,e){return i?V.some(t=>t.accountId===i&&t.attributeKeys.includes(e)):!1}function ze(){return{pending:[]}}function z(i,e){const t=i.pending.findIndex(n=>n.pathname===e.pathname);if(t>=0){i.pending[t]=e;return}i.pending.push(e)}function $(i){if(!i?.getUserIdentities)return!1;const e=i.getUserIdentities().userIdentities;return e?Object.keys(e).some(t=>{const n=e[t];return g(n)&&n.length>0}):!1}function oe(i){const e=i?.getMPID?.();return e==null?null:String(e)}function ce(i,e,t){const n=i.filteredUser?.getAllUserAttributes?.()||{},r={},s=[];for(const o of t.attributeKeys){const c=i.getEventAttributeValue(e,o),u=A(c)?i.userAttributes[o]??n[o]:c;if(A(u)){s.push(o);continue}r[o]=u}return{collected:r,missingKeys:s}}function $e(i,e){Promise.resolve(i.selectPlacements(e)).catch(t=>{const n=t instanceof Error?t.message:String(t);i.log({message:`Rokt Kit: Preselect selectPlacements call failed: ${n}`,code:"PRESELECT_DISPATCH_FAILED"})})}function ae(i,e,t,n,r,s){const o=De(e,t),c=Me(o),u=!!c&&JSON.stringify(c.attributes)===JSON.stringify(r);if(c&&c.expiresAt>Date.now()&&u){i.logPlacementDiagnostic(R("skipped","active_preselection"));return}Fe(o,r),i.logPlacementDiagnostic(R("fired",s)),$e(i,{attributes:r,preselect:!0,identifier:n,omitUrl:!0})}function qe(i,e){if(!e.accountId||!e.isKitReady())return;const t=je(e.accountId);if(t){if(i.pending.some(n=>n.pathname===t.pathname)){H(e.accountId);return}if(!e.isPreselectionEnabled()){H(e.accountId);return}$(e.filteredUser)&&(H(e.accountId),oe(e.filteredUser)===t.mpid&&ae(e,e.accountId,t.pathname,t.identifier,t.attributes,"recovered"))}}function le(i,e,t,n=window.location.pathname){const r=Ve(e.accountId,n);if(!r)return;if(!e.isKitReady()){z(i,{event:t,pathname:n}),e.logPlacementDiagnostic(R("queued","not_ready"));const c=oe(e.filteredUser);if(e.accountId&&c&&$(e.filteredUser)){const{collected:u,missingKeys:l}=ce(e,t,r);l.length===0&&Ge(e.accountId,n,r.targetPageIdentifier,u,c)}return}if(!e.isPreselectionEnabled())return;if(!$(e.filteredUser)){e.logPlacementDiagnostic(R("missed","no_valid_identity")),z(i,{event:t,pathname:n});return}const{collected:s,missingKeys:o}=ce(e,t,r);if(o.length>0){for(const c of o)e.logPlacementDiagnostic(R("missed",`missing_attribute:${c}`));z(i,{event:t,pathname:n});return}ae(e,e.accountId||"",n,r.targetPageIdentifier,s,"fired")}function Je(i,e,t=window.location.pathname){if(qe(i,e),i.pending.length===0)return;const n=i.pending;i.pending=[],n.forEach(({event:r,pathname:s})=>{s===t&&le(i,e,r,s)})}function Be(){return{context:null,lifecycle:"idle",recreateInFlight:null}}function Qe(i,e){i.context={accountId:e.accountId,launcherOptions:{...e.launcherOptions},legacyRoktExtensions:[...e.legacyRoktExtensions]}}function Xe(i){i.lifecycle="attached"}function Ze(i){i.lifecycle!=="idle"&&(i.lifecycle="terminated")}function et(i){i.lifecycle="terminated"}function tt(i){i.context=null,i.lifecycle="idle",i.recreateInFlight=null}function it(i,e,t){if(i.recreateInFlight)return i.recreateInFlight;if(i.lifecycle!=="terminated"||!i.context||!e)return;i.lifecycle="recreating";const n=i.context;return i.recreateInFlight=t(n).finally(()=>{i.recreateInFlight=null}),i.recreateInFlight}const h="Rokt",N=181,nt="selectPlacements",rt="apps.roktecommerce.com",st=.1,ot="ThankYouPageJourney",ct="rokt-launcher",at="rokt-thank-you-element",lt="userIdentifiedInWorkspace",ut=3,dt=2,ht="page_events",gt="page_view_attributes",ft="mparticle_session_id",pt="mparticle_device_id",ue=500,q={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST",LOG_DELIVERY_FAILURE:"LOG_DELIVERY_FAILURE"},I={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"},mt="apps.rokt-api.com",Et="/v1/log",_t="/v1/errors",It=10;function a(){return window.mParticle}function de(i,e){const n=[U(i),"/wsdk/integrations/launcher.js"].join("");return!e||e.length===0?n:n+"?extensions="+e.join(",")}function he(i){return[U(i),"/rokt-elements/rokt-element-thank-you.js"].join("")}function U(i){const e=i!==void 0?i:mt;return e.includes("://")?e.replace(/\/+$/,""):["https://",e].join("")}function ge(i,e,t){if(i)return i.startsWith("http://")||i.startsWith("https://")?i:"https://"+i;const r=e?.includes("://")&&!/^https?:\/\//i.test(e)?void 0:e;return U(r)+t}function fe(i,e,t){if(document.getElementById(i))return;const n=document.head||document.body,r=document.createElement("script");r.id=i,r.type="text/javascript",r.src=e,r.async=!0,r.crossOrigin="anonymous",r.fetchPriority="high",t?.onLoad&&(r.onload=t.onLoad),t?.onError&&(r.onerror=t.onError),n.appendChild(r)}function C(i){if(!i)return[];try{return JSON.parse(i.replace(/"/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function pe(i){const e=i?C(i):[],t=[],n=[];let r=!1;for(let s=0;s<e.length;s++){const o=e[s].value;o==="thank-you-journey"?(r=!0,n.push(ot)):t.push(o)}return{roktExtensionsQueryParams:t,legacyRoktExtensions:n,loadThankYouElement:r}}async function St(i,e){const t=[];if(e)for(const n of i)t.push(e.use(n));return Promise.all(t)}function me(i){if(!i)return{};const e={};for(let t=0;t<i.length;t++){const n=i[t];e[n.jsmap]=n.value}return e}function Ee(i){const e={};if(!Array.isArray(i))return e;for(let t=0;t<i.length;t++){const n=i[t];if(!n||!g(n.value)||!g(n.map))continue;const r=n.value,s=n.map;e[r]||(e[r]=[]),e[r].push({eventAttributeKey:s,conditions:Array.isArray(n.conditions)?n.conditions:[]})}return e}function _e(i,e,t){return a().generateHash([i,e,t].join(""))}function yt(i){let n="mParticle_wsdkv_"+a().getVersion()+"_kitv_"+"3.2.2";return i&&(n+="_"+i),n}function J(i){const e=document.createElement("iframe");e.style.display="none",e.setAttribute("sandbox","allow-scripts allow-same-origin"),e.src=i,e.onload=function(){e.onload=null,e.parentNode&&e.parentNode.removeChild(e)};const t=document.body||document.head;t&&t.appendChild(e)}function Ie(i,e){const t=X(window.location.origin);if(S._allowedOriginHashes.indexOf(t)===-1||Math.random()>=st)return;const r=window.__rokt_li_guid__;if(!r||i&&i.includes("://")&&!/^https:\/\//i.test(i))return;const s=window.location.href.split("?")[0].split("#")[0],o="version="+encodeURIComponent(e??"")+"&launcherInstanceGuid="+encodeURIComponent(r)+"&pageUrl="+encodeURIComponent(s),c=i?U(i):"https://apps.rokt.com";J(c+"/v1/wsdk-init/index.html?"+o),J("https://"+rt+"/v1/wsdk-init/index.html?"+o+"&isControl=true")}function At(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function Pt(){return typeof window<"u"?window.location?.href:void 0}function Rt(){return typeof window<"u"?window.navigator?.userAgent:void 0}class Se{constructor(){this._logCount={}}incrementAndCheck(e){const n=(this._logCount[e]||0)+1;return this._logCount[e]=n,n>It}}class K{constructor(e,t,n,r,s){this._reporter="mp-wsdk";const o=e.isLoggingEnabled;this._integrationName=t||"",this._launcherInstanceGuid=n,this._accountId=r||null,this._rateLimiter=s||new Se,this._isEnabled=At()||o}send(e,t,n,r,s,o){if(!(!this._isEnabled||this._rateLimiter.incrementAndCheck(t)))try{const c={additionalInformation:{message:n,version:this._integrationName},severity:t,code:r||q.UNKNOWN_ERROR,url:Pt(),deviceInfo:Rt(),stackTrace:s,reporter:this._reporter,integration:this._integrationName},u={Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","rokt-launcher-version":this._integrationName,"rokt-wsdk-version":"joint"};this._launcherInstanceGuid&&(u["rokt-launcher-instance-guid"]=this._launcherInstanceGuid),this._accountId&&(u["rokt-account-id"]=this._accountId),fetch(e,{method:"POST",headers:u,body:JSON.stringify(c)}).then(l=>{if(!l.ok){const m=new Error("HTTP "+l.status+" from log endpoint");throw m.statusCode=l.status,m}}).catch(l=>{console.error("ReportingTransport: Failed to send log",l),o&&o(l)})}catch(c){console.error("ReportingTransport: Failed to send log",c),o&&o(c)}}}class ye{constructor(e,t,n,r,s){this._transport=new K(e,t,n,r,s),this._errorUrl=ge(e?.errorUrl,e?.integrationDomain,_t)}report(e){if(!e)return;const t=e.severity||I.ERROR;this._transport.send(this._errorUrl,t,e.message,e.code,e.stackTrace)}}class Ae{constructor(e,t,n,r,s,o){this._transport=new K(e,n,r,s,o),this._placementDiagnosticTransport=new K(e,n,r,s),this._loggingUrl=ge(e?.loggingUrl,e?.integrationDomain,Et),this._errorReportingService=t}log(e){e&&this._send(this._transport,e)}logPlacementDiagnostic(e){e&&this._send(this._placementDiagnosticTransport,e)}_send(e,t){e.send(this._loggingUrl,I.INFO,t.message,t.code,void 0,n=>{if(this._errorReportingService){const r=typeof n.statusCode=="number";this._errorReportingService.report({message:"LoggingService: Failed to send log: "+n.message,code:q.LOG_DELIVERY_FAILURE,severity:r?I.ERROR:I.WARNING})}})}}function kt(i){const e=x(window.location.href),t=i.EventAttributes?.title||document.title,n=Ue(),r=i.ActiveTimeOnSite;return{pageUrl:e,sourceMessageId:i.SourceMessageId,timestamp:i.Timestamp,...t?{pageTitle:t}:{},...n!==void 0?{canonicalUrl:n}:{},...Number.isFinite(r)?{activeTimeOnSite:r}:{}}}const E=class E{constructor(){this.name=h,this.id=N,this.moduleId=N,this.isInitialized=!1,this.launcher=null,this.filters={},this.userAttributes={},this.userIdentifiedInWorkspace=!1,this.testHelpers=null,this.placementEventMappingLookup={},this.placementEventAttributeMappingLookup={},this.integrationName=null,this.errorReportingService=null,this.loggingService=null,this._thankYouElementOnLoadCallback=null,this._isThankYouElementLoaded=!1,this._workspaceSearchInFlightPromise=null,this._launcherAttachState=Be(),this.accountId=null,this._preselectState=ze()}getEventAttributeValue(e,t){const n=e&&e.EventAttributes;return!n||n[t]===void 0?null:n[t]}doesEventAttributeConditionMatch(e,t){if(!e||!g(e.operator))return!1;const n=e.operator.toLowerCase(),r=e.attributeValue;return n==="exists"?t!==null:t==null?!1:n==="equals"?String(t)===String(r):n==="contains"?String(t).indexOf(String(r))!==-1:!1}doesEventMatchRule(e,t){if(!t||!g(t.eventAttributeKey))return!1;const n=t.conditions;if(!Array.isArray(n))return!1;const r=this.getEventAttributeValue(e,t.eventAttributeKey);if(n.length===0)return r!==null;for(let s=0;s<n.length;s++)if(!this.doesEventAttributeConditionMatch(n[s],r))return!1;return!0}applyPlacementEventAttributeMapping(e){const t=Object.keys(this.placementEventAttributeMappingLookup);for(let n=0;n<t.length;n++){const r=t[n],s=this.placementEventAttributeMappingLookup[r];if(A(s))continue;let o=!0;for(let c=0;c<s.length;c++)if(!this.doesEventMatchRule(e,s[c])){o=!1;break}o&&a().Rokt.setLocalSessionAttribute?.(r,!0)}}capturePageView(e){let t;try{t=x(window.location.href);const n=ne(),r=kt(e);n.push(r);const s=Math.min(n.length,te),o=Te(n);if(o===0){const c=Y()?"quota":"ls_unavailable";this.loggingService?.log({message:`Rokt Kit: Failed to persist page view for ${t} [reason: ${c}]`,code:"PAGE_VIEW_CAPTURE_FAILED"})}else o<s&&this.loggingService?.log({message:`Rokt Kit: Page view storage reduced from ${s} to ${o} record(s) under quota pressure [reason: quota_eviction]`,code:"PAGE_VIEW_QUOTA_EVICTION"})}catch(n){const r=Y()?"exception":"ls_unavailable",s=n instanceof Error?n.message:String(n);this.loggingService?.log({message:`Rokt Kit: Failed to capture page view for ${t}: ${s} [reason: ${r}]`,code:"PAGE_VIEW_CAPTURE_FAILED"})}}isPreselectionEnabled(){return this.launcher?.enablePreselection===!0}buildCacheMatchKeys(e){if(!this.isPreselectionEnabled())return;const t=We(this.accountId,e);if(t)return t.attributeKeys}buildPreselectHost(){return{accountId:this.accountId,filteredUser:this.filters.filteredUser,userAttributes:this.userAttributes,isKitReady:()=>this.isKitReady(),isPreselectionEnabled:()=>this.isPreselectionEnabled(),getEventAttributeValue:(e,t)=>this.getEventAttributeValue(e,t),logPlacementDiagnostic:e=>this.loggingService?.logPlacementDiagnostic(e),log:e=>this.loggingService?.log(e),selectPlacements:e=>this.selectPlacements(e)}}flushPendingPreselectDispatches(){Je(this._preselectState,this.buildPreselectHost())}isLauncherReadyToAttach(){return!!window.Rokt&&w(window.Rokt.createLauncher)}returnUserIdentities(e){if(!e||!e.getUserIdentities)return{};const t=e.getUserIdentities().userIdentities;return this.replaceOtherIdentityWithEmailsha256(t)}returnLocalSessionAttributes(){return!a().Rokt||typeof a().Rokt.getLocalSessionAttributes!="function"?{}:a().Rokt.getLocalSessionAttributes()}replaceOtherIdentityWithEmailsha256(e){const t={...e||{}},n=this._mappedEmailSha256Key;return n&&e[n]&&(t[E.EMAIL_SHA256_KEY]=e[n]),n&&delete t[n],t}logSelectPlacementsEvent(e){if(!window.mParticle||typeof a().logEvent!="function"||!f(e))return;const t=a().EventType.Other;a().logEvent(nt,t,e)}setRoktSessionId(e){if(!(!e||typeof e!="string"))try{const t=a().getInstance();t&&w(t.setIntegrationAttribute)&&t.setIntegrationAttribute(N,{roktSessionId:e})}catch{}}readMpSessionId(){const e=a()?.sessionManager,t=e?.getSessionId??e?.getSession;if(w(t))return t.call(e)||void 0}readMpDeviceId(){return a()?.getDeviceId?.()||void 0}attachLauncher(e,t,n=[]){Qe(this._launcherAttachState,{accountId:e,launcherOptions:t||{},legacyRoktExtensions:n});const r={accountId:e,...t||{}};let s;return this.isPartnerInLocalLauncherTestGroup()?s=Promise.resolve(window.Rokt.createLocalLauncher(r)):s=window.Rokt.createLauncher(r),s.then(async o=>{await St([...n],o),this.initRoktLauncher(o)}).catch(o=>{et(this._launcherAttachState),console.error("Error creating Rokt launcher:",o)})}recreateLauncherIfTerminated(){return it(this._launcherAttachState,this.isLauncherReadyToAttach(),e=>this.attachLauncher(e.accountId,e.launcherOptions,e.legacyRoktExtensions))}initRoktLauncher(e){window.Rokt&&(window.Rokt.currentLauncher=e),this.launcher=e,Xe(this._launcherAttachState);const t=a().Rokt?.filters;t?(this.filters=t,t.filteredUser?this._workspaceSearchInFlightPromise=this.search(t.filteredUser):console.warn("Rokt Kit: No filtered user has been set.")):console.warn("Rokt Kit: No filters have been set."),this.isInitialized=!0,Ie(this.domain,this.integrationName),a().Rokt.attachKit(this),this.flushPendingPreselectDispatches()}fetchOptimizely(){const e=a()._getActiveForwarders().filter(t=>t.name==="Optimizely");try{if(e.length>0&&window.optimizely){const t=window.optimizely.get("state");return!t||!t.getActiveExperimentIds?{}:t.getActiveExperimentIds().reduce((s,o)=>(s["rokt.custom.optimizely.experiment."+o+".variationId"]=t.getVariationMap()[o].id,s),{})}}catch(t){console.error("Error fetching Optimizely attributes:",t)}return{}}isKitReady(){return!!(this.isInitialized&&this.launcher)}isTargetingDisabled(){return a().Rokt?.launcherOptions?.noTargeting===!0}isPartnerInLocalLauncherTestGroup(){return!!(a().config&&a().config.isLocalLauncherEnabled&&this.isAssignedToSampleGroup())}isAssignedToSampleGroup(){return Math.random()>.5}captureTiming(e){window&&a()&&a().captureTiming&&e&&a().captureTiming(e)}init(e,t,n,r,s){const o=e,c=o.accountId;this.accountId=c||null,this.userAttributes=v(s),this._onboardingExpProvider=o.onboardingExpProvider;const u=C(o.placementEventMapping);this.placementEventMappingLookup=me(u);const l=C(o.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=Ee(l),o.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=o.hashedEmailUserIdentityType.toLowerCase()),this._workspaceIdSyncApiKey=g(o.workspaceIdSyncApiKey)?o.workspaceIdSyncApiKey:void 0;const m=a().Rokt?.domain,{roktExtensionsQueryParams:B,legacyRoktExtensions:D,loadThankYouElement:M}=pe(o.roktExtensions),_={...a().Rokt?.launcherOptions||{}};this.integrationName=yt(_.integrationName),_.integrationName=this.integrationName,this.domain=m;const k={loggingUrl:o.loggingUrl,errorUrl:o.errorUrl,integrationDomain:m,isLoggingEnabled:a().config?.isLoggingEnabled===!0},y=new ye(k,this.integrationName,window.__rokt_li_guid__,o.accountId),b=new Ae(k,y,this.integrationName,window.__rokt_li_guid__,o.accountId);if(this.errorReportingService=y,this.loggingService=b,this.isTargetingDisabled())try{re(),se()}catch(p){this.errorReportingService?.report({message:"Rokt Kit: Failed to clear page views when targeting is disabled",code:"PAGE_VIEW_CAPTURE_FAILED",severity:I.INFO,stackTrace:p instanceof Error?p.stack:void 0})}return a()._registerErrorReportingService&&a()._registerErrorReportingService(y),a()._registerLoggingService&&a()._registerLoggingService(b),n?(this.testHelpers={generateLauncherScript:de,generateThankYouElementScript:he,extractRoktExtensionConfig:pe,hashEventMessage:_e,parseSettingsString:C,generateMappedEventLookup:me,generateMappedEventAttributeLookup:Ee,sendAdBlockMeasurementSignals:Ie,createAutoRemovedIframe:J,djb2:X,setAllowedOriginHashes:p=>{E._allowedOriginHashes=p},ReportingTransport:K,ErrorReportingService:ye,LoggingService:Ae,RateLimiter:Se,ErrorCodes:q,WSDKErrorSeverity:I,resetLauncherAttachState:()=>tt(this._launcherAttachState)},this.attachLauncher(c,_),"Successfully initialized: "+h):(M&&(a().Rokt.flushOnShoppableAdsReadyMessageQueue?.(this),fe(at,he(m),{onLoad:()=>{this._isThankYouElementLoaded=!0,this._thankYouElementOnLoadCallback&&this._thankYouElementOnLoadCallback()},onError:p=>{console.error("Error loading Rokt Thank You Element script:",p)}})),this.isLauncherReadyToAttach()?this.attachLauncher(c,_,D):(fe(ct,de(m,B),{onLoad:()=>{this.isLauncherReadyToAttach()?this.attachLauncher(c,_,D):console.error("Rokt object is not available after script load.")},onError:p=>{console.error("Error loading Rokt launcher script:",p)}}),this.captureTiming(E.PERFORMANCE_MARKS.RoktScriptAppended)),"Successfully initialized: "+h)}process(e){if(this.isTargetingDisabled()||(e.EventDataType===ut&&(Oe(this.loggingService),this.capturePageView(e),le(this._preselectState,this.buildPreselectHost(),e)),e.EventDataType===dt&&(re(),se())),!this.isKitReady())return"Kit not ready for forwarder: "+h;if(w(a().Rokt?.setLocalSessionAttribute)&&(A(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(e),!A(this.placementEventMappingLookup))){const t=_e(e.EventDataType,e.EventCategory,e.EventName??"");this.placementEventMappingLookup[String(t)]&&a().Rokt.setLocalSessionAttribute?.(this.placementEventMappingLookup[String(t)],!0)}return"Successfully sent to forwarder: "+h}setExtensionData(e){if(!this.isKitReady()){console.error("Rokt Kit: Not initialized");return}window.Rokt.setExtensionData(e)}setUserAttribute(e,t){return Q(e)||(this.userAttributes[e]=t),He(this.accountId,e)&&this.flushPendingPreselectDispatches(),"Successfully set user attribute for forwarder: "+h}removeUserAttribute(e){return delete this.userAttributes[e],"Successfully removed user attribute for forwarder: "+h}handleIdentityComplete(e,t){return this.userAttributes=v(e.getAllUserAttributes()),"Successfully called "+t+" for forwarder: "+h}onUserIdentified(e){const t=e;this.filters.filteredUser=t,this._workspaceSearchInFlightPromise=this.search(t);const n=this.handleIdentityComplete(e,"onUserIdentified");return this.flushPendingPreselectDispatches(),n}search(e){const t=this._workspaceIdSyncApiKey;if(!t)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const n=a().Identity?.search;if(typeof n!="function")return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const r=e.getUserIdentities?e.getUserIdentities().userIdentities:null,s={};if(r)for(const u of Object.keys(r)){const l=r[u];g(l)&&l.length>0&&(s[u]=l)}const o=Object.keys(s);if(o.length===0)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const c=o.sort().map(u=>`${u}=${s[u]}`).join("&");return c===this._workspaceLastSearchedIdentitiesKey?this._workspaceSearchInFlightPromise||Promise.resolve():(this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=c,new Promise(u=>{try{n(t,s,l=>{l?.httpCode===200&&(this.userIdentifiedInWorkspace=!0),u()})}catch(l){console.error("Rokt Kit: Workspace IDSync search failed",l),this._workspaceLastSearchedIdentitiesKey=void 0,u()}}))}onLoginComplete(e,t){return this.handleIdentityComplete(e,"onLoginComplete")}onLogoutComplete(e,t){return this.userIdentifiedInWorkspace=!1,this._workspaceSearchInFlightPromise=null,this._workspaceLastSearchedIdentitiesKey=void 0,this.handleIdentityComplete(e,"onLogoutComplete")}onModifyComplete(e,t){return this.handleIdentityComplete(e,"onModifyComplete")}selectPlacements(e){const t=this.recreateLauncherIfTerminated();if(t){const n=this._workspaceSearchInFlightPromise,r=n?Promise.race([n,new Promise(s=>setTimeout(s,ue))]):Promise.resolve();return Promise.all([t,r]).then(()=>this._dispatchPlacements(e))}if(this._workspaceSearchInFlightPromise){const n=this._workspaceSearchInFlightPromise;return Promise.race([n,new Promise(r=>setTimeout(r,ue))]).then(()=>this._dispatchPlacements(e))}return this._dispatchPlacements(e)}_dispatchPlacements(e){const t=e&&e.attributes||{},r={...v(this.userAttributes),...t},s=this.filters||{},o=s.userAttributeFilters||[],c=s.filteredUser||null,u=c?c.getMPID():null;let l;s?s.filterUserAttributes?l=s.filterUserAttributes(r,o):l=r:(console.warn("Rokt Kit: No filters available, using user attributes"),l=r),this.userAttributes=v(l);const m=this._onboardingExpProvider==="Optimizely"?this.fetchOptimizely():{},B=this.returnUserIdentities(c),D=this.returnLocalSessionAttributes(),M=Le(ne()),_=Ne(),k=this.readMpSessionId(),y=this.readMpDeviceId(),b={...B,...l,...m,...D,...M.length?{[ht]:JSON.stringify(M)}:{},..._?{[gt]:_}:{},...this.userIdentifiedInWorkspace?{[lt]:!0}:{},...k?{[ft]:k}:{},...y?{[pt]:y}:{},mpid:u},p=this.buildCacheMatchKeys(typeof e.identifier=="string"?e.identifier:void 0),wt={...e,attributes:b,...p!==void 0?{cacheMatchKeys:p}:{}},Pe=this.launcher.selectPlacements(wt),Re=e.preselect===!0,Tt=()=>{Re||this.logSelectPlacementsEvent(b)};return Promise.resolve(Pe).then(Lt=>{if(!Re)return Lt?.context?.sessionId?.then(Ot=>this.setRoktSessionId(Ot))}).catch(()=>{}).finally(Tt),Pe}hashAttributes(e){return this.isKitReady()?this.launcher.hashAttributes(e):(console.error("Rokt Kit: Not initialized"),null)}use(e){return this.isKitReady()?!e||!g(e)?Promise.reject(new Error("Rokt Kit: Invalid extension name")):this.launcher.use(e):(console.error("Rokt Kit: Not initialized"),Promise.reject(new Error("Rokt Kit: Not initialized")))}terminate(){return this.isKitReady()?(Ze(this._launcherAttachState),this.launcher.terminate()):(console.error("Rokt Kit: Not initialized"),Promise.resolve())}onShoppableAdsReady(e){this._isThankYouElementLoaded?e():this._thankYouElementOnLoadCallback=e}};E._allowedOriginHashes=[-553112570,549508659],E.PERFORMANCE_MARKS={RoktScriptAppended:"mp:RoktScriptAppended"},E.EMAIL_SHA256_KEY="emailsha256";let S=E;function bt(){return N}function vt(i){if(!i){window.console.log("You must pass a config object to register the kit "+h);return}if(!f(i)){window.console.log("'config' must be an object. You passed in a "+typeof i);return}f(i.kits)?i.kits[h]={constructor:S}:(i.kits={},i.kits[h]={constructor:S}),window.console.log("Successfully registered "+h+" to your mParticle configuration")}return typeof window<"u"&&window.mParticle&&a().addForwarder&&a().addForwarder({name:h,constructor:S,getId:bt}),F.register=vt,Object.defineProperty(F,Symbol.toStringTag,{value:"Module"}),F})({});
|
|
1
|
+
var RoktKit=(function(j){"use strict";const ve=["active_time_on_site_ms","billingaddress1","billingaddress2","billingcity","billingstate","billingzipcode","cartitems","ccbin","confirmationref","conversiontype","country","couponcode","currency","language","paymentserviceprovider","paymentserviceproviderattribute","paymenttype","shippingaddress1","shippingcity","shippingcountry","shippingmethod","shippingstate","shippingzipcode","totalprice"],we=new Set(ve);function Z(i){return we.has(i.toLowerCase())}function R(i){const e={},t=i||{},n=Object.keys(t);for(let r=0;r<n.length;r++){const s=n[r];Z(s)||(e[s]=t[s])}return e}function f(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function g(i){return typeof i=="string"}function N(i){return typeof i=="function"}function b(i){return i==null?!0:typeof i=="string"?i.length===0:typeof i=="object"?Object.keys(i).length===0:!1}function V(i){try{const e=new URL(i);return e.search="",e.toString()}catch{return i}}function ee(i){let e=5381;for(let t=0;t<i.length;t++)e=(e<<5)+e+i.charCodeAt(t),e=e&e;return e}const d="mp-rokt-kit",te="__rokt_ls_probe__";function W(){try{return window.localStorage.setItem(te,"1"),window.localStorage.removeItem(te),!0}catch{return!1}}const I=()=>window.localStorage;function H(i,e=I){try{const t=e().getItem(i);return t===null?null:JSON.parse(t)}catch{return null}}function ie(i,e,t=I){try{return t().setItem(i,JSON.stringify(e)),!0}catch{return!1}}function Te(i,e=I){try{e().removeItem(i)}catch{}}function k(i,e,t=I){const n=H(i,t);return f(n)?n[e]:void 0}function U(i,e,t,n=I){const r=H(i,n),s=f(r)?{...r}:{};return s[e]=t,ie(i,s,n)}function C(i,e,t=I){const n=H(i,t);if(!f(n)||!(e in n))return;const r={...n};delete r[e],Object.keys(r).length===0?Te(i,t):ie(i,r,t)}const z="pageViews",K="utmParams",ne=25,Le=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"];function re(i){return i.slice(-ne)}function se(){const i=k(d,z);return Array.isArray(i)?i:[]}function Oe(i){const e=re(i);for(let t=0;t<e.length;t++){const n=e.slice(t);if(U(d,z,n))return n.length}return 0}function oe(){C(d,z)}function Ne(i){const e=re(i);return e.map((t,n)=>{const r=t.activeTimeOnSite,s=r!==void 0&&Number.isFinite(r),c=e[n+1]?.activeTimeOnSite,u=c!==void 0&&Number.isFinite(c),l=s&&u?c-r:void 0;return{pageUrl:t.pageUrl,sourceMessageId:t.sourceMessageId,timestamp:t.timestamp,...t.pageTitle!==void 0?{pageTitle:t.pageTitle}:{},...t.canonicalUrl!==void 0?{canonicalUrl:t.canonicalUrl}:{},...s?{activeTimeOnSite:r}:{},...l!==void 0&&l>=0?{activeTimeOnPage:l}:{}}})}function Ue(i){if(k(d,K)!==void 0)return;const e=new URLSearchParams(window.location.search),t={};for(const r of Le){const s=e.get(r);s&&(t[r]=s)}if(Object.keys(t).length===0)return;const n=Object.keys(t).join(", ");if(!U(d,K,t)){const r=W()?"quota":"ls_unavailable";i?.log({message:`Rokt Kit: Failed to persist UTM params [reason: ${r}]`,code:"UTM_CAPTURE_FAILED"});return}i?.log({message:`Rokt Kit: Captured UTM params [${n}]`,code:"UTM_CAPTURE_SUCCESS"})}function Ce(){const i=k(d,K);return f(i)?i:null}function ce(){C(d,K)}function Ke(){const e=document.querySelector('link[rel="canonical"]')?.href;if(e)return V(e)}const $=[{accountId:"2919171670744024290",pathname:"/checkout",targetPageIdentifier:"prod.rokt.conf",attributeKeys:["email","amount","concessions_total","customertype","eventvenue","firstname","lastname","member_status","billingzipcode","currency"]}],De=6e4;function Me(i){return f(i)&&typeof i.expiresAt=="number"&&f(i.attributes)}function Fe(i,e){return`activePreselect:${i}:${e}`}function xe(i){const e=k(d,i);return Me(e)?e:null}function Ye(i,e){U(d,i,{expiresAt:Date.now()+De,attributes:e})}const Ge=2*6e4;function D(){return window.sessionStorage}function je(i){return f(i)&&typeof i.expiresAt=="number"&&g(i.pathname)&&g(i.identifier)&&f(i.attributes)&&g(i.mpid)}function q(i){return`pendingPreselect:${i}`}function Ve(i){const e=q(i),t=k(d,e,D);return je(t)?t.expiresAt<=Date.now()?(C(d,e,D),null):t:null}function We(i,e,t,n,r){return U(d,q(i),{expiresAt:Date.now()+Ge,pathname:e,identifier:t,attributes:n,mpid:r},D)}function v(i){C(d,q(i),D)}function y(i,e){const t={fired:"PRESELECT_FIRED",missed:"PRESELECT_MISSED",queued:"PRESELECT_QUEUED",skipped:"PRESELECT_SKIPPED"};return{message:`Rokt Kit: preselect ${i} [reason=${e}]`,code:t[i]}}function He(i,e){if(i)return $.find(t=>t.accountId===i&&t.pathname===e)}function ze(i,e){if(!(!i||!g(e)))return $.find(t=>t.accountId===i&&t.targetPageIdentifier===e)}function $e(i,e){return i?$.some(t=>t.accountId===i&&t.attributeKeys.includes(e)):!1}function qe(){return{pending:[]}}function J(i,e){const t=i.pending.findIndex(n=>n.pathname===e.pathname);if(t>=0){i.pending[t]=e;return}i.pending.push(e)}function B(i){if(!i?.getUserIdentities)return!1;const e=i.getUserIdentities().userIdentities;return e?Object.keys(e).some(t=>{const n=e[t];return g(n)&&n.length>0}):!1}function ae(i){const e=i?.getMPID?.();return e==null?null:String(e)}function le(i,e,t){const n=i.filteredUser?.getAllUserAttributes?.()||{},r={},s=[];for(const o of t.attributeKeys){const c=i.getEventAttributeValue(e,o),u=b(c)?i.userAttributes[o]??n[o]:c;if(b(u)){s.push(o);continue}r[o]=u}return{collected:r,missingKeys:s}}function Je(i,e){Promise.resolve(i.selectPlacements(e)).catch(t=>{const n=t instanceof Error?t.message:String(t);i.log({message:`Rokt Kit: Preselect selectPlacements call failed: ${n}`,code:"PRESELECT_DISPATCH_FAILED"})})}function ue(i,e,t,n,r,s){const o=Fe(e,t),c=xe(o),u=!!c&&JSON.stringify(c.attributes)===JSON.stringify(r);if(c&&c.expiresAt>Date.now()&&u){i.logPlacementDiagnostic(y("skipped","active_preselection"));return}Ye(o,r),i.logPlacementDiagnostic(y("fired",s)),Je(i,{attributes:r,preselect:!0,identifier:n,omitUrl:!0})}function Be(i,e){if(!e.accountId||!e.isKitReady())return;const t=Ve(e.accountId);if(t){if(i.pending.some(n=>n.pathname===t.pathname)){v(e.accountId);return}if(!e.isPreselectionEnabled()){v(e.accountId);return}B(e.filteredUser)&&(v(e.accountId),ae(e.filteredUser)===t.mpid&&ue(e,e.accountId,t.identifier,t.identifier,t.attributes,"recovered"))}}function de(i,e,t,n=window.location.pathname){const r=He(e.accountId,n);if(!r)return;if(!e.isKitReady()){const c=[y("queued","not_ready")],u=ae(e.filteredUser);if(e.accountId&&u&&B(e.filteredUser)){const{collected:l,missingKeys:p}=le(e,t,r);if(p.length===0){const w=R(l);We(e.accountId,n,r.targetPageIdentifier,w,u)||c.push(y("queued","persist_failed"))}}J(i,{event:t,pathname:n,storedDiagnostics:c});return}if(!e.isPreselectionEnabled())return;if(!B(e.filteredUser)){e.logPlacementDiagnostic(y("missed","no_valid_identity")),J(i,{event:t,pathname:n});return}const{collected:s,missingKeys:o}=le(e,t,r);if(o.length>0){for(const c of o)e.logPlacementDiagnostic(y("missed",`missing_attribute:${c}`));J(i,{event:t,pathname:n});return}ue(e,e.accountId||"",n,r.targetPageIdentifier,s,"fired")}function Qe(i,e,t=window.location.pathname){if(Be(i,e),i.pending.length===0)return;const n=i.pending;i.pending=[],n.forEach(({event:r,pathname:s,storedDiagnostics:o})=>{s===t&&(e.isKitReady()&&e.isPreselectionEnabled()&&o?.forEach(c=>e.logPlacementDiagnostic(c)),de(i,e,r,s))})}function Xe(){return{context:null,lifecycle:"idle",recreateInFlight:null}}function Ze(i,e){i.context={accountId:e.accountId,launcherOptions:{...e.launcherOptions},legacyRoktExtensions:[...e.legacyRoktExtensions]}}function et(i){i.lifecycle="attached"}function tt(i){i.lifecycle!=="idle"&&(i.lifecycle="terminated")}function it(i){i.lifecycle="terminated"}function nt(i){i.context=null,i.lifecycle="idle",i.recreateInFlight=null}function rt(i,e,t){if(i.recreateInFlight)return i.recreateInFlight;if(i.lifecycle!=="terminated"||!i.context||!e)return;i.lifecycle="recreating";const n=i.context;return i.recreateInFlight=t(n).finally(()=>{i.recreateInFlight=null}),i.recreateInFlight}const h="Rokt",M=181,st="selectPlacements",ot="apps.roktecommerce.com",ct=.1,at="ThankYouPageJourney",lt="rokt-launcher",ut="rokt-thank-you-element",dt="userIdentifiedInWorkspace",ht=3,gt=2,ft="page_events",pt="page_view_attributes",mt="mparticle_session_id",Et="mparticle_device_id",he=500,Q={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST",LOG_DELIVERY_FAILURE:"LOG_DELIVERY_FAILURE"},S={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"},_t="apps.rokt-api.com",It="/v1/log",yt="/v1/errors",St=10;function a(){return window.mParticle}function ge(i,e){const n=[F(i),"/wsdk/integrations/launcher.js"].join("");return!e||e.length===0?n:n+"?extensions="+e.join(",")}function fe(i){return[F(i),"/rokt-elements/rokt-element-thank-you.js"].join("")}function F(i){const e=i!==void 0?i:_t;return e.includes("://")?e.replace(/\/+$/,""):["https://",e].join("")}function pe(i,e,t){if(i)return i.startsWith("http://")||i.startsWith("https://")?i:"https://"+i;const r=e?.includes("://")&&!/^https?:\/\//i.test(e)?void 0:e;return F(r)+t}function me(i,e,t){if(document.getElementById(i))return;const n=document.head||document.body,r=document.createElement("script");r.id=i,r.type="text/javascript",r.src=e,r.async=!0,r.crossOrigin="anonymous",r.fetchPriority="high",t?.onLoad&&(r.onload=t.onLoad),t?.onError&&(r.onerror=t.onError),n.appendChild(r)}function x(i){if(!i)return[];try{return JSON.parse(i.replace(/"/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function Ee(i){const e=i?x(i):[],t=[],n=[];let r=!1;for(let s=0;s<e.length;s++){const o=e[s].value;o==="thank-you-journey"?(r=!0,n.push(at)):t.push(o)}return{roktExtensionsQueryParams:t,legacyRoktExtensions:n,loadThankYouElement:r}}async function At(i,e){const t=[];if(e)for(const n of i)t.push(e.use(n));return Promise.all(t)}function _e(i){if(!i)return{};const e={};for(let t=0;t<i.length;t++){const n=i[t];e[n.jsmap]=n.value}return e}function Ie(i){const e={};if(!Array.isArray(i))return e;for(let t=0;t<i.length;t++){const n=i[t];if(!n||!g(n.value)||!g(n.map))continue;const r=n.value,s=n.map;e[r]||(e[r]=[]),e[r].push({eventAttributeKey:s,conditions:Array.isArray(n.conditions)?n.conditions:[]})}return e}function ye(i,e,t){return a().generateHash([i,e,t].join(""))}function Pt(i){let n="mParticle_wsdkv_"+a().getVersion()+"_kitv_"+"3.3.0";return i&&(n+="_"+i),n}function X(i){const e=document.createElement("iframe");e.style.display="none",e.setAttribute("sandbox","allow-scripts allow-same-origin"),e.src=i,e.onload=function(){e.onload=null,e.parentNode&&e.parentNode.removeChild(e)};const t=document.body||document.head;t&&t.appendChild(e)}function Se(i,e){const t=ee(window.location.origin);if(A._allowedOriginHashes.indexOf(t)===-1||Math.random()>=ct)return;const r=window.__rokt_li_guid__;if(!r||i&&i.includes("://")&&!/^https:\/\//i.test(i))return;const s=window.location.href.split("?")[0].split("#")[0],o="version="+encodeURIComponent(e??"")+"&launcherInstanceGuid="+encodeURIComponent(r)+"&pageUrl="+encodeURIComponent(s),c=i?F(i):"https://apps.rokt.com";X(c+"/v1/wsdk-init/index.html?"+o),X("https://"+ot+"/v1/wsdk-init/index.html?"+o+"&isControl=true")}function Rt(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function bt(){return typeof window<"u"?window.location?.href:void 0}function kt(){return typeof window<"u"?window.navigator?.userAgent:void 0}class Ae{constructor(){this._logCount={}}incrementAndCheck(e){const n=(this._logCount[e]||0)+1;return this._logCount[e]=n,n>St}}class Y{constructor(e,t,n,r,s){this._reporter="mp-wsdk";const o=e.isLoggingEnabled;this._integrationName=t||"",this._launcherInstanceGuid=n,this._accountId=r||null,this._rateLimiter=s||new Ae,this._isEnabled=Rt()||o}send(e,t,n,r,s,o){if(!(!this._isEnabled||this._rateLimiter.incrementAndCheck(t)))try{const c={additionalInformation:{message:n,version:this._integrationName},severity:t,code:r||Q.UNKNOWN_ERROR,url:bt(),deviceInfo:kt(),stackTrace:s,reporter:this._reporter,integration:this._integrationName},u={Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","rokt-launcher-version":this._integrationName,"rokt-wsdk-version":"joint"};this._launcherInstanceGuid&&(u["rokt-launcher-instance-guid"]=this._launcherInstanceGuid),this._accountId&&(u["rokt-account-id"]=this._accountId),fetch(e,{method:"POST",headers:u,body:JSON.stringify(c)}).then(l=>{if(!l.ok){const p=new Error("HTTP "+l.status+" from log endpoint");throw p.statusCode=l.status,p}}).catch(l=>{console.error("ReportingTransport: Failed to send log",l),o&&o(l)})}catch(c){console.error("ReportingTransport: Failed to send log",c),o&&o(c)}}}class Pe{constructor(e,t,n,r,s){this._transport=new Y(e,t,n,r,s),this._errorUrl=pe(e?.errorUrl,e?.integrationDomain,yt)}report(e){if(!e)return;const t=e.severity||S.ERROR;this._transport.send(this._errorUrl,t,e.message,e.code,e.stackTrace)}}class Re{constructor(e,t,n,r,s,o){this._transport=new Y(e,n,r,s,o),this._placementDiagnosticTransport=new Y(e,n,r,s),this._loggingUrl=pe(e?.loggingUrl,e?.integrationDomain,It),this._errorReportingService=t}log(e){e&&this._send(this._transport,e)}logPlacementDiagnostic(e){e&&this._send(this._placementDiagnosticTransport,e)}_send(e,t){e.send(this._loggingUrl,S.INFO,t.message,t.code,void 0,n=>{if(this._errorReportingService){const r=typeof n.statusCode=="number";this._errorReportingService.report({message:"LoggingService: Failed to send log: "+n.message,code:Q.LOG_DELIVERY_FAILURE,severity:r?S.ERROR:S.WARNING})}})}}function vt(i){const e=V(window.location.href),t=i.EventAttributes?.title||document.title,n=Ke(),r=i.ActiveTimeOnSite;return{pageUrl:e,sourceMessageId:i.SourceMessageId,timestamp:i.Timestamp,...t?{pageTitle:t}:{},...n!==void 0?{canonicalUrl:n}:{},...Number.isFinite(r)?{activeTimeOnSite:r}:{}}}const E=class E{constructor(){this.name=h,this.id=M,this.moduleId=M,this.isInitialized=!1,this.launcher=null,this.filters={},this.userAttributes={},this.userIdentifiedInWorkspace=!1,this.testHelpers=null,this.placementEventMappingLookup={},this.placementEventAttributeMappingLookup={},this.integrationName=null,this.errorReportingService=null,this.loggingService=null,this._thankYouElementOnLoadCallback=null,this._isThankYouElementLoaded=!1,this._workspaceSearchInFlightPromise=null,this._launcherAttachState=Xe(),this.accountId=null,this._preselectState=qe()}getEventAttributeValue(e,t){const n=e&&e.EventAttributes;return!n||n[t]===void 0?null:n[t]}doesEventAttributeConditionMatch(e,t){if(!e||!g(e.operator))return!1;const n=e.operator.toLowerCase(),r=e.attributeValue;return n==="exists"?t!==null:t==null?!1:n==="equals"?String(t)===String(r):n==="contains"?String(t).indexOf(String(r))!==-1:!1}doesEventMatchRule(e,t){if(!t||!g(t.eventAttributeKey))return!1;const n=t.conditions;if(!Array.isArray(n))return!1;const r=this.getEventAttributeValue(e,t.eventAttributeKey);if(n.length===0)return r!==null;for(let s=0;s<n.length;s++)if(!this.doesEventAttributeConditionMatch(n[s],r))return!1;return!0}applyPlacementEventAttributeMapping(e){const t=Object.keys(this.placementEventAttributeMappingLookup);for(let n=0;n<t.length;n++){const r=t[n],s=this.placementEventAttributeMappingLookup[r];if(b(s))continue;let o=!0;for(let c=0;c<s.length;c++)if(!this.doesEventMatchRule(e,s[c])){o=!1;break}o&&a().Rokt.setLocalSessionAttribute?.(r,!0)}}capturePageView(e){let t;try{t=V(window.location.href);const n=se(),r=vt(e);n.push(r);const s=Math.min(n.length,ne),o=Oe(n);if(o===0){const c=W()?"quota":"ls_unavailable";this.loggingService?.log({message:`Rokt Kit: Failed to persist page view for ${t} [reason: ${c}]`,code:"PAGE_VIEW_CAPTURE_FAILED"})}else o<s&&this.loggingService?.log({message:`Rokt Kit: Page view storage reduced from ${s} to ${o} record(s) under quota pressure [reason: quota_eviction]`,code:"PAGE_VIEW_QUOTA_EVICTION"})}catch(n){const r=W()?"exception":"ls_unavailable",s=n instanceof Error?n.message:String(n);this.loggingService?.log({message:`Rokt Kit: Failed to capture page view for ${t}: ${s} [reason: ${r}]`,code:"PAGE_VIEW_CAPTURE_FAILED"})}}isPreselectionEnabled(){return this.launcher?.enablePreselection===!0}buildCacheMatchKeys(e){if(!this.isPreselectionEnabled())return;const t=ze(this.accountId,e);if(t)return t.attributeKeys}buildPreselectHost(){return{accountId:this.accountId,filteredUser:this.filters.filteredUser,userAttributes:this.userAttributes,isKitReady:()=>this.isKitReady(),isPreselectionEnabled:()=>this.isPreselectionEnabled(),getEventAttributeValue:(e,t)=>this.getEventAttributeValue(e,t),logPlacementDiagnostic:e=>this.loggingService?.logPlacementDiagnostic(e),log:e=>this.loggingService?.log(e),selectPlacements:e=>this.selectPlacements(e)}}flushPendingPreselectDispatches(){Qe(this._preselectState,this.buildPreselectHost())}isLauncherReadyToAttach(){return!!window.Rokt&&N(window.Rokt.createLauncher)}returnUserIdentities(e){if(!e||!e.getUserIdentities)return{};const t=e.getUserIdentities().userIdentities;return this.replaceOtherIdentityWithEmailsha256(t)}returnLocalSessionAttributes(){return!a().Rokt||typeof a().Rokt.getLocalSessionAttributes!="function"?{}:a().Rokt.getLocalSessionAttributes()}replaceOtherIdentityWithEmailsha256(e){const t={...e||{}},n=this._mappedEmailSha256Key;return n&&e[n]&&(t[E.EMAIL_SHA256_KEY]=e[n]),n&&delete t[n],t}logSelectPlacementsEvent(e){if(!window.mParticle||typeof a().logEvent!="function"||!f(e))return;const t=a().EventType.Other;a().logEvent(st,t,e)}setRoktSessionId(e){if(!(!e||typeof e!="string"))try{const t=a().getInstance();t&&N(t.setIntegrationAttribute)&&t.setIntegrationAttribute(M,{roktSessionId:e})}catch{}}readMpSessionId(){const e=a()?.sessionManager,t=e?.getSessionId??e?.getSession;if(N(t))return t.call(e)||void 0}readMpDeviceId(){return a()?.getDeviceId?.()||void 0}attachLauncher(e,t,n=[]){Ze(this._launcherAttachState,{accountId:e,launcherOptions:t||{},legacyRoktExtensions:n});const r={accountId:e,...t||{}};let s;return this.isPartnerInLocalLauncherTestGroup()?s=Promise.resolve(window.Rokt.createLocalLauncher(r)):s=window.Rokt.createLauncher(r),s.then(async o=>{await At([...n],o),this.initRoktLauncher(o)}).catch(o=>{it(this._launcherAttachState),console.error("Error creating Rokt launcher:",o)})}recreateLauncherIfTerminated(){return rt(this._launcherAttachState,this.isLauncherReadyToAttach(),e=>this.attachLauncher(e.accountId,e.launcherOptions,e.legacyRoktExtensions))}initRoktLauncher(e){window.Rokt&&(window.Rokt.currentLauncher=e),this.launcher=e,et(this._launcherAttachState);const t=a().Rokt?.filters;t?(this.filters=t,t.filteredUser?this._workspaceSearchInFlightPromise=this.search(t.filteredUser):console.warn("Rokt Kit: No filtered user has been set.")):console.warn("Rokt Kit: No filters have been set."),this.isInitialized=!0,Se(this.domain,this.integrationName),a().Rokt.attachKit(this),this.flushPendingPreselectDispatches()}fetchOptimizely(){const e=a()._getActiveForwarders().filter(t=>t.name==="Optimizely");try{if(e.length>0&&window.optimizely){const t=window.optimizely.get("state");return!t||!t.getActiveExperimentIds?{}:t.getActiveExperimentIds().reduce((s,o)=>(s["rokt.custom.optimizely.experiment."+o+".variationId"]=t.getVariationMap()[o].id,s),{})}}catch(t){console.error("Error fetching Optimizely attributes:",t)}return{}}isKitReady(){return!!(this.isInitialized&&this.launcher)}isTargetingDisabled(){return a().Rokt?.launcherOptions?.noTargeting===!0}isPartnerInLocalLauncherTestGroup(){return!!(a().config&&a().config.isLocalLauncherEnabled&&this.isAssignedToSampleGroup())}isAssignedToSampleGroup(){return Math.random()>.5}captureTiming(e){window&&a()&&a().captureTiming&&e&&a().captureTiming(e)}init(e,t,n,r,s){const o=e,c=o.accountId;this.accountId=c||null,this.userAttributes=R(s),this._onboardingExpProvider=o.onboardingExpProvider;const u=x(o.placementEventMapping);this.placementEventMappingLookup=_e(u);const l=x(o.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=Ie(l),o.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=o.hashedEmailUserIdentityType.toLowerCase()),this._workspaceIdSyncApiKey=g(o.workspaceIdSyncApiKey)?o.workspaceIdSyncApiKey:void 0;const p=a().Rokt?.domain,{roktExtensionsQueryParams:w,legacyRoktExtensions:T,loadThankYouElement:G}=Ee(o.roktExtensions),_={...a().Rokt?.launcherOptions||{}};this.integrationName=Pt(_.integrationName),_.integrationName=this.integrationName,this.domain=p;const L={loggingUrl:o.loggingUrl,errorUrl:o.errorUrl,integrationDomain:p,isLoggingEnabled:a().config?.isLoggingEnabled===!0},P=new Pe(L,this.integrationName,window.__rokt_li_guid__,o.accountId),O=new Re(L,P,this.integrationName,window.__rokt_li_guid__,o.accountId);if(this.errorReportingService=P,this.loggingService=O,this.isTargetingDisabled())try{oe(),ce()}catch(m){this.errorReportingService?.report({message:"Rokt Kit: Failed to clear page views when targeting is disabled",code:"PAGE_VIEW_CAPTURE_FAILED",severity:S.INFO,stackTrace:m instanceof Error?m.stack:void 0})}return a()._registerErrorReportingService&&a()._registerErrorReportingService(P),a()._registerLoggingService&&a()._registerLoggingService(O),n?(this.testHelpers={generateLauncherScript:ge,generateThankYouElementScript:fe,extractRoktExtensionConfig:Ee,hashEventMessage:ye,parseSettingsString:x,generateMappedEventLookup:_e,generateMappedEventAttributeLookup:Ie,sendAdBlockMeasurementSignals:Se,createAutoRemovedIframe:X,djb2:ee,setAllowedOriginHashes:m=>{E._allowedOriginHashes=m},ReportingTransport:Y,ErrorReportingService:Pe,LoggingService:Re,RateLimiter:Ae,ErrorCodes:Q,WSDKErrorSeverity:S,resetLauncherAttachState:()=>nt(this._launcherAttachState)},this.attachLauncher(c,_),"Successfully initialized: "+h):(G&&(a().Rokt.flushOnShoppableAdsReadyMessageQueue?.(this),me(ut,fe(p),{onLoad:()=>{this._isThankYouElementLoaded=!0,this._thankYouElementOnLoadCallback&&this._thankYouElementOnLoadCallback()},onError:m=>{console.error("Error loading Rokt Thank You Element script:",m)}})),this.isLauncherReadyToAttach()?this.attachLauncher(c,_,T):(me(lt,ge(p,w),{onLoad:()=>{this.isLauncherReadyToAttach()?this.attachLauncher(c,_,T):console.error("Rokt object is not available after script load.")},onError:m=>{console.error("Error loading Rokt launcher script:",m)}}),this.captureTiming(E.PERFORMANCE_MARKS.RoktScriptAppended)),"Successfully initialized: "+h)}process(e){if(this.isTargetingDisabled()||(e.EventDataType===ht&&(Ue(this.loggingService),this.capturePageView(e),de(this._preselectState,this.buildPreselectHost(),e)),e.EventDataType===gt&&(oe(),ce(),this.accountId&&v(this.accountId))),!this.isKitReady())return"Kit not ready for forwarder: "+h;if(N(a().Rokt?.setLocalSessionAttribute)&&(b(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(e),!b(this.placementEventMappingLookup))){const t=ye(e.EventDataType,e.EventCategory,e.EventName??"");this.placementEventMappingLookup[String(t)]&&a().Rokt.setLocalSessionAttribute?.(this.placementEventMappingLookup[String(t)],!0)}return"Successfully sent to forwarder: "+h}setExtensionData(e){if(!this.isKitReady()){console.error("Rokt Kit: Not initialized");return}window.Rokt.setExtensionData(e)}setUserAttribute(e,t){return Z(e)||(this.userAttributes[e]=t),$e(this.accountId,e)&&this.flushPendingPreselectDispatches(),"Successfully set user attribute for forwarder: "+h}removeUserAttribute(e){return delete this.userAttributes[e],"Successfully removed user attribute for forwarder: "+h}handleIdentityComplete(e,t){return this.userAttributes=R(e.getAllUserAttributes()),"Successfully called "+t+" for forwarder: "+h}onUserIdentified(e){const t=e;this.filters.filteredUser=t,this._workspaceSearchInFlightPromise=this.search(t);const n=this.handleIdentityComplete(e,"onUserIdentified");return this.flushPendingPreselectDispatches(),n}search(e){const t=this._workspaceIdSyncApiKey;if(!t)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const n=a().Identity?.search;if(typeof n!="function")return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const r=e.getUserIdentities?e.getUserIdentities().userIdentities:null,s={};if(r)for(const u of Object.keys(r)){const l=r[u];g(l)&&l.length>0&&(s[u]=l)}const o=Object.keys(s);if(o.length===0)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const c=o.sort().map(u=>`${u}=${s[u]}`).join("&");return c===this._workspaceLastSearchedIdentitiesKey?this._workspaceSearchInFlightPromise||Promise.resolve():(this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=c,new Promise(u=>{try{n(t,s,l=>{l?.httpCode===200&&(this.userIdentifiedInWorkspace=!0),u()})}catch(l){console.error("Rokt Kit: Workspace IDSync search failed",l),this._workspaceLastSearchedIdentitiesKey=void 0,u()}}))}onLoginComplete(e,t){return this.handleIdentityComplete(e,"onLoginComplete")}onLogoutComplete(e,t){return this.userIdentifiedInWorkspace=!1,this._workspaceSearchInFlightPromise=null,this._workspaceLastSearchedIdentitiesKey=void 0,this.accountId&&v(this.accountId),this.handleIdentityComplete(e,"onLogoutComplete")}onModifyComplete(e,t){return this.handleIdentityComplete(e,"onModifyComplete")}selectPlacements(e){const t=this.recreateLauncherIfTerminated();if(t){const n=this._workspaceSearchInFlightPromise,r=n?Promise.race([n,new Promise(s=>setTimeout(s,he))]):Promise.resolve();return Promise.all([t,r]).then(()=>this._dispatchPlacements(e))}if(this._workspaceSearchInFlightPromise){const n=this._workspaceSearchInFlightPromise;return Promise.race([n,new Promise(r=>setTimeout(r,he))]).then(()=>this._dispatchPlacements(e))}return this._dispatchPlacements(e)}_dispatchPlacements(e){const t=e&&e.attributes||{},r={...R(this.userAttributes),...t},s=this.filters||{},o=s.userAttributeFilters||[],c=s.filteredUser||null,u=c?c.getMPID():null;let l;s?s.filterUserAttributes?l=s.filterUserAttributes(r,o):l=r:(console.warn("Rokt Kit: No filters available, using user attributes"),l=r),this.userAttributes=R(l);const p=this._onboardingExpProvider==="Optimizely"?this.fetchOptimizely():{},w=this.returnUserIdentities(c),T=this.returnLocalSessionAttributes(),G=Ne(se()),_=Ce(),L=this.readMpSessionId(),P=this.readMpDeviceId(),O={...w,...l,...p,...T,...G.length?{[ft]:JSON.stringify(G)}:{},..._?{[pt]:_}:{},...this.userIdentifiedInWorkspace?{[dt]:!0}:{},...L?{[mt]:L}:{},...P?{[Et]:P}:{},mpid:u},m=this.buildCacheMatchKeys(typeof e.identifier=="string"?e.identifier:void 0),Lt={...e,attributes:O,...m!==void 0?{cacheMatchKeys:m}:{}},be=this.launcher.selectPlacements(Lt),ke=e.preselect===!0,Ot=()=>{ke||this.logSelectPlacementsEvent(O)};return Promise.resolve(be).then(Nt=>{if(!ke)return Nt?.context?.sessionId?.then(Ut=>this.setRoktSessionId(Ut))}).catch(()=>{}).finally(Ot),be}hashAttributes(e){return this.isKitReady()?this.launcher.hashAttributes(e):(console.error("Rokt Kit: Not initialized"),null)}use(e){return this.isKitReady()?!e||!g(e)?Promise.reject(new Error("Rokt Kit: Invalid extension name")):this.launcher.use(e):(console.error("Rokt Kit: Not initialized"),Promise.reject(new Error("Rokt Kit: Not initialized")))}terminate(){return this.isKitReady()?(tt(this._launcherAttachState),this.launcher.terminate()):(console.error("Rokt Kit: Not initialized"),Promise.resolve())}onShoppableAdsReady(e){this._isThankYouElementLoaded?e():this._thankYouElementOnLoadCallback=e}};E._allowedOriginHashes=[-553112570,549508659],E.PERFORMANCE_MARKS={RoktScriptAppended:"mp:RoktScriptAppended"},E.EMAIL_SHA256_KEY="emailsha256";let A=E;function wt(){return M}function Tt(i){if(!i){window.console.log("You must pass a config object to register the kit "+h);return}if(!f(i)){window.console.log("'config' must be an object. You passed in a "+typeof i);return}f(i.kits)?i.kits[h]={constructor:A}:(i.kits={},i.kits[h]={constructor:A}),window.console.log("Successfully registered "+h+" to your mParticle configuration")}return typeof window<"u"&&window.mParticle&&a().addForwarder&&a().addForwarder({name:h,constructor:A,getId:wt}),j.register=Tt,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"}),j})({});
|
|
2
2
|
//# sourceMappingURL=Rokt-Kit.iife.js.map
|