@schibsted/sourcepoint
Version:
Package containing scripts used by Schibsteds' sites to integrate with Sourcepoint CMP
2 lines (1 loc) • 19.2 kB
JavaScript
;const e=["jsSdkVersion","id","realm","clientId","pulseTracker","referrer","state","pulseObjectName","showInWebview","identityObject","identityObjectName","disableSentry","disableNativeConsentCheck","enableUserCentric","groupId"],n=["jsSdkVersion","id","realm","clientId","pulseTracker","referrer","state","pulseObjectName","showInWebview","identityObject","identityObjectName","disableSentry","disableNativeConsentCheck","enableUserCentric","groupId"],t=["jsSdkVersion","id","realm","clientId","pulseTracker","referrer","state","pulseObjectName","showInWebview","identityObject","identityObjectName","disableSentry","disableNativeConsentCheck","enableUserCentric","enableEcosystemConsent","groupId"];function s(e,n){if(null==e)return{};var t={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(n.includes(s))continue;t[s]=e[s]}return t}function o(e,n){var t,s;if(null!=(t=e.psi)&&t.identityObject)return e.psi.identityObject;if(null!=n&&n.identityObject)return n.identityObject;const o=(null==(s=e.psi)?void 0:s.identityObjectName)||(null==n?void 0:n.identityObjectName)||"Identity";return e[o]?e[o]:console.warn("@schibsted/sourcepoint: No Schibsted Account integration detected.")}async function r(e,n,t){return void 0===n&&(n={}),void 0===t&&(t=1e4),new Promise(((s,r)=>{if(e.schIdentity)return s(e.schIdentity);const i=setTimeout((()=>{r(new Error("@schibsted/sourcepoint: Timeout of "+t+"ms exceeded while waiting for schIdentity instance"))}),t);e.addEventListener("schIdentity:ready",(e=>{let{detail:n}=e;w("schIdentity instance resolved from schIdentity:ready event ",!!n.instance),clearTimeout(i),s(n.instance)}),{once:!0});const c=o(e,n);c&&(console.warn("@schibsted/sourcepoint: schIdentity instance not found, falling back to legacy Identity instance. Please update to the latest Schibsted Account SDK."),clearTimeout(i),s(c))}))}function i(e){const n=Array.from({length:20},(()=>String.fromCharCode(Math.floor(25*Math.random()+97)))).join(""),t=btoa(JSON.stringify(n));o(e)&&o(e).login({state:t})}const c=["Mixed","PSI","SCC","TCF","PMC"],a="default",u="cmp",l="cache",p="accepted",d="rejected",f="unknown",g=Object.freeze({purposes:{CMP_ANALYTICS:{optIn:!1,status:f},CMP_MARKETING:{optIn:!1,status:f},CMP_ADVERTISING:{optIn:!1,status:f},CMP_PERSONALIZATION:{optIn:!1,status:f}},source:a});function y(e,n,t,s){w("Pulse: "+t+"(actor, data):",n,s),m(e,(e=>{e&&"function"==typeof e.track&&e.track(t,{schema:"http://schema.schibsted.com/events/tracker-event.json/314.json",object:Object.assign({},s,y.pulseCommonData),provider:{component:"CMP"},actor:n})}))}function m(e,n){var t,s;if(null!=(t=e.psi)&&t.pulseTracker)return n(e.psi.pulseTracker);const o=(null==(s=e.psi)?void 0:s.pulseObjectName)||"pulse";return"function"!=typeof e[o]?console.error("No Pulse integration detected. Aborting."):e[o]((e=>{"function"==typeof n&&n(e)}))}function b(){var e;const n=null==(e=y.pulseCommonData)?void 0:e.messageName;if(n)return c.find((e=>n.includes(e)))}function h(e){return"CMP_"+("personalisation"===e?"personalization":e).toUpperCase()}function v(e,n,t){const s=Object.keys(_(e)).filter((n=>_(e)[n])),o=Object.keys(_(e)).filter((n=>!_(e)[n]));return s.map((e=>{const t=n.purposes[h(e)];t.optIn=!0,t.status=p})),o.map((e=>{n.purposes[h(e)].status=d})),n.source=t,n}function _(e){const n=P((e._scc_||e._tcf_).getPermissionSync("CMP:advertising")),t=P((e._scc_||e._tcf_).getPermissionSync("CMP:analytics")),s=P((e._scc_||e._tcf_).getPermissionSync("CMP:marketing")),o=P((e._scc_||e._tcf_).getPermissionSync("CMP:personalisation"));var r;return r={advertising:n,analytics:t,marketing:s,personalisation:o},Object.entries(r).filter((e=>{let[n,t]=e;return null!=t})).reduce(((e,n)=>{let[t,s]=n;return Object.assign({},e,{[t]:s})}),{})}function I(e,n){const t=n.performance.now();return e?Math.round((t-e)/1e3):null}function w(){"undefined"!=typeof document&&document.location.href.indexOf("sp_debug=1")>0&&console.debug("[CMP]",...arguments)}function C(e,n,t,s,o){const r=new URL(e);r.searchParams.append("utm_source","cmp"),r.searchParams.append("utm_medium","psi"),r.searchParams.append("referrer",s||window.location.href),t&&r.searchParams.append("client_id",t),n&&r.searchParams.append("environment_id",n),o&&r.searchParams.append("state",o),window.location.href=r.href}function P(e){return null===e?null:Boolean(parseInt(e))}const S=(e,n)=>Object.keys(n).filter((n=>void 0!==e[n])).forEach((t=>"object"==typeof n[t]?Object.keys(n[t]).forEach((s=>e[t][s]=n[t][s])):e[t]=n[t]));function j(e,n,t){const s=new Date;s.setTime(s.getTime()+24*t*60*60*1e3);let o="expires="+s.toUTCString();document.cookie=e+"="+n+";"+o+";path=/"}function O(e){let n=e+"=",t=decodeURIComponent(document.cookie).split(";");for(let e=0;e<t.length;e++){let s=t[e];for(;" "==s.charAt(0);)s=s.substring(1);if(0==s.indexOf(n))return s.substring(n.length,s.length)}return""}function M(e){document.cookie=e+"=; Max-Age=-99999999;"}function T(e,n,t){e.targetingParams=e.targetingParams||{},e.targetingParams[n]=t}const k=function(e){if("number"==typeof e||void 0===e)return config.userId=e;throw new Error("Id value "+e+" is invalid")},E=function(e){return(e=>{try{return Boolean(new URL(e))}catch(e){return!1}})(e)?window.psi.isLoggedInUser?C(e,null,window.psi.clientId,window.psi.referrer,window.psi.state):m(window,(n=>{n.getEnvironmentId().then((n=>{C(e,n,window.psi.clientId,window.psi.referrer,window.psi.state)}))})):console.error("The URL passed to the configuration is invalid. Please, correct it.")},N=function(){return i(window)};let A=null,L=!1,U=!1;function R(e,n){if(n&&("object"!=typeof(t=n)||t.constructor!==Object))return console.error("Provided object is incorrect");var t;if(0===Object.keys(_(e)).length){if(!n)return g;const e=JSON.parse(JSON.stringify(n));return e.source=a,e}return v(e,JSON.parse(JSON.stringify(n||g)),l)}function x(e,n){n.events=n.events||{};const t=n.events.onMessageReceiveData,s=n.events.onMessageChoiceSelect,o=n.events.onMessageReady,r=n.events.onPrivacyManagerAction,i=n.events.onConsentReady;let c,a=!0;const l={id:n.userId,realm:n.realm};n.events.onMessageReceiveData=function(e,s){w("Sourcepoint: onMessageReceiveData(data)",s),A=!0,y.pulseCommonData={"@id":"sdrn:privacy:cmp:"+(s.messageId||""),"@type":"CMP",messageName:s.msgDescription||"",propertyId:n.propertyId,messageId:s.messageId||void 0,bucket:s.bucket||void 0,jsSdkVersion:n.jsSdkVersion,partitionId:s.prtnUUID||"",language:n.consentLanguage},"function"==typeof t&&t(s)},n.events.onMessageReady=function(){var n;null==(n=window._tcf_)||null==(n=n.TCFCallbacks)||n.map((e=>{e()})),w("Sourcepoint: onMessageReady()");const t=b();if(w("Pulse: Detected message type: "+t),!A)return y(e,l,"View",{name:"CMP: Privacy Manager displayed",messageType:b()});c=e.performance.now(),y(e,l,"View",{name:"CMP: Message displayed",messageType:t}),"function"==typeof o&&o()},n.events.onMessageChoiceSelect=function(n,t,o){if(w("Sourcepoint: onMessageReady(choice_id="+t+", choice_type_id="+o+")"),5===o){const n=I(c,e);y(e,l,"engagementEvent",Object.assign({name:"CMP: Link to Privacy / Cookie Policy clicked",elementType:"anchor",isFirstLayer:A,messageType:b()},n&&{duration:n})),A=null}if(9===o){a=!1,A=null;const n=I(c,e);y(e,l,"engagementEvent",Object.assign({name:"CMP: Open Privacy Settings",elementType:"button",messageType:b()},n&&{duration:n}))}if(11===o&&(a=!0),12===o&&(A=!1),15===o){const n=I(c,e);y(e,l,"engagementEvent",Object.assign({name:"CMP: Dismiss message",elementType:"button",messageType:b()},n&&{duration:n}))}"function"==typeof s&&s(t,o)},n.events.onPrivacyManagerAction=function(e,n){w("Sourcepoint: onPrivacyManagerAction()"),L=!0,A=!1,"none"===n.purposeConsent?(U=!0,a=!1):(U=!1,a=!0),"function"==typeof r&&r()},n.events.onConsentReady=function(n,t,s,o){var r,p;null==(r=window._tcf_)||null==(r=r.consentedCallback)||r.map((e=>{e(o.consentedToAll)})),null==(p=window._tcf_)||null==(p=p.TCFCallbacks)||p.map((e=>{e()})),w("Sourcepoint: onConsentReady(message_type="+n+", consentUUID="+t+", euconsent)",s),w("Sourcepoint: getMessageType() "+b());const d=I(c,e);if(void 0===b()&&!L)return;const f="PSI"===b()?null:_(e);if(function(e){const n=JSON.parse(JSON.stringify(g));m(e,(t=>{try{t.setConsents(v(e,n,u))}catch(e){console.error("Consents couldn't be set. The provided version of Pulse SDK does not support the setConsents event")}}))}(e),U&&y(e,l,"engagementEvent",Object.assign({name:"CMP: Reject all",elementType:"button",messageType:b()},d&&{duration:d})),!a)return!1;y(e,l,"engagementEvent",Object.assign({name:"CMP: Accept",elementType:"button",messageType:b(),consentedToAll:null==o?void 0:o.consentedToAll,isFirstLayer:A||!!A},f&&{consents:f},d&&{duration:d})),A=null,L=!1,U=!1,"function"==typeof i&&i(n,t,s,o)}}function D(e){e.events=e.events||{},e.events.onError=function(n,t,s){try{n&&window._cmp_.sentry.setTag("message_type",n),t&&window._cmp_.sentry.setTag("errorCode",t),window._cmp_.sentry.setTag("propertyId",e.propertyId),window._cmp_.sentry.captureException(s)}catch(e){console.error("Can not send the error to Sentry, "+e)}},e.events.onMessageChoiceError=function(e,n){try{e&&window._cmp_.sentry.setTag("message_type",e),window._cmp_.sentry.captureException(n)}catch(n){console.error("Can not send the error to Sentry, "+n)}}}const H=["Hermes","_app_","tv.nu","FinnApp","Omni"];function W(e){return H.some((n=>e.userAgent.includes(n)))}function F(e,n,t){return W(n)&&!t.disableNativeConsentCheck&&!function(e){var n;const t=new URLSearchParams(null==(n=e.location)?void 0:n.search),s=t.has("_sp_pass_consent");try{if(s)return e.sessionStorage.setItem("_sp_pass_consent","true"),!0;if("true"===e.sessionStorage.getItem("_sp_pass_consent")){t.set("_sp_pass_consent","true");const n=e.location.pathname+"?"+t.toString()+e.location.hash;return e.history.replaceState({},"",n),!0}}catch(e){return s}return!1}(e)}function J(n,t,o,r,i){V(n,t,o,r,i);return z(n,s(r,e))}function V(e,n,t,s,r){var i,c,a;if(!(s&&s.baseEndpoint&&s.propertyId&&s.consentLanguage))throw new Error("One of missing: baseEndpoint, propertyId, consentLanguage");x(e,s),D(s),s.accountId=s.accountId||1047,s.custom={},"psi"!==r&&(s.gdpr={includeTcfApi:"tcf"===r}),s.propertyHref&&(s.joinHref=!0);const u=s.userId||(null==(i=o(e,s))?void 0:i._session.userId);u&&T(s,"loggedin","true");const l=s.clientId||(null==(c=o(e,s))?void 0:c.clientId);W(t)&&T(s,"mobile-webview",!s.showInWebview||s.showInWebview);const p=null==n||null==(a=n.referrer)?void 0:a.split("/")[2];p&&T(s,"referrer-hostname",p),function(){const e=/(_sch_cmp_[_a-z0-9]+)=(.+)/i;n.cookie.split(";").filter((n=>e.test(n))).map((e=>e.split("=").map((e=>e.trim())))).forEach((e=>{let[n,t]=e;return T(s,n,t)}))}(),s.propertyHref&&n.location.search&&-1===s.propertyHref.indexOf("?")&&(s.propertyHref+=n.location.search);const{pulseTracker:d,referrer:f,state:g,pulseObjectName:y,showInWebview:m,identityObject:b,identityObjectName:h,enableUserCentric:v,groupId:_}=s;e.psi=e.psi||{},e.psi.isLoggedInUser=!!u,e.psi.setUserId=k,e.psi.openPrivacySettings=E,e.psi.pulseTracker=d,e.psi.clientId=l,e.psi.referrer=f,e.psi.state=g,e.psi.pulseObjectName=y,e.psi.showInWebview=m,e.psi.identityObject=b,e.psi.identityObjectName=h,e.psi.triggerLogin=N,e.psi.enableUserCentric=v,e.psi.groupId=_}function z(e,n){e._sp_=e._sp_||{},e._sp_.config=n,w("Sourcepoint initiated with config: ",n)}function B(e,n,t){if(!n||!n.groupPmId)throw new Error("groupPmId is required");const s="CMP:advertising",o="CMP:analytics",r="CMP:marketing",i="CMP:personalisation",c="CMP:performance_marketing";let a=[];const u={};function l(n){return w(t+": getPermissionFromCache(category="+n+")"),e.localStorage.getItem(n)}u[s]=[],u[o]=[],u[r]=[],u[i]=[],u[c]=[];let p=null;const d={subscribers:u,consentedCallback:[],TCFCallbacks:[],showPrivacyManager:function(){w("${type}: showPrivacyManager()"),y.pulseCommonData.messageName="",L=!0,A=!1,e._sp_.gdpr.loadPrivacyManagerModal(n.groupPmId)},getPermissionSync:function(e){return w(t+": getPermissionSync(category="+e+")"),l(e)},getPermission:function(e,n){w(t+": getPermission(category="+e+")");const s=d.subscribe(e,function(){let e=!1;return t=>{e?"function"==typeof s&&s():(e=!0,n(t),n=function(){})}}())},notify:(f={[s]:l(s),[o]:l(o),[r]:l(r),[i]:l(i),[c]:l(c)},(e,n)=>{if(f[e]===n)return void w(t+": notify(category="+e+", value="+n+") - IGNORED");null===p&&(p=setTimeout((()=>{const e=a;for(let n=0;n<e.length;n++)e[n]();p=null}),10)),w(t+": notify(category="+e+", value="+n+")"),f[e]=n;const s=d.subscribers[e];for(let e=0;e<s.length;e++)s[e](n)}),subscribe:function(e,n){if(w(t+": subscribe(category="+e+")"),!d.subscribers[e])return void console.error("Unable to subscribe - undefined consent category!");d.subscribers[e].push(n);const s=l(e);return null!==s&&n(s),()=>{d.subscribers[e]=d.subscribers[e].filter((e=>e!==n))}},subscribeAny:function(e){return w("subscribeAny"),a.push(e),()=>{a=a.filter((n=>n!==e))}},getCachedOrDefaultConsentsForPulse:function(n){return R(e,n)},isConsentedToAll:function(e){d.consentedCallback.push(e)},getConsentedToAllSync:function(){const e=l("_sp_user_consent_"+n.propertyId);try{var t;if(0===Object.keys(localStorage).filter((e=>e.startsWith("CMP:"))).length)return null;const n=null==(t=JSON.parse(e))||null==(t=t.gdpr)?void 0:t.consentStatus;if((null==n?void 0:n.vendorListAdditions)||(null==n?void 0:n.legalBasisChanges))return null;const s=null==n?void 0:n.consentedAll;return void 0===s?null:s}catch(e){return null}},onTcfReady:function(e){d.TCFCallbacks.push(e)}};var f;return e._SourcePoint_Consent_Callback=d.notify,d}async function G(e,n,i,c){!function(e,n,t,s){var r,i;if(!(s&&s.baseEndpoint&&s.propertyId&&s.consentLanguage))throw new Error("One of missing: baseEndpoint, propertyId, consentLanguage");e._sp_=e._sp_||{},e._sp_.config=e._sp_.config||{},x(e,s),D(s),s.propertyHref&&(s.joinHref=!0);s.accountId=s.accountId||1047,s.custom={},s.gdpr={includeTcfApi:!0};["baseEndpoint","propertyId","consentLanguage","accountId","propertyHref","joinHref","gdpr","custom"].forEach((n=>{void 0!==s[n]&&(e._sp_.config[n]=s[n])}));const c=s.userId||(null==(r=o(e,s))||null==(r=r._session)?void 0:r.userId),a=s.clientId||(null==(i=o(e,s))?void 0:i.clientId),{pulseTracker:u,referrer:l,state:p,pulseObjectName:d,showInWebview:f,identityObject:g,identityObjectName:y,enableUserCentric:m,groupId:b}=s;e.psi=e.psi||{},e.psi.isLoggedInUser=!!c,e.psi.setUserId=k,e.psi.openPrivacySettings=E,e.psi.pulseTracker=u,e.psi.clientId=a,e.psi.referrer=l,e.psi.state=p,e.psi.pulseObjectName=d,e.psi.showInWebview=f,e.psi.identityObject=g,e.psi.identityObjectName=y,e.psi.triggerLogin=N,e.psi.enableUserCentric=m,e.psi.groupId=b}(e,0,0,c);const{enableEcosystemConsent:a}=c,u=s(c,t);if(!a)return w("Ecosystem Consent is disabled"),K(e,u);try{const n=await r(e);if(!n)return console.warn("Ecosystem Consent: No Schibsted Account integration detected."),K(e,u);const t=await async function(e){if(!e)return null;try{if(!(O("CMP:isLoggedIn")||await e.isLoggedIn()))return null;e.on("logout",(function(){M("CMP:isLoggedIn")})),O("CMP:isLoggedIn")||j("CMP:isLoggedIn",!0);const n=await e.getUserId();if(!n)return console.warn("Ecosystem Consent: Invalid userId received from getUserId()"),null;const t=await async function(e){const n=(new TextEncoder).encode(e),t=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}(n);return t}catch(e){return console.error("Ecosystem Consent - Identity error: ",e),null}}(n);return t?(w("Ecosystem Consent: AuthId resolved for authenticated user"),T(c,"ecosystem-consent",!0),K(e,Object.assign({authId:t,targetingParams:c.targetingParams},u))):(w("Ecosystem Consent: No authId available, falling back to standard config"),K(e,u))}catch(n){return console.error("Ecosystem Consent setup error: ",n),K(e,u)}}function K(e,n){e._sp_=e._sp_||{},e._sp_.config=e._sp_.config||{},Object.assign(e._sp_.config,n),w("Ecosystem Consent initiated with config: ",e._sp_.config)}function q(e,n){const t=e.baseEndpoint+"/unified/wrapperMessagingWithoutDetection.js",s=n.getElementsByTagName("script"),o=s[s.length-1],r=n.createElement("link");S(r,{rel:"preload",as:"script",crossorigin:"crossorigin",href:t}),n.head.appendChild(r);const i=n.createElement("script");S(i,{async:!0,src:t,onload:()=>(w("dispatching cmp:loaded event"),void document.dispatchEvent(new Event("cmp:loaded")))}),o.insertAdjacentElement("afterend",i)}function Y(){w("dispatching cmp:ready event"),document.dispatchEvent(new Event("cmp:ready"))}function Z(e,n){if(n.disableSentry)return;const t=e.createElement("script");S(t,{async:!0,type:"module",src:"https://static.privacy.schibsted.com/dist/index.js",fetchPriority:"low"}),e.head.appendChild(t)}exports.psi=function(e,n,t,s){Z(n,s),J(e,n,t,Object.assign({},s,{jsSdkVersion:"5.5.9"}),"psi"),q(s,n),Y()},exports.scc=function(e,n,t,s){Z(n,s),J(e,n,t,s,"scc"),function(e,n){e._scc_=B(e,n)}(e,s),q(s,n),Y()},exports.tcf=async function(e,t,o,i){F(e,o,i)?console.warn("CMP: Native consent is not passed. Sourcepoint will not be initialized."):(!function(e){const n=e.createElement("script");n.innerHTML='"use strict";function _typeof(t){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}!function(){var t=function(){var t,e,o=[],n=window,r=n;for(;r;){try{if(r.frames.__tcfapiLocator){t=r;break}}catch(t){}if(r===n.top)break;r=r.parent}t||(!function t(){var e=n.document,o=!!n.frames.__tcfapiLocator;if(!o)if(e.body){var r=e.createElement("iframe");r.style.cssText="display:none",r.name="__tcfapiLocator",e.body.appendChild(r)}else setTimeout(t,5);return!o}(),n.__tcfapi=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];if(!n.length)return o;"setGdprApplies"===n[0]?n.length>3&&2===parseInt(n[1],10)&&"boolean"==typeof n[3]&&(e=n[3],"function"==typeof n[2]&&n[2]("set",!0)):"ping"===n[0]?"function"==typeof n[2]&&n[2]({gdprApplies:e,cmpLoaded:!1,cmpStatus:"stub"}):o.push(n)},n.addEventListener("message",(function(t){var e="string"==typeof t.data,o={};if(e)try{o=JSON.parse(t.data)}catch(t){}else o=t.data;var n="object"===_typeof(o)&&null!==o?o.__tcfapiCall:null;n&&window.__tcfapi(n.command,n.version,(function(o,r){var a={__tcfapiReturn:{returnValue:o,success:r,callId:n.callId}};t&&t.source&&t.source.postMessage&&t.source.postMessage(e?JSON.stringify(a):a,"*")}),n.parameter)}),!1))};"undefined"!=typeof module?module.exports=t:t()}();',e.head.appendChild(n)}(t),Z(t,i),function(e,n){e._tcf_=B(e,n)}(e,i),i.enableEcosystemConsent?await G(e,0,0,i):i.enableUserCentric?await async function(e,t,o,i,c){V(e,t,o,i,c);const a=s(i,n);try{const n=await r(e);if(!O("CMP:isLoggedIn")&&!await n.isLoggedIn())return z(e,a);n.on("logout",(function(){M("CMP:isLoggedIn")})),O("CMP:isLoggedIn")||j("CMP:isLoggedIn",!0),T(i,"loggedin",!0);const t={externalParty:"sourcepoint",optionalSuffix:i.groupId},s=await n.getExternalId(t.externalParty,t.optionalSuffix),o=T(i,"enableUserCentric",!0);z(e,Object.assign({authId:s,targetingParams:o},a))}catch(n){console.error("Identity: ",n),z(e,a)}}(e,t,o,i,"tcf"):J(e,t,o,i,"tcf"),q(i,t),Y())};