7 lines
88 KiB
JavaScript
7 lines
88 KiB
JavaScript
/**
|
|
* @id5io/id5-api.js
|
|
* @version v1.0.76
|
|
* @link https://id5.io/
|
|
* @license Apache-2.0
|
|
*/
|
|
!function(){"use strict";function i(t,e){var r,i=Object.keys(t);return Object.getOwnPropertySymbols&&(r=Object.getOwnPropertySymbols(t),e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,r)),i}function _(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?i(Object(r),!0).forEach(function(e){d(t,e,r[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):i(Object(r)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))})}return t}function c(e,t,r,i,s,n,o){try{var a=e[n](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(i,s)}function f(a){return function(){var e=this,o=arguments;return new Promise(function(t,r){var i=a.apply(e,o);function s(e){c(i,t,r,s,n,"next",e)}function n(e){c(i,t,r,s,n,"throw",e)}s(void 0)})}}function d(e,t,r){return(t=function(e){e=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0===r)return("string"===t?String:Number)(e);t=r.call(e,t||"default");if("object"!=typeof t)return t;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return"symbol"==typeof e?e:String(e)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function h(){return(h=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r,i=arguments[t];for(r in i)Object.prototype.hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e}).apply(this,arguments)}function t(e,t){if(null==e)return{};var r,i=function(e,t){if(null==e)return{};for(var r,i={},s=Object.keys(e),n=0;n<s.length;n++)r=s[n],0<=t.indexOf(r)||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols)for(var s=Object.getOwnPropertySymbols(e),n=0;n<s.length;n++)r=s[n],0<=t.indexOf(r)||Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r]);return i}function l(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var i,s,n,o,a=[],c=!0,d=!1;try{if(n=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(i=n.call(r)).done)&&(a.push(i.value),a.length!==t);c=!0);}catch(e){d=!0,s=e}finally{try{if(!c&&null!=r.return&&(o=r.return(),Object(o)!==o))return}finally{if(d)throw s}}return a}}(e,t)||a(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(e,t){if(e){if("string"==typeof e)return s(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Map"===(r="Object"===r&&e.constructor?e.constructor.name:r)||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?s(e,t):void 0}}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=new Array(t);r<t;r++)i[r]=e[r];return i}function m(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=a(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var i=0,t=function(){};return{s:t,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:t}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,n=!0,o=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return n=e.done,e},e:function(e){o=!0,s=e},f:function(){try{n||null==r.return||r.return()}finally{if(o)throw s}}}}function r(e,t,r){return function(e,t){if(e!==t)throw new TypeError("Private static access of wrong provenance")}(e,t),r}class e{debug(){}info(){}warn(){}error(){}}const u=new e,n="*",o=void 0;class g{constructor(e,t,r,i,s,n){var o=6<arguments.length&&void 0!==arguments[6]?arguments[6]:void 0;d(this,"_isId5Message",!0),d(this,"id",void 0),d(this,"timestamp",void 0),d(this,"type",void 0),d(this,"src",void 0),d(this,"dst",void 0),d(this,"request",void 0),d(this,"payload",void 0),this.id=i,this.timestamp=e,this.src=t,this.dst=r,this.type=n,this.request=o,this.payload=s}}class p{constructor(e){d(this,"_senderId",void 0),d(this,"_messageSeqNb",0),this._senderId=e,this._messageSeqNb=0}createBroadcastMessage(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:e.constructor.name;return new g(Date.now(),this._senderId,o,++this._messageSeqNb,e,t||e.constructor.name)}createResponse(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:t.constructor.name;return new g(Date.now(),this._senderId,e.src,++this._messageSeqNb,t,r||t.constructor.name,e)}createUnicastMessage(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:t.constructor.name;return new g(Date.now(),this._senderId,e,++this._messageSeqNb,t,r||t.constructor.name)}}class v{constructor(e){var t=1<arguments.length&&void 0!==arguments[1]&&arguments[1],r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:void 0;d(this,"instance",void 0),d(this,"instanceState",void 0),d(this,"isResponse",void 0),this.instance=e,this.instanceState=r,this.isResponse=t}}d(v,"TYPE","HelloMessage");const I=Object.freeze({LEADER:"leader",FOLLOWER:"follower",STORAGE:"storage"});class y{constructor(e,t,r){d(this,"target",void 0),d(this,"methodName",void 0),d(this,"methodArguments",void 0),this.target=e,this.methodName=t,this.methodArguments=r}}d(y,"TYPE","RemoteMethodCallMessage");class C{constructor(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:u;d(this,"_targets",{}),d(this,"_log",void 0),this._log=e}registerTarget(e,t){return this._targets[e]=t,this}_handle(t){const e=this._targets[t.target];if(e)try{e[t.methodName](...t.methodArguments)}catch(e){this._log.error("Error while handling method call ",t,e)}}}class w{constructor(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:u,i=3<arguments.length?arguments[3]:void 0;d(this,"_id",void 0),d(this,"_messageFactory",void 0),d(this,"_log",void 0),d(this,"_metrics",void 0),d(this,"_onMessageCallBackFunction",void 0),this._id=e,this._messageFactory=new p(this._id),this._log=r,this._window=t,this._handlers={},this._metrics=i,this._register()}_register(){const s=this;s._abortController="undefined"!=typeof AbortController?new AbortController:void 0;var e=null===(e=s._abortController)||void 0===e?void 0:e.signal;s._window.addEventListener("message",r=>{let i=r.data;if(void 0!==r.data&&r.data._isId5Message&&r.data.src!==s._id&&(void 0===r.data.dst||r.data.dst===s._id))try{[n,i.type].forEach(e=>{let t=s._handlers[e];t&&t.forEach(e=>e(i,r.source))})}catch(e){s._log.error("Error while handling message",i,e)}},{capture:!1,signal:e})}unregister(){this._abortController&&this._abortController.abort()}onAnyMessage(e){return this.onMessage(n,e)}onMessage(e,t){const r=this._handlers[e];return r?r.push(t):this._handlers[e]=[t],this}broadcastMessage(e,t){this._log.debug("Broadcasting message",t,e),this._postMessage(this._messageFactory.createBroadcastMessage(e,t))}sendResponseMessage(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:t.constructor.name;this._log.debug("Sending response message",e,r,t),this._postMessage(this._messageFactory.createResponse(e,t,r))}unicastMessage(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:t.constructor.name;this._log.debug("Sending message to",e,r,t),this._postMessage(this._messageFactory.createUnicastMessage(e,t,r))}_postToWindow(e,t){try{e.postMessage(t,"*")}catch(e){this._log.error("Could not post message to window",e)}}_postMessage(i){let s=this;(function t(e){try{s._postToWindow(e,i);var r=e.frames;if(r)for(let e=0;e<r.length;e++)t(r[e])}catch(e){s._log.error("Could not broadcast message",e)}})(s._window.top)}callProxyMethod(e,t,r,i){this._log.info("Calling ProxyMethodCall",{target:t,name:r,args:i}),this.unicastMessage(e,new y(t,r,i),y.TYPE)}onProxyMethodCall(t){return this.onMessage(y.TYPE,e=>void 0===e.dst?(this._countInvalidMessage(e,"no-destination-proxy"),void this._log.error("Received invalid RemoteMethodCallMessage message",JSON.stringify(e),"Ignoring it....")):void t._handle(h(new y,e.payload)))}_countInvalidMessage(e,t){var r,i=e=>null!=e;void 0!==(null===(r=this._metrics)||void 0===r?void 0:r.instanceInvalidMsgCounter)&&this._metrics.instanceInvalidMsgCounter({reason:t,hasDestination:i(e.dst),hasSource:i(e.src),hasPayload:i(e.payload),hasRequest:i(e.request),hasTimestamp:i(e.timestamp)}).inc()}}function S(e,t){var r="^\\d+(\\.\\d+(\\.\\d+){0,1}){0,1}$";if(e.match(r)&&t.match(r)){var i=e.split("."),s=t.split("."),r=e=>parseInt(e)||0,e=(e,t)=>{t=e-t;return 0==t?0:t<0?-1:1},t=e(r(i[0]),r(s[0]));if(0!==t)return t;t=e(r(i[1]),r(s[1]));return 0===t?e(r(i[2]),r(s[2])):t}}const D="Array",b="String",E="Function",P=Object.prototype.toString;function T(e,t){return P.call(e)==="[object "+t+"]"}function A(e){return T(e,E)}function O(e){return T(e,b)}function R(e){return T(e,D)}function N(e){return T(e,"Number")}function x(e){return T(e,"Object")}function L(e){return void 0!==e}function F(t,r){if(!function(e){if(!e)return 1;if(R(e)||O(e))return!(0<e.length);for(var t in e)if(hasOwnProperty.call(e,t))return;return 1}(t)){if(A(t.forEach))return t.forEach(r,this);let e=0;var i=t.length;if(0<i)for(;e<i;e++)r(t[e],e,t);else for(e in t)hasOwnProperty.call(t,e)&&r.call(this,t[e],e)}}function U(e,t){let r=document.createElement("a");t&&"noDecodeWholeURL"in t&&t.noDecodeWholeURL?r.href=e:r.href=decodeURIComponent(e);t=t&&"decodeSearchAsString"in t&&t.decodeSearchAsString;return{href:r.href,protocol:(r.protocol||"").replace(/:$/,""),hostname:r.hostname,port:+r.port,pathname:r.pathname.replace(/^(?!\/)/,"/"),search:t?r.search:(t=r.search||"")?t.replace(/^\?/,"").split("&").reduce((e,t)=>{let r=t.split("="),i=l(r,2),s=i[0],n=i[1];return/\[\]$/.test(s)?(s=s.replace("[]",""),e[s]=e[s]||[],e[s].push(n)):e[s]=n||"",e},{}):{},hash:(r.hash||"").replace(/^#/,""),host:r.host||window.location.host}}function V(e){return(e.protocol||"http")+"://"+(e.host||e.hostname+(e.port?":".concat(e.port):""))+(e.pathname||"")+(e.search?"?".concat((r=e.search||"",Object.keys(r).map(t=>Array.isArray(r[t])?r[t].map(e=>"".concat(t,"[]=").concat(e)).join("&"):"".concat(t,"=").concat(r[t])).join("&"))):"")+(e.hash?"#".concat(e.hash):"");var r}function G(r,e){function i(e,t){if(A(Math.imul))return Math.imul(e,t);var r=(4194303&e)*(t|=0);return 4290772992&e&&(r+=(4290772992&e)*t|0),0|r}e=1<arguments.length&&void 0!==e?e:0;let s=3735928559^e,n=1103547991^e;for(let e=0,t;e<r.length;e++)t=r.charCodeAt(e),s=i(s^t,2654435761),n=i(n^t,1597334677);return s=i(s^s>>>16,2246822507)^i(n^n>>>13,3266489909),n=i(n^n>>>16,2246822507)^i(s^s>>>13,3266489909),(4294967296*(2097151&n)+(s>>>0)).toString()}const M=Object.freeze({cmp:"cmp",partner:"partner",prebid:"prebid"}),j=["localStoragePurposeConsent","ccpaString"],k=Object.freeze({NONE:"none",TCF_V1:"TCFv1",TCF_V2:"TCFv2",USP_V1:"USPv1",ID5_ALLOWED_VENDORS:"ID5",PREBID:"PBJS",GPP_V1_0:"GPPv1.0",GPP_V1_1:"GPPv1.1"});class W{constructor(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:void 0,t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:void 0,r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:void 0,i=3<arguments.length&&void 0!==arguments[3]?arguments[3]:void 0,s=4<arguments.length&&void 0!==arguments[4]?arguments[4]:void 0;d(this,"version",void 0),d(this,"localStoragePurposeConsent",void 0),d(this,"applicableSections",void 0),d(this,"gppString",void 0),d(this,"vendorsConsentForId5Granted",void 0),this.version=e,this.localStoragePurposeConsent=t,this.applicableSections=i,this.gppString=s,this.vendorsConsentForId5Granted=r}isGranted(){return!this.applicableSections.includes(2)||!0===this.localStoragePurposeConsent&&!1!==this.vendorsConsentForId5Granted}}class H{constructor(){d(this,"apiTypes",void 0),d(this,"gdprApplies",void 0),d(this,"consentString",void 0),d(this,"localStoragePurposeConsent",void 0),d(this,"allowedVendors",void 0),d(this,"ccpaString",void 0),d(this,"forcedGrantByConfig",void 0),d(this,"gppData",void 0),d(this,"source",void 0),d(this,"vendorsConsentForId5Granted",void 0),this.apiTypes=[],this.gdprApplies=!1,this.consentString=void 0,this.localStoragePurposeConsent=!1,this.ccpaString=void 0,this.allowedVendors=void 0,this.forcedGrantByConfig=!1,this.gppData=void 0}localStorageGrant(){return!0===this.forcedGrantByConfig?new J(!0,q.FORCE_ALLOWED_BY_CONFIG):0===this.apiTypes.length?new J(!0,q.PROVISIONAL):this._getLocalStorageGrantFromApi()}_getLocalStorageGrantFromApi(){const e=this.apiTypes,t={};var r={};e.includes(k.TCF_V1)&&(t[k.TCF_V1]=this._isGranted(),this._addToDebugInfo(k.TCF_V1,this,r)),e.includes(k.TCF_V2)&&(t[k.TCF_V2]=this._isGranted(),this._addToDebugInfo(k.TCF_V2,this,r)),e.includes(k.ID5_ALLOWED_VENDORS)&&(t[k.ID5_ALLOWED_VENDORS]=this.allowedVendors.includes("131")),e.includes(k.USP_V1)&&(t[k.USP_V1]=!0),e.includes(k.GPP_V1_0)&&(t[k.GPP_V1_0]=this.gppData.isGranted(),this._addToDebugInfo(k.GPP_V1_0,this.gppData,r)),e.includes(k.GPP_V1_1)&&(t[k.GPP_V1_1]=this.gppData.isGranted(),this._addToDebugInfo(k.GPP_V1_1,this.gppData,r));var i=Object.keys(t).map(e=>t[e]).reduce((e,t)=>e&&t,!0);return new J(i,q.CONSENT_API,t,r)}_addToDebugInfo(e,t,r){return void 0!==t.localStoragePurposeConsent&&(r[e+"-localStoragePurposeConsent"]=t.localStoragePurposeConsent),void 0!==t.vendorsConsentForId5Granted&&(r[e+"-vendorsConsentForId5Granted"]=t.vendorsConsentForId5Granted),r}_isGranted(){return!1===this.gdprApplies||!0===this.localStoragePurposeConsent&&!1!==this.vendorsConsentForId5Granted}hashCode(){this.localStoragePurposeConsent,this.ccpaString;var e=t(this,j);return G(JSON.stringify(e))}static createFrom(e){const t=h(new H,e);return L(t.api)&&(t.apiTypes=function(e){var t=e.api;if(t===k.NONE)return[];if(t!==k.PREBID)return[t];{const r=[];return(L(e.gdprApplies)||L(e.consentString))&&r.push(k.TCF_V2),L(e.ccpaString)&&r.push(k.USP_V1),L(e.gppData)&&L(e.gppData.version)&&r.push(e.gppData.version),r}}(e),t.api=void 0),x(t.gppData)&&(t.gppData=h(new W,t.gppData)),t}getApiTypeData(e){if(this.apiTypes.includes(e)){if(e===k.USP_V1)return{ccpaString:this.ccpaString};if(e===k.TCF_V2)return{consentString:this.consentString,gdprApplies:this.gdprApplies,localStoragePurposeConsent:this.localStoragePurposeConsent};if(e===k.GPP_V1_1||e===k.GPP_V1_0)return this.gppData;if(e===k.ID5_ALLOWED_VENDORS)return{allowedVendors:this.allowedVendors}}}}const q=Object.freeze({FORCE_ALLOWED_BY_CONFIG:"force_allowed_by_config",ID5_CONSENT:"id5_consent",PROVISIONAL:"provisional",JURISDICTION:"jurisdiction",CONSENT_API:"consent_api"});class J{constructor(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},i=3<arguments.length&&void 0!==arguments[3]?arguments[3]:{};d(this,"allowed",!1),d(this,"grantType",q.NONE),d(this,"api",{}),d(this,"_debugInfo",{}),this.allowed=e,this.grantType=t,this.api=r,this._debugInfo=i}isDefinitivelyAllowed(){return this.allowed&&this.grantType!==q.PROVISIONAL}}var B=Object.freeze({STORAGE_CONFIG:{ID5:{name:"id5id",expiresDays:90},ID5_V2:{name:"id5id_v2",expiresDays:15},LAST:{name:"id5id_last",expiresDays:90},CONSENT_DATA:{name:"id5id_cached_consent_data",expiresDays:30},PRIVACY:{name:"id5id_privacy",expiresDays:30},EXTENSIONS:{name:"id5id_extensions",expiresDays:8/24}},LEGACY_COOKIE_NAMES:["id5.1st","id5id.1st"],PRIVACY:{JURISDICTIONS:{gdpr:!0,ccpa:!1,lgpd:!0,other:!1}},ID5_EIDS_SOURCE:"id5-sync.com"});class K{constructor(e,t){this.name=e,this.expiresDays=t}withNameSuffixed(){let e=this.name;for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];for(var s=0,n=r;s<n.length;s++){var o=n[s];e+="_".concat(o)}return new K(e,this.expiresDays)}}class Y{constructor(){let r=0<arguments.length&&void 0!==arguments[0]?arguments[0]:void 0;function e(e){var t=void 0!==r?Math.max(1,r):e.expiresDays;return new K(e.name,t)}var t=B.STORAGE_CONFIG;this.ID5=e(t.ID5),this.ID5_V2=e(t.ID5_V2),this.LAST=e(t.LAST),this.CONSENT_DATA=e(t.CONSENT_DATA),this.PRIVACY=e(t.PRIVACY),this.EXTENSIONS=new K(t.EXTENSIONS.name,t.EXTENSIONS.expiresDays)}}d(Y,"DEFAULT",new Y);class z{constructor(e,t){d(this,"_clientStore",void 0),d(this,"_trueLinkAdapter",void 0),this._clientStore=e,this._trueLinkAdapter=t}hasConsentChanged(e){return e&&!this._clientStore.storedConsentDataMatchesConsentData(e)}storeConsent(e){this._clientStore.putHashedConsentData(e)}incNb(e){this._clientStore.incNbV2(e,1<arguments.length&&void 0!==arguments[1]?arguments[1]:1)}updateNbs(e){var t,r=m(e);try{for(r.s();!(t=r.n()).done;){var i=l(t.value,2),s=i[0],n=i[1],o=null==n?void 0:n.nb;0<o&&this.incNb(s,-o)}}catch(e){r.e(e)}finally{r.f()}}storeResponse(e,r){this._clientStore.putResponseV1(r.getGenericResponse()),this._clientStore.setResponseDateTimeV1(new Date(r.timestamp).toUTCString());const i=new Set;e.forEach(e=>{var t=e.cacheId;i.has(t)||(e=r.getResponseFor(e.integrationId))&&(this._clientStore.storeResponseV2(t,e,r.timestamp),i.add(t))}),this._trueLinkAdapter.setPrivacy(null===(e=r.getGenericResponse())||void 0===e?void 0:e.privacy)}clearAll(e){this._clientStore.clearResponse(),this._clientStore.clearDateTime(),e.forEach(e=>{e=e.cacheId;this._clientStore.clearResponseV2(e)}),this._clientStore.clearHashedConsentData(),this._trueLinkAdapter.clearPrivacy(),this._clientStore.clearExtensions()}getCachedResponse(e){e=this._clientStore.getStoredResponseV2(e);if(e)return new X(e.response,e.responseTimestamp,e.nb)}getCachedExtensions(){return this._clientStore.getExtensions()}storeExtensions(e){var t=N(e.ttl)?e.ttl/86400:Y.DEFAULT.EXTENSIONS.expiresDays,t=new K(Y.DEFAULT.EXTENSIONS.name,t);return this._clientStore.storeExtensions(e,t)}}class X{constructor(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:0;d(this,"response",void 0),d(this,"timestamp",void 0),d(this,"nb",void 0),this.response=e,this.timestamp=t,this.nb=r}isExpired(){var e=this.getMaxAge();return!(N(e)&&0<e)||this._isOlderThanSec(e)}_isOlderThanSec(e){return this.timestamp<=0||this.getAgeSec()>e}isStale(){return!this.timestamp||this._isOlderThanSec(1209600)}isResponseComplete(){return x(this.response)&&O(this.response.universal_uid)&&O(this.response.signature)}isValid(){return this.isResponseComplete()&&!this.isStale()}getMaxAge(){var e,t;return null===(e=this.response)||void 0===e||null===(t=e.cache_control)||void 0===t?void 0:t.max_age_sec}getAgeSec(){return(Date.now()-this.timestamp)/1e3|0}}const Q="_exp";class ${constructor(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:u;d(this,"storage",void 0),d(this,"_log",void 0),this.storage=e,this._log=t}getItem(e){try{return this.storage.getItem(e)}catch(e){}}setItem(e,t){try{this.storage.setItem(e,t)}catch(e){}}removeItem(e){try{this.storage.removeItem(e)}catch(e){}}removeExpiredObjectWithPrefix(t){var r=1<arguments.length&&void 0!==arguments[1]&&arguments[1];this._log.info("Check, prefix",t);try{var i=this.storage.getKeysWithPrefix(t);let e=0;var s,n=m(i);try{for(n.s();!(s=n.n()).done;){var o,a,c=s.value;r?(this._log.info("Found",c," remove it"),this.removeItem(c)):(a=null==(o=this.getObjectWithExpiration({name:c}))?void 0:o.expireAt)&&a<Date.now()&&(this._log.info("Found expired object",c,"expiration time",a,"It will be removed"),this.removeItem(c),e+=1)}}catch(e){n.e(e)}finally{n.f()}return{all:i.length,expired:e}}catch(e){}}getItemWithExpiration(e){var t=e.name,e=this.getItem(t+Q);return!e||new Date(e).getTime()-Date.now()<=0?(this.removeItemWithExpiration({name:t}),null):this.getItem(t)}setItemWithExpiration(e,t){var r=e.name,e=e.expiresDays,e=Date.now()+864e5*e,e=new Date(e).toUTCString();this.setItem(r+Q,e),this.setItem(r,t)}removeItemWithExpiration(e){e=e.name;this.removeItem(e),this.removeItem(e+Q)}setObjectWithExpiration(e,t){var r=e.name,e=e.expiresDays,e=Date.now()+864e5*e;this.setItem(r,JSON.stringify({data:t,expireAt:e}))}getObjectWithExpiration(t){t=t.name;try{var e=JSON.parse(this.getItem(t));if(null!=e&&e.expireAt&&0<e.expireAt-Date.now())return e.data;null!=e&&e.expireAt&&this.removeItem(t)}catch(e){this._log.error("Error while getting ",t,"object from storage",e)}}updateObjectWithExpiration(e,t){var r=e.name,e=e.expiresDays;try{var i=t(this.getObjectWithExpiration({name:r}));return this.setObjectWithExpiration({name:r,expiresDays:e},i),i}catch(e){this._log.error("Error while updating object with ",r,e)}}}class Z{getItem(){}removeItem(){}setItem(){}getKeysWithPrefix(){return[]}}const ee=new Z;class te extends Z{constructor(e){var t=!(1<arguments.length&&void 0!==arguments[1])||arguments[1];super(),d(this,"_writingEnabled",void 0),d(this,"_underlying",void 0),this._writingEnabled=t;try{this._underlying=e.localStorage}catch(e){}}getItem(e){try{return this._underlying.getItem(e)}catch(e){}}removeItem(e){try{this._underlying.removeItem(e)}catch(e){}}setItem(e,t){try{this._writingEnabled&&this._underlying.setItem(e,t)}catch(e){}}getKeysWithPrefix(t){try{var r=this._underlying.length;if(this._writingEnabled){const i=[];for(let e=0;e<r;e++){const s=this._underlying.key(e);s&&s.startsWith(t)&&i.push(s)}return i}}catch(e){}}static checkIfAccessible(){var e="__id5test";try{return window.localStorage.setItem(e,e),window.localStorage.removeItem(e),!0}catch(e){return!1}}}class re{constructor(e){d(this,"_replicas",[]),d(this,"_lastKeyOperation",{}),d(this,"_primaryStorage",void 0),this._primaryStorage=e}getItem(e){return this._primaryStorage.getItem(e)}removeItem(t){this._primaryStorage.removeItem(t);var e=e=>{e.removeItem(t)};this._replicas.forEach(e),this._lastKeyOperation[t]=e}setItem(t,r){this._primaryStorage.setItem(t,r);var e=e=>{e.setItem(t,r)};this._replicas.forEach(e),this._lastKeyOperation[t]=e}addReplica(t){Object.values(this._lastKeyOperation).forEach(e=>e(t)),this._replicas.push(t)}getKeysWithPrefix(e){return this._primaryStorage.getKeysWithPrefix(e)}}const ie="undefined"!=typeof Promise&&"undefined"!=typeof fetch;class se{constructor(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:void 0;this.url=e||"https://diagnostics.id5-sync.com/measurements",this._metadata=t}publish(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:void 0;return e&&0<e.length?(e.forEach(e=>function(r){Object.keys(r).forEach(function(e){var t=r[e];t&&(t instanceof Object?r[e]=JSON.stringify(t):r[e]="".concat(t))})}(e.tags)),fetch(this.url,{method:"POST",headers:{"Content-Type":"text/plain"},mode:"no-cors",body:JSON.stringify({metadata:_(_({},this._metadata),t),measurements:e})})):Promise.resolve()}}const ne=Object.freeze({});var oe={EMPTY:ne,from:function(e){return e?e instanceof Map?Object.fromEntries(e):e:ne},toString:function(e){return Array.from(Object.entries(e),e=>{var t=l(e,2),e=t[0],t=t[1];return"".concat(e,"=").concat(t)}).sort().toString()}};const ae=Object.freeze({TIMER:"TIMER",SUMMARY:"SUMMARY",COUNTER:"COUNTER"});class ce{constructor(e,t,r){d(this,"name",void 0),d(this,"tags",void 0),d(this,"values",void 0),this.name=e,this.tags=oe.from(t),this.type=r,this.values=[]}reset(){this.values=[]}}class de extends ce{constructor(e){super(e,1<arguments.length&&void 0!==arguments[1]?arguments[1]:void 0,ae.TIMER)}startMeasurement(){try{return new le(this)}catch(e){return}}record(e){try{isNaN(e)||this.values.push({value:e,timestamp:Date.now()})}catch(e){}}recordNow(){try{var e;this.record(0|(null===(e=performance)||void 0===e?void 0:e.now()))}catch(e){}}}class le{constructor(){this.timer=0<arguments.length&&void 0!==arguments[0]?arguments[0]:void 0,this.startTime=performance.now()}record(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:void 0;try{var r=performance.now()-this.startTime|0;let e=t||this.timer;return e&&e.record(r),r}catch(e){return}}}class he extends ce{constructor(e){super(e,1<arguments.length&&void 0!==arguments[1]?arguments[1]:void 0,ae.COUNTER)}inc(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:1;try{return 0===this.values.length?this.values.push({value:e,timestamp:Date.now()}):(this.values[0].value+=e,this.values[0].timestamp=Date.now()),this.values[0].value}catch(e){}}}class ue extends ce{constructor(e){super(e,1<arguments.length&&void 0!==arguments[1]?arguments[1]:void 0,ae.SUMMARY)}record(e){try{this.values.push({value:e,timestamp:Date.now()})}catch(e){}}}class ge{has(e){return void 0!==this[e]}set(e,t){return this[e]=t,this}get(e){return this[e]}values(){return Object.entries(this).map(e=>{return l(e,2)[1]})}}function pe(){return new le}function ve(e){return{partner:e}}class _e extends class{constructor(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:void 0,t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:void 0;d(this,"_registry",void 0),d(this,"commonTags",void 0),d(this,"_scheduled",void 0),this._registry=new ge,this.commonTags=oe.from(e),this.commonPrefix=t}getOrCreate(e,t,r){var i=_(_({},t),this.commonTags),t=this.commonPrefix?this.commonPrefix+"."+e:e,e="".concat(t,"[").concat(oe.toString(i),"]");return this._registry.has(e)||this._registry.set(e,r(t,i)),this._registry.get(e)}getAllMeasurements(){return this._registry.values().map(e=>({name:e.name,type:e.type,tags:e.tags,values:e.values})).filter(function(e){return e.values&&0<e.values.length})}reset(){Array.from(this._registry.values()).forEach(e=>e.reset())}addCommonTags(e){this.commonTags=_(_({},this.commonTags),oe.from(e))}timer(e){return this.getOrCreate(e,1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},(e,t)=>new de(e,t))}counter(e){return this.getOrCreate(e,1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},(e,t)=>new he(e,t))}summary(e){return this.getOrCreate(e,1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},(e,t)=>new ue(e,t))}publish(){let t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:e=>e,r=1<arguments.length&&void 0!==arguments[1]?arguments[1]:void 0;return Promise.resolve(this.getAllMeasurements()).then(e=>t(e,r)).then(()=>this.reset())}schedulePublishAfterMsec(t,r){if(!this._scheduled){let e=this;setTimeout(()=>(e._scheduled=!1,e.publish(r,{trigger:"fixed-time",fixed_time_msec:t})),t),this._scheduled=!0}return this}schedulePublishBeforeUnload(e){const t=this,r="undefined"!=typeof AbortController?new AbortController:void 0;return r&&(r.publisher=e,addEventListener("beforeunload",()=>t.publish(e,{trigger:"beforeunload"}),{capture:!1,signal:r.signal}),this._onUnloadPublishAbortController=r),this}unregister(){const e=this._onUnloadPublishAbortController;if(e)return e.abort(),this.publish(e.publisher,{trigger:"unregister"})}}{constructor(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:void 0,i=3<arguments.length&&void 0!==arguments[3]?arguments[3]:void 0;super(_(_({source:e,version:t},ve(r)),i),"id5.api")}loadDelayTimer(){return this.timer("instance.load.delay",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}fetchCallTimer(e){return this.timer("fetch.call.time",_({status:e},1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}))}fetchFailureCallTimer(){return this.fetchCallTimer("fail",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}fetchSuccessfulCallTimer(){return this.fetchCallTimer("success",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}extensionsCallTimer(e,t){return this.timer("extensions.call.time",_({extensionType:e,status:t?"success":"fail"},2<arguments.length&&void 0!==arguments[2]?arguments[2]:{}))}consentRequestTimer(e){return this.timer("consent.request.time",_({requestType:e},1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}))}invocationCountSummary(){return this.summary("invocation.count",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}instanceCounter(e){return this.counter("instance.count",_({instanceId:e},1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}))}instanceUniqueDomainsCounter(e){return this.counter("instance.domains.count",_({instanceId:e},1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}))}instanceUniqWindowsCounter(e){return this.counter("instance.windows.count",_({instanceId:e},1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}))}instanceUniqPartnersCounter(e){return this.counter("instance.partners.count",_({instanceId:e},1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}))}instanceJoinDelayTimer(){return this.timer("instance.join.delay.time",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}instanceLateJoinCounter(e){return this.counter("instance.lateJoin.count",_({instanceId:e},1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}))}instanceLateJoinDelayTimer(){return this.timer("instance.lateJoin.delay",_({},0<arguments.length&&void 0!==arguments[0]?arguments[0]:{}))}instanceLastJoinDelayTimer(){return this.timer("instance.lastJoin.delay",_({},0<arguments.length&&void 0!==arguments[0]?arguments[0]:{}))}instanceMsgDeliveryTimer(){return this.timer("instance.message.delivery.time",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}instanceInvalidMsgCounter(){return this.counter("instance.message.invalid.count",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}userIdProvisioningDelayTimer(e){return this.timer("userid.provisioning.delay",_({cachedResponseUsed:e},1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}))}userIdNotificationDeliveryDelayTimer(){return this.timer("userid.provisioning.delivery.delay",_({},0<arguments.length&&void 0!==arguments[0]?arguments[0]:{}))}userIdProvisioningDuplicateTimer(){return this.timer("userid.provisioning.duplicate",_({},0<arguments.length&&void 0!==arguments[0]?arguments[0]:{}))}cachedUserIdAge(){return this.summary("userid.cached.age",_({},0<arguments.length&&void 0!==arguments[0]?arguments[0]:{}))}consentChangeCounter(){return this.counter("leader.consent.change.count",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}consentIgnoreCounter(){return this.counter("leader.consent.ignore.count",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}storageAllKeysCounter(){return this.summary("storage.keys.all.count",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}storageExpiredKeysCounter(){return this.summary("storage.keys.expired.count",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}instanceSurvivalTime(){return this.timer("instance.survival.time",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}localStorageGrantCounter(){return this.counter("consent.lsg.count",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}consentDiscrepancyCounter(){return this.counter("consent.discrepancy.count",0<arguments.length&&void 0!==arguments[0]?arguments[0]:{})}refreshCallCounter(e){return this.counter("refresh.call.count",_({target:e},1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}))}}class fe{constructor(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:Date.now();d(this,"timestamp",void 0),d(this,"response",void 0),this.response=e,this.timestamp=t}getGenericResponse(){return this.response.generic}getResponseFor(e){var t,r;if(null!==(t=this.response)&&void 0!==t&&t.responses&&null!==(r=this.response)&&void 0!==r&&r.responses[e])return _(_({},this.response.generic),this.response.responses[e])}}class me{constructor(e,t,r){d(this,"_extensionsProvider",void 0),d(this,"_metrics",void 0),d(this,"_log",void 0),this._extensionsProvider=r,this._metrics=e,this._log=t}fetchId(e,d,l){return this._extensionsProvider.gather(e).then(n=>{const s=e.map(e=>{const t=e.cacheData;var r=null===t||void 0===t||null===(s=t.response)||void 0===s?void 0:s.signature,i=null===t||void 0===t?void 0:t.nb,s=null===t||void 0===t?void 0:t.getMaxAge();return this._createRequest(d,e,r,i,s,n,l)}),o=this._log,a=this._metrics,c=this;return new Promise((t,r)=>{const i=pe();var e="".concat("https://id5-sync.com").concat("/gm/v3");o.info("Fetching ID5 ID from:",e,s),function(i,s,n,o,e){o=3<arguments.length&&void 0!==o?o:{};let a=4<arguments.length&&void 0!==e?e:u;try{let r;var c,d=o.method||(n?"POST":"GET");let e=document.createElement("a");e.href=i;let t="object"==typeof s&&null!==s?s:{success:function(){a.info("ajax","xhr success")},error:function(e){a.error("ajax","xhr error",null,e)}};"function"==typeof s&&(t.success=s),r=new window.XMLHttpRequest,r.onreadystatechange=function(){var e;4===r.readyState&&(200<=(e=r.status)&&e<300||304===e?t.success(r.responseText,r):t.error(r.statusText,r))},r.ontimeout=function(){a.error("ajax","xhr timeout after ",r.timeout,"ms")},"GET"===d&&n&&(h((c=U(i,o)).search,n),i=V(c)),r.open(d,i,!0),o.withCredentials&&(r.withCredentials=!0),F(o.customHeaders,(e,t)=>{r.setRequestHeader(t,e)}),o.preflight&&r.setRequestHeader("X-Requested-With","XMLHttpRequest"),r.setRequestHeader("Content-Type",o.contentType||"text/plain"),"POST"===d&&n?r.send(n):r.send()}catch(e){a.error("ajax","xhr construction",e)}}(e,{success:function(e){o.info("Success at fetch call:",e),i.record(null===a||void 0===a?void 0:a.fetchSuccessfulCallTimer());try{t(new fe(c._validateResponse(e)))}catch(e){r(e)}},error:function(e){i.record(null===a||void 0===a?void 0:a.fetchFailureCallTimer()),r(e)}},JSON.stringify({requests:s}),{method:"POST",withCredentials:!0},o)})})}_validateResponse(e){if(!e||!O(e)||e.length<1)throw new Error('Empty fetch response from ID5 servers: "'.concat(e,'"'));var t=JSON.parse(e);if(!x(t.generic))throw new Error("Server response failed to validate: ".concat(e));return this._log.info("Valid json response from ID5 received",t),t}_createRequest(e,r,t,i,s,n,o){this._log.info("Create request data for",{fetchIdData:r,consentData:e,signature:t,nbValue:i,refreshInSecondUsed:s,extensions:n});var a=r.partnerId;const c={requestId:r.integrationId,requestCount:r.requestCount,role:r.role,cacheId:r.cacheId,refresh:r.refresh,source:r.source,sourceVersion:r.sourceVersion,partner:a,v:r.originVersion,o:r.origin,tml:null===(a=r.refererInfo)||void 0===a?void 0:a.topmostLocation,ref:null===(a=r.refererInfo)||void 0===a?void 0:a.ref,cu:null===(a=r.refererInfo)||void 0===a?void 0:a.canonicalUrl,u:(null===(a=r.refererInfo)||void 0===a?void 0:a.stack[0])||window.location.href,top:null!==(a=r.refererInfo)&&void 0!==a&&a.reachedTop?1:0,localStorage:!0===o?1:0,nbPage:i,id5cdn:r.isUsingCdn,ua:window.navigator.userAgent,att:r.att};i=e.gdprApplies;L(i)&&(c.gdpr=i?1:0);i=e.consentString;L(i)&&(c.gdpr_consent=i),L(r.allowedVendors)?c.allowed_vendors=r.allowedVendors:L(e.allowedVendors)&&(c.allowed_vendors=e.allowedVendors),L(e.gppData)&&(c.gpp_string=e.gppData.gppString,c.gpp_sid=e.gppData.applicableSections.join(",")),L(t)&&(c.s=t);t=r.uaHints;L(t)&&(c.ua_hints=t),L(e.ccpaString)&&""!==e.ccpaString&&(c.us_privacy=e.ccpaString),function(e){var t=Object.keys(e);let r=t.length,i=new Array(r);for(;r--;)i[r]=[t[r],e[t[r]]];return i}({pd:"pd",partnerUserId:"puid",provider:"provider",segments:"segments",trueLink:"true_link"}).forEach(e=>{var t=l(e,2),e=t[0],t=t[1];L(r[e])&&(c[t]=r[e])});e=r.abTesting;e&&!0===e.enabled&&(c.ab_testing={enabled:!0,control_group_pct:e.controlGroupPct});e=r.invalidSegmentsCount;return e&&0<e&&(c._invalid_segments=e),r.trace&&(c._trace=!0),c.provided_options={refresh_in_seconds:r.providedRefreshInSeconds},c.used_refresh_in_seconds=s,c.extensions=n,c}}const Ie=Object.freeze({CONSENT_UPDATED:"consent_updated",USER_ID_READY:"user_id_ready",CASCADE_NEEDED:"fire_sync_pixel",USER_ID_FETCH_CANCELED:"user_id_fetch_canceled",USER_ID_FETCH_FAILED:"user_id_fetch_failed"}),ye=Object.freeze({ID5_MESSAGE_RECEIVED:"message",ID5_INSTANCE_JOINED:"instance-joined",ID5_LEADER_ELECTED:"leader-elected"}),Ce=Object.freeze([...Object.values(ye),...Object.values(Ie)]);class we{constructor(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:u;d(this,"_handlers",void 0),d(this,"_log",void 0),this._log=e,this._handlers={}}_dispatch(t){var e=this._handlers[t];if(e){for(var r=arguments.length,i=new Array(1<r?r-1:0),s=1;s<r;s++)i[s-1]=arguments[s];var n,o=m(e);try{for(o.s();!(n=o.n()).done;){const a=n.value;try{a(...i)}catch(e){this._log.error("Event ".concat(t," handler execution failed."),e)}}}catch(e){o.e(e)}finally{o.f()}}}emit(e){if(void 0!==e&&Ce.includes(e)){for(var t=arguments.length,r=new Array(1<t?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];this._dispatch(e,...r)}else this._log.warn("Unsupported event",e)}on(e,t){void 0!==e&&Ce.includes(e)?(this._handlers[e]||(this._handlers[e]=[]),this._handlers[e].push(t)):this._log.warn("Unsupported event",e)}}const Se=Object.freeze({DIRECT_METHOD:"direct_method",POST_MESSAGE:"post_message"});class De{constructor(e,t,r){var i=3<arguments.length&&void 0!==arguments[3]?arguments[3]:u;d(this,"_instanceProperties",void 0),d(this,"_log",void 0),d(this,"callType",void 0),d(this,"_instanceWindow",void 0),this._instanceWindow=t,this._instanceProperties=r,this._log=i,this.callType=e}getId(){return this._instanceProperties.id}getFetchIdData(){return this._instanceProperties.fetchIdData}updateFetchIdData(e){h(this._instanceProperties.fetchIdData,e)}getCacheId(){var e=this._instanceProperties.fetchIdData,e={partnerId:e.partnerId,att:e.att,pd:e.pd,provider:e.provider,abTesting:e.abTesting,segments:JSON.stringify(e.segments),providedRefresh:e.providedRefreshInSeconds,trueLink:null===(e=e.trueLink)||void 0===e?void 0:e.id};return G(JSON.stringify(e))}getDeclaredConsentSource(){return this._instanceProperties.fetchIdData.consentSource||M.cmp}getSourceVersion(){return this._instanceProperties.sourceVersion}getSource(){return this._instanceProperties.source}notifyUidReady(){}notifyFetchUidCanceled(){}notifyCascadeNeeded(){}canDoCascade(){return!0===this._instanceProperties.canDoCascade}getStorage(){return ee}getWindow(){return this._instanceWindow}}class be extends De{constructor(e,t,r){var i=3<arguments.length&&void 0!==arguments[3]?arguments[3]:u,s=4<arguments.length?arguments[4]:void 0;super(Se.DIRECT_METHOD,e,t,i),d(this,"_dispatcher",void 0),d(this,"_provisionedUids",void 0),d(this,"_metrics",void 0),this._dispatcher=r,this._metrics=s,this._provisionedUids=new Map}notifyUidReady(e,t){var r,i=null==e||null===(r=e.responseObj)||void 0===r?void 0:r.universal_uid;i&&(this._provisionedUids.has(i)?(r=this._provisionedUids.get(i),this._metrics.userIdProvisioningDuplicateTimer({provisioner:t.provisioner,firstProvisioner:r.provisioner}).record(performance.now()-r.time)):(this._provisionedUids.set(i,{provisioner:t.provisioner,time:performance.now()}),this._dispatcher.emit(Ie.USER_ID_READY,e,t)))}notifyFetchUidCanceled(e){this._dispatcher.emit(Ie.USER_ID_FETCH_CANCELED,e)}notifyCascadeNeeded(e){this._dispatcher.emit(Ie.CASCADE_NEEDED,e)}}class Ee extends Z{constructor(e,t){super(),d(this,"_messenger",void 0),d(this,"_destinationId",void 0),this._messanger=e,this._destinationId=t}getItem(){}removeItem(e){this._remoteCall("removeItem",[e])}setItem(e,t){this._remoteCall("setItem",[e,t])}_remoteCall(e,t){this._messanger.callProxyMethod(this._destinationId,I.STORAGE,e,t)}}class Pe extends De{constructor(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:u;super(Se.POST_MESSAGE,e.getWindow(),e.properties,r),d(this,"_messenger",void 0),this._messenger=t}_callProxy(e,t){this._messenger.callProxyMethod(this.getId(),I.FOLLOWER,e,t)}notifyUidReady(e,t){this._callProxy("notifyUidReady",[e,t])}notifyFetchUidCanceled(e){this._callProxy("notifyFetchUidCanceled",[e])}notifyCascadeNeeded(e){this._callProxy("notifyCascadeNeeded",[e])}getStorage(){return new Ee(this._messenger,this.getId())}}class Te{constructor(e,t,r,i){d(this,"_store",void 0),d(this,"_log",void 0),d(this,"_provisioner",void 0),d(this,"_meter",void 0),this._provisioner=e,this._store=t,this._log=r,this._meter=i}provisionFromCache(t){var r=1<arguments.length&&void 0!==arguments[1]?arguments[1]:void 0;try{const o=this._log;var i=t.getCacheId();const a=this._store.getCachedResponse(i);var s,n=!a||!a.isValid()||a.isExpired();let e=!1;return a&&(s=a.getAgeSec(),this._meter.cachedUserIdAge({expired:a.isExpired(),valid:a.isValid(),provisioner:this._provisioner,maxAge:a.getMaxAge()}).record(isNaN(s)?0:s)),a&&a.isValid()?(o.info("Found valid cached response for instance ",JSON.stringify({id:t.getId(),cacheId:t.getCacheId(),provisioner:this._provisioner,responseFromCache:a})),t.notifyUidReady({timestamp:a.timestamp,responseObj:a.response,isFromCache:!0,willBeRefreshed:!!n},{timestamp:Date.now(),provisioner:this._provisioner,tags:_({callType:t.callType},r)}),e=!0):o.info("Couldn't find response for cacheId",t.getCacheId()),{cacheId:i,responseFromCache:a,refreshRequired:n,provisioned:e}}catch(e){return this._log.error("Cached UserId provisioning failure",e),{refreshRequired:!0,provisioned:!1}}}}class Ae{constructor(){var e=0<arguments.length&&void 0!==arguments[0]&&arguments[0],t=1<arguments.length&&void 0!==arguments[1]&&arguments[1];d(this,"lateJoiner",!1),d(this,"uniqueLateJoiner",!1),this.lateJoiner=e,this.uniqueLateJoiner=t}}class Oe{updateConsent(){}updateFetchIdData(){}refreshUid(){}addFollower(){}getProperties(){}}class Re extends Oe{constructor(e,t,r,i,s,n){var o=6<arguments.length&&void 0!==arguments[6]?arguments[6]:u,a=7<arguments.length?arguments[7]:void 0;super(),d(this,"_followers",void 0),d(this,"_followersRequests",{}),d(this,"_refreshRequired",{}),d(this,"_fetcher",void 0),d(this,"_log",void 0),d(this,"_consentManager",void 0),d(this,"_inProgressFetch",void 0),d(this,"_queuedRefreshArgs",void 0),d(this,"_lastConsentDataSet",void 0),d(this,"_metrics",void 0),d(this,"_leaderStorage",void 0),d(this,"_store",void 0),this._followers=[],this._fetcher=a,this._properties=t,this._consentManager=s,this._metrics=n,this._window=e,this._leaderStorage=r,this._log=o,this._store=i,this._firstFetchTriggered=!1,this._cachedIdProvider=new Te("leader",this._store,this._log,this._metrics)}_handleRefreshResult(e,t,r,i){const s=this._log,n=this._consentManager,o=this._store;if(void 0!==i){var a;n.setStoredPrivacy(null===(a=i.getGenericResponse())||void 0===a?void 0:a.privacy);const p=n.localStorageGrant("fetcher-after-response");p.isDefinitivelyAllowed()?(s.info("Storing ID and request hashes in cache"),o.updateNbs(t),o.storeResponse(e,i)):(s.info("Cannot use local storage to cache ID",p),o.clearAll(e));var c,d=m(e);try{for(d.s();!(c=d.n()).done;){var l=c.value.integrationId;this._followersRequests[l]=(this._followersRequests[l]||0)+1}}catch(e){d.e(e)}finally{d.f()}const v=[];var h,u=m(this._followers);try{for(u.s();!(h=u.n()).done;){const _=h.value;var g=i.getResponseFor(_.getId());void 0!==g&&(this._log.debug("Notify uid ready.","Follower:",_.getId(),"Uid:",g),this._refreshRequired[_.getId()]=!1,this._notifyUidReady(_,{timestamp:i.timestamp,responseObj:g,isFromCache:!1}),!0===g.cascade_needed&&v.push(_.getId()))}}catch(e){u.e(e)}finally{u.f()}void 0!==r&&0<v.length&&this._consentManager.localStorageGrant("leader-before-cascade").isDefinitivelyAllowed()&&this._handleCascade(v,i,r)}}_notifyUidReady(e,t){var r={timestamp:Date.now(),provisioner:"leader",tags:{callType:e.callType}};e.notifyUidReady(t,r)}_handleCascade(e,t,r){var i,s=this._followers.filter(t=>void 0!==e.find(e=>t.getId()===e)&&t.canDoCascade()).sort((e,t)=>{function r(e){var t;return(null===(e=e.getFetchIdData().refererInfo)||void 0===e||null===(t=e.stack)||void 0===t?void 0:t.length)||Number.MAX_SAFE_INTEGER}return r(e)-r(t)});if(0<s.length){const n=s[0];n.notifyCascadeNeeded({partnerId:n.getFetchIdData().partnerId,userId:t.getResponseFor(n.getId()).universal_uid,gdprApplies:r.gdprApplies,consentString:r.consentString,gppString:null===(t=r.gppData)||void 0===t?void 0:t.gppString,gppSid:null===(r=r.gppData)||void 0===r||null===(i=r.applicableSections)||void 0===i?void 0:i.join(",")})}else this._log.error("Couldn't find cascade eligible follower")}_handleCancel(e){var t,r=m(this._followers);try{for(r.s();!(t=r.n()).done;){const i=t.value;i.notifyFetchUidCanceled({reason:e})}}catch(e){r.e(e)}finally{r.f()}}_getId(){let n=0<arguments.length&&void 0!==arguments[0]&&arguments[0];const o=this._log;this._waitForConsent().then(t=>{const e=this._consentManager.localStorageGrant("fetch-before-request");if(o.info("Local storage grant",e),e.allowed){var r=this._store.hasConsentChanged(t);e.isDefinitivelyAllowed()&&this._store.storeConsent(t);var i=te.checkIfAccessible();const c=new Map;let a=n;const s=this._followers.map(e=>{var t=e.getId(),r=(this._followersRequests[t]||0)+1,i=this._properties.id,s=!0===this._refreshRequired[e.getId()];a=a||s;var n,o=e.getCacheId();return c.has(o)||(n=this._store.getCachedResponse(o))&&c.set(o,n),_(_({},e.getFetchIdData()),{},{integrationId:t,requestCount:r,refresh:s,role:i===e.getId()?"leader":"follower",cacheId:o,cacheData:c.get(o),sourceVersion:e.getSourceVersion(),source:e.getSource()})});r||a?(o.info("Decided to fetch a fresh ID5 ID",{consentHasChanged:r,shouldRefresh:a}),o.info("Fetching ID5 ID (forceFetch:".concat(n,")")),this._inProgressFetch=!0,this._firstFetchTriggered=!0,this._fetcher.fetchId(s,t,i).then(e=>{this._handleRefreshResult(s,c,t,e),this._handleFetchCompleted()}).catch(e=>{this._handleFailed(e),this._handleFetchCompleted()})):(o.info("Not decided to refresh ID5 ID",{consentHasChanged:r,shouldRefresh:a}),this._handleFetchCompleted())}else o.info("No legal basis to use ID5",t),this._store.clearAll(this._followers.map(e=>({cacheId:e.getCacheId()}))),this._handleCancel("No legal basis to use ID5")})}_waitForConsent(){const t=this._log,e=this._consentManager,r=this._metrics;t.info("Waiting for consent");const i=r.timer("fetch.consent.wait.time");return e.getConsentData().then(e=>(t.info("Consent received",e),i&&i.recordNow(),e))}start(){!0!==this._started&&(this._getId(!1),this._started=!0)}refreshUid(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};let t=1<arguments.length?arguments[1]:void 0;var r=!0===e.forceFetch;t&&(r?this._refreshRequired[t]=!0:(r=this._followers.find(e=>e.getId()===t))&&this._provisionFromCache(r)),this._metrics.refreshCallCounter("leader",{overwrites:void 0===this._queuedRefreshArgs}).inc(),this._callRefresh(e,t)}_callRefresh(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t=1<arguments.length?arguments[1]:void 0;this._inProgressFetch?this._queuedRefreshArgs=[e,t]:(!0===e.resetConsent&&(this._consentManager.resetConsentData(!0===e.forceAllowLocalStorageGrant),this._awaitedConsentFrom=t),this._getId(!0===e.forceFetch))}updateConsent(e,t){if(this._consentManager.hasConsentSet())this._handleIgnoredConsentUpdate(e);else{const s=new Set(this._followers.map(e=>e.getDeclaredConsentSource()));var r=e.source||M.cmp,i=1===s.size&&s.has(M.partner);this._awaitedConsentFrom?this._awaitedConsentFrom===t?(this._consentManager.setConsentData(e),this._awaitedConsentFrom=void 0):this._handleIgnoredConsent(e,"awaited"):r!==M.partner||i?this._consentManager.setConsentData(e):this._handleIgnoredConsent(e,"partner")}}_handleIgnoredConsentUpdate(e){try{const i=this._consentManager._consentDataHolder.getValue();if(i){const s={},n=H.createFrom(e);Object.values(k).forEach(e=>{var t,r;n.apiTypes.includes(e)&&i.apiTypes.includes(e)?(t=JSON.stringify(i.getApiTypeData(e)),r=JSON.stringify(n.getApiTypeData(e)),s[e]=t===r?"same":"different"):n.apiTypes.includes(e)?s[e]="added":i.apiTypes.includes(e)&&(s[e]="missed")}),this._metrics.consentChangeCounter(s).inc()}}catch(e){this._log.error(e)}}_handleIgnoredConsent(e,t){try{const r={reason:t,source:e.source};e.apiTypes.forEach(e=>r[e]=!0),this._metrics.consentIgnoreCounter(r)}catch(e){this._log.error(e)}}updateFetchIdData(t,e){const r=this._followers.find(e=>e.getId()===t);var i=r.getCacheId();r.updateFetchIdData(e);e=r.getCacheId();e!==i&&(this._log.info("Follower",r.getId(),"cacheId changed from",i," to",e,"required refresh"),this._refreshRequired[r.getId()]=!0)}addFollower(t){const e=this._log;var r=void 0===this._followers.find(e=>e.getCacheId()===t.getCacheId());this._followers.push(t),e.info("Added follower",t.getId(),"cacheId",t.getCacheId()),this._window!==t.getWindow()&&(i=t.getStorage(),e.info("Adding follower's",t.getId(),"storage as replica"),this._leaderStorage.addReplica(i));var i=this._provisionFromCache(t);let s=new Ae;return!0===this._firstFetchTriggered&&(s.lateJoiner=!0,s.uniqueLateJoiner=r,i&&this._callRefresh({forceFetch:!0})),s}_provisionFromCache(e){var t=this._cachedIdProvider.provisionFromCache(e);return this._refreshRequired[e.getId()]=t.refreshRequired,t.provisioned&&this._store.incNb(t.cacheId),t.refreshRequired}getProperties(){return this._properties}_handleFetchCompleted(){this._inProgressFetch=void 0,this._queuedRefreshArgs&&(this._callRefresh(...this._queuedRefreshArgs),this._queuedRefreshArgs=void 0)}_handleFailed(e){this._log.error("Fetch id failed",e);var t,r=m(this._followers);try{for(r.s();!(t=r.n()).done;){const i=t.value;i.notifyFetchUidCanceled({reason:"error"})}}catch(e){r.e(e)}finally{r.f()}}}class Ne extends Oe{constructor(e,t){super(),d(this,"_messenger",void 0),d(this,"_leaderInstanceProperties",void 0),this._messenger=e,this._leaderInstanceProperties=t}_sendToLeader(e,t){this._messenger.callProxyMethod(this._leaderInstanceProperties.id,I.LEADER,e,t)}updateConsent(e,t){this._sendToLeader("updateConsent",[e,t])}refreshUid(e,t){this._sendToLeader("refreshUid",[e,t])}updateFetchIdData(e,t){this._sendToLeader("updateFetchIdData",[e,t])}getProperties(){return this._leaderInstanceProperties}}class xe extends Oe{constructor(){super(...arguments),d(this,"_callsQueue",[]),d(this,"_assignedLeader",void 0)}updateConsent(e,t){this._callOrBuffer("updateConsent",[e,t])}updateFetchIdData(e,t){this._callOrBuffer("updateFetchIdData",[e,t])}refreshUid(e,t){this._callOrBuffer("refreshUid",[e,t])}addFollower(e){return this._callOrBuffer("addFollower",[e])}getProperties(){if(this._assignedLeader)return this._assignedLeader.getProperties()}assignLeader(e){this._assignedLeader=e;var t,r=m(this._callsQueue);try{for(r.s();!(t=r.n()).done;){var i=t.value;this._callAssignedLeader(i.name,i.args)}}catch(e){r.e(e)}finally{r.f()}this._callsQueue=[]}_callOrBuffer(e,t){if(this._assignedLeader)return this._callAssignedLeader(e,t);this._callsQueue.push({name:e,args:t})}_callAssignedLeader(e,t){return this._assignedLeader[e](...t)}}class Le{constructor(){d(this,"_valuePromise",void 0),d(this,"_value",void 0),d(this,"_resolve",void 0),d(this,"_hasValue",void 0),this.reset()}reset(){this._value=void 0,this._hasValue=!1,this._valuePromise=new Promise(e=>{this._resolve=e})}set(e){this._hasValue?this._valuePromise=Promise.resolve(e):(this._hasValue=!0,this._resolve(e)),this._value=e}getValuePromise(){return this._valuePromise}hasValue(){return this._hasValue}getValue(){return this._value}}class Fe extends class{getConsentData(){}localStorageGrant(){}setStoredPrivacy(){}}{constructor(e,t,r,i,s){super(),d(this,"_consentDataHolder",void 0),d(this,"storedPrivacyData",void 0),d(this,"localStorage",void 0),d(this,"_forceAllowLocalStorageGrant",void 0),this._log=i,this.localStorage=e,this.storageConfig=t,this._consentDataHolder=new Le,this._forceAllowLocalStorageGrant=r,this._metrics=s}isForceAllowLocalStorageGrant(){return this._forceAllowLocalStorageGrant}resetConsentData(e){this._consentDataHolder.reset(),this.storedPrivacyData=void 0,this._forceAllowLocalStorageGrant=e}localStorageGrant(){var e,t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"unknown",r=this._getLocalStorageGrant();return null===(e=this._metrics)||void 0===e||null!==(t=e.localStorageGrantCounter(_(_({allowed:r.allowed,grantType:r.grantType,lsgContext:t,consentSet:null===(t=this._consentDataHolder)||void 0===t?void 0:t.hasValue()},r.api),r._debugInfo)))&&void 0!==t&&t.inc(),r}_getLocalStorageGrant(){const e=this._log;if(!0===this._forceAllowLocalStorageGrant)return e.warn("cmpApi: Local storage access granted by configuration override, consent will not be checked"),new J(!0,q.FORCE_ALLOWED_BY_CONFIG);if(this._consentDataHolder.hasValue()&&0!==this._consentDataHolder.getValue().apiTypes.length)return this._consentDataHolder.getValue().localStorageGrant();if(x(this.storedPrivacyData)||(t=this.localStorage.getItemWithExpiration(this.storageConfig.PRIVACY),this.storedPrivacyData=t&&JSON.parse(t),e.info("cmpApi: Loaded stored privacy data from local storage",this.storedPrivacyData)),this.storedPrivacyData&&!0===this.storedPrivacyData.id5_consent)return new J(!0,q.ID5_CONSENT);if(!this.storedPrivacyData||!L(this.storedPrivacyData.jurisdiction))return new J(!0,q.PROVISIONAL);var t=this.storedPrivacyData.jurisdiction,t=t in B.PRIVACY.JURISDICTIONS&&B.PRIVACY.JURISDICTIONS[t];return new J(!1===t,q.JURISDICTION)}setStoredPrivacy(e){const t=this._log;try{x(e)?(this.storedPrivacyData=e,this.localStorage.setItemWithExpiration(this.storageConfig.PRIVACY,JSON.stringify(e))):t.error("cmpApi: Cannot store privacy data if it is not an object",e)}catch(e){t.error("cmpApi: Error while storing privacy data",e)}}setConsentData(e){this._log.debug("Set consent data",e);e=H.createFrom(e);this._consentDataHolder.set(e)}getConsentData(){return this._consentDataHolder.getValuePromise()}hasConsentSet(){return this._consentDataHolder.hasValue()}}class Ue{constructor(e,t,r,i){d(this,"localStorageGrantChecker",void 0),d(this,"localStorage",void 0),d(this,"_log",void 0),this.localStorageGrantChecker=e,this.localStorage=t,this.storageConfig=r,this._log=i}get(e){const t=this._log;try{const i=this.localStorageGrant();if(i.isDefinitivelyAllowed()){var r=this.localStorage.getItemWithExpiration(e);return t.info("Local storage get key=".concat(e.name," value=").concat(r)),r}t.warn("clientStore.get() has been called without definitive grant",i)}catch(e){t.error(e)}}_getObject(e){const t=this._log;try{const i=this.localStorageGrant();if(i.isDefinitivelyAllowed()){var r=this.localStorage.getObjectWithExpiration(e);return t.info("Local storage get key=".concat(e.name," value=").concat(r)),r}t.warn("clientStore.get() has been called without definitive grant",i)}catch(e){t.error(e)}}clear(e){const t=this._log;try{this.localStorage.removeItemWithExpiration(e)}catch(e){t.error(e)}}scheduleGC(t){const r=this.localStorageGrant(),i=this.localStorage,s=this.storageConfig.ID5_V2.name;setTimeout(function(){var e;r.isDefinitivelyAllowed()&&(e=i.removeExpiredObjectWithPrefix(s),t.storageAllKeysCounter().record((null==e?void 0:e.all)||0),t.storageExpiredKeysCounter().record((null==e?void 0:e.expired)||0))},0)}_clearObject(e){const t=this._log;try{this.localStorage.removeItem(e.name)}catch(e){t.error(e)}}_put(e,t){const r=this._log;try{const i=this.localStorageGrant();i.isDefinitivelyAllowed()?(r.info("Local storage put key=".concat(e.name," value=").concat(t)),this.localStorage.setItemWithExpiration(e,t)):r.warn("clientStore._put() has been called without definitive grant",i)}catch(e){r.error(e)}}_updateObject(e,t){const r=this._log;try{const i=this.localStorageGrant();if(i.isDefinitivelyAllowed())return this.localStorage.updateObjectWithExpiration(e,t);r.warn("clientStore._updateObject() has been called without definitive grant",i)}catch(e){r.error(e)}}localStorageGrant(){return this.localStorageGrantChecker()}getResponse(){var e=this.get(this.storageConfig.ID5);return e&&JSON.parse(decodeURIComponent(e))}clearResponse(){this.clear(this.storageConfig.ID5)}clearResponseV2(e){this._clearObject(this.storageConfig.ID5_V2.withNameSuffixed(e))}putResponseV1(e){this._put(this.storageConfig.ID5,encodeURIComponent(O(e)?e:JSON.stringify(e)))}getHashedConsentData(){return this.get(this.storageConfig.CONSENT_DATA)}clearHashedConsentData(){this.clear(this.storageConfig.CONSENT_DATA)}putHashedConsentData(e){e!==new H&&this._put(this.storageConfig.CONSENT_DATA,e.hashCode())}clearDateTime(){this.clear(this.storageConfig.LAST)}setResponseDateTimeV1(e){this._put(this.storageConfig.LAST,e)}storeResponseV2(e,t){let r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:Date.now();return this._updateObject(this.storageConfig.ID5_V2.withNameSuffixed(e),e=>_(_({},e),{},{response:t,responseTimestamp:r}))}getStoredResponseV2(e){return this._getObject(this.storageConfig.ID5_V2.withNameSuffixed(e))}incNbV2(e){let r=1<arguments.length&&void 0!==arguments[1]?arguments[1]:1;return this._updateObject(this.storageConfig.ID5_V2.withNameSuffixed(e),e=>{var t=Math.max(0,N(null==e?void 0:e.nb)?Math.round(e.nb)+r:r);return _(_({},e),{},{nb:t})})}static storedDataMatchesCurrentData(e,t){return null==e||e===t}storedConsentDataMatchesConsentData(e){return Ue.storedDataMatchesCurrentData(this.getHashedConsentData(),e.hashCode())}getExtensions(){return this._getObject(this.storageConfig.EXTENSIONS)}storeExtensions(e,t){return this._updateObject(t,()=>e)}clearExtensions(){return this.clear(this.storageConfig.EXTENSIONS)}}class Ve{constructor(e,t,r){d(this,"_metrics",void 0),d(this,"_log",void 0),d(this,"_store",void 0),this._metrics=e,this._log=t,this._store=r}static getChunkUrl(e,t){return"https://d".concat(e,".eu-").concat(t,"-id5-sync.com")}submitExtensionCall(t,r){var e=2<arguments.length&&void 0!==arguments[2]?arguments[2]:void 0;let i=pe();return fetch(t,e).then(e=>{if(e.ok)return i.record(this._metrics.extensionsCallTimer(r,!0)),e.json();i.record(this._metrics.extensionsCallTimer(r,!1));e="The call to get extensions at ".concat(t," was not ok, status: ").concat(e.status,", statusText: ").concat(e.statusText);return this._log.warn(e),Promise.reject(new Error(e))}).catch(e=>(i.record(this._metrics.extensionsCallTimer(r,!1)),this._log.warn("Got error from ".concat(t," endpoint"),e),{}))}gatherChunks(e,r){if(e){let t=pe();return Promise.all(Array.from({length:r.length},(e,t)=>{t=Ve.getChunkUrl(t,r.urlVersion);return fetch(t).then(e=>{if(e.ok)return e.text();throw new Error("The call to get ".concat(r.name," was not ok, status: ").concat(e.status,", statusText: ").concat(e.statusText))})})).then(e=>(t.record(this._metrics.extensionsCallTimer(r.name,!0)),{[r.name]:e,[r.name+"Version"]:"".concat(r.version)})).catch(e=>(t.record(this._metrics.extensionsCallTimer(r.name,!1)),this._log.warn("Got error when getting ".concat(r.name),e),{}))}return Promise.resolve({})}gather(e){var t=this._store.getCachedExtensions();if(void 0!==t)return Promise.resolve(t);let r=pe(),i=this._submitBounce(e);return this.submitExtensionCall("https://lb.eu-1-id5-sync.com/lb/v1","lb").then(e=>{var t=this.getChunksEnabled(e);return Promise.allSettled([Promise.resolve(e),this.gatherChunks(t,Ve.CHUNKS_CONFIGS.devChunks),this.gatherChunks(t,Ve.CHUNKS_CONFIGS.groupChunks),i])}).then(e=>{r.record(this._metrics.extensionsCallTimer("all",!0));let t=Ve.DEFAULT_RESPONSE;return e.forEach(e=>{e.value&&(t=_(_({},t),e.value))}),this._store.storeExtensions(t),t}).catch(e=>(r.record(this._metrics.extensionsCallTimer("all",!1)),this._log.error("Got error ".concat(e," when gathering extensions data")),Ve.DEFAULT_RESPONSE))}_submitBounce(e){return e.some(e=>{return L(null===(e=e.cacheData)||void 0===e?void 0:e.signature)})?Promise.resolve({}):this.submitExtensionCall("https://id5-sync.com/bounce","bounce",{credentials:"include"})}getChunksEnabled(e){e=null==e?void 0:e.chunks;return 0!==e&&e}}d(Ve,"CHUNKS_CONFIGS",Object.freeze({devChunks:{name:"devChunks",urlVersion:3,length:8,version:4},groupChunks:{name:"groupChunks",urlVersion:4,length:8,version:4}})),d(Ve,"DEFAULT_RESPONSE",{lbCDN:"%%LB_CDN%%"});const Ge={createExtensions:function(e,t,r){return new Ve(e,t,r)}},Me=Object.freeze({UNKNOWN:"unknown",LEADER:"leader",FOLLOWER:"follower"}),je=Object.freeze({MULTIPLEXING:"multiplexing",SINGLETON:"singleton"}),ke=Object.freeze({AWAITING_SCHEDULE:"awaiting_schedule",SKIPPED:"skipped",SCHEDULED:"scheduled",COMPLETED:"completed",CANCELED:"canceled"});class We{constructor(e,t,r){d(this,"properties",void 0),d(this,"knownState",void 0),d(this,"_joinTime",void 0),d(this,"_window",void 0),this.properties=e,this.knownState=t,this._window=r,this._joinTime=performance.now()}getId(){return this.properties.id}isMultiplexingPartyAllowed(){var e;return(null===(e=this.knownState)||void 0===e?void 0:e.operatingMode)===je.MULTIPLEXING}getInstanceMultiplexingLeader(){var e,t;if((null===(e=this.knownState)||void 0===e?void 0:e.operatingMode)===je.MULTIPLEXING)return null===(e=this.knownState)||void 0===e||null===(t=e.multiplexing)||void 0===t?void 0:t.leader}getWindow(){return this._window}}class He{constructor(e){d(this,"_knownValues",[]),d(this,"_counter",void 0),this._counter=e}add(e){e&&-1===this._knownValues.indexOf(e)&&(this._counter.inc(),this._knownValues.push(e))}}class qe{constructor(e,t){d(this,"_instancesCounter",void 0),d(this,"_domainsCounter",void 0),d(this,"_windowsCounter",void 0),d(this,"_partnersCounter",void 0);var r=t.id;this._instancesCounter=e.instanceCounter(t.id),this._windowsCounter=new He(e.instanceUniqWindowsCounter(r)),this._partnersCounter=new He(e.instanceUniqPartnersCounter(r)),this._domainsCounter=new He(e.instanceUniqueDomainsCounter(r))}addInstance(e){var t,r,i;this._instancesCounter.inc(),this._partnersCounter.add((null==e||null===(t=e.fetchIdData)||void 0===t?void 0:t.partnerId)|(null==e||null===(r=e.sourceConfiguration)||void 0===r||null===(i=r.options)||void 0===i?void 0:i.partnerId)),this._domainsCounter.add(null==e?void 0:e.domain),this._windowsCounter.add(null==e?void 0:e.href)}}class Je{constructor(e){d(this,"_scheduleTime",void 0),d(this,"_closeTime",void 0),d(this,"_timeoutId",void 0),d(this,"_state",ke.AWAITING_SCHEDULE),d(this,"_delayMs",void 0),d(this,"_instance",void 0),this._instance=e}schedule(e){const t=this;t._delayMs=e,this._timeoutId=setTimeout(()=>{t._timeoutId&&(t._timeoutId=void 0,t._instance._doElection(),t._closeWithState(ke.COMPLETED))},t._delayMs),t._state=ke.SCHEDULED,t._scheduleTime=performance.now()}skip(){this._closeWithState(ke.SKIPPED)}cancel(){this._timeoutId&&(clearTimeout(this._timeoutId),this._timeoutId=void 0),this._closeWithState(ke.CANCELED)}_closeWithState(e){this._state=e,this._closeTime=performance.now()}}class Be{constructor(e,t,r,i,s,n,o){d(this,"properties",void 0),d(this,"_messenger",void 0),d(this,"_knownInstances",new Map),d(this,"_lastJoinedInstance",void 0),d(this,"role",void 0),d(this,"_leader",void 0),d(this,"_mode",void 0),d(this,"_metrics",void 0),d(this,"_logger",void 0),d(this,"_instanceCounters",void 0),d(this,"_election",void 0),d(this,"_window",void 0),d(this,"_storage",void 0),d(this,"_trueLinkAdapter",void 0),d(this,"_cachedIdProvider",void 0);var a=L(globalThis)&&L(globalThis.crypto)&&A(globalThis.crypto.randomUUID)?globalThis.crypto.randomUUID():"".concat(1e6*Math.random()|0);this.properties=h({id:a,version:"1.0.33",href:null===(a=e.location)||void 0===a?void 0:a.href,domain:null===(a=e.location)||void 0===a?void 0:a.hostname},t),this.role=Me.UNKNOWN,this._metrics=i,this._instanceCounters=new qe(i,this.properties),this._loadTime=performance.now(),this._logger=new Ke(s,this),this._window=e,this._dispatcher=new we(this._logger),this._leader=new xe,this._followerRole=new be(this._window,this.properties,this._dispatcher,this._logger,this._metrics),this._election=new Je(this),this._storage=r,this._trueLinkAdapter=n,this._cachedIdProvider=new Te("self",new z(o,n),this._logger,this._metrics)}updateConfig(e){h(this.properties,e)}init(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:500;let i=this,s=i._window;i._mode=!0===i.properties.singletonMode?je.SINGLETON:je.MULTIPLEXING,i._instanceCounters.addInstance(i.properties),function(r){const i=r._metrics;[100,200,500,1e3,2e3,3e3,5e3].forEach(t=>{setTimeout(()=>{var e=((null===(e=r._knownInstances)||void 0===e?void 0:e.size)||0)+1;i.summary("instance.partySize",{after:t,electionState:r._election._state}).record(e)},t)})}(i),i._messenger=new w(i.properties.id,s,i._logger,i._metrics),i._messenger.onAnyMessage((e,t)=>{var r=Date.now()-e.timestamp|0;i._metrics.instanceMsgDeliveryTimer({messageType:e.type,sameWindow:s===t}).record(r),i._logger.debug("Message received",e),i._doFireEvent(ye.ID5_MESSAGE_RECEIVED,e)}).onMessage(v.TYPE,(e,t)=>{let r=h(new v,e.payload);void 0===r.isResponse&&(r.isResponse=e.dst!==o),i._handleHelloMessage(r,e,t)}).onProxyMethodCall(new C(this._logger).registerTarget(I.LEADER,i._leader).registerTarget(I.FOLLOWER,i._followerRole).registerTarget(I.STORAGE,i._storage)),i._mode===je.SINGLETON?(i._election.skip(),i._onLeaderElected(i.properties)):i._mode===je.MULTIPLEXING&&i._election.schedule(e),i._messenger.broadcastMessage(i._createHelloMessage(!1),v.TYPE)}register(e){try{this.updateConfig(e),this.init()}catch(e){this._logger.error("Failed to register integration instance",e)}return this}_handleHelloMessage(e,t,r){this._joinInstance(e,t,r)}unregister(){this._logger.info("Unregistering"),this._messenger&&this._messenger.unregister()}on(e,t){return this._dispatcher.on(e,t),this}_joinInstance(e,t,r){var i=e.isResponse;const s=new We(e.instance,e.instanceState,r);this._knownInstances.get(s.getId())?this._logger.debug("Instance already known",s.getId()):(this._knownInstances.set(s.getId(),s),this._lastJoinedInstance=s,this._instanceCounters.addInstance(s.properties),this._metrics.instanceJoinDelayTimer({election:this._election._state}).record(performance.now()-this._loadTime|0),i?(i=s.getInstanceMultiplexingLeader(),this._mode===je.MULTIPLEXING&&this.role===Me.UNKNOWN&&void 0!==i&&(this._logger.info("Joined late, elected leader is",i),this._election.cancel(),this._onLeaderElected(i))):(this._messenger.sendResponseMessage(t,this._createHelloMessage(!0),v.TYPE),this._mode===je.MULTIPLEXING&&this.role!==Me.UNKNOWN&&this._handleLateJoiner(s)),this._logger.debug("Instance joined",s.getId()),this._doFireEvent(ye.ID5_INSTANCE_JOINED,s.properties))}_createHelloMessage(){var e,t=0<arguments.length&&void 0!==arguments[0]&&arguments[0];let r={operatingMode:this._mode,knownInstances:Array.from(this._knownInstances.values()).map(e=>e.properties)};return this._mode===je.MULTIPLEXING&&(r.multiplexing={role:this.role,electionState:null===(e=this._election)||void 0===e?void 0:e._state,leader:this._leader.getProperties()}),new v(this.properties,t,r)}_handleLateJoiner(e){this._logger.info("Late joiner detected",e.properties);var t=this._metrics.instanceLateJoinCounter(this.properties.id,{scope:"party"}).inc();this._metrics.instanceLateJoinDelayTimer({election:this._election._state,isFirst:1===t}).record(performance.now()-this._election._closeTime),!e.isMultiplexingPartyAllowed()||this.role!==Me.LEADER||!0===(null==(e=this._leader.addFollower(new Pe(e,this._messenger,this._logger)))?void 0:e.lateJoiner)&&this._metrics.instanceLateJoinCounter(this.properties.id,{scope:"leader",unique:!0===(null==e?void 0:e.uniqueLateJoiner)}).inc()}_doFireEvent(e){for(var t=arguments.length,r=new Array(1<t?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];this._dispatcher.emit(e,...r)}_actAsLeader(){var e=this.properties;const t=this._logger;var r=this._metrics,i=new re(this._storage),s=new $(i),n=new Y(e.storageExpirationDays);const o=new Fe(s,n,e.forceAllowLocalStorageGrant,t,r);s=new z(new Ue(()=>o.localStorageGrant("client-store"),s,n,t),this._trueLinkAdapter),n=new me(r,t,Ge.createExtensions(r,t,s));const a=new Re(this._window,e,i,s,o,r,t,n);a.addFollower(this._followerRole),this._leader.assignLeader(a),this._mode===je.MULTIPLEXING&&Array.from(this._knownInstances.values()).filter(e=>e.isMultiplexingPartyAllowed()).map(e=>a.addFollower(new Pe(e,this._messenger,t))),a.start()}_followRemoteLeader(e){this._leader.assignLeader(new Ne(this._messenger,e)),this._logger.info("Following remote leader ",e)}updateConsent(e){this._leader.updateConsent(e,this.properties.id)}updateFetchIdData(e){this._leader.updateFetchIdData(this.properties.id,e),h(this.properties.fetchIdData,e)}refreshUid(e){this._leader.refreshUid(e,this.properties.id)}_doElection(){var e=this._election;const t=this._knownInstances;let r=Array.from(t.values()).filter(e=>e.isMultiplexingPartyAllowed()).map(e=>e.properties);r.push(this.properties),this._onLeaderElected(function(e){if(!e||0===e.length)return;e=e.sort((e,t)=>{let r=-(0|S(e.version,t.version));var i,s,n;return 0===r&&(r=e.source.localeCompare(t.source),0===r&&(r=-(0|S(e.sourceVersion,t.sourceVersion))),0===r&&(s=(null===(s=e.fetchIdData)||void 0===s||null===(i=s.refererInfo)||void 0===i?void 0:i.numIframes)||Number.MAX_SAFE_INTEGER,n=(null===(i=t.fetchIdData)||void 0===i||null===(n=i.refererInfo)||void 0===n?void 0:n.numIframes)||Number.MAX_SAFE_INTEGER,r=s-n),0===r&&(r=e.id.localeCompare(t.id))),r});return e[0]}(r));var i=this._lastJoinedInstance;i&&this._metrics.instanceLastJoinDelayTimer().record(Math.max(i._joinTime-e._scheduleTime,0))}_onLeaderElected(e){var t=this;t.role=e.id===t.properties.id?Me.LEADER:Me.FOLLOWER,t.role===Me.LEADER?t._actAsLeader():t.role===Me.FOLLOWER&&t._followRemoteLeader(e),t._logger.debug("Leader elected",e.id,"my role",t.role),t._doFireEvent(ye.ID5_LEADER_ELECTED,t.role,t._leader.getProperties())}getId(){return this.properties.id}lookupForCachedId(){return this._logger.info("Self lookup for cachedId triggered"),this._cachedIdProvider.provisionFromCache(this._followerRole)}}class Ke extends e{constructor(e,t){super(),d(this,"_instance",void 0),this._delegate=e||u,this._instance=t}_prefix(){return"Instance(id=".concat(this._instance.getId(),", role=").concat(this._instance.role,")")}debug(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this._delegate.debug((new Date).toISOString(),this._prefix(),...t)}info(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this._delegate.info((new Date).toISOString(),this._prefix(),...t)}warn(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this._delegate.warn((new Date).toISOString(),this._prefix(),...t)}error(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this._delegate.error((new Date).toISOString(),this._prefix(),...t)}}const Ye=new class{createInstance(e,t,r,i,s,n){return new Be(e,{},i,r,t,s,n)}},ze="TRUE"===rt("id5_debug").toUpperCase(),Xe="TRACE"===rt("id5_debug").toUpperCase(),Qe=Boolean(window.console);let $e=!1;function Ze(e,t,r,i,s){et()&&Qe&&e&&e.apply(console,["%cID5 - ".concat(t,"#").concat(r),"color: #fff; background: #1c307e; padding: 1px 4px; border-radius: 3px;",i].concat(s))}function et(){return ze||Xe||$e}class tt extends e{constructor(e,t){super(),d(this,"_invocationId",void 0),d(this,"_origin",void 0),this._invocationId=t,this._origin=e}debug(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];!function(e,t){for(var r=arguments.length,i=new Array(2<r?r-2:0),s=2;s<r;s++)i[s-2]=arguments[s];Ze(console.info,e,t,"DEBUG",i)}(this._origin,this._invocationId,...t)}info(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];!function(e,t){for(var r=arguments.length,i=new Array(2<r?r-2:0),s=2;s<r;s++)i[s-2]=arguments[s];Ze(console.info,e,t,"INFO",i)}(this._origin,this._invocationId,...t)}warn(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];!function(e,t){for(var r=arguments.length,i=new Array(2<r?r-2:0),s=2;s<r;s++)i[s-2]=arguments[s];Ze(console.warn,e,t,"WARNING",i)}(this._origin,this._invocationId,...t)}error(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];!function(e,t){for(var r=arguments.length,i=new Array(2<r?r-2:0),s=2;s<r;s++)i[s-2]=arguments[s];Ze(console.error,e,t,"ERROR",i)}(this._origin,this._invocationId,...t)}}function rt(e){const t=new RegExp("[\\?&]"+e+"=([^&#]*)"),r=t.exec(window.location.search);return null===r?"":decodeURIComponent(r[1].replace(/\+/g," "))}const it=T,st=A,nt=O,ot=R,at=N,ct=x,dt=function(e){return T(e,"Boolean")},lt=L;function ht(e,t,r,i,s){for(t=t.split?t.split("."):t,i=0;i<t.length;i++)e=e?e[t[i]]:s;return e===s?r:e}new tt("ajax");const ut="1.0.76",gt=Object.freeze({NEVER:"never",AFTER_UID_SET:"after-uid-set",ASAP:"asap"}),pt=Object.freeze({allowGCReclaim:Object.values(gt)});class vt{constructor(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:u;if(d(this,"invocationId",void 0),d(this,"options",void 0),d(this,"providedOptions",void 0),d(this,"invalidSegments",void 0),this._log=t,this.options={debugBypassConsent:!1,allowLocalStorageWithoutConsentApi:!1,cmpApi:"iab",consentData:{},refreshInSeconds:7200,partnerId:void 0,partnerUserId:void 0,callbackOnAvailable:void 0,callbackOnUpdates:void 0,callbackTimeoutInMs:void 0,pd:void 0,abTesting:{enabled:!1,controlGroupPct:0},provider:void 0,maxCascades:8,applyCreativeRestrictions:!1,acr:!1,segments:void 0,disableUaHints:!1,storageExpirationDays:void 0,att:void 0,diagnostics:{publishingDisabled:!1,publishAfterLoadInMsec:3e4,publishBeforeWindowUnload:!0,publishingSampleRatio:.01},multiplexing:{_disabled:!1},allowGCReclaim:gt.AFTER_UID_SET},this.providedOptions={},!at(e.partnerId)&&!nt(e.partnerId))throw new Error("partnerId is required and must be a number or a string");this.invalidSegments=0,this.updOptions(e),this.storageConfig=new Y(e.storageExpirationDays)}getOptions(){return this.options}getProvidedOptions(){return this.providedOptions}getInvalidSegments(){return this.invalidSegments}hasCreativeRestrictions(){return this.options.applyCreativeRestrictions||this.options.acr}updOptions(a){const c=this,d=c._log;if(ct(a)){this.setPartnerId(a.partnerId);const l=(e,t)=>{this.options[e]=t,this.providedOptions[e]=t};Object.keys(a).forEach(e=>{if("segments"===e){const i=a[e],s=[];L(i)&&(ot(i)?(i.forEach((e,t)=>{t="segments[".concat(t,"]");return ot(e.ids)&&function(e,t){let r=!0;return F(e,e=>r=r&&t(e)),r}(e.ids,nt)?e.ids.length<1?(d.error("Config option ".concat(t,".ids should contain at least one segment ID")),void(c.invalidSegments+=1)):nt(e.destination)?void s.push(e):(_t(d,"".concat(t,".destination"),"String",e.destination),void(c.invalidSegments+=1)):(_t(d,"".concat(t,".ids"),"Array of String",e.ids),void(c.invalidSegments+=1))}),l(e,s)):_t(d,e,"Array",i))}else if("diagnostics"===e){const n=this.options.diagnostics,o=a.diagnostics;if(it(o,vt.configTypes.diagnostics)){let t=_({},n);Object.keys(o).forEach(e=>{void 0!==n[e]&&typeof n[e]==typeof o[e]&&(t[e]=o[e])}),this.options[e]=t}this.providedOptions[e]=a[e]}else{var t,r;void 0!==pt[e]?(r=a[e])&&pt[e].includes(r)&&l(e,r):"partnerId"!==e&&(t=vt.configTypes[e],L(r=a[e])&&(it(r,t)?l(e,r):_t(d,e,t,r)))}})}else d.error("Config options must be an object")}setPartnerId(e){let t;if(nt(e)){if(t=parseInt(e),isNaN(t)||t<0)throw new Error("partnerId is required and must parse to a positive integer")}else at(e)&&(t=e);if(at(t)){if(at(this.options.partnerId)&&t!==this.options.partnerId)throw new Error("Cannot update config with a different partnerId");this.options.partnerId=t,this.providedOptions.partnerId=e}}}function _t(e,t,r,i){e.error("Config option ".concat(t," must be of type ").concat(r," but was ").concat(toString.call(i),". Ignoring..."))}d(vt,"configTypes",{debugBypassConsent:"Boolean",allowLocalStorageWithoutConsentApi:"Boolean",cmpApi:"String",consentData:"Object",refreshInSeconds:"Number",partnerUserId:"String",callbackOnAvailable:"Function",callbackOnUpdates:"Function",callbackTimeoutInMs:"Number",pd:"String",abTesting:"Object",provider:"String",maxCascades:"Number",applyCreativeRestrictions:"Boolean",acr:"Boolean",disableUaHints:"Boolean",storageExpirationDays:"Number",att:"Number",diagnostics:"Object",multiplexing:"Object",dynamicConfig:"Object",allowGCReclaim:"String"});class ft{static gatherUaHints(e,t){return f(function*(){if(L(window.navigator.userAgentData)&&!e){let e;try{e=yield window.navigator.userAgentData.getHighEntropyValues(["architecture","fullVersionList","model","platformVersion"])}catch(e){return void t.error("Error while calling navigator.userAgentData.getHighEntropyValues()",e)}return ft.filterUaHints(e)}})()}static filterUaHints(e){if(L(e)){const t=/[()-.:;=?_/]/g;return R(e.brands)&&(e.brands=e.brands.filter(e=>O(e.brand)&&e.brand.search(t)<0)),R(e.fullVersionList)&&(e.fullVersionList=e.fullVersionList.filter(e=>O(e.brand)&&e.brand.search(t)<0)),e}}}const mt={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,a:26,b:27,c:28,d:29,e:30,f:31,g:32,h:33,i:34,j:35,k:36,l:37,m:38,n:39,o:40,p:41,q:42,r:43,s:44,t:45,u:46,v:47,w:48,x:49,y:50,z:51,0:52,1:53,2:54,3:55,4:56,5:57,6:58,7:59,8:60,9:61,"-":62,_:63,"+":62,"/":63};const It=Object.freeze({tcfv2:{objName:"__tcfapiCall",objKeys:["command","version"],returnObjName:"__tcfapiReturn"},uspv1:{objName:"__uspapiCall",objKeys:["command","version"],returnObjName:"__uspapiReturn"},gppv1:{objName:"__gppCall",objKeys:["command","parameter"],returnObjName:"__gppReturn"}}),yt=Object.freeze({TCF:0,USP:1,GPP:2});class Ct{constructor(e,t){d(this,"direct",void 0),d(this,"version",void 0),this.direct=e,this.version=t}getConsentData(){var e=this;return f(function*(){return e.getClientConsentData()})()}static create(a){return f(function*(){var e=Et._findCmpApi("__gpp"),t=e.cmpApiFrame,e=e.cmpApiFunction;let r,i=!1;if(!t)return a.warn("cmpApi: GPP not found! Using defaults."),Promise.resolve();if(st(e))i=!0,a.info("cmpApi: Detected GPP is directly accessible, calling it now."),r=e;else{a.info("cmpApi: Detected GPP is outside the current iframe. Using message passing.");const o=Et._buildCmpSurrogate(It.gppv1,t);r=function(e,t,r){o(e,r,t)}}var s=yield new Promise(t=>{var e=r("ping",function(e){t(e)});e&&t(e)});switch(s.gppVersion){case St.version:return new St(s,r,i);case bt.version:return new bt(s,r,i);default:var n="Unsupported version of gpp: ".concat(s.gppVersion);return a.warn(n),Promise.reject(n)}})()}static tcfDataHasLocalStorageGrant(e){e=r(Ct,Ct,wt).call(Ct,e,"PurposeConsent","PurposeConsents");return ot(e)&&!0===e[0]}static tcfDataHasID5VendorConsented(e){let t=r(Ct,Ct,wt).call(Ct,e,"VendorConsent","VendorConsents");return void 0!==(null===t||void 0===t?void 0:t.find(e=>"131"==e))}static getTcfData(e){e=null==e?void 0:e.tcfeuv2;let t=void 0;return ot(e)&&ct(e[0])?t=e[0]:ct(e)&&(t=e),t}}function wt(e,t,r){return t in e?e[t]:e[r]}class St extends Ct{constructor(e,t,r){super(r,St.version),d(this,"gppFn",void 0),d(this,"ready",void 0),this.gppFn=t,this.ready=this.isReady(e)}isReady(e){return"loaded"===e.cmpStatus&&"visible"!==e.cmpDisplayStatus}getClientConsentData(){var i=this;return f(function*(){i.ready||(i.ready=yield new Promise(t=>{i.gppFn("addEventListener",e=>!!i.isReady(e.pingData)&&void t(!0))}));var e=new Promise(t=>{i.gppFn("getGPPData",e=>{t(e)})}),t=new Promise(t=>{i.gppFn("getSection",e=>{t(e)},"tcfeuv2")}),e=l(yield Promise.all([e,t]),2),t=e[0],e=e[1];const r=new W;return r.version=k.GPP_V1_0,r.gppString=t.gppString,r.applicableSections=t.applicableSections,e&&(r.localStoragePurposeConsent=Ct.tcfDataHasLocalStorageGrant(e),r.vendorsConsentForId5Granted=Ct.tcfDataHasID5VendorConsented(e)),r})()}}function Dt(e,t,r){r&&(e.apiTypes.push(t),h(e,r))}d(St,"version","1.0");class bt extends Ct{constructor(e,t,r){super(r,bt.version),d(this,"gppFn",void 0),d(this,"readyPingData",void 0),this.gppFn=t,"ready"===e.signalStatus&&(this.readyPingData=e)}getClientConsentData(){var r=this;return f(function*(){return new Promise(t=>{r.readyPingData?t(r.parsePingData(r.readyPingData)):r.gppFn("addEventListener",e=>"ready"===e.pingData.signalStatus&&void t(r.parsePingData(e.pingData)))})})()}parsePingData(e){const t=new W;t.gppString=e.gppString,t.version=k.GPP_V1_1,t.applicableSections=e.applicableSections;e=Ct.getTcfData(e.parsedSections);return e&&(t.localStoragePurposeConsent=Ct.tcfDataHasLocalStorageGrant(e),t.vendorsConsentForId5Granted=Ct.tcfDataHasID5VendorConsented(e)),t}}d(bt,"version","1.1");class Et{constructor(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:u;d(this,"_lookupInProgress",void 0),d(this,"_log",void 0),d(this,"_metrics",void 0),d(this,"_consentDataPromise",void 0),this._metrics=e,this._log=t}refreshConsentData(e,t,r){const i=this;return i._lookupInProgress||(i._lookupInProgress=!0,i._consentDataPromise=this._lookupConsentData(e,t,r).finally(()=>{i._lookupInProgress=!1})),this._consentDataPromise}_lookupConsentData(e,t,r){if(e){this._log.warn("cmpApi: ID5 is operating in forced consent mode and will not retrieve any consent signals from the CMP");let e=new H;return e.forcedGrantByConfig=!0,e.source=M.partner,Promise.resolve(e)}switch(t){case"static":return new Promise(e=>{this._parseStaticConsentData(r,e)});case"iab":return new Promise(e=>{this._lookupIabConsent(e)});default:return this._log.error("cmpApi: Unknown consent API: ".concat(t)),Promise.reject(new Error("Unknown consent API: ".concat(t)))}}_parseStaticConsentData(e,t){e=e||{};let r=new H;if(r.source=M.partner,ct(e.getTCData)){const i=this._parseTcfData(e.getTCData);Dt(r,k.TCF_V2,i);try{const s=this._metrics;this._lookupTcf(e=>{s.consentDiscrepancyCounter({apiType:k.TCF_V2,sameString:(null==e?void 0:e.consentString)===(null===i||void 0===i?void 0:i.consentString),sameLSPC:(null==e?void 0:e.localStoragePurposeConsent)===(null===i||void 0===i?void 0:i.localStoragePurposeConsent),sameVendorsConsentForId5Granted:(null==e?void 0:e.vendorsConsentForId5Granted)===(null===i||void 0===i?void 0:i.vendorsConsentForId5Granted),sameGdpr:(null==e?void 0:e.gdprApplies)===(null===i||void 0===i?void 0:i.gdprApplies)}).inc()})}catch(e){}}if(ot(e.allowedVendors)&&Dt(r,k.ID5_ALLOWED_VENDORS,{allowedVendors:e.allowedVendors.map(e=>e.toString()),gdprApplies:!0}),ct(e.getUSPData)){const n=this._parseUspData(e.getUSPData);Dt(r,k.USP_V1,n);try{const o=this._metrics;this._lookupUsp(e=>{o.consentDiscrepancyCounter({apiType:k.USP_V1,sameString:(null==e?void 0:e.ccpaString)===(null===n||void 0===n?void 0:n.ccpaString)}).inc()})}catch(e){}}0===r.apiTypes.length&&this._log.warn("cmpApi: No static consent data detected! Using defaults."),this._log.info("cmpApi: Detected APIs '".concat(r.apiTypes,"' from static consent data"),e),t(r)}_lookupIabConsent(i){const s=[];let n=new H;n.source=M.cmp;var e=r=>(s[r]=0,(e,t)=>{s[r]||(s[r]=Date.now(),e&&Dt(n,t,e),s.every(e=>0<e)&&i(n))}),t=e(yt.TCF),r=e(yt.USP),e=e(yt.GPP);this._lookupGpp(e),this._lookupTcf(t),this._lookupUsp(r)}_lookupUsp(r){var e=Et._findCmpApi("__uspapi"),t=e.cmpApiFrame,e=e.cmpApiFunction;let i;if(!t)return this._log.warn("cmpApi: USP not found! Using defaults for CCPA."),void r();i=st(e)?(this._log.info("cmpApi: Detected USP is directly accessible, calling it now."),e):(this._log.info("cmpApi: Detected USP is outside the current iframe. Using message passing."),Et._buildCmpSurrogate(It.uspv1,t));i("getUSPData",1,(e,t)=>{t?r(this._parseUspData(e),k.USP_V1):(this._log.error("cmpApi: USP callback not successful. Using defaults for CCPA."),r())})}_lookupGpp(n){var o=this;return f(function*(){var t=Date.now();try{let e=yield Ct.create(o._log);if(e){var r={gppVersion:e.version,directCmp:e.direct};try{var i=yield e.getConsentData();n({gppData:i},i.version);var s=Date.now();o._metrics.timer("gpp.delay",r).record(s-t)}catch(e){o._metrics.counter("gpp.failure",h({type:"CONSENT"},r)).inc(),o._log.error("cmpApi: getting GPP consent not successful. Using defaults for Gpp."),n()}}else n()}catch(e){o._metrics.counter("gpp.failure",{type:"CLIENT"}).inc(),o._log.error("cmpApi: creating GPP client not successful. Using defaults for Gpp."),n()}})()}static _buildCmpSurrogate(a,c){return(e,t,r)=>{const i=Math.random()+"",s={},n={};n[a.objKeys[0]]=e,n[a.objKeys[1]]=t,n.callId=i,s[a.objName]=n;const o=e=>{e=ht(e,"data.".concat(a.returnObjName));e&&e.callId===i&&(void 0!==(e=r(e.returnValue,e.success))&&!0!==e||window.removeEventListener("message",o))};window.addEventListener("message",o,!1),c.postMessage(s,"*")}}_lookupTcf(e){var t=Et._findTCF(),r=t.cmpFrame,t=t.cmpFunction;if(!r)return this._log.warn("cmpApi: TCF not found! Using defaults for GDPR."),void e();st(t)?this._lookupDirectTcf(t,e):(this._log.info("cmpApi: Detected TCF is outside the current iframe. Using message passing."),this._lookupMessageTcf(r,e))}_lookupMessageTcf(e,t){e=Et._buildCmpSurrogate(It.tcfv2,e);this._lookupDirectTcf(e,t)}_lookupDirectTcf(e,s){const n=this._log;e("addEventListener",2,(e,t)=>{var r,i;return r="event",i=e,n.info("cmpApi: TCFv2 - Received a call back: ".concat(r),i),t?!(!e||!1!==e.gdprApplies&&"tcloaded"!==e.eventStatus&&"useractioncomplete"!==e.eventStatus)&&void s(this._parseTcfData(e),k.TCF_V2):(n.error("cmpApi: TCFv2 - Received insuccess: ".concat("addEventListener",". Please check your CMP setup. Using defaults for GDPR.")),void s())})}_parseUspData(e){if(ct(e)&&nt(e.uspString))return{ccpaString:e.uspString};this._log.error("cmpApi: No or malformed USP data. Using defaults for CCPA.")}_parseTcfData(e){let t=this._log,r,i;if(r=Et._isValidV2ConsentObject,i=Et._normalizeV2Data,r(e))return i(e);t.error("cmpApi: Invalid CMP data. Using defaults for GDPR.",e)}static _isValidV2ConsentObject(e){var t=e&&e.gdprApplies,e=e&&e.tcString;return!1===t||nt(e)}static _tcfDataHasID5VendorConsented(e){var t,r;return!0===(null==e||null===(t=e.vendor)||void 0===t||null===(r=t.consents)||void 0===r?void 0:r[131])}static _normalizeV2Data(e){let t=ht(e,"purpose.consents.1");dt(t)||(t=function(e,t){var r=152+t-1,t=~~(r/6);if(e&&"C"===e.charAt(0)&&!(e.length<=t)){t=e.charAt(t),t=mt[t];if(void 0!==t)return 0!=(t&1<<6-r%6-1)}}(e.tcString,1));var r=Et._tcfDataHasID5VendorConsented(e);return{consentString:e.tcString,localStoragePurposeConsent:t,gdprApplies:e.gdprApplies,vendorsConsentForId5Granted:r}}static _findTCF(){let e=window,t,r;for(;!t;){try{if("function"==typeof e.__tcfapi){r=e.__tcfapi,t=e;break}}catch(e){}try{if(e.frames.__tcfapiLocator){t=e;break}}catch(e){}if(e===window.top)break;e=e.parent}return{cmpFrame:t,cmpFunction:r}}static _findCmpApi(e){let t=window,r,i;for(;!r;){try{if("function"==typeof t[e]){i=t[e],r=t;break}}catch(e){}try{if(t.frames["".concat(e,"Locator")]){r=t;break}}catch(e){}if(t===window.top)break;t=t.parent}return{cmpApiFrame:r,cmpApiFunction:i}}}class Pt{isBooted(){return x(window.id5Bootstrap)}getTrueLink(){return this.isBooted()?window.id5Bootstrap.getTrueLinkInfo():{booted:!1}}setPrivacy(e){this.isBooted()&&window.id5Bootstrap.setPrivacy&&window.id5Bootstrap.setPrivacy(e)}clearPrivacy(){this.setPrivacy(void 0)}}const Tt="id5-prebid-ext-module";class At{set debug(e){e=e,$e=!!e}get debug(){return et()}constructor(){d(this,"invocationId",0),d(this,"_version",ut),d(this,"userIdReady",!1),this._isUsingCdn=!!(document&&document.currentScript&&document.currentScript.src&&0===document.currentScript.src.indexOf("https://cdn.id5-sync.com"))}fetchId5Id(d,l,h,u,g,p){var v=this;return f(function*(){var e;v.invocationId+=1;var t=lt(window.pbjs)?window.pbjs.version:"unknown";const s=new tt(Tt,v.invocationId);s.info("ID5 API Prebid external module version ".concat(v._version,". Invoking fetchId5Id()"),d,l);const r=new vt({partnerId:l.partner,pd:l.pd,abTesting:l.abTesting,multiplexing:l.multiplexing,diagnostics:l.diagnostics,segments:l.segments,disableUaHints:l.disableUaHints,dynamicConfig:d},s);var i=r.getOptions();const n=v._configureDiagnostics(i.partnerId,i.diagnostics,h,s,t);n&&(n.loadDelayTimer().recordNow(),n.invocationCountSummary().record(v.invocationId));var o=new te(window);const a=Ye.createInstance(window,s,n,o,new Pt);a.updateConsent(v._buildConsentData(u,g,p));const c=pe();o=new Promise((i,t)=>{a.on(Ie.USER_ID_READY,(e,t)=>{try{var r=null!=t&&t.tags?_({},t.tags):{};null!=t&&t.timestamp&&n.userIdNotificationDeliveryDelayTimer(r).record(Date.now()-t.timestamp),c.record(n.userIdProvisioningDelayTimer(e.isFromCache,_(_({},r),{},{isUpdate:!1})))}catch(e){s.error("Failed to measure provisioning metrics",e)}e=e.responseObj;v.userIdReady=!0,i({universal_uid:e.universal_uid,ext:e.ext,ab_testing:e.ab_testing})}).on(Ie.USER_ID_FETCH_CANCELED,e=>{s.info("ID5 User ID fetch canceled:",e.reason),t(e.reason)})}),t=yield v._gatherFetchIdData(r,h,s,t);return a.register({source:Tt,sourceVersion:ut,sourceConfiguration:{options:r.getOptions()},fetchIdData:t,singletonMode:!0===(null==i||null===(e=i.multiplexing)||void 0===e?void 0:e._disabled),canDoCascade:!1,forceAllowLocalStorageGrant:!1,storageExpirationDays:i.storageExpirationDays}),o})()}_buildConsentData(e,t,r){const i=new H;return i.source=M.prebid,e&&(i.apiTypes.push(k.TCF_V2),i.gdprApplies=e.gdprApplies,i.consentString=e.consentString,i.localStoragePurposeConsent=ht(e.vendorData,"purpose.consents.1")),t&&(i.apiTypes.push(k.USP_V1),i.ccpaString=t,i.localStoragePurposeConsent=!0),null!=r&&r.gppString&&(t=(e=Ct.getTcfData(r.parsedSections))?Ct.tcfDataHasLocalStorageGrant(e):void 0,(e=this._translateGppVersion(r.gppVersion))&&(i.apiTypes.push(e),i.gppData=new W(e,t,r.applicableSections,r.gppString))),i}_translateGppVersion(e){switch(e){case"1.0":return k.GPP_V1_0;case"1.1":return k.GPP_V1_1;default:return}}_configureDiagnostics(t,r,i,s,n){try{let e=new _e(Tt,this._version);var o;return e.addCommonTags(_(_({},ve(t)),{},{tml:i.topmostLocation,prebidVersion:n})),null!=r&&r.publishingDisabled||(a=r.publishingSampleRatio,o=Math.random()<a&&ie?(e,t)=>new se(c,{sampling:a}).publish(e,t):e=>e,null!=r&&r.publishAfterLoadInMsec&&0<r.publishAfterLoadInMsec&&e.schedulePublishAfterMsec(r.publishAfterLoadInMsec,o),null!=r&&r.publishBeforeWindowUnload&&e.schedulePublishBeforeUnload(o)),e}catch(e){return void s.error("Failed to configure diagnostics",e)}var a,c}_gatherFetchIdData(r,i,s,n){var o=this;return f(function*(){var e=r.getOptions(),t=yield ft.gatherUaHints(e.disableUaHints,s);return{partnerId:e.partnerId,refererInfo:i,origin:"pbjs",originVersion:n,isUsingCdn:o._isUsingCdn,att:e.att,uaHints:t,abTesting:e.abTesting,segments:e.segments,invalidSegmentsCount:r.getInvalidSegments(),provider:e.provider,pd:e.pd,partnerUserId:e.partnerUserId,refreshInSeconds:e.refreshInSeconds,providedRefreshInSeconds:r.getProvidedOptions().refreshInSeconds,trace:Xe,consentSource:M.prebid,trueLink:(new Pt).getTrueLink()}})()}}window.id5Prebid||(window.id5Prebid={}),(!window.id5Prebid.version||S(window.id5Prebid.version,ut)<=0)&&(window.id5Prebid.integration=new At,window.id5Prebid.version=ut)}(); |