@mparticle/web-rokt-kit 3.2.0 → 3.2.2
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.d.ts +0 -2
- package/dist/Rokt-Kit.esm.js +357 -331
- package/dist/Rokt-Kit.iife.js +1 -1
- package/package.json +1 -1
package/dist/Rokt-Kit.common.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});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"],be=new Set(ve);function ue(i){return be.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];ue(s)||(e[s]=t[s])}return e}function E(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function m(i){return typeof i=="string"}function O(i){return typeof i=="function"}function T(i){return i==null?!0:typeof i=="string"?i.length===0:typeof i=="object"?Object.keys(i).length===0:!1}function j(i){try{const e=new URL(i);return e.search="",e.toString()}catch{return i}}function de(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",J="__rokt_ls_probe__";function x(){try{return window.localStorage.setItem(J,"1"),window.localStorage.removeItem(J),!0}catch{return!1}}function V(i){try{const e=window.localStorage.getItem(i);return e===null?null:JSON.parse(e)}catch{return null}}function he(i,e){try{return window.localStorage.setItem(i,JSON.stringify(e)),!0}catch{return!1}}function Pe(i){try{window.localStorage.removeItem(i)}catch{}}function D(i,e){const t=V(i);return E(t)?t[e]:void 0}function G(i,e,t){const n=V(i),r=E(n)?{...n}:{};return r[e]=t,he(i,r)}function ge(i,e){const t=V(i);if(!E(t)||!(e in t))return;const n={...t};delete n[e],Object.keys(n).length===0?Pe(i):he(i,n)}const H="pageViews",C="utmParams",pe=25,Re=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"];function fe(i){return i.slice(-pe)}function B(){const i=D(_,H);return Array.isArray(i)?i:[]}function ke(i){const e=fe(i);for(let t=0;t<e.length;t++){const n=e.slice(t);if(G(_,H,n))return n.length}return 0}function Q(){ge(_,H)}function Te(i){const e=fe(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 we(i){if(D(_,C)!==void 0)return;const e=new URLSearchParams(window.location.search),t={};for(const r of Re){const s=e.get(r);s&&(t[r]=s)}if(Object.keys(t).length===0)return;const n=Object.keys(t).join(", ");if(!G(_,C,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 Le(){const i=D(_,C);return E(i)?i:null}function X(){ge(_,C)}function Oe(){const e=document.querySelector('link[rel="canonical"]')?.href;if(e)return j(e)}const W=[{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 Ne(i,e){if(i)return W.find(t=>t.accountId===i&&t.pathname===e)}function Ue(i,e){if(!(!i||!m(e)))return W.find(t=>t.accountId===i&&t.targetPageIdentifier===e)}function Ce(i,e){return i?W.some(t=>t.accountId===i&&t.attributeKeys.includes(e)):!1}const De=6e4;function Ke(i){return E(i)&&typeof i.expiresAt=="number"&&E(i.attributes)}function Me(i,e){return`activePreselect:${i}:${e}`}function Fe(i){const e=D(_,i);return Ke(e)?e:null}function xe(i,e){G(_,i,{expiresAt:Date.now()+De,attributes:e})}function M(i,e){return{message:`Rokt Kit: ${i} called [attributeKeys=${e.join(",")}]`,code:"ATTRIBUTE_SETTER_CALLED"}}function Ye(i){return{message:`Rokt Kit: selectPlacements dispatched [placementAttributeKeys=${i.join(",")}]`,code:"SELECT_PLACEMENTS_DISPATCHED"}}function k(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 je(){return{pending:[]}}function F(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 Ve(i){if(!i?.getUserIdentities)return!1;const e=i.getUserIdentities().userIdentities;return e?Object.keys(e).some(t=>{const n=e[t];return m(n)&&n.length>0}):!1}function Ge(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 me(i,e,t,n=window.location.pathname){const r=Ne(e.accountId,n);if(!r)return;if(!e.isKitReady()){F(i,{event:t,pathname:n}),e.logPlacementDiagnostic(k("queued","not_ready"));return}if(!e.isPreselectionEnabled())return;if(!Ve(e.filteredUser)){e.logPlacementDiagnostic(k("missed","no_valid_identity")),F(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=T(S)?e.userAttributes[h]??s[h]:S;if(T(p)){a.push(h);continue}o[h]=p}if(a.length>0){for(const h of a)e.logPlacementDiagnostic(k("missed",`missing_attribute:${h}`));F(i,{event:t,pathname:n});return}const u=Me(e.accountId||"",n),l=Fe(u),g=!!l&&JSON.stringify(l.attributes)===JSON.stringify(o);if(l&&l.expiresAt>Date.now()&&g){e.logPlacementDiagnostic(k("skipped","active_preselection"));return}const P={attributes:o,preselect:!0,identifier:r.targetPageIdentifier,omitUrl:!0};xe(u,o),e.logPlacementDiagnostic(k("fired","fired")),Ge(e,P)}function He(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&&me(i,e,r,s)})}function We(){return{context:null,lifecycle:"idle",recreateInFlight:null}}function ze(i,e){i.context={accountId:e.accountId,launcherOptions:{...e.launcherOptions},legacyRoktExtensions:[...e.legacyRoktExtensions]}}function $e(i){i.lifecycle="attached"}function qe(i){i.lifecycle!=="idle"&&(i.lifecycle="terminated")}function Je(i){i.lifecycle="terminated"}function Be(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",N=181,Xe="selectPlacements",Ze="apps.roktecommerce.com",et=.1,tt="ThankYouPageJourney",it="rokt-launcher",nt="rokt-thank-you-element",rt="userIdentifiedInWorkspace",st=3,ot=2,ct="page_events",at="page_view_attributes",lt="mparticle_session_id",ut="mparticle_device_id",Z=500,z={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST",LOG_DELIVERY_FAILURE:"LOG_DELIVERY_FAILURE"},v={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"},dt="apps.rokt-api.com",ht="/v1/log",gt="/v1/errors",pt=10;function c(){return window.mParticle}function ee(i,e){const n=[K(i),"/wsdk/integrations/launcher.js"].join("");return!e||e.length===0?n:n+"?extensions="+e.join(",")}function te(i){return[K(i),"/rokt-elements/rokt-element-thank-you.js"].join("")}function K(i){const e=i!==void 0?i:dt;return e.includes("://")?e.replace(/\/+$/,""):["https://",e].join("")}function Ee(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 K(r)+t}function ie(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 U(i){if(!i)return[];try{return JSON.parse(i.replace(/"/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function ne(i){const e=i?U(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(tt)):t.push(o)}return{roktExtensionsQueryParams:t,legacyRoktExtensions:n,loadThankYouElement:r}}async function ft(i,e){const t=[];if(e)for(const n of i)t.push(e.use(n));return Promise.all(t)}function re(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||!m(n.value)||!m(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 oe(i,e,t){return c().generateHash([i,e,t].join(""))}function mt(i){let n="mParticle_wsdkv_"+c().getVersion()+"_kitv_"+"3.2.0";return i&&(n+="_"+i),n}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 ce(i,e){const t=de(window.location.origin);if(b._allowedOriginHashes.indexOf(t)===-1||Math.random()>=et)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?K(i):"https://apps.rokt.com";Y(a+"/v1/wsdk-init/index.html?"+o),Y("https://"+Ze+"/v1/wsdk-init/index.html?"+o+"&isControl=true")}function Et(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function _t(){return typeof window<"u"?window.location?.href:void 0}function It(){return typeof window<"u"?window.navigator?.userAgent:void 0}class _e{constructor(){this._logCount={}}incrementAndCheck(e){const n=(this._logCount[e]||0)+1;return this._logCount[e]=n,n>pt}}class w{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 _e,this._isEnabled=Et()||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:_t(),deviceInfo:It(),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 ae{constructor(e,t,n,r,s){this._transport=new w(e,t,n,r,s),this._errorUrl=Ee(e?.errorUrl,e?.integrationDomain,gt)}report(e){if(!e)return;const t=e.severity||v.ERROR;this._transport.send(this._errorUrl,t,e.message,e.code,e.stackTrace)}}class le{constructor(e,t,n,r,s,o){this._transport=new w(e,n,r,s,o),this._diagnosticTransport=new w(e,n,r,s),this._placementDiagnosticTransport=new w(e,n,r,s),this._loggingUrl=Ee(e?.loggingUrl,e?.integrationDomain,ht),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,v.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?v.ERROR:v.WARNING})}})}}function St(i){const e=j(window.location.href),t=i.EventAttributes?.title||document.title,n=Oe(),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=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=We(),this.accountId=null,this._preselectState=je()}getEventAttributeValue(e,t){const n=e&&e.EventAttributes;return!n||n[t]===void 0?null:n[t]}doesEventAttributeConditionMatch(e,t){if(!e||!m(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||!m(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(T(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=j(window.location.href);const n=B(),r=St(e);n.push(r);const s=Math.min(n.length,pe),o=ke(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=Ue(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(){He(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"||!E(e))return;const t=c().EventType.Other;c().logEvent(Xe,t,e)}setRoktSessionId(e){if(!(!e||typeof e!="string"))try{const t=c().getInstance();t&&O(t.setIntegrationAttribute)&&t.setIntegrationAttribute(N,{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=[]){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 ft([...n],o),this.initRoktLauncher(o)}).catch(o=>{Je(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,$e(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,ce(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=U(o.placementEventMapping);this.placementEventMappingLookup=re(u);const l=U(o.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=se(l),o.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=o.hashedEmailUserIdentityType.toLowerCase()),this._workspaceIdSyncApiKey=m(o.workspaceIdSyncApiKey)?o.workspaceIdSyncApiKey:void 0;const g=c().Rokt?.domain,{roktExtensionsQueryParams:P,legacyRoktExtensions:h,loadThankYouElement:S}=ne(o.roktExtensions),p={...c().Rokt?.launcherOptions||{}};this.integrationName=mt(p.integrationName),p.integrationName=this.integrationName,this.domain=g;const R={loggingUrl:o.loggingUrl,errorUrl:o.errorUrl,integrationDomain:g,isLoggingEnabled:c().config?.isLoggingEnabled===!0},y=new ae(R,this.integrationName,window.__rokt_li_guid__,o.accountId),A=new le(R,y,this.integrationName,window.__rokt_li_guid__,o.accountId);if(this.errorReportingService=y,this.loggingService=A,this.isTargetingDisabled())try{Q(),X()}catch(f){this.errorReportingService?.report({message:"Rokt Kit: Failed to clear page views when targeting is disabled",code:"PAGE_VIEW_CAPTURE_FAILED",severity:v.INFO,stackTrace:f instanceof Error?f.stack:void 0})}return c()._registerErrorReportingService&&c()._registerErrorReportingService(y),c()._registerLoggingService&&c()._registerLoggingService(A),n?(this.testHelpers={generateLauncherScript:ee,generateThankYouElementScript:te,extractRoktExtensionConfig:ne,hashEventMessage:oe,parseSettingsString:U,generateMappedEventLookup:re,generateMappedEventAttributeLookup:se,sendAdBlockMeasurementSignals:ce,createAutoRemovedIframe:Y,djb2:de,setAllowedOriginHashes:f=>{I._allowedOriginHashes=f},ReportingTransport:w,ErrorReportingService:ae,LoggingService:le,RateLimiter:_e,ErrorCodes:z,WSDKErrorSeverity:v,resetLauncherAttachState:()=>Be(this._launcherAttachState)},this.attachLauncher(a,p),"Successfully initialized: "+d):(S&&(c().Rokt.flushOnShoppableAdsReadyMessageQueue?.(this),ie(nt,te(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):(ie(it,ee(g,P),{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===st&&(we(this.loggingService),this.capturePageView(e),me(this._preselectState,this.buildPreselectHost(),e)),e.EventDataType===ot&&(Q(),X())),!this.isKitReady())return"Kit not ready for forwarder: "+d;if(O(c().Rokt?.setLocalSessionAttribute)&&(T(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(e),!T(this.placementEventMappingLookup))){const t=oe(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(M("setUserAttribute",[e])),ue(e)||(this.userAttributes[e]=t),Ce(this.accountId,e)&&this.flushPendingPreselectDispatches(),"Successfully set user attribute for forwarder: "+d}removeUserAttribute(e){return this.loggingService?.logDiagnostic(M("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(M(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];m(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,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={...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():{},P=this.returnUserIdentities(a),h=this.returnLocalSessionAttributes(),S=Te(B()),p=Le(),R=this.readMpSessionId(),y=this.readMpDeviceId(),A={...P,...l,...g,...h,...S.length?{[ct]:JSON.stringify(S)}:{},...p?{[at]:p}:{},...this.userIdentifiedInWorkspace?{[rt]:!0}:{},...R?{[lt]:R}:{},...y?{[ut]:y}:{},mpid:u},f=this.buildCacheMatchKeys(typeof e.identifier=="string"?e.identifier:void 0),Ie={...e,attributes:A,...f!==void 0?{cacheMatchKeys:f}:{}};this.loggingService?.logPlacementDiagnostic(Ye(Object.keys(A)));const $=this.launcher.selectPlacements(Ie),q=e.preselect===!0,Se=()=>{q||this.logSelectPlacementsEvent(A)};return Promise.resolve($).then(ye=>{if(!q)return ye?.context?.sessionId?.then(Ae=>this.setRoktSessionId(Ae))}).catch(()=>{}).finally(Se),$}hashAttributes(e){return this.isKitReady()?this.launcher.hashAttributes(e):(console.error("Rokt Kit: Not initialized"),null)}use(e){return this.isKitReady()?!e||!m(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()?(qe(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 b=I;function yt(){return N}function At(i){if(!i){window.console.log("You must pass a config object to register the kit "+d);return}if(!E(i)){window.console.log("'config' must be an object. You passed in a "+typeof i);return}E(i.kits)?i.kits[d]={constructor:b}:(i.kits={},i.kits[d]={constructor:b}),window.console.log("Successfully registered "+d+" to your mParticle configuration")}typeof window<"u"&&window.mParticle&&c().addForwarder&&c().addForwarder({name:d,constructor:b,getId:yt});exports.register=At;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const we=["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"],Te=new Set(we);function fe(i){return Te.has(i.toLowerCase())}function T(i){const e={},t=i||{},n=Object.keys(t);for(let r=0;r<n.length;r++){const s=n[r];fe(s)||(e[s]=t[s])}return e}function p(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function g(i){return typeof i=="string"}function L(i){return typeof i=="function"}function R(i){return i==null?!0:typeof i=="string"?i.length===0:typeof i=="object"?Object.keys(i).length===0:!1}function W(i){try{const e=new URL(i);return e.search="",e.toString()}catch{return i}}function pe(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 h="mp-rokt-kit",X="__rokt_ls_probe__";function j(){try{return window.localStorage.setItem(X,"1"),window.localStorage.removeItem(X),!0}catch{return!1}}function H(i){try{const e=window.localStorage.getItem(i);return e===null?null:JSON.parse(e)}catch{return null}}function me(i,e){try{return window.localStorage.setItem(i,JSON.stringify(e)),!0}catch{return!1}}function Le(i){try{window.localStorage.removeItem(i)}catch{}}function k(i,e){const t=H(i);return p(t)?t[e]:void 0}function K(i,e,t){const n=H(i),r=p(n)?{...n}:{};return r[e]=t,me(i,r)}function D(i,e){const t=H(i);if(!p(t)||!(e in t))return;const n={...t};delete n[e],Object.keys(n).length===0?Le(i):me(i,n)}const z="pageViews",U="utmParams",Ee=25,Oe=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"];function _e(i){return i.slice(-Ee)}function Z(){const i=k(h,z);return Array.isArray(i)?i:[]}function Ne(i){const e=_e(i);for(let t=0;t<e.length;t++){const n=e.slice(t);if(K(h,z,n))return n.length}return 0}function ee(){D(h,z)}function Ue(i){const e=_e(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 Ce(i){if(k(h,U)!==void 0)return;const e=new URLSearchParams(window.location.search),t={};for(const r of Oe){const s=e.get(r);s&&(t[r]=s)}if(Object.keys(t).length===0)return;const n=Object.keys(t).join(", ");if(!K(h,U,t)){const r=j()?"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=k(h,U);return p(i)?i:null}function te(){D(h,U)}function De(){const e=document.querySelector('link[rel="canonical"]')?.href;if(e)return W(e)}const $=[{accountId:"2919171670744024290",pathname:"/checkout",targetPageIdentifier:"prod.rokt.conf",attributeKeys:["email","amount","concessions_total","customertype","eventvenue","firstname","lastname","member_status","billingzipcode","currency"]}],Me=6e4;function Fe(i){return p(i)&&typeof i.expiresAt=="number"&&p(i.attributes)}function xe(i,e){return`activePreselect:${i}:${e}`}function Ye(i){const e=k(h,i);return Fe(e)?e:null}function je(i,e){K(h,i,{expiresAt:Date.now()+Me,attributes:e})}const Ge=2*6e4;function Ve(i){return p(i)&&typeof i.expiresAt=="number"&&g(i.pathname)&&g(i.identifier)&&p(i.attributes)&&g(i.mpid)}function q(i){return`pendingPreselect:${i}`}function We(i){const e=q(i),t=k(h,e);return Ve(t)?t.expiresAt<=Date.now()?(D(h,e),null):t:null}function He(i,e,t,n,r){K(h,q(i),{expiresAt:Date.now()+Ge,pathname:e,identifier:t,attributes:n,mpid:r})}function x(i){D(h,q(i))}function b(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 ze(i,e){if(i)return $.find(t=>t.accountId===i&&t.pathname===e)}function $e(i,e){if(!(!i||!g(e)))return $.find(t=>t.accountId===i&&t.targetPageIdentifier===e)}function qe(i,e){return i?$.some(t=>t.accountId===i&&t.attributeKeys.includes(e)):!1}function Je(){return{pending:[]}}function Y(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 G(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 Ie(i){const e=i?.getMPID?.();return e==null?null:String(e)}function ie(i,e,t){const n=i.filteredUser?.getAllUserAttributes?.()||{},r={},s=[];for(const o of t.attributeKeys){const c=i.getEventAttributeValue(e,o),u=R(c)?i.userAttributes[o]??n[o]:c;if(R(u)){s.push(o);continue}r[o]=u}return{collected:r,missingKeys:s}}function Be(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 Se(i,e,t,n,r,s){const o=xe(e,t),c=Ye(o),u=!!c&&JSON.stringify(c.attributes)===JSON.stringify(r);if(c&&c.expiresAt>Date.now()&&u){i.logPlacementDiagnostic(b("skipped","active_preselection"));return}je(o,r),i.logPlacementDiagnostic(b("fired",s)),Be(i,{attributes:r,preselect:!0,identifier:n,omitUrl:!0})}function Qe(i,e){if(!e.accountId||!e.isKitReady())return;const t=We(e.accountId);if(t){if(i.pending.some(n=>n.pathname===t.pathname)){x(e.accountId);return}if(!e.isPreselectionEnabled()){x(e.accountId);return}G(e.filteredUser)&&(x(e.accountId),Ie(e.filteredUser)===t.mpid&&Se(e,e.accountId,t.pathname,t.identifier,t.attributes,"recovered"))}}function ye(i,e,t,n=window.location.pathname){const r=ze(e.accountId,n);if(!r)return;if(!e.isKitReady()){Y(i,{event:t,pathname:n}),e.logPlacementDiagnostic(b("queued","not_ready"));const c=Ie(e.filteredUser);if(e.accountId&&c&&G(e.filteredUser)){const{collected:u,missingKeys:l}=ie(e,t,r);l.length===0&&He(e.accountId,n,r.targetPageIdentifier,u,c)}return}if(!e.isPreselectionEnabled())return;if(!G(e.filteredUser)){e.logPlacementDiagnostic(b("missed","no_valid_identity")),Y(i,{event:t,pathname:n});return}const{collected:s,missingKeys:o}=ie(e,t,r);if(o.length>0){for(const c of o)e.logPlacementDiagnostic(b("missed",`missing_attribute:${c}`));Y(i,{event:t,pathname:n});return}Se(e,e.accountId||"",n,r.targetPageIdentifier,s,"fired")}function Xe(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&&ye(i,e,r,s)})}function Ze(){return{context:null,lifecycle:"idle",recreateInFlight:null}}function et(i,e){i.context={accountId:e.accountId,launcherOptions:{...e.launcherOptions},legacyRoktExtensions:[...e.legacyRoktExtensions]}}function tt(i){i.lifecycle="attached"}function it(i){i.lifecycle!=="idle"&&(i.lifecycle="terminated")}function nt(i){i.lifecycle="terminated"}function rt(i){i.context=null,i.lifecycle="idle",i.recreateInFlight=null}function st(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",O=181,ot="selectPlacements",ct="apps.roktecommerce.com",at=.1,lt="ThankYouPageJourney",ut="rokt-launcher",dt="rokt-thank-you-element",ht="userIdentifiedInWorkspace",gt=3,ft=2,pt="page_events",mt="page_view_attributes",Et="mparticle_session_id",_t="mparticle_device_id",ne=500,J={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"},It="apps.rokt-api.com",St="/v1/log",yt="/v1/errors",At=10;function a(){return window.mParticle}function re(i,e){const n=[M(i),"/wsdk/integrations/launcher.js"].join("");return!e||e.length===0?n:n+"?extensions="+e.join(",")}function se(i){return[M(i),"/rokt-elements/rokt-element-thank-you.js"].join("")}function M(i){const e=i!==void 0?i:It;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 M(r)+t}function oe(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 N(i){if(!i)return[];try{return JSON.parse(i.replace(/"/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function ce(i){const e=i?N(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(lt)):t.push(o)}return{roktExtensionsQueryParams:t,legacyRoktExtensions:n,loadThankYouElement:r}}async function Pt(i,e){const t=[];if(e)for(const n of i)t.push(e.use(n));return Promise.all(t)}function ae(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 le(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 ue(i,e,t){return a().generateHash([i,e,t].join(""))}function Rt(i){let n="mParticle_wsdkv_"+a().getVersion()+"_kitv_"+"3.2.2";return i&&(n+="_"+i),n}function V(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 de(i,e){const t=pe(window.location.origin);if(y._allowedOriginHashes.indexOf(t)===-1||Math.random()>=at)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?M(i):"https://apps.rokt.com";V(c+"/v1/wsdk-init/index.html?"+o),V("https://"+ct+"/v1/wsdk-init/index.html?"+o+"&isControl=true")}function bt(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function kt(){return typeof window<"u"?window.location?.href:void 0}function vt(){return typeof window<"u"?window.navigator?.userAgent:void 0}class Pe{constructor(){this._logCount={}}incrementAndCheck(e){const n=(this._logCount[e]||0)+1;return this._logCount[e]=n,n>At}}class C{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 Pe,this._isEnabled=bt()||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||J.UNKNOWN_ERROR,url:kt(),deviceInfo:vt(),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 he{constructor(e,t,n,r,s){this._transport=new C(e,t,n,r,s),this._errorUrl=Ae(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 ge{constructor(e,t,n,r,s,o){this._transport=new C(e,n,r,s,o),this._placementDiagnosticTransport=new C(e,n,r,s),this._loggingUrl=Ae(e?.loggingUrl,e?.integrationDomain,St),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:J.LOG_DELIVERY_FAILURE,severity:r?S.ERROR:S.WARNING})}})}}function wt(i){const e=W(window.location.href),t=i.EventAttributes?.title||document.title,n=De(),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 _=class _{constructor(){this.name=d,this.id=O,this.moduleId=O,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=Ze(),this.accountId=null,this._preselectState=Je()}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(R(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=W(window.location.href);const n=Z(),r=wt(e);n.push(r);const s=Math.min(n.length,Ee),o=Ne(n);if(o===0){const c=j()?"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=j()?"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=$e(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(){Xe(this._preselectState,this.buildPreselectHost())}isLauncherReadyToAttach(){return!!window.Rokt&&L(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[_.EMAIL_SHA256_KEY]=e[n]),n&&delete t[n],t}logSelectPlacementsEvent(e){if(!window.mParticle||typeof a().logEvent!="function"||!p(e))return;const t=a().EventType.Other;a().logEvent(ot,t,e)}setRoktSessionId(e){if(!(!e||typeof e!="string"))try{const t=a().getInstance();t&&L(t.setIntegrationAttribute)&&t.setIntegrationAttribute(O,{roktSessionId:e})}catch{}}readMpSessionId(){const e=a()?.sessionManager,t=e?.getSessionId??e?.getSession;if(L(t))return t.call(e)||void 0}readMpDeviceId(){return a()?.getDeviceId?.()||void 0}attachLauncher(e,t,n=[]){et(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 Pt([...n],o),this.initRoktLauncher(o)}).catch(o=>{nt(this._launcherAttachState),console.error("Error creating Rokt launcher:",o)})}recreateLauncherIfTerminated(){return st(this._launcherAttachState,this.isLauncherReadyToAttach(),e=>this.attachLauncher(e.accountId,e.launcherOptions,e.legacyRoktExtensions))}initRoktLauncher(e){window.Rokt&&(window.Rokt.currentLauncher=e),this.launcher=e,tt(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,de(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=T(s),this._onboardingExpProvider=o.onboardingExpProvider;const u=N(o.placementEventMapping);this.placementEventMappingLookup=ae(u);const l=N(o.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=le(l),o.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=o.hashedEmailUserIdentityType.toLowerCase()),this._workspaceIdSyncApiKey=g(o.workspaceIdSyncApiKey)?o.workspaceIdSyncApiKey:void 0;const m=a().Rokt?.domain,{roktExtensionsQueryParams:F,legacyRoktExtensions:v,loadThankYouElement:w}=ce(o.roktExtensions),E={...a().Rokt?.launcherOptions||{}};this.integrationName=Rt(E.integrationName),E.integrationName=this.integrationName,this.domain=m;const A={loggingUrl:o.loggingUrl,errorUrl:o.errorUrl,integrationDomain:m,isLoggingEnabled:a().config?.isLoggingEnabled===!0},I=new he(A,this.integrationName,window.__rokt_li_guid__,o.accountId),P=new ge(A,I,this.integrationName,window.__rokt_li_guid__,o.accountId);if(this.errorReportingService=I,this.loggingService=P,this.isTargetingDisabled())try{ee(),te()}catch(f){this.errorReportingService?.report({message:"Rokt Kit: Failed to clear page views when targeting is disabled",code:"PAGE_VIEW_CAPTURE_FAILED",severity:S.INFO,stackTrace:f instanceof Error?f.stack:void 0})}return a()._registerErrorReportingService&&a()._registerErrorReportingService(I),a()._registerLoggingService&&a()._registerLoggingService(P),n?(this.testHelpers={generateLauncherScript:re,generateThankYouElementScript:se,extractRoktExtensionConfig:ce,hashEventMessage:ue,parseSettingsString:N,generateMappedEventLookup:ae,generateMappedEventAttributeLookup:le,sendAdBlockMeasurementSignals:de,createAutoRemovedIframe:V,djb2:pe,setAllowedOriginHashes:f=>{_._allowedOriginHashes=f},ReportingTransport:C,ErrorReportingService:he,LoggingService:ge,RateLimiter:Pe,ErrorCodes:J,WSDKErrorSeverity:S,resetLauncherAttachState:()=>rt(this._launcherAttachState)},this.attachLauncher(c,E),"Successfully initialized: "+d):(w&&(a().Rokt.flushOnShoppableAdsReadyMessageQueue?.(this),oe(dt,se(m),{onLoad:()=>{this._isThankYouElementLoaded=!0,this._thankYouElementOnLoadCallback&&this._thankYouElementOnLoadCallback()},onError:f=>{console.error("Error loading Rokt Thank You Element script:",f)}})),this.isLauncherReadyToAttach()?this.attachLauncher(c,E,v):(oe(ut,re(m,F),{onLoad:()=>{this.isLauncherReadyToAttach()?this.attachLauncher(c,E,v):console.error("Rokt object is not available after script load.")},onError:f=>{console.error("Error loading Rokt launcher script:",f)}}),this.captureTiming(_.PERFORMANCE_MARKS.RoktScriptAppended)),"Successfully initialized: "+d)}process(e){if(this.isTargetingDisabled()||(e.EventDataType===gt&&(Ce(this.loggingService),this.capturePageView(e),ye(this._preselectState,this.buildPreselectHost(),e)),e.EventDataType===ft&&(ee(),te())),!this.isKitReady())return"Kit not ready for forwarder: "+d;if(L(a().Rokt?.setLocalSessionAttribute)&&(R(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(e),!R(this.placementEventMappingLookup))){const t=ue(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 fe(e)||(this.userAttributes[e]=t),qe(this.accountId,e)&&this.flushPendingPreselectDispatches(),"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=T(e.getAllUserAttributes()),"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=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,ne))]):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,ne))]).then(()=>this._dispatchPlacements(e))}return this._dispatchPlacements(e)}_dispatchPlacements(e){const t=e&&e.attributes||{},r={...T(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=T(l);const m=this._onboardingExpProvider==="Optimizely"?this.fetchOptimizely():{},F=this.returnUserIdentities(c),v=this.returnLocalSessionAttributes(),w=Ue(Z()),E=Ke(),A=this.readMpSessionId(),I=this.readMpDeviceId(),P={...F,...l,...m,...v,...w.length?{[pt]:JSON.stringify(w)}:{},...E?{[mt]:E}:{},...this.userIdentifiedInWorkspace?{[ht]:!0}:{},...A?{[Et]:A}:{},...I?{[_t]:I}:{},mpid:u},f=this.buildCacheMatchKeys(typeof e.identifier=="string"?e.identifier:void 0),Re={...e,attributes:P,...f!==void 0?{cacheMatchKeys:f}:{}},B=this.launcher.selectPlacements(Re),Q=e.preselect===!0,be=()=>{Q||this.logSelectPlacementsEvent(P)};return Promise.resolve(B).then(ke=>{if(!Q)return ke?.context?.sessionId?.then(ve=>this.setRoktSessionId(ve))}).catch(()=>{}).finally(be),B}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()?(it(this._launcherAttachState),this.launcher.terminate()):(console.error("Rokt Kit: Not initialized"),Promise.resolve())}onShoppableAdsReady(e){this._isThankYouElementLoaded?e():this._thankYouElementOnLoadCallback=e}};_._allowedOriginHashes=[-553112570,549508659],_.PERFORMANCE_MARKS={RoktScriptAppended:"mp:RoktScriptAppended"},_.EMAIL_SHA256_KEY="emailsha256";let y=_;function Tt(){return O}function Lt(i){if(!i){window.console.log("You must pass a config object to register the kit "+d);return}if(!p(i)){window.console.log("'config' must be an object. You passed in a "+typeof i);return}p(i.kits)?i.kits[d]={constructor:y}:(i.kits={},i.kits[d]={constructor:y}),window.console.log("Successfully registered "+d+" to your mParticle configuration")}typeof window<"u"&&window.mParticle&&a().addForwarder&&a().addForwarder({name:d,constructor:y,getId:Tt});exports.register=Lt;
|
|
2
2
|
//# sourceMappingURL=Rokt-Kit.common.js.map
|
package/dist/Rokt-Kit.d.ts
CHANGED
|
@@ -12,7 +12,6 @@ declare interface LogEntry {
|
|
|
12
12
|
|
|
13
13
|
export declare class LoggingService {
|
|
14
14
|
private readonly _transport;
|
|
15
|
-
private readonly _diagnosticTransport;
|
|
16
15
|
private readonly _placementDiagnosticTransport;
|
|
17
16
|
private readonly _loggingUrl;
|
|
18
17
|
private readonly _errorReportingService;
|
|
@@ -20,7 +19,6 @@ export declare class LoggingService {
|
|
|
20
19
|
report: (e: ErrorReport) => void;
|
|
21
20
|
}, integrationName: string | null | undefined, launcherInstanceGuid?: string, accountId?: string | null, rateLimiter?: RateLimiter);
|
|
22
21
|
log(entry: LogEntry | null | undefined): void;
|
|
23
|
-
logDiagnostic(entry: LogEntry | null | undefined): void;
|
|
24
22
|
logPlacementDiagnostic(entry: LogEntry | null | undefined): void;
|
|
25
23
|
private _send;
|
|
26
24
|
}
|