@schibsted/sourcepoint
Version:
Package containing scripts used by Schibsteds' sites to integrate with Sourcepoint CMP
2 lines (1 loc) • 18.7 kB
JavaScript
!function(){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 o(e,n){if(null==e)return{};var t={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(n.includes(o))continue;t[o]=e[o]}return t}const s="__CONFIGURATION_PLACEHOLDER__";function r(e,n){var t,o;if(null!=(t=e.psi)&&t.identityObject)return e.psi.identityObject;if(null!=n&&n.identityObject)return n.identityObject;const s=(null==(o=e.psi)?void 0:o.identityObjectName)||(null==n?void 0:n.identityObjectName)||"Identity";return e[s]?e[s]:console.warn("@schibsted/sourcepoint: No Schibsted Account integration detected.")}async function i(e,n,t){return void 0===n&&(n={}),void 0===t&&(t=1e4),new Promise(((o,s)=>{if(e.schIdentity)return o(e.schIdentity);const i=setTimeout((()=>{s(new Error("@schibsted/sourcepoint: Timeout of "+t+"ms exceeded while waiting for schIdentity instance"))}),t);e.addEventListener("schIdentity:ready",(e=>{let{detail:n}=e;C("schIdentity instance resolved from schIdentity:ready event ",!!n.instance),clearTimeout(i),o(n.instance)}),{once:!0});const c=r(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),o(c))}))}function c(e){const n=Array.from({length:20},(()=>String.fromCharCode(Math.floor(25*Math.random()+97)))).join(""),t=btoa(JSON.stringify(n));r(e)&&r(e).login({state:t})}const a=["Mixed","PSI","SCC","TCF","PMC"],u="default",l="cmp",d="cache",p="accepted",f="rejected",g="unknown",y=Object.freeze({purposes:{CMP_ANALYTICS:{optIn:!1,status:g},CMP_MARKETING:{optIn:!1,status:g},CMP_ADVERTISING:{optIn:!1,status:g},CMP_PERSONALIZATION:{optIn:!1,status:g}},source:u});function m(e,n,t,o){C("Pulse: "+t+"(actor, data):",n,o),b(e,(e=>{e&&"function"==typeof e.track&&e.track(t,{schema:"http://schema.schibsted.com/events/tracker-event.json/314.json",object:Object.assign({},o,m.pulseCommonData),provider:{component:"CMP"},actor:n})}))}function b(e,n){var t,o;if(null!=(t=e.psi)&&t.pulseTracker)return n(e.psi.pulseTracker);const s=(null==(o=e.psi)?void 0:o.pulseObjectName)||"pulse";return"function"!=typeof e[s]?console.error("No Pulse integration detected. Aborting."):e[s]((e=>{"function"==typeof n&&n(e)}))}function v(){var e;const n=null==(e=m.pulseCommonData)?void 0:e.messageName;if(n)return a.find((e=>n.includes(e)))}function h(e){return"CMP_"+("personalisation"===e?"personalization":e).toUpperCase()}function _(e,n,t){const o=Object.keys(w(e)).filter((n=>w(e)[n])),s=Object.keys(w(e)).filter((n=>!w(e)[n]));return o.map((e=>{const t=n.purposes[h(e)];t.optIn=!0,t.status=p})),s.map((e=>{n.purposes[h(e)].status=f})),n.source=t,n}function w(e){const n=S((e._scc_||e._tcf_).getPermissionSync("CMP:advertising")),t=S((e._scc_||e._tcf_).getPermissionSync("CMP:analytics")),o=S((e._scc_||e._tcf_).getPermissionSync("CMP:marketing")),s=S((e._scc_||e._tcf_).getPermissionSync("CMP:personalisation"));var r;return r={advertising:n,analytics:t,marketing:o,personalisation:s},Object.entries(r).filter((e=>{let[n,t]=e;return null!=t})).reduce(((e,n)=>{let[t,o]=n;return Object.assign({},e,{[t]:o})}),{})}function I(e,n){const t=n.performance.now();return e?Math.round((t-e)/1e3):null}function C(){"undefined"!=typeof document&&document.location.href.indexOf("sp_debug=1")>0&&console.debug("[CMP]",...arguments)}function P(e,n,t,o,s){const r=new URL(e);r.searchParams.append("utm_source","cmp"),r.searchParams.append("utm_medium","psi"),r.searchParams.append("referrer",o||window.location.href),t&&r.searchParams.append("client_id",t),n&&r.searchParams.append("environment_id",n),s&&r.searchParams.append("state",s),window.location.href=r.href}function S(e){return null===e?null:Boolean(parseInt(e))}function O(e,n,t){const o=new Date;o.setTime(o.getTime()+24*t*60*60*1e3);let s="expires="+o.toUTCString();document.cookie=e+"="+n+";"+s+";path=/"}function j(e){let n=e+"=",t=decodeURIComponent(document.cookie).split(";");for(let e=0;e<t.length;e++){let o=t[e];for(;" "==o.charAt(0);)o=o.substring(1);if(0==o.indexOf(n))return o.substring(n.length,o.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?P(e,null,window.psi.clientId,window.psi.referrer,window.psi.state):b(window,(n=>{n.getEnvironmentId().then((n=>{P(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 c(window)};let L=null,A=!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(w(e)).length){if(!n)return y;const e=JSON.parse(JSON.stringify(n));return e.source=u,e}return _(e,JSON.parse(JSON.stringify(n||y)),d)}function D(e,n){n.events=n.events||{};const t=n.events.onMessageReceiveData,o=n.events.onMessageChoiceSelect,s=n.events.onMessageReady,r=n.events.onPrivacyManagerAction,i=n.events.onConsentReady;let c,a=!0;const u={id:n.userId,realm:n.realm};n.events.onMessageReceiveData=function(e,o){C("Sourcepoint: onMessageReceiveData(data)",o),L=!0,m.pulseCommonData={"@id":"sdrn:privacy:cmp:"+(o.messageId||""),"@type":"CMP",messageName:o.msgDescription||"",propertyId:n.propertyId,messageId:o.messageId||void 0,bucket:o.bucket||void 0,jsSdkVersion:n.jsSdkVersion,partitionId:o.prtnUUID||"",language:n.consentLanguage},"function"==typeof t&&t(o)},n.events.onMessageReady=function(){var n;null==(n=window._tcf_)||null==(n=n.TCFCallbacks)||n.map((e=>{e()})),C("Sourcepoint: onMessageReady()");const t=v();if(C("Pulse: Detected message type: "+t),!L)return m(e,u,"View",{name:"CMP: Privacy Manager displayed",messageType:v()});c=e.performance.now(),m(e,u,"View",{name:"CMP: Message displayed",messageType:t}),"function"==typeof s&&s()},n.events.onMessageChoiceSelect=function(n,t,s){if(C("Sourcepoint: onMessageReady(choice_id="+t+", choice_type_id="+s+")"),5===s){const n=I(c,e);m(e,u,"engagementEvent",Object.assign({name:"CMP: Link to Privacy / Cookie Policy clicked",elementType:"anchor",isFirstLayer:L,messageType:v()},n&&{duration:n})),L=null}if(9===s){a=!1,L=null;const n=I(c,e);m(e,u,"engagementEvent",Object.assign({name:"CMP: Open Privacy Settings",elementType:"button",messageType:v()},n&&{duration:n}))}if(11===s&&(a=!0),12===s&&(L=!1),15===s){const n=I(c,e);m(e,u,"engagementEvent",Object.assign({name:"CMP: Dismiss message",elementType:"button",messageType:v()},n&&{duration:n}))}"function"==typeof o&&o(t,s)},n.events.onPrivacyManagerAction=function(e,n){C("Sourcepoint: onPrivacyManagerAction()"),A=!0,L=!1,"none"===n.purposeConsent?(U=!0,a=!1):(U=!1,a=!0),"function"==typeof r&&r()},n.events.onConsentReady=function(n,t,o,s){var r,d;null==(r=window._tcf_)||null==(r=r.consentedCallback)||r.map((e=>{e(s.consentedToAll)})),null==(d=window._tcf_)||null==(d=d.TCFCallbacks)||d.map((e=>{e()})),C("Sourcepoint: onConsentReady(message_type="+n+", consentUUID="+t+", euconsent)",o),C("Sourcepoint: getMessageType() "+v());const p=I(c,e);if(void 0===v()&&!A)return;const f="PSI"===v()?null:w(e);if(function(e){const n=JSON.parse(JSON.stringify(y));b(e,(t=>{try{t.setConsents(_(e,n,l))}catch(e){console.error("Consents couldn't be set. The provided version of Pulse SDK does not support the setConsents event")}}))}(e),U&&m(e,u,"engagementEvent",Object.assign({name:"CMP: Reject all",elementType:"button",messageType:v()},p&&{duration:p})),!a)return!1;m(e,u,"engagementEvent",Object.assign({name:"CMP: Accept",elementType:"button",messageType:v(),consentedToAll:null==s?void 0:s.consentedToAll,isFirstLayer:L||!!L},f&&{consents:f},p&&{duration:p})),L=null,A=!1,U=!1,"function"==typeof i&&i(n,t,o,s)}}function x(e,n,t){if(!n.groupPmId)throw new Error("groupPmId is required");const o="CMP:advertising",s="CMP:analytics",r="CMP:marketing",i="CMP:personalisation",c="CMP:performance_marketing";let a=[];const u={};function l(n){return C(t+": getPermissionFromCache(category="+n+")"),e.localStorage.getItem(n)}u[o]=[],u[s]=[],u[r]=[],u[i]=[],u[c]=[];let d=null;const p={subscribers:u,consentedCallback:[],TCFCallbacks:[],showPrivacyManager:function(){C("${type}: showPrivacyManager()"),m.pulseCommonData.messageName="",A=!0,L=!1,e._sp_.gdpr.loadPrivacyManagerModal(n.groupPmId)},getPermissionSync:function(e){return C(t+": getPermissionSync(category="+e+")"),l(e)},getPermission:function(e,n){C(t+": getPermission(category="+e+")");const o=p.subscribe(e,function(){let e=!1;return t=>{e?"function"==typeof o&&o():(e=!0,n(t),n=function(){})}}())},notify:(f={[o]:l(o),[s]:l(s),[r]:l(r),[i]:l(i),[c]:l(c)},(e,n)=>{if(f[e]===n)return void C(t+": notify(category="+e+", value="+n+") - IGNORED");null===d&&(d=setTimeout((()=>{const e=a;for(let n=0;n<e.length;n++)e[n]();d=null}),10)),C(t+": notify(category="+e+", value="+n+")"),f[e]=n;const o=p.subscribers[e];for(let e=0;e<o.length;e++)o[e](n)}),subscribe:function(e,n){if(C(t+": subscribe(category="+e+")"),!p.subscribers[e])return void console.error("Unable to subscribe - undefined consent category!");p.subscribers[e].push(n);const o=l(e);return null!==o&&n(o),()=>{p.subscribers[e]=p.subscribers[e].filter((e=>e!==n))}},subscribeAny:function(e){return C("subscribeAny"),a.push(e),()=>{a=a.filter((n=>n!==e))}},getCachedOrDefaultConsentsForPulse:function(n){return R(e,n)},isConsentedToAll:function(e){p.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 o=null==n?void 0:n.consentedAll;return void 0===o?null:o}catch(e){return null}},onTcfReady:function(e){p.TCFCallbacks.push(e)}};var f;return e._SourcePoint_Consent_Callback=p.notify,p}function H(e){e.events=e.events||{},e.events.onError=function(n,t,o){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(o)}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 F=["Hermes","_app_","tv.nu","FinnApp","Omni"];function J(e){return F.some((n=>e.userAgent.includes(n)))}function W(e,n,t){return J(n)&&!t.disableNativeConsentCheck&&!function(e){var n;const t=new URLSearchParams(null==(n=e.location)?void 0:n.search),o=t.has("_sp_pass_consent");try{if(o)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 o}return!1}(e)}function V(e,n,t,o,s){var i,c,a;if(!o.baseEndpoint||!o.propertyId||!o.consentLanguage)throw new Error("One of missing: baseEndpoint, propertyId, consentLanguage");D(e,o),H(o),o.accountId=o.accountId||1047,o.custom={},o.gdpr={includeTcfApi:"tcf"===s},o.propertyHref&&(o.joinHref=!0);const u=o.userId||(null==(i=r(e,o))?void 0:i._session.userId);u&&T(o,"loggedin","true");const l=o.clientId||(null==(c=r(e,o))?void 0:c.clientId);J(t)&&T(o,"mobile-webview",!o.showInWebview||o.showInWebview);const d=null==n||null==(a=n.referrer)?void 0:a.split("/")[2];d&&T(o,"referrer-hostname",d),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(o,n,t)}))}(),o.propertyHref&&n.location.search&&-1===o.propertyHref.indexOf("?")&&(o.propertyHref+=n.location.search);const{pulseTracker:p,referrer:f,state:g,pulseObjectName:y,showInWebview:m,identityObject:b,identityObjectName:v,enableUserCentric:h,groupId:_}=o;e.psi=e.psi||{},e.psi.isLoggedInUser=!!u,e.psi.setUserId=k,e.psi.openPrivacySettings=E,e.psi.pulseTracker=p,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=v,e.psi.triggerLogin=N,e.psi.enableUserCentric=h,e.psi.groupId=_}function G(e,n){e._sp_=e._sp_||{},e._sp_.config=n,C("Sourcepoint initiated with config: ",n)}async function z(e,n,s,c){!function(e,n,t,o){var s,i;if(!o.baseEndpoint||!o.propertyId||!o.consentLanguage)throw new Error("One of missing: baseEndpoint, propertyId, consentLanguage");e._sp_=e._sp_||{},e._sp_.config=e._sp_.config||{},D(e,o),H(o),o.propertyHref&&(o.joinHref=!0);o.accountId=o.accountId||1047,o.custom={},o.gdpr={includeTcfApi:!0};["baseEndpoint","propertyId","consentLanguage","accountId","propertyHref","joinHref","gdpr","custom"].forEach((n=>{void 0!==o[n]&&(e._sp_.config[n]=o[n])}));const c=o.userId||(null==(s=r(e,o))||null==(s=s._session)?void 0:s.userId),a=o.clientId||(null==(i=r(e,o))?void 0:i.clientId),{pulseTracker:u,referrer:l,state:d,pulseObjectName:p,showInWebview:f,identityObject:g,identityObjectName:y,enableUserCentric:m,groupId:b}=o;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=d,e.psi.pulseObjectName=p,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=o(c,t);if(!a)return C("Ecosystem Consent is disabled"),B(e,u);try{const n=await i(e);if(!n)return console.warn("Ecosystem Consent: No Schibsted Account integration detected."),B(e,u);const t=await async function(e){if(!e)return null;try{if(!(j("CMP:isLoggedIn")||await e.isLoggedIn()))return null;e.on("logout",(function(){M("CMP:isLoggedIn")})),j("CMP:isLoggedIn")||O("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?(C("Ecosystem Consent: AuthId resolved for authenticated user"),T(c,"ecosystem-consent",!0),B(e,Object.assign({authId:t,targetingParams:c.targetingParams},u))):(C("Ecosystem Consent: No authId available, falling back to standard config"),B(e,u))}catch(n){return console.error("Ecosystem Consent setup error: ",n),B(e,u)}}function B(e,n){e._sp_=e._sp_||{},e._sp_.config=e._sp_.config||{},Object.assign(e._sp_.config,n),C("Ecosystem Consent initiated with config: ",e._sp_.config)}function K(){C("dispatching cmp:ready event"),document.dispatchEvent(new Event("cmp:ready"))}function q(e,n){if(n.disableSentry)return;const t=e.createElement("script");var o,s;o=t,s={async:!0,type:"module",src:"https://static.privacy.schibsted.com/dist/index.js",fetchPriority:"low"},Object.keys(s).filter((e=>void 0!==o[e])).forEach((e=>"object"==typeof s[e]?Object.keys(s[e]).forEach((n=>o[e][n]=s[e][n])):o[e]=s[e])),e.head.appendChild(t)}W(window,navigator,s)?(console.warn("CMP: Native consent is not passed. Sourcepoint will not be initialized."),window._sp_={config:{accountId:1047,baseEndpoint:"https://cdn.privacy-mgmt.com"}}):(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)}(document),q(document,s),function(e,n){e._tcf_=x(e,n)}(window,s),s.enableEcosystemConsent?z(window,document,navigator,s).then((()=>{K()})):s.enableUserCentric?async function(e,t,s,r,c){V(e,t,s,r,c);const a=o(r,n);try{const n=await i(e);if(!j("CMP:isLoggedIn")&&!await n.isLoggedIn())return G(e,a);n.on("logout",(function(){M("CMP:isLoggedIn")})),j("CMP:isLoggedIn")||O("CMP:isLoggedIn",!0),T(r,"loggedin",!0);const t={externalParty:"sourcepoint",optionalSuffix:r.groupId},o=await n.getExternalId(t.externalParty,t.optionalSuffix),s=T(r,"enableUserCentric",!0);G(e,Object.assign({authId:o,targetingParams:s},a))}catch(n){console.error("Identity: ",n),G(e,a)}}(window,document,navigator,s,"tcf").then((()=>{K()})):(function(n,t,s,r,i){V(n,t,s,r,i),G(n,o(r,e))}(window,document,navigator,s,"tcf"),K()))}();