@mparticle/web-rokt-kit 1.36.1 → 3.2.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.
@@ -1,2 +1,2 @@
1
- var RoktKit=(function(N){"use strict";const ge=["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"],fe=new Set(ge);function W(i){return fe.has(i.toLowerCase())}function R(i){const e={},t=i||{},n=Object.keys(t);for(let r=0;r<n.length;r++){const o=n[r];W(o)||(e[o]=t[o])}return e}function m(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function E(i){return typeof i=="string"}function v(i){return typeof i=="function"}function U(i){return i==null?!0:typeof i=="object"?Object.keys(i).length===0:!1}function C(i){try{const e=new URL(i);return e.search="",e.toString()}catch{return i}}const H="__rokt_ls_probe__";function M(){try{return window.localStorage.setItem(H,"1"),window.localStorage.removeItem(H),!0}catch{return!1}}function K(i){try{const e=window.localStorage.getItem(i);return e===null?null:JSON.parse(e)}catch{return null}}function V(i,e){try{return window.localStorage.setItem(i,JSON.stringify(e)),!0}catch{return!1}}function me(i){try{window.localStorage.removeItem(i)}catch{}}function F(i,e){const t=K(i);return m(t)?t[e]:void 0}function z(i,e,t){const n=K(i),r=m(n)?{...n}:{};return r[e]=t,V(i,r)}function q(i,e){const t=K(i);if(!m(t)||!(e in t))return;const n={...t};delete n[e],Object.keys(n).length===0?me(i):V(i,n)}const _="mp-rokt-kit",D="pageViews",w="utmParams",$=25,Ee=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"];function J(i){return i.slice(-$)}function B(){const i=F(_,D);return Array.isArray(i)?i:[]}function _e(i){const e=J(i);for(let t=0;t<e.length;t++){const n=e.slice(t);if(z(_,D,n))return n.length}return 0}function Q(){q(_,D)}function Ie(i){const e=J(i);return e.map((t,n)=>{const r=t.activeTimeOnSite,o=r!==void 0&&Number.isFinite(r),c=e[n+1]?.activeTimeOnSite,u=c!==void 0&&Number.isFinite(c),l=o&&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}:{},...o?{activeTimeOnSite:r}:{},...l!==void 0&&l>=0?{activeTimeOnPage:l}:{}}})}function Se(i){if(F(_,w)!==void 0)return;const e=new URLSearchParams(window.location.search),t={};for(const r of Ee){const o=e.get(r);o&&(t[r]=o)}if(Object.keys(t).length===0)return;const n=Object.keys(t).join(", ");if(!z(_,w,t)){const r=M()?"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 ye(){const i=F(_,w);return m(i)?i:null}function X(){q(_,w)}function Ae(){const e=document.querySelector('link[rel="canonical"]')?.href;if(e)return C(e)}function ke(){return{context:null,lifecycle:"idle",recreateInFlight:null}}function Re(i,e){i.context={accountId:e.accountId,launcherOptions:{...e.launcherOptions},legacyRoktExtensions:[...e.legacyRoktExtensions]}}function ve(i){i.lifecycle="attached"}function we(i){i.lifecycle!=="idle"&&(i.lifecycle="terminated")}function be(i){i.lifecycle="terminated"}function Te(i){i.context=null,i.lifecycle="idle",i.recreateInFlight=null}function Le(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 d="Rokt",b=181,Pe="selectPlacements",Oe="apps.roktecommerce.com",Ne=.1,Ue="ThankYouPageJourney",Ce="rokt-launcher",Me="rokt-thank-you-element",Ke="userIdentifiedInWorkspace",Fe=3,De=2,xe="page_events",Ye="page_view_attributes",je="mparticle_session_id",Ge="mparticle_device_id",Z=500,x={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"},We="apps.rokt-api.com",He="/v1/log",Ve="/v1/errors",ze=10;function a(){return window.mParticle}function ee(i,e){const n=[T(i),"/wsdk/integrations/launcher.js"].join("");return!e||e.length===0?n:n+"?extensions="+e.join(",")}function te(i){return[T(i),"/rokt-elements/rokt-element-thank-you.js"].join("")}function T(i){const e=typeof i<"u"?i:We;return e.includes("://")?e.replace(/\/+$/,""):["https://",e].join("")}function ie(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 T(r)+t}function ne(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 L(i){if(!i)return[];try{return JSON.parse(i.replace(/&quot;/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function re(i){const e=i?L(i):[],t=[],n=[];let r=!1;for(let o=0;o<e.length;o++){const s=e[o].value;s==="thank-you-journey"?(r=!0,n.push(Ue)):t.push(s)}return{roktExtensionsQueryParams:t,legacyRoktExtensions:n,loadThankYouElement:r}}async function qe(i,e){const t=[];if(e)for(const n of i)t.push(e.use(n));return Promise.all(t)}function oe(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 se(i){const e={};if(!Array.isArray(i))return e;for(let t=0;t<i.length;t++){const n=i[t];if(!n||!E(n.value)||!E(n.map))continue;const r=n.value,o=n.map;e[r]||(e[r]=[]),e[r].push({eventAttributeKey:o,conditions:Array.isArray(n.conditions)?n.conditions:[]})}return e}function ae(i,e,t){return a().generateHash([i,e,t].join(""))}function $e(i){let n="mParticle_wsdkv_"+a().getVersion()+"_kitv_"+"1.36.1";return i&&(n+="_"+i),n}function ce(i){let e=5381;for(let t=0;t<i.length;t++)e=(e<<5)+e+i.charCodeAt(t),e=e&e;return e}function Y(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 le(i,e){const t=ce(window.location.origin);if(S._allowedOriginHashes.indexOf(t)===-1||Math.random()>=Ne)return;const r=window.__rokt_li_guid__;if(!r||i&&i.includes("://")&&!/^https:\/\//i.test(i))return;const o=window.location.href.split("?")[0].split("#")[0],s="version="+encodeURIComponent(e??"")+"&launcherInstanceGuid="+encodeURIComponent(r)+"&pageUrl="+encodeURIComponent(o),c=i?T(i):"https://apps.rokt.com";Y(c+"/v1/wsdk-init/index.html?"+s),Y("https://"+Oe+"/v1/wsdk-init/index.html?"+s+"&isControl=true")}function Je(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function Be(){return typeof window<"u"?window.location?.href:void 0}function Qe(){return typeof window<"u"?window.navigator?.userAgent:void 0}class ue{constructor(){this._logCount={}}incrementAndCheck(e){const n=(this._logCount[e]||0)+1;return this._logCount[e]=n,n>ze}}class j{constructor(e,t,n,r,o){this._reporter="mp-wsdk";const s=e.isLoggingEnabled;this._integrationName=t||"",this._launcherInstanceGuid=n,this._accountId=r||null,this._rateLimiter=o||new ue,this._isEnabled=Je()||s}send(e,t,n,r,o,s){if(!(!this._isEnabled||this._rateLimiter.incrementAndCheck(t)))try{const c={additionalInformation:{message:n,version:this._integrationName},severity:t,code:r||x.UNKNOWN_ERROR,url:Be(),deviceInfo:Qe(),stackTrace:o,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),s&&s(l)})}catch(c){console.error("ReportingTransport: Failed to send log",c),s&&s(c)}}}class de{constructor(e,t,n,r,o){this._transport=new j(e,t,n,r,o),this._errorUrl=ie(e?.errorUrl,e?.integrationDomain,Ve)}report(e){if(!e)return;const t=e.severity||I.ERROR;this._transport.send(this._errorUrl,t,e.message,e.code,e.stackTrace)}}class he{constructor(e,t,n,r,o,s){this._transport=new j(e,n,r,o,s),this._loggingUrl=ie(e?.loggingUrl,e?.integrationDomain,He),this._errorReportingService=t}log(e){e&&this._transport.send(this._loggingUrl,I.INFO,e.message,e.code,void 0,t=>{if(this._errorReportingService){const n=typeof t.statusCode=="number";this._errorReportingService.report({message:"LoggingService: Failed to send log: "+t.message,code:x.LOG_DELIVERY_FAILURE,severity:n?I.ERROR:I.WARNING})}})}}function Xe(i){const e=C(window.location.href),t=i.EventAttributes?.title||document.title,n=Ae(),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 g=class g{constructor(){this.name=d,this.id=b,this.moduleId=b,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=ke()}getEventAttributeValue(e,t){const n=e&&e.EventAttributes;return!n||typeof n[t]>"u"?null:n[t]}doesEventAttributeConditionMatch(e,t){if(!e||!E(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||!E(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 o=0;o<n.length;o++)if(!this.doesEventAttributeConditionMatch(n[o],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],o=this.placementEventAttributeMappingLookup[r];if(U(o))continue;let s=!0;for(let c=0;c<o.length;c++)if(!this.doesEventMatchRule(e,o[c])){s=!1;break}s&&a().Rokt.setLocalSessionAttribute?.(r,!0)}}capturePageView(e){let t;try{t=C(window.location.href);const n=B(),r=Xe(e);n.push(r);const o=Math.min(n.length,$),s=_e(n);if(s===0){const c=M()?"quota":"ls_unavailable";this.loggingService?.log({message:`Rokt Kit: Failed to persist page view for ${t} [reason: ${c}]`,code:"PAGE_VIEW_CAPTURE_FAILED"})}else s<o&&this.loggingService?.log({message:`Rokt Kit: Page view storage reduced from ${o} to ${s} record(s) under quota pressure [reason: quota_eviction]`,code:"PAGE_VIEW_QUOTA_EVICTION"})}catch(n){const r=M()?"exception":"ls_unavailable",o=n instanceof Error?n.message:String(n);this.loggingService?.log({message:`Rokt Kit: Failed to capture page view for ${t}: ${o} [reason: ${r}]`,code:"PAGE_VIEW_CAPTURE_FAILED"})}}isLauncherReadyToAttach(){return!!window.Rokt&&v(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[g.EMAIL_SHA256_KEY]=e[n]),n&&delete t[n],t}logSelectPlacementsEvent(e){if(!window.mParticle||typeof a().logEvent!="function"||!m(e))return;const t=a().EventType.Other;a().logEvent(Pe,t,e)}setRoktSessionId(e){if(!(!e||typeof e!="string"))try{const t=a().getInstance();t&&v(t.setIntegrationAttribute)&&t.setIntegrationAttribute(b,{roktSessionId:e})}catch{}}readMpSessionId(){const e=a()?.sessionManager,t=e?.getSessionId??e?.getSession;if(v(t))return t.call(e)||void 0}readMpDeviceId(){return a()?.getDeviceId?.()||void 0}attachLauncher(e,t,n=[]){Re(this._launcherAttachState,{accountId:e,launcherOptions:t||{},legacyRoktExtensions:n});const r={accountId:e,...t||{}};let o;return this.isPartnerInLocalLauncherTestGroup()?o=Promise.resolve(window.Rokt.createLocalLauncher(r)):o=window.Rokt.createLauncher(r),o.then(async s=>{await qe([...n],s),this.initRoktLauncher(s)}).catch(s=>{be(this._launcherAttachState),console.error("Error creating Rokt launcher:",s)})}recreateLauncherIfTerminated(){return Le(this._launcherAttachState,this.isLauncherReadyToAttach(),e=>this.attachLauncher(e.accountId,e.launcherOptions,e.legacyRoktExtensions))}initRoktLauncher(e){window.Rokt&&(window.Rokt.currentLauncher=e),this.launcher=e,ve(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,le(this.domain,this.integrationName),a().Rokt.attachKit(this)}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((o,s)=>(o["rokt.custom.optimizely.experiment."+s+".variationId"]=t.getVariationMap()[s].id,o),{})}}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,o){const s=e,c=s.accountId;this.userAttributes=R(o),this._onboardingExpProvider=s.onboardingExpProvider;const u=L(s.placementEventMapping);this.placementEventMappingLookup=oe(u);const l=L(s.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=se(l),s.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=s.hashedEmailUserIdentityType.toLowerCase()),this._workspaceIdSyncApiKey=E(s.workspaceIdSyncApiKey)?s.workspaceIdSyncApiKey:void 0;const p=a().Rokt?.domain,{roktExtensionsQueryParams:G,legacyRoktExtensions:P,loadThankYouElement:O}=re(s.roktExtensions),f={...a().Rokt?.launcherOptions||{}};this.integrationName=$e(f.integrationName),f.integrationName=this.integrationName,this.domain=p;const A={loggingUrl:s.loggingUrl,errorUrl:s.errorUrl,integrationDomain:p,isLoggingEnabled:a().config?.isLoggingEnabled===!0},y=new de(A,this.integrationName,window.__rokt_li_guid__,s.accountId),k=new he(A,y,this.integrationName,window.__rokt_li_guid__,s.accountId);if(this.errorReportingService=y,this.loggingService=k,this.isTargetingDisabled())try{Q(),X()}catch(h){this.errorReportingService?.report({message:"Rokt Kit: Failed to clear page views when targeting is disabled",code:"PAGE_VIEW_CAPTURE_FAILED",severity:I.INFO,stackTrace:h instanceof Error?h.stack:void 0})}return a()._registerErrorReportingService&&a()._registerErrorReportingService(y),a()._registerLoggingService&&a()._registerLoggingService(k),n?(this.testHelpers={generateLauncherScript:ee,generateThankYouElementScript:te,extractRoktExtensionConfig:re,hashEventMessage:ae,parseSettingsString:L,generateMappedEventLookup:oe,generateMappedEventAttributeLookup:se,sendAdBlockMeasurementSignals:le,createAutoRemovedIframe:Y,djb2:ce,setAllowedOriginHashes:h=>{g._allowedOriginHashes=h},ReportingTransport:j,ErrorReportingService:de,LoggingService:he,RateLimiter:ue,ErrorCodes:x,WSDKErrorSeverity:I,resetLauncherAttachState:()=>Te(this._launcherAttachState)},this.attachLauncher(c,f),"Successfully initialized: "+d):(O&&(a().Rokt.flushOnShoppableAdsReadyMessageQueue?.(this),ne(Me,te(p),{onLoad:()=>{this._isThankYouElementLoaded=!0,this._thankYouElementOnLoadCallback&&this._thankYouElementOnLoadCallback()},onError:h=>{console.error("Error loading Rokt Thank You Element script:",h)}})),this.isLauncherReadyToAttach()?this.attachLauncher(c,f,P):(ne(Ce,ee(p,G),{onLoad:()=>{this.isLauncherReadyToAttach()?this.attachLauncher(c,f,P):console.error("Rokt object is not available after script load.")},onError:h=>{console.error("Error loading Rokt launcher script:",h)}}),this.captureTiming(g.PERFORMANCE_MARKS.RoktScriptAppended)),"Successfully initialized: "+d)}process(e){if(this.isTargetingDisabled()||(e.EventDataType===Fe&&(Se(this.loggingService),this.capturePageView(e)),e.EventDataType===De&&(Q(),X())),!this.isKitReady())return"Kit not ready for forwarder: "+d;if(v(a().Rokt?.setLocalSessionAttribute)&&(U(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(e),!U(this.placementEventMappingLookup))){const t=ae(e.EventDataType,e.EventCategory,e.EventName??"");this.placementEventMappingLookup[String(t)]&&a().Rokt.setLocalSessionAttribute?.(this.placementEventMappingLookup[String(t)],!0)}return"Successfully sent to forwarder: "+d}setExtensionData(e){if(!this.isKitReady()){console.error("Rokt Kit: Not initialized");return}window.Rokt.setExtensionData(e)}setUserAttribute(e,t){return W(e)||(this.userAttributes[e]=t),"Successfully set user attribute for forwarder: "+d}removeUserAttribute(e){return delete this.userAttributes[e],"Successfully removed user attribute for forwarder: "+d}handleIdentityComplete(e,t){return this.userAttributes=R(e.getAllUserAttributes()),"Successfully called "+t+" for forwarder: "+d}onUserIdentified(e){const t=e;return this.filters.filteredUser=t,this._workspaceSearchInFlightPromise=this.search(t),this.handleIdentityComplete(e,"onUserIdentified")}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,o={};if(r)for(const u of Object.keys(r)){const l=r[u];E(l)&&l.length>0&&(o[u]=l)}const s=Object.keys(o);if(s.length===0)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const c=s.sort().map(u=>`${u}=${o[u]}`).join("&");return c===this._workspaceLastSearchedIdentitiesKey?this._workspaceSearchInFlightPromise||Promise.resolve():(this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=c,new Promise(u=>{try{n(t,o,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(o=>setTimeout(o,Z))]):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,Z))]).then(()=>this._dispatchPlacements(e))}return this._dispatchPlacements(e)}_dispatchPlacements(e){const t=e&&e.attributes||{},r={...R(this.userAttributes),...t},o=this.filters||{},s=o.userAttributeFilters||[],c=o.filteredUser||null,u=c?c.getMPID():null;let l;o?o.filterUserAttributes?l=o.filterUserAttributes(r,s):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():{},G=this.returnUserIdentities(c),P=this.returnLocalSessionAttributes(),O=Ie(B()),f=ye(),A=this.readMpSessionId(),y=this.readMpDeviceId(),k={...G,...l,...p,...P,...O.length?{[xe]:JSON.stringify(O)}:{},...f?{[Ye]:f}:{},...this.userIdentifiedInWorkspace?{[Ke]:!0}:{},...A?{[je]:A}:{},...y?{[Ge]:y}:{},mpid:u},h={...e,attributes:k},pe=this.launcher.selectPlacements(h),tt=()=>this.logSelectPlacementsEvent(k);return Promise.resolve(pe).then(it=>it?.context?.sessionId?.then(nt=>this.setRoktSessionId(nt))).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||!E(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()?(we(this._launcherAttachState),this.launcher.terminate()):(console.error("Rokt Kit: Not initialized"),Promise.resolve())}onShoppableAdsReady(e){this._isThankYouElementLoaded?e():this._thankYouElementOnLoadCallback=e}};g._allowedOriginHashes=[-553112570,549508659],g.PERFORMANCE_MARKS={RoktScriptAppended:"mp:RoktScriptAppended"},g.EMAIL_SHA256_KEY="emailsha256";let S=g;function Ze(){return b}function et(i){if(!i){window.console.log("You must pass a config object to register the kit "+d);return}if(!m(i)){window.console.log("'config' must be an object. You passed in a "+typeof i);return}m(i.kits)?i.kits[d]={constructor:S}:(i.kits={},i.kits[d]={constructor:S}),window.console.log("Successfully registered "+d+" to your mParticle configuration")}return typeof window<"u"&&window.mParticle&&a().addForwarder&&a().addForwarder({name:d,constructor:S,getId:Ze}),N.register=et,Object.defineProperty(N,Symbol.toStringTag,{value:"Module"}),N})({});
1
+ var RoktKit=(function(M){"use strict";const Se=["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"],ye=new Set(Se);function q(i){return ye.has(i.toLowerCase())}function L(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 m(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function E(i){return typeof i=="string"}function O(i){return typeof i=="function"}function P(i){return i==null?!0:typeof i=="string"?i.length===0:typeof i=="object"?Object.keys(i).length===0:!1}function F(i){try{const e=new URL(i);return e.search="",e.toString()}catch{return i}}function J(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 _="mp-rokt-kit",B="__rokt_ls_probe__";function x(){try{return window.localStorage.setItem(B,"1"),window.localStorage.removeItem(B),!0}catch{return!1}}function Y(i){try{const e=window.localStorage.getItem(i);return e===null?null:JSON.parse(e)}catch{return null}}function Q(i,e){try{return window.localStorage.setItem(i,JSON.stringify(e)),!0}catch{return!1}}function Ae(i){try{window.localStorage.removeItem(i)}catch{}}function N(i,e){const t=Y(i);return m(t)?t[e]:void 0}function j(i,e,t){const n=Y(i),r=m(n)?{...n}:{};return r[e]=t,Q(i,r)}function X(i,e){const t=Y(i);if(!m(t)||!(e in t))return;const n={...t};delete n[e],Object.keys(n).length===0?Ae(i):Q(i,n)}const V="pageViews",U="utmParams",Z=25,ve=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"];function ee(i){return i.slice(-Z)}function te(){const i=N(_,V);return Array.isArray(i)?i:[]}function be(i){const e=ee(i);for(let t=0;t<e.length;t++){const n=e.slice(t);if(j(_,V,n))return n.length}return 0}function ie(){X(_,V)}function Pe(i){const e=ee(i);return e.map((t,n)=>{const r=t.activeTimeOnSite,s=r!==void 0&&Number.isFinite(r),a=e[n+1]?.activeTimeOnSite,u=a!==void 0&&Number.isFinite(a),l=s&&u?a-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 Re(i){if(N(_,U)!==void 0)return;const e=new URLSearchParams(window.location.search),t={};for(const r of ve){const s=e.get(r);s&&(t[r]=s)}if(Object.keys(t).length===0)return;const n=Object.keys(t).join(", ");if(!j(_,U,t)){const r=x()?"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 ke(){const i=N(_,U);return m(i)?i:null}function ne(){X(_,U)}function Te(){const e=document.querySelector('link[rel="canonical"]')?.href;if(e)return F(e)}const G=[{accountId:"2919171670744024290",pathname:"/checkout",targetPageIdentifier:"prod.rokt.conf",attributeKeys:["email","amount","concessions_total","customertype","eventvenue","firstname","lastname","locale","member_status","billingzipcode","country","currency","language"]}];function we(i,e){if(i)return G.find(t=>t.accountId===i&&t.pathname===e)}function Le(i,e){if(!(!i||!E(e)))return G.find(t=>t.accountId===i&&t.targetPageIdentifier===e)}function Oe(i,e){return i?G.some(t=>t.accountId===i&&t.attributeKeys.includes(e)):!1}const Ne=6e4;function Ue(i){return m(i)&&typeof i.expiresAt=="number"&&m(i.attributes)}function Ce(i,e){return`activePreselect:${i}:${e}`}function De(i){const e=N(_,i);return Ue(e)?e:null}function Ke(i,e){j(_,i,{expiresAt:Date.now()+Ne,attributes:e})}function H(i,e){return{message:`Rokt Kit: ${i} called [attributeKeys=${e.join(",")}]`,code:"ATTRIBUTE_SETTER_CALLED"}}function Me(i){return{message:`Rokt Kit: selectPlacements dispatched [placementAttributeKeys=${i.join(",")}]`,code:"SELECT_PLACEMENTS_DISPATCHED"}}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 Fe(){return{pending:[]}}function W(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 xe(i){if(!i?.getUserIdentities)return!1;const e=i.getUserIdentities().userIdentities;return e?Object.keys(e).some(t=>{const n=e[t];return E(n)&&n.length>0}):!1}function Ye(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 re(i,e,t,n=window.location.pathname){const r=we(e.accountId,n);if(!r)return;if(!e.isKitReady()){W(i,{event:t,pathname:n}),e.logPlacementDiagnostic(R("queued","not_ready"));return}if(!e.isPreselectionEnabled())return;if(!xe(e.filteredUser)){e.logPlacementDiagnostic(R("missed","no_valid_identity")),W(i,{event:t,pathname:n});return}const s=e.filteredUser?.getAllUserAttributes?.()||{},o={},a=[];for(const h of r.attributeKeys){const S=e.getEventAttributeValue(t,h),p=P(S)?e.userAttributes[h]??s[h]:S;if(P(p)){a.push(h);continue}o[h]=p}if(a.length>0){for(const h of a)e.logPlacementDiagnostic(R("missed",`missing_attribute:${h}`));W(i,{event:t,pathname:n});return}const u=Ce(e.accountId||"",n),l=De(u),g=!!l&&JSON.stringify(l.attributes)===JSON.stringify(o);if(l&&l.expiresAt>Date.now()&&g){e.logPlacementDiagnostic(R("skipped","active_preselection"));return}const T={attributes:o,preselect:!0,identifier:r.targetPageIdentifier,omitUrl:!0};Ke(u,o),e.logPlacementDiagnostic(R("fired","fired")),Ye(e,T)}function je(i,e,t=window.location.pathname){if(i.pending.length===0)return;const n=i.pending;i.pending=[],n.forEach(({event:r,pathname:s})=>{s===t&&re(i,e,r,s)})}function Ve(){return{context:null,lifecycle:"idle",recreateInFlight:null}}function Ge(i,e){i.context={accountId:e.accountId,launcherOptions:{...e.launcherOptions},legacyRoktExtensions:[...e.legacyRoktExtensions]}}function He(i){i.lifecycle="attached"}function We(i){i.lifecycle!=="idle"&&(i.lifecycle="terminated")}function ze(i){i.lifecycle="terminated"}function $e(i){i.context=null,i.lifecycle="idle",i.recreateInFlight=null}function qe(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 d="Rokt",C=181,Je="selectPlacements",Be="apps.roktecommerce.com",Qe=.1,Xe="ThankYouPageJourney",Ze="rokt-launcher",et="rokt-thank-you-element",tt="userIdentifiedInWorkspace",it=3,nt=2,rt="page_events",st="page_view_attributes",ot="mparticle_session_id",ct="mparticle_device_id",se=500,z={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST",LOG_DELIVERY_FAILURE:"LOG_DELIVERY_FAILURE"},y={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"},at="apps.rokt-api.com",lt="/v1/log",ut="/v1/errors",dt=10;function c(){return window.mParticle}function oe(i,e){const n=[D(i),"/wsdk/integrations/launcher.js"].join("");return!e||e.length===0?n:n+"?extensions="+e.join(",")}function ce(i){return[D(i),"/rokt-elements/rokt-element-thank-you.js"].join("")}function D(i){const e=i!==void 0?i:at;return e.includes("://")?e.replace(/\/+$/,""):["https://",e].join("")}function ae(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 D(r)+t}function le(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 K(i){if(!i)return[];try{return JSON.parse(i.replace(/&quot;/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function ue(i){const e=i?K(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(Xe)):t.push(o)}return{roktExtensionsQueryParams:t,legacyRoktExtensions:n,loadThankYouElement:r}}async function ht(i,e){const t=[];if(e)for(const n of i)t.push(e.use(n));return Promise.all(t)}function de(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 he(i){const e={};if(!Array.isArray(i))return e;for(let t=0;t<i.length;t++){const n=i[t];if(!n||!E(n.value)||!E(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 ge(i,e,t){return c().generateHash([i,e,t].join(""))}function gt(i){let n="mParticle_wsdkv_"+c().getVersion()+"_kitv_"+"3.2.0";return i&&(n+="_"+i),n}function $(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 pe(i,e){const t=J(window.location.origin);if(A._allowedOriginHashes.indexOf(t)===-1||Math.random()>=Qe)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),a=i?D(i):"https://apps.rokt.com";$(a+"/v1/wsdk-init/index.html?"+o),$("https://"+Be+"/v1/wsdk-init/index.html?"+o+"&isControl=true")}function pt(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function ft(){return typeof window<"u"?window.location?.href:void 0}function mt(){return typeof window<"u"?window.navigator?.userAgent:void 0}class fe{constructor(){this._logCount={}}incrementAndCheck(e){const n=(this._logCount[e]||0)+1;return this._logCount[e]=n,n>dt}}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 fe,this._isEnabled=pt()||o}send(e,t,n,r,s,o){if(!(!this._isEnabled||this._rateLimiter.incrementAndCheck(t)))try{const a={additionalInformation:{message:n,version:this._integrationName},severity:t,code:r||z.UNKNOWN_ERROR,url:ft(),deviceInfo:mt(),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(a)}).then(l=>{if(!l.ok){const g=new Error("HTTP "+l.status+" from log endpoint");throw g.statusCode=l.status,g}}).catch(l=>{console.error("ReportingTransport: Failed to send log",l),o&&o(l)})}catch(a){console.error("ReportingTransport: Failed to send log",a),o&&o(a)}}}class me{constructor(e,t,n,r,s){this._transport=new k(e,t,n,r,s),this._errorUrl=ae(e?.errorUrl,e?.integrationDomain,ut)}report(e){if(!e)return;const t=e.severity||y.ERROR;this._transport.send(this._errorUrl,t,e.message,e.code,e.stackTrace)}}class Ee{constructor(e,t,n,r,s,o){this._transport=new k(e,n,r,s,o),this._diagnosticTransport=new k(e,n,r,s),this._placementDiagnosticTransport=new k(e,n,r,s),this._loggingUrl=ae(e?.loggingUrl,e?.integrationDomain,lt),this._errorReportingService=t}log(e){e&&this._send(this._transport,e)}logDiagnostic(e){e&&this._send(this._diagnosticTransport,e)}logPlacementDiagnostic(e){e&&this._send(this._placementDiagnosticTransport,e)}_send(e,t){e.send(this._loggingUrl,y.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:z.LOG_DELIVERY_FAILURE,severity:r?y.ERROR:y.WARNING})}})}}function Et(i){const e=F(window.location.href),t=i.EventAttributes?.title||document.title,n=Te(),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 I=class I{constructor(){this.name=d,this.id=C,this.moduleId=C,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=Ve(),this.accountId=null,this._preselectState=Fe()}getEventAttributeValue(e,t){const n=e&&e.EventAttributes;return!n||n[t]===void 0?null:n[t]}doesEventAttributeConditionMatch(e,t){if(!e||!E(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||!E(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(P(s))continue;let o=!0;for(let a=0;a<s.length;a++)if(!this.doesEventMatchRule(e,s[a])){o=!1;break}o&&c().Rokt.setLocalSessionAttribute?.(r,!0)}}capturePageView(e){let t;try{t=F(window.location.href);const n=te(),r=Et(e);n.push(r);const s=Math.min(n.length,Z),o=be(n);if(o===0){const a=x()?"quota":"ls_unavailable";this.loggingService?.log({message:`Rokt Kit: Failed to persist page view for ${t} [reason: ${a}]`,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=x()?"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=Le(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&&O(window.Rokt.createLauncher)}returnUserIdentities(e){if(!e||!e.getUserIdentities)return{};const t=e.getUserIdentities().userIdentities;return this.replaceOtherIdentityWithEmailsha256(t)}returnLocalSessionAttributes(){return!c().Rokt||typeof c().Rokt.getLocalSessionAttributes!="function"?{}:c().Rokt.getLocalSessionAttributes()}replaceOtherIdentityWithEmailsha256(e){const t={...e||{}},n=this._mappedEmailSha256Key;return n&&e[n]&&(t[I.EMAIL_SHA256_KEY]=e[n]),n&&delete t[n],t}logSelectPlacementsEvent(e){if(!window.mParticle||typeof c().logEvent!="function"||!m(e))return;const t=c().EventType.Other;c().logEvent(Je,t,e)}setRoktSessionId(e){if(!(!e||typeof e!="string"))try{const t=c().getInstance();t&&O(t.setIntegrationAttribute)&&t.setIntegrationAttribute(C,{roktSessionId:e})}catch{}}readMpSessionId(){const e=c()?.sessionManager,t=e?.getSessionId??e?.getSession;if(O(t))return t.call(e)||void 0}readMpDeviceId(){return c()?.getDeviceId?.()||void 0}attachLauncher(e,t,n=[]){Ge(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 ht([...n],o),this.initRoktLauncher(o)}).catch(o=>{ze(this._launcherAttachState),console.error("Error creating Rokt launcher:",o)})}recreateLauncherIfTerminated(){return qe(this._launcherAttachState,this.isLauncherReadyToAttach(),e=>this.attachLauncher(e.accountId,e.launcherOptions,e.legacyRoktExtensions))}initRoktLauncher(e){window.Rokt&&(window.Rokt.currentLauncher=e),this.launcher=e,He(this._launcherAttachState);const t=c().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,pe(this.domain,this.integrationName),c().Rokt.attachKit(this),this.flushPendingPreselectDispatches()}fetchOptimizely(){const e=c()._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 c().Rokt?.launcherOptions?.noTargeting===!0}isPartnerInLocalLauncherTestGroup(){return!!(c().config&&c().config.isLocalLauncherEnabled&&this.isAssignedToSampleGroup())}isAssignedToSampleGroup(){return Math.random()>.5}captureTiming(e){window&&c()&&c().captureTiming&&e&&c().captureTiming(e)}init(e,t,n,r,s){const o=e,a=o.accountId;this.accountId=a||null,this.userAttributes=L(s),this._onboardingExpProvider=o.onboardingExpProvider;const u=K(o.placementEventMapping);this.placementEventMappingLookup=de(u);const l=K(o.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=he(l),o.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=o.hashedEmailUserIdentityType.toLowerCase()),this._workspaceIdSyncApiKey=E(o.workspaceIdSyncApiKey)?o.workspaceIdSyncApiKey:void 0;const g=c().Rokt?.domain,{roktExtensionsQueryParams:T,legacyRoktExtensions:h,loadThankYouElement:S}=ue(o.roktExtensions),p={...c().Rokt?.launcherOptions||{}};this.integrationName=gt(p.integrationName),p.integrationName=this.integrationName,this.domain=g;const w={loggingUrl:o.loggingUrl,errorUrl:o.errorUrl,integrationDomain:g,isLoggingEnabled:c().config?.isLoggingEnabled===!0},v=new me(w,this.integrationName,window.__rokt_li_guid__,o.accountId),b=new Ee(w,v,this.integrationName,window.__rokt_li_guid__,o.accountId);if(this.errorReportingService=v,this.loggingService=b,this.isTargetingDisabled())try{ie(),ne()}catch(f){this.errorReportingService?.report({message:"Rokt Kit: Failed to clear page views when targeting is disabled",code:"PAGE_VIEW_CAPTURE_FAILED",severity:y.INFO,stackTrace:f instanceof Error?f.stack:void 0})}return c()._registerErrorReportingService&&c()._registerErrorReportingService(v),c()._registerLoggingService&&c()._registerLoggingService(b),n?(this.testHelpers={generateLauncherScript:oe,generateThankYouElementScript:ce,extractRoktExtensionConfig:ue,hashEventMessage:ge,parseSettingsString:K,generateMappedEventLookup:de,generateMappedEventAttributeLookup:he,sendAdBlockMeasurementSignals:pe,createAutoRemovedIframe:$,djb2:J,setAllowedOriginHashes:f=>{I._allowedOriginHashes=f},ReportingTransport:k,ErrorReportingService:me,LoggingService:Ee,RateLimiter:fe,ErrorCodes:z,WSDKErrorSeverity:y,resetLauncherAttachState:()=>$e(this._launcherAttachState)},this.attachLauncher(a,p),"Successfully initialized: "+d):(S&&(c().Rokt.flushOnShoppableAdsReadyMessageQueue?.(this),le(et,ce(g),{onLoad:()=>{this._isThankYouElementLoaded=!0,this._thankYouElementOnLoadCallback&&this._thankYouElementOnLoadCallback()},onError:f=>{console.error("Error loading Rokt Thank You Element script:",f)}})),this.isLauncherReadyToAttach()?this.attachLauncher(a,p,h):(le(Ze,oe(g,T),{onLoad:()=>{this.isLauncherReadyToAttach()?this.attachLauncher(a,p,h):console.error("Rokt object is not available after script load.")},onError:f=>{console.error("Error loading Rokt launcher script:",f)}}),this.captureTiming(I.PERFORMANCE_MARKS.RoktScriptAppended)),"Successfully initialized: "+d)}process(e){if(this.isTargetingDisabled()||(e.EventDataType===it&&(Re(this.loggingService),this.capturePageView(e),re(this._preselectState,this.buildPreselectHost(),e)),e.EventDataType===nt&&(ie(),ne())),!this.isKitReady())return"Kit not ready for forwarder: "+d;if(O(c().Rokt?.setLocalSessionAttribute)&&(P(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(e),!P(this.placementEventMappingLookup))){const t=ge(e.EventDataType,e.EventCategory,e.EventName??"");this.placementEventMappingLookup[String(t)]&&c().Rokt.setLocalSessionAttribute?.(this.placementEventMappingLookup[String(t)],!0)}return"Successfully sent to forwarder: "+d}setExtensionData(e){if(!this.isKitReady()){console.error("Rokt Kit: Not initialized");return}window.Rokt.setExtensionData(e)}setUserAttribute(e,t){return this.loggingService?.logDiagnostic(H("setUserAttribute",[e])),q(e)||(this.userAttributes[e]=t),Oe(this.accountId,e)&&this.flushPendingPreselectDispatches(),"Successfully set user attribute for forwarder: "+d}removeUserAttribute(e){return this.loggingService?.logDiagnostic(H("removeUserAttribute",[e])),delete this.userAttributes[e],"Successfully removed user attribute for forwarder: "+d}handleIdentityComplete(e,t){return this.userAttributes=L(e.getAllUserAttributes()),this.loggingService?.logDiagnostic(H(t,Object.keys(this.userAttributes))),"Successfully called "+t+" for forwarder: "+d}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=c().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];E(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 a=o.sort().map(u=>`${u}=${s[u]}`).join("&");return a===this._workspaceLastSearchedIdentitiesKey?this._workspaceSearchInFlightPromise||Promise.resolve():(this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=a,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,se))]):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,se))]).then(()=>this._dispatchPlacements(e))}return this._dispatchPlacements(e)}_dispatchPlacements(e){const t=e&&e.attributes||{},r={...L(this.userAttributes),...t},s=this.filters||{},o=s.userAttributeFilters||[],a=s.filteredUser||null,u=a?a.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=L(l);const g=this._onboardingExpProvider==="Optimizely"?this.fetchOptimizely():{},T=this.returnUserIdentities(a),h=this.returnLocalSessionAttributes(),S=Pe(te()),p=ke(),w=this.readMpSessionId(),v=this.readMpDeviceId(),b={...T,...l,...g,...h,...S.length?{[rt]:JSON.stringify(S)}:{},...p?{[st]:p}:{},...this.userIdentifiedInWorkspace?{[tt]:!0}:{},...w?{[ot]:w}:{},...v?{[ct]:v}:{},mpid:u},f=this.buildCacheMatchKeys(typeof e.identifier=="string"?e.identifier:void 0),St={...e,attributes:b,...f!==void 0?{cacheMatchKeys:f}:{}};this.loggingService?.logPlacementDiagnostic(Me(Object.keys(b)));const _e=this.launcher.selectPlacements(St),Ie=e.preselect===!0,yt=()=>{Ie||this.logSelectPlacementsEvent(b)};return Promise.resolve(_e).then(At=>{if(!Ie)return At?.context?.sessionId?.then(vt=>this.setRoktSessionId(vt))}).catch(()=>{}).finally(yt),_e}hashAttributes(e){return this.isKitReady()?this.launcher.hashAttributes(e):(console.error("Rokt Kit: Not initialized"),null)}use(e){return this.isKitReady()?!e||!E(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()?(We(this._launcherAttachState),this.launcher.terminate()):(console.error("Rokt Kit: Not initialized"),Promise.resolve())}onShoppableAdsReady(e){this._isThankYouElementLoaded?e():this._thankYouElementOnLoadCallback=e}};I._allowedOriginHashes=[-553112570,549508659],I.PERFORMANCE_MARKS={RoktScriptAppended:"mp:RoktScriptAppended"},I.EMAIL_SHA256_KEY="emailsha256";let A=I;function _t(){return C}function It(i){if(!i){window.console.log("You must pass a config object to register the kit "+d);return}if(!m(i)){window.console.log("'config' must be an object. You passed in a "+typeof i);return}m(i.kits)?i.kits[d]={constructor:A}:(i.kits={},i.kits[d]={constructor:A}),window.console.log("Successfully registered "+d+" to your mParticle configuration")}return typeof window<"u"&&window.mParticle&&c().addForwarder&&c().addForwarder({name:d,constructor:A,getId:_t}),M.register=It,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"}),M})({});
2
2
  //# sourceMappingURL=Rokt-Kit.iife.js.map
package/package.json CHANGED
@@ -1,63 +1,62 @@
1
1
  {
2
- "name": "@mparticle/web-rokt-kit",
3
- "version": "1.36.1",
4
- "description": "mParticle integration kit for Rokt",
5
- "main": "dist/Rokt-Kit.common.js",
6
- "module": "dist/Rokt-Kit.esm.js",
7
- "types": "dist/Rokt-Kit.d.ts",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/Rokt-Kit.d.ts",
11
- "import": "./dist/Rokt-Kit.esm.js",
12
- "require": "./dist/Rokt-Kit.common.js"
13
- }
14
- },
15
- "files": [
16
- "dist/Rokt-Kit.common.js",
17
- "dist/Rokt-Kit.esm.js",
18
- "dist/Rokt-Kit.iife.js",
19
- "dist/Rokt-Kit.d.ts"
20
- ],
21
- "repository": "https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt",
22
- "scripts": {
23
- "build": "vite build",
24
- "build:watch": "vite build --watch",
25
- "lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
26
- "lint:fix": "eslint \"src/**/*.ts\" \"test/**/*.ts\" --fix",
27
- "test": "vitest run",
28
- "test:watch": "vitest",
29
- "test:coverage": "vitest run --coverage"
30
- },
31
- "publishConfig": {
32
- "access": "public",
33
- "provenance": true,
34
- "registry": "https://registry.npmjs.org"
35
- },
36
- "devDependencies": {
37
- "@eslint/js": "^9.23.0",
38
- "@eslint/eslintrc": "^3.3.1",
39
- "@mparticle/event-models": "^1.1.9",
40
- "@semantic-release/changelog": "^6.0.3",
41
- "@semantic-release/exec": "^6.0.3",
42
- "@semantic-release/git": "^10.0.1",
43
- "@semantic-release/npm": "^13.1.2",
44
- "@typescript-eslint/eslint-plugin": "^8.28.0",
45
- "@typescript-eslint/parser": "^8.28.0",
46
- "@types/node": "^20.11.5",
47
- "@vitest/coverage-v8": "^4.0.0",
48
- "eslint": "^9.23.0",
49
- "eslint-config-prettier": "^9.0.0",
50
- "eslint-plugin-prettier": "^5.0.0",
51
- "jsdom": "latest",
52
- "prettier": "^3.0.0",
53
- "semantic-release": "^24.2.0",
54
- "typescript": "^5.5.4",
55
- "vite": "^6.0.0",
56
- "vite-plugin-dts": "~3.8.1",
57
- "vitest": "^4.0.0"
58
- },
59
- "dependencies": {
60
- "@mparticle/web-sdk": "^2.62.0"
61
- },
62
- "license": "Apache-2.0"
2
+ "name": "@mparticle/web-rokt-kit",
3
+ "version": "3.2.0",
4
+ "description": "mParticle integration kit for Rokt",
5
+ "main": "dist/Rokt-Kit.common.js",
6
+ "module": "dist/Rokt-Kit.esm.js",
7
+ "types": "dist/Rokt-Kit.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/Rokt-Kit.d.ts",
11
+ "import": "./dist/Rokt-Kit.esm.js",
12
+ "require": "./dist/Rokt-Kit.common.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist/Rokt-Kit.common.js",
17
+ "dist/Rokt-Kit.esm.js",
18
+ "dist/Rokt-Kit.iife.js",
19
+ "dist/Rokt-Kit.d.ts"
20
+ ],
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/mParticle/mparticle-web-sdk",
24
+ "directory": "kits/rokt"
25
+ },
26
+ "scripts": {
27
+ "build": "vite build",
28
+ "build:watch": "vite build --watch",
29
+ "lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
30
+ "lint:fix": "eslint \"src/**/*.ts\" \"test/**/*.ts\" --fix",
31
+ "test": "vitest run",
32
+ "test:watch": "vitest",
33
+ "test:coverage": "vitest run --coverage"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "registry": "https://registry.npmjs.org"
38
+ },
39
+ "peerDependencies": {
40
+ "@mparticle/web-sdk": "^3.0.0"
41
+ },
42
+ "devDependencies": {
43
+ "@eslint/js": "^9.23.0",
44
+ "@eslint/eslintrc": "^3.3.1",
45
+ "@mparticle/event-models": "^1.1.9",
46
+ "@mparticle/web-sdk": "^3.0.0",
47
+ "@typescript-eslint/eslint-plugin": "^8.28.0",
48
+ "@typescript-eslint/parser": "^8.28.0",
49
+ "@types/node": "^20.11.5",
50
+ "@vitest/coverage-v8": "^4.0.0",
51
+ "eslint": "^9.23.0",
52
+ "eslint-config-prettier": "^9.0.0",
53
+ "eslint-plugin-prettier": "^5.0.0",
54
+ "jsdom": "latest",
55
+ "prettier": "^3.0.0",
56
+ "typescript": "^5.5.4",
57
+ "vite": "^6.0.0",
58
+ "vite-plugin-dts": "~3.8.1",
59
+ "vitest": "^4.0.0"
60
+ },
61
+ "license": "Apache-2.0"
63
62
  }