diff --git a/blocks/form/form.js b/blocks/form/form.js
index 387ad31e..c158ee48 100644
--- a/blocks/form/form.js
+++ b/blocks/form/form.js
@@ -1,4 +1,4 @@
-import { readBlockConfig } from '../../scripts/lib-franklin.js';
+import { readBlockConfig, toCamelCase } from '../../scripts/lib-franklin.js';
function generateUnique() {
return new Date().valueOf() + Math.random();
@@ -418,6 +418,8 @@ export default async function decorate(block) {
formLink.replaceWith(form);
const config = readBlockConfig(block);
- Object.entries(config).forEach(([key, value]) => { if (value) form.dataset[key] = value; });
+ Object.entries(config).forEach(([key, value]) => {
+ if (value) form.dataset[toCamelCase(key)] = value;
+ });
}
}
diff --git a/head.html b/head.html
index 9c1b93b2..f38a08f7 100644
--- a/head.html
+++ b/head.html
@@ -1,4 +1,8 @@
-
+
+
+
+
+
\ No newline at end of file
diff --git a/scripts/adobe-martech/acdl.min.js b/scripts/adobe-martech/acdl.min.js
new file mode 100644
index 00000000..948094c8
--- /dev/null
+++ b/scripts/adobe-martech/acdl.min.js
@@ -0,0 +1 @@
+(()=>{var e={},t={};t={get:function(e,t,n){let r=Array.isArray(t)?t:t.split("."),a=e;for(let e of r)if(void 0===(a=a[e]))return n;return a},has:function(e,t){let n=Array.isArray(t)?t:t.split("."),r=e;for(let e of n){if(!r?.hasOwnProperty(e))return!1;r=r[e]}return!0}};var n=JSON.parse('{"version":"2.0.2"}').version,r={},a={};a=function(e,t){let n=Object.keys(t).find(n=>{let r=t[n].type,a=n&&t[n].values,i=!t[n].optional,o=e[n],l=typeof o,c=r&&l!==r,f=a&&!a.includes(o);return i?!o||c||f:o&&(c||f)});return void 0===n};var i={};i={event:{event:{type:"string"},eventInfo:{optional:!0}},listenerOn:{on:{type:"string"},handler:{type:"function"},scope:{type:"string",values:["past","future","all"],optional:!0},path:{type:"string",optional:!0}},listenerOff:{off:{type:"string"},handler:{type:"function",optional:!0},scope:{type:"string",values:["past","future","all"],optional:!0},path:{type:"string",optional:!0}}};var o={};o={itemType:{DATA:"data",FCTN:"fctn",EVENT:"event",LISTENER_ON:"listenerOn",LISTENER_OFF:"listenerOff"},dataLayerEvent:{CHANGE:"adobeDataLayer:change",EVENT:"adobeDataLayer:event"},listenerScope:{PAST:"past",FUTURE:"future",ALL:"all"}};let l=e=>[Object,Array].includes((e||{}).constructor)&&!Object.entries(e||{}).length;r=function(e,t){let n=Object.keys(i).find(t=>a(e,i[t]))||"function"==typeof e&&o.itemType.FCTN||function(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(e)&&o.itemType.DATA,r=function(){let t=Object.keys(e).filter(e=>!Object.keys(i.event).includes(e)).reduce((t,n)=>(t[n]=e[n],t),{});if(!l(t))return t}();return{config:e,type:n,data:r,valid:!!n,index:t}};var c={};c=function(e){let t=e.config.on||e.config.off,n=e.config.handler||null,r=e.config.scope||e.config.on&&o.listenerScope.ALL||null,a=e.config.path||null;return{event:t,handler:n,scope:r,path:a}};var f={},s={};s={mergeWith:function e(t,n,r){if(n&&t)return Object.keys(n).forEach(a=>{let i=r?r(t[a],n[a],a,t):void 0;void 0===i&&(i=n[a]===Object(n[a])&&a in t&&!Array.isArray(n[a])?e(t[a],n[a],r):n[a]),t[a]=i}),t},cloneDeepWith:function e(t,n){let r=n?n(t):void 0;if(void 0===r){if(t===Object(t)&&!Array.isArray(t)){r={};let a=Object.keys(t);for(let i=0;i-1&&t[r].splice(a,1)}else t[r]=[]}},triggerListeners:function(e){let n=function(e){let t=[];switch(e.type){case o.itemType.DATA:t.push(o.dataLayerEvent.CHANGE);break;case o.itemType.EVENT:t.push(o.dataLayerEvent.EVENT),e.data&&t.push(o.dataLayerEvent.CHANGE),e.config.event!==o.dataLayerEvent.CHANGE&&t.push(e.config.event)}return t}(e);n.forEach(function(n){if(Object.prototype.hasOwnProperty.call(t,n))for(let a of t[n])r(a,e)})},triggerListener:function(e,t){r(e,t)}}};var g={},h=s.cloneDeepWith,v=s.mergeWith;g=function(e,t){return v(e,t,function(e,t){if(null==t)return null}),e=function(e,t=e=>!e){return h(e,function e(n){if(n===Object(n)){if(Array.isArray(n))return n.filter(e=>!t(e)).map(t=>h(t,e));let r={};for(let a of Object.keys(n))t(n[a])||(r[a]=h(n[a],e));return r}})}(e,e=>null==e)},e=function(e){let a;let i=e||{},l=[],s=[],u={},p={getState:function(){return u},getDataLayer:function(){return l}};function y(e){u=g(u,e.data)}function d(e){if(!e.valid){h(e);return}function t(e){return 0===l.length||e.index>l.length-1?[]:l.slice(0,e.index).map(e=>r(e))}({data:function(e){y(e),a.triggerListeners(e)},fctn:function(e){e.config.call(l,l)},event:function(e){e.data&&y(e),a.triggerListeners(e)},listenerOn:function(e){let n=c(e);switch(n.scope){case o.listenerScope.PAST:for(let r of t(e))a.triggerListener(n,r);break;case o.listenerScope.FUTURE:a.register(n);break;case o.listenerScope.ALL:{let r=a.register(n);if(r)for(let r of t(e))a.triggerListener(n,r)}}},listenerOff:function(e){a.unregister(c(e))}})[e.type](e)}function h(e){let t="The following item cannot be handled by the data layer because it does not have a valid format: "+JSON.stringify(e.config);console.error(t)}return Array.isArray(i.dataLayer)||(i.dataLayer=[]),s=i.dataLayer.splice(0,i.dataLayer.length),(l=i.dataLayer).version=n,u={},a=f(p),l.push=function(...e){if(Object.keys(e).forEach(function(t){let n=e[t],a=r(n);switch(a.valid||(h(a),delete e[t]),a.type){case o.itemType.DATA:case o.itemType.EVENT:d(a);break;case o.itemType.FCTN:delete e[t],d(a);break;case o.itemType.LISTENER_ON:case o.itemType.LISTENER_OFF:delete e[t]}}),e[0])return Array.prototype.push.apply(this,e)},l.getState=function(e){return e?(0,t.get)(structuredClone(u),e):structuredClone(u)},l.addEventListener=function(e,t,n){let a=r({on:e,handler:t,scope:n&&n.scope,path:n&&n.path});d(a)},l.removeEventListener=function(e,t){let n=r({off:e,handler:t});d(n)},function(){for(let e=0;e1?t-1:0),o=1;o>>1:t>>>1;e.push(t)}return function(n,t){n=unescape(encodeURIComponent(n)),t||(t=0),t=~t;for(var r=0;r>>8^e[o]}return(t=~t)>>>0}}(),S=function(){var e={};return e.promise=new Promise((function(n,t){e.resolve=n,e.reject=t})),e},k=function(e,n){return e===n},T=function(e,n){for(var t=0;t1&&void 0!==arguments[1]?arguments[1]:{},t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],o=(arguments.length>4&&void 0!==arguments[4]?arguments[4]:document).createElement(e);return Object.keys(n).forEach((function(e){o.setAttribute(e,n[e])})),function(e,n){Object.keys(n).forEach((function(t){if("style"===t&&g(n[t])){var r=n[t];Object.keys(r).forEach((function(n){e.style[n]=r[n]}))}else e[t]=n[t]}))}(o,t),r.forEach((function(e){return D(o,e)})),o},R="IMG",O="STYLE",A="SCRIPT",N=function(e){var n=e.src,t=e.currentDocument,r=void 0===t?document:t;return new Promise((function(e,t){P(R,{src:n},{onload:e,onerror:t,onabort:t},[],r)}))},M=function(e){return"function"==typeof e},x=function(e){return Array.isArray(e)&&e.length>0},q=function(e){return Array.isArray(e)?e:null==e?[]:[].slice.call(e)},j=/^\s*>/,L=function(e,n){if(!j.test(n))return q(e.querySelectorAll(n));var t="alloy-"+Date.now();try{return e.classList.add(t),q(e.querySelectorAll("."+t+" "+n))}finally{e.classList.remove(t)}},_=function(e,n){return e.substr(0,n.length)===n},U=":shadow",F=function(e,n){var t=n;return _(t,">")?window.document.documentMode?t.substring(1).trim():(e instanceof Element||e instanceof HTMLDocument?":scope":":host")+" "+t:t},B=function(e,n){if(!window.document.documentElement.attachShadow)return L(e,n.replace(U,""));var t=function(e){return e.split(U)}(n);if(t.length<2)return L(e,n);for(var r=e,o=0;o1&&void 0!==arguments[1]?arguments[1]:document;return-1===e.indexOf(U)?L(n,e):B(n,e)},V="MutationObserver",z={childList:!0,subtree:!0},J=function(e){return new Error("Could not find: "+e)},Q=function(e){return new Promise(e)},G=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:H,t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:5e3,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:window,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:document,i=n(e);return x(i)?Promise.resolve(i):function(e){return M(e[V])}(r)?function(e,n,t,r,o){return Q((function(i,a){var u,c=new e[V]((function(){var e=o(t);x(e)&&(c.disconnect(),u&&clearTimeout(u),i(e))}));u=setTimeout((function(){c.disconnect(),a(J(t))}),r),c.observe(n,z)}))}(r,o,e,t,n):function(e){return"visible"===e.visibilityState}(o)?function(e,n,t,r){return Q((function(o,i){!function t(){var i=r(n);x(i)?o(i):e.requestAnimationFrame(t)}(),setTimeout((function(){i(J(n))}),t)}))}(r,e,t,n):function(e,n,t){return Q((function(r,o){!function n(){var o=t(e);x(o)?r(o):setTimeout(n,100)}(),setTimeout((function(){o(J(e))}),n)}))}(e,t,n)},X=function(e){var n=e.parentNode;return n?n.removeChild(e):null},Y={name:"Adobe Alloy"},W={style:{display:"none",width:0,height:0}},K=function(e){return g(e)&&0===Object.keys(e).length},$=function e(n,t){return p(n)||!g(n)?n:Object.keys(n).reduce((function(r,o){var i=n[o];if(g(i)){var a=e(i,t);return K(a)?r:Xu(Xu({},r),{},Qu({},o,a))}return t(i)?Xu(Xu({},r),{},Qu({},o,i)):r}),{})},Z=function(e,n){return Array.prototype.concat.apply([],e.map(n))},ee="com.adobe.alloy.",ne=ee+"getTld",te="kndctr",re=function(e){return e.replace("@","_")},oe=function(e,n){return te+"_"+re(e)+"_"+n},ie=function(e,n){var t={};return e.forEach((function(e){var r=n(e);t[r]||(t[r]=[]),t[r].push(e)})),t},ae=function(e){var n=e.orgId,t=oe(n,"identity");return function(){return Boolean(h.get(t))}},ue=function(e,n,t){return{getItem:function(r){try{return e[n].getItem(t+r)}catch(e){return null}},setItem:function(r,o){try{return e[n].setItem(t+r,o),!0}catch(e){return!1}},clear:function(){try{return Object.keys(e[n]).forEach((function(r){_(r,t)&&e[n].removeItem(r)})),!0}catch(e){return!1}}}},ce=function(e){return function(n){var t=ee+n;return{session:ue(e,"sessionStorage",t),persistent:ue(e,"localStorage",t)}}},se=function(e){return"boolean"==typeof e},de=function(e){return"number"==typeof e&&!isNaN(e)},le=function(e){var n=parseInt(e,10);return de(n)&&e===n},fe=function(e){return"string"==typeof e},pe=function(e){return fe(e)&&e.length>0},ge=function(){},me=function(e,n,t){var r=String(e),o=String(t);if(r.length>=n||0===o.length)return r;for(var i=n-r.length;i>o.length;)o+=o;return o.slice(0,i)+r},ve=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e){for(var t={key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:/?#]*)(?::(\d*))?))?((((?:[^?#/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@/]*@)([^:/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#/]*\.[^?#/.]+(?:[?#]|$)))*\/?)?([^?#/]*))(?:\?([^#]*))?(?:#(.*))?)/}},r=t.parser[n.strictMode?"strict":"loose"].exec(e),o={},i=14;i--;)o[t.key[i]]=r[i]||"";return o[t.q.name]={},o[t.key[12]].replace(t.q.parser,(function(e,n,r){n&&(o[t.q.name][n]=r)})),o}},he=Vu(ve),ye=function(e){var n={},t=e.split(".");switch(t.length){case 1:n.subdomain="",n.domain=e,n.topLevelDomain="";break;case 2:n.subdomain="",n.domain=e,n.topLevelDomain=t[1];break;case 3:n.subdomain="www"===t[0]?"":t[0],n.domain=e,n.topLevelDomain=t[2];break;case 4:n.subdomain="www"===t[0]?"":t[0],n.domain=e,n.topLevelDomain=t[2]+"."+t[3]}return n},be=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ye;fe(e)||(e="");var t=he(e)||{},r=t.host,o=void 0===r?"":r,i=t.path,a=void 0===i?"":i,u=t.query,c=void 0===u?"":u,s=t.anchor;return Xu({path:a,query:c,fragment:void 0===s?"":s},n(o))},we=function(e){if(p(e)||"object"!==Zu(e))return null;var n=$(e,(function(e){return!p(e)&&(!!se(e)||(!!de(e)||(!!pe(e)||!!x(e))))}));return K(n)?null:n},Ee={},Ie=function(e){switch(Zu(e)){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};Ee.decode=Ee.parse=function(e,n,t,r){n=n||"&",t=t||"=";var o={};if("string"!=typeof e||0===e.length)return o;var i=/\+/g;e=e.split(n);var a=1e3;r&&"number"==typeof r.maxKeys&&(a=r.maxKeys);var u=e.length;a>0&&u>a&&(u=a);for(var c=0;c=0?(s=p.substr(0,g),d=p.substr(g+1)):(s=p,d=""),l=decodeURIComponent(s),f=decodeURIComponent(d),tc(o,l)?Array.isArray(o[l])?o[l].push(f):o[l]=[o[l],f]:o[l]=f}return o},Ee.encode=Ee.stringify=function(e,n,t,r){return n=n||"&",t=t||"=",null===e&&(e=void 0),"object"===Zu(e)?Object.keys(e).map((function(r){var o=encodeURIComponent(Ie(r))+t;return Array.isArray(e[r])?e[r].map((function(e){return o+encodeURIComponent(Ie(e))})).join(n):o+encodeURIComponent(Ie(e[r]))})).join(n):r?encodeURIComponent(Ie(r))+t+encodeURIComponent(Ie(e)):""};for(var Ce,Se=Ee,ke={parse:function(e){return"string"==typeof e&&(e=e.trim().replace(/^[?#&]/,"")),Se.parse(e)},stringify:function(e){return Se.stringify(e)}},Te=Vu(ke),De=function(e){return e instanceof Error?e:new Error(e)},Pe=function(e){var n=e.error,t=e.message;try{n.message=t}catch(e){}},Re=function(e){var n=e.error,t=e.message,r=De(n),o=t+"\nCaused by: "+r.message;return Pe({error:r,message:o}),r},Oe=function(e,n){if(de(e)||fe(e)){var t=Math.round(Number(e));if(!isNaN(t))return t}return n},Ae=[],Ne=0;Ne<256;++Ne)Ae.push((Ne+256).toString(16).slice(1));var Me=new Uint8Array(16),xe={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},qe=function(e){return function(n,t){return null==n?n:e.call(this,n,t)}},je=function(e,n){return function(t,r){return n.call(this,e.call(this,t,r),r)}},Le=function(e,n,t){return f(je(e,n),e,t)},_e=function(e,n,t){return f(je(e,qe(n)),e,t)},Ue=function(e,n,t){return f((r=qe(n),o=e,function(e,n){var t=this,i=[],a=[r,o].reduce((function(e,r){try{return r.call(t,e,n)}catch(n){return i.push(n),e}}),e);if(i.length)throw new Error(i.join("\n"));return a}),e,t);var r,o},Fe=function(e,n,t,r){if(!e)throw new Error("'"+t+"': Expected "+r+", but got "+JSON.stringify(n)+".")},Be=function(e,n){return Fe(se(e),e,n,"true or false"),e},He=function(e,n){return Fe(M(e),e,n,"a function"),e},Ve=function(e,n){return function(t,r){return Fe(t>=n,t,r,e+" greater than or equal to "+n),t}},ze=function(e){return function(n,t){return g(n)?Fe(!K(n),n,t,e):Fe(n.length>0,n,t,e),n}},Je=function(){return function(e,n){Fe(function(e){for(var n=Object.create(null),t=0;t0&&void 0!==arguments[0]?arguments[0]:"This field has been deprecated";return function(n,t){var r=e;return void 0!==n&&(t&&(r="'"+t+"': "+r),this&&this.logger&&this.logger.warn(r)),n}}(e))};var en=function(){return _e(this,Ge)},nn=function(e){return _e(this,Ve("an integer",e))},tn=function(e){return _e(this,Ve("a number",e))},rn=function(e){return _e(this,(n="a number",t=e,function(e,r){return Fe(e<=t,e,r,n+" less than or equal to "+t),e}));var n,t},on=function(){return _e(this,Xe,{minimum:nn})},an=function(){return _e(this,ze("a non-empty string"))},un=function(){return _e(this,ze("a non-empty array"))},cn=function(){return _e(this,ze("a non-empty object"))},sn=function(){return _e(this,We)},dn=function(e){return _e(this,function(e){return function(n,t){return Fe(e.test(n),n,t,"does not match the "+e.toString()),n}}(e))},ln=function(){return _e(this,function(){var e=[];return function(n,t){return Fe(-1===e.indexOf(n),n,t,"a unique value across instances"),e.push(n),n}}())},fn=function(){return _e(this,Je())},pn=function e(n){return{noUnknownFields:function(){return _e(this,function(e){return function(n,t){var r=[];if(Object.keys(n).forEach((function(n){if(!e[n]){var o=t?t+"."+n:n;r.push("'"+o+"': Unknown field.")}})),r.length)throw new Error(r.join("\n"));return n}}(n))},nonEmpty:cn,concat:function(t){var r=Xu(Xu({},n),t.schema);return _e(this,t,e(r))},renamed:function(e,n,t){return Ue(this,function(e,n,t){return function(r,o){Fe(g(r),r,o,"an object");var i=r[e],a=r[t],u=Yu(r,[e,t].map($u)),c=n(i,o);if(void 0!==c){var s="The field '"+e+"' is deprecated. Use '"+t+"' instead.";if(o&&(s="'"+o+"': "+s),void 0!==a&&a!==c)throw new Error(s);this&&this.logger&&this.logger.warn(s)}return Xu(Qu({},t,a||c),u)}}(e,n,t))},schema:n}},gn=function(e,n){return Le(this,function(e,n){return function(t,r){var o,i=this,a=T(e,(function(e){try{return o=e.call(i,t,r),!0}catch(e){return!1}}));return Fe(a,t,r,n),o}}(e,n))}.bind(Ze),mn=function(){return this}.bind(Ze),vn=function(e){return _e(this,function(e){return function(n,t){var r=this;Fe(Array.isArray(n),n,t,"an array");var o=[],i=n.map((function(i,a){try{return e.call(r,i,t+"["+a+"]",n)}catch(e){return void o.push(e.message)}}));if(o.length)throw new Error(o.join("\n"));return i}}(e),{nonEmpty:un,uniqueItems:fn})}.bind(Ze),hn=function(){return _e(this,Be)}.bind(Ze),yn=function(){return _e(this,He)}.bind(Ze),bn=function(e){return _e(this,function(e){return function(n,t){return Fe(n===e,n,t,""+e),n}}(e))}.bind(Ze),wn=function(){return _e(this,Ye,{minimum:tn,maximum:rn,integer:on,unique:ln})}.bind(Ze),En=function(e){return _e(this,(n=e,function(e,t){var r=this;Fe(g(e),e,t,"an object");var o=[],i={};if(Object.keys(e).forEach((function(a){var u=e[a],c=t?t+"."+a:a;try{var s=n.call(r,u,c);void 0!==s&&(i[a]=s)}catch(e){o.push(e.message)}})),o.length)throw new Error(o.join("\n"));return i}),{nonEmpty:cn});var n}.bind(Ze),In=function(e){return _e(this,function(e){return function(n,t){var r=this;Fe(g(n),n,t,"an object");var o=[],i={};if(Object.keys(e).forEach((function(a){var u=n[a],c=e[a],s=t?t+"."+a:a;try{var d=c.call(r,u,s);void 0!==d&&(i[a]=d)}catch(e){o.push(e.message)}})),Object.keys(n).forEach((function(e){Object.prototype.hasOwnProperty.call(i,e)||(i[e]=n[e])})),o.length)throw new Error(o.join("\n"));return i}}(e),pn(e))}.bind(Ze),Cn=function(){return _e(this,$e,{regexp:sn,domain:en,nonEmpty:an,unique:ln,matches:dn})}.bind(Ze),Sn=function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&void 0!==arguments[1]?arguments[1]:{},a=(t=Object.keys(n),r=Object.keys(i),t.filter((function(e){return o(r,e)})));if(a.length)throw new Error("[ComponentRegistry] Could not register "+e+" because it has existing command(s): "+a.join(","));Object.keys(i).forEach((function(t){var r=i[t];r.commandName=t,r.run=Nn(r.run,"["+e+"] An error occurred while executing the "+t+" command."),n[t]=r}))};return{register:function(n,o){var i=o.commands,a=o.lifecycle;r(n,i),function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Object.keys(n).forEach((function(r){t[r]=t[r]||[],t[r].push(Nn(n[r],"["+e+"] An error occurred while executing the "+r+" lifecycle hook."))}))}(n,a),e[n]=o},getCommand:function(e){return n[e]},getCommandNames:function(){return Object.keys(n)},getLifecycleCallbacks:function(e){return t[e]||[]},getComponentNames:function(){return Object.keys(e)}}},xn="in",qn="out",jn="pending",Ln="general",_n="declinedConsent",Un="default",Fn="initial",Bn="new",Hn=function(e){var n=new Error(e);return n.code=_n,n.message=e,n},Vn=function(e){var n=e.logger,t=[],r=function(){return Promise.resolve()},o=function(){return Promise.resolve()},i=function(){return Promise.reject(Hn("No consent preferences have been set."))},a=function(){return Promise.reject(Hn("The user declined consent."))},u=function(e){if(e)return Promise.reject(new Error("Consent is pending."));var n=S();return t.push(n),n.promise};return{in:function(e){e===Un?this.awaitConsent=r:(e===Fn?n.info("Loaded user consent preferences. The user previously consented."):e===Bn&&this.awaitConsent!==o&&n.info("User consented."),function(){for(;t.length;)t.shift().resolve()}(),this.awaitConsent=o)},out:function(e){e===Un?(n.warn("User consent preferences not found. Default consent of out will be used."),this.awaitConsent=i):(e===Fn?n.warn("Loaded user consent preferences. The user previously declined consent."):e===Bn&&this.awaitConsent!==a&&n.warn("User declined consent."),function(){for(;t.length;)t.shift().reject(Hn("The user declined consent."))}(),this.awaitConsent=a)},pending:function(e){e===Un&&n.info("User consent preferences not found. Default consent of pending will be used. Some commands may be delayed."),this.awaitConsent=u},awaitConsent:function(){return Promise.reject(new Error("Consent has not been initialized."))},withConsent:function(){return this.awaitConsent(!0)},current:function(){switch(this.awaitConsent){case r:return{state:"in",wasSet:!1};case o:return{state:"in",wasSet:!0};case i:return{state:"out",wasSet:!1};case a:return{state:"out",wasSet:!0};case u:return{state:"pending",wasSet:!1};default:return{state:"in",wasSet:!1}}}}},zn=function(e){return e&&e._experience&&e._experience.decisioning&&x(e._experience.decisioning.propositions)?e._experience.decisioning.propositions:[]},Jn=function(){var e,n,t={},r=!1,o=!1,i=!0,a=function(e){if(o)throw new Error(e+" cannot be called after event is finalized.")},u={hasQuery:function(){return Object.prototype.hasOwnProperty.call(this.getContent(),"query")},getContent:function(){var r=JSON.parse(JSON.stringify(t));return e&&b(r,{xdm:e}),n&&b(r,{data:n}),r},setUserXdm:function(n){a("setUserXdm"),e=n},setUserData:function(e){a("setUserData"),n=e},mergeXdm:function(e){a("mergeXdm"),e&&b(t,{xdm:e})},mergeData:function(e){a("mergeData"),e&&b(t,{data:e})},mergeMeta:function(e){a("mergeMeta"),e&&b(t,{meta:e})},mergeQuery:function(e){a("mergeQuery"),e&&b(t,{query:e})},documentMayUnload:function(){r=!0},finalize:function(r){if(!o){var a=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:k;return e.filter((function(t,r){return function(e,n,t){for(var r=0;r0&&(t.xdm._experience.decisioning.propositions=a),n&&u.mergeData(n),o=!0,r){i=!1;var c={xdm:t.xdm||{},data:t.data||{}},s=r(c);i=!1!==s,t.xdm=c.xdm||{},t.data=c.data||{},K(t.xdm)&&delete t.xdm,K(t.data)&&delete t.data}}},getDocumentMayUnload:function(){return r},isEmpty:function(){return K(t)&&(!e||K(e))&&(!n||K(n))},shouldSend:function(){return i},getViewName:function(){if(e&&e.web&&e.web.webPageDetails)return e.web.webPageDetails.viewName},toJSON:function(){if(!o)throw new Error("toJSON called before finalize");return t}};return u},Qn="configure",Gn="setDebug",Xn=function(e){var n,t=e.logger,r=e.configureCommand,o=e.setDebugCommand,i=e.handleError,a=e.validateCommandOptions;return function(e){var u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(i){var c=function(e,i){var u;if(e===Qn){if(n)throw new Error("The library has already been configured and may only be configured once.");u=function(){return(n=r(i)).then((function(){}))}}else{if(!n)throw new Error("The library must be configured first. Please do so by executing the configure command.");u=e===Gn?function(){return o(i)}:function(){return n.then((function(n){var t=n.getCommand(e);if(!t||!M(t.run)){var r=[Qn,Gn].concat(n.getCommandNames()).join(", ");throw new Error("The "+e+" command does not exist. List of available commands: "+r+".")}var o=a({command:t,options:i});return t.run(o)}),(function(){return t.warn("An error during configuration is preventing the "+e+" command from executing."),new Promise((function(){}))}))}}return u}(e,u);t.logOnBeforeCommand({commandName:e,options:u}),i(c())})).catch((function(n){return i(n,e+" command")})).catch((function(n){throw t.logOnCommandRejected({commandName:e,options:u,error:n}),n})).then((function(n){var r=g(n)?n:{};return t.logOnCommandResolved({commandName:e,options:u,result:r}),r}))}},Yn=function(e){var n=e.command,t=e.options,r=n.commandName,o=n.documentationUri,i=void 0===o?"https://adobe.ly/3sHgQHb":o,a=n.optionsValidator,u=t;if(a)try{u=a(t)}catch(e){throw new Error("Invalid "+r+" command options:\n\t - "+e+" For command documentation see: "+i)}return u},Wn=["xdm","data","documentUnloading","type","mergeId","datasetId","edgeConfigOverrides"],Kn=function(e){var n=e.eventManager,t=e.logger;return{commands:{sendEvent:{documentationUri:"https://adobe.ly/3GQ3Q7t",optionsValidator:function(e){return function(e){var n=e.options;return In({type:Cn(),xdm:In({eventType:Cn(),identityMap:kn}),data:In({}),documentUnloading:hn(),renderDecisions:hn(),decisionScopes:vn(Cn()).uniqueItems(),personalization:In({decisionScopes:vn(Cn()).uniqueItems(),surfaces:vn(Cn()).uniqueItems(),sendDisplayEvent:hn().default(!0),includeRenderedPropositions:hn().default(!1),defaultPersonalizationEnabled:hn(),decisionContext:In({})}).default({sendDisplayEvent:!0}),datasetId:Cn(),mergeId:Cn(),edgeConfigOverrides:Tn,initializePersonalization:hn()}).required().noUnknownFields()(n)}({options:e})},run:function(e){var r=e.xdm,o=e.data,i=e.documentUnloading,a=e.type,u=e.mergeId,c=e.datasetId,s=e.edgeConfigOverrides,d=Yu(e,Wn),l=n.createEvent();return i&&l.documentMayUnload(),l.setUserXdm(r),l.setUserData(o),a&&l.mergeXdm({eventType:a}),u&&l.mergeXdm({eventMergeId:u}),s&&(d.edgeConfigOverrides=s),c&&(t.warn("The 'datasetId' option has been deprecated. Please use 'edgeConfigOverrides.com_adobe_experience_platform.datasets.event.datasetId' instead."),d.edgeConfigOverrides=s||{},b(d.edgeConfigOverrides,{com_adobe_experience_platform:{datasets:{event:{datasetId:c}}}})),n.sendEvent(l,d)}},applyResponse:{documentationUri:"",optionsValidator:function(e){return function(e){var n=e.options;return In({renderDecisions:hn(),responseHeaders:En(Cn().required()),responseBody:In({handle:vn(In({type:Cn().required(),payload:mn().required()})).required()}).required(),personalization:In({sendDisplayEvent:hn().default(!0),decisionContext:In({})}).default({sendDisplayEvent:!0})}).noUnknownFields()(n)}({options:e})},run:function(e){var t=e.renderDecisions,r=void 0!==t&&t,o=e.decisionContext,i=void 0===o?{}:o,a=e.responseHeaders,u=void 0===a?{}:a,c=e.responseBody,s=void 0===c?{handle:[]}:c,d=e.personalization,l=n.createEvent();return n.applyResponse(l,{renderDecisions:r,decisionContext:i,responseHeaders:u,responseBody:s,personalization:d})}}}}};Kn.namespace="DataCollector";var $n,Zn=function(e){var n=function(e){var n=e.eventManager,t=e.lifecycle,r=e.handleError;return function(e){if(e.s_fe)return Promise.resolve();var o=e.target,i=n.createEvent();return i.documentMayUnload(),t.onClick({event:i,clickedElement:o}).then((function(){return i.isEmpty()?Promise.resolve():n.sendEvent(i)})).then(ge).catch((function(e){r(e,"click collection")}))}}({eventManager:e.eventManager,lifecycle:e.lifecycle,handleError:e.handleError});document.addEventListener("click",n,!0)},et=Cn().regexp().default("\\.(exe|zip|wav|mp3|mov|mpg|avi|wmv|pdf|doc|docx|xls|xlsx|ppt|pptx)$"),nt=In({clickCollectionEnabled:hn().default(!0),clickCollection:In({internalLinkEnabled:hn().default(!0),externalLinkEnabled:hn().default(!0),downloadLinkEnabled:hn().default(!0),sessionStorageEnabled:hn().default(!1),eventGroupingEnabled:hn().default(!1),filterClickProperties:yn()}).default({internalLinkEnabled:!0,externalLinkEnabled:!0,downloadLinkEnabled:!0,sessionStorageEnabled:!1,eventGroupingEnabled:!1}),downloadLinkQualifier:et,onBeforeLinkClickSend:yn().deprecated('The field "onBeforeLinkClickSend" has been deprecated. Use "clickCollection.filterClickDetails" instead.')}),tt=function(){return null!==(arguments.length>0&&void 0!==arguments[0]?arguments[0]:document).getElementById("cppXYctnr")},rt=function(e){var n=e;return/^https?:\/\//i.test(n)||(n=window.location.protocol+"//"+e),new URL(n).hostname},ot=function(e){var n=e.config,t=e.logger,r=e.getClickedElementProperties,o=e.clickActivityStorage,i=n.clickCollectionEnabled,a=n.clickCollection;return i?function(e){var i,u,c=e.event,s=e.clickedElement,d=r({clickActivityStorage:o,clickedElement:s,config:n,logger:t}),l=d.linkType;tt()||(d.isValidLink()&&function(e,n){return n&&("download"===n&&!e.downloadLinkEnabled||"exit"===n&&!e.externalLinkEnabled||"other"===n&&!e.internalLinkEnabled)}(a,l)?t.info("Cancelling link click event due to clickCollection."+l+"LinkEnabled = false."):d.isInternalLink()&&a.eventGroupingEnabled&&(!n.onBeforeLinkClickSend||a.filterClickDetails)&&(i=window.location.hostname,u=d.linkUrl,rt(i)===rt(u))?o.save(d.properties):d.isValidLink()?(c.mergeXdm(d.xdm),c.mergeData(d.data),o.save({pageName:d.pageName,pageIDType:d.pageIDType})):d.isValidActivityMapData()&&o.save(d.properties))}:function(){}},it=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.properties,t=e.logger,r=n||{};return{get pageName(){return r.pageName},set pageName(e){r.pageName=e},get linkName(){return r.linkName},set linkName(e){r.linkName=e},get linkRegion(){return r.linkRegion},set linkRegion(e){r.linkRegion=e},get linkType(){return r.linkType},set linkType(e){r.linkType=e},get linkUrl(){return r.linkUrl},set linkUrl(e){r.linkUrl=e},get pageIDType(){return r.pageIDType},set pageIDType(e){r.pageIDType=e},get clickedElement(){return r.clickedElement},set clickedElement(e){r.clickedElement=e},get properties(){return{pageName:r.pageName,linkName:r.linkName,linkRegion:r.linkRegion,linkType:r.linkType,linkUrl:r.linkUrl,pageIDType:r.pageIDType}},isValidLink:function(){return!!(r.linkUrl&&r.linkType&&r.linkName&&r.linkRegion)},isInternalLink:function(){return this.isValidLink()&&"other"===r.linkType},isValidActivityMapData:function(){return!!r.pageName&&!!r.linkName&&!!r.linkRegion&&void 0!==r.pageIDType},get xdm(){return r.filteredXdm?r.filteredXdm:function(e){return{eventType:"web.webinteraction.linkClicks",web:{webInteraction:{name:e.linkName,region:e.linkRegion,type:e.linkType,URL:e.linkUrl,linkClicks:{value:1}}}}}(this)},get data(){return r.filteredData?r.filteredData:function(e){return{__adobe:{analytics:{contextData:{a:{activitymap:{page:e.pageName,link:e.linkName,region:e.linkRegion,pageIDType:e.pageIDType}}}}}}}(this)},applyPropertyFilter:function(e){e&&!1===e(r)&&(t&&t.info("Clicked element properties were rejected by filter function: "+JSON.stringify(this.properties,null,2)),r={})},applyOptionsFilter:function(e){var n=this.options;if(n&&n.clickedElement&&(n.xdm||n.data)){if(e&&!1===e(n))return t&&t.info("Clicked element properties were rejected by filter function: "+JSON.stringify(this.properties,null,2)),void(this.options=void 0);this.options=n,r.filteredXdm=n.xdm,r.filteredData=n.data}},get options(){var e={};if(this.isValidLink()&&(e.xdm=this.xdm),this.isValidActivityMapData()&&(e.data=this.data),this.clickedElement&&(e.clickedElement=this.clickedElement),e.xdm||e.data)return e},set options(e){r={},e&&function(e,n){var t=e.xdm,r=e.data,o=e.clickedElement;if(n.clickedElement=o,t&&t.web&&t.web.webInteraction){var i=t.web.webInteraction,a=i.name,u=i.region,c=i.type,s=i.URL;n.linkName=a,n.linkRegion=u,n.linkType=c,n.linkUrl=s}if(r&&r.__adobe&&r.__adobe.analytics){var d=r.__adobe.analytics.contextData;if(d&&d.a&&d.a.activitymap){var l=d.a.activitymap,f=l.page,p=l.link,g=l.region,m=l.pageIDType;n.pageName=f||n.pageName,n.linkName=p||n.linkName,n.linkRegion=g||n.linkRegion,void 0!==m&&(n.pageIDType=m)}}}(e,r)}}},at="clickData",ut=function(e){return e&&e.replace(/\s+/g," ").trim()},ct=/^(SCRIPT|STYLE|LINK|CANVAS|NOSCRIPT|#COMMENT)$/i,st=function e(n){var t=[],r=!1;(function(e){return!(e&&e.nodeName&&e.nodeName.match(ct))})(n)?(t.push(n),n.childNodes&&Array.prototype.slice.call(n.childNodes).forEach((function(n){var o=e(n);t=t.concat(o.supportedNodes),r=r||o.includesUnsupportedNodes}))):r=!0;return{supportedNodes:t,includesUnsupportedNodes:r}},dt=function(e,n,t){var r;return t&&t!==e.nodeName.toUpperCase()||(r=e.getAttribute(n)),r},lt=/^(HEADER|MAIN|FOOTER|NAV)$/i,ft=function(e){var n;return"region"===e.role&&pe(e["aria-label"])&&(n=e["aria-label"]),n},pt=function(e){var n;return e&&e.nodeName&&e.nodeName.match(lt)&&(n=e.nodeName),n},gt=function(e){return!(!e.href||"A"!==e.tagName&&"AREA"!==e.tagName||e.onclick&&e.protocol&&!(e.protocol.toLowerCase().indexOf("javascript")<0))},mt=function(e){return!!e&&!!e.onclick},vt=function(e){if("INPUT"===e.tagName){var n=e.getAttribute("type");if("submit"===n)return!0;if("image"===n&&e.src)return!0}return!1},ht=function(e){return"BUTTON"===e.tagName&&"submit"===e.type},yt=function(e){var n=e.indexOf("?"),t=e.indexOf("#");return n>=0&&(n=0?e.substring(0,t):e},bt=function(e){var n=e.window,t=e.getLinkName,r=e.getLinkRegion,o=e.getAbsoluteUrlFromAnchorElement,i=e.findClickableElement,a=e.determineLinkType;return function(e){var u=e.clickedElement,c=e.config,s=e.logger,d=e.clickActivityStorage,l=c.onBeforeLinkClickSend,f=c.clickCollection.filterClickDetails,p=it({logger:s});if(u){var g=i(u);if(g){p.clickedElement=u,p.linkUrl=o(n,g),p.linkType=a(n,c,p.linkUrl,g),p.linkRegion=r(g),p.linkName=t(g),p.pageIDType=0,p.pageName=n.location.href;var m=d.load();m&&m.pageName&&(p.pageName=m.pageName,p.pageIDType=1),f?p.applyPropertyFilter(f):l&&p.applyOptionsFilter(l)}}return p}}({window:window,getLinkName:function(e){var n=ut(e.innerText||e.textContent),t=st(e);if(!n||t.includesUnsupportedNodes){var r=function(e){var n={texts:[]};return e.supportedNodes.forEach((function(e){e.getAttribute&&(n.alt||(n.alt=ut(e.getAttribute("alt"))),n.title||(n.title=ut(e.getAttribute("title"))),n.inputValue||(n.inputValue=ut(dt(e,"value","INPUT"))),n.imgSrc||(n.imgSrc=ut(dt(e,"src","IMG")))),e.nodeValue&&n.texts.push(e.nodeValue)})),n}(t);(n=ut(r.texts.join("")))||(n=r.alt||r.title||r.inputValue||r.imgSrc)}return n||""},getLinkRegion:function(e){for(var n,t=e.parentNode;t;){if(n=ut(t.id||ft(t)||pt(t)))return n;t=t.parentNode}return"BODY"},getAbsoluteUrlFromAnchorElement:function(e,n){var t=e.location,r=n.href||"";"string"!=typeof r&&(r="");var o,i=n.protocol,a=n.host;if(r&&(!(o=r)||!/^[a-z0-9]+:\/\//i.test(o))){i||(i=t.protocol?t.protocol:""),i=i?i+"//":"",a||(a=t.host?t.host:"");var u="";if("/"!==r.substring(0,1)){var c=t.pathname.lastIndexOf("/");c=c<0?0:c,u=t.pathname.substring(0,c)}r=""+i+a+u+"/"+r}return r},findClickableElement:function(e){for(var n=e;n;){if(gt(n)||mt(n)||vt(n)||ht(n))return n;n=n.parentNode}return null},determineLinkType:function(e,n,t,r){var o="other";return pe(t)&&(!function(e,n,t){var r=!1;if(n)if(t&&t.download)r=!0;else if(e){var o=new RegExp(e),i=yt(n).toLowerCase();r=o.test(i)}return r}(n.downloadLinkQualifier,t,r)?function(e,n){var t=!1;if(n&&e.location.hostname){var r=e.location.hostname.toLowerCase();t=yt(n).toLowerCase().indexOf(r)<0}return t}(e,t)&&(o="exit"):o="download"),o}}),wt=function(e){var n=e.config,t=e.eventManager,r=e.handleError,o=e.logger,i=n.clickCollection,a=ce(window)(n.orgId||""),u=function(){var e={};return{getItem:function(n){return e[n]},setItem:function(n,t){e[n]=t},removeItem:function(n){delete e[n]}}}(),c=i.sessionStorageEnabled?a.session:u;$n=function(e){var n=e.storage;return{save:function(e){var t=JSON.stringify(e);n.setItem(at,t)},load:function(){var e=null,t=n.getItem(at);return t&&(e=JSON.parse(t)),e},remove:function(){n.removeItem(at)}}}({storage:c});var s=ot({config:n,logger:o,clickActivityStorage:$n,getClickedElementProperties:bt}),d=function(e){var n=e.clickActivityStorage;return function(e){if(!tt()){var t=n.load(),r=it({properties:t});if(r.isValidLink()||r.isValidActivityMapData()){if(r.isValidLink()){var o=r.xdm;delete o.eventType,e.mergeXdm(o)}r.isValidActivityMapData()&&e.mergeData(r.data),n.save({pageName:r.pageName,pageIDType:r.pageIDType})}}}}({clickActivityStorage:$n}),l=function(e){var n=e.clickActivityStorage;return function(e){n.save({pageName:e.getContent().xdm.web.webPageDetails.name,pageIDType:1})}}({clickActivityStorage:$n});return{lifecycle:{onComponentsRegistered:function(e){var n=e.lifecycle;Zn({eventManager:t,lifecycle:n,handleError:r})},onClick:function(e){var n=e.event,t=e.clickedElement;s({event:n,clickedElement:t})},onBeforeEvent:function(e){var n=e.event;(function(e){var n=e.getContent();return void 0!==n.xdm&&void 0!==n.xdm.web&&void 0!==n.xdm.web.webPageDetails&&void 0!==n.xdm.web.webPageDetails.name})(n)&&(i.eventGroupingEnabled&&d(n),l(n,o,$n))}}}};wt.namespace="ActivityCollector",wt.configValidators=nt,wt.buildOnInstanceConfiguredExtraParams=function(e){var n=e.config,t=e.logger;return{getLinkDetails:function(e){return bt({clickActivityStorage:$n,clickedElement:e,config:n,logger:t}).properties}}};var Et,It,Ct=function(e,n){return"ID sync "+(n?"succeeded":"failed")+": "+e.spec.url},St=In({thirdPartyCookiesEnabled:hn().default(!0),idMigrationEnabled:hn().default(!0)}),kt=In({namespaces:vn(bn("ECID")).nonEmpty().uniqueItems().default(["ECID"]),edgeConfigOverrides:Tn}).noUnknownFields().default({namespaces:["ECID"]}),Tt=In({url:Cn().required().nonEmpty(),edgeConfigOverrides:Tn}).required().noUnknownFields(),Dt=function(e){var n=e.logger;return new Promise((function(e,t){if(g(window.adobe)&&g(window.adobe.optIn)){var r=window.adobe.optIn;n.info("Delaying request while waiting for legacy opt-in to let Visitor retrieve ECID from server."),r.fetchPermissions((function(){r.isApproved([r.Categories.ECID])?(n.info("Received legacy opt-in approval to let Visitor retrieve ECID from server."),e()):t(new Error("Legacy opt-in was declined."))}),!0)}else e()}))},Pt=function(e){var n=e.logger,t=e.orgId,r=e.awaitVisitorOptIn;return function(){var e=function(e){var n=e.Visitor;return M(n)&&M(n.getInstance)&&n}(window);return e?r({logger:n}).then((function(){return n.info("Delaying request while using Visitor to retrieve ECID from server."),new Promise((function(r){e.getInstance(t,{}).getMarketingCloudVisitorID((function(e){n.info("Resuming previously delayed request that was waiting for ECID from Visitor."),r(e)}),!0)}))})).catch((function(e){e?n.info(e.message+", retrieving ECID from experience edge"):n.info("An error occurred while obtaining the ECID from Visitor.")})):Promise.resolve()}},Rt="ECID",Ot=function(e){e.mergeQuery({identity:{fetch:[Rt]}})},At=(Et=function(o){return(i=Qu(Qu(Qu(Qu(Qu(Qu({},n,/Edge\/([0-9\._]+)/),t,/Edg\/([0-9\.]+)/),e,/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/),"Firefox",/Firefox\/([0-9\.]+)(?:\s|$)/),"IE",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/),"Safari",/Version\/([0-9\._]+).*Safari/),function(e){for(var n=Object.keys(i),t=0;t0&&void 0!==arguments[0]?arguments[0]:{},i=e.namespaces,a=e.edgeConfigOverrides,u=Bt({payload:t(i),globalConfigOverrides:o,localConfigOverrides:a}),c=r(u);return n({request:c})}}({sendEdgeNetworkRequest:i,createIdentityRequestPayload:zt,createIdentityRequest:Vt,globalConfigOverrides:d}),m=function(e){var n=e.thirdPartyCookiesEnabled,t=e.areThirdPartyCookiesSupportedByDefault;return function(e){n&&t(At(window))&&e.setUseIdThirdPartyDomain()}}({thirdPartyCookiesEnabled:s,areThirdPartyCookiesSupportedByDefault:a}),v=function(e){var n=e.getLegacyEcid,t=e.addEcidToPayload;return function(e){return e.hasIdentity(Rt)?Promise.resolve():n().then((function(n){n&&t(e,n)}))}}({getLegacyEcid:l.getEcid,addEcidToPayload:Nt}),y=function(e){var n=e.locationSearch,t=e.dateProvider,r=e.orgId,o=e.logger;return function(e){if(!e.hasIdentity(Rt)){var i=Te.parse(n).adobe_mc;if(void 0!==i){Array.isArray(i)&&(o.warn("Found multiple adobe_mc query string paramters, only using the last one."),i=i[i.length-1]);var a=i.split("|").reduce((function(e,n){var t=Wu(n.split("="),2),r=t[0],o=t[1];return e[r]=o,e}),{}),u=parseInt(a.TS,10),c=a.MCMID,s=decodeURIComponent(a.MCORGID);t().getTime()/1e3<=u+300&&s===r&&c?(o.info("Found valid ECID identity "+c+" from the adobe_mc query string parameter."),e.addIdentity(Rt,{id:c})):o.info("Detected invalid or expired adobe_mc query string parameter.")}}}}({locationSearch:window.document.location.search,dateProvider:function(){return new Date},orgId:c,logger:t}),b=function(e){var n=e.doesIdentityCookieExist,t=e.orgId,r=e.logger;return function(e){var o=e.onResponse,i=e.onRequestFailure;return new Promise((function(e,a){o((function(){n()?e():(r.warn("Identity cookie not found. This could be caused by any of the following issues:\n\t* The org ID "+t+" configured in Alloy doesn't match the org ID specified in the edge configuration.\n\t* Experience edge was not able to set the identity cookie due to domain or cookie restrictions.\n\t* The request was canceled by the browser and not fully processed."),a(new Error("Identity cookie not found.")))})),i((function(){n()?e():a(new Error("Identity cookie not found."))}))}))}}({doesIdentityCookieExist:p,orgId:c,logger:t}),w=function(e){var n,t=e.doesIdentityCookieExist,r=e.setDomainForInitialIdentityPayload,o=e.addLegacyEcidToPayload,i=e.awaitIdentityCookie,a=e.logger,u=function(e){return r(e),o(e.getPayload())};return function(e){var r=e.request,o=e.onResponse,c=e.onRequestFailure;if(t())return r.setIsIdentityEstablished(),Promise.resolve();if(n){a.info("Delaying request while retrieving ECID from server.");var s=n;return n=s.catch((function(){return i({onResponse:o,onRequestFailure:c})})),s.then((function(){a.info("Resuming previously delayed request."),r.setIsIdentityEstablished()})).catch((function(){return u(r)}))}return(n=i({onResponse:o,onRequestFailure:c})).catch((function(){})),u(r)}}({doesIdentityCookieExist:p,setDomainForInitialIdentityPayload:m,addLegacyEcidToPayload:v,awaitIdentityCookie:b,logger:t}),E=function(e){var n=e.fireReferrerHideableImage,t=e.logger;return function(e){var r=e.filter((function(e){return"url"===e.type}));return r.length?Promise.all(r.map((function(e){return n(e.spec).then((function(){t.info(Ct(e,!0))})).catch((function(){t.error(Ct(e,!1))}))}))).then(ge):Promise.resolve()}}({fireReferrerHideableImage:o,logger:t}),C=function(e){var n=e.processIdSyncs;return function(e){return n(e.getPayloadsByType("identity:exchange"))}}({processIdSyncs:E}),S=function(e){var n=e.dateProvider,t=e.orgId;return function(e,r){var o=Math.round(n().getTime()/1e3),i=encodeURIComponent("TS="+o+"|MCMID="+e+"|MCORGID="+encodeURIComponent(t)),a=Wu(r.match(Jt),4),u=a[1],c=a[2],s=a[3],d=function(e){return""===e?"?":"?"===e?"":"&"}(c);return""+u+c+d+"adobe_mc="+i+s}}({dateProvider:function(){return new Date},orgId:c,globalConfigOverrides:d});return function(e){var n,t=e.addEcidQueryToPayload,r=e.addQueryStringIdentityToPayload,o=e.ensureSingleIdentity,i=e.setLegacyEcid,a=e.handleResponseForIdSyncs,u=e.getEcidFromResponse,c=e.getIdentity,s=e.consent,d=e.appendIdentityToUrl,l=e.logger,p={};return{lifecycle:{onBeforeRequest:function(e){var n=e.request,i=e.onResponse,a=e.onRequestFailure;return t(n.getPayload()),r(n.getPayload()),o({request:n,onResponse:i,onRequestFailure:a})},onResponse:function(e){var t=e.response;return n||(n=u(t))&&i(n),p=f(p,t.getEdge()),a(t)}},commands:{getIdentity:{optionsValidator:kt,run:function(e){return s.awaitConsent().then((function(){return n?void 0:c(e)})).then((function(){return{identity:{ECID:n},edge:p}}))}},appendIdentityToUrl:{optionsValidator:Tt,run:function(e){return s.withConsent().then((function(){return n?void 0:c(e)})).then((function(){return{url:d(n,e.url)}})).catch((function(n){return l.warn("Unable to append identity to url. "+n.message),e}))}}}}}({addEcidQueryToPayload:Ot,addQueryStringIdentityToPayload:y,ensureSingleIdentity:w,setLegacyEcid:l.setEcid,handleResponseForIdSyncs:C,getEcidFromResponse:Mt,getIdentity:g,consent:r,appendIdentityToUrl:S,logger:t,config:n})};Qt.namespace="Identity",Qt.configValidators=St;var Gt=function(e){var n=e.fireReferrerHideableImage,t=e.logger,r=e.cookieJar,o=e.isPageSsl?{sameSite:"none",secure:!0}:{};return function(e){return function(e){e.filter((function(e){return"cookie"===e.type})).forEach((function(e){var n=e.spec,t=n.name,i=n.value,a=n.domain,u=n.ttlDays;r.set(t,i||"",Xu({domain:a||"",expires:u||10},o))}))}(e),function(e){var r=e.filter((function(e){return"url"===e.type}));return Promise.all(r.map((function(e){return n(e.spec).then((function(){t.info(function(e){return"URL destination succeeded: "+e.spec.url}(e))})).catch((function(){}))}))).then(ge)}(e)}},Xt=function(e){var n=e.processDestinations;return function(e){var t,r,o=e.response;return(t={response:o},r=t.response.getPayloadsByType("activation:push"),n(r)).then((function(){return{destinations:{response:o}.response.getPayloadsByType("activation:pull")}}))}},Yt=function(e){var n=e.logger,t=e.fireReferrerHideableImage,r=h.withConverter({write:function(e){return encodeURIComponent(e)}}),o=I({logger:n,cookieJar:r}),i=Gt({fireReferrerHideableImage:t,logger:n,cookieJar:o,isPageSsl:"https:"===window.location.protocol});return{lifecycle:{onResponse:Xt({processDestinations:i})},commands:{}}};Yt.namespace="Audiences";var Wt="web",Kt="://",$t=/^(\w+):\/\/([^/#]+)(\/[^#]*)?(#.*)?$/,Zt=/^(?:.*@)?(?:[a-z\d\u00a1-\uffff.-]+|\[[a-f\d:]+])(?::\d+)?$/,er=/^\/(?:[/\w\u00a1-\uffff-.~]|%[a-fA-F\d]{2})*$/,nr=/^#(?:[/\w\u00a1-\uffff-.~]|%[a-fA-F\d]{2})+$/,tr=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/",n=e.length;n>0&&-1!=="/".indexOf(e.charAt(n-1));)n-=1;return e.substring(0,n)||"/"},rr=function(e){return""+e.surfaceType+Kt+e.authority+(e.path||"")+(e.fragment||"")},or=function(e){var n=e(),t=n.host.toLowerCase(),r=n.pathname;return Wt+Kt+t+tr(r)},ir=function(e,n,t){var r=function(e){return t.warn(e),null};if(!pe(e))return r("Invalid surface: "+e);var i,a,u,c,s=function(e,n){return _(e,"#")?or(n)+e:e}(e,n),d=(c=s.match($t))?{surfaceType:(u=c[1],pe(u)?u.toLowerCase():""),authority:(a=c[2],pe(a)?a.toLowerCase():""),path:(i=c[3],pe(i)?tr(i):"/"),fragment:c[4]}:null;return null===d?r("Invalid surface: "+e):o([Wt,"webapp"],d.surfaceType)?d.authority&&Zt.test(d.authority)?d.path&&!er.test(d.path)?r("Invalid path "+d.path+" in surface: "+e):d.fragment&&!nr.test(d.fragment)?r("Invalid fragment "+d.fragment+" in surface: "+e):d:r("Invalid authority "+d.authority+" in surface: "+e):r("Unsupported surface type "+d.surfaceType+" in surface: "+e)},ar=function(e){return!!e&&0===e.indexOf(Wt+Kt)&&-1===e.indexOf("#")},ur="__view__",cr="https://ns.adobe.com/personalization/default-content-item",sr="https://ns.adobe.com/personalization/dom-action",dr="https://ns.adobe.com/personalization/html-content-item",lr="https://ns.adobe.com/personalization/json-content-item",fr="https://ns.adobe.com/personalization/ruleset-item",pr="https://ns.adobe.com/personalization/redirect-item",gr="https://ns.adobe.com/personalization/message/in-app",mr=function(e){return e.filter((function(n,t){return e.indexOf(n)===t}))},vr=function(e){var n=e.getPageLocation,t=e.renderDecisions,r=e.decisionScopes,i=e.personalization,a=e.event,u=e.isCacheInitialized,c=e.logger,s=a.getViewName();return{isRenderDecisions:function(){return t},isSendDisplayEvent:function(){return!!i.sendDisplayEvent},shouldIncludeRenderedPropositions:function(){return!!i.includeRenderedPropositions},getViewName:function(){return s},hasScopes:function(){return r.length>0||x(i.decisionScopes)},hasSurfaces:function(){return x(i.surfaces)},hasViewName:function(){return pe(s)},createQueryDetails:function(){var e=Ku(r);x(i.decisionScopes)&&e.push.apply(e,Ku(i.decisionScopes));var t=function(){var e=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0;return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]).map((function(t){return ir(t,e,n)})).filter((function(e){return!p(e)})).map(rr)}(i.surfaces,n,c);this.shouldRequestDefaultPersonalization()&&(function(e){o(e,ur)||e.push(ur)}(e),function(e,n){var t=or(n);o(e,t)||e.push(t)}(t,n));var a=[cr,dr,lr,pr,fr,gr,"https://ns.adobe.com/personalization/message/feed-item"];return o(e,ur)&&a.push(sr),{schemas:a,decisionScopes:mr(e),surfaces:mr(t)}},isCacheInitialized:function(){return u},shouldFetchData:function(){return this.hasScopes()||this.hasSurfaces()||this.shouldRequestDefaultPersonalization()},shouldUseCachedData:function(){return this.hasViewName()&&!this.shouldFetchData()},shouldRequestDefaultPersonalization:function(){return i.defaultPersonalizationEnabled||!this.isCacheInitialized()&&!1!==i.defaultPersonalizationEnabled}}},hr="decisioning.propositionDisplay",yr="decisioning.propositionInteract",br="decisioning.propositionTrigger",wr="decisioning.propositionDismiss",Er={DISPLAY:"display",INTERACT:"interact",TRIGGER:"trigger",DISMISS:"dismiss"},Ir=Qu(Qu(Qu(Qu({},hr,Er.DISPLAY),yr,Er.INTERACT),br,Er.TRIGGER),wr,Er.DISMISS);Qu(Qu(Qu(Qu({},Er.DISPLAY,hr),Er.INTERACT,yr),Er.TRIGGER,br),Er.DISMISS,wr);var Cr=function(e){return Ir[e]},Sr={propositions:[]},kr=function(e){var n=e.getPageLocation,t=e.logger,r=e.fetchDataHandler,o=e.viewChangeHandler,i=e.onClickHandler,a=e.isAuthoringModeEnabled,u=e.mergeQuery,c=e.viewCache,s=e.showContainers,d=e.applyPropositions,l=e.setTargetMigration,f=e.mergeDecisionsMeta,p=e.renderedPropositions,g=e.onDecisionHandler,m=e.handleConsentFlicker;return{lifecycle:{onComponentsRegistered:function(){m()},onDecision:g,onBeforeRequest:function(e){var n=e.request;return l(n),Promise.resolve()},onBeforeEvent:function(e){var i=e.event,d=e.renderDecisions,l=e.decisionScopes,g=void 0===l?[]:l,m=e.personalization,v=void 0===m?{}:m,h=e.onResponse,y=void 0===h?ge:h,b=e.onRequestFailure,w=void 0===b?ge:b;if(y((function(){return{propositions:[]}})),w((function(){return s()})),a())return t.warn("Rendering is disabled for authoring mode."),u(i,{enabled:!1}),Promise.resolve();var E=vr({getPageLocation:n,renderDecisions:d,decisionScopes:g,personalization:v,event:i,isCacheInitialized:c.isInitialized(),logger:t}),I=[];if(E.shouldIncludeRenderedPropositions()&&I.push(p.clear()),E.shouldFetchData()){var C=c.createCacheUpdate(E.getViewName());w((function(){return C.cancel()})),r({cacheUpdate:C,personalizationDetails:E,event:i,onResponse:y})}else E.shouldUseCachedData()&&I.push(o({personalizationDetails:E,event:i,onResponse:y,onRequestFailure:w}));return Promise.all(I).then((function(e){var n=Z(e,(function(e){return e}));x(n)&&f(i,n,[Er.DISPLAY])}))},onClick:function(e){var n=e.event,t=e.clickedElement;i({event:n,clickedElement:t})}},commands:{applyPropositions:{optionsValidator:function(e){return function(e){var n=e.logger,t=e.options,r=In({propositions:vn(In({id:Cn().required(),scope:Cn().required(),scopeDetails:In({decisionProvider:Cn().required()}).required(),items:vn(In({id:Cn().required(),schema:Cn().required(),data:mn().required()})).nonEmpty().required()}).required()).nonEmpty().required(),metadata:In(mn()),viewName:Cn()}).required();try{return r(t)}catch(e){return n.warn("Invalid options for applyPropositions. No propositions will be applied.",e),Sr}}({logger:t,options:e})},run:d}}}},Tr=function(e){return P("DIV",{},{innerHTML:e})},Dr={exports:{}};Dr.exports=function(e){if(e.CSS&&e.CSS.escape)return e.CSS.escape;var n=function(e){if(0==arguments.length)throw new TypeError("`CSS.escape` requires an argument.");for(var n,t=String(e),r=t.length,o=-1,i="",a=t.charCodeAt(0);++o=1&&n<=31||127==n||0==o&&n>=48&&n<=57||1==o&&n>=48&&n<=57&&45==a?"\\"+n.toString(16)+" ":0==o&&1==r&&45==n||!(n>=128||45==n||95==n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122)?"\\"+t.charAt(o):t.charAt(o):i+="�";return i};return e.CSS||(e.CSS={}),e.CSS.escape=n,n}(u);var Pr,Rr=Vu(Dr.exports),Or=/:eq\((\d+)\)/g,Ar=function(e){return-1===e.indexOf(":eq(")},Nr=/(#|\.)(-?\w+)/g,Mr=function(e,n,t){return""+n+Rr(t)},xr=function(e){for(var n=[],t=function(e){return e.split(Or).filter(pe)}(function(e){return e.replace(Nr,Mr)}(e.trim())),r=t.length,o=0;ol-1)break;if(a1&&void 0!==arguments[1]?arguments[1]:document).getElementById(e)},Lr=function(e,n,t){e.setAttribute(n,t)},_r=function(e,n){return e.getAttribute(n)},Ur=function(e){return e.parentNode},Fr=function(e,n){if(e){var t=Ur(e);t&&t.insertBefore(n,function(e){return e.nextElementSibling}(e))}},Br=function(e,n){if(e){var t=Ur(e);t&&t.insertBefore(n,e)}},Hr=function(e){var n=e.childNodes;return n?q(n):[]},Vr=function(e){return e.firstElementChild},zr=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;if(void 0===Pr){var n=e.querySelector("[nonce]");Pr=n&&(n.nonce||n.getAttribute("nonce"))}return Pr},Jr="src",Qr=function(e){return P(R,{src:e})},Gr=function(e){H(R,e).forEach((function(e){var n=_r(e,Jr);n&&Qr(n)}))},Xr=function(e){return function(e,n){return e.tagName===n}(e,O)&&!_r(e,Jr)},Yr=function(e){var n=H(O,e),t=n.length,r=zr();if(r)for(var o=0;o=0;){var c=o[u];t(c);var s=Vr(e);s?Br(s,c):D(e,c),u-=1}return ao(e,i),uo(a)},fo="alloy-prehiding",po={},go=function(e){var n=po[e];n&&(X(n),delete po[e])},mo=function(e){if(e&&!jr(fo)){var n=zr(),t=Xu({id:fo},n&&{nonce:n}),r=P(O,t,{textContent:e});D(document.head,r)}},vo=function(){var e=jr(fo);e&&X(e)},ho=function(e,n,t){t(e),e.textContent=n},yo=function(e,n,t){var r=Tr(n);Yr(r);var o=Hr(r),i=oo(r),a=io(r);return Gr(r),o.forEach((function(n){t(n),Br(e,n)})),ao(e,i),uo(a)},bo=function(e,n,t){return yo(e,n,t).then((function(){X(e)}))},wo=function(e,n,t){var r=Tr(n);Yr(r);var o=Hr(r),i=oo(r),a=io(r);Gr(r);var u=e;return o.forEach((function(e){t(e),Fr(u,e),u=e})),ao(e,i),uo(a)},Eo=["priority"],Io=function(e,n,t){var r=n.priority,o=Yu(n,Eo);Object.keys(o).forEach((function(n){!function(e,n,t,r){var o;o=r?n+":"+t+" !"+r+";":n+":"+t+";",e.style.cssText+=";"+o}(e,n,o[n],r)})),t(e)},Co=function(e,n,t){Object.keys(n).forEach((function(t){Lr(e,t,n[t])})),t(e)},So=function(e,n,t){e.tagName===R&&(Qr(n),t(e),function(e,n){e.removeAttribute(n)}(e,Jr),Lr(e,Jr,n))},ko=function(e,n,t){var r=n.from,o=n.to,i=function(e){var n=e.children;return n?q(n):[]}(e),a=i[r],u=i[o];a&&u&&(r0&&void 0!==arguments[0]?arguments[0]:document).location.href.indexOf("adobe_authoring_enabled")},Fo=function(e,n,t,r){if(0!==n.length){var o={};t.forEach((function(e){o[e]=1}));var i={_experience:{decisioning:{propositions:n,propositionEventType:o}}};r&&(i._experience.decisioning.propositionAction=r),e.mergeXdm(i)}},Bo=function(e,n){e.mergeQuery({personalization:Xu({},n)})},Ho=function(){var e={};return{storeClickMeta:function(n){var t=n.selector,r=n.meta,o=r.id,i=r.scope,a=r.scopeDetails,u=r.trackingLabel,c=r.scopeType;e[t]||(e[t]={}),e[t][o]={scope:i,scopeDetails:a,trackingLabel:u,scopeType:c}},getClickSelectors:function(){return Object.keys(e)},getClickMetas:function(n){return e[n]?function(e){return Object.keys(e).map((function(n){return Xu({id:n},e[n])}))}(e[n]):{}}}},Vo=function(e,n){return e===lr&&n===Ao},zo=Qu(Qu(Qu(Qu({},sr,(function(){return!0})),dr,(function(){return!0})),lr,Vo),gr,(function(){return!0})),Jo=function(e){var n=e.processPropositions,t=e.createProposition,r=e.renderedPropositions,o=e.viewCache,i=function(e){var n=e.items,t=e.metadataForScope,r=void 0===t?{}:t,o=r.actionType,i=r.selector;return n.filter((function(e){return function(e,n){return"function"==typeof zo[e]&&zo[e](e,n)}(e.schema,o)})).map((function(e){var n=e.schema;return n===dr||Vo(n,o)?K(r)?void 0:Xu(Xu({},e),{},{schema:Vo(n,o)?sr:n,data:Xu(Xu({},e.data),{},{selector:i,type:o})}):Xu({},e)})).filter((function(e){return e}))},a=function(e){return!(e.scope===ur&&e.renderAttempted)};return function(e){var u=e.propositions,c=void 0===u?[]:u,s=e.metadata,d=void 0===s?{}:s,l=e.viewName,f=S();r.concat(f.promise);var p=function(e){var n=e.propositions,t=e.metadata;return n.filter(a).map((function(e){return x(e.items)?{id:e.id,scope:e.scope,scopeDetails:e.scopeDetails,items:i({items:e.items,metadataForScope:t[e.scope]})}:e})).filter((function(e){return x(e.items)}))}({propositions:c,metadata:d}).map((function(e){return t(e)}));return Promise.resolve().then((function(){return l?o.getView(l):[]})).then((function(e){var t=n([].concat(Ku(p),Ku(e))),r=t.render,o=t.returnedPropositions;return r().then(f.resolve),{propositions:o}}))}},Qo=function(e){var n=e.selector;return e.type!==Po||"BODY > *:eq(0)"!==n?e:f({},e,{selector:"BODY"})},Go=function(e){return!fe(e)||!e.trim()},Xo=function(e){var n=f({},e),t=n.content,r=n.selector;if(Go(t))return n;if(null==r)return n;var o=qr(r);return no(o[0],"HEAD")?(n.type=Ro,n.content=function(e){var n=Tr(e);return H("SCRIPT,LINK,STYLE",n).map((function(e){return e.outerHTML})).join("")}(t),n):n},Yo=function(e){var n=e.preprocess,t=e.isPageWideSurface;return function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],o=e.id,i=e.scope,a=e.scopeDetails,u=e.items,c=void 0===u?[]:u,s=(a||{}).characteristics,d=(void 0===s?{}:s).scopeType;return{getScope:function(){return i||i},getScopeType:function(){return i===ur||t(i)?"page":d===Mo?Mo:"proposition"},getItems:function(){var e=this;return c.map((function(t){return function(e,t){var r=e.id,o=e.schema,i=e.data,a=e.characteristics,u=(void 0===a?{}:a).trackingLabel,c=i?i.type:void 0,s=n(i);return{getId:function(){return r},getSchema:function(){return o},getSchemaType:function(){return c},getData:function(){return s},getProposition:function(){return t},getTrackingLabel:function(){return u},getOriginalItem:function(){return e},toString:function(){return JSON.stringify(e)},toJSON:function(){return e}}}(t,e)}))},getNotification:function(){return{id:o,scope:i,scopeDetails:a}},getId:function(){return o},toJSON:function(){return e},addToReturnValues:function(n,t,o,i){r&&(n.push(Xu(Xu({},e),{},{items:o.map((function(e){return e.getOriginalItem()})),renderAttempted:i})),i||t.push(Xu(Xu({},e),{},{items:o.map((function(e){return e.getOriginalItem()}))})))}}}},Wo=function(){return{setRenderAttempted:!0,includeInNotification:!0}},Ko="always",$o="never",Zo="decoratedElementsOnly",ei=[Ko,$o,Zo],ni="data-aep-interact-id",ti="data-aep-click-label",ri=0,oi=function(e,n,t,r,i,a,u,c){var s=u.scopeDetails;return function(e,n){return!!e&&!!e[n]&&o([Ko,Zo],e[n])}(e,(void 0===s?{}:s).decisionProvider)||n===Oo?function(e){if(e.tagName){var n,o=(n=_r(e,ni))?parseInt(n,10):++ri;c(t,r,a,u,o),Lr(e,ni,o),i&&!_r(e,ti)&&Lr(e,ti,i)}}:ge},ii=function(e){var n=e.schemaProcessors,t=e.logger,r=function(e,n){return function(){return Promise.resolve().then(e).then((function(){return t.enabled&&t.info("Action "+n.toString()+" executed."),!0})).catch((function(e){if(t.enabled){var r=e.message,o=e.stack,i="Failed to execute action "+n.toString()+". "+r+" "+o;t.warn(i)}return!1}))}},o=function(e){var t=n[e.getSchema()];return t?t(e):{}},i=function(e){for(var n,t,i,a,u=e.renderers,c=e.returnedPropositions,s=e.returnedDecisions,d=e.items,l=e.proposition,f=Ku(u),p=Ku(c),g=Ku(s),m=[],v=[],h=[],y=!1,b=!1,w=0;d.length>w;){a=d[w];var E=o(a);if(n=E.render,t=E.setRenderAttempted,i=E.includeInNotification,b=E.onlyRenderThis){p=[],g=[],t?(m=[a],v=[]):(m=[],v=[a]),f=[],h=[n],y=i;break}n&&h.push(r(n,a)),i&&(y=!0),t?m.push(a):v.push(a),w+=1}if(h.length>0){var I=y?l.getNotification():void 0;f.push((function(){return function(e,n){return Promise.all(e.map((function(e){return e()}))).then((function(e){if(e.includes(!0))return n}))}(h,I)}))}else y&&f.push((function(){return Promise.resolve(l.getNotification())}));return m.length>0&&l.addToReturnValues(p,g,m,!0),v.length>0&&l.addToReturnValues(p,g,v,!1),{renderers:f,returnedPropositions:p,returnedDecisions:g,onlyRenderThis:b}};return function(e){for(var n,t,r,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],a=[],u=[],c=[],s=0;e.length>s;){r=(t=e[s]).getItems();var d=i({renderers:a,returnedPropositions:u,returnedDecisions:c,items:r,proposition:t});if(a=d.renderers,u=d.returnedPropositions,c=d.returnedDecisions,n=d.onlyRenderThis)break;s+=1}n&&e.forEach((function(e,n){n!==s&&e.addToReturnValues(u,c,e.getItems(),!1)})),o.forEach((function(e){e.addToReturnValues(u,c,e.getItems(),!1)}));return{returnedPropositions:u,returnedDecisions:c,render:function(){return Promise.all(a.map((function(e){return e()}))).then((function(e){return e.filter((function(e){return e}))}))}}}},ai="text/html",ui=["content","contentType"],ci=["mobileParameters","webParameters","html"],si=function(e){var n=e.modules,t=e.logger;return function(e){var r=e.getData(),o=Xu({},e.getProposition().getNotification());if(!r)return t.warn("Invalid in-app message data: undefined.",r),{};var i=r.type,a=void 0===i?"defaultContent":i;return n[a]?function(e,n){for(var t=0;t0&&X(n[0])},li=function(e){return function(n){return arguments.length>1&&void 0!==arguments[1]&&arguments[1]?e.location.href=n:e.location.replace(n),new Promise((function(){}))}},fi="alloy-messaging-container",pi="alloy-overlay-container",gi="alloy-content-iframe",mi=function(){return[fi,pi].forEach(di)},vi=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:li(window);return function(t){t.preventDefault(),t.stopImmediatePropagation();var r=t.target,o="a"===r.tagName.toLowerCase()?r:r.closest("a");if(o){var i=function(e){var n={};if(!e||"a"!==e.tagName.toLowerCase())return n;var t=e.href;if(!t||!_(t,"adbinapp://"))return n;var r,o,i=t.split("?"),a=i[0].split("://")[1],u=e.innerText,c=e.getAttribute("data-uuid")||"";if(x(i)){var s=Te.parse(i[1]);r=s.interaction||"",o=decodeURIComponent(s.link||"")}return{action:a,interaction:r,link:o,label:u,uuid:c}}(o),a=i.action,u=i.interaction,c=i.link,s=i.label,d=i.uuid;e(a,{label:s,id:u,uuid:d,link:c}),"dismiss"===a&&mi(),pe(c)&&c.length>0&&n(c,!0)}}},hi=function(e){var n=e.verticalAlign,t=e.width,r=e.horizontalAlign,o=e.backdropColor,i=e.height,a=e.cornerRadius,u=e.horizontalInset,c=e.verticalInset,s=e.uiTakeover,d={width:t?t+"%":"100%",backgroundColor:o||"rgba(0, 0, 0, 0.5)",borderRadius:a?a+"px":"0px",border:"none",position:void 0!==s&&s?"fixed":"relative",overflow:"hidden"};return"left"===r?d.left=u?u+"%":"0":"right"===r?d.right=u?u+"%":"0":"center"===r&&(d.left="50%",d.transform="translateX(-50%)"),"top"===n?d.top=c?c+"%":"0":"bottom"===n?(d.position="fixed",d.bottom=c?c+"%":"0"):"center"===n&&(d.top="50%",d.transform=("center"===r?d.transform+" ":"")+"translateY(-50%)",d.display="flex",d.alignItems="center",d.justifyContent="center"),d.height=i?i+"vh":"100%",d},yi=function(e){return{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",background:"transparent",opacity:e.backdropOpacity||.5,backgroundColor:e.backdropColor||"#FFFFFF"}},bi=["enabled","parentElement","insertionMethod"],wi=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;mi();var t=e.content,r=e.contentType,i=e.mobileParameters,a=e.webParameters;if(r===ai){var u=P("div",{id:fi}),c=function(e,n){var t=(new DOMParser).parseFromString(e,ai),r=t.querySelector("script");r&&r.setAttribute("nonce",zr());var o=P("iframe",{src:URL.createObjectURL(new Blob([t.documentElement.outerHTML],{type:"text/html"})),id:gi});return o.addEventListener("load",(function(){(0,(o.contentDocument||o.contentWindow.document).addEventListener)("click",n)})),o}(t,vi(n)),s=P("div",{id:pi});(function(e){if(!e)return!1;var n=Object.keys(e);if(!o(n,fi))return!1;if(!o(n,pi))return!1;for(var t=Dn(e),r=0;r0?r:[n({scope:t,scopeDetails:{characteristics:{scopeType:Mo}},items:[{schema:cr}]},!1)]};return{createCacheUpdate:function(e){var n=S();return t=!0,r=r.then((function(e){return n.promise.then((function(n){return f({},e,n)})).catch((function(){return e}))})),{update:function(t){var r=t.filter((function(e){return e.getScope()})),i=ie(r,(function(e){return e.getScope().toLowerCase()}));return n.resolve(i),e?o(i,e):[]},cancel:function(){n.reject()}}},getView:function(e){return r.then((function(n){return o(n,e)}))},isInitialized:function(){return t}}}({createProposition:k}),D=li(window),P=Qu(Qu(Qu(Qu(Qu({},cr,Wo),sr,function(e){var n=e.modules,t=e.logger,r=e.storeInteractionMeta,o=e.storeClickMeta,i=e.autoCollectPropositionInteractions;return function(e){var a=e.getData()||{},u=a.type,c=a.selector;if(!u)return t.warn("Invalid DOM action data: missing type.",e.getData()),{setRenderAttempted:!1,includeInNotification:!1};if(u===Oo)return c?(o({selector:c,meta:Xu(Xu({},e.getProposition().getNotification()),{},{trackingLabel:e.getTrackingLabel(),scopeType:e.getProposition().getScopeType()})}),{setRenderAttempted:!0,includeInNotification:!1}):(t.warn("Invalid DOM action data: missing selector.",e.getData()),{setRenderAttempted:!1,includeInNotification:!1});if(!n[u])return t.warn("Invalid DOM action data: unknown type.",e.getData()),{setRenderAttempted:!1,includeInNotification:!1};var s=oi(i,u,e.getProposition().getId(),e.getId(),e.getTrackingLabel(),e.getProposition().getScopeType(),e.getProposition().getNotification(),r);return{render:function(){return n[u](e.getData(),s)},setRenderAttempted:!0,includeInNotification:!0}}}({modules:I,logger:a,storeInteractionMeta:m,storeClickMeta:y,autoCollectPropositionInteractions:l})),dr,function(e){var n=e.modules,t=e.logger,r=e.storeInteractionMeta,o=e.autoCollectPropositionInteractions;return function(e){var i=e.getData()||{},a=i.type;if(!i.selector||!a)return{setRenderAttempted:!1,includeInNotification:!1};if(!n[a])return t.warn("Invalid HTML content data",e.getData()),{setRenderAttempted:!1,includeInNotification:!1};var u=oi(o,a,e.getProposition().getId(),e.getId(),e.getTrackingLabel(),e.getProposition().getScopeType(),e.getProposition().getNotification(),r);return{render:function(){return n[a](e.getData(),u)},setRenderAttempted:!0,includeInNotification:!0}}}({modules:I,logger:a,storeInteractionMeta:m,autoCollectPropositionInteractions:l})),pr,function(e){var n=e.logger,t=e.executeRedirect,r=e.collect;return function(e){var o=(e.getData()||{}).content;return o?{render:function(){return r({decisionsMeta:[e.getProposition().getNotification()],documentMayUnload:!0}).then((function(){return t(o)}))},setRenderAttempted:!0,onlyRenderThis:!0}:(n.warn("Invalid Redirect data",e.getData()),{})}}({logger:a,executeRedirect:D,collect:p})),gr,si({modules:Ei(p),logger:a})),R=ii({schemaProcessors:P,logger:a}),O=(o=Promise.resolve([]),{concat:function(e){o=o.then((function(n){return e.then((function(e){return n.concat(e)})).catch((function(){return n}))}))},clear:function(){var e=o;return o=Promise.resolve([]),e}}),A=function(e,n){return function(t,r,o){if(!t)return function(){};if(!r){var i=S();return n.concat(i.promise),i.resolve}return function(n){n.length>0&&e({decisionsMeta:n,viewName:o})}}}(p,O),N=function(e){var n=e.prehidingStyle,t=e.showContainers,r=e.hideContainers,o=e.mergeQuery,i=e.processPropositions,a=e.createProposition,u=e.notificationHandler,c=e.consent;return function(e){var s=e.cacheUpdate,d=e.personalizationDetails,l=e.event,f=e.onResponse,p=c.current(),g=p.state,m=p.wasSet;"out"===g&&m||(d.isRenderDecisions()?r(n):t()),o(l,d.createQueryDetails());var v=u(d.isRenderDecisions(),d.isSendDisplayEvent(),d.getViewName());f((function(e){var n,r,o,u=e.response.getPayloadsByType("personalization:decisions").map((function(e){return a(e)})),c=ie(u,(function(e){return e.getScopeType()})),l=c.page,f=void 0===l?[]:l,p=c.view,g=void 0===p?[]:p,m=c.proposition,h=void 0===m?[]:m,y=s.update(g);if(d.isRenderDecisions()){var b=i([].concat(Ku(f),Ku(y)),h);n=b.render,r=b.returnedPropositions,o=b.returnedDecisions,n().then(v),t()}else{var w=i([],[].concat(Ku(f),Ku(y),Ku(h)));r=w.returnedPropositions,o=w.returnedDecisions}return{propositions:r,decisions:o}}))}}({prehidingStyle:d,showContainers:vo,hideContainers:mo,mergeQuery:Bo,processPropositions:R,createProposition:k,notificationHandler:A,consent:c}),M=function(e){var n=e.mergeDecisionsMeta,t=e.collectInteractions,r=e.collectClicks,o=e.getInteractionMetas,i=e.getClickMetas,a=e.getClickSelectors,u=e.autoCollectPropositionInteractions;return function(e){var c,s,d,l=e.event,f=e.clickedElement,p=[];if([t(f,o,u),r(f,a(),i)].forEach((function(e){var n=e.decisionsMeta,t=e.propositionActionLabel,r=e.propositionActionToken,o=e.viewName;Array.prototype.push.apply(p,n),!c&&t&&(c=t),!s&&r&&(s=r),!d&&o&&(d=o)})),x(p)){var g={eventType:yr};d&&(g.web={webPageDetails:{viewName:d}}),l.mergeXdm(g),n(l,p,[Er.INTERACT],function(e,n){if(n||e){var t={};return e&&(t.label=e),n&&(t.tokens=[n]),t}}(c,s))}}}({mergeDecisionsMeta:Fo,collectInteractions:Ci,collectClicks:_o,getInteractionMetas:v,getClickMetas:w,getClickSelectors:b,autoCollectPropositionInteractions:l}),q=function(e){var n=e.processPropositions,t=e.viewCache;return function(e){var r,o,i=e.personalizationDetails,a=e.onResponse,u=i.getViewName();return a((function(){return{propositions:r,decisions:o}})),t.getView(u).then((function(e){var t;if(i.isRenderDecisions()){var a=n(e);return t=a.render,r=a.returnedPropositions,o=a.returnedDecisions,t()}var u=n([],e);return r=u.returnedPropositions,o=u.returnedDecisions,[]}))}}({processPropositions:R,viewCache:T}),j=Jo({processPropositions:R,createProposition:k,renderedPropositions:O,viewCache:T}),L=function(e){return e.targetMigrationEnabled?function(e){e.getPayload().mergeMeta({target:{migration:!0}})}:ge}({targetMigrationEnabled:s}),_=function(e){var n=e.processPropositions,t=e.createProposition,r=e.notificationHandler;return function(e){var o=e.renderDecisions,i=e.propositions,a=e.event,u=e.personalization,c=void 0===u?{}:u;if(!o)return Promise.resolve();var s=c.sendDisplayEvent,d=void 0===s||s,l=a?a.getViewName():void 0,f=i.map((function(e){return t(e,!0)})),p=n(f),g=p.render,m=p.returnedPropositions,v=r(o,d,l);return g().then(v),Promise.resolve({propositions:m})}}({processPropositions:R,createProposition:k,notificationHandler:A}),U=function(e){var n=e.showContainers,t=e.consent;return function(){var e=t.current(),r=e.state,o=e.wasSet;r===qn&&o?n():t.awaitConsent().catch(n)}}({showContainers:vo,consent:c});return kr({getPageLocation:E,logger:a,fetchDataHandler:N,viewChangeHandler:q,onClickHandler:M,isAuthoringModeEnabled:Uo,mergeQuery:Bo,viewCache:T,showContainers:vo,applyPropositions:j,setTargetMigration:L,mergeDecisionsMeta:Fo,renderedPropositions:O,onDecisionHandler:_,handleConsentFlicker:U})};ki.namespace="Personalization";var Ti=ei.map((function(e){return bn(e)}));ki.configValidators=In({prehidingStyle:Cn().nonEmpty(),targetMigrationEnabled:hn().default(!1),autoCollectPropositionInteractions:In(Qu(Qu({},Si,gn(Ti).default(Ko)),"TGT",gn(Ti).default($o))).default(Qu(Qu({},Si,Ko),"TGT",$o)).noUnknownFields()});var Di,Pi=function(e){return function(n){var t=e().toISOString();b(n,{timestamp:t})}},Ri="2.21.1",Oi=[["architecture","string"],["bitness","string"],["model","string"],["platformVersion","string"],["wow64","boolean"]],Ai=function(e){return function(n){var t={webPageDetails:{URL:e.location.href||e.location},webReferrer:{URL:e.document.referrer}};b(n,{web:t})}}(window),Ni=function(e){return function(n){var t=e.screen,r=t.width,o=t.height,i={},a=Oe(o);a>=0&&(i.screenHeight=a);var u=Oe(r);u>=0&&(i.screenWidth=u);var c=function(e){var n=e.screen.orientation;if(null==n||null==n.type)return null;var t=n.type.split("-");return 0===t.length||"portrait"!==t[0]&&"landscape"!==t[0]?null:t[0]}(e)||function(e){if(M(e.matchMedia)){if(e.matchMedia("(orientation: portrait)").matches)return"portrait";if(e.matchMedia("(orientation: landscape)").matches)return"landscape"}return null}(e);c&&(i.screenOrientation=c),Object.keys(i).length>0&&b(n,{device:i})}}(window),Mi=function(e){return function(n){var t=e.document.documentElement,r=void 0===t?{}:t,o=r.clientWidth,i=r.clientHeight,a={type:"browser"},u=Oe(o);u>=0&&(a.browserDetails={viewportWidth:u});var c=Oe(i);c>=0&&(a.browserDetails=a.browserDetails||{},a.browserDetails.viewportHeight=c),b(n,{environment:a})}}(window),xi=(Di=function(){return new Date},function(e){var n=Di(),t={},r=Oe(n.getTimezoneOffset());void 0!==r&&(t.localTimezoneOffset=r),(void 0===r||Math.abs(r)<6e3)&&(t.localTime=function(e){var n=e.getFullYear(),t=me(e.getMonth()+1,2,"0"),r=me(e.getDate(),2,"0"),o=me(e.getHours(),2,"0"),i=me(e.getMinutes(),2,"0"),a=me(e.getSeconds(),2,"0"),u=me(e.getMilliseconds(),3,"0"),c=Oe(e.getTimezoneOffset(),0);return n+"-"+t+"-"+r+"T"+o+":"+i+":"+a+"."+u+(c>0?"-":"+")+me(Math.floor(Math.abs(c)/60),2,"0")+":"+me(Math.abs(c)%60,2,"0")}(n)),b(e,{placeContext:t})}),qi=Pi((function(){return new Date})),ji={web:Ai,device:Ni,environment:Mi,placeContext:xi},Li={highEntropyUserAgentHints:function(e){return function(e){return void 0!==e.userAgentData}(e)?function(n,t){try{return e.userAgentData.getHighEntropyValues(Oi.map((function(e){return e[0]}))).then((function(e){var t={};Oi.forEach((function(n){var r=Wu(n,2),o=r[0],i=r[1];Object.prototype.hasOwnProperty.call(e,o)&&Zu(e[o])===i&&(t[o]=e[o])})),b(n,{environment:{browserDetails:{userAgentClientHints:t}}})}))}catch(e){return t.warn("Unable to collect user-agent client hints. "+e.message),ge}}:ge}(navigator)},_i=Xu(Xu({},ji),Li),Ui=[qi,function(e){b(e,{implementationDetails:{name:"https://ns.adobe.com/experience/alloy",version:Ri,environment:"browser"}})}],Fi=function(e){return function(e,n,t,r){var o=e.context,i=Z(o,(function(e,r){return t[e]?[t[e]]:(n.warn("Invalid context["+r+"]: '"+e+"' is not available."),[])})).concat(r);return{namespace:"Context",lifecycle:{onBeforeEvent:function(e){var t=e.event,r={};return Promise.all(i.map((function(e){return Promise.resolve(e(r,n))}))).then((function(){return t.mergeXdm(r)}))}}}}(e.config,e.logger,_i,Ui)};Fi.namespace="Context",Fi.configValidators=In({context:vn(Cn()).default(Object.keys(ji))});var Bi=function e(n){return Array.isArray(n)?n.map((function(n){return e(n)})):"object"===Zu(n)&&null!==n?Object.keys(n).sort().reduce((function(t,r){return t[r]=e(n[r]),t}),{}):n},Hi=function(e){return C(JSON.stringify(Bi(e)))},Vi=["standard","version"],zi=function(e){return e.standard+"."+e.version},Ji=function(){var e={},n=Lt({content:e,addIdentity:function(n,t){e.identityMap=e.identityMap||{},e.identityMap[n]=e.identityMap[n]||[],e.identityMap[n].push(t)},hasIdentity:function(n){return void 0!==(e.identityMap&&e.identityMap[n])}});return n.setConsent=function(n){e.consent=n},n},Qi=function(e){var n=e.payload,t=e.datastreamIdOverride;return qt({payload:n,datastreamIdOverride:t,getAction:function(){return"privacy/set-consent"},getUseSendBeacon:function(){return!1}})},Gi=function(e){return e.split(";").reduce((function(e,n){var t=Wu(n.split("="),2),r=t[0],o=t[1];return e[r]=o,e}),{})},Xi=In({consent:vn(mn()).required().nonEmpty(),identityMap:kn,edgeConfigOverrides:Tn}).noUnknownFields().required(),Yi=function(e){var n,t,r=e.config,o=e.consent,i=e.sendEdgeNetworkRequest,a=e.createNamespacedStorage,u=r.orgId,c=r.defaultConsent,s=function(e){var n=e.parseConsentCookie,t=e.orgId,r=e.cookieJar,o=oe(t,"consent");return{read:function(){var e=r.get(o);return e?n(e):{}},clear:function(){r.remove(o)}}}({parseConsentCookie:Gi,orgId:u,cookieJar:h}),d=(n=0,t=Promise.resolve(),{addTask:function(e){n+=1;var r=function(){return e().finally((function(){n-=1}))};return t=t.then(r,r)},get length(){return n}}),l=function(e){var n=e.createConsentRequestPayload,t=e.createConsentRequest,r=e.sendEdgeNetworkRequest,o=e.edgeConfigOverrides;return function(e){var i=e.consentOptions,a=e.identityMap,u=e.edgeConfigOverrides,c=Bt({payload:n(),globalConfigOverrides:o,localConfigOverrides:u});c.payload.setConsent(i),g(a)&&Object.keys(a).forEach((function(e){a[e].forEach((function(n){c.payload.addIdentity(e,n)}))}));var s=t(c);return r({request:s}).then((function(){}))}}({createConsentRequestPayload:Ji,createConsentRequest:Qi,sendEdgeNetworkRequest:i,edgeConfigOverrides:r.edgeConfigOverrides}),f=function(e){var n=e.storage;return{clear:function(){n.clear()},lookup:function(e){var t={},r=function(e){var n=zi(e);e.standard,e.version;var r=Yu(e,Vi);return t[n]||(t[n]=Hi(r).toString()),t[n]};return{isNew:function(){return e.some((function(e){var t=zi(e),o=n.getItem(t);return null===o||o!==r(e)}))},save:function(){e.forEach((function(e){var t=zi(e);n.setItem(t,r(e))}))}}}}}({storage:a(re(u)+".consentHashes.").persistent}),p=ae({orgId:u});return function(e){var n=e.storedConsent,t=e.taskQueue,r=e.defaultConsent,o=e.consent,i=e.sendSetConsentRequest,a=e.validateSetConsentOptions,u=e.consentHashStore,c=e.doesIdentityCookieExist,s=Qu({},Ln,r),d=n.read(),l=c(),f=void 0!==d[Ln];l&&f||u.clear(),l||(n.clear(),d={}),o.initializeConsent(s,d);var p=function(){if(0===t.length){var e=n.read();void 0!==e[Ln]&&o.setConsent(e)}};return{commands:{setConsent:{optionsValidator:a,run:function(e){var n=e.consent,r=e.identityMap,a=e.edgeConfigOverrides;o.suspend();var c=u.lookup(n);return t.addTask((function(){return c.isNew()?i({consentOptions:n,identityMap:r,edgeConfigOverrides:a}):Promise.resolve()})).then((function(){return c.save()})).finally(p)}}},lifecycle:{onResponse:p,onRequestFailure:p}}}({storedConsent:s,taskQueue:d,defaultConsent:c,consent:o,sendSetConsentRequest:l,validateSetConsentOptions:Xi,consentHashStore:f,doesIdentityCookieExist:p})};Yi.namespace="Privacy";var Wi=function(){return{eventMergeId:oc()}},Ki=function(){return{commands:{createEventMergeId:{run:{createEventMergeId:Wi}.createEventMergeId}}}};Ki.namespace="EventMerge";var $i=function(e){var n=function(e){var n=e.config,t=e.componentRegistry,r=[].concat(Ku(t.getCommandNames()),[Qn,Gn]).sort(),o=Xu({},n);Object.keys(n).forEach((function(e){var t=n[e];"function"==typeof t&&(o[e]=t.toString())}));var i=t.getComponentNames();return{version:Ri,configs:o,commands:r,components:i}}({config:e.config,componentRegistry:e.componentRegistry});return{commands:{getLibraryInfo:{run:function(){return{libraryInfo:n}}}}}};$i.namespace="LibraryInfo";var Zi,ea=function(e){return null!==e&&"object"===Zu(e)&&Object.getPrototypeOf(e)===Object.prototype},na=function e(n){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return Object.keys(n).forEach((function(o){ea(n[o])||Array.isArray(n[o])?e(n[o],t,[].concat(Ku(r),[o])):t[[].concat(Ku(r),[o]).join(".")]=n[o]})),t},ta=function(e){return ea(e)?na(e):e},ra={MATCHER:"matcher",GROUP:"group",HISTORICAL:"historical"},oa={EQUALS:"eq",NOT_EQUALS:"ne",EXISTS:"ex",NOT_EXISTS:"nx",GREATER_THAN:"gt",GREATER_THAN_OR_EQUAL_TO:"ge",LESS_THAN:"lt",LESS_THAN_OR_EQUAL_TO:"le",CONTAINS:"co",NOT_CONTAINS:"nc",STARTS_WITH:"sw",ENDS_WITH:"ew"},ia={AND:"and",OR:"or"},aa={ANY:"any",ORDERED:"ordered"},ua=(Qu(Qu(Qu(Qu(Qu(Qu(Qu(Qu(Qu(Qu(Zi={},oa.EQUALS,{matches:function(e,n){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];if(gc(e[n]))return!1;for(var r=String(e[n]).toLowerCase(),o=0;o2&&void 0!==arguments[2]?arguments[2]:[];if(gc(e[n]))return!1;for(var r=String(e[n]).toLowerCase(),o=0;o2&&void 0!==arguments[2]?arguments[2]:[],r=e[n];if(!mc(r))return!1;for(var o=0;ot[o])return!0;return!1}}),oa.GREATER_THAN_OR_EQUAL_TO,{matches:function(e,n){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=e[n];if(!mc(r))return!1;for(var o=0;o=t[o])return!0;return!1}}),oa.LESS_THAN,{matches:function(e,n){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=e[n];if(!mc(r))return!1;for(var o=0;o2&&void 0!==arguments[2]?arguments[2]:[],r=e[n];if(!mc(r))return!1;for(var o=0;o2&&void 0!==arguments[2]?arguments[2]:[];if(gc(e[n]))return!1;for(var r=String(e[n]).toLowerCase(),o=0;o2&&void 0!==arguments[2]?arguments[2]:[];if(gc(e[n]))return!1;for(var r=String(e[n]).toLowerCase(),o=0;o2&&void 0!==arguments[2]?arguments[2]:[];if(gc(e[n]))return!1;for(var r=String(e[n]).toLowerCase(),o=0;o2&&void 0!==arguments[2]?arguments[2]:[];if(gc(e[n]))return!1;for(var r=String(e[n]).toLowerCase(),o=0;o0&&void 0!==arguments[0]?arguments[0]:[],t=[];return Array.isArray(n)?(n.forEach((function(n){Array.isArray(n)?t.push.apply(t,Ku(e(n))):t.push(n)})),t):n},pa=Qu(Qu({},"cjmiam",(function(e,n,t){var r=t.html,o=t.mobileParameters;return{schema:gr,data:{mobileParameters:o,webParameters:{},content:r,contentType:ai},id:e}})),"schema",(function(e,n,t){return{schema:t.schema,data:t.data,id:t.id||e}})),ga=function(e){var n=e.schema,t=e.data;if(n===fr)return!0;if(n!==lr)return!1;try{var r="string"==typeof t.content?JSON.parse(t.content):t.content;return r&&Object.prototype.hasOwnProperty.call(r,"version")&&Object.prototype.hasOwnProperty.call(r,"rules")}catch(e){return!1}},ma=function(e,n,t){var r=function(e){var n=e.id,t=e.type,r=e.detail;return"function"==typeof pa[t]?pa[t](n,t,r):r},o=da(e),i=[];return Array.isArray(e.items)&&e.items.filter(ga).forEach((function(e){var n=e.data,t=void 0===n?{}:n,r=e.schema===fr?t:t.content;r&&i.push(Tc("string"==typeof r?JSON.parse(r):r))})),{evaluate:function(a){var u=n.getEvent(hr,o),c=u?u.firstTimestamp:void 0,s=fa(i.map((function(e){return e.execute(a)}))).map(r).map((function(e){var n=(t.recordQualified(o)||{}).firstTimestamp;return Xu(Xu({},e),{},{data:Xu(Xu({},e.data),{},{qualifiedDate:n,displayedDate:c})})}));return Xu(Xu({},e),{},{items:s})},isEvaluable:i.length>0}},va=function(e){var n=e.eventRegistry,t={},r=function(e){var n=e.eventRegistry;return{recordQualified:function(e){if(e)return n.addEvent({},Er.TRIGGER,e)}}}({eventRegistry:n}),o=function(e){var o=da(e);if(o){var i=ma(e,n,r);i.isEvaluable&&(t[o]=i)}};return{addPayload:o,addPayloads:function(e){e.forEach(o)},evaluate:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Object.values(t).map((function(n){return n.evaluate(e)})).filter((function(e){return e.items.length>0}))}}},ha="events",ya=function(e){return"iam."+e},ba=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:30;return function(t){var r={};return Object.keys(t).forEach((function(o){r[o]={},Object.values(t[o]).filter((function(e){return new Date(e.firstTimestamp)>=function(e){var n=new Date;return n.setDate(n.getDate()-e),n}(n)})).sort((function(e,n){return e.firstTimestamp-n.firstTimestamp})).slice(-1*e).forEach((function(e){r[o][e.event[ya("id")]]=e}))})),r}},wa=function(e){var n,t,r,o=e.storage,i=o,a=function(e){n=function(e,n){return function(t){var r=e.getItem(n);if(!r)return t;try{return JSON.parse(r)}catch(e){return t}}}(i=e,ha),t=function(e,n){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(e){return e};return function(r){e.setItem(n,JSON.stringify(t(r)))}}(i,ha,ba(1e3,30)),r=n({})};a(o);var u=function(e,n,o,i){if(n&&o){r[n]||(r[n]={});var a=r[n][o],u=a?a.count:0,c=(new Date).getTime(),s=a?a.firstTimestamp||a.timestamp:c;return r[n][o]={event:Xu(Xu({},e),{},Qu(Qu(Qu({},ya("id"),o),ya("eventType"),n),ya("action"),i)),firstTimestamp:s,timestamp:c,count:u+1},t(r),r[n][o]}};return{addExperienceEdgeEvent:function(e){var n=e.getContent().xdm,t=void 0===n?{}:n,r=t._experience;if(function(e){var n=e.eventType,t=void 0===n?"":n,r=e._experience;return!(!t||""===t||!r||"object"!==Zu(r))}(t)){var o=r.decisioning,i=void 0===o?{}:o,a=i.propositionEventType,c=void 0===a?{}:a,s=i.propositionAction,d=void 0===s?{}:s,l=i.propositions,f=void 0===l?[]:l,p=Object.keys(c);if(0!==p.length){var g=d.id;p.filter((function(e){return 1===c[e]})).forEach((function(e){f.forEach((function(n){(function(e){var n=e.scopeDetails;return(void 0===n?{}:n).decisionProvider})(n)===Si&&u({},e,da(n),g)}))}))}}},addEvent:u,getEvent:function(e,n){if(r[e])return r[e][n]},toJSON:function(){return r},setStorage:a}},Ea=function(e){var n=e.eventRegistry,t=e.window,r=(new Date).getTime(),o={browser:{name:At(t)},page:Xu({title:t.title,url:t.url},be(t.url)),referringPage:Xu({url:t.referrer},be(t.referrer))},i=function(){return Xu(Xu(Xu({},o),(e=new Date,n=e.getTime(),{pageLoadTimestamp:r,currentTimestamp:n,currentDate:e.getDate(),"~state.com.adobe.module.lifecycle/lifecyclecontextdata.dayofweek":e.getDay()+1,"~state.com.adobe.module.lifecycle/lifecyclecontextdata.hourofday":e.getHours(),currentMinute:e.getMinutes(),currentMonth:e.getMonth(),currentYear:e.getFullYear(),pageVisitDuration:n-r,"~timestampu":n/1e3,"~timestampz":e.toISOString()})),{},{window:{height:t.height,width:t.width,scrollY:t.scrollY,scrollX:t.scrollX},"~sdkver":Ri});var e,n};return{getContext:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=Xu(Xu({},i()),e);return Xu(Xu({},ta(t)),{},{events:n.toJSON()})}}},Ia=function(e){for(var n=arguments.length,t=new Array(n>1?n-1:0),r=1;r1&&void 0!==arguments[1]?arguments[1]:void 0;return"function"!=typeof e?function(){}:(r[t+=1]={callback:e,params:o},n=t,function(){delete r[n]})},emit:function(){for(var t=arguments.length,o=new Array(t),i=0;i0},setEmissionPreprocessor:function(n){"function"==typeof n&&(e=n)},setEmissionCondition:function(e){"function"==typeof e&&(n=e)}}},ka=function(e,n){var t=e.surfacesFilter,r=e.schemasFilter;return[{propositions:n.filter((function(e){return!t||o(t,e.scope)})).map((function(e){var n=e.items,t=void 0===n?[]:n;return Xu(Xu({},e),{},{items:t.filter((function(e){return!r||o(r,e.schema)}))})})).filter((function(e){return e.items.length>0}))}]},Ta=function(e,n){return n.propositions.length>0},Da=function(){var e=Sa();e.setEmissionPreprocessor(ka),e.setEmissionCondition(Ta);return{refresh:function(n){e.hasSubscriptions()&&e.emit(n)},command:{optionsValidator:function(e){return function(e){var n=e.options;return In({surfaces:vn(Cn()).uniqueItems(),schemas:vn(Cn()).uniqueItems(),callback:yn().required()}).noUnknownFields()(n)}({options:e})},run:function(n){var t=n.surfaces,r=n.schemas,o=n.callback,i=e.add(o,{surfacesFilter:t instanceof Array?t:void 0,schemasFilter:r instanceof Array?r:void 0});return Promise.resolve({unsubscribe:i})}}}},Pa="~type",Ra="~source",Oa="com.adobe.eventType.edge",Aa="com.adobe.eventType.rulesEngine",Na="com.adobe.eventSource.requestContent",Ma=function(e){var n=e.contextProvider,t=e.decisionProvider;return{optionsValidator:function(e){return function(e){var n=e.options;return In({renderDecisions:hn(),personalization:In({decisionContext:In({})})}).noUnknownFields()(n)}({options:e})},run:function(e){var r=e.renderDecisions,o=e.decisionContext;return(0,e.applyResponse)({renderDecisions:r,propositions:t.evaluate(n.getContext(o))})}}},xa=function(e){var n=e.config,t=e.createNamespacedStorage,r=e.consent,o=n.orgId,i=n.personalizationStorageEnabled,a=t(re(o)+".decisioning.");i||la(a.persistent);var u,c,s=wa({storage:(u={},{getItem:function(e){return e in u?u[e]:null},setItem:function(e,n){u[e]=n}})}),d=va({eventRegistry:s}),l=Ea({eventRegistry:s,window:window}),f=Ma({contextProvider:l,decisionProvider:d}),p=Da();return{lifecycle:{onDecision:function(e){var n=e.propositions;p.refresh(n)},onComponentsRegistered:function(e){var n;n=e.lifecycle,c=function(e){var t=e.renderDecisions,r=void 0!==t&&t,o=e.propositions,i=void 0===o?[]:o,a=e.event,u=e.personalization;return i.length>0&&n&&n.onDecision({renderDecisions:r,propositions:i,event:a,personalization:u}),{propositions:i}},i&&r.awaitConsent().then((function(){s.setStorage(a.persistent)})).catch((function(){a&&la(a.persistent)}))},onBeforeEvent:function(e){var n=e.event,t=e.renderDecisions,r=e.personalization,o=void 0===r?{}:r,i=e.onResponse,a=void 0===i?ge:i,u=o.decisionContext,f=void 0===u?{}:u;a(function(e){var n=e.renderDecisions,t=e.decisionProvider,r=e.applyResponse,o=e.event,i=e.personalization,a=e.decisionContext,u=Xu(Xu({},ta(o.getContent())),a);return function(e){var a=e.response;if(t.addPayloads(a.getPayloadsByType("personalization:decisions")),!o.hasQuery())return{propositions:[]};var c=t.evaluate(u);return r({renderDecisions:n,propositions:c,event:o,personalization:i})}}({renderDecisions:t,decisionProvider:d,applyResponse:c,event:n,personalization:o,decisionContext:l.getContext(Xu(Qu(Qu({},Pa,Oa),Ra,Na),f))})),s.addExperienceEdgeEvent(n)}},commands:{evaluateRulesets:{run:function(e){var n=e.renderDecisions,t=e.personalization,r=(void 0===t?{}:t).decisionContext,o=void 0===r?{}:r;return f.run({renderDecisions:n,decisionContext:Xu(Qu(Qu({},Pa,Aa),Ra,Na),o),applyResponse:c})},optionsValidator:f.optionsValidator},subscribeRulesetItems:p.command}}};xa.namespace="DecisioningEngine",xa.configValidators=In({personalizationStorageEnabled:hn().default(!1)});var qa=function(e){return{inferences:e.response.getPayloadsByType("rtml:inferences")}},ja=function(){return{lifecycle:{onResponse:qa},commands:{}}};ja.namespace="MachineLearning";var La="main",_a="completed",Ua=function(){var e;return{getSession:function(n){return e[n]||{}},storeSession:function(n){var t=n.playerId,r=n.sessionDetails;void 0===e&&(e={}),e[t]=r},stopPing:function(n){var t=n.playerId,r=e[t];r&&(clearTimeout(r.pingId),r.pingId=null,r.playbackState=_a)},savePing:function(n){var t=n.playerId,r=n.pingId,o=n.playbackState;e[t]&&(e[t].pingId&&clearTimeout(e[t].pingId),e[t].pingId=r,e[t].playbackState=o)}}},Fa={PAUSE:"media.pauseStart",PLAY:"media.play",BUFFER_START:"media.bufferStart",AD_START:"media.adStart",Ad_BREAK_START:"media.adBreakStart",SESSION_END:"media.sessionEnd",SESSION_START:"media.sessionStart",SESSION_COMPLETE:"media.sessionComplete",PING:"media.ping",AD_BREAK_COMPLETE:"media.adBreakComplete",AD_COMPLETE:"media.adComplete",AD_SKIP:"media.adSkip",BITRATE_CHANGE:"media.bitrateChange",CHAPTER_COMPLETE:"media.chapterComplete",CHAPTER_SKIP:"media.chapterSkip",CHAPTER_START:"media.chapterStart",ERROR:"media.error",STATES_UPDATE:"media.statesUpdate"},Ba=function(e){var n=e.config,t=e.eventManager,r=e.consent,o=e.sendEdgeNetworkRequest,i=e.setTimestamp;return{createMediaEvent:function(e){var r=e.options,o=t.createEvent(),a=r.xdm;if(i(a),o.setUserXdm(a),a.eventType===Fa.AD_START){var u=r.xdm.mediaCollection.advertisingDetails;o.mergeXdm({mediaCollection:{advertisingDetails:{playerName:u.playerName||n.streamingMedia.playerName}}})}return o},createMediaSession:function(e){var r=n.streamingMedia,o=r.playerName,i=r.channel,a=r.appVersion,u=t.createEvent(),c=e.xdm.mediaCollection.sessionDetails;return u.setUserXdm(e.xdm),u.mergeXdm({eventType:Fa.SESSION_START,mediaCollection:{sessionDetails:{playerName:c.playerName||o,channel:c.channel||i,appVersion:c.appVersion||a}}}),u},augmentMediaEvent:function(e){var n=e.event,t=e.playerId,r=e.getPlayerDetails,o=e.sessionID;if(!t||!r)return n;var i=r({playerId:t}),a=i.playhead,u=i.qoeDataDetails;return n.mergeXdm({mediaCollection:{playhead:Oe(a),qoeDataDetails:u,sessionID:o}}),n},trackMediaSession:function(e){var n=e.event,r=e.mediaOptions;return t.sendEvent(n,{mediaOptions:r})},trackMediaEvent:function(e){var n=e.event,t=e.action,i=Ut(),a=function(e){var n=e.mediaRequestPayload,t=e.action;return qt({payload:n,edgeSubPath:"/va",getAction:function(){return t},getUseSendBeacon:function(){return!1}})}({mediaRequestPayload:i,action:t});return i.addEvent(n),n.finalize(),r.awaitConsent().then((function(){return o({request:a}).then((function(){return{}}))}))}}},Ha=function(e){var n=e.mediaEventManager,t=e.mediaSessionCacheManager,r=e.config,o=function e(o){var i=n.createMediaEvent({options:o}),a=o.playerId,u=o.xdm.eventType,c=u.split(".")[1],s=t.getSession(a),d=s.getPlayerDetails,l=s.sessionPromise,f=s.playbackState;return l.then((function(o){return o.sessionId?(n.augmentMediaEvent({event:i,eventType:u,playerId:a,getPlayerDetails:d,sessionID:o.sessionId}),n.trackMediaEvent({event:i,action:c}).then((function(){if(a)if(u===Fa.SESSION_COMPLETE||u===Fa.SESSION_END)t.stopPing({playerId:a});else{var n=function(e,n){return e===Fa.AD_START||e===Fa.Ad_BREAK_START||e===Fa.AD_SKIP||e===Fa.AD_COMPLETE?"ad":e===Fa.AD_BREAK_COMPLETE||e===Fa.CHAPTER_COMPLETE||e===Fa.CHAPTER_START||e===Fa.CHAPTER_SKIP||e===Fa.SESSION_START?"main":e===Fa.SESSION_END||e===Fa.SESSION_COMPLETE?"completed":n}(u,f);if("completed"===n)return;var o="ad"===n?r.streamingMedia.adPingInterval:r.streamingMedia.mainPingInterval,i=setTimeout((function(){e({playerId:a,xdm:{eventType:Fa.PING}})}),1e3*o);t.savePing({playerId:a,pingId:i,playbackState:n})}}))):Promise.reject(new Error("Failed to trigger media event: "+u+". Session ID is not available for playerId: "+a+"."))}))};return function(e){return o(e)}},Va=In({streamingMedia:In({channel:Cn().nonEmpty().required(),playerName:Cn().nonEmpty().required(),appVersion:Cn(),mainPingInterval:wn().minimum(10).maximum(50).default(10),adPingInterval:wn().minimum(1).maximum(10).default(10)}).noUnknownFields()}),za=function(e){var n=e.config,t=e.trackMediaEvent,r=e.trackMediaSession,o=e.mediaResponseHandler;return{lifecycle:{onBeforeEvent:function(e){var n=e.mediaOptions,t=e.onResponse,r=void 0===t?ge:t;if(n){var i=n.legacy,a=n.playerId,u=n.getPlayerDetails;i||r((function(e){var n=e.response;return o({playerId:a,getPlayerDetails:u,response:n})}))}}},commands:{createMediaSession:{optionsValidator:function(e){return function(e){var n=e.options;return gn([In({playerId:Cn().required(),getPlayerDetails:yn().required(),xdm:In({mediaCollection:In({sessionDetails:In(mn()).required()})})}).required(),In({xdm:In({mediaCollection:In({playhead:wn().required(),sessionDetails:In(mn()).required()})})}).required()],"Error validating the createMediaSession command options.")(n)}({options:e})},run:r},sendMediaEvent:{optionsValidator:function(e){return function(e){var n=e.options;return gn([In({playerId:Cn().required(),xdm:In({eventType:Sn.apply(void 0,Ku(Object.values(Fa))).required(),mediaCollection:In(mn())}).required()}).required(),In({xdm:In({eventType:Sn.apply(void 0,Ku(Object.values(Fa))).required(),mediaCollection:In({playhead:wn().integer().required(),sessionID:Cn().required()}).required()}).required()}).required()],"Error validating the sendMediaEvent command options.")(n)}({options:e})},run:function(e){return n.streamingMedia?t(e):Promise.reject(new Error("Streaming media is not configured."))}}}}},Ja=function(e){var n=e.config,t=e.mediaEventManager,r=e.mediaSessionCacheManager,o=e.legacy,i=void 0!==o&&o;return function(e){if(!n.streamingMedia)return Promise.reject(new Error("Streaming media is not configured."));var o=e.playerId,a=e.getPlayerDetails,u=t.createMediaSession(e);t.augmentMediaEvent({event:u,playerId:o,getPlayerDetails:a});var c=t.trackMediaSession({event:u,mediaOptions:{playerId:o,getPlayerDetails:a,legacy:i}});return r.storeSession({playerId:o,sessionDetails:{sessionPromise:c,getPlayerDetails:a,playbackState:La}}),c}},Qa=function(e){var n=e.mediaSessionCacheManager,t=e.config,r=e.trackMediaEvent;return function(e){var o=e.response,i=e.playerId,a=e.getPlayerDetails,u=o.getPayloadsByType("media-analytics:new-session");if(x(u)){var c=u[0].sessionId;if(Go(c))return{};if(!i||!a)return{sessionId:c};var s=setTimeout((function(){r({playerId:i,xdm:{eventType:Fa.PING}})}),1e3*t.streamingMedia.mainPingInterval);return n.savePing({playerId:i,pingId:s,playbackState:La}),{sessionId:c}}return{}}},Ga=function(e){var n=e.config,t=e.logger,r=e.eventManager,o=e.sendEdgeNetworkRequest,i=e.consent,a=Ua(),u=Ba({config:n,eventManager:r,logger:t,consent:i,sendEdgeNetworkRequest:o,setTimestamp:Pi((function(){return new Date}))}),c=Ha({mediaSessionCacheManager:a,mediaEventManager:u,config:n}),s=Ja({config:n,mediaEventManager:u,mediaSessionCacheManager:a}),d=Qa({mediaSessionCacheManager:a,config:n,trackMediaEvent:c});return za({config:n,trackMediaEvent:c,mediaEventManager:u,mediaResponseHandler:d,trackMediaSession:s})};Ga.namespace="Streaming media",Ga.configValidators=Va;var Xa={Video:"video",Audio:"audio"},Ya={VOD:"vod",Live:"live",Linear:"linear",Podcast:"podcast",Audiobook:"audiobook",AOD:"aod"},Wa={FullScreen:"fullScreen",ClosedCaption:"closedCaptioning",Mute:"mute",PictureInPicture:"pictureInPicture",InFocus:"inFocus"},Ka={AdBreakStart:"adBreakStart",AdBreakComplete:"adBreakComplete",AdStart:"adStart",AdComplete:"adComplete",AdSkip:"adSkip",ChapterStart:"chapterStart",ChapterComplete:"chapterComplete",ChapterSkip:"chapterSkip",SeekStart:"seekStart",SeekComplete:"seekComplete",BufferStart:"bufferStart",BufferComplete:"bufferComplete",BitrateChange:"bitrateChange",StateStart:"stateStart",StateEnd:"stateEnd"},$a="sessionStart",Za="sessionEnd",eu="sessionComplete",nu="play",tu="pauseStart",ru="error",ou="statesUpdate",iu={MediaResumed:"media.resumed",GranularAdTracking:"media.granularadtracking"},au={Show:"a.media.show",Season:"a.media.season",Episode:"a.media.episode",AssetId:"a.media.asset",Genre:"a.media.genre",FirstAirDate:"a.media.airDate",FirstDigitalDate:"a.media.digitalDate",Rating:"a.media.rating",Originator:"a.media.originator",Network:"a.media.network",ShowType:"a.media.type",AdLoad:"a.media.adLoad",MVPD:"a.media.pass.mvpd",Authorized:"a.media.pass.auth",DayPart:"a.media.dayPart",Feed:"a.media.feed",StreamFormat:"a.media.format"},uu={Artist:"a.media.artist",Album:"a.media.album",Label:"a.media.label",Author:"a.media.author",Station:"a.media.station",Publisher:"a.media.publisher"},cu={Advertiser:"a.media.ad.advertiser",CampaignId:"a.media.ad.campaign",CreativeId:"a.media.ad.creative",PlacementId:"a.media.ad.placement",SiteId:"a.media.ad.site",CreativeUrl:"a.media.ad.creativeURL"},su=function(e){var n=e.logger;return{createMediaObject:function(e,t,r,o,i){var a={friendlyName:e,name:t,length:r,streamType:i,contentType:o},u=In({friendlyName:Cn().nonEmpty(),name:Cn().nonEmpty(),length:wn().required(),streamType:Cn().nonEmpty(),contentType:Cn().nonEmpty()});try{var c=u(a);return{sessionDetails:{name:c.name,friendlyName:c.friendlyName,length:c.length,streamType:c.streamType,contentType:c.contentType}}}catch(e){return n.warn("An error occurred while creating the Media Object.",e),{}}},createAdBreakObject:function(e,t,r){var o={friendlyName:e,offset:t,index:r},i=In({friendlyName:Cn().nonEmpty(),offset:wn(),index:wn()});try{var a=i(o);return{advertisingPodDetails:{friendlyName:a.friendlyName,offset:a.offset,index:a.index}}}catch(e){return n.warn("An error occurred while creating the Ad Break Object.",e),{}}},createAdObject:function(e,t,r,o){var i={friendlyName:e,name:t,podPosition:r,length:o},a=In({friendlyName:Cn().nonEmpty(),name:Cn().nonEmpty(),podPosition:wn(),length:wn()});try{var u=a(i);return{advertisingDetails:{friendlyName:u.friendlyName,name:u.name,podPosition:u.podPosition,length:u.length}}}catch(e){return n.warn("An error occurred while creating the Advertising Object.",e),{}}},createChapterObject:function(e,t,r,o){var i={friendlyName:e,offset:t,length:r,index:o},a=In({friendlyName:Cn().nonEmpty(),offset:wn(),length:wn(),index:wn()});try{var u=a(i);return{chapterDetails:{friendlyName:u.friendlyName,offset:u.offset,index:u.index,length:u.length}}}catch(e){return n.warn("An error occurred while creating the Chapter Object.",e),{}}},createStateObject:function(e){var t=Cn().matches(/^[a-zA-Z0-9_]{1,64}$/,"This is not a valid state name.");try{return{name:t(e)}}catch(e){return n.warn("An error occurred while creating the State Object.",e),{}}},createQoEObject:function(e,t,r,o){var i={bitrate:e,droppedFrames:t,fps:r,startupTime:o},a=In({bitrate:wn(),droppedFrames:wn(),fps:wn(),startupTime:wn()});try{var u=a(i);return{bitrate:u.bitrate,droppedFrames:u.droppedFrames,framesPerSecond:u.fps,timeToStart:u.startupTime}}catch(e){return n.warn("An error occurred while creating the QOE Object.",e),{}}}}},du={"a.media.show":"show","a.media.season":"season","a.media.episode":"episode","a.media.asset":"assetID","a.media.genre":"genre","a.media.airDate":"firstAirDate","a.media.digitalDate":"firstDigitalDate","a.media.rating":"rating","a.media.originator":"originator","a.media.network":"network","a.media.type":"showType","a.media.adLoad":"adLoad","a.media.pass.mvpd":"mvpd","a.media.pass.auth":"authorized","a.media.dayPart":"dayPart","a.media.feed":"feed","a.media.format":"streamFormat","a.media.artist":"artist","a.media.album":"album","a.media.label":"label","a.media.author":"author","a.media.station":"station","a.media.publisher":"publisher","media.resumed":"hasResume"},lu={"a.media.ad.advertiser":"advertiser","a.media.ad.campaign":"campaignID","a.media.ad.creative":"creativeID","a.media.ad.placement":"placementID","a.media.ad.site":"siteID","a.media.ad.creativeURL":"creativeURL"},fu=function(e){var n=e.logger,t=e.trackMediaSession,r=e.trackMediaEvent,i=e.uuid,a=null,u=function(e){var n=e.eventType,t=e.mediaDetails,r=void 0===t?{}:t,o=e.contextData,i=void 0===o?[]:o,a=function(e){var n=e.eventType;return n===Ka.BufferComplete||n===Ka.SeekComplete?nu:n===Ka.StateStart||n===Ka.StateEnd?ou:n===Ka.SeekStart?tu:n}({eventType:n});if(n===Ka.StateStart)return{eventType:"media."+a,mediaCollection:{statesStart:[r]}};if(n===Ka.StateEnd)return{eventType:"media."+a,mediaCollection:{statesEnd:[r]}};var u={eventType:"media."+a,mediaCollection:Xu({},r)},c=[];return Object.keys(i).forEach((function(e){du[e]?u.mediaCollection.sessionDetails[du[e]]=i[e]:lu[e]?u.mediaCollection.advertisingDetails[lu[e]]=i[e]:c.push({name:e,value:i[e]})})),x(c)&&(u.mediaCollection.customMetadata=c),u};return{trackSessionStart:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(p(e)||K(e))return n.warn("Invalid media object"),{};null===a&&(n.warn("The Media Session was completed. Restarting a new session."),a={qoe:null,lastPlayhead:0,playerId:i()});var o=u({eventType:$a,mediaDetails:e,contextData:r});return t({playerId:a.playerId,getPlayerDetails:function(){return{playhead:a.lastPlayhead,qoeDataDetails:a.qoe}},xdm:o})},trackPlay:function(){if(null===a)return n.warn("The Media Session was completed."),{};var e=u({eventType:nu});return r({playerId:a.playerId,xdm:e})},trackPause:function(){if(null===a)return n.warn("The Media Session was completed."),{};var e=u({eventType:tu});return r({playerId:a.playerId,xdm:e})},trackSessionEnd:function(){if(null===a)return n.warn("The Media Session was completed."),{};var e=u({eventType:Za});return r({playerId:a.playerId,xdm:e})},trackComplete:function(){if(null===a)return n.warn("The Media Session was completed."),{};var e=u({eventType:eu});return r({playerId:a.playerId,xdm:e})},trackError:function(e){if(n.warn("trackError("+e+")"),null===a)return n.warn("The Media Session was completed."),{};var t=u({eventType:ru,mediaDetails:{errorDetails:{name:e,source:"player"}}});return r({playerId:a.playerId,xdm:t})},trackEvent:function(e,t,i){if(K(t))return n.warn("Invalid media object."),{};if(null===a)return n.warn("The Media Session was completed."),{};if(!o(Object.values(Ka),e))return n.warn("Invalid event type"),{};var c=u({eventType:e,mediaDetails:t,contextData:i});return r({playerId:a.playerId,xdm:c})},updatePlayhead:function(e){null!==a?de(e)&&(a.lastPlayhead=parseInt(e,10)):n.warn("The Media Session was completed.")},updateQoEObject:function(e){null!==a?e&&(a.qoe=e):n.warn("The Media Session was completed.")},destroy:function(){n.warn("Destroy called, destroying the tracker."),a=null}}},pu=function(e){var n=e.eventManager,t=e.sendEdgeNetworkRequest,r=e.config,o=e.logger,i=e.consent,a=Ua(),u=Ba({sendEdgeNetworkRequest:t,config:r,consent:i,eventManager:n,setTimestamp:Pi((function(){return new Date}))}),c=Ha({mediaSessionCacheManager:a,mediaEventManager:u,config:r}),s=Ja({config:r,mediaEventManager:u,mediaSessionCacheManager:a,legacy:!0});return function(e){var n=e.trackMediaEvent,t=e.trackMediaSession,r=e.mediaResponseHandler,o=e.logger,i=e.createMediaHelper,a=e.createGetInstance,u=e.config;return{lifecycle:{onBeforeEvent:function(e){var n=e.mediaOptions,t=e.onResponse,o=void 0===t?ge:t;if(n){var i=n.legacy,a=n.playerId,u=n.getPlayerDetails;i&&o((function(e){var n=e.response;return r({playerId:a,getPlayerDetails:u,response:n})}))}}},commands:{getMediaAnalyticsTracker:{run:function(){if(!u.streamingMedia)return Promise.reject(new Error("Streaming media is not configured."));o.info("Streaming media is configured in legacy mode.");var e=i({logger:o});return Promise.resolve(Xu({getInstance:function(){return a({logger:o,trackMediaEvent:n,trackMediaSession:t,uuid:oc})},Event:Ka,MediaType:Xa,PlayerState:Wa,StreamType:Ya,MediaObjectKey:iu,VideoMetadataKeys:au,AudioMetadataKeys:uu,AdMetadataKeys:cu},e))}}}}}({mediaResponseHandler:Qa({mediaSessionCacheManager:a,config:r,trackMediaEvent:c}),trackMediaSession:s,trackMediaEvent:c,createMediaHelper:su,createGetInstance:fu,logger:o,config:r})};pu.namespace="Legacy Media Analytics";var gu,mu=[Kn,wt,Qt,Yt,ki,Fi,Yi,Ki,$i,ja,xa,pu,Ga],vu=function(e){var n=e.options,t=e.componentCreators,r=e.coreConfigValidators,o=e.createConfig,i=e.logger,a=e.setDebugEnabled,u=function(e){var n=[],t={get enabled(){return e.enabled},flush:function(){n.forEach((function(n){var t=n.method,r=n.args;return e[t].apply(e,Ku(r))}))}};return Object.keys(e).filter((function(n){return"function"==typeof e[n]})).forEach((function(e){t[e]=function(){for(var t=arguments.length,r=new Array(t),o=0;o0){var i=f({},o,n);t.forEach((function(n){n[e]&&n[e](i)}))}},u=function(e){for(var r=arguments.length,o=new Array(r>1?r-1:0),u=1;u0||n()},logOnInstanceCreated:function(e){a("onInstanceCreated",e),u("info","Instance initialized.")},logOnInstanceConfigured:function(e){a("onInstanceConfigured",e),u("info","Instance configured. Computed configuration:",e.config)},logOnBeforeCommand:function(e){a("onBeforeCommand",e),u("info","Executing "+e.commandName+" command. Options:",e.options)},logOnCommandResolved:function(e){a("onCommandResolved",e),u("info",e.commandName+" command resolved. Result:",e.result)},logOnCommandRejected:function(e){a("onCommandRejected",e),u("error",e.commandName+" command was rejected. Error:",e.error)},logOnBeforeNetworkRequest:function(e){a("onBeforeNetworkRequest",e),u("info","Request "+e.requestId+": Sending request.",e.payload)},logOnNetworkResponse:function(e){a("onNetworkResponse",e);var n=e.parsedBody||e.body?"response body:":"no response body.";u("info","Request "+e.requestId+": Received response with status code "+e.statusCode+" and "+n,e.parsedBody||e.body)},logOnNetworkError:function(e){a("onNetworkError",e),u("error","Request "+e.requestId+": Network request failed.",e.error)},info:u.bind(null,"info"),warn:u.bind(null,"warn"),error:u.bind(null,"error")}},wu=["edgeConfigOverrides"],Eu="Event was canceled because the onBeforeEventSend callback returned false.",Iu=function(e){var n=e.orgId,t=e.targetMigrationEnabled;return function(e){return function(e,n){return 0===n.indexOf(te+"_"+re(e)+"_")}(n,e)||"at_qa_mode"===e||t&&"mbox"===e}},Cu=function(e){var n=e.shift()||[],t=e.shift()||[],r=e;return m.apply(void 0,[{}].concat(Ku(n),Ku(t),Ku(r)))},Su=function(e){return function(n){var t=function(){throw n};return e.call({error:n}).then(t,t)}},ku="The server responded with a",Tu=function(e){var n=e.orgId,t=e.cookieJar,r=oe(n,"cluster");return function(){return t.get(r)||function(){var e=t.get("mboxEdgeCluster");if(e)return"t"+e}()}},Du=[429,503,502,504],Pu=function(e){var n=e.response;return e.retriesAttempted<3&&o(Du,n.statusCode)},Ru=function(e){var n=e.response,t=e.retriesAttempted,r=function(e){var n,t=e.getHeader("Retry-After");if(t){var r=parseInt(t,10);n=le(r)?1e3*r:Math.max(0,new Date(t).getTime()-(new Date).getTime())}return n}(n);return void 0===r&&(r=function(e){var n=1e3+1e3*e,t=.3*n,r=n-t,o=n+t;return Math.round(r+Math.random()*(o-r))}(t)),r},Ou=ce(window),Au=window,Nu=Au.console,Mu=Au.fetch,xu=Au.navigator,qu=Au.XMLHttpRequest,ju=function(){return window.__alloyMonitors||[]},Lu=In({debugEnabled:hn().default(!1),defaultConsent:Sn(xn,qn,jn).default(xn),datastreamId:Cn().unique().required(),edgeDomain:Cn().domain().default("edge.adobedc.net"),edgeBasePath:Cn().nonEmpty().default("ee"),orgId:Cn().unique().required(),onBeforeEventSend:yn().default(ge),edgeConfigOverrides:Tn}).renamed("edgeConfigId",Cn().unique(),"datastreamId"),_u=function(e,n){for(var t,r,o="",i=e.location.hostname.toLowerCase().split("."),a=1;a0&&void 0!==arguments[0]?arguments[0]:{},t=n.appendNode,r=void 0===t?D:t,o=n.awaitSelector,i=void 0===o?G:o,a=n.createNode,u=void 0===a?P:a,c=n.fireImage,s=void 0===c?N:c,d=s,l=function(n){var t=n.src;return i("BODY").then((function(n){var t=Wu(n,1)[0];return e||(e=u("IFRAME",Y,W),r(t,e))})).then((function(e){var n=e.contentWindow.document;return s({src:t,currentDocument:n})}))};return function(e){var n=e.hideReferrer,t=e.url;return n?l({src:t}):d({src:t})}}(),Bu=function(e){var n=e.window,t=(0,e.createNamespacedStorage)("validation.");return function(){var e=Te.parse(n.location.search).adb_validation_sessionid;if(!e)return"";var r=function(e){var n=e.persistent.getItem(Ht);return n||(n=oc(),e.persistent.setItem(Ht,n)),n}(t),o=e+"|"+r;return"&"+Te.stringify({adobeAepValidationToken:o})}}({window:window,createNamespacedStorage:Ou}),Hu=function(e){var n=e.instanceName,t=e.logController,r=t.setDebugEnabled,o=t.logger,i=t.createComponentLogger,a=Mn(),u=An(a),c=I({logger:o,cookieJar:h}),s=yu({errorPrefix:"["+n+"]",logger:o}),d=Xn({logger:o,configureCommand:function(e){var t=vu({options:e,componentCreators:mu,coreConfigValidators:Lu,createConfig:hu,logger:o,setDebugEnabled:r}),s=t.orgId,d=t.targetMigrationEnabled,l=Iu({orgId:s,targetMigrationEnabled:d}),f=function(e){var n=e.cookieJar,t=e.shouldTransferCookie,r=e.apexDomain,o=e.dateProvider;return{cookiesToPayload:function(e,o){var i,a=(i=r,o.substr(-i.length)===i),u={domain:r,cookiesEnabled:!0};if(!a){var c=n.get(),s=Object.keys(c).filter(t).map((function(e){return{key:e,value:c[e]}}));s.length&&(u.entries=s)}e.mergeState(u)},responseToCookies:function(e){e.getPayloadsByType("state:store").forEach((function(e){var t={domain:r},i=e.attrs&&e.attrs.SameSite&&e.attrs.SameSite.toLowerCase();void 0!==e.maxAge&&(t.expires=new Date(o().getTime()+1e3*e.maxAge)),void 0!==i&&(t.sameSite=i),"none"===i&&(t.secure=!0),n.set(e.key,e.value,t)}))}}}({cookieJar:c,shouldTransferCookie:l,apexDomain:_u,dateProvider:function(){return new Date}}),p=M(xu.sendBeacon)?function(e){var n=e.sendBeacon,t=e.sendFetchRequest,r=e.logger;return function(e,o){var i=new Blob([o],{type:"text/plain; charset=UTF-8"});return n(e,i)?Promise.resolve({statusCode:204,getHeader:function(){return null},body:""}):(r.info("Unable to use `sendBeacon`; falling back to `fetch`."),t(e,o))}}({sendBeacon:xu.sendBeacon.bind(xu),sendFetchRequest:Uu,logger:o}):Uu,g=function(e){var n=e.logger,t=e.sendFetchRequest,r=e.sendBeaconRequest,o=e.isRequestRetryable,i=e.getRequestRetryDelay;return function(e){var a=e.requestId,u=e.url,c=e.payload,s=e.useSendBeacon,d=JSON.stringify(c),l=JSON.parse(d);return n.logOnBeforeNetworkRequest({url:u,requestId:a,payload:l}),function e(){var c=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return(s?r:t)(u,d).then((function(t){var r;if(o({response:t,retriesAttempted:c})){var s=i({response:t,retriesAttempted:c});return new Promise((function(n){setTimeout((function(){n(e(c+1))}),s)}))}try{r=JSON.parse(t.body)}catch(e){}return n.logOnNetworkResponse(Xu(Xu({requestId:a,url:u,payload:l},t),{},{parsedBody:r,retriesAttempted:c})),{statusCode:t.statusCode,body:t.body,parsedBody:r,getHeader:t.getHeader}}))}().catch((function(e){throw n.logOnNetworkError({requestId:a,url:u,payload:l,error:e}),Re({error:e,message:"Network request failed."})}))}}({logger:o,sendFetchRequest:Uu,sendBeaconRequest:p,isRequestRetryable:Pu,getRequestRetryDelay:Ru}),m=function(e){var n=e.logger;return function(e){var t=e.statusCode,r=e.body,o=e.parsedBody;if(t<200||t>=300||!o&&204!==t||o&&!Array.isArray(o.handle)){var i=o?JSON.stringify(o,null,2):r;throw new Error(ku+" status code "+t+" and "+(i?"response body:\n"+i:"no response body."))}if(o){var a=o.warnings,u=void 0===a?[]:a,c=o.errors,s=void 0===c?[]:c;u.forEach((function(e){n.warn(ku+" warning:",e)})),s.forEach((function(e){n.error(ku+" non-fatal error:",e)}))}}}({logger:o}),v=function(e){var n=e.logger;return function(e){if(e){var t=e.split(";");if(t.length>=2&&t[1].length>0)try{var r=parseInt(t[1],10);if(!isNaN(r))return{regionId:r}}catch(e){}n.warn('Invalid adobe edge: "'+e+'"')}return{}}}({logger:o}),y=function(e){var n=e.extractEdgeInfo;return function(e){var t=e.content,r=void 0===t?{}:t,o=e.getHeader,i=r.handle,a=void 0===i?[]:i,u=r.errors,c=void 0===u?[]:u,s=r.warnings,d=void 0===s?[]:s;return{getPayloadsByType:function(e){return Z(a.filter((function(n){return n.type===e})),(function(e){return e.payload}))},getErrors:function(){return c},getWarnings:function(){return d},getEdge:function(){return n(o("x-adobe-edge"))},toJSON:function(){return r}}}}({extractEdgeInfo:v}),b=Tu({orgId:s,cookieJar:h}),w=function(e){var n=e.config,t=e.lifecycle,r=e.cookieTransfer,o=e.sendNetworkRequest,i=e.createResponse,a=e.processWarningsAndErrors,u=e.getLocationHint,c=e.getAssuranceValidationTokenParams,s=n.edgeDomain,d=n.edgeBasePath,l=n.datastreamId;return function(e){var n=e.request,f=e.runOnResponseCallbacks,p=void 0===f?ge:f,g=e.runOnRequestFailureCallbacks,m=void 0===g?ge:g,v=E();v.add(t.onResponse),v.add(p);var h=E();return h.add(t.onRequestFailure),h.add(m),t.onBeforeRequest({request:n,onResponse:v.add,onRequestFailure:h.add}).then((function(){var e=n.getUseIdThirdPartyDomain()?"adobedc.demdex.net":s,t=u(),i=t?d+"/"+t+n.getEdgeSubPath():""+d+n.getEdgeSubPath(),a=n.getDatastreamIdOverride()||l,f=n.getPayload();a!==l&&f.mergeMeta({sdkConfig:{datastream:{original:l}}});var p="https://"+e+"/"+i+"/v1/"+n.getAction()+"?configId="+a+"&requestId="+n.getId()+c();return r.cookiesToPayload(f,e),o({requestId:n.getId(),url:p,payload:f,useSendBeacon:n.getUseSendBeacon()})})).then((function(e){return a(e),e})).catch(Su(h)).then((function(e){var n=e.parsedBody,t=e.getHeader,o=i({content:n,getHeader:t});return r.responseToCookies(o),v.call({response:o}).then(Cu)}))}}({config:t,lifecycle:u,cookieTransfer:f,sendNetworkRequest:g,createResponse:y,processWarningsAndErrors:m,getLocationHint:b,getAssuranceValidationTokenParams:Bu}),I=function(e){var n=e.cookieTransfer,t=e.lifecycle,r=e.createResponse,o=e.processWarningsAndErrors;return function(e){var i=e.request,a=e.responseHeaders,u=e.responseBody,c=e.runOnResponseCallbacks,s=void 0===c?ge:c,d=e.runOnRequestFailureCallbacks,l=void 0===d?ge:d,f=E();f.add(t.onResponse),f.add(s);var p=E();p.add(t.onRequestFailure),p.add(l);var g=function(e){return a[e]};return t.onBeforeRequest({request:i,onResponse:f.add,onRequestFailure:p.add}).then((function(){return o({statusCode:200,getHeader:g,body:JSON.stringify(u),parsedBody:u})})).catch(Su(p)).then((function(){var e=r({content:u,getHeader:g});return n.responseToCookies(e),f.call({response:e}).then(Cu)}))}}({lifecycle:u,cookieTransfer:f,createResponse:y,processWarningsAndErrors:m}),C=function(e){var n=e.generalConsentState,t=e.logger,r=function(e,r){switch(e[Ln]){case xn:n.in(r);break;case qn:n.out(r);break;case jn:n.pending(r);break;default:t.warn("Unknown consent value: "+e[Ln])}};return{initializeConsent:function(e,n){n[Ln]?r(n,Fn):r(e,Un)},setConsent:function(e){r(e,Bn)},suspend:function(){n.pending()},awaitConsent:function(){return n.awaitConsent()},withConsent:function(){return n.withConsent()},current:function(){return n.current()}}}({generalConsentState:Vn({logger:o}),logger:o}),S=function(e){var n=e.config,t=e.logger,r=e.lifecycle,o=e.consent,i=e.createEvent,a=e.createDataCollectionRequestPayload,u=e.createDataCollectionRequest,c=e.sendEdgeNetworkRequest,s=e.applyResponse,d=n.onBeforeEventSend,l=n.edgeConfigOverrides;return{createEvent:i,sendEvent:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=n.edgeConfigOverrides,s=Yu(n,wu),f=Bt({payload:a(),localConfigOverrides:i,globalConfigOverrides:l}),p=u(f),g=E(),m=E();return r.onBeforeEvent(Xu(Xu({},s),{},{event:e,onResponse:g.add,onRequestFailure:m.add})).then((function(){return f.payload.addEvent(e),o.awaitConsent()})).then((function(){try{e.finalize(d)}catch(o){var n=function(){throw o};return m.add(r.onRequestFailure),m.call({error:o}).then(n,n)}if(!e.shouldSend()){m.add(r.onRequestFailure),t.info(Eu);var o=new Error(Eu);return m.call({error:o}).then((function(){}))}return c({request:p,runOnResponseCallbacks:g.call,runOnRequestFailureCallbacks:m.call})}))},applyResponse:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},t=n.renderDecisions,o=void 0!==t&&t,i=n.decisionContext,c=void 0===i?{}:i,d=n.responseHeaders,l=void 0===d?{}:d,f=n.responseBody,p=void 0===f?{handle:[]}:f,g=n.personalization,m=a(),v=u({payload:m}),h=E();return r.onBeforeEvent({event:e,renderDecisions:o,decisionContext:c,decisionScopes:[ur],personalization:g,onResponse:h.add,onRequestFailure:ge}).then((function(){return m.addEvent(e),s({request:v,responseHeaders:l,responseBody:p,runOnResponseCallbacks:h.call})}))}}}({config:t,logger:o,lifecycle:u,consent:C,createEvent:Jn,createDataCollectionRequestPayload:Ut,createDataCollectionRequest:jt,sendEdgeNetworkRequest:w,applyResponse:I});return function(e){var n=e.componentCreators,t=e.lifecycle,r=e.componentRegistry,o=e.getImmediatelyAvailableTools;return n.forEach((function(e){var n,t=e.namespace,i=o(t);try{n=e(i)}catch(e){throw Re({error:e,message:"["+t+"] An error occurred during component creation."})}r.register(t,n)})),t.onComponentsRegistered({lifecycle:t}).then((function(){return r}))}({componentCreators:mu,lifecycle:u,componentRegistry:a,getImmediatelyAvailableTools:function(e){var r=i(e);return{config:t,componentRegistry:a,consent:C,eventManager:S,fireReferrerHideableImage:Fu,logger:r,lifecycle:u,sendEdgeNetworkRequest:w,handleError:yu({errorPrefix:"["+n+"] ["+e+"]",logger:r}),createNamespacedStorage:Ou,apexDomain:_u}}})},setDebugCommand:function(e){r(e.enabled,{fromConfig:!1})},handleError:s,validateCommandOptions:Yn});return d};(gu=window.__alloyNS)&&gu.forEach((function(e){var n=Rn({console:Nu,locationSearch:window.location.search,createLogger:bu,instanceName:e,createNamespacedStorage:Ou,getMonitors:ju}),t=function(e){return function(n){var t=n[0],r=n[1],o=n[2],i=o[0],a=o[1];e(i,a).then(t,r)}}(Hu({instanceName:e,logController:n})),r=window[e].q;r.push=t,n.logger.logOnInstanceCreated({instance:t}),r.forEach(t)}))}function Vu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function zu(e){if(e.__esModule)return e;var n=e.default;if("function"==typeof n){var t=function e(){return this instanceof e?Reflect.construct(n,arguments,this.constructor):n.apply(this,arguments)};t.prototype=n.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(e).forEach((function(n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})})),t}
+/*
+ object-assign
+ (c) Sindre Sorhus
+ @license MIT
+ */function Ju(e,n){(null==n||n>e.length)&&(n=e.length);for(var t=0,r=Array(n);t1&&void 0!==arguments[1]?arguments[1]:0;return(Ae[e[n+0]]+Ae[e[n+1]]+Ae[e[n+2]]+Ae[e[n+3]]+"-"+Ae[e[n+4]]+Ae[e[n+5]]+"-"+Ae[e[n+6]]+Ae[e[n+7]]+"-"+Ae[e[n+8]]+Ae[e[n+9]]+"-"+Ae[e[n+10]]+Ae[e[n+11]]+Ae[e[n+12]]+Ae[e[n+13]]+Ae[e[n+14]]+Ae[e[n+15]]).toLowerCase()}(r)}function ic(e){return Boolean(e&&void 0!==e.length)}function ac(){}function uc(e){if(!(this instanceof uc))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],pc(e,this)}function cc(e,n){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,uc._immediateFn((function(){var t=1===e._state?n.onFulfilled:n.onRejected;if(null!==t){var r;try{r=t(e._value)}catch(e){return void dc(n.promise,e)}sc(n.promise,r)}else(1===e._state?sc:dc)(n.promise,e._value)}))):e._deferreds.push(n)}function sc(e,n){try{if(n===e)throw new TypeError("A promise cannot be resolved with itself.");if(n&&("object"===Zu(n)||"function"==typeof n)){var t=n.then;if(n instanceof uc)return e._state=3,e._value=n,void lc(e);if("function"==typeof t)return void pc(function(e,n){return function(){e.apply(n,arguments)}}(t,n),e)}e._state=1,e._value=n,lc(e)}catch(n){dc(e,n)}}function dc(e,n){e._state=2,e._value=n,lc(e)}function lc(e){2===e._state&&0===e._deferreds.length&&uc._immediateFn((function(){e._handled||uc._unhandledRejectionFn(e._value)}));for(var n=0,t=e._deferreds.length;n=o)&&(vc(r)||u.timestamp<=r);return o=u.timestamp,c}))?1:0}(e,a,r,o):function(e,n,t,r){return e.reduce((function(e,o){var i=hc(o,ca);if(!i)return e;var a=n.events[i];if(!a)return e;var u=hc(o,sa);if(!u)return e;var c=a[u];if(!c)return e;if(!yc(o,c))return e;var s=c.count,d=void 0===s?1:s;return vc(t)||vc(r)||c.timestamp>=t&&c.timestamp<=r?e+d:e}),0)}(e,a,r,o),function(e,n,t){switch(n){case oa.GREATER_THAN:return e>t;case oa.GREATER_THAN_OR_EQUAL_TO:return e>=t;case oa.LESS_THAN:return e0}))},getVersion:function(){return t},numRules:function(){return r.length}}}}();
\ No newline at end of file
diff --git a/scripts/adobe-martech/index.js b/scripts/adobe-martech/index.js
new file mode 100644
index 00000000..f2b7a5ec
--- /dev/null
+++ b/scripts/adobe-martech/index.js
@@ -0,0 +1,469 @@
+/* eslint-disable no-underscore-dangle */
+/**
+ * Default configuration for the library.
+ * @typedef {Object} MartechConfig
+ * @property {Boolean} analytics Indicates whether analytics tracking should be enabled
+ * (defaults to true)
+ * @property {String} alloyInstanceName The name of the alloy instance in the global scope
+ * (defaults to "alloy")
+ * @property {Boolean} dataLayer Indicates whether the data layer should be used
+ * (defaults to true)
+ * @property {String} dataLayerInstanceName The name of the data ayer instance in the global scope
+ * (defaults to "adobeDataLayer")
+ * @property {String[]} launchUrls A list of launch container URLs to load (defults to empty list)
+ * @property {Boolean} personalization Indicates whether Adobe Target should be enabled
+ * (defaults to true)
+ * @property {Number} personalizationTimeout Indicates the amount of time to wait before bailing
+ * out on the personalization and continue rendering the
+ * page (defaults to 1s)
+ */
+export const DEFAULT_CONFIG = {
+ analytics: true,
+ alloyInstanceName: 'alloy',
+ dataLayer: true,
+ dataLayerInstanceName: 'adobeDataLayer',
+ launchUrls: [],
+ personalization: true,
+ personalizationTimeout: 1000,
+};
+
+let config;
+let alloyConfig;
+let isAlloyConfigured = false;
+const pendingAlloyCommands = [];
+
+/**
+ * Runs a promise with a timeout that rejects it if the time has passed.
+ * @param {Promise} promise The base promise to use
+ * @param {Number} [timeout=1000] The timeout to use in ms
+ * @returns the promise result, or a rejected promise if it did not resolve in time
+ */
+function promiseWithTimeout(promise, timeout = 1000) {
+ let timer;
+ return Promise.race([
+ promise,
+ new Promise((_, reject) => { timer = setTimeout(reject, timeout); }),
+ ]).finally(() => clearTimeout(timer));
+}
+
+/**
+ * Error handler for rejected promises.
+ * @param {Error} error The base error
+ * @throws a decorated error that can be intercepted by RUM handlers.
+ */
+function handleRejectedPromise(error) {
+ const [, file, line] = error.stack.split('\n')[1].trim().split(' ')[1].match(/(.*):(\d+):(\d+)/);
+ error.sourceURL = file;
+ error.line = line;
+ throw error;
+}
+
+/**
+ * Initializes a queue for the alloy instance in order to be ready to receive events before the
+ * alloy library is fully loaded.
+ * Documentation:
+ * https://experienceleague.adobe.com/docs/experience-platform/edge/fundamentals/installing-the-sdk.html?lang=en#adding-the-code
+ * @param {String} instanceName The name of the instance in the blobal scope
+ */
+function initAlloyQueue(instanceName) {
+ if (window[instanceName]) {
+ return;
+ }
+ // eslint-disable-next-line no-underscore-dangle
+ (window.__alloyNS ||= []).push(instanceName);
+ window[instanceName] = (...args) => new Promise((resolve, reject) => {
+ window.setTimeout(() => {
+ window[instanceName].q.push([resolve, reject, args]);
+ });
+ });
+ window[instanceName].q = [];
+}
+
+/**
+ * Initializes a queue for the datalayer in order to be ready to receive events before the
+ * ACDL library is fully loaded.
+ * Documentation:
+ * https://github.com/adobe/adobe-client-data-layer/wiki#setup
+ * @param {String} instanceName The name of the instance in the blobal scope
+ */
+function initDatalayer(instanceName) {
+ window[instanceName] ||= [];
+}
+
+/**
+ * Returns the default alloy configuration
+ * Documentation:
+ * https://experienceleague.adobe.com/docs/experience-platform/edge/fundamentals/configuring-the-sdk.html
+ */
+function getDefaultAlloyConfiguration() {
+ const { hostname } = window.location;
+
+ return {
+ context: ['web', 'device', 'environment'],
+ // enable while debugging
+ debugEnabled: hostname === 'localhost' || hostname.endsWith('.hlx.page') || hostname.endsWith('.aem.page'),
+ // wait for exlicit consent before tracking anything
+ defaultConsent: 'pending',
+ };
+}
+
+/**
+ * Loads the alloy library and configures it.
+ * Documentation:
+ * https://experienceleague.adobe.com/docs/experience-platform/edge/fundamentals/configuring-the-sdk.html
+ * @param {String} instanceName The name of the instance in the blobal scope
+ * @param {Object} webSDKConfig The configuration to use
+ * @returns a promise that the library was loaded and configured
+ */
+async function loadAndConfigureAlloy(instanceName, webSDKConfig) {
+ await import('./alloy.min.js');
+ try {
+ await window[instanceName]('configure', webSDKConfig);
+ isAlloyConfigured = true;
+ pendingAlloyCommands.forEach((fn) => fn());
+ } catch (err) {
+ handleRejectedPromise(new Error(err));
+ }
+}
+
+/**
+ * Runs the specified function on every decorated block/section
+ * @param {Function} fn The function to call
+ */
+function onDecoratedElement(fn) {
+ // Apply propositions to all already decorated blocks/sections
+ if (document.querySelector('[data-block-status="loaded"],[data-section-status="loaded"]')) {
+ fn();
+ }
+
+ const observer = new MutationObserver((mutations) => {
+ if (mutations.some((m) => m.target.tagName === 'BODY'
+ || m.target.dataset.sectionStatus === 'loaded'
+ || m.target.dataset.blockStatus === 'loaded')) {
+ fn();
+ }
+ });
+ // Watch sections and blocks being decorated async
+ observer.observe(document.querySelector('main'), {
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['data-block-status', 'data-section-status'],
+ });
+ // Watch anything else added to the body
+ document.querySelectorAll('body').forEach((el) => {
+ observer.observe(el, { childList: true });
+ });
+}
+
+/**
+ * Pushes data to the data layer
+ * @param {Object} payload the data to push
+ */
+export function pushToDataLayer(payload) {
+ // eslint-disable-next-line no-console
+ console.assert(config.dataLayerInstanceName && window[config.dataLayerInstanceName], 'Martech needs to be initialized before the `pushToDataLayer` method is called');
+ window[config.dataLayerInstanceName].push(payload);
+}
+
+/**
+ * Pushes an event to the data layer
+ * @param {String} event the name of the event to push
+ * @param {Object} xdm the xdm data object to send
+ * @param {Object} [data] additional data mapping for the event
+ */
+export function pushEventToDataLayer(event, xdm, data) {
+ pushToDataLayer({ event, xdm, data });
+}
+
+/**
+ * Sends an analytics event to alloy
+ * @param {Object} xdmData the xdm data object to send
+ * @param {Object} [dataMapping] additional data mapping for the event
+ * @returns {Promise<*>} a promise that the event was sent
+ */
+export async function sendAnalyticsEvent(xdmData, dataMapping) {
+ // eslint-disable-next-line no-console
+ console.assert(config.alloyInstanceName && window[config.alloyInstanceName], 'Martech needs to be initialized before the `sendAnalyticsEvent` method is called');
+ // eslint-disable-next-line no-console
+ console.assert(config.analytics, 'Analytics tracking is disabled in the martech config');
+ try {
+ // eslint-disable-next-line no-undef
+ return window[config.alloyInstanceName]('sendEvent', {
+ documentUnloading: true,
+ xdm: xdmData,
+ data: dataMapping,
+ });
+ } catch (err) {
+ handleRejectedPromise(new Error(err));
+ return Promise.reject(new Error(err));
+ }
+}
+
+/**
+ * Loads the ACDL library.
+ * @returns the ACDL instance
+ */
+async function loadAndConfigureDataLayer() {
+ await import('./acdl.min.js');
+ if (config.analytics) {
+ window[config.dataLayerInstanceName].push((dl) => {
+ dl.addEventListener('adobeDataLayer:event', (event) => {
+ sendAnalyticsEvent({ eventType: event.event, ...event.xdm }, event.data);
+ });
+ });
+ }
+ [...document.querySelectorAll('[data-block-data-layer]')].forEach((el) => {
+ let data;
+ try {
+ data = JSON.parse(el.dataset.blockDataLayer);
+ } catch (err) {
+ data = {};
+ }
+ if (!el.id) {
+ const index = [...document.querySelectorAll(`.${el.classList[0]}`)].indexOf(el);
+ el.id = `${data.parentId ? `${data.parentId}-` : ''}${index + 1}`;
+ }
+ window[config.dataLayerInstanceName].push({
+ blocks: { [el.id]: data },
+ });
+ });
+}
+
+/**
+ * Sets Adobe standard v2.0 consent for alloy based on the input
+ * Documentation:
+ * https://experienceleague.adobe.com/en/docs/experience-platform/landing/governance-privacy-security/consent/adobe/dataset#structure
+ * https://experienceleague.adobe.com/en/docs/experience-platform/xdm/data-types/consents
+ * @param {Object} config The consent config to use
+ * @param {Boolean} [config.collect] Whether data collection is allowed
+ * @param {Boolean} [config.marketing] Whether data can be used for marketing purposes
+ * @param {Boolean} [config.personalize] Whether data can be used for personalization purposes
+ * @param {Boolean} [config.share] Whether data can be shared/sold to 3rd parties
+ * @returns {Promise<*>} a promise that the consent setting shave been updated
+ */
+export async function updateUserConsent(consent) {
+ // eslint-disable-next-line no-console
+ console.assert(config.alloyInstanceName, 'Martech needs to be initialized before the `updateUserConsent` method is called');
+
+ const fn = () => window[config.alloyInstanceName]('setConsent', {
+ consent: [{
+ standard: 'Adobe',
+ version: '2.0',
+ value: {
+ collect: { val: consent.collect ? 'y' : 'n' },
+ marketing: {
+ any: { val: consent.marketing ? 'y' : 'n' },
+ preferred: 'email',
+ },
+ personalize: {
+ content: { val: consent.personalize ? 'y' : 'n' },
+ },
+ share: { val: consent.share ? 'y' : 'n' },
+ },
+ }],
+ });
+ if (isAlloyConfigured) {
+ return fn();
+ }
+ pendingAlloyCommands.push(fn);
+ return Promise.resolve();
+}
+
+/**
+ * Converts an internal element selector to a proper CSS selector.
+ * @param {String} selector the internal selector
+ * @returns {String} the corresponding CSS selector
+ */
+function toCssSelector(selector) {
+ return selector.replace(/(\.\S+)?:eq\((\d+)\)/g, (_, clss, i) => `:nth-child(${Number(i) + 1}${clss ? ` of ${clss})` : ''}`);
+}
+
+/**
+ * Find the element for the specified proposition.
+ * @param {Object} proposition The proprosition for the element
+ * @param {String} [proposition.cssSelector] The CSS selector for the proposition
+ * @param {String} [proposition.selector] The internal selector for the proposition
+ * @returns {HTMLElement} The DOM element for the proposition
+ */
+async function getElementForProposition(proposition) {
+ const selector = proposition.data.prehidingSelector || toCssSelector(proposition.data.selector);
+ return document.querySelector(selector);
+}
+
+let response;
+
+/**
+ * Fetching propositions from the backend and applying the propositions as the AEM EDS page loads
+ * its content async.
+ * Documentation:
+ * https://experienceleague.adobe.com/en/docs/experience-platform/web-sdk/personalization/rendering-personalization-content#manual
+ * @param {String} instanceName The name of the instance in the blobal scope
+ * @returns a promise that the propositions were retrieved and will be applied as the page renders
+ */
+async function applyPropositions(instanceName) {
+ // Get the decisions, but don't render them automatically
+ // so we can hook up into the AEM EDS page load sequence
+ const renderDecisionResponse = await window[instanceName]('sendEvent', {
+ type: 'decisioning.propositionFetch',
+ renderDecisions: false,
+ personalization: {
+ sendDisplayEvent: false,
+ },
+ });
+ response = renderDecisionResponse;
+ if (!renderDecisionResponse?.propositions) {
+ return [];
+ }
+ const propositions = window.structuredClone(renderDecisionResponse.propositions);
+ onDecoratedElement(async () => {
+ if (!propositions.length) {
+ return;
+ }
+ await window[instanceName]('applyPropositions', { propositions });
+ propositions.forEach((p) => {
+ p.items = p.items.filter((i) => i.schema !== 'https://ns.adobe.com/personalization/dom-action' || !getElementForProposition(i));
+ });
+ });
+ return renderDecisionResponse;
+}
+
+/**
+ * Initializes the martech library.
+ * Documentation:
+ * https://experienceleague.adobe.com/en/docs/experience-platform/web-sdk/commands/configure/overview
+ * @param {Object} webSDKConfig the WebSDK config
+ * @param {Object} [martechConfig] the martech config
+ * @param {String} [martechConfig.alloyInstanceName="alloy"] the WebSDK instance name in the global
+ * scope (defaults to `alloy`)
+ * @param {String} [martechConfig.dataLayerInstanceName="adobeDataLayer"] the ACDL instance name in
+ * the global scope (defaults to `adobeDataLayer`)
+ * @param {String[]} [martechConfig.launchUrls] a list of Launch configurations to load
+ * @returns a promise that the library was loaded and configured
+ */
+export async function initMartech(webSDKConfig, martechConfig = {}) {
+ // eslint-disable-next-line no-console
+ console.assert(!config, 'Martech already initialized.');
+ // eslint-disable-next-line no-console
+ console.assert(webSDKConfig?.datastreamId || webSDKConfig?.edgeConfigId, 'Please set your "datastreamId" for the WebSDK config.');
+ // eslint-disable-next-line no-console
+ console.assert(webSDKConfig?.orgId, 'Please set your "orgId" for the WebSDK config.');
+
+ config = {
+ ...DEFAULT_CONFIG,
+ ...martechConfig,
+ };
+
+ initAlloyQueue(config.alloyInstanceName);
+ if (config.dataLayer) {
+ initDatalayer(config.dataLayerInstanceName);
+ }
+
+ alloyConfig = {
+ ...getDefaultAlloyConfiguration(),
+ ...webSDKConfig,
+ onBeforeEventSend: (payload) => {
+ payload.data ||= {};
+ payload.data.__adobe ||= {};
+
+ // Let project override the data if needed
+ if (webSDKConfig?.onBeforeEventSend) {
+ webSDKConfig?.onBeforeEventSend(payload);
+ }
+
+ // Automatically track displayed propositions as part of the pageview event
+ if (payload.xdm?.eventType === 'web.webpagedetails.pageViews' && config.personalization) {
+ payload.xdm.eventType = 'decisioning.propositionDisplay';
+ payload.xdm._experience = {
+ decisioning: {
+ propositions: response.propositions
+ .map((p) => ({ id: p.id, scope: p.scope, scopeDetails: p.scopeDetails })),
+ propositionEventType: { display: 1 },
+ },
+ };
+ }
+ },
+ };
+ if (config.personalization) {
+ await loadAndConfigureAlloy(config.alloyInstanceName, alloyConfig);
+ }
+ return Promise.resolve();
+}
+
+const debug = (label = 'martech', ...args) => {
+ if (alloyConfig.debugEnabled) {
+ // eslint-disable-next-line no-console
+ console.debug.call(null, `[${label}]`, ...args);
+ }
+};
+
+export function initRumTracking(sampleRUM, options = {}) {
+ // Load the RUM enhancer so we can map all RUM events even on non-sampled pages
+ if (options.withRumEnhancer) {
+ const script = document.createElement('script');
+ script.src = new URL('.rum/@adobe/helix-rum-enhancer@^1/src/index.js', sampleRUM.baseURL).href;
+ document.head.appendChild(script);
+ }
+
+ // Define RUM tracking function
+ let track;
+ if (sampleRUM.always) {
+ track = (ev, cb) => sampleRUM.always.on(ev, (data) => {
+ debug('rum', ev, data);
+ cb(data);
+ });
+ } else {
+ track = (ev, cb) => document.addEventListener('rum', (data) => {
+ debug('rum', ev, data);
+ cb(data);
+ });
+ }
+ return track;
+}
+
+/**
+ * Martech logic to be executed in the eager phase.
+ * @returns a promise that the eager logic was executed
+ */
+export async function martechEager() {
+ if (config.personalization) {
+ // eslint-disable-next-line no-console
+ console.assert(window.alloy, 'Martech needs to be initialized before the `martechEager` method is called');
+ return promiseWithTimeout(
+ applyPropositions(config.alloyInstanceName),
+ config.personalizationTimeout,
+ ).catch(() => {
+ if (alloyConfig.debugEnabled) {
+ // eslint-disable-next-line no-console
+ console.warn('Could not apply personalization in time. Either backend is taking too long, or user did not give consent in time.');
+ }
+ });
+ }
+ return Promise.resolve();
+}
+
+/**
+ * Martech logic to be executed in the lazy phase.
+ * @returns a promise that the lazy logic was executed
+ */
+export async function martechLazy() {
+ if (config.dataLayer) {
+ await loadAndConfigureDataLayer({});
+ }
+
+ if (!config.personalization) {
+ await loadAndConfigureAlloy(config.alloyInstanceName, alloyConfig);
+ }
+}
+
+/**
+ * Martech logic to be executed in the delayed phase.
+ * @returns a promise that the delayed logic was executed
+ */
+export async function martechDelayed() {
+ // eslint-disable-next-line no-console
+ console.assert(window.alloy, 'Martech needs to be initialized before the `martechDelayed` method is called');
+
+ const { launchUrls } = config;
+ return Promise.all(launchUrls.map((url) => import(url)))
+ .catch((err) => handleRejectedPromise(new Error(err)));
+}
diff --git a/scripts/analytics/alloy.js b/scripts/analytics/alloy.js
deleted file mode 100644
index 65279cb0..00000000
--- a/scripts/analytics/alloy.js
+++ /dev/null
@@ -1,11658 +0,0 @@
-/**
- * Copyright 2019 Adobe. All rights reserved.
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License. You may obtain a copy
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- * OF ANY KIND, either express or implied. See the License for the specific language
- * governing permissions and limitations under the License.
- */
-
-(function () {
- 'use strict';
-
- if (document.documentMode && document.documentMode < 11) {
- console.warn('The Adobe Experience Cloud Web SDK does not support IE 10 and below.');
- return;
- }
-
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createInstanceFunction = (function (executeCommand) {
- return function (args) {
- // Would use destructuring, but destructuring doesn't work on IE
- // without polyfilling Symbol.
- // https://github.com/babel/babel/issues/7597
- var resolve = args[0];
- var reject = args[1];
- var userProvidedArgs = args[2];
- var commandName = userProvidedArgs[0];
- var options = userProvidedArgs[1];
- executeCommand(commandName, options).then(resolve, reject);
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var CHROME = "Chrome";
- var EDGE$1 = "Edge";
- var EDGE_CHROMIUM = "EdgeChromium";
- var FIREFOX = "Firefox";
- var IE = "IE";
- var SAFARI = "Safari";
- var UNKNOWN = "Unknown";
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Determines whether an array includes a certain value.
- * @param {Array} arr Array to search.
- * @param {*} item The item for which to search.
- * @returns {boolean}
- */
- var includes = (function (arr, item) {
- return arr.indexOf(item) !== -1;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- // we don't know. We also assume "unknown" browsers support third-party cookies,
- // though we don't really know that either. We're making best guesses.
-
- var browsersSupportingThirdPartyCookie = [CHROME, EDGE$1, EDGE_CHROMIUM, IE, UNKNOWN];
- var areThirdPartyCookiesSupportedByDefault = (function (browser) {
- return includes(browsersSupportingThirdPartyCookie, browser);
- });
-
- /*
- object-assign
- (c) Sindre Sorhus
- @license MIT
- */
- /* eslint-disable no-unused-vars */
-
- var getOwnPropertySymbols = Object.getOwnPropertySymbols;
- var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
- var propIsEnumerable = Object.prototype.propertyIsEnumerable;
-
- function toObject(val) {
- if (val === null || val === undefined) {
- throw new TypeError('Object.assign cannot be called with null or undefined');
- }
-
- return Object(val);
- }
-
- function shouldUseNative() {
- try {
- if (!Object.assign) {
- return false;
- } // Detect buggy property enumeration order in older V8 versions.
- // https://bugs.chromium.org/p/v8/issues/detail?id=4118
-
-
- var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
-
- test1[5] = 'de';
-
- if (Object.getOwnPropertyNames(test1)[0] === '5') {
- return false;
- } // https://bugs.chromium.org/p/v8/issues/detail?id=3056
-
-
- var test2 = {};
-
- for (var i = 0; i < 10; i++) {
- test2['_' + String.fromCharCode(i)] = i;
- }
-
- var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
- return test2[n];
- });
-
- if (order2.join('') !== '0123456789') {
- return false;
- } // https://bugs.chromium.org/p/v8/issues/detail?id=3056
-
-
- var test3 = {};
- 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
- test3[letter] = letter;
- });
-
- if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') {
- return false;
- }
-
- return true;
- } catch (err) {
- // We don't expect any of the above to throw, but better to be safe.
- return false;
- }
- }
-
- var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
- var from;
- var to = toObject(target);
- var symbols;
-
- for (var s = 1; s < arguments.length; s++) {
- from = Object(arguments[s]);
-
- for (var key in from) {
- if (hasOwnProperty$1.call(from, key)) {
- to[key] = from[key];
- }
- }
-
- if (getOwnPropertySymbols) {
- symbols = getOwnPropertySymbols(from);
-
- for (var i = 0; i < symbols.length; i++) {
- if (propIsEnumerable.call(from, symbols[i])) {
- to[symbols[i]] = from[symbols[i]];
- }
- }
- }
- }
-
- return to;
- };
-
- var reactorObjectAssign = objectAssign;
-
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
-
- function createCommonjsModule(fn, module) {
- return module = { exports: {} }, fn(module, module.exports), module.exports;
- }
-
- var js_cookie = createCommonjsModule(function (module, exports) {
-
- (function (factory) {
- var registeredInModuleLoader;
-
- {
- module.exports = factory();
- registeredInModuleLoader = true;
- }
-
- if (!registeredInModuleLoader) {
- var OldCookies = window.Cookies;
- var api = window.Cookies = factory();
-
- api.noConflict = function () {
- window.Cookies = OldCookies;
- return api;
- };
- }
- })(function () {
- function extend() {
- var i = 0;
- var result = {};
-
- for (; i < arguments.length; i++) {
- var attributes = arguments[i];
-
- for (var key in attributes) {
- result[key] = attributes[key];
- }
- }
-
- return result;
- }
-
- function decode(s) {
- return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
- }
-
- function init(converter) {
- function api() {}
-
- function set(key, value, attributes) {
- if (typeof document === 'undefined') {
- return;
- }
-
- attributes = extend({
- path: '/'
- }, api.defaults, attributes);
-
- if (typeof attributes.expires === 'number') {
- attributes.expires = new Date(new Date() * 1 + attributes.expires * 864e+5);
- } // We're using "expires" because "max-age" is not supported by IE
-
-
- attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';
-
- try {
- var result = JSON.stringify(value);
-
- if (/^[\{\[]/.test(result)) {
- value = result;
- }
- } catch (e) {}
-
- value = converter.write ? converter.write(value, key) : encodeURIComponent(String(value)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
- key = encodeURIComponent(String(key)).replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent).replace(/[\(\)]/g, escape);
- var stringifiedAttributes = '';
-
- for (var attributeName in attributes) {
- if (!attributes[attributeName]) {
- continue;
- }
-
- stringifiedAttributes += '; ' + attributeName;
-
- if (attributes[attributeName] === true) {
- continue;
- } // Considers RFC 6265 section 5.2:
- // ...
- // 3. If the remaining unparsed-attributes contains a %x3B (";")
- // character:
- // Consume the characters of the unparsed-attributes up to,
- // not including, the first %x3B (";") character.
- // ...
-
-
- stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
- }
-
- return document.cookie = key + '=' + value + stringifiedAttributes;
- }
-
- function get(key, json) {
- if (typeof document === 'undefined') {
- return;
- }
-
- var jar = {}; // To prevent the for loop in the first place assign an empty array
- // in case there are no cookies at all.
-
- var cookies = document.cookie ? document.cookie.split('; ') : [];
- var i = 0;
-
- for (; i < cookies.length; i++) {
- var parts = cookies[i].split('=');
- var cookie = parts.slice(1).join('=');
-
- if (!json && cookie.charAt(0) === '"') {
- cookie = cookie.slice(1, -1);
- }
-
- try {
- var name = decode(parts[0]);
- cookie = (converter.read || converter)(cookie, name) || decode(cookie);
-
- if (json) {
- try {
- cookie = JSON.parse(cookie);
- } catch (e) {}
- }
-
- jar[name] = cookie;
-
- if (key === name) {
- break;
- }
- } catch (e) {}
- }
-
- return key ? jar[key] : jar;
- }
-
- api.set = set;
-
- api.get = function (key) {
- return get(key, false
- /* read as raw */
- );
- };
-
- api.getJSON = function (key) {
- return get(key, true
- /* read as json */
- );
- };
-
- api.remove = function (key, attributes) {
- set(key, '', extend(attributes, {
- expires: -1
- }));
- };
-
- api.defaults = {};
- api.withConverter = init;
- return api;
- }
-
- return init(function () {});
- });
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var cookieJar = {
- get: js_cookie.get,
- set: js_cookie.set,
- remove: js_cookie.remove,
- withConverter: js_cookie.withConverter
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Returns true when the value is null.
- * @param {*} value
- * @returns {boolean}
- */
- var isNil = (function (value) {
- return value == null;
- });
-
- function ownKeys(object, enumerableOnly) {
- var keys = Object.keys(object);
-
- if (Object.getOwnPropertySymbols) {
- var symbols = Object.getOwnPropertySymbols(object);
- enumerableOnly && (symbols = symbols.filter(function (sym) {
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
- })), keys.push.apply(keys, symbols);
- }
-
- return keys;
- }
-
- function _objectSpread2(target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = null != arguments[i] ? arguments[i] : {};
- i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
- _defineProperty(target, key, source[key]);
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
- });
- }
-
- return target;
- }
-
- function _typeof(obj) {
- "@babel/helpers - typeof";
-
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
- return typeof obj;
- } : function (obj) {
- return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- }, _typeof(obj);
- }
-
- function _defineProperty(obj, key, value) {
- if (key in obj) {
- Object.defineProperty(obj, key, {
- value: value,
- enumerable: true,
- configurable: true,
- writable: true
- });
- } else {
- obj[key] = value;
- }
-
- return obj;
- }
-
- function _objectWithoutPropertiesLoose(source, excluded) {
- if (source == null) return {};
- var target = {};
- var sourceKeys = Object.keys(source);
- var key, i;
-
- for (i = 0; i < sourceKeys.length; i++) {
- key = sourceKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- target[key] = source[key];
- }
-
- return target;
- }
-
- function _objectWithoutProperties(source, excluded) {
- if (source == null) return {};
-
- var target = _objectWithoutPropertiesLoose(source, excluded);
-
- var key, i;
-
- if (Object.getOwnPropertySymbols) {
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
-
- for (i = 0; i < sourceSymbolKeys.length; i++) {
- key = sourceSymbolKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
- target[key] = source[key];
- }
- }
-
- return target;
- }
-
- function _slicedToArray(arr, i) {
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
- }
-
- function _toConsumableArray(arr) {
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
- }
-
- function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr)) return _arrayLikeToArray(arr);
- }
-
- function _arrayWithHoles(arr) {
- if (Array.isArray(arr)) return arr;
- }
-
- function _iterableToArray(iter) {
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
- }
-
- function _iterableToArrayLimit(arr, i) {
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
-
- if (_i == null) return;
- var _arr = [];
- var _n = true;
- var _d = false;
-
- var _s, _e;
-
- try {
- for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
- _arr.push(_s.value);
-
- if (i && _arr.length === i) break;
- }
- } catch (err) {
- _d = true;
- _e = err;
- } finally {
- try {
- if (!_n && _i["return"] != null) _i["return"]();
- } finally {
- if (_d) throw _e;
- }
- }
-
- return _arr;
- }
-
- function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
- }
-
- function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
-
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
-
- return arr2;
- }
-
- function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
-
- function _nonIterableRest() {
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
-
- /**
- * Returns whether the value is an object.
- * @param {*} value
- * @returns {boolean}
- */
-
- var isObject = (function (value) {
- return !isNil(value) && !Array.isArray(value) && _typeof(value) === "object";
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var deepAssignObject = function deepAssignObject(target, source) {
- Object.keys(source).forEach(function (key) {
- if (isObject(target[key]) && isObject(source[key])) {
- deepAssignObject(target[key], source[key]);
- return;
- }
-
- target[key] = source[key];
- });
- };
- /**
- * Recursively copy the values of all enumerable own properties from a source item to a target item if the both items are objects
- * @param {Object} target - a target object
- * @param {...Object} source - an array of source objects
- * @example
- * deepAssign({ a: 'a', b: 'b' }, { b: 'B', c: 'c' });
- * // { a: 'a', b: 'B', c: 'c' }
- */
-
-
- var deepAssign = (function (target) {
- if (isNil(target)) {
- throw new TypeError('deepAssign "target" cannot be null or undefined');
- }
-
- var result = Object(target);
-
- for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- sources[_key - 1] = arguments[_key];
- }
-
- sources.forEach(function (source) {
- return deepAssignObject(result, Object(source));
- });
- return result;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Creates a function that, when passed an object of updates, will merge
- * the updates onto the current value of a payload property.
- * @param {Object} content The base object to modify
- * @param {String } key The property to merge updates into. This
- * can be a dot-notation property path.
- * @returns {Function}
- */
-
- var createMerger = (function (content, key) {
- return function (updates) {
- var propertyPath = key.split(".");
- var hostObjectForUpdates = propertyPath.reduce(function (obj, propertyName) {
- obj[propertyName] = obj[propertyName] || {};
- return obj[propertyName];
- }, content);
- deepAssign(hostObjectForUpdates, updates);
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Allows callbacks to be registered and then later called. When the
- * callbacks are called, their responses are combined into a single promise.
- */
- var createCallbackAggregator = (function () {
- var callbacks = [];
- return {
- add: function add(callback) {
- callbacks.push(callback);
- },
- call: function call() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- // While this utility doesn't necessarily need to be doing the
- // Promise.all, it's currently useful everywhere this is used and
- // reduces repetitive code. We can factor it out later if we want
- // to make this utility more "pure".
- return Promise.all(callbacks.map(function (callback) {
- return callback.apply(void 0, args);
- }));
- }
- };
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createLoggingCookieJar = (function (_ref) {
- var logger = _ref.logger,
- cookieJar = _ref.cookieJar;
- return _objectSpread2(_objectSpread2({}, cookieJar), {}, {
- set: function set(key, value, options) {
- logger.info("Setting cookie", _objectSpread2({
- name: key,
- value: value
- }, options));
- cookieJar.set(key, value, options);
- }
- });
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Sequences tasks.
- */
- var createTaskQueue = (function () {
- var queueLength = 0;
- var lastPromiseInQueue = Promise.resolve();
- return {
- /**
- * Add a task to the queue. If no task is currenty running,
- * the task will begin immediately.
- * @param {Function} task A function that will be called when
- * the task should be run. If the task it asynchronous, it should
- * return a promise.
- * @returns {Promise} A promise that will be resolved or rejected
- * with whatever value the task resolved or rejects its promise.
- */
- addTask: function addTask(task) {
- queueLength += 1;
-
- var lastPromiseFulfilledHandler = function lastPromiseFulfilledHandler() {
- return task().finally(function () {
- queueLength -= 1;
- });
- };
-
- lastPromiseInQueue = lastPromiseInQueue.then(lastPromiseFulfilledHandler, lastPromiseFulfilledHandler);
- return lastPromiseInQueue;
- },
-
- /**
- * How many tasks are in the queue. This includes the task
- * that's currently running.
- * @returns {number}
- */
- get length() {
- return queueLength;
- }
-
- };
- });
-
- /* eslint-disable */
-
- /*
- crc32 · JavaScript Function to Calculate CRC32 of a String
- Description
- Below is a JavaScript function to calculate CRC32 of a string.
- The string can be either ASCII or Unicode.
- Unicode strings will be encoded in UTF-8.
- The polynomial used in calculation is 0xedb88320.
- This polynomial is used in Ethernet, Gzip, PNG, SATA and many other technologies.
- */
- var crc32 = function () {
- var table = [];
-
- for (var i = 0; i < 256; i++) {
- var c = i;
-
- for (var j = 0; j < 8; j++) {
- c = c & 1 ? 0xedb88320 ^ c >>> 1 : c >>> 1;
- }
-
- table.push(c);
- }
-
- return function (str, crc) {
- str = unescape(encodeURIComponent(str));
- if (!crc) crc = 0;
- crc = crc ^ -1;
-
- for (var _i = 0; _i < str.length; _i++) {
- var y = (crc ^ str.charCodeAt(_i)) & 0xff;
- crc = crc >>> 8 ^ table[y];
- }
-
- crc = crc ^ -1;
- return crc >>> 0;
- };
- }();
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * A simple utility for managing a promise's state outside of
- * the promise's "executor" (the function passed into the constructor).
- */
- var defer = (function () {
- var deferred = {};
- deferred.promise = new Promise(function (resolve, reject) {
- deferred.resolve = resolve;
- deferred.reject = reject;
- });
- return deferred;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Whether a string ends with the characters of a specified string
- * @param {String} str The string to search within.
- * @param {String} suffix The string to search for.
- * @returns {boolean}
- */
- var endsWith = (function (str, suffix) {
- return str.substr(-suffix.length) === suffix;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Returns the first item in the array that satisfies the provided testing function.
- * @param {Array} arr The array to search.
- * @param {Function} predicate Function that will be called for each item. Arguments
- * will be the item, the item index, then the array itself.
- * @returns {*}
- */
- var find = (function (arr, predicate) {
- for (var i = 0; i < arr.length; i += 1) {
- var item = arr[i];
-
- if (predicate(item, i, arr)) {
- return item;
- }
- }
-
- return undefined;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var appendNode = (function (parent, node) {
- return parent.appendChild(node);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var populateElementProperties = function populateElementProperties(element, props) {
- Object.keys(props).forEach(function (key) {
- // The following is to support setting style properties to avoid CSP errors.
- if (key === "style" && isObject(props[key])) {
- var styleProps = props[key];
- Object.keys(styleProps).forEach(function (styleKey) {
- element.style[styleKey] = styleProps[styleKey];
- });
- } else {
- element[key] = props[key];
- }
- });
- };
-
- var createNode = (function (tag) {
- var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var props = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- var children = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
- var doc = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : document;
- var result = doc.createElement(tag);
- Object.keys(attrs).forEach(function (key) {
- // TODO: To highlight CSP problems consider throwing a descriptive error
- // if nonce is available and key is style.
- result.setAttribute(key, attrs[key]);
- });
- populateElementProperties(result, props);
- children.forEach(function (child) {
- return appendNode(result, child);
- });
- return result;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var BODY = "BODY";
- var IFRAME = "IFRAME";
- var IMG = "IMG";
- var DIV = "DIV";
- var STYLE = "STYLE";
- var SCRIPT = "SCRIPT";
- var HEAD = "HEAD";
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Fires an image pixel from the current document's window.
- * @param {object} currentDocument
- * @param {string} src
- * @returns {Promise}
- */
-
- var fireImageInDocument = (function (_ref) {
- var src = _ref.src,
- _ref$currentDocument = _ref.currentDocument,
- currentDocument = _ref$currentDocument === void 0 ? document : _ref$currentDocument;
- return new Promise(function (resolve, reject) {
- var attrs = {
- src: src
- };
- var props = {
- onload: resolve,
- onerror: reject,
- onabort: reject
- };
- createNode(IMG, attrs, props, [], currentDocument);
- });
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Returns whether the value is a function.
- * @param {*} value
- * @returns {boolean}
- */
- var isFunction = (function (value) {
- return typeof value === "function";
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Returns whether the value is a non-empty array.
- * @param {*} value
- * @returns {boolean}
- */
- var isNonEmptyArray = (function (value) {
- return Array.isArray(value) && value.length > 0;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var toArray = (function (value) {
- if (Array.isArray(value)) {
- return value;
- }
-
- if (value == null) {
- return [];
- }
-
- return [].slice.call(value);
- });
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var SIBLING_PATTERN = /^\s*>/;
- var querySelectorAll = (function (context, selector) {
- if (!SIBLING_PATTERN.test(selector)) {
- return toArray(context.querySelectorAll(selector));
- }
-
- var tag = "alloy-" + Date.now(); // We could use a :scope selector here, but we want to be IE compliant
- // so we add a dummy css class to be able to select the children
-
- try {
- context.classList.add(tag);
- return toArray(context.querySelectorAll("." + tag + " " + selector));
- } finally {
- context.classList.remove(tag);
- }
- });
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Whether a string starts with the characters of a specified string
- * @param {String} str The string to search within.
- * @param {String} prefix The string to search for.
- * @returns {boolean}
- */
- var startsWith = (function (str, prefix) {
- return str.substr(0, prefix.length) === prefix;
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var SHADOW_SEPARATOR = ":shadow";
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var splitWithShadow = function splitWithShadow(selector) {
- return selector.split(SHADOW_SEPARATOR);
- };
-
- var transformPrefix = function transformPrefix(parent, selector) {
- var result = selector.trim();
- var hasChildCombinatorPrefix = startsWith(result, ">");
-
- if (!hasChildCombinatorPrefix) {
- return result;
- } // IE doesn't support :scope
-
-
- if (window.document.documentMode) {
- return result.substring(1).trim();
- }
-
- var prefix = parent instanceof Element || parent instanceof HTMLDocument ? ":scope" : ":host"; // see https://bugs.webkit.org/show_bug.cgi?id=233380
-
- return prefix + " " + result;
- };
-
- var selectNodesWithShadow = (function (context, selector) {
- // Shadow DOM should be supported
- if (!window.document.documentElement.attachShadow) {
- return querySelectorAll(context, selector.replace(SHADOW_SEPARATOR, ""));
- }
-
- var parts = splitWithShadow(selector);
-
- if (parts.length < 2) {
- return querySelectorAll(context, selector);
- } // split the selector into parts separated by :shadow pseudo-selectors
- // find each subselector element based on the previously selected node's shadowRoot
-
-
- var parent = context;
-
- for (var i = 0; i < parts.length; i += 1) {
- var part = transformPrefix(parent, parts[i]);
- var partNode = querySelectorAll(parent, part);
-
- if (partNode.length === 0 || !partNode[0] || !partNode[0].shadowRoot) {
- return partNode;
- }
-
- parent = partNode[0].shadowRoot;
- }
-
- return undefined;
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var isShadowSelector = (function (str) {
- return str.indexOf(SHADOW_SEPARATOR) !== -1;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Returns an array of matched DOM nodes.
- * @param {String} selector
- * @param {Node} [context=document] defaults to document
- * @returns {Array} an array of DOM nodes
- */
-
- var selectNodes = (function (selector) {
- var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document;
-
- if (!isShadowSelector(selector)) {
- return querySelectorAll(context, selector);
- }
-
- return selectNodesWithShadow(context, selector);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var MUTATION_OBSERVER = "MutationObserver";
- var RAF = "requestAnimationFrame";
- var MUTATION_OBSERVER_CONFIG = {
- childList: true,
- subtree: true
- };
- var VISIBILITY_STATE = "visibilityState";
- var VISIBLE = "visible";
- var DELAY = 100;
- var MAX_POLLING_TIMEOUT = 5000;
-
- var createError = function createError(selector) {
- return new Error("Could not find: " + selector);
- };
-
- var createPromise = function createPromise(executor) {
- return new Promise(executor);
- };
-
- var canUseMutationObserver = function canUseMutationObserver(win) {
- return isFunction(win[MUTATION_OBSERVER]);
- };
- var awaitUsingMutationObserver = function awaitUsingMutationObserver(win, doc, selector, timeout, selectFunc) {
- return createPromise(function (resolve, reject) {
- var mutationObserver = new win[MUTATION_OBSERVER](function () {
- var nodes = selectFunc(selector);
-
- if (isNonEmptyArray(nodes)) {
- mutationObserver.disconnect();
- resolve(nodes);
- }
- });
- setTimeout(function () {
- mutationObserver.disconnect();
- reject(createError(selector));
- }, timeout);
- mutationObserver.observe(doc, MUTATION_OBSERVER_CONFIG);
- });
- };
- var canUseRequestAnimationFrame = function canUseRequestAnimationFrame(doc) {
- return doc[VISIBILITY_STATE] === VISIBLE;
- };
- var awaitUsingRequestAnimation = function awaitUsingRequestAnimation(win, selector, timeout, selectFunc) {
- return createPromise(function (resolve, reject) {
- var execute = function execute() {
- var nodes = selectFunc(selector);
-
- if (isNonEmptyArray(nodes)) {
- resolve(nodes);
- return;
- }
-
- win[RAF](execute);
- };
-
- execute();
- setTimeout(function () {
- reject(createError(selector));
- }, timeout);
- });
- };
- var awaitUsingTimer = function awaitUsingTimer(selector, timeout, selectFunc) {
- return createPromise(function (resolve, reject) {
- var execute = function execute() {
- var nodes = selectFunc(selector);
-
- if (isNonEmptyArray(nodes)) {
- resolve(nodes);
- return;
- }
-
- setTimeout(execute, DELAY);
- };
-
- execute();
- setTimeout(function () {
- reject(createError(selector));
- }, timeout);
- });
- };
- var awaitSelector = (function (selector) {
- var selectFunc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : selectNodes;
- var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : MAX_POLLING_TIMEOUT;
- var win = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : window;
- var doc = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : document;
- var nodes = selectFunc(selector);
-
- if (isNonEmptyArray(nodes)) {
- return Promise.resolve(nodes);
- }
-
- if (canUseMutationObserver(win)) {
- return awaitUsingMutationObserver(win, doc, selector, timeout, selectFunc);
- }
-
- if (canUseRequestAnimationFrame(doc)) {
- return awaitUsingRequestAnimation(win, selector, timeout, selectFunc);
- }
-
- return awaitUsingTimer(selector, timeout, selectFunc);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Returns true if element matches the selector.
- * @param {String} selector
- * @param {Node} [element]
- * @returns {Boolean}
- */
- var matchesSelector = (function (selector, element) {
- if (element.matches) {
- return element.matches(selector);
- } // Making IE 11 happy
-
-
- return element.msMatchesSelector(selector);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var removeNode = (function (node) {
- var parent = node.parentNode;
-
- if (parent) {
- return parent.removeChild(node);
- }
-
- return null;
- });
-
- var IFRAME_ATTRS = {
- name: "Adobe Alloy"
- };
- var IFRAME_PROPS = {
- style: {
- display: "none",
- width: 0,
- height: 0
- }
- };
- var injectFireReferrerHideableImage = (function () {
- var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
- _ref$appendNode = _ref.appendNode,
- appendNode$1 = _ref$appendNode === void 0 ? appendNode : _ref$appendNode,
- _ref$awaitSelector = _ref.awaitSelector,
- awaitSelector$1 = _ref$awaitSelector === void 0 ? awaitSelector : _ref$awaitSelector,
- _ref$createNode = _ref.createNode,
- createNode$1 = _ref$createNode === void 0 ? createNode : _ref$createNode,
- _ref$fireImage = _ref.fireImage,
- fireImage = _ref$fireImage === void 0 ? fireImageInDocument : _ref$fireImage;
-
- var fireOnPage = fireImage;
- var hiddenIframe;
-
- var createIframe = function createIframe() {
- return awaitSelector$1(BODY).then(function (_ref2) {
- var _ref3 = _slicedToArray(_ref2, 1),
- body = _ref3[0];
-
- if (hiddenIframe) {
- return hiddenIframe;
- }
-
- hiddenIframe = createNode$1(IFRAME, IFRAME_ATTRS, IFRAME_PROPS);
- return appendNode$1(body, hiddenIframe);
- });
- };
-
- var fireInIframe = function fireInIframe(_ref4) {
- var src = _ref4.src;
- return createIframe().then(function (iframe) {
- var currentDocument = iframe.contentWindow.document;
- return fireImage({
- src: src,
- currentDocument: currentDocument
- });
- });
- };
-
- return function (request) {
- var hideReferrer = request.hideReferrer,
- url = request.url;
- return hideReferrer ? fireInIframe({
- src: url
- }) : fireOnPage({
- src: url
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Returns whether the value is an empty object.
- * @param {*} value
- * @returns {boolean}
- */
-
- var isEmptyObject = (function (value) {
- return isObject(value) && Object.keys(value).length === 0;
- });
-
- /**
- * Given an object and a function that takes a value and returns a predicate, filter out
- * all non-object deeply nested values that do not pass the predicate.
- *
- * Example: filterObject({ a: 2, b: { c: 6 } }, (val) => val > 5) returns { b { c: 6 } }
- *
- * @param {*} obj
- * @param {* => boolean} predicate a function that takes a value and return a boolean,
- * representing if it should be included in the result object or not.
- * @returns A copy of the original object with the values that fail the predicate, filtered out.
- */
-
- var filterObject = function filterObject(obj, predicate) {
- if (isNil(obj) || !isObject(obj)) {
- return obj;
- }
-
- return Object.keys(obj).reduce(function (result, key) {
- var value = obj[key];
-
- if (isObject(value)) {
- // value is object, go deeper
- var filteredValue = filterObject(value, predicate);
-
- if (isEmptyObject(filteredValue)) {
- return result;
- }
-
- return _objectSpread2(_objectSpread2({}, result), {}, _defineProperty({}, key, filteredValue));
- } // value is not an object, test predicate
-
-
- if (predicate(value)) {
- return _objectSpread2(_objectSpread2({}, result), {}, _defineProperty({}, key, value));
- }
-
- return result;
- }, {});
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var flatMap = (function (array, mapFunction) {
- return Array.prototype.concat.apply([], array.map(mapFunction));
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var baseNamespace = "com.adobe.alloy.";
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Returns the last N number of items from an array.
- * @param {Array} arr
- * @param {number} itemCount
- * @returns {Array}
- */
- var getLastArrayItems = (function (arr, itemCount) {
- return arr.slice(-itemCount);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var cookieName = baseNamespace + "getTld";
- /**
- * Of the current web page's hostname, this is the top-most domain that is
- * not a "public suffix" as outlined in https://publicsuffix.org/. In other
- * words, this is top-most domain that is able to accept cookies.
- * @param {Object} window
- * @param {Object} cookieJar
- * @returns {string}
- */
-
- var getApexDomain = (function (window, cookieJar) {
- var topLevelCookieDomain = ""; // If hostParts.length === 1, we may be on localhost.
-
- var hostParts = window.location.hostname.toLowerCase().split(".");
- var i = 1;
-
- while (i < hostParts.length && !cookieJar.get(cookieName)) {
- i += 1;
- topLevelCookieDomain = getLastArrayItems(hostParts, i).join(".");
- cookieJar.set(cookieName, cookieName, {
- domain: topLevelCookieDomain
- });
- }
-
- cookieJar.remove(cookieName, {
- domain: topLevelCookieDomain
- });
- return topLevelCookieDomain;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- // Remember to also incorporate the org ID wherever cookies are read or written.
- var COOKIE_NAME_PREFIX = "kndctr";
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var sanitizeOrgIdForCookieName = (function (orgId) {
- return orgId.replace("@", "_");
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var getNamespacedCookieName = (function (orgId, key) {
- return COOKIE_NAME_PREFIX + "_" + sanitizeOrgIdForCookieName(orgId) + "_" + key;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var IDENTITY = "identity";
- var CONSENT = "consent";
- var CLUSTER = "cluster";
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectDoesIdentityCookieExist = (function (_ref) {
- var orgId = _ref.orgId;
- var identityCookieName = getNamespacedCookieName(orgId, IDENTITY);
- /**
- * Returns whether the identity cookie exists.
- */
-
- return function () {
- return Boolean(cookieJar.get(identityCookieName));
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var getStorageByType = function getStorageByType(context, storageType, namespace) {
- // When storage is disabled on Safari, the mere act of referencing
- // window.localStorage or window.sessionStorage throws an error.
- // For this reason, we wrap in a try-catch.
- return {
- /**
- * Reads a value from storage.
- * @param {string} name The name of the item to be read.
- * @returns {string}
- */
- getItem: function getItem(name) {
- try {
- return context[storageType].getItem(namespace + name);
- } catch (e) {
- return null;
- }
- },
-
- /**
- * Saves a value to storage.
- * @param {string} name The name of the item to be saved.
- * @param {string} value The value of the item to be saved.
- * @returns {boolean} Whether the item was successfully saved to storage.
- */
- setItem: function setItem(name, value) {
- try {
- context[storageType].setItem(namespace + name, value);
- return true;
- } catch (e) {
- return false;
- }
- },
-
- /**
- * Clear all values in storage that match the namespace.
- */
- clear: function clear() {
- try {
- Object.keys(context[storageType]).forEach(function (key) {
- if (startsWith(key, namespace)) {
- context[storageType].removeItem(key);
- }
- });
- return true;
- } catch (e) {
- return false;
- }
- }
- };
- };
-
- var injectStorage = (function (context) {
- return function (additionalNamespace) {
- var finalNamespace = baseNamespace + additionalNamespace;
- return {
- session: getStorageByType(context, "sessionStorage", finalNamespace),
- persistent: getStorageByType(context, "localStorage", finalNamespace)
- };
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Returns items that are found within both arrays.
- * @param {Array} a
- * @param {Array} b
- * @returns {Array}
- */
-
- var intersection = (function (a, b) {
- return a.filter(function (x) {
- return includes(b, x);
- });
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Returns whether the value is a boolean.
- * @param {*} value
- * @returns {boolean}
- */
- var isBoolean = (function (value) {
- return typeof value === "boolean";
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Returns whether the value is a number.
- * @param {*} value
- * @returns {boolean}
- */
- // eslint-disable-next-line no-restricted-globals
- var isNumber = (function (value) {
- return typeof value === "number" && !isNaN(value);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Returns whether the value is an integer.
- * @param {*} value
- * @returns {boolean}
- */
-
- var isInteger = (function (value) {
- var parsed = parseInt(value, 10);
- return isNumber(parsed) && value === parsed;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Determines whether a cookie name is namespaced according to the contract
- * defined by the server.
- * @param {String} orgId The org ID configured for the Alloy instance.
- * @param {String} name The cookie name.
- * @returns {boolean}
- */
-
- var isNamespacedCookieName = (function (orgId, name) {
- return name.indexOf(COOKIE_NAME_PREFIX + "_" + sanitizeOrgIdForCookieName(orgId) + "_") === 0;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Returns whether the value is a string.
- * @param {*} value
- * @returns {boolean}
- */
- var isString = (function (value) {
- return typeof value === "string";
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Returns whether the value is a populated string.
- * @param {*} value
- * @returns {boolean}
- */
-
- var isNonEmptyString = (function (value) {
- return isString(value) && value.length > 0;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Creates a function that memoizes the result of `fn`. If `keyResolver` is
- * provided, it determines the cache key for storing the result based on the
- * arguments provided to the memoized function. By default, the first argument
- * provided to the memoized function is used as the map cache key.
- *
- * @param {Function} fn The function to have its output memoized.
- * @param {Function} [keyResolver] The function to resolve the cache key.
- * @returns {Function} The new memoized function.
- */
- var memoize = (function (fn, keyResolver) {
- var map = new Map();
- return function () {
- var key = keyResolver ? keyResolver.apply(void 0, arguments) : arguments.length <= 0 ? undefined : arguments[0];
-
- if (map.has(key)) {
- return map.get(key);
- }
-
- var result = fn.apply(void 0, arguments);
- map.set(key, result);
- return result;
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * A function that performs no operations.
- */
- var noop$1 = (function () {});
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- // adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
- var padStart = (function (string, targetLength, padString) {
- var originalString = String(string);
- var repeatedPadString = String(padString);
-
- if (originalString.length >= targetLength || repeatedPadString.length === 0) {
- return originalString;
- }
-
- var lengthToAdd = targetLength - originalString.length;
-
- while (lengthToAdd > repeatedPadString.length) {
- repeatedPadString += repeatedPadString;
- }
-
- return repeatedPadString.slice(0, lengthToAdd) + originalString;
- });
-
- // to be able to add overrides in the future without us needing to make
- // any changes to the Web SDK
-
- var prepareConfigOverridesForEdge = (function (configuration) {
- if (isNil(configuration) || _typeof(configuration) !== "object") {
- return null;
- } // remove entries that are empty strings or arrays
-
-
- var configOverrides = filterObject(configuration, function (value) {
- if (isNil(value)) {
- return false;
- }
-
- if (isBoolean(value)) {
- return true;
- }
-
- if (isNumber(value)) {
- return true;
- }
-
- if (isNonEmptyString(value)) {
- return true;
- }
-
- if (isNonEmptyArray(value)) {
- return true;
- }
-
- return false;
- });
-
- if (isEmptyObject(configOverrides)) {
- return null;
- }
-
- return configOverrides;
- });
-
- // Copyright Joyent, Inc. and other Node contributors.
- // obj.hasOwnProperty(prop) will break.
- // See: https://github.com/joyent/node/issues/1707
-
- function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
- }
-
- var decode = function decode(qs, sep, eq, options) {
- sep = sep || '&';
- eq = eq || '=';
- var obj = {};
-
- if (typeof qs !== 'string' || qs.length === 0) {
- return obj;
- }
-
- var regexp = /\+/g;
- qs = qs.split(sep);
- var maxKeys = 1000;
-
- if (options && typeof options.maxKeys === 'number') {
- maxKeys = options.maxKeys;
- }
-
- var len = qs.length; // maxKeys <= 0 means that we should not limit keys count
-
- if (maxKeys > 0 && len > maxKeys) {
- len = maxKeys;
- }
-
- for (var i = 0; i < len; ++i) {
- var x = qs[i].replace(regexp, '%20'),
- idx = x.indexOf(eq),
- kstr,
- vstr,
- k,
- v;
-
- if (idx >= 0) {
- kstr = x.substr(0, idx);
- vstr = x.substr(idx + 1);
- } else {
- kstr = x;
- vstr = '';
- }
-
- k = decodeURIComponent(kstr);
- v = decodeURIComponent(vstr);
-
- if (!hasOwnProperty(obj, k)) {
- obj[k] = v;
- } else if (Array.isArray(obj[k])) {
- obj[k].push(v);
- } else {
- obj[k] = [obj[k], v];
- }
- }
-
- return obj;
- };
-
- // Copyright Joyent, Inc. and other Node contributors.
-
- var stringifyPrimitive = function stringifyPrimitive(v) {
- switch (_typeof(v)) {
- case 'string':
- return v;
-
- case 'boolean':
- return v ? 'true' : 'false';
-
- case 'number':
- return isFinite(v) ? v : '';
-
- default:
- return '';
- }
- };
-
- var encode = function encode(obj, sep, eq, name) {
- sep = sep || '&';
- eq = eq || '=';
-
- if (obj === null) {
- obj = undefined;
- }
-
- if (_typeof(obj) === 'object') {
- return Object.keys(obj).map(function (k) {
- var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
-
- if (Array.isArray(obj[k])) {
- return obj[k].map(function (v) {
- return ks + encodeURIComponent(stringifyPrimitive(v));
- }).join(sep);
- } else {
- return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
- }
- }).join(sep);
- }
-
- if (!name) return '';
- return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj));
- };
-
- var querystring = createCommonjsModule(function (module, exports) {
-
- exports.decode = exports.parse = decode;
- exports.encode = exports.stringify = encode;
- });
- querystring.decode;
- querystring.parse;
- querystring.encode;
- querystring.stringify;
-
- // This allows us to more easily make changes to the underlying implementation later without
- // having to worry about breaking extensions. If extensions demand additional functionality, we
- // can make adjustments as needed.
-
-
- var reactorQueryString = {
- parse: function parse(string) {
- //
- if (typeof string === 'string') {
- // Remove leading ?, #, & for some leniency so you can pass in location.search or
- // location.hash directly.
- string = string.trim().replace(/^[?#&]/, '');
- }
-
- return querystring.parse(string);
- },
- stringify: function stringify(object) {
- return querystring.stringify(object);
- }
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Creates and returns a new error using the provided value as a message.
- * If the provided value is already an Error, it will be returned unmodified.
- * @param {*} value
- * @returns {Error}
- */
- var toError = (function (value) {
- return value instanceof Error ? value : new Error(value);
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var updateErrorMessage = (function (_ref) {
- var error = _ref.error,
- message = _ref.message;
-
- try {
- error.message = message;
- } catch (e) {// We'll set a new message when we can, but some errors, like DOMException,
- // have a read-only message property, which limits our options.
- }
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Augments an error's message with additional context as it bubbles up the call stack.
- * @param {String} message The message to be added to the error.
- * @param {*} error Optimally, this is an instance of Error. If it is not,
- * this is used as the basis for the message of a newly created Error instance.
- * @returns {*}
- */
-
- var stackError = (function (_ref) {
- var error = _ref.error,
- message = _ref.message;
- var errorToStack = toError(error);
- var newMessage = message + "\nCaused by: " + errorToStack.message;
- updateErrorMessage({
- error: errorToStack,
- message: newMessage
- });
- return errorToStack;
- });
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var stringToBoolean = (function (str) {
- return isString(str) && str.toLowerCase() === "true";
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /*
- * coerce `value` to a number or return `defaultValue` if it cannot be.
- *
- * The coersion is attempted if value is a number or string.
- */
-
- var toInteger = (function (value, defaultValue) {
- if (isNumber(value) || isString(value)) {
- var n = Math.round(Number(value)); // eslint-disable-next-line no-restricted-globals
-
- if (!isNaN(n)) {
- return n;
- }
- }
-
- return defaultValue;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Formats the date into an ISO date-time string in the local timezone
- * @param {Date} date
- * @returns {string}
- */
-
- var toISOStringLocal = (function (date) {
- var YYYY = date.getFullYear();
- var MM = padStart(date.getMonth() + 1, 2, "0");
- var DD = padStart(date.getDate(), 2, "0");
- var hh = padStart(date.getHours(), 2, "0");
- var mm = padStart(date.getMinutes(), 2, "0");
- var ss = padStart(date.getSeconds(), 2, "0");
- var mmm = padStart(date.getMilliseconds(), 3, "0"); // The time-zone offset is the difference, in minutes, from local time to UTC. Note that this
- // means that the offset is positive if the local timezone is behind UTC and negative if it is
- // ahead. For example, for time zone UTC+10:00, -600 will be returned.
-
- var timezoneOffset = toInteger(date.getTimezoneOffset(), 0);
- var ts = timezoneOffset > 0 ? "-" : "+";
- var th = padStart(Math.floor(Math.abs(timezoneOffset) / 60), 2, "0");
- var tm = padStart(Math.abs(timezoneOffset) % 60, 2, "0");
- return YYYY + "-" + MM + "-" + DD + "T" + hh + ":" + mm + ":" + ss + "." + mmm + ts + th + ":" + tm;
- });
-
- var rngBrowser = createCommonjsModule(function (module) {
- // Unique ID creation requires a high quality random # generator. In the
- // browser this is a little complicated due to unknown quality of Math.random()
- // and inconsistent support for the `crypto` API. We do the best we can via
- // feature-detection
- // getRandomValues needs to be invoked in a context where "this" is a Crypto
- // implementation. Also, find the complete implementation of crypto on IE11.
- var getRandomValues = typeof crypto != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto);
-
- if (getRandomValues) {
- // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
- var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
-
- module.exports = function whatwgRNG() {
- getRandomValues(rnds8);
- return rnds8;
- };
- } else {
- // Math.random()-based (RNG)
- //
- // If all else fails, use Math.random(). It's fast, but is of unspecified
- // quality.
- var rnds = new Array(16);
-
- module.exports = function mathRNG() {
- for (var i = 0, r; i < 16; i++) {
- if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
- rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
- }
-
- return rnds;
- };
- }
- });
-
- /**
- * Convert array of 16 byte values to UUID string format of the form:
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
- */
- var byteToHex = [];
-
- for (var i = 0; i < 256; ++i) {
- byteToHex[i] = (i + 0x100).toString(16).substr(1);
- }
-
- function bytesToUuid(buf, offset) {
- var i = offset || 0;
- var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
-
- return [bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]]].join('');
- }
-
- var bytesToUuid_1 = bytesToUuid;
-
- function v4(options, buf, offset) {
- var i = buf && offset || 0;
-
- if (typeof options == 'string') {
- buf = options === 'binary' ? new Array(16) : null;
- options = null;
- }
-
- options = options || {};
- var rnds = options.random || (options.rng || rngBrowser)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
-
- rnds[6] = rnds[6] & 0x0f | 0x40;
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
-
- if (buf) {
- for (var ii = 0; ii < 16; ++ii) {
- buf[i + ii] = rnds[ii];
- }
- }
-
- return buf || bytesToUuid_1(rnds);
- }
-
- var v4_1 = v4;
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Chains two validators together.
- *
- * Validators are functions of two parameters (value and path) that return the computed value if
- * the input is valid, or throw an exception if the input is invalid. In most cases the returned
- * value is the same as the input value; however, reference createDefaultValidator.js
- * to see an example where the computed value is different from the input. Additionally, if we ever
- * wanted to coerce types (i.e. parse string values into integers) as part of the validation process
- * we could use the computed value to accomplish that.
- *
- * The path parameter is used to generate informative error messages. It is created by the objectOf, and
- * arrayOf validators so that any error message can describe which key within the object or array is
- * invalid.
- *
- * The validators also have methods to chain additional validation logic. For example, when you call
- * `string()` to start a validator chain, it returns a validator function but it also has methods
- * like `required` and `nonEmpty`. In index.js you can see that these methods are actually calling `chain`.
- * Specifically in this function, the leftValidator is called first and then the return value of that is
- * sent to the rightValidator. For example, when calling `string().nonEmpty().required()` the following
- * chain is built up:
- * ```
- * *
- * / \
- * * required
- * / \
- * * nonEmpty
- * / \
- * base string
- * ```
- * Where every * is a call to chain where the two are combined. The individual validators are called from
- * left to right in the above tree. The base validator is simply the identity function `value => value`,
- * representing an optional value.
- *
- * After combining the validators, the new validator function is then augmented with the methods from the
- * leftValidator and from the additionalMethods parameter. For example, when the string() function is called
- * it chains to the base validator, but also adds additional methods like (`regexp`, `domain`, `nonEmpty`,
- * and `unique`). When `nonEmpty` is called, which calls chain again, the additional methods are carried
- * forward because they are already defined on the leftValidator.
- *
- * The base validator also contains the two methods `required` and `default`, so these can be used anywhere
- * after any of the exposed validator functions are called.
- */
-
- var chain = (function (leftValidator, rightValidator) {
- var additionalMethods = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
-
- // combine the two validators, calling left first and then right.
- // pass the return value from left into right.
- var combinedValidator = function combinedValidator(value, path) {
- return rightValidator(leftValidator(value, path), path);
- }; // add the methods already defined on the left validator, and the additionalMethods
- // to the new combined validator function.
-
-
- reactorObjectAssign(combinedValidator, leftValidator, additionalMethods);
- return combinedValidator;
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * This augments `chain` with a null check done before running the rightValidator.
- * See chain for more info.
- *
- * For most validators, we want the validation to be optional (i.e. allow null or
- * undefined values). To accomplish this, the validator needs to have a check
- * at the begining of the function, short circuiting the validation logic and
- * returning value if value is null or undefined. `default` and `required` do not
- * want this null check though. Indeed, `default` should return the default value
- * if value is null, and `required` should throw an error if value is null.
- *
- * So to keep from having to have a null check in front of most validators, this
- * function allows you to chain a rightValidator that needs to have a null check.
- */
-
- var nullSafeChain = (function (leftValidator, rightValidator, additionalMethods) {
- var rightValidatorWithNullCheck = function rightValidatorWithNullCheck(value, path) {
- return value == null ? value : rightValidator(value, path);
- };
-
- return chain(leftValidator, rightValidatorWithNullCheck, additionalMethods);
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var assertValid = (function (isValid, value, path, message) {
- if (!isValid) {
- throw new Error("'" + path + "': Expected " + message + ", but got " + JSON.stringify(value) + ".");
- }
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var booleanValidator = (function (value, path) {
- assertValid(isBoolean(value), value, path, "true or false");
- return value;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var callbackValidator = (function (value, path) {
- assertValid(isFunction(value), value, path, "a function");
- return value;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createArrayOfValidator = (function (elementValidator) {
- return function (value, path) {
- assertValid(Array.isArray(value), value, path, "an array");
- var errors = [];
- var validatedArray = value.map(function (subValue, i) {
- try {
- return elementValidator(subValue, path + "[" + i + "]");
- } catch (e) {
- errors.push(e.message);
- return undefined;
- }
- });
-
- if (errors.length) {
- throw new Error(errors.join("\n"));
- }
-
- return validatedArray;
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createDefaultValidator = (function (defaultValue) {
- return function (value) {
- if (value == null) {
- return defaultValue;
- }
-
- return value;
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createLiteralValidator = (function (literalValue) {
- return function (value, path) {
- assertValid(value === literalValue, value, path, "" + literalValue);
- return value;
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createMapOfValuesValidator = (function (valueValidator) {
- return function (value, path) {
- assertValid(isObject(value), value, path, "an object");
- var errors = [];
- var validatedObject = {};
- Object.keys(value).forEach(function (subKey) {
- var subValue = value[subKey];
- var subPath = path ? path + "." + subKey : subKey;
-
- try {
- var validatedValue = valueValidator(subValue, subPath);
-
- if (validatedValue !== undefined) {
- validatedObject[subKey] = validatedValue;
- }
- } catch (e) {
- errors.push(e.message);
- }
- });
-
- if (errors.length) {
- throw new Error(errors.join("\n"));
- }
-
- return validatedObject;
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createMinimumValidator = (function (typeName, minimum) {
- return function (value, path) {
- assertValid(value >= minimum, value, path, typeName + " greater than or equal to " + minimum);
- return value;
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createNoUnknownFieldsValidator = (function (schema) {
- return function (value, path) {
- var errors = [];
- Object.keys(value).forEach(function (subKey) {
- if (!schema[subKey]) {
- var subPath = path ? path + "." + subKey : subKey;
- errors.push("'" + subPath + "': Unknown field.");
- }
- });
-
- if (errors.length) {
- throw new Error(errors.join("\n"));
- }
-
- return value;
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createNonEmptyValidator = (function (message) {
- return function (value, path) {
- if (isObject(value)) {
- assertValid(!isEmptyObject(value), value, path, message);
- } else {
- assertValid(value.length > 0, value, path, message);
- }
-
- return value;
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createObjectOfValidator = (function (schema) {
- return function (value, path) {
- assertValid(isObject(value), value, path, "an object");
- var errors = [];
- var validatedObject = {};
- Object.keys(schema).forEach(function (subKey) {
- var subValue = value[subKey];
- var subSchema = schema[subKey];
- var subPath = path ? path + "." + subKey : subKey;
-
- try {
- var validatedValue = subSchema(subValue, subPath);
-
- if (validatedValue !== undefined) {
- validatedObject[subKey] = validatedValue;
- }
- } catch (e) {
- errors.push(e.message);
- }
- }); // copy over unknown properties
-
- Object.keys(value).forEach(function (subKey) {
- if (!Object.prototype.hasOwnProperty.call(validatedObject, subKey)) {
- validatedObject[subKey] = value[subKey];
- }
- });
-
- if (errors.length) {
- throw new Error(errors.join("\n"));
- }
-
- return validatedObject;
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createAnyOfValidator = (function (validators, message) {
- return function (value, path) {
- var valid = find(validators, function (validator) {
- try {
- validator(value, path);
- return true;
- } catch (e) {
- return false;
- }
- });
- assertValid(valid, value, path, message);
- return value;
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createUniqueValidator = (function () {
- var values = [];
- return function (value, path) {
- assertValid(values.indexOf(value) === -1, value, path, "a unique value across instances");
- values.push(value);
- return value;
- };
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Returns whether an array contains unique values.
- * @param {*} value
- * @returns {boolean}
- */
- var isUnique = (function (values) {
- var storedVals = Object.create(null);
-
- for (var i = 0; i < values.length; i += 1) {
- var item = values[i];
-
- if (item in storedVals) {
- return false;
- }
-
- storedVals[item] = true;
- }
-
- return true;
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createUniqueItemsValidator = (function () {
- return function (value, path) {
- assertValid(isUnique(value), value, path, "array values to be unique");
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var DOMAIN_REGEX = /^[a-z0-9.-]{1,}$/i;
- var domainValidator = (function (value, path) {
- assertValid(DOMAIN_REGEX.test(value), value, path, "a valid domain");
- return value;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var integerValidator = (function (value, path) {
- assertValid(isInteger(value), value, path, "an integer");
- return value;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var numberValidator = (function (value, path) {
- assertValid(isNumber(value), value, path, "a number");
- return value;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Determines whether the value is a valid regular expression.
- * @param {*} value
- * @returns {boolean}
- */
- var isValidRegExp = (function (value) {
- try {
- return new RegExp(value) !== null;
- } catch (e) {
- return false;
- }
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var regexpValidator = (function (value, path) {
- assertValid(isValidRegExp(value), value, path, "a regular expression");
- return value;
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var requiredValidator = (function (value, path) {
- if (value == null) {
- throw new Error("'" + path + "' is a required option");
- }
-
- return value;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var stringValidator = (function (value, path) {
- assertValid(isString(value), value, path, "a string");
- return value;
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var base = function base(value) {
- return value;
- }; // The 'default' and 'required' methods are available after any data-type method
- // Don't use the nullSafeChain because they need to handle the null or undefined case
-
-
- base.default = function _default(defaultValue) {
- return chain(this, createDefaultValidator(defaultValue));
- };
-
- base.required = function required() {
- return chain(this, requiredValidator);
- }; // helper validators
-
-
- var domain = function domain() {
- return nullSafeChain(this, domainValidator);
- };
-
- var minimumInteger = function minimumInteger(minValue) {
- return nullSafeChain(this, createMinimumValidator("an integer", minValue));
- };
-
- var minimumNumber = function minimumNumber(minValue) {
- return nullSafeChain(this, createMinimumValidator("a number", minValue));
- };
-
- var integer = function integer() {
- return nullSafeChain(this, integerValidator, {
- minimum: minimumInteger
- });
- };
-
- var nonEmptyString = function nonEmptyString() {
- return nullSafeChain(this, createNonEmptyValidator("a non-empty string"));
- };
-
- var nonEmptyArray = function nonEmptyArray() {
- return nullSafeChain(this, createNonEmptyValidator("a non-empty array"));
- };
-
- var nonEmptyObject = function nonEmptyObject() {
- return nullSafeChain(this, createNonEmptyValidator("a non-empty object"));
- };
-
- var regexp = function regexp() {
- return nullSafeChain(this, regexpValidator);
- };
-
- var unique = function createUnique() {
- return nullSafeChain(this, createUniqueValidator());
- };
-
- var uniqueItems = function createUniqueItems() {
- return nullSafeChain(this, createUniqueItemsValidator());
- }; // top-level validators. These are the first functions that are called to create a validator.
-
-
- var anyOf = function anyOf(validators, message) {
- // use chain here because we don't want to accept null or undefined unless at least
- // one of the validators accept null or undefined.
- return chain(this, createAnyOfValidator(validators, message));
- };
-
- var anything = function anything() {
- return nullSafeChain(this, base);
- };
-
- var arrayOf = function arrayOf(elementValidator) {
- return nullSafeChain(this, createArrayOfValidator(elementValidator), {
- nonEmpty: nonEmptyArray,
- uniqueItems: uniqueItems
- });
- };
-
- var boolean = function boolean() {
- return nullSafeChain(this, booleanValidator);
- };
-
- var callback = function callback() {
- return nullSafeChain(this, callbackValidator);
- };
-
- var literal = function literal(literalValue) {
- return nullSafeChain(this, createLiteralValidator(literalValue));
- };
-
- var number = function number() {
- return nullSafeChain(this, numberValidator, {
- minimum: minimumNumber,
- integer: integer,
- unique: unique
- });
- };
-
- var mapOfValues = function mapOfValues(valuesValidator) {
- return nullSafeChain(this, createMapOfValuesValidator(valuesValidator), {
- nonEmpty: nonEmptyObject
- });
- };
-
- var objectOf = function objectOf(schema) {
- var noUnknownFields = function noUnknownFields() {
- return nullSafeChain(this, createNoUnknownFieldsValidator(schema));
- };
-
- return nullSafeChain(this, createObjectOfValidator(schema), {
- noUnknownFields: noUnknownFields,
- nonEmpty: nonEmptyObject
- });
- };
-
- var string = function string() {
- return nullSafeChain(this, stringValidator, {
- regexp: regexp,
- domain: domain,
- nonEmpty: nonEmptyString,
- unique: unique
- });
- };
-
- var boundAnyOf = anyOf.bind(base);
- var boundAnything = anything.bind(base);
- var boundArrayOf = arrayOf.bind(base);
- var boundBoolean = boolean.bind(base);
- var boundCallback = callback.bind(base);
- var boundLiteral = literal.bind(base);
- number.bind(base);
- var boundMapOfValues = mapOfValues.bind(base);
- var boundObjectOf = objectOf.bind(base);
- var boundString = string.bind(base); // compound validators
-
- var boundEnumOf = function boundEnumOf() {
- for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
- values[_key] = arguments[_key];
- }
-
- return boundAnyOf(values.map(boundLiteral), "one of these values: [" + JSON.stringify(values) + "]");
- };
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var AMBIGUOUS = "ambiguous";
- var AUTHENTICATED = "authenticated";
- var LOGGED_OUT = "loggedOut";
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var validateIdentityMap = boundMapOfValues(boundArrayOf(boundObjectOf({
- authenticatedState: boundEnumOf(AMBIGUOUS, AUTHENTICATED, LOGGED_OUT),
- id: boundString(),
- namespace: boundObjectOf({
- code: boundString()
- }).noUnknownFields(),
- primary: boundBoolean(),
- xid: boundString()
- }).noUnknownFields()).required());
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var validateConfigOverride = boundObjectOf({});
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var debugQueryParam = "alloy_debug";
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createLogController = (function (_ref) {
- var console = _ref.console,
- locationSearch = _ref.locationSearch,
- createLogger = _ref.createLogger,
- instanceName = _ref.instanceName,
- createNamespacedStorage = _ref.createNamespacedStorage,
- getMonitors = _ref.getMonitors;
- var parsedQueryString = reactorQueryString.parse(locationSearch);
- var storage = createNamespacedStorage("instance." + instanceName + ".");
- var debugSessionValue = storage.session.getItem("debug");
- var debugEnabled = debugSessionValue === "true";
- var debugEnabledWritableFromConfig = debugSessionValue === null;
-
- var getDebugEnabled = function getDebugEnabled() {
- return debugEnabled;
- };
-
- var setDebugEnabled = function setDebugEnabled(value, _ref2) {
- var fromConfig = _ref2.fromConfig;
-
- if (!fromConfig || debugEnabledWritableFromConfig) {
- debugEnabled = value;
- }
-
- if (!fromConfig) {
- // Web storage only allows strings, so we explicitly convert to string.
- storage.session.setItem("debug", value.toString());
- debugEnabledWritableFromConfig = false;
- }
- };
-
- if (parsedQueryString[debugQueryParam] !== undefined) {
- setDebugEnabled(stringToBoolean(parsedQueryString[debugQueryParam]), {
- fromConfig: false
- });
- }
-
- return {
- setDebugEnabled: setDebugEnabled,
- logger: createLogger({
- getDebugEnabled: getDebugEnabled,
- context: {
- instanceName: instanceName
- },
- getMonitors: getMonitors,
- console: console
- }),
- createComponentLogger: function createComponentLogger(componentName) {
- return createLogger({
- getDebugEnabled: getDebugEnabled,
- context: {
- instanceName: instanceName,
- componentName: componentName
- },
- getMonitors: getMonitors,
- console: console
- });
- }
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- // TO-DOCUMENT: Lifecycle hooks and their params.
- var hookNames = [// Called after all components have been registered.
- "onComponentsRegistered", // Called before an event is sent on a data collection request
- "onBeforeEvent", // Called before each request is made to the edge.
- "onBeforeRequest", // Called after each response is returned from the edge with a successful
- // status code
- "onResponse", // Called after a network request to the edge fails. Either the request
- // didn't make it to the edge, didn't make it to Konductor, or Konductor
- // failed to return a regularly-structured response. (In this case { error }
- // is passed as the parameter)
- // Also called when the respone returns a 400 or 500 error. (In this case
- // { response } is passed as the parameter)
- "onRequestFailure", // A user clicked on an element.
- "onClick"];
-
- var createHook = function createHook(componentRegistry, hookName) {
- return function () {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- return Promise.all(componentRegistry.getLifecycleCallbacks(hookName).map(function (callback) {
- return new Promise(function (resolve) {
- resolve(callback.apply(void 0, args));
- });
- }));
- };
- };
- /**
- * This ensures that if a component's lifecycle method X
- * attempts to execute lifecycle method Y, that all X methods on all components
- * will have been called before any of their Y methods are called. It does
- * this by kicking the call to the Y method to the next JavaScript tick.
- * @returns {function}
- */
-
-
- var guardHook = function guardHook(fn) {
- return function () {
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- args[_key2] = arguments[_key2];
- }
-
- return Promise.resolve().then(function () {
- return fn.apply(void 0, args);
- });
- };
- };
-
- var createLifecycle = (function (componentRegistry) {
- return hookNames.reduce(function (memo, hookName) {
- memo[hookName] = guardHook(createHook(componentRegistry, hookName));
- return memo;
- }, {});
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var wrapForErrorHandling = function wrapForErrorHandling(fn, stackMessage) {
- return function () {
- var result;
-
- try {
- result = fn.apply(void 0, arguments);
- } catch (error) {
- throw stackError({
- error: error,
- message: stackMessage
- });
- }
-
- if (result instanceof Promise) {
- result = result.catch(function (error) {
- throw stackError({
- error: error,
- message: stackMessage
- });
- });
- }
-
- return result;
- };
- }; // TO-DOCUMENT: All public commands and their signatures.
-
-
- var createComponentRegistry = (function () {
- var componentsByNamespace = {};
- var commandsByName = {};
- var lifecycleCallbacksByName = {};
-
- var registerComponentCommands = function registerComponentCommands(namespace) {
- var componentCommandsByName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var conflictingCommandNames = intersection(Object.keys(commandsByName), Object.keys(componentCommandsByName));
-
- if (conflictingCommandNames.length) {
- throw new Error("[ComponentRegistry] Could not register " + namespace + " " + ("because it has existing command(s): " + conflictingCommandNames.join(",")));
- }
-
- Object.keys(componentCommandsByName).forEach(function (commandName) {
- var command = componentCommandsByName[commandName];
- command.commandName = commandName;
- command.run = wrapForErrorHandling(command.run, "[" + namespace + "] An error occurred while executing the " + commandName + " command.");
- commandsByName[commandName] = command;
- });
- };
-
- var registerLifecycleCallbacks = function registerLifecycleCallbacks(namespace) {
- var componentLifecycleCallbacksByName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- Object.keys(componentLifecycleCallbacksByName).forEach(function (hookName) {
- lifecycleCallbacksByName[hookName] = lifecycleCallbacksByName[hookName] || [];
- lifecycleCallbacksByName[hookName].push(wrapForErrorHandling(componentLifecycleCallbacksByName[hookName], "[" + namespace + "] An error occurred while executing the " + hookName + " lifecycle hook."));
- });
- };
-
- return {
- register: function register(namespace, component) {
- var commands = component.commands,
- lifecycle = component.lifecycle;
- registerComponentCommands(namespace, commands);
- registerLifecycleCallbacks(namespace, lifecycle);
- componentsByNamespace[namespace] = component;
- },
- getCommand: function getCommand(commandName) {
- return commandsByName[commandName];
- },
- getCommandNames: function getCommandNames() {
- return Object.keys(commandsByName);
- },
- getLifecycleCallbacks: function getLifecycleCallbacks(hookName) {
- return lifecycleCallbacksByName[hookName] || [];
- }
- };
- });
-
- var injectSendNetworkRequest = (function (_ref) {
- var logger = _ref.logger,
- sendFetchRequest = _ref.sendFetchRequest,
- sendBeaconRequest = _ref.sendBeaconRequest,
- isRequestRetryable = _ref.isRequestRetryable,
- getRequestRetryDelay = _ref.getRequestRetryDelay;
-
- /**
- * Send a network request and returns details about the response.
- */
- return function (_ref2) {
- var requestId = _ref2.requestId,
- url = _ref2.url,
- payload = _ref2.payload,
- useSendBeacon = _ref2.useSendBeacon;
- // We want to log raw payload and event data rather than
- // our fancy wrapper objects. Calling payload.toJSON() is
- // insufficient to get all the nested raw data, because it's
- // not recursive (it doesn't call toJSON() on the event objects).
- // Parsing the result of JSON.stringify(), however, gives the
- // fully recursive raw data.
- var stringifiedPayload = JSON.stringify(payload);
- var parsedPayload = JSON.parse(stringifiedPayload);
- logger.logOnBeforeNetworkRequest({
- url: url,
- requestId: requestId,
- payload: parsedPayload
- });
-
- var executeRequest = function executeRequest() {
- var retriesAttempted = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
- var requestMethod = useSendBeacon ? sendBeaconRequest : sendFetchRequest;
- return requestMethod(url, stringifiedPayload).then(function (response) {
- var requestIsRetryable = isRequestRetryable({
- response: response,
- retriesAttempted: retriesAttempted
- });
-
- if (requestIsRetryable) {
- var requestRetryDelay = getRequestRetryDelay({
- response: response,
- retriesAttempted: retriesAttempted
- });
- return new Promise(function (resolve) {
- setTimeout(function () {
- resolve(executeRequest(retriesAttempted + 1));
- }, requestRetryDelay);
- });
- }
-
- var parsedBody;
-
- try {
- parsedBody = JSON.parse(response.body);
- } catch (e) {// Non-JSON. Something went wrong.
- }
-
- logger.logOnNetworkResponse(_objectSpread2(_objectSpread2({
- requestId: requestId,
- url: url,
- payload: parsedPayload
- }, response), {}, {
- parsedBody: parsedBody,
- retriesAttempted: retriesAttempted
- }));
- return {
- statusCode: response.statusCode,
- body: response.body,
- parsedBody: parsedBody,
- getHeader: response.getHeader
- };
- });
- };
-
- return executeRequest().catch(function (error) {
- logger.logOnNetworkError({
- requestId: requestId,
- url: url,
- payload: parsedPayload,
- error: error
- });
- throw stackError({
- error: error,
- message: "Network request failed."
- });
- });
- };
- });
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectExtractEdgeInfo = (function (_ref) {
- var logger = _ref.logger;
- return function (adobeEdgeHeader) {
- if (adobeEdgeHeader) {
- var headerParts = adobeEdgeHeader.split(";");
-
- if (headerParts.length >= 2 && headerParts[1].length > 0) {
- try {
- var regionId = parseInt(headerParts[1], 10); // eslint recommends using Number.isNaN instead, but this function is
- // not available in Internet Explorer. Number.isNaN is more robust to
- // non-numeric parameters. Since we already know regionId will be an
- // integer, using isNaN is okay.
- // https://github.com/airbnb/javascript#standard-library--isnan
- // eslint-disable-next-line no-restricted-globals
-
- if (!isNaN(regionId)) {
- return {
- regionId: regionId
- };
- }
- } catch (e) {// No need to do anything. The log statement below will log an error
- }
- }
-
- logger.warn("Invalid adobe edge: \"" + adobeEdgeHeader + "\"");
- }
-
- return {};
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var IN = "in";
- var OUT = "out";
- var PENDING = "pending";
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var GENERAL = "general";
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var DECLINED_CONSENT_ERROR_CODE = "declinedConsent";
- var CONSENT_SOURCE_DEFAULT = "default";
- var CONSENT_SOURCE_INITIAL = "initial";
- var CONSENT_SOURCE_NEW = "new";
-
- var createDeclinedConsentError = function createDeclinedConsentError(errorMessage) {
- var error = new Error(errorMessage);
- error.code = DECLINED_CONSENT_ERROR_CODE;
- error.message = errorMessage;
- return error;
- };
-
- var createConsentStateMachine = (function (_ref) {
- var logger = _ref.logger;
- var deferreds = [];
-
- var runAll = function runAll() {
- while (deferreds.length) {
- deferreds.shift().resolve();
- }
- };
-
- var discardAll = function discardAll() {
- while (deferreds.length) {
- deferreds.shift().reject(createDeclinedConsentError("The user declined consent."));
- }
- };
-
- var awaitInitial = function awaitInitial() {
- return Promise.reject(new Error("Consent has not been initialized."));
- };
-
- var awaitInDefault = function awaitInDefault() {
- return Promise.resolve();
- };
-
- var awaitIn = function awaitIn() {
- return Promise.resolve();
- };
-
- var awaitOutDefault = function awaitOutDefault() {
- return Promise.reject(createDeclinedConsentError("No consent preferences have been set."));
- };
-
- var awaitOut = function awaitOut() {
- return Promise.reject(createDeclinedConsentError("The user declined consent."));
- };
-
- var awaitPending = function awaitPending(returnImmediately) {
- if (returnImmediately) {
- return Promise.reject(new Error("Consent is pending."));
- }
-
- var deferred = defer();
- deferreds.push(deferred);
- return deferred.promise;
- };
-
- return {
- in: function _in(source) {
- if (source === CONSENT_SOURCE_DEFAULT) {
- this.awaitConsent = awaitInDefault;
- } else {
- if (source === CONSENT_SOURCE_INITIAL) {
- logger.info("Loaded user consent preferences. The user previously consented.");
- } else if (source === CONSENT_SOURCE_NEW && this.awaitConsent !== awaitIn) {
- logger.info("User consented.");
- }
-
- runAll();
- this.awaitConsent = awaitIn;
- }
- },
- out: function out(source) {
- if (source === CONSENT_SOURCE_DEFAULT) {
- logger.warn("User consent preferences not found. Default consent of out will be used.");
- this.awaitConsent = awaitOutDefault;
- } else {
- if (source === CONSENT_SOURCE_INITIAL) {
- logger.warn("Loaded user consent preferences. The user previously declined consent.");
- } else if (source === CONSENT_SOURCE_NEW && this.awaitConsent !== awaitOut) {
- logger.warn("User declined consent.");
- }
-
- discardAll();
- this.awaitConsent = awaitOut;
- }
- },
- pending: function pending(source) {
- if (source === CONSENT_SOURCE_DEFAULT) {
- logger.info("User consent preferences not found. Default consent of pending will be used. Some commands may be delayed.");
- }
-
- this.awaitConsent = awaitPending;
- },
- awaitConsent: awaitInitial,
- withConsent: function withConsent() {
- return this.awaitConsent(true);
- }
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createConsent = (function (_ref) {
- var generalConsentState = _ref.generalConsentState,
- logger = _ref.logger;
-
- var _setConsent = function setConsent(consentByPurpose, source) {
- switch (consentByPurpose[GENERAL]) {
- case IN:
- generalConsentState.in(source);
- break;
-
- case OUT:
- generalConsentState.out(source);
- break;
-
- case PENDING:
- generalConsentState.pending(source);
- break;
-
- default:
- logger.warn("Unknown consent value: " + consentByPurpose[GENERAL]);
- break;
- }
- };
-
- return {
- initializeConsent: function initializeConsent(defaultConsentByPurpose, storedConsentByPurpose) {
- if (storedConsentByPurpose[GENERAL]) {
- _setConsent(storedConsentByPurpose, CONSENT_SOURCE_INITIAL);
- } else {
- _setConsent(defaultConsentByPurpose, CONSENT_SOURCE_DEFAULT);
- }
- },
- setConsent: function setConsent(consentByPurpose) {
- _setConsent(consentByPurpose, CONSENT_SOURCE_NEW);
- },
- suspend: function suspend() {
- generalConsentState.pending();
- },
- awaitConsent: function awaitConsent() {
- return generalConsentState.awaitConsent();
- },
- withConsent: function withConsent() {
- return generalConsentState.withConsent();
- }
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createEvent = (function () {
- var content = {};
- var userXdm;
- var userData;
- var _documentMayUnload = false;
- var isFinalized = false;
- var shouldSendEvent = true;
-
- var throwIfEventFinalized = function throwIfEventFinalized(methodName) {
- if (isFinalized) {
- throw new Error(methodName + " cannot be called after event is finalized.");
- }
- };
-
- var event = {
- setUserXdm: function setUserXdm(value) {
- throwIfEventFinalized("setUserXdm");
- userXdm = value;
- },
- setUserData: function setUserData(value) {
- throwIfEventFinalized("setUserData");
- userData = value;
- },
- mergeXdm: function mergeXdm(xdm) {
- throwIfEventFinalized("mergeXdm");
-
- if (xdm) {
- deepAssign(content, {
- xdm: xdm
- });
- }
- },
- mergeMeta: function mergeMeta(meta) {
- throwIfEventFinalized("mergeMeta");
-
- if (meta) {
- deepAssign(content, {
- meta: meta
- });
- }
- },
- mergeQuery: function mergeQuery(query) {
- throwIfEventFinalized("mergeQuery");
-
- if (query) {
- deepAssign(content, {
- query: query
- });
- }
- },
- documentMayUnload: function documentMayUnload() {
- _documentMayUnload = true;
- },
- finalize: function finalize(onBeforeEventSend) {
- if (isFinalized) {
- return;
- }
-
- if (userXdm) {
- event.mergeXdm(userXdm);
- }
-
- if (userData) {
- content.data = userData;
- } // the event should already be considered finalized in case onBeforeEventSend throws an error
-
-
- isFinalized = true;
-
- if (onBeforeEventSend) {
- // assume that the onBeforeEventSend callback will fail (in-case of an error)
- shouldSendEvent = false; // this allows the user to replace the xdm and data properties
- // on the object passed to the callback
-
- var tempContent = {
- xdm: content.xdm || {},
- data: content.data || {}
- };
- var result = onBeforeEventSend(tempContent);
- shouldSendEvent = result !== false;
- content.xdm = tempContent.xdm || {};
- content.data = tempContent.data || {};
-
- if (isEmptyObject(content.xdm)) {
- delete content.xdm;
- }
-
- if (isEmptyObject(content.data)) {
- delete content.data;
- }
- }
- },
- getDocumentMayUnload: function getDocumentMayUnload() {
- return _documentMayUnload;
- },
- isEmpty: function isEmpty() {
- return isEmptyObject(content) && (!userXdm || isEmptyObject(userXdm)) && (!userData || isEmptyObject(userData));
- },
- shouldSend: function shouldSend() {
- return shouldSendEvent;
- },
- getViewName: function getViewName() {
- if (!userXdm || !userXdm.web || !userXdm.web.webPageDetails) {
- return undefined;
- }
-
- return userXdm.web.webPageDetails.viewName;
- },
- toJSON: function toJSON() {
- if (!isFinalized) {
- throw new Error("toJSON called before finalize");
- }
-
- return content;
- }
- };
- return event;
- });
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var RETRY_AFTER = "Retry-After";
- var ADOBE_EDGE = "x-adobe-edge";
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Creates a representation of a gateway response with the addition of
- * helper methods.
- * @returns Response
- */
-
- var injectCreateResponse = (function (_ref) {
- var extractEdgeInfo = _ref.extractEdgeInfo;
- return function (_ref2) {
- var _ref2$content = _ref2.content,
- content = _ref2$content === void 0 ? {} : _ref2$content,
- getHeader = _ref2.getHeader;
- var _content$handle = content.handle,
- handle = _content$handle === void 0 ? [] : _content$handle,
- _content$errors = content.errors,
- errors = _content$errors === void 0 ? [] : _content$errors,
- _content$warnings = content.warnings,
- warnings = _content$warnings === void 0 ? [] : _content$warnings;
- /**
- * Response object.
- * @typedef {Object} Response
- */
-
- return {
- /**
- * Returns matching fragments of the response by type.
- * @param {String} type A string with the current format:
- *
- * @example
- * getPayloadsByType("identity:persist")
- */
- getPayloadsByType: function getPayloadsByType(type) {
- return flatMap(handle.filter(function (fragment) {
- return fragment.type === type;
- }), function (fragment) {
- return fragment.payload;
- });
- },
-
- /**
- * Returns all errors.
- */
- getErrors: function getErrors() {
- return errors;
- },
-
- /**
- * Returns all warnings.
- */
- getWarnings: function getWarnings() {
- return warnings;
- },
-
- /**
- * Returns an object containing the regionId from the x-adobe-edge header
- */
- getEdge: function getEdge() {
- return extractEdgeInfo(getHeader(ADOBE_EDGE));
- },
- toJSON: function toJSON() {
- return content;
- }
- };
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var CONFIGURE = "configure";
- var SET_DEBUG = "setDebug";
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectExecuteCommand = (function (_ref) {
- var logger = _ref.logger,
- configureCommand = _ref.configureCommand,
- setDebugCommand = _ref.setDebugCommand,
- handleError = _ref.handleError,
- validateCommandOptions = _ref.validateCommandOptions;
- var configurePromise;
-
- var getExecutor = function getExecutor(commandName, options) {
- var executor;
-
- if (commandName === CONFIGURE) {
- if (configurePromise) {
- throw new Error("The library has already been configured and may only be configured once.");
- }
-
- executor = function executor() {
- configurePromise = configureCommand(options);
- return configurePromise.then(function () {// Don't expose internals to the user.
- });
- };
- } else {
- if (!configurePromise) {
- throw new Error("The library must be configured first. Please do so by executing the configure command.");
- }
-
- if (commandName === SET_DEBUG) {
- executor = function executor() {
- return setDebugCommand(options);
- };
- } else {
- executor = function executor() {
- return configurePromise.then(function (componentRegistry) {
- var command = componentRegistry.getCommand(commandName);
-
- if (!command || !isFunction(command.run)) {
- var commandNames = [CONFIGURE, SET_DEBUG].concat(componentRegistry.getCommandNames()).join(", ");
- throw new Error("The " + commandName + " command does not exist. List of available commands: " + commandNames + ".");
- }
-
- var validatedOptions = validateCommandOptions({
- command: command,
- options: options
- });
- return command.run(validatedOptions);
- }, function () {
- logger.warn("An error during configuration is preventing the " + commandName + " command from executing."); // If configuration failed, we prevent the configuration
- // error from bubbling here because we don't want the
- // configuration error to be reported in the console every
- // time any command is executed. Only having it bubble
- // once when the configure command runs is sufficient.
- // Instead, for this command, we'll just return a promise
- // that never gets resolved.
-
- return new Promise(function () {});
- });
- };
- }
- }
-
- return executor;
- };
-
- return function (commandName) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- return new Promise(function (resolve) {
- // We have to wrap the getExecutor() call in the promise so the promise
- // will be rejected if getExecutor() throws errors.
- var executor = getExecutor(commandName, options);
- logger.logOnBeforeCommand({
- commandName: commandName,
- options: options
- });
- resolve(executor());
- }).catch(function (error) {
- return handleError(error, commandName + " command");
- }).catch(function (error) {
- logger.logOnCommandRejected({
- commandName: commandName,
- options: options,
- error: error
- });
- throw error;
- }).then(function (rawResult) {
- // We should always be returning an object from every command.
- var result = isObject(rawResult) ? rawResult : {};
- logger.logOnCommandResolved({
- commandName: commandName,
- options: options,
- result: result
- });
- return result;
- });
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var COMMAND_DOC_URI = "https://adobe.ly/3sHgQHb";
- var validateCommandOptions = (function (_ref) {
- var command = _ref.command,
- options = _ref.options;
- var commandName = command.commandName,
- _command$documentatio = command.documentationUri,
- documentationUri = _command$documentatio === void 0 ? COMMAND_DOC_URI : _command$documentatio,
- optionsValidator = command.optionsValidator;
- var validatedOptions = options;
-
- if (optionsValidator) {
- try {
- validatedOptions = optionsValidator(options);
- } catch (validationError) {
- var invalidOptionsMessage = "Invalid " + commandName + " command options:\n\t - " + validationError + " For command documentation see: " + documentationUri;
- throw new Error(invalidOptionsMessage);
- }
- }
-
- return validatedOptions;
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Verifies user provided event options.
- * @param {*} options The user event options to validate
- * @returns {*} Validated options
- */
-
- var validateUserEventOptions = (function (_ref) {
- var options = _ref.options;
- var eventOptionsValidator = boundObjectOf({
- type: boundString(),
- xdm: boundObjectOf({
- eventType: boundString(),
- identityMap: validateIdentityMap
- }),
- data: boundObjectOf({}),
- documentUnloading: boundBoolean(),
- renderDecisions: boundBoolean(),
- decisionScopes: boundArrayOf(boundString()).uniqueItems(),
- personalization: boundObjectOf({
- decisionScopes: boundArrayOf(boundString()).uniqueItems(),
- surfaces: boundArrayOf(boundString()).uniqueItems()
- }),
- datasetId: boundString(),
- mergeId: boundString(),
- edgeConfigOverrides: validateConfigOverride
- }).required().noUnknownFields();
- return eventOptionsValidator(options);
- });
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var validateApplyResponse = (function (_ref) {
- var options = _ref.options;
- var validator = boundObjectOf({
- renderDecisions: boundBoolean(),
- responseHeaders: boundMapOfValues(boundString().required()),
- responseBody: boundObjectOf({
- handle: boundArrayOf(boundObjectOf({
- type: boundString().required(),
- payload: boundAnything().required()
- })).required()
- }).required()
- }).noUnknownFields();
- return validator(options);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var createDataCollector = function createDataCollector(_ref) {
- var eventManager = _ref.eventManager,
- logger = _ref.logger;
- return {
- commands: {
- sendEvent: {
- documentationUri: "https://adobe.ly/3GQ3Q7t",
- optionsValidator: function optionsValidator(options) {
- return validateUserEventOptions({
- options: options
- });
- },
- run: function run(options) {
- var xdm = options.xdm,
- data = options.data,
- _options$documentUnlo = options.documentUnloading,
- documentUnloading = _options$documentUnlo === void 0 ? false : _options$documentUnlo,
- type = options.type,
- mergeId = options.mergeId,
- _options$renderDecisi = options.renderDecisions,
- renderDecisions = _options$renderDecisi === void 0 ? false : _options$renderDecisi,
- _options$decisionScop = options.decisionScopes,
- decisionScopes = _options$decisionScop === void 0 ? [] : _options$decisionScop,
- _options$personalizat = options.personalization,
- personalization = _options$personalizat === void 0 ? {} : _options$personalizat,
- datasetId = options.datasetId,
- edgeConfigOverrides = options.edgeConfigOverrides;
- var event = eventManager.createEvent();
-
- if (documentUnloading) {
- event.documentMayUnload();
- }
-
- event.setUserXdm(xdm);
- event.setUserData(data);
-
- if (type) {
- event.mergeXdm({
- eventType: type
- });
- }
-
- if (mergeId) {
- event.mergeXdm({
- eventMergeId: mergeId
- });
- }
-
- var sendEventOptions = {
- renderDecisions: renderDecisions,
- decisionScopes: decisionScopes,
- personalization: personalization
- };
-
- if (edgeConfigOverrides) {
- sendEventOptions.edgeConfigOverrides = edgeConfigOverrides;
- }
-
- if (datasetId) {
- logger.warn("The 'datasetId' option has been deprecated. Please use 'edgeConfigOverrides.experience_platform.datasets.event' instead.");
- sendEventOptions.edgeConfigOverrides = edgeConfigOverrides || {};
- deepAssign(sendEventOptions.edgeConfigOverrides, {
- com_adobe_experience_platform: {
- datasets: {
- event: {
- datasetId: datasetId
- }
- }
- }
- });
- }
-
- return eventManager.sendEvent(event, sendEventOptions);
- }
- },
- applyResponse: {
- documentationUri: "",
- optionsValidator: function optionsValidator(options) {
- return validateApplyResponse({
- options: options
- });
- },
- run: function run(options) {
- var _options$renderDecisi2 = options.renderDecisions,
- renderDecisions = _options$renderDecisi2 === void 0 ? false : _options$renderDecisi2,
- _options$responseHead = options.responseHeaders,
- responseHeaders = _options$responseHead === void 0 ? {} : _options$responseHead,
- _options$responseBody = options.responseBody,
- responseBody = _options$responseBody === void 0 ? {
- handle: []
- } : _options$responseBody;
- var event = eventManager.createEvent();
- return eventManager.applyResponse(event, {
- renderDecisions: renderDecisions,
- responseHeaders: responseHeaders,
- responseBody: responseBody
- });
- }
- }
- }
- };
- };
-
- createDataCollector.namespace = "DataCollector";
- createDataCollector.configValidators = {};
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var createClickHandler = function createClickHandler(_ref) {
- var eventManager = _ref.eventManager,
- lifecycle = _ref.lifecycle,
- handleError = _ref.handleError;
- return function (clickEvent) {
- // TODO: Consider safeguarding from the same object being clicked multiple times in rapid succession?
- var clickedElement = clickEvent.target;
- var event = eventManager.createEvent(); // this is to make sure a exit link personalization metric use send beacon
-
- event.documentMayUnload();
- return lifecycle.onClick({
- event: event,
- clickedElement: clickedElement
- }).then(function () {
- if (event.isEmpty()) {
- return Promise.resolve();
- }
-
- return eventManager.sendEvent(event);
- }) // eventManager.sendEvent() will return a promise resolved to an
- // object and we want to avoid returning any value to the customer
- .then(noop$1).catch(function (error) {
- handleError(error, "click collection");
- });
- };
- };
-
- var attachClickActivityCollector = (function (_ref2) {
- var eventManager = _ref2.eventManager,
- lifecycle = _ref2.lifecycle,
- handleError = _ref2.handleError;
- var clickHandler = createClickHandler({
- eventManager: eventManager,
- lifecycle: lifecycle,
- handleError: handleError
- });
- document.addEventListener("click", clickHandler, true);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var configValidators$1 = {
- clickCollectionEnabled: boundBoolean().default(true),
- downloadLinkQualifier: boundString().regexp().default("\\.(exe|zip|wav|mp3|mov|mpg|avi|wmv|pdf|doc|docx|xls|xlsx|ppt|pptx)$"),
- onBeforeLinkClickSend: boundCallback()
- };
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createLinkClick = (function (_ref) {
- var getLinkDetails = _ref.getLinkDetails,
- config = _ref.config,
- logger = _ref.logger;
- var clickCollectionEnabled = config.clickCollectionEnabled;
-
- if (!clickCollectionEnabled) {
- return function () {
- return undefined;
- };
- }
-
- return function (_ref2) {
- var targetElement = _ref2.targetElement,
- event = _ref2.event;
- var linkDetails = getLinkDetails({
- targetElement: targetElement,
- config: config,
- logger: logger
- });
-
- if (linkDetails) {
- event.mergeXdm(linkDetails.xdm);
- event.setUserData(linkDetails.data);
- }
- };
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createGetLinkDetails = (function (_ref) {
- var window = _ref.window,
- getLinkName = _ref.getLinkName,
- getLinkRegion = _ref.getLinkRegion,
- getAbsoluteUrlFromAnchorElement = _ref.getAbsoluteUrlFromAnchorElement,
- findSupportedAnchorElement = _ref.findSupportedAnchorElement,
- determineLinkType = _ref.determineLinkType;
- return function (_ref2) {
- var targetElement = _ref2.targetElement,
- config = _ref2.config,
- logger = _ref2.logger;
- var anchorElement = findSupportedAnchorElement(targetElement);
-
- if (!anchorElement) {
- logger.info("This link click event is not triggered because the HTML element is not an anchor.");
- return undefined;
- }
-
- var linkUrl = getAbsoluteUrlFromAnchorElement(window, anchorElement);
-
- if (!linkUrl) {
- logger.info("This link click event is not triggered because the HTML element doesn't have an URL.");
- return undefined;
- }
-
- var linkType = determineLinkType(window, config, linkUrl, anchorElement);
- var linkRegion = getLinkRegion(anchorElement);
- var linkName = getLinkName(anchorElement);
- var onBeforeLinkClickSend = config.onBeforeLinkClickSend;
- var options = {
- xdm: {
- eventType: "web.webinteraction.linkClicks",
- web: {
- webInteraction: {
- name: linkName,
- region: linkRegion,
- type: linkType,
- URL: linkUrl,
- linkClicks: {
- value: 1
- }
- }
- }
- },
- data: {},
- clickedElement: targetElement
- };
-
- if (!onBeforeLinkClickSend) {
- return options;
- }
-
- var shouldEventBeTracked = onBeforeLinkClickSend(options);
-
- if (shouldEventBeTracked !== false) {
- return options;
- }
-
- logger.info("This link click event is not triggered because it was canceled in onBeforeLinkClickSend.");
- return undefined;
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var urlStartsWithScheme = function urlStartsWithScheme(url) {
- return url && /^[a-z0-9]+:\/\//i.test(url);
- };
-
- var getAbsoluteUrlFromAnchorElement = function getAbsoluteUrlFromAnchorElement(window, element) {
- var loc = window.location;
- var url = element.href ? element.href : "";
- var protocol = element.protocol,
- host = element.host;
-
- if (!urlStartsWithScheme(url)) {
- if (!protocol) {
- protocol = loc.protocol ? loc.protocol : "";
- }
-
- protocol = protocol ? protocol + "//" : "";
-
- if (!host) {
- host = loc.host ? loc.host : "";
- }
-
- var path = "";
-
- if (url.substring(0, 1) !== "/") {
- var indx = loc.pathname.lastIndexOf("/");
- indx = indx < 0 ? 0 : indx;
- path = loc.pathname.substring(0, indx);
- }
-
- url = "" + protocol + host + path + "/" + url;
- }
-
- return url;
- };
-
- var isSupportedAnchorElement = function isSupportedAnchorElement(element) {
- if (element.href && (element.tagName === "A" || element.tagName === "AREA") && (!element.onclick || !element.protocol || element.protocol.toLowerCase().indexOf("javascript") < 0)) {
- return true;
- }
-
- return false;
- };
-
- var isDownloadLink = function isDownloadLink(downloadLinkQualifier, linkUrl, clickedObj) {
- var re = new RegExp(downloadLinkQualifier);
- return clickedObj.download ? true : re.test(linkUrl.toLowerCase());
- };
-
- var isExitLink = function isExitLink(window, linkUrl) {
- var currentHostname = window.location.hostname.toLowerCase();
-
- if (linkUrl.toLowerCase().indexOf(currentHostname) >= 0) {
- return false;
- }
-
- return true;
- };
- /**
- * Reduces repeated whitespace within a string. Whitespace surrounding the string
- * is trimmed and any occurrence of whitespace within the string is replaced with
- * a single space.
- * @param {string} str String to be formatted.
- * @returns {string} Formatted string.
- */
-
-
- var truncateWhiteSpace = function truncateWhiteSpace(str) {
- return str && str.replace(/\s+/g, " ").trim();
- };
-
- var determineLinkType = function determineLinkType(window, config, linkUrl, clickedObj) {
- var linkType = "other";
-
- if (isDownloadLink(config.downloadLinkQualifier, linkUrl, clickedObj)) {
- linkType = "download";
- } else if (isExitLink(window, linkUrl)) {
- linkType = "exit";
- }
-
- return linkType;
- };
-
- var findSupportedAnchorElement = function findSupportedAnchorElement(targetElement) {
- var node = targetElement;
-
- while (node) {
- if (isSupportedAnchorElement(node)) {
- return node;
- }
-
- node = node.parentNode;
- }
-
- return null;
- };
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var unsupportedNodeNames = /^(SCRIPT|STYLE|LINK|CANVAS|NOSCRIPT|#COMMENT)$/i;
- /**
- * Determines if a node qualifies as a supported link text node.
- * @param {*} node Node to determine support for.
- * @returns {boolean}
- */
-
- var isSupportedTextNode = function isSupportedTextNode(node) {
- if (node && node.nodeName) {
- if (node.nodeName.match(unsupportedNodeNames)) {
- return false;
- }
- }
-
- return true;
- };
- /**
- * Orders and returns specified node and its child nodes in arrays of supported
- * and unsupported nodes.
- * @param {*} node The node to extract supported and unsupported nodes from.
- * @returns {{supportedNodes: Array, includesUnsupportedNodes: boolean}} Node support object.
- */
-
-
- var extractSupportedNodes = function extractSupportedNodes(node) {
- var supportedNodes = [];
- var includesUnsupportedNodes = false;
-
- if (isSupportedTextNode(node)) {
- supportedNodes.push(node);
-
- if (node.childNodes) {
- var childNodes = Array.prototype.slice.call(node.childNodes);
- childNodes.forEach(function (childNode) {
- var nodes = extractSupportedNodes(childNode);
- supportedNodes = supportedNodes.concat(nodes.supportedNodes);
- includesUnsupportedNodes = includesUnsupportedNodes || nodes.includesUnsupportedNodes;
- });
- }
- } else {
- includesUnsupportedNodes = true;
- }
-
- return {
- supportedNodes: supportedNodes,
- includesUnsupportedNodes: includesUnsupportedNodes
- };
- };
- /**
- * Returns the value of a node attribute.
- * @param {*} node The node holding the attribute.
- * @param {string} attributeName The name of the attribute.
- * @param {string} nodeName Optional node name constraint.
- * @returns {string} Attribute value or undefined.
- */
-
-
- var getNodeAttributeValue = function getNodeAttributeValue(node, attributeName, nodeName) {
- var attributeValue;
-
- if (!nodeName || nodeName === node.nodeName.toUpperCase()) {
- attributeValue = node.getAttribute(attributeName);
- }
-
- return attributeValue;
- };
- /**
- * Extracts the children supported nodes attributes map
- * @param {*} nodes The nodes array holding the children nodes.
- * The returned map contains the supported not empty children attributes values.
- * */
-
-
- var getChildrenAttributes = function getChildrenAttributes(nodes) {
- var attributes = {
- texts: []
- };
- nodes.supportedNodes.forEach(function (supportedNode) {
- if (supportedNode.getAttribute) {
- if (!attributes.alt) {
- attributes.alt = truncateWhiteSpace(supportedNode.getAttribute("alt"));
- }
-
- if (!attributes.title) {
- attributes.title = truncateWhiteSpace(supportedNode.getAttribute("title"));
- }
-
- if (!attributes.inputValue) {
- attributes.inputValue = truncateWhiteSpace(getNodeAttributeValue(supportedNode, "value", "INPUT"));
- }
-
- if (!attributes.imgSrc) {
- attributes.imgSrc = truncateWhiteSpace(getNodeAttributeValue(supportedNode, "src", "IMG"));
- }
- }
-
- if (supportedNode.nodeValue) {
- attributes.texts.push(supportedNode.nodeValue);
- }
- });
- return attributes;
- };
- /**
- * Extracts a link-name from a given node.
- *
- * The returned link-name is set to one of the following (in order of priority):
- *
- * 1. Clicked node innerText
- * 2. Clicked node textContent
- * 3. Clicked node and its child nodes nodeValue appended together.
- * 4. Clicked node alt attribute or node descendant alt attribute.
- * Whichever is found first.
- * 5. Clicked node text attribute or node descendant text attribute.
- * Whichever is found first.
- * 6. Clicked node INPUT descendant value attribute.
- * Whichever is found first.
- * 7. Clicked node IMG descendant src attribute.
- * Whichever is found first.
- *
- * @param {*} node The node to find link text for.
- * @returns {string} link-name or an empty string if not link-name is found.
- */
-
-
- var getLinkName = (function (node) {
- var nodeText = truncateWhiteSpace(node.innerText || node.textContent);
- var nodes = extractSupportedNodes(node); // if contains unsupported nodes we want children node attributes
-
- if (!nodeText || nodes.includesUnsupportedNodes) {
- var attributesMap = getChildrenAttributes(nodes);
- nodeText = truncateWhiteSpace(attributesMap.texts.join(""));
-
- if (!nodeText) {
- nodeText = attributesMap.alt || attributesMap.title || attributesMap.inputValue || attributesMap.imgSrc;
- }
- }
-
- return nodeText || "";
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var semanticElements = /^(HEADER|MAIN|FOOTER|NAV)$/i;
-
- var getAriaRegionLabel = function getAriaRegionLabel(node) {
- var regionLabel;
-
- if (node.role === "region" && isNonEmptyString(node["aria-label"])) {
- regionLabel = node["aria-label"];
- }
-
- return regionLabel;
- };
-
- var getSectionNodeName = function getSectionNodeName(node) {
- var nodeName;
-
- if (node && node.nodeName) {
- if (node.nodeName.match(semanticElements)) {
- nodeName = node.nodeName;
- }
- }
-
- return nodeName;
- };
- /**
- * Extracts a node link-region.
- *
- * The link-region is determined by traversing up the DOM
- * looking for a region that is determined in order of priority:
- *
- * 1. element.id
- * 2. Aria region label
- * 3. Semantic element name
- * 4. BODY (if no other link-region is found).
- *
- * @param {*} node The node to find link region for.
- * @returns {string} link-region.
- */
-
-
- var getLinkRegion = (function (node) {
- var linkParentNode = node.parentNode;
- var regionName;
-
- while (linkParentNode) {
- regionName = truncateWhiteSpace(linkParentNode.id || getAriaRegionLabel(linkParentNode) || getSectionNodeName(linkParentNode));
-
- if (regionName) {
- return regionName;
- }
-
- linkParentNode = linkParentNode.parentNode;
- }
-
- return "BODY";
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var _getLinkDetails = createGetLinkDetails({
- window: window,
- getLinkName: getLinkName,
- getLinkRegion: getLinkRegion,
- getAbsoluteUrlFromAnchorElement: getAbsoluteUrlFromAnchorElement,
- findSupportedAnchorElement: findSupportedAnchorElement,
- determineLinkType: determineLinkType
- });
-
- var createActivityCollector = function createActivityCollector(_ref) {
- var config = _ref.config,
- eventManager = _ref.eventManager,
- handleError = _ref.handleError,
- logger = _ref.logger;
- var linkClick = createLinkClick({
- getLinkDetails: _getLinkDetails,
- config: config,
- logger: logger
- });
- return {
- lifecycle: {
- onComponentsRegistered: function onComponentsRegistered(tools) {
- var lifecycle = tools.lifecycle;
- attachClickActivityCollector({
- eventManager: eventManager,
- lifecycle: lifecycle,
- handleError: handleError
- }); // TODO: createScrollActivityCollector ...
- },
- onClick: function onClick(_ref2) {
- var event = _ref2.event,
- clickedElement = _ref2.clickedElement;
- linkClick({
- targetElement: clickedElement,
- event: event
- });
- }
- }
- };
- };
-
- createActivityCollector.namespace = "ActivityCollector";
- createActivityCollector.configValidators = configValidators$1;
-
- createActivityCollector.buildOnInstanceConfiguredExtraParams = function (_ref3) {
- var config = _ref3.config,
- logger = _ref3.logger;
- return {
- getLinkDetails: function getLinkDetails(targetElement) {
- return _getLinkDetails({
- targetElement: targetElement,
- config: config,
- logger: logger
- });
- }
- };
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var createResultLogMessage$1 = function createResultLogMessage(idSync, success) {
- return "ID sync " + (success ? "succeeded" : "failed") + ": " + idSync.spec.url;
- };
-
- var injectProcessIdSyncs = (function (_ref) {
- var fireReferrerHideableImage = _ref.fireReferrerHideableImage,
- logger = _ref.logger;
- return function (idSyncs) {
- var urlIdSyncs = idSyncs.filter(function (idSync) {
- return idSync.type === "url";
- });
-
- if (!urlIdSyncs.length) {
- return Promise.resolve();
- }
-
- return Promise.all(urlIdSyncs.map(function (idSync) {
- return fireReferrerHideableImage(idSync.spec).then(function () {
- logger.info(createResultLogMessage$1(idSync, true));
- }).catch(function () {
- // We intentionally do not throw an error if id syncs fail. We
- // consider it a non-critical failure and therefore do not want it to
- // reject the promise handed back to the customer.
- logger.error(createResultLogMessage$1(idSync, false));
- });
- })).then(noop$1);
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var configValidators = {
- thirdPartyCookiesEnabled: boundBoolean().default(true),
- idMigrationEnabled: boundBoolean().default(true)
- };
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Verifies user provided event options.
- * @param {*} options The user event options to validate
- * @returns {*} Validated options
- */
-
- var getIdentityOptionsValidator = boundObjectOf({
- namespaces: boundArrayOf(boundLiteral("ECID")).nonEmpty().uniqueItems().default(["ECID"]),
- edgeConfigOverrides: validateConfigOverride
- }).noUnknownFields().default({
- namespaces: ["ECID"]
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Verifies user provided event options.
- * @param {*} options The user event options to validate
- * @returns {*} Validated options
- */
-
- var appendIdentityToUrlOptionsValidator = boundObjectOf({
- url: boundString().required().nonEmpty(),
- edgeConfigOverrides: validateConfigOverride
- }).required().noUnknownFields();
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createComponent$4 = (function (_ref) {
- var addEcidQueryToPayload = _ref.addEcidQueryToPayload,
- addQueryStringIdentityToPayload = _ref.addQueryStringIdentityToPayload,
- ensureSingleIdentity = _ref.ensureSingleIdentity,
- setLegacyEcid = _ref.setLegacyEcid,
- handleResponseForIdSyncs = _ref.handleResponseForIdSyncs,
- getEcidFromResponse = _ref.getEcidFromResponse,
- getIdentity = _ref.getIdentity,
- consent = _ref.consent,
- appendIdentityToUrl = _ref.appendIdentityToUrl,
- logger = _ref.logger;
- var ecid;
- var edge = {};
- return {
- lifecycle: {
- onBeforeRequest: function onBeforeRequest(_ref2) {
- var request = _ref2.request,
- onResponse = _ref2.onResponse,
- onRequestFailure = _ref2.onRequestFailure;
- // Querying the ECID on every request to be able to set the legacy cookie, and make it
- // available for the `getIdentity` command.
- addEcidQueryToPayload(request.getPayload());
- addQueryStringIdentityToPayload(request.getPayload());
- return ensureSingleIdentity({
- request: request,
- onResponse: onResponse,
- onRequestFailure: onRequestFailure
- });
- },
- onResponse: function onResponse(_ref3) {
- var response = _ref3.response;
-
- if (!ecid) {
- ecid = getEcidFromResponse(response); // Only data collection calls will have an ECID in the response.
- // https://jira.corp.adobe.com/browse/EXEG-1234
-
- if (ecid) {
- setLegacyEcid(ecid);
- }
- } // For sendBeacon requests, getEdge() will return {}, so we are using assign here
- // so that sendBeacon requests don't override the edge info from before.
-
-
- edge = reactorObjectAssign(edge, response.getEdge());
- return handleResponseForIdSyncs(response);
- }
- },
- commands: {
- getIdentity: {
- optionsValidator: getIdentityOptionsValidator,
- run: function run(options) {
- return consent.awaitConsent().then(function () {
- return ecid ? undefined : getIdentity(options);
- }).then(function () {
- return {
- identity: {
- ECID: ecid
- },
- edge: edge
- };
- });
- }
- },
- appendIdentityToUrl: {
- optionsValidator: appendIdentityToUrlOptionsValidator,
- run: function run(options) {
- return consent.withConsent().then(function () {
- return ecid ? undefined : getIdentity(options);
- }).then(function () {
- return {
- url: appendIdentityToUrl(ecid, options.url)
- };
- }).catch(function (error) {
- logger.warn("Unable to append identity to url. " + error.message);
- return options;
- });
- }
- }
- }
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Handles migration of ECID to and from Visitor.js.
- */
- var createLegacyIdentity = (function (_ref) {
- var config = _ref.config,
- getEcidFromVisitor = _ref.getEcidFromVisitor,
- apexDomain = _ref.apexDomain,
- isPageSsl = _ref.isPageSsl,
- cookieJar = _ref.cookieJar;
- var idMigrationEnabled = config.idMigrationEnabled,
- orgId = config.orgId;
- var amcvCookieName = "AMCV_" + orgId;
-
- var getEcidFromLegacyCookies = function getEcidFromLegacyCookies() {
- var ecid = null;
- var secidCookieName = "s_ecid";
- var legacyEcidCookieValue = cookieJar.get(secidCookieName) || cookieJar.get(amcvCookieName);
-
- if (legacyEcidCookieValue) {
- var reg = /(^|\|)MCMID\|(\d+)($|\|)/;
- var matches = legacyEcidCookieValue.match(reg);
-
- if (matches) {
- // Destructuring arrays breaks in IE
- ecid = matches[2];
- }
- }
-
- return ecid;
- };
-
- return {
- getEcid: function getEcid() {
- if (idMigrationEnabled) {
- var ecid = getEcidFromLegacyCookies();
-
- if (ecid) {
- return Promise.resolve(ecid);
- }
-
- return getEcidFromVisitor();
- }
-
- return Promise.resolve();
- },
- setEcid: function setEcid(ecid) {
- if (idMigrationEnabled && getEcidFromLegacyCookies() !== ecid) {
- var extraOptions = isPageSsl ? {
- sameSite: "none",
- secure: true
- } : {};
- cookieJar.set(amcvCookieName, "MCMID|" + ecid, _objectSpread2({
- domain: apexDomain,
- // Without `expires` this will be a session cookie.
- expires: 390
- }, extraOptions));
- }
- }
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var awaitVisitorOptIn = (function (_ref) {
- var logger = _ref.logger;
- return new Promise(function (resolve, reject) {
- if (isObject(window.adobe) && isObject(window.adobe.optIn)) {
- var optInOld = window.adobe.optIn;
- logger.info("Delaying request while waiting for legacy opt-in to let Visitor retrieve ECID from server.");
- optInOld.fetchPermissions(function () {
- if (optInOld.isApproved([optInOld.Categories.ECID])) {
- logger.info("Received legacy opt-in approval to let Visitor retrieve ECID from server.");
- resolve();
- } else {
- reject(new Error("Legacy opt-in was declined."));
- }
- }, true);
- } else {
- resolve();
- }
- });
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var getVisitor = (function (window) {
- var Visitor = window.Visitor;
- return isFunction(Visitor) && isFunction(Visitor.getInstance) && Visitor;
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectGetEcidFromVisitor = (function (_ref) {
- var logger = _ref.logger,
- orgId = _ref.orgId,
- awaitVisitorOptIn = _ref.awaitVisitorOptIn;
- return function () {
- var Visitor = getVisitor(window);
-
- if (Visitor) {
- // Need to explicitly wait for optIn because visitor will call callback
- // with invalid values prior to optIn being approved
- return awaitVisitorOptIn({
- logger: logger
- }).then(function () {
- logger.info("Delaying request while using Visitor to retrieve ECID from server.");
- return new Promise(function (resolve) {
- var visitor = Visitor.getInstance(orgId, {});
- visitor.getMarketingCloudVisitorID(function (ecid) {
- logger.info("Resuming previously delayed request that was waiting for ECID from Visitor.");
- resolve(ecid);
- }, true);
- });
- }).catch(function (error) {
- // If consent was denied, get the ECID from experience edge. OptIn and AEP Web SDK
- // consent should operate independently, but during id migration AEP Web SDK needs
- // to wait for optIn object consent resolution so that only one ECID is generated.
- if (error) {
- logger.info(error.message + ", retrieving ECID from experience edge");
- } else {
- logger.info("An error occurred while obtaining the ECID from Visitor.");
- }
- });
- }
-
- return Promise.resolve();
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectHandleResponseForIdSyncs = (function (_ref) {
- var processIdSyncs = _ref.processIdSyncs;
- return function (response) {
- return processIdSyncs(response.getPayloadsByType("identity:exchange"));
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- // TO-DOCUMENT: We queue subsequent requests until we have an identity cookie.
- var injectEnsureSingleIdentity = (function (_ref) {
- var doesIdentityCookieExist = _ref.doesIdentityCookieExist,
- setDomainForInitialIdentityPayload = _ref.setDomainForInitialIdentityPayload,
- addLegacyEcidToPayload = _ref.addLegacyEcidToPayload,
- awaitIdentityCookie = _ref.awaitIdentityCookie,
- logger = _ref.logger;
- var obtainedIdentityPromise;
-
- var allowRequestToGoWithoutIdentity = function allowRequestToGoWithoutIdentity(request) {
- setDomainForInitialIdentityPayload(request);
- return addLegacyEcidToPayload(request.getPayload());
- };
- /**
- * Ensures that if no identity cookie exists, we only let one request at a
- * time without an identity until its response returns. In the meantime,
- * we queue all other requests, otherwise the requests could result in
- * multiple ECIDs being minted for the user. Once we get an identity
- * cookie, we can let the queued requests be sent all at once, since they
- * will have the newly minted ECID.
- *
- * Konductor should make every effort to return an identity, but in
- * certain scenarios it may not. For example, in cases where the
- * request does not match what Konductor is expecting (ie 400s).
- * In cases where Konductor does not set an identity, there should be
- * no events recorded so we don't need to worry about multiple ECIDs
- * being minted for each user.
- *
- * The reason we allow for multiple sequential requests to be sent without
- * an identity is to prevent a single malformed request causing all other
- * requests to never send.
- */
-
-
- return function (_ref2) {
- var request = _ref2.request,
- onResponse = _ref2.onResponse,
- onRequestFailure = _ref2.onRequestFailure;
-
- if (doesIdentityCookieExist()) {
- request.setIsIdentityEstablished();
- return Promise.resolve();
- }
-
- if (obtainedIdentityPromise) {
- // We don't have an identity cookie, but at least one request has
- // been sent to get it. Konductor may set the identity cookie in the
- // response. We will hold up this request until the last request
- // requiring identity returns and awaitIdentityCookie confirms the
- // identity was set.
- logger.info("Delaying request while retrieving ECID from server.");
- var previousObtainedIdentityPromise = obtainedIdentityPromise; // This promise resolves when we have an identity cookie. Additional
- // requests are chained together so that only one is sent at a time
- // until we have the identity cookie.
-
- obtainedIdentityPromise = previousObtainedIdentityPromise.catch(function () {
- return awaitIdentityCookie({
- onResponse: onResponse,
- onRequestFailure: onRequestFailure
- });
- }); // When this returned promise resolves, the request will go out.
-
- return previousObtainedIdentityPromise.then(function () {
- logger.info("Resuming previously delayed request.");
- request.setIsIdentityEstablished();
- }) // If Konductor did not set the identity cookie on the previous
- // request, then awaitIdentityCookie will reject its promise.
- // Catch the rejection here and allow this request to go out.
- .catch(function () {
- return allowRequestToGoWithoutIdentity(request);
- });
- } // For Alloy+Konductor communication to be as robust as possible and
- // to ensure we don't mint new ECIDs for requests that would otherwise
- // be sent in parallel, we'll let this request go out to fetch the
- // cookie
-
-
- obtainedIdentityPromise = awaitIdentityCookie({
- onResponse: onResponse,
- onRequestFailure: onRequestFailure
- });
- return allowRequestToGoWithoutIdentity(request);
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var ecidNamespace = "ECID";
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var addEcidQueryToPayload = (function (payload) {
- payload.mergeQuery({
- identity: {
- fetch: [ecidNamespace]
- }
- });
- });
-
- var matchUserAgent = function matchUserAgent(regexs) {
- return function (userAgent) {
- var keys = Object.keys(regexs);
-
- for (var i = 0; i < keys.length; i += 1) {
- var key = keys[i];
- var regex = regexs[key];
-
- if (regex.test(userAgent)) {
- return key;
- }
- }
-
- return UNKNOWN;
- };
- };
-
- var getBrowser = memoize(function (window) {
- var _matchUserAgent;
-
- return matchUserAgent((_matchUserAgent = {}, _defineProperty(_matchUserAgent, EDGE$1, /Edge\/([0-9\._]+)/), _defineProperty(_matchUserAgent, EDGE_CHROMIUM, /Edg\/([0-9\.]+)/), _defineProperty(_matchUserAgent, CHROME, /(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/), _defineProperty(_matchUserAgent, FIREFOX, /Firefox\/([0-9\.]+)(?:\s|$)/), _defineProperty(_matchUserAgent, IE, /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/), _defineProperty(_matchUserAgent, SAFARI, /Version\/([0-9\._]+).*Safari/), _matchUserAgent))(window.navigator.userAgent);
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectSetDomainForInitialIdentityPayload = (function (_ref) {
- var thirdPartyCookiesEnabled = _ref.thirdPartyCookiesEnabled,
- areThirdPartyCookiesSupportedByDefault = _ref.areThirdPartyCookiesSupportedByDefault;
- return function (request) {
- if (thirdPartyCookiesEnabled && areThirdPartyCookiesSupportedByDefault(getBrowser(window))) {
- // If third-party cookies are enabled by the customer and
- // supported by the browser, we will send the request to a
- // a third-party identification domain that allows for more accurate
- // identification of the user through use of a third-party cookie.
- // If we have an identity to migrate, we still want to hit the
- // third-party identification domain because the third-party identification
- // domain will use our ECID to set the third-party cookie if the third-party
- // cookie isn't already set, which provides for better cross-domain
- // identification for future requests.
- request.setUseIdThirdPartyDomain();
- }
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectAddLegacyEcidToPayload = (function (_ref) {
- var getLegacyEcid = _ref.getLegacyEcid,
- addEcidToPayload = _ref.addEcidToPayload;
- return function (payload) {
- if (payload.hasIdentity(ecidNamespace)) {
- // don't get the legacy identity if we already have the query string identity or if
- // the user specified it in the identity map
- return Promise.resolve();
- }
-
- return getLegacyEcid().then(function (ecidToMigrate) {
- if (ecidToMigrate) {
- addEcidToPayload(payload, ecidToMigrate);
- }
- });
- };
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var queryStringIdentityParam = "adobe_mc";
-
- var LINK_TTL_SECONDS = 300; // 5 minute link time to live
-
- var injectAddQueryStringIdentityToPayload = (function (_ref) {
- var locationSearch = _ref.locationSearch,
- dateProvider = _ref.dateProvider,
- orgId = _ref.orgId,
- logger = _ref.logger;
- return function (payload) {
- if (payload.hasIdentity(ecidNamespace)) {
- // don't overwrite a user provided ecid identity
- return;
- }
-
- var parsedQueryString = reactorQueryString.parse(locationSearch);
- var queryStringValue = parsedQueryString[queryStringIdentityParam];
-
- if (queryStringValue === undefined) {
- return;
- }
-
- var properties = queryStringValue.split("|").reduce(function (memo, keyValue) {
- var _keyValue$split = keyValue.split("="),
- _keyValue$split2 = _slicedToArray(_keyValue$split, 2),
- key = _keyValue$split2[0],
- value = _keyValue$split2[1];
-
- memo[key] = value;
- return memo;
- }, {}); // We are using MCMID and MCORGID to be compatible with Visitor.
-
- var ts = parseInt(properties.TS, 10);
- var mcmid = properties.MCMID;
- var mcorgid = decodeURIComponent(properties.MCORGID);
-
- if ( // When TS is not specified or not a number, the following inequality returns false.
- // All inequalities with NaN variables are false.
- dateProvider().getTime() / 1000 <= ts + LINK_TTL_SECONDS && mcorgid === orgId && mcmid) {
- logger.info("Found valid ECID identity " + mcmid + " from the adobe_mc query string parameter.");
- payload.addIdentity(ecidNamespace, {
- id: mcmid
- });
- } else {
- logger.info("Detected invalid or expired adobe_mc query string parameter.");
- }
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var addEcidToPayload = (function (payload, ecid) {
- payload.addIdentity(ecidNamespace, {
- id: ecid
- });
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectAwaitIdentityCookie = (function (_ref) {
- var doesIdentityCookieExist = _ref.doesIdentityCookieExist,
- orgId = _ref.orgId;
-
- /**
- * Returns a promise that will be resolved once an identity cookie exists.
- * If an identity cookie doesn't already exist, it should always exist after
- * the first response.
- */
- return function (_ref2) {
- var onResponse = _ref2.onResponse,
- onRequestFailure = _ref2.onRequestFailure;
- return new Promise(function (resolve, reject) {
- onResponse(function () {
- if (doesIdentityCookieExist()) {
- resolve();
- } else {
- // This logic assumes that the code setting the cookie is working as expected and that
- // the cookie was missing from the response.
- var noIdentityCookieError = new Error("An identity was not set properly. Please verify that the org ID " + orgId + " configured in Alloy matches the org ID specified in the edge configuration."); // Rejecting the promise will reject commands that were queued
- // by the Identity component while waiting on the response to
- // the initial request.
-
- reject(noIdentityCookieError); // Throwing an error will reject the event command that initiated
- // the request.
-
- throw noIdentityCookieError;
- }
- });
- onRequestFailure(function () {
- if (doesIdentityCookieExist()) {
- resolve();
- } else {
- // The error from the request failure will be logged separately. Rejecting this here
- // will tell ensureSingleIdentity to send the next request without identity
- reject(new Error("No identity was set on response."));
- }
- });
- });
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var getEcidFromResponse = (function (response) {
- var identityResultPayloads = response.getPayloadsByType("identity:result");
- var ecidPayload = find(identityResultPayloads, function (payload) {
- return payload.namespace && payload.namespace.code === ecidNamespace;
- });
- return ecidPayload ? ecidPayload.id : undefined;
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createGetIdentity = (function (_ref) {
- var sendEdgeNetworkRequest = _ref.sendEdgeNetworkRequest,
- createIdentityRequestPayload = _ref.createIdentityRequestPayload,
- createIdentityRequest = _ref.createIdentityRequest,
- globalConfigOverrides = _ref.globalConfigOverrides;
- return function () {
- var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
- namespaces = _ref2.namespaces,
- localConfigOverrides = _ref2.edgeConfigOverrides;
-
- var payload = createIdentityRequestPayload(namespaces);
- var request = createIdentityRequest(payload); // merge the configurations, but give preference to the command-local configs
-
- payload.mergeConfigOverride(globalConfigOverrides);
- payload.mergeConfigOverride(localConfigOverrides);
- return sendEdgeNetworkRequest({
- request: request
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createAddIdentity = (function (content) {
- return function (namespaceCode, identity) {
- content.xdm = content.xdm || {};
- content.xdm.identityMap = content.xdm.identityMap || {};
- content.xdm.identityMap[namespaceCode] = content.xdm.identityMap[namespaceCode] || [];
- content.xdm.identityMap[namespaceCode].push(identity);
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var createRequest = (function (options) {
- var payload = options.payload,
- _getAction = options.getAction,
- _getUseSendBeacon = options.getUseSendBeacon;
- var id = v4_1();
- var shouldUseThirdPartyDomain = false;
- var isIdentityEstablished = false;
- return {
- getId: function getId() {
- return id;
- },
- getPayload: function getPayload() {
- return payload;
- },
- getAction: function getAction() {
- return _getAction({
- isIdentityEstablished: isIdentityEstablished
- });
- },
- getUseSendBeacon: function getUseSendBeacon() {
- return _getUseSendBeacon({
- isIdentityEstablished: isIdentityEstablished
- });
- },
- getUseIdThirdPartyDomain: function getUseIdThirdPartyDomain() {
- return shouldUseThirdPartyDomain;
- },
- setUseIdThirdPartyDomain: function setUseIdThirdPartyDomain() {
- shouldUseThirdPartyDomain = true;
- },
- setIsIdentityEstablished: function setIsIdentityEstablished() {
- isIdentityEstablished = true;
- }
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createDataCollectionRequest = (function (dataCollectionRequestPayload) {
- var getUseSendBeacon = function getUseSendBeacon(_ref) {
- var isIdentityEstablished = _ref.isIdentityEstablished;
- // When the document may be unloading, we still hit the interact endpoint
- // using fetch if an identity has not been established. If we were instead
- // to hit the collect endpoint using sendBeacon in this case, one of three
- // things would occur:
- //
- // 1. The document ultimately isn't unloaded and Alloy receives an empty
- // response back from the collect endpoint, resulting in an error being
- // thrown by Alloy because we weren't able to establish an identity.
- // This is bad.
- // 2. The document is unloaded, but Alloy receives the empty
- // response back from the collect endpoint before navigation is completed,
- // resulting in an error being thrown by Alloy because we weren't able to
- // establish an identity. This is bad.
- // 3. The document is unloaded and Alloy does not receive the empty response
- // back from the collect endpoint before navigation is completed. No error
- // will be thrown, but no identity was established either. This is okay,
- // though no identity was established.
- //
- // By hitting the interact endpoint using fetch, one of the three things
- // would occur:
- //
- // 1. The document ultimately isn't unloaded and Alloy receives a
- // response with an identity back from the interact endpoint. No
- // error will be thrown and an identity is established. This is good.
- // 2. The document is unloaded and Alloy receives a response with an
- // identity back from the interact endpoint before navigation is completed.
- // No error will be thrown and an identity is established. This is good.
- // 3. The document is unloaded and Alloy does not receive the empty response
- // back from the collect endpoint before navigation is completed. In this
- // case, no error is thrown, but no identity was established and it's
- // more likely that the request never makes it to the server because we're
- // using fetch instead of sendBeacon.
- //
- // The second approach seemed preferable.
- return dataCollectionRequestPayload.getDocumentMayUnload() && isIdentityEstablished;
- };
-
- return createRequest({
- payload: dataCollectionRequestPayload,
- getAction: function getAction(_ref2) {
- var isIdentityEstablished = _ref2.isIdentityEstablished;
- return getUseSendBeacon({
- isIdentityEstablished: isIdentityEstablished
- }) ? "collect" : "interact";
- },
- getUseSendBeacon: getUseSendBeacon
- });
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- // request payloads share.
-
- var createRequestPayload = (function (options) {
- var content = options.content,
- addIdentity = options.addIdentity,
- hasIdentity = options.hasIdentity;
-
- var _mergeConfigOverride = createMerger(content, "meta.configOverrides");
-
- return {
- mergeMeta: createMerger(content, "meta"),
- mergeState: createMerger(content, "meta.state"),
- mergeQuery: createMerger(content, "query"),
- mergeConfigOverride: function mergeConfigOverride(updates) {
- return _mergeConfigOverride(prepareConfigOverridesForEdge(updates));
- },
- addIdentity: addIdentity,
- hasIdentity: hasIdentity,
- toJSON: function toJSON() {
- return content;
- }
- };
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createHasIdentity = (function (content) {
- return function (namespaceCode) {
- return (content.xdm && content.xdm.identityMap && content.xdm.identityMap[namespaceCode]) !== undefined;
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createDataCollectionRequestPayload = (function () {
- var content = {};
- var payload = createRequestPayload({
- content: content,
- addIdentity: createAddIdentity(content),
- hasIdentity: createHasIdentity(content)
- });
-
- payload.addEvent = function (event) {
- content.events = content.events || [];
- content.events.push(event);
- };
-
- payload.getDocumentMayUnload = function () {
- return (content.events || []).some(function (event) {
- return event.getDocumentMayUnload();
- });
- };
-
- return payload;
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var ASSURANCE_VALIDATION_SESSION_URL_PARAM = "adb_validation_sessionid";
- var ASSURANCE_VALIDATION_NAMESPACE = "validation.";
- var CLIENT_ID = "clientId";
-
- var getOrCreateAssuranceClientId = function getOrCreateAssuranceClientId(storage) {
- var clientId = storage.persistent.getItem(CLIENT_ID);
-
- if (!clientId) {
- clientId = v4_1();
- storage.persistent.setItem(CLIENT_ID, clientId);
- }
-
- return clientId;
- };
-
- var createGetAssuranceValidationTokenParams = (function (_ref) {
- var window = _ref.window,
- createNamespacedStorage = _ref.createNamespacedStorage;
- var storage = createNamespacedStorage(ASSURANCE_VALIDATION_NAMESPACE);
- return function () {
- var parsedQuery = reactorQueryString.parse(window.location.search);
- var validationSessionId = parsedQuery[ASSURANCE_VALIDATION_SESSION_URL_PARAM];
-
- if (!validationSessionId) {
- return "";
- }
-
- var clientId = getOrCreateAssuranceClientId(storage);
- var validationToken = validationSessionId + "|" + clientId;
- return "&" + reactorQueryString.stringify({
- adobeAepValidationToken: validationToken
- });
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createIdentityRequest = (function (identityRequestPayload) {
- return createRequest({
- payload: identityRequestPayload,
- getAction: function getAction() {
- return "identity/acquire";
- },
- getUseSendBeacon: function getUseSendBeacon() {
- return false;
- }
- });
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createIdentityRequestPayload = (function (namespaces) {
- var content = {
- query: {
- identity: {
- fetch: namespaces
- }
- }
- };
- return createRequestPayload({
- content: content,
- addIdentity: createAddIdentity(content),
- hasIdentity: createHasIdentity(content)
- });
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var URL_REGEX = /^([^?#]*)(\??[^#]*)(#?.*)$/;
-
- var getSeparator = function getSeparator(queryString) {
- if (queryString === "") {
- return "?";
- }
-
- if (queryString === "?") {
- return "";
- }
-
- return "&";
- };
-
- var injectAppendIdentityToUrl = (function (_ref) {
- var dateProvider = _ref.dateProvider,
- orgId = _ref.orgId;
- return function (ecid, url) {
- var ts = Math.round(dateProvider().getTime() / 1000);
- var adobemc = encodeURIComponent("TS=" + ts + "|MCMID=" + ecid + "|MCORGID=" + encodeURIComponent(orgId));
-
- var _url$match = url.match(URL_REGEX),
- _url$match2 = _slicedToArray(_url$match, 4),
- location = _url$match2[1],
- queryString = _url$match2[2],
- fragment = _url$match2[3];
-
- var separator = getSeparator(queryString);
- return "" + location + queryString + separator + "adobe_mc=" + adobemc + fragment;
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var createIdentity = function createIdentity(_ref) {
- var config = _ref.config,
- logger = _ref.logger,
- consent = _ref.consent,
- fireReferrerHideableImage = _ref.fireReferrerHideableImage,
- sendEdgeNetworkRequest = _ref.sendEdgeNetworkRequest,
- apexDomain = _ref.apexDomain;
- var orgId = config.orgId,
- thirdPartyCookiesEnabled = config.thirdPartyCookiesEnabled,
- globalConfigOverrides = config.edgeConfigOverrides;
- var getEcidFromVisitor = injectGetEcidFromVisitor({
- logger: logger,
- orgId: orgId,
- awaitVisitorOptIn: awaitVisitorOptIn
- });
- var loggingCookieJar = createLoggingCookieJar({
- logger: logger,
- cookieJar: cookieJar
- });
- var legacyIdentity = createLegacyIdentity({
- config: config,
- getEcidFromVisitor: getEcidFromVisitor,
- apexDomain: apexDomain,
- cookieJar: loggingCookieJar,
- isPageSsl: window.location.protocol === "https:"
- });
- var doesIdentityCookieExist = injectDoesIdentityCookieExist({
- orgId: orgId
- });
- var getIdentity = createGetIdentity({
- sendEdgeNetworkRequest: sendEdgeNetworkRequest,
- createIdentityRequestPayload: createIdentityRequestPayload,
- createIdentityRequest: createIdentityRequest,
- globalConfigOverrides: globalConfigOverrides
- });
- var setDomainForInitialIdentityPayload = injectSetDomainForInitialIdentityPayload({
- thirdPartyCookiesEnabled: thirdPartyCookiesEnabled,
- areThirdPartyCookiesSupportedByDefault: areThirdPartyCookiesSupportedByDefault
- });
- var addLegacyEcidToPayload = injectAddLegacyEcidToPayload({
- getLegacyEcid: legacyIdentity.getEcid,
- addEcidToPayload: addEcidToPayload
- });
- var addQueryStringIdentityToPayload = injectAddQueryStringIdentityToPayload({
- locationSearch: window.document.location.search,
- dateProvider: function dateProvider() {
- return new Date();
- },
- orgId: orgId,
- logger: logger
- });
- var awaitIdentityCookie = injectAwaitIdentityCookie({
- doesIdentityCookieExist: doesIdentityCookieExist,
- orgId: orgId
- });
- var ensureSingleIdentity = injectEnsureSingleIdentity({
- doesIdentityCookieExist: doesIdentityCookieExist,
- setDomainForInitialIdentityPayload: setDomainForInitialIdentityPayload,
- addLegacyEcidToPayload: addLegacyEcidToPayload,
- awaitIdentityCookie: awaitIdentityCookie,
- logger: logger
- });
- var processIdSyncs = injectProcessIdSyncs({
- fireReferrerHideableImage: fireReferrerHideableImage,
- logger: logger
- });
- var handleResponseForIdSyncs = injectHandleResponseForIdSyncs({
- processIdSyncs: processIdSyncs
- });
- var appendIdentityToUrl = injectAppendIdentityToUrl({
- dateProvider: function dateProvider() {
- return new Date();
- },
- orgId: orgId,
- globalConfigOverrides: globalConfigOverrides
- });
- return createComponent$4({
- addEcidQueryToPayload: addEcidQueryToPayload,
- addQueryStringIdentityToPayload: addQueryStringIdentityToPayload,
- ensureSingleIdentity: ensureSingleIdentity,
- setLegacyEcid: legacyIdentity.setEcid,
- handleResponseForIdSyncs: handleResponseForIdSyncs,
- getEcidFromResponse: getEcidFromResponse,
- getIdentity: getIdentity,
- consent: consent,
- appendIdentityToUrl: appendIdentityToUrl,
- logger: logger,
- config: config
- });
- };
-
- createIdentity.namespace = "Identity";
- createIdentity.configValidators = configValidators;
-
- var createResultLogMessage = function createResultLogMessage(urlDestination, success) {
- return "URL destination " + (success ? "succeeded" : "failed") + ": " + urlDestination.spec.url;
- };
-
- var injectProcessDestinations = (function (_ref) {
- var fireReferrerHideableImage = _ref.fireReferrerHideableImage,
- logger = _ref.logger,
- cookieJar = _ref.cookieJar,
- isPageSsl = _ref.isPageSsl;
- var extraCookieOptions = isPageSsl ? {
- sameSite: "none",
- secure: true
- } : {};
-
- var processCookies = function processCookies(destinations) {
- var cookieDestinations = destinations.filter(function (dest) {
- return dest.type === "cookie";
- });
- cookieDestinations.forEach(function (dest) {
- var _dest$spec = dest.spec,
- name = _dest$spec.name,
- value = _dest$spec.value,
- domain = _dest$spec.domain,
- ttlDays = _dest$spec.ttlDays;
- cookieJar.set(name, value || "", _objectSpread2({
- domain: domain || "",
- expires: ttlDays || 10
- }, extraCookieOptions));
- });
- };
-
- var processUrls = function processUrls(destinations) {
- var urlDestinations = destinations.filter(function (dest) {
- return dest.type === "url";
- });
- return Promise.all(urlDestinations.map(function (urlDestination) {
- return fireReferrerHideableImage(urlDestination.spec).then(function () {
- logger.info(createResultLogMessage(urlDestination, true));
- }).catch(function () {// We intentionally do not throw an error if destinations fail. We
- // consider it a non-critical failure and therefore do not want it to
- // reject the promise handed back to the customer.
- });
- })).then(noop$1);
- };
-
- return function (destinations) {
- processCookies(destinations);
- return processUrls(destinations);
- };
- });
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectProcessResponse = (function (_ref) {
- var processDestinations = _ref.processDestinations;
-
- var processPushDestinations = function processPushDestinations(_ref2) {
- var response = _ref2.response;
- var destinations = response.getPayloadsByType("activation:push");
- return processDestinations(destinations);
- };
-
- var retrievePullDestinations = function retrievePullDestinations(_ref3) {
- var response = _ref3.response;
- return {
- destinations: response.getPayloadsByType("activation:pull")
- };
- };
-
- return function (_ref4) {
- var response = _ref4.response;
- return processPushDestinations({
- response: response
- }).then(function () {
- return retrievePullDestinations({
- response: response
- });
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var createAudiences = function createAudiences(_ref) {
- var logger = _ref.logger,
- fireReferrerHideableImage = _ref.fireReferrerHideableImage;
- // we override the js-cookie converter to encode the cookie value similar on how it is in DIL (PDCL-10238)
- var cookieJarWithEncoding = cookieJar.withConverter({
- write: function write(value) {
- return encodeURIComponent(value);
- }
- });
- var loggingCookieJar = createLoggingCookieJar({
- logger: logger,
- cookieJar: cookieJarWithEncoding
- });
- var processDestinations = injectProcessDestinations({
- fireReferrerHideableImage: fireReferrerHideableImage,
- logger: logger,
- cookieJar: loggingCookieJar,
- isPageSsl: window.location.protocol === "https:"
- });
- var processResponse = injectProcessResponse({
- processDestinations: processDestinations
- });
- return {
- lifecycle: {
- onResponse: processResponse
- },
- commands: {}
- };
- };
-
- createAudiences.namespace = "Audiences";
- createAudiences.configValidators = {};
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var WEB = "web";
- var WEBAPP = "webapp";
- var SURFACE_TYPE_DELIMITER = "://";
- var FRAGMENT_DELIMITER = "#";
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var SURFACE_REGEX = /^(\w+):\/\/([^/#]+)(\/[^#]*)?(#.*)?$/;
- var AUTHORITY_REGEX = /^(?:.*@)?(?:[a-z\d\u00a1-\uffff.-]+|\[[a-f\d:]+])(?::\d+)?$/;
- var PATH_REGEX = /^\/(?:[/\w\u00a1-\uffff-.~]|%[a-fA-F\d]{2})*$/;
- var FRAGMENT_REGEX = /^#(?:[/\w\u00a1-\uffff-.~]|%[a-fA-F\d]{2})+$/;
-
- var normalizePath = function normalizePath() {
- var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "/";
- var end = path.length;
-
- while (end > 0 && "/".indexOf(path.charAt(end - 1)) !== -1) {
- end -= 1;
- }
-
- return path.substring(0, end) || "/";
- };
-
- var getSurfaceType = function getSurfaceType(surfaceTypeMatch) {
- return isNonEmptyString(surfaceTypeMatch) ? surfaceTypeMatch.toLowerCase() : "";
- };
-
- var getAuthority = function getAuthority(authorityMatch) {
- return isNonEmptyString(authorityMatch) ? authorityMatch.toLowerCase() : "";
- };
-
- var getPath = function getPath(pathMatch) {
- return isNonEmptyString(pathMatch) ? normalizePath(pathMatch) : "/";
- };
-
- var parseSurface = function parseSurface(surfaceString) {
- var matched = surfaceString.match(SURFACE_REGEX);
- return matched ? {
- surfaceType: getSurfaceType(matched[1]),
- authority: getAuthority(matched[2]),
- path: getPath(matched[3]),
- fragment: matched[4]
- } : null;
- };
-
- var stringifySurface = function stringifySurface(surface) {
- return "" + surface.surfaceType + SURFACE_TYPE_DELIMITER + surface.authority + (surface.path || "") + (surface.fragment || "");
- };
-
- var buildPageSurface = function buildPageSurface(getPageLocation) {
- var location = getPageLocation();
- var host = location.host.toLowerCase();
- var path = location.pathname;
- return WEB + SURFACE_TYPE_DELIMITER + host + normalizePath(path);
- };
-
- var expandFragmentSurface = function expandFragmentSurface(surface, getPageLocation) {
- return startsWith(surface, FRAGMENT_DELIMITER) ? buildPageSurface(getPageLocation) + surface : surface;
- };
-
- var validateSurface = function validateSurface(surface, getPageLocation, logger) {
- var invalidateSurface = function invalidateSurface(validationError) {
- logger.warn(validationError);
- return null;
- };
-
- if (!isNonEmptyString(surface)) {
- return invalidateSurface("Invalid surface: " + surface);
- }
-
- var expanded = expandFragmentSurface(surface, getPageLocation);
- var parsed = parseSurface(expanded);
-
- if (parsed === null) {
- return invalidateSurface("Invalid surface: " + surface);
- }
-
- if (!includes([WEB, WEBAPP], parsed.surfaceType)) {
- return invalidateSurface("Unsupported surface type " + parsed.surfaceType + " in surface: " + surface);
- }
-
- if (!parsed.authority || !AUTHORITY_REGEX.test(parsed.authority)) {
- return invalidateSurface("Invalid authority " + parsed.authority + " in surface: " + surface);
- }
-
- if (parsed.path && !PATH_REGEX.test(parsed.path)) {
- return invalidateSurface("Invalid path " + parsed.path + " in surface: " + surface);
- }
-
- if (parsed.fragment && !FRAGMENT_REGEX.test(parsed.fragment)) {
- return invalidateSurface("Invalid fragment " + parsed.fragment + " in surface: " + surface);
- }
-
- return parsed;
- };
-
- var isPageWideSurface = function isPageWideSurface(scope) {
- return !!scope && scope.indexOf(WEB + SURFACE_TYPE_DELIMITER) === 0 && scope.indexOf(FRAGMENT_DELIMITER) === -1;
- };
- var normalizeSurfaces = function normalizeSurfaces() {
- var surfaces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
- var getPageLocation = arguments.length > 1 ? arguments[1] : undefined;
- var logger = arguments.length > 2 ? arguments[2] : undefined;
- return surfaces.map(function (surface) {
- return validateSurface(surface, getPageLocation, logger);
- }).filter(function (surface) {
- return !isNil(surface);
- }).map(stringifySurface);
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var PAGE_WIDE_SCOPE = "__view__";
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var DEFAULT_CONTENT_ITEM = "https://ns.adobe.com/personalization/default-content-item";
- var DOM_ACTION = "https://ns.adobe.com/personalization/dom-action";
- var HTML_CONTENT_ITEM = "https://ns.adobe.com/personalization/html-content-item";
- var JSON_CONTENT_ITEM = "https://ns.adobe.com/personalization/json-content-item";
- var REDIRECT_ITEM = "https://ns.adobe.com/personalization/redirect-item";
- var MEASUREMENT_SCHEMA = "https://ns.adobe.com/personalization/measurement";
-
- var addPageWideScope = function addPageWideScope(scopes) {
- if (!includes(scopes, PAGE_WIDE_SCOPE)) {
- scopes.push(PAGE_WIDE_SCOPE);
- }
- };
-
- var addPageSurface = function addPageSurface(surfaces, getPageLocation) {
- var pageSurface = buildPageSurface(getPageLocation);
-
- if (!includes(surfaces, pageSurface)) {
- surfaces.push(pageSurface);
- }
- };
-
- var dedupe = function dedupe(array) {
- return array.filter(function (item, pos) {
- return array.indexOf(item) === pos;
- });
- };
-
- var createPersonalizationDetails = (function (_ref) {
- var getPageLocation = _ref.getPageLocation,
- renderDecisions = _ref.renderDecisions,
- decisionScopes = _ref.decisionScopes,
- personalization = _ref.personalization,
- event = _ref.event,
- viewCache = _ref.viewCache,
- logger = _ref.logger;
- var viewName = event.getViewName();
- return {
- isRenderDecisions: function isRenderDecisions() {
- return renderDecisions;
- },
- getViewName: function getViewName() {
- return viewName;
- },
- hasScopes: function hasScopes() {
- return decisionScopes.length > 0 || isNonEmptyArray(personalization.decisionScopes);
- },
- hasSurfaces: function hasSurfaces() {
- return isNonEmptyArray(personalization.surfaces);
- },
- hasViewName: function hasViewName() {
- return isNonEmptyString(viewName);
- },
- createQueryDetails: function createQueryDetails() {
- var scopes = _toConsumableArray(decisionScopes);
-
- if (isNonEmptyArray(personalization.decisionScopes)) {
- scopes.push.apply(scopes, _toConsumableArray(personalization.decisionScopes));
- }
-
- var eventSurfaces = normalizeSurfaces(personalization.surfaces, getPageLocation, logger);
-
- if (!this.isCacheInitialized()) {
- addPageWideScope(scopes);
- addPageSurface(eventSurfaces, getPageLocation);
- }
-
- var schemas = [DEFAULT_CONTENT_ITEM, HTML_CONTENT_ITEM, JSON_CONTENT_ITEM, REDIRECT_ITEM];
-
- if (includes(scopes, PAGE_WIDE_SCOPE)) {
- schemas.push(DOM_ACTION);
- }
-
- return {
- schemas: schemas,
- decisionScopes: dedupe(scopes),
- surfaces: dedupe(eventSurfaces)
- };
- },
- isCacheInitialized: function isCacheInitialized() {
- return viewCache.isInitialized();
- },
- shouldFetchData: function shouldFetchData() {
- return this.hasScopes() || this.hasSurfaces() || !this.isCacheInitialized();
- },
- shouldUseCachedData: function shouldUseCachedData() {
- return this.hasViewName() && this.isCacheInitialized();
- }
- };
- });
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var AUTHORING_ENABLED = "Rendering is disabled for authoring mode.";
- var REDIRECT_EXECUTION_ERROR = "An error occurred while executing the redirect offer.";
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var EMPTY_PROPOSITIONS = {
- propositions: []
- };
- var validateApplyPropositionsOptions = (function (_ref) {
- var logger = _ref.logger,
- options = _ref.options;
- var applyPropositionsOptionsValidator = boundObjectOf({
- propositions: boundArrayOf(boundObjectOf(boundAnything())).nonEmpty(),
- metadata: boundObjectOf(boundAnything())
- }).required();
-
- try {
- return applyPropositionsOptionsValidator(options);
- } catch (e) {
- logger.warn("Invalid options for applyPropositions. No propositions will be applied.", e);
- return EMPTY_PROPOSITIONS;
- }
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createComponent$3 = (function (_ref) {
- var getPageLocation = _ref.getPageLocation,
- logger = _ref.logger,
- fetchDataHandler = _ref.fetchDataHandler,
- viewChangeHandler = _ref.viewChangeHandler,
- onClickHandler = _ref.onClickHandler,
- isAuthoringModeEnabled = _ref.isAuthoringModeEnabled,
- mergeQuery = _ref.mergeQuery,
- viewCache = _ref.viewCache,
- showContainers = _ref.showContainers,
- applyPropositions = _ref.applyPropositions,
- setTargetMigration = _ref.setTargetMigration;
- return {
- lifecycle: {
- onBeforeRequest: function onBeforeRequest(_ref2) {
- var request = _ref2.request;
- setTargetMigration(request);
- return Promise.resolve();
- },
- onBeforeEvent: function onBeforeEvent(_ref3) {
- var event = _ref3.event,
- renderDecisions = _ref3.renderDecisions,
- _ref3$decisionScopes = _ref3.decisionScopes,
- decisionScopes = _ref3$decisionScopes === void 0 ? [] : _ref3$decisionScopes,
- _ref3$personalization = _ref3.personalization,
- personalization = _ref3$personalization === void 0 ? {} : _ref3$personalization,
- _ref3$onResponse = _ref3.onResponse,
- onResponse = _ref3$onResponse === void 0 ? noop$1 : _ref3$onResponse,
- _ref3$onRequestFailur = _ref3.onRequestFailure,
- onRequestFailure = _ref3$onRequestFailur === void 0 ? noop$1 : _ref3$onRequestFailur;
- // Include propositions on all responses, overridden with data as needed
- onResponse(function () {
- return {
- propositions: []
- };
- });
- onRequestFailure(function () {
- return showContainers();
- });
-
- if (isAuthoringModeEnabled()) {
- logger.warn(AUTHORING_ENABLED); // If we are in authoring mode we disable personalization
-
- mergeQuery(event, {
- enabled: false
- });
- return;
- }
-
- var personalizationDetails = createPersonalizationDetails({
- getPageLocation: getPageLocation,
- renderDecisions: renderDecisions,
- decisionScopes: decisionScopes,
- personalization: personalization,
- event: event,
- viewCache: viewCache,
- logger: logger
- });
-
- if (personalizationDetails.shouldFetchData()) {
- var decisionsDeferred = defer();
- viewCache.storeViews(decisionsDeferred.promise);
- onRequestFailure(function () {
- return decisionsDeferred.reject();
- });
- fetchDataHandler({
- decisionsDeferred: decisionsDeferred,
- personalizationDetails: personalizationDetails,
- event: event,
- onResponse: onResponse
- });
- return;
- }
-
- if (personalizationDetails.shouldUseCachedData()) {
- // eslint-disable-next-line consistent-return
- return viewChangeHandler({
- personalizationDetails: personalizationDetails,
- event: event,
- onResponse: onResponse,
- onRequestFailure: onRequestFailure
- });
- }
- },
- onClick: function onClick(_ref4) {
- var event = _ref4.event,
- clickedElement = _ref4.clickedElement;
- onClickHandler({
- event: event,
- clickedElement: clickedElement
- });
- }
- },
- commands: {
- applyPropositions: {
- optionsValidator: function optionsValidator(options) {
- return validateApplyPropositionsOptions({
- logger: logger,
- options: options
- });
- },
- run: applyPropositions
- }
- }
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createFragment = (function (content) {
- return createNode(DIV, {}, {
- innerHTML: content
- });
- });
-
- var css_escape = createCommonjsModule(function (module, exports) {
-
- (function (root, factory) {
- // https://github.com/umdjs/umd/blob/master/returnExports.js
- {
- // For Node.js.
- module.exports = factory(root);
- }
- })(typeof commonjsGlobal != 'undefined' ? commonjsGlobal : commonjsGlobal, function (root) {
- if (root.CSS && root.CSS.escape) {
- return root.CSS.escape;
- } // https://drafts.csswg.org/cssom/#serialize-an-identifier
-
-
- var cssEscape = function cssEscape(value) {
- if (arguments.length == 0) {
- throw new TypeError('`CSS.escape` requires an argument.');
- }
-
- var string = String(value);
- var length = string.length;
- var index = -1;
- var codeUnit;
- var result = '';
- var firstCodeUnit = string.charCodeAt(0);
-
- while (++index < length) {
- codeUnit = string.charCodeAt(index); // Note: there’s no need to special-case astral symbols, surrogate
- // pairs, or lone surrogates.
- // If the character is NULL (U+0000), then the REPLACEMENT CHARACTER
- // (U+FFFD).
-
- if (codeUnit == 0x0000) {
- result += "\uFFFD";
- continue;
- }
-
- if ( // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is
- // U+007F, […]
- codeUnit >= 0x0001 && codeUnit <= 0x001F || codeUnit == 0x007F || // If the character is the first character and is in the range [0-9]
- // (U+0030 to U+0039), […]
- index == 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039 || // If the character is the second character and is in the range [0-9]
- // (U+0030 to U+0039) and the first character is a `-` (U+002D), […]
- index == 1 && codeUnit >= 0x0030 && codeUnit <= 0x0039 && firstCodeUnit == 0x002D) {
- // https://drafts.csswg.org/cssom/#escape-a-character-as-code-point
- result += '\\' + codeUnit.toString(16) + ' ';
- continue;
- }
-
- if ( // If the character is the first character and is a `-` (U+002D), and
- // there is no second character, […]
- index == 0 && length == 1 && codeUnit == 0x002D) {
- result += '\\' + string.charAt(index);
- continue;
- } // If the character is not handled by one of the above rules and is
- // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or
- // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to
- // U+005A), or [a-z] (U+0061 to U+007A), […]
-
-
- if (codeUnit >= 0x0080 || codeUnit == 0x002D || codeUnit == 0x005F || codeUnit >= 0x0030 && codeUnit <= 0x0039 || codeUnit >= 0x0041 && codeUnit <= 0x005A || codeUnit >= 0x0061 && codeUnit <= 0x007A) {
- // the character itself
- result += string.charAt(index);
- continue;
- } // Otherwise, the escaped character.
- // https://drafts.csswg.org/cssom/#escape-a-character
-
-
- result += '\\' + string.charAt(index);
- }
-
- return result;
- };
-
- if (!root.CSS) {
- root.CSS = {};
- }
-
- root.CSS.escape = cssEscape;
- return cssEscape;
- });
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var EQ_START = ":eq(";
- var EQ_PATTERN = /:eq\((\d+)\)/g;
- var isNotEqSelector = function isNotEqSelector(str) {
- return str.indexOf(EQ_START) === -1;
- };
- var splitWithEq = function splitWithEq(selector) {
- return selector.split(EQ_PATTERN).filter(isNonEmptyString);
- };
-
- var CSS_IDENTIFIER_PATTERN = /(#|\.)(-?\w+)/g; // Here we use CSS.escape() to make sure we get
- // correct values for ID and CSS class
- // Please check: https://www.w3.org/TR/css-syntax-3/#escaping
- // CSS.escape() polyfill can be found here: https://github.com/mathiasbynens/CSS.escape
-
- var replaceIdentifier = function replaceIdentifier(_, $1, $2) {
- return "" + $1 + css_escape($2);
- };
-
- var escapeIdentifiersInSelector = function escapeIdentifiersInSelector(selector) {
- return selector.replace(CSS_IDENTIFIER_PATTERN, replaceIdentifier);
- };
- var parseSelector = function parseSelector(rawSelector) {
- var result = [];
- var selector = escapeIdentifiersInSelector(rawSelector.trim());
- var parts = splitWithEq(selector);
- var length = parts.length;
- var i = 0;
-
- while (i < length) {
- var sel = parts[i];
- var eq = parts[i + 1];
-
- if (eq) {
- result.push({
- sel: sel,
- eq: Number(eq)
- });
- } else {
- result.push({
- sel: sel
- });
- }
-
- i += 2;
- }
-
- return result;
- };
- /**
- * Returns an array of matched DOM nodes.
- * @param {String} selector that contains Sizzle "eq(...)" pseudo selector
- * @returns {Array} an array of DOM nodes
- */
-
- var selectNodesWithEq = function selectNodesWithEq(selector) {
- var doc = document;
-
- if (isNotEqSelector(selector)) {
- return selectNodes(selector, doc);
- }
-
- var parts = parseSelector(selector);
- var length = parts.length;
- var result = [];
- var context = doc;
- var i = 0;
-
- while (i < length) {
- var _parts$i = parts[i],
- sel = _parts$i.sel,
- eq = _parts$i.eq;
- var nodes = selectNodes(sel, context);
- var nodesCount = nodes.length;
-
- if (nodesCount === 0) {
- break;
- }
-
- if (eq != null && eq > nodesCount - 1) {
- break;
- }
-
- if (i < length - 1) {
- if (eq == null) {
- var _nodes = _slicedToArray(nodes, 1);
-
- context = _nodes[0];
- } else {
- context = nodes[eq];
- }
- }
-
- if (i === length - 1) {
- if (eq == null) {
- result = nodes;
- } else {
- result = [nodes[eq]];
- }
- }
-
- i += 1;
- }
-
- return result;
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Returns an array of matched DOM nodes.
- * @param {String} id
- * @param {Node} [context=document] defaults to document
- * @returns {HTMLElement} an element of null
- */
- var getElementById = (function (id) {
- var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document;
- return context.getElementById(id);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var setAttribute = (function (element, name, value) {
- element.setAttribute(name, value);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var getAttribute = (function (element, name) {
- return element.getAttribute(name);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var removeAttribute = (function (element, name) {
- element.removeAttribute(name);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var setStyle = (function (element, name, value, priority) {
- var css;
-
- if (priority) {
- css = name + ":" + value + " !" + priority + ";";
- } else {
- css = name + ":" + value + ";";
- }
-
- element.style.cssText += ";" + css;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var getParent = (function (element) {
- return element.parentNode;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var getNextSibling = (function (element) {
- return element.nextElementSibling;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var insertAfter = (function (container, element) {
- if (!container) {
- return;
- }
-
- var parent = getParent(container);
-
- if (parent) {
- parent.insertBefore(element, getNextSibling(container));
- }
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var insertBefore = (function (container, element) {
- if (!container) {
- return;
- }
-
- var parent = getParent(container);
-
- if (parent) {
- parent.insertBefore(element, container);
- }
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var getChildren = (function (element) {
- var children = element.children;
-
- if (children) {
- return toArray(children);
- }
-
- return [];
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var getChildNodes = (function (element) {
- var childNodes = element.childNodes;
-
- if (childNodes) {
- return toArray(childNodes);
- }
-
- return [];
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var getFirstChild = (function (element) {
- return element.firstElementChild;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var nonce;
- /**
- * Returns the nonce if available.
- * @param {Node} [context=document] defaults to document
- * @returns {(String|undefined)} the nonce or undefined if not available
- */
-
- var getNonce = (function () {
- var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;
-
- if (nonce === undefined) {
- var n = context.querySelector("[nonce]"); // NOTE: We're keeping n.getAttribute("nonce") until it is safe to remove:
- // ref: https://github.com/whatwg/html/issues/2369#issuecomment-280853946
-
- nonce = n && (n.nonce || n.getAttribute("nonce"));
- }
-
- return nonce;
- }); // This function is only used for testing and removed when library is built (tree-shaking)
-
- var PREHIDING_ID = "alloy-prehiding";
- var HIDING_STYLE_DEFINITION = "{ visibility: hidden }"; // Using global is OK since we have a single DOM
- // so storing nodes even for multiple Alloy instances is fine
-
- var styleNodes = {};
- var hideElements = function hideElements(prehidingSelector) {
- // if we have different events with the same
- // prehiding selector we don't want to recreate
- // the style tag
- if (styleNodes[prehidingSelector]) {
- return;
- }
-
- var nonce = getNonce();
-
- var attrs = _objectSpread2({}, nonce && {
- nonce: nonce
- });
-
- var props = {
- textContent: prehidingSelector + " " + HIDING_STYLE_DEFINITION
- };
- var node = createNode(STYLE, attrs, props);
- appendNode(document.head, node);
- styleNodes[prehidingSelector] = node;
- };
- var showElements = function showElements(prehidingSelector) {
- var node = styleNodes[prehidingSelector];
-
- if (node) {
- removeNode(node);
- delete styleNodes[prehidingSelector];
- }
- };
- var hideContainers = function hideContainers(prehidingStyle) {
- if (!prehidingStyle) {
- return;
- } // If containers prehiding style has been added
- // by customer's prehiding snippet we don't
- // want to add the same node
-
-
- var node = getElementById(PREHIDING_ID);
-
- if (node) {
- return;
- }
-
- var nonce = getNonce();
-
- var attrs = _objectSpread2({
- id: PREHIDING_ID
- }, nonce && {
- nonce: nonce
- });
-
- var props = {
- textContent: prehidingStyle
- };
- var styleNode = createNode(STYLE, attrs, props);
- appendNode(document.head, styleNode);
- };
- var showContainers = function showContainers() {
- // If containers prehiding style exists
- // we will remove it
- var node = getElementById(PREHIDING_ID);
-
- if (!node) {
- return;
- }
-
- removeNode(node);
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var setText = (function (container, text) {
- container.textContent = text;
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var SRC = "src";
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var isImage = function isImage(element) {
- return element.tagName === IMG;
- };
- var loadImage = function loadImage(url) {
- return createNode(IMG, {
- src: url
- });
- };
- var loadImages = function loadImages(fragment) {
- var images = selectNodes(IMG, fragment);
- images.forEach(function (image) {
- var url = getAttribute(image, SRC);
-
- if (url) {
- loadImage(url);
- }
- });
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var is$1 = function is(element, tagName) {
- return element.tagName === tagName;
- };
-
- var isInlineStyleElement = function isInlineStyleElement(element) {
- return is$1(element, STYLE) && !getAttribute(element, SRC);
- };
-
- var addNonceToInlineStyleElements = (function (fragment) {
- var styleNodes = selectNodes(STYLE, fragment);
- var length = styleNodes.length;
- var nonce = getNonce();
-
- if (!nonce) {
- return;
- }
- /* eslint-disable no-continue */
-
-
- for (var i = 0; i < length; i += 1) {
- var element = styleNodes[i];
-
- if (!isInlineStyleElement(element)) {
- continue;
- }
-
- element.nonce = nonce;
- }
- });
-
- /**
- * @this {Promise}
- */
- function finallyConstructor(callback) {
- var constructor = this.constructor;
- return this.then(function (value) {
- // @ts-ignore
- return constructor.resolve(callback()).then(function () {
- return value;
- });
- }, function (reason) {
- // @ts-ignore
- return constructor.resolve(callback()).then(function () {
- // @ts-ignore
- return constructor.reject(reason);
- });
- });
- }
-
- // other code modifying setTimeout (like sinon.useFakeTimers())
-
- var setTimeoutFunc = setTimeout;
-
- function isArray(x) {
- return Boolean(x && typeof x.length !== 'undefined');
- }
-
- function noop() {} // Polyfill for Function.prototype.bind
-
-
- function bind(fn, thisArg) {
- return function () {
- fn.apply(thisArg, arguments);
- };
- }
- /**
- * @constructor
- * @param {Function} fn
- */
-
-
- function Promise$1(fn) {
- if (!(this instanceof Promise$1)) throw new TypeError('Promises must be constructed via new');
- if (typeof fn !== 'function') throw new TypeError('not a function');
- /** @type {!number} */
-
- this._state = 0;
- /** @type {!boolean} */
-
- this._handled = false;
- /** @type {Promise|undefined} */
-
- this._value = undefined;
- /** @type {!Array} */
-
- this._deferreds = [];
- doResolve(fn, this);
- }
-
- function handle(self, deferred) {
- while (self._state === 3) {
- self = self._value;
- }
-
- if (self._state === 0) {
- self._deferreds.push(deferred);
-
- return;
- }
-
- self._handled = true;
-
- Promise$1._immediateFn(function () {
- var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
-
- if (cb === null) {
- (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
- return;
- }
-
- var ret;
-
- try {
- ret = cb(self._value);
- } catch (e) {
- reject(deferred.promise, e);
- return;
- }
-
- resolve(deferred.promise, ret);
- });
- }
-
- function resolve(self, newValue) {
- try {
- // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
- if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');
-
- if (newValue && (_typeof(newValue) === 'object' || typeof newValue === 'function')) {
- var then = newValue.then;
-
- if (newValue instanceof Promise$1) {
- self._state = 3;
- self._value = newValue;
- finale(self);
- return;
- } else if (typeof then === 'function') {
- doResolve(bind(then, newValue), self);
- return;
- }
- }
-
- self._state = 1;
- self._value = newValue;
- finale(self);
- } catch (e) {
- reject(self, e);
- }
- }
-
- function reject(self, newValue) {
- self._state = 2;
- self._value = newValue;
- finale(self);
- }
-
- function finale(self) {
- if (self._state === 2 && self._deferreds.length === 0) {
- Promise$1._immediateFn(function () {
- if (!self._handled) {
- Promise$1._unhandledRejectionFn(self._value);
- }
- });
- }
-
- for (var i = 0, len = self._deferreds.length; i < len; i++) {
- handle(self, self._deferreds[i]);
- }
-
- self._deferreds = null;
- }
- /**
- * @constructor
- */
-
-
- function Handler(onFulfilled, onRejected, promise) {
- this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
- this.onRejected = typeof onRejected === 'function' ? onRejected : null;
- this.promise = promise;
- }
- /**
- * Take a potentially misbehaving resolver function and make sure
- * onFulfilled and onRejected are only called once.
- *
- * Makes no guarantees about asynchrony.
- */
-
-
- function doResolve(fn, self) {
- var done = false;
-
- try {
- fn(function (value) {
- if (done) return;
- done = true;
- resolve(self, value);
- }, function (reason) {
- if (done) return;
- done = true;
- reject(self, reason);
- });
- } catch (ex) {
- if (done) return;
- done = true;
- reject(self, ex);
- }
- }
-
- Promise$1.prototype['catch'] = function (onRejected) {
- return this.then(null, onRejected);
- };
-
- Promise$1.prototype.then = function (onFulfilled, onRejected) {
- // @ts-ignore
- var prom = new this.constructor(noop);
- handle(this, new Handler(onFulfilled, onRejected, prom));
- return prom;
- };
-
- Promise$1.prototype['finally'] = finallyConstructor;
-
- Promise$1.all = function (arr) {
- return new Promise$1(function (resolve, reject) {
- if (!isArray(arr)) {
- return reject(new TypeError('Promise.all accepts an array'));
- }
-
- var args = Array.prototype.slice.call(arr);
- if (args.length === 0) return resolve([]);
- var remaining = args.length;
-
- function res(i, val) {
- try {
- if (val && (_typeof(val) === 'object' || typeof val === 'function')) {
- var then = val.then;
-
- if (typeof then === 'function') {
- then.call(val, function (val) {
- res(i, val);
- }, reject);
- return;
- }
- }
-
- args[i] = val;
-
- if (--remaining === 0) {
- resolve(args);
- }
- } catch (ex) {
- reject(ex);
- }
- }
-
- for (var i = 0; i < args.length; i++) {
- res(i, args[i]);
- }
- });
- };
-
- Promise$1.resolve = function (value) {
- if (value && _typeof(value) === 'object' && value.constructor === Promise$1) {
- return value;
- }
-
- return new Promise$1(function (resolve) {
- resolve(value);
- });
- };
-
- Promise$1.reject = function (value) {
- return new Promise$1(function (resolve, reject) {
- reject(value);
- });
- };
-
- Promise$1.race = function (arr) {
- return new Promise$1(function (resolve, reject) {
- if (!isArray(arr)) {
- return reject(new TypeError('Promise.race accepts an array'));
- }
-
- for (var i = 0, len = arr.length; i < len; i++) {
- Promise$1.resolve(arr[i]).then(resolve, reject);
- }
- });
- }; // Use polyfill for setImmediate for performance gains
-
-
- Promise$1._immediateFn = // @ts-ignore
- typeof setImmediate === 'function' && function (fn) {
- // @ts-ignore
- setImmediate(fn);
- } || function (fn) {
- setTimeoutFunc(fn, 0);
- };
-
- Promise$1._unhandledRejectionFn = function _unhandledRejectionFn(err) {
- if (typeof console !== 'undefined' && console) {
- console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
- }
- };
-
- // Karma + Webpack. You need to specify the default import when using promise-polyfill`
- // with Webpack 2+. We need `require('promise-polyfill').default` for running the tests
- // and `require('promise-polyfill')` for building Turbine.
-
-
- var reactorPromise = typeof window !== 'undefined' && window.Promise || typeof commonjsGlobal !== 'undefined' && commonjsGlobal.Promise || Promise$1.default || Promise$1;
-
- var getPromise = function getPromise(url, script) {
- return new reactorPromise(function (resolve, reject) {
- script.onload = function () {
- resolve(script);
- };
-
- script.onerror = function () {
- reject(new Error('Failed to load script ' + url));
- };
- });
- };
-
- var reactorLoadScript = function reactorLoadScript(url) {
- var script = document.createElement('script');
- script.src = url;
- script.async = true;
- var promise = getPromise(url, script);
- document.getElementsByTagName('head')[0].appendChild(script);
- return promise;
- };
-
- var is = function is(element, tagName) {
- return !!element && element.tagName === tagName;
- };
-
- var isInlineScript = function isInlineScript(element) {
- return is(element, SCRIPT) && !getAttribute(element, SRC);
- };
-
- var isRemoteScript = function isRemoteScript(element) {
- return is(element, SCRIPT) && getAttribute(element, SRC);
- };
-
- var getInlineScripts = function getInlineScripts(fragment) {
- var scripts = selectNodes(SCRIPT, fragment);
- var result = [];
- var length = scripts.length;
- var nonce = getNonce();
-
- var attributes = _objectSpread2({}, nonce && {
- nonce: nonce
- });
- /* eslint-disable no-continue */
-
-
- for (var i = 0; i < length; i += 1) {
- var element = scripts[i];
-
- if (!isInlineScript(element)) {
- continue;
- }
-
- var textContent = element.textContent;
-
- if (!textContent) {
- continue;
- }
-
- result.push(createNode(SCRIPT, attributes, {
- textContent: textContent
- }));
- }
- /* eslint-enable no-continue */
-
-
- return result;
- };
- var getRemoteScriptsUrls = function getRemoteScriptsUrls(fragment) {
- var scripts = selectNodes(SCRIPT, fragment);
- var result = [];
- var length = scripts.length;
- /* eslint-disable no-continue */
-
- for (var i = 0; i < length; i += 1) {
- var element = scripts[i];
-
- if (!isRemoteScript(element)) {
- continue;
- }
-
- var url = getAttribute(element, SRC);
-
- if (!url) {
- continue;
- }
-
- result.push(url);
- }
- /* eslint-enable no-continue */
-
-
- return result;
- };
- var executeInlineScripts = function executeInlineScripts(parent, scripts) {
- scripts.forEach(function (script) {
- parent.appendChild(script);
- parent.removeChild(script);
- });
- };
- var executeRemoteScripts = function executeRemoteScripts(urls) {
- return Promise.all(urls.map(reactorLoadScript));
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var appendHtml = (function (container, html) {
- var fragment = createFragment(html);
- addNonceToInlineStyleElements(fragment);
- var elements = getChildNodes(fragment);
- var scripts = getInlineScripts(fragment);
- var scriptsUrls = getRemoteScriptsUrls(fragment);
- loadImages(fragment);
- elements.forEach(function (element) {
- appendNode(container, element);
- });
- executeInlineScripts(container, scripts);
- return executeRemoteScripts(scriptsUrls);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var clear = function clear(container) {
- // We want to remove ALL nodes, text, comments etc
- var childNodes = getChildNodes(container);
- childNodes.forEach(removeNode);
- };
-
- var setHtml = (function (container, html) {
- clear(container);
- appendHtml(container, html);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var prependHtml = (function (container, html) {
- var fragment = createFragment(html);
- addNonceToInlineStyleElements(fragment);
- var elements = getChildNodes(fragment);
- var scripts = getInlineScripts(fragment);
- var scriptsUrls = getRemoteScriptsUrls(fragment);
- var length = elements.length;
- var i = length - 1; // We have to proactively load images to avoid flicker
-
- loadImages(fragment); // We are inserting elements in reverse order
-
- while (i >= 0) {
- var element = elements[i];
- var firstChild = getFirstChild(container);
-
- if (firstChild) {
- insertBefore(firstChild, element);
- } else {
- appendNode(container, element);
- }
-
- i -= 1;
- }
-
- executeInlineScripts(container, scripts);
- return executeRemoteScripts(scriptsUrls);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var insertHtmlBefore = (function (container, html) {
- var fragment = createFragment(html);
- addNonceToInlineStyleElements(fragment);
- var elements = getChildNodes(fragment);
- var scripts = getInlineScripts(fragment);
- var scriptsUrls = getRemoteScriptsUrls(fragment);
- loadImages(fragment);
- elements.forEach(function (element) {
- insertBefore(container, element);
- });
- executeInlineScripts(container, scripts);
- return executeRemoteScripts(scriptsUrls);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var replaceHtml = (function (container, html) {
- insertHtmlBefore(container, html);
- removeNode(container);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var insertHtmlAfter = (function (container, html) {
- var fragment = createFragment(html);
- addNonceToInlineStyleElements(fragment);
- var elements = getChildNodes(fragment);
- var scripts = getInlineScripts(fragment);
- var scriptsUrls = getRemoteScriptsUrls(fragment);
- loadImages(fragment);
- elements.forEach(function (element) {
- insertAfter(container, element);
- });
- executeInlineScripts(container, scripts);
- return executeRemoteScripts(scriptsUrls);
- });
-
- var _excluded$1 = ["priority"];
- var setStyles = (function (container, styles) {
- var priority = styles.priority,
- style = _objectWithoutProperties(styles, _excluded$1);
-
- Object.keys(style).forEach(function (key) {
- setStyle(container, key, style[key], priority);
- });
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var setAttributes = (function (container, attributes) {
- Object.keys(attributes).forEach(function (key) {
- setAttribute(container, key, attributes[key]);
- });
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var swapImage = (function (container, url) {
- if (!isImage(container)) {
- return;
- } // Start downloading the image
-
-
- loadImage(url); // Remove "src" so there is no flicker
-
- removeAttribute(container, SRC); // Replace the image "src"
-
- setAttribute(container, SRC, url);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var rearrangeChildren = (function (container, _ref) {
- var from = _ref.from,
- to = _ref.to;
- var children = getChildren(container);
- var elementFrom = children[from];
- var elementTo = children[to];
-
- if (!elementFrom || !elementTo) {
- // TODO: We will need to add logging
- // to ease troubleshooting
- return;
- }
-
- if (from < to) {
- insertAfter(elementTo, elementFrom);
- } else {
- insertBefore(elementTo, elementFrom);
- }
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var _click = (function (settings, store) {
- var selector = settings.selector,
- meta = settings.meta;
- store({
- selector: selector,
- meta: meta
- });
- return Promise.resolve();
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var renderContent = function renderContent(elements, content, renderFunc) {
- var executions = elements.map(function (element) {
- return renderFunc(element, content);
- });
- return Promise.all(executions);
- };
-
- var createAction = function createAction(renderFunc) {
- return function (settings) {
- var selector = settings.selector,
- prehidingSelector = settings.prehidingSelector,
- content = settings.content,
- meta = settings.meta;
- hideElements(prehidingSelector);
- return awaitSelector(selector, selectNodesWithEq).then(function (elements) {
- return renderContent(elements, content, renderFunc);
- }).then(function () {
- // if everything is OK, show elements
- showElements(prehidingSelector);
- return {
- meta: meta
- };
- }, function (error) {
- // in case of awaiting timing or error, we need to remove the style tag
- // hence showing the pre-hidden elements
- showElements(prehidingSelector);
- return {
- meta: meta,
- error: error
- };
- });
- };
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var initDomActionsModules = (function (store) {
- return {
- setHtml: createAction(setHtml),
- customCode: createAction(prependHtml),
- setText: createAction(setText),
- setAttribute: createAction(setAttributes),
- setImageSource: createAction(swapImage),
- setStyle: createAction(setStyles),
- move: createAction(setStyles),
- resize: createAction(setStyles),
- rearrange: createAction(rearrangeChildren),
- remove: createAction(removeNode),
- insertAfter: createAction(insertHtmlAfter),
- insertBefore: createAction(insertHtmlBefore),
- replaceHtml: createAction(replaceHtml),
- prependHtml: createAction(prependHtml),
- appendHtml: createAction(appendHtml),
- click: function click(settings) {
- return _click(settings, store);
- },
- defaultContent: function defaultContent(settings) {
- return Promise.resolve({
- meta: settings.meta
- });
- }
- };
- });
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- /**
- * Returns whether a string value is blank. Also returns true if the value is not a string.
- * @param {*} value
- * @returns {boolean}
- */
-
- var isBlankString = (function (value) {
- return isString(value) ? !value.trim() : true;
- });
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var APPEND_HTML = "appendHtml";
- var HEAD_TAGS_SELECTOR = "SCRIPT,LINK,STYLE";
-
- var filterHeadContent = function filterHeadContent(content) {
- var container = createFragment(content);
- var headNodes = selectNodes(HEAD_TAGS_SELECTOR, container);
- return headNodes.map(function (node) {
- return node.outerHTML;
- }).join("");
- };
-
- var remapHeadOffers = (function (action) {
- var result = reactorObjectAssign({}, action);
- var content = result.content,
- selector = result.selector;
-
- if (isBlankString(content)) {
- return result;
- }
-
- var container = selectNodesWithEq(selector);
-
- if (!is(container[0], HEAD)) {
- return result;
- }
-
- result.type = APPEND_HTML;
- result.content = filterHeadContent(content);
- return result;
- });
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var ACTION_CUSTOM_CODE = "customCode";
- var TARGET_BODY_SELECTOR = "BODY > *:eq(0)";
- var remapCustomCodeOffers = (function (action) {
- var selector = action.selector,
- type = action.type;
-
- if (type !== ACTION_CUSTOM_CODE) {
- return action;
- }
-
- if (selector !== TARGET_BODY_SELECTOR) {
- return action;
- }
-
- return reactorObjectAssign({}, action, {
- selector: "BODY"
- });
- });
-
- var logActionError = function logActionError(logger, action, error) {
- if (logger.enabled) {
- var details = JSON.stringify(action);
- var message = error.message,
- stack = error.stack;
- var errorMessage = "Failed to execute action " + details + ". " + message + " " + (stack ? "\n " + stack : "");
- logger.error(errorMessage);
- }
- };
-
- var logActionCompleted = function logActionCompleted(logger, action) {
- if (logger.enabled) {
- var details = JSON.stringify(action);
- logger.info("Action " + details + " executed.");
- }
- };
-
- var executeAction = function executeAction(logger, modules, type, args) {
- var execute = modules[type];
-
- if (!execute) {
- var error = new Error("DOM action \"" + type + "\" not found");
- logActionError(logger, args[0], error);
- throw error;
- }
-
- return execute.apply(void 0, _toConsumableArray(args));
- };
-
- var PREPROCESSORS = [remapHeadOffers, remapCustomCodeOffers];
-
- var preprocess = function preprocess(action) {
- return PREPROCESSORS.reduce(function (processed, fn) {
- return reactorObjectAssign(processed, fn(processed));
- }, action);
- };
-
- var executeActions = (function (actions, modules, logger) {
- var actionPromises = actions.map(function (action) {
- var processedAction = preprocess(action);
- var type = processedAction.type;
- return executeAction(logger, modules, type, [processedAction]).then(function (result) {
- logActionCompleted(logger, processedAction);
- return result;
- }).catch(function (error) {
- logActionError(logger, processedAction, error);
- throw error;
- });
- });
- return Promise.all(actionPromises);
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var DISPLAY = "decisioning.propositionDisplay";
- var INTERACT = "decisioning.propositionInteract";
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var PropositionEventType = {
- DISPLAY: "display",
- INTERACT: "interact"
- };
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createCollect = (function (_ref) {
- var eventManager = _ref.eventManager,
- mergeDecisionsMeta = _ref.mergeDecisionsMeta;
- // Called when a decision is auto-rendered for the __view__ scope or a SPA view(display and empty display notification)
- return function (_ref2) {
- var _ref2$decisionsMeta = _ref2.decisionsMeta,
- decisionsMeta = _ref2$decisionsMeta === void 0 ? [] : _ref2$decisionsMeta,
- _ref2$documentMayUnlo = _ref2.documentMayUnload,
- documentMayUnload = _ref2$documentMayUnlo === void 0 ? false : _ref2$documentMayUnlo,
- viewName = _ref2.viewName;
- var event = eventManager.createEvent();
- var data = {
- eventType: DISPLAY
- };
-
- if (viewName) {
- data.web = {
- webPageDetails: {
- viewName: viewName
- }
- };
- }
-
- if (isNonEmptyArray(decisionsMeta)) {
- mergeDecisionsMeta(event, decisionsMeta, PropositionEventType.DISPLAY);
- }
-
- event.mergeXdm(data);
-
- if (documentMayUnload) {
- event.documentMayUnload();
- }
-
- return eventManager.sendEvent(event);
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var DEFAULT_ACTION_TYPE = "defaultContent";
-
- var identity = function identity(item) {
- return item;
- };
-
- var getItemMeta = function getItemMeta(item, decisionMeta) {
- return item.characteristics && item.characteristics.trackingLabel ? reactorObjectAssign({
- trackingLabel: item.characteristics.trackingLabel
- }, decisionMeta) : decisionMeta;
- };
-
- var buildActions = function buildActions(decision) {
- var decisionMeta = {
- id: decision.id,
- scope: decision.scope,
- scopeDetails: decision.scopeDetails
- };
- return decision.items.map(function (item) {
- return reactorObjectAssign({
- type: DEFAULT_ACTION_TYPE
- }, item.data, {
- meta: getItemMeta(item, decisionMeta)
- });
- });
- };
-
- var processMetas = function processMetas(logger, actionResults) {
- var results = flatMap(actionResults, identity);
- var finalMetas = [];
- var set = new Set();
- results.forEach(function (item) {
- // for click actions we don't return an item
- if (!item) {
- return;
- }
-
- if (item.error) {
- logger.warn(item);
- return;
- }
-
- var meta = item.meta;
-
- if (set.has(meta.id)) {
- return;
- }
-
- set.add(meta.id);
- finalMetas.push(meta);
- });
- return finalMetas;
- };
-
- var createExecuteDecisions = (function (_ref) {
- var modules = _ref.modules,
- logger = _ref.logger,
- executeActions = _ref.executeActions;
- return function (decisions) {
- var actionResultsPromises = decisions.map(function (decision) {
- var actions = buildActions(decision);
- return executeActions(actions, modules, logger);
- });
- return Promise.all(actionResultsPromises).then(function (results) {
- return processMetas(logger, results);
- }).catch(function (error) {
- logger.error(error);
- });
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createFetchDataHandler = (function (_ref) {
- var prehidingStyle = _ref.prehidingStyle,
- responseHandler = _ref.responseHandler,
- hideContainers = _ref.hideContainers,
- mergeQuery = _ref.mergeQuery;
- return function (_ref2) {
- var decisionsDeferred = _ref2.decisionsDeferred,
- personalizationDetails = _ref2.personalizationDetails,
- event = _ref2.event,
- onResponse = _ref2.onResponse;
-
- if (personalizationDetails.isRenderDecisions()) {
- hideContainers(prehidingStyle);
- }
-
- mergeQuery(event, personalizationDetails.createQueryDetails());
- onResponse(function (_ref3) {
- var response = _ref3.response;
- return responseHandler({
- decisionsDeferred: decisionsDeferred,
- personalizationDetails: personalizationDetails,
- response: response
- });
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var matchesSelectorWithEq = (function (selector, element) {
- if (isNotEqSelector(selector)) {
- return matchesSelector(selector, element);
- } // Using node selection vs matches selector, because of :eq()
- // Find all nodes using document as context
-
-
- var nodes = selectNodesWithEq(selector);
- var result = false; // Iterate through all the identified elements
- // and reference compare with element
-
- for (var i = 0; i < nodes.length; i += 1) {
- if (nodes[i] === element) {
- result = true;
- break;
- }
- }
-
- return result;
- });
-
- var getMetasIfMatches = function getMetasIfMatches(clickedElement, selector, getClickMetasBySelector) {
- var _document = document,
- documentElement = _document.documentElement;
- var element = clickedElement;
- var i = 0;
-
- while (element && element !== documentElement) {
- if (matchesSelectorWithEq(selector, element)) {
- var matchedMetas = getClickMetasBySelector(selector);
- var foundMetaWithLabel = matchedMetas.find(function (meta) {
- return meta.trackingLabel;
- });
-
- if (foundMetaWithLabel) {
- return {
- metas: matchedMetas,
- label: foundMetaWithLabel.trackingLabel,
- weight: i
- };
- }
-
- return {
- metas: matchedMetas
- };
- }
-
- element = element.parentNode;
- i += 1;
- }
-
- return {
- metas: null
- };
- };
-
- var cleanMetas = function cleanMetas(metas) {
- return metas.map(function (meta) {
- delete meta.trackingLabel;
- return meta;
- });
- };
-
- var dedupMetas = function dedupMetas(metas) {
- return metas.filter(function (meta, index) {
- var stringifiedMeta = JSON.stringify(meta);
- return index === metas.findIndex(function (innerMeta) {
- return JSON.stringify(innerMeta) === stringifiedMeta;
- });
- });
- };
-
- var collectClicks = (function (clickedElement, selectors, getClickMetasBySelector) {
- var result = [];
- var resultLabel = "";
- var resultLabelWeight = Number.MAX_SAFE_INTEGER;
- /* eslint-disable no-continue */
-
- for (var i = 0; i < selectors.length; i += 1) {
- var _getMetasIfMatches = getMetasIfMatches(clickedElement, selectors[i], getClickMetasBySelector),
- metas = _getMetasIfMatches.metas,
- label = _getMetasIfMatches.label,
- weight = _getMetasIfMatches.weight;
-
- if (!metas) {
- continue;
- }
-
- if (label && weight <= resultLabelWeight) {
- resultLabel = label;
- resultLabelWeight = weight;
- }
-
- result.push.apply(result, _toConsumableArray(cleanMetas(metas)));
- }
-
- return {
- decisionsMeta: dedupMetas(result),
- eventLabel: resultLabel
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var isAuthoringModeEnabled = (function () {
- var doc = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;
- return doc.location.href.indexOf("adobe_authoring_enabled") !== -1;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var EVENT_TYPE_TRUE = 1;
- /* eslint-disable no-underscore-dangle */
-
- var mergeDecisionsMeta = function mergeDecisionsMeta(event, decisionsMeta, eventType) {
- var eventLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "";
- var xdm = {
- _experience: {
- decisioning: {
- propositions: decisionsMeta,
- propositionEventType: _defineProperty({}, eventType, EVENT_TYPE_TRUE)
- }
- }
- };
-
- if (eventLabel) {
- xdm._experience.decisioning.propositionAction = {
- label: eventLabel
- };
- }
-
- event.mergeXdm(xdm);
- };
- var mergeQuery = function mergeQuery(event, details) {
- event.mergeQuery({
- personalization: _objectSpread2({}, details)
- });
- };
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createOnClickHandler = (function (_ref) {
- var mergeDecisionsMeta = _ref.mergeDecisionsMeta,
- collectClicks = _ref.collectClicks,
- getClickSelectors = _ref.getClickSelectors,
- getClickMetasBySelector = _ref.getClickMetasBySelector;
- // Called when an element qualifying for conversion within an offer is clicked.
- return function (_ref2) {
- var event = _ref2.event,
- clickedElement = _ref2.clickedElement;
- var selectors = getClickSelectors();
-
- if (isNonEmptyArray(selectors)) {
- var _collectClicks = collectClicks(clickedElement, selectors, getClickMetasBySelector),
- decisionsMeta = _collectClicks.decisionsMeta,
- eventLabel = _collectClicks.eventLabel;
-
- if (isNonEmptyArray(decisionsMeta)) {
- var xdm = {
- eventType: INTERACT
- };
- var scope = decisionsMeta[0].scope;
-
- if (scope !== PAGE_WIDE_SCOPE) {
- xdm.web = {
- webPageDetails: {
- viewName: scope
- }
- };
- }
-
- event.mergeXdm(xdm);
- mergeDecisionsMeta(event, decisionsMeta, PropositionEventType.INTERACT, eventLabel);
- }
- }
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createViewCacheManager = (function () {
- var viewStorage;
- var viewStorageDeferred = defer();
-
- var storeViews = function storeViews(decisionsPromise) {
- decisionsPromise.then(function (decisions) {
- if (viewStorage === undefined) {
- viewStorage = {};
- }
-
- reactorObjectAssign(viewStorage, decisions);
- viewStorageDeferred.resolve();
- }).catch(function () {
- if (viewStorage === undefined) {
- viewStorage = {};
- }
-
- viewStorageDeferred.resolve();
- });
- };
-
- var getView = function getView(viewName) {
- return viewStorageDeferred.promise.then(function () {
- return viewStorage[viewName] || [];
- });
- };
-
- var isInitialized = function isInitialized() {
- return !(viewStorage === undefined);
- };
-
- return {
- storeViews: storeViews,
- getView: getView,
- isInitialized: isInitialized
- };
- });
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var addRenderAttemptedToDecisions = (function (_ref) {
- var decisions = _ref.decisions,
- renderAttempted = _ref.renderAttempted;
- return decisions.map(function (decision) {
- return reactorObjectAssign({
- renderAttempted: renderAttempted
- }, decision);
- });
- });
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var composePersonalizationResultingObject = (function () {
- var decisions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
- var renderDecisions = arguments.length > 1 ? arguments[1] : undefined;
- var resultingObject = {
- propositions: addRenderAttemptedToDecisions({
- decisions: decisions,
- renderAttempted: renderDecisions
- })
- };
-
- if (!renderDecisions) {
- resultingObject.decisions = decisions;
- }
-
- return resultingObject;
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createViewChangeHandler = (function (_ref) {
- var mergeDecisionsMeta = _ref.mergeDecisionsMeta,
- collect = _ref.collect,
- executeDecisions = _ref.executeDecisions,
- viewCache = _ref.viewCache;
- return function (_ref2) {
- var personalizationDetails = _ref2.personalizationDetails,
- event = _ref2.event,
- onResponse = _ref2.onResponse;
- var viewName = personalizationDetails.getViewName();
- return viewCache.getView(viewName).then(function (viewDecisions) {
- if (personalizationDetails.isRenderDecisions()) {
- return executeDecisions(viewDecisions).then(function (decisionsMeta) {
- // if there are decisions to be rendered we render them and attach the result in experience.decisions.propositions
- if (isNonEmptyArray(decisionsMeta)) {
- mergeDecisionsMeta(event, decisionsMeta, PropositionEventType.DISPLAY);
- onResponse(function () {
- return composePersonalizationResultingObject(viewDecisions, true);
- });
- return;
- } // if there are no decisions in cache for this view, we will send a empty notification
-
-
- onResponse(function () {
- collect({
- decisionsMeta: [],
- viewName: viewName
- });
- return composePersonalizationResultingObject(viewDecisions, true);
- });
- });
- }
-
- onResponse(function () {
- return composePersonalizationResultingObject(viewDecisions, false);
- });
- return {};
- });
- };
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var isPageWideScope = (function (scope) {
- return scope === PAGE_WIDE_SCOPE || isPageWideSurface(scope);
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var VIEW_SCOPE_TYPE = "view";
-
- var splitItems = function splitItems(items, schemas) {
- var matched = [];
- var nonMatched = [];
- items.forEach(function (item) {
- if (includes(schemas, item.schema)) {
- matched.push(item);
- } else {
- nonMatched.push(item);
- }
- });
- return [matched, nonMatched];
- };
-
- var createDecision = function createDecision(decision, items) {
- return {
- id: decision.id,
- scope: decision.scope,
- items: items,
- scopeDetails: decision.scopeDetails
- };
- };
-
- var splitMergedMetricDecisions = function splitMergedMetricDecisions(decisions) {
- var matchedDecisions = decisions.filter(function (decision) {
- var _decision$items = decision.items,
- items = _decision$items === void 0 ? [] : _decision$items;
- return items.some(function (item) {
- return item.schema === MEASUREMENT_SCHEMA;
- });
- });
- var unmatchedDecisions = decisions.filter(function (decision) {
- return !includes(matchedDecisions, decision);
- });
- return {
- matchedDecisions: matchedDecisions,
- unmatchedDecisions: unmatchedDecisions
- };
- };
-
- var splitDecisions = function splitDecisions(decisions) {
- for (var _len = arguments.length, schemas = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- schemas[_key - 1] = arguments[_key];
- }
-
- var matchedDecisions = [];
- var unmatchedDecisions = [];
- decisions.forEach(function (decision) {
- var _decision$items2 = decision.items,
- items = _decision$items2 === void 0 ? [] : _decision$items2;
-
- var _splitItems = splitItems(items, schemas),
- _splitItems2 = _slicedToArray(_splitItems, 2),
- matchedItems = _splitItems2[0],
- nonMatchedItems = _splitItems2[1];
-
- if (isNonEmptyArray(matchedItems)) {
- matchedDecisions.push(createDecision(decision, matchedItems));
- }
-
- if (isNonEmptyArray(nonMatchedItems)) {
- unmatchedDecisions.push(createDecision(decision, nonMatchedItems));
- }
- });
- return {
- matchedDecisions: matchedDecisions,
- unmatchedDecisions: unmatchedDecisions
- };
- };
-
- var appendScopeDecision = function appendScopeDecision(scopeDecisions, decision) {
- if (!scopeDecisions[decision.scope]) {
- scopeDecisions[decision.scope] = [];
- }
-
- scopeDecisions[decision.scope].push(decision);
- };
-
- var isViewScope = function isViewScope(scopeDetails) {
- return scopeDetails.characteristics && scopeDetails.characteristics.scopeType && scopeDetails.characteristics.scopeType === VIEW_SCOPE_TYPE;
- };
-
- var extractDecisionsByScope = function extractDecisionsByScope(decisions) {
- var pageWideScopeDecisions = [];
- var nonPageWideScopeDecisions = [];
- var viewScopeDecisions = {};
-
- if (isNonEmptyArray(decisions)) {
- decisions.forEach(function (decision) {
- if (isPageWideScope(decision.scope)) {
- pageWideScopeDecisions.push(decision);
- } else if (isViewScope(decision.scopeDetails)) {
- appendScopeDecision(viewScopeDecisions, decision);
- } else {
- nonPageWideScopeDecisions.push(decision);
- }
- });
- }
-
- return {
- pageWideScopeDecisions: pageWideScopeDecisions,
- nonPageWideScopeDecisions: nonPageWideScopeDecisions,
- viewScopeDecisions: viewScopeDecisions
- };
- };
-
- var groupDecisions = function groupDecisions(unprocessedDecisions) {
- // split redirect decisions
- var decisionsGroupedByRedirectItemSchema = splitDecisions(unprocessedDecisions, REDIRECT_ITEM); // split merged measurement decisions
-
- var mergedMetricDecisions = splitMergedMetricDecisions(decisionsGroupedByRedirectItemSchema.unmatchedDecisions); // split renderable decisions
-
- var decisionsGroupedByRenderableSchemas = splitDecisions(mergedMetricDecisions.unmatchedDecisions, DOM_ACTION, DEFAULT_CONTENT_ITEM); // group renderable decisions by scope
-
- var _extractDecisionsBySc = extractDecisionsByScope(decisionsGroupedByRenderableSchemas.matchedDecisions),
- pageWideScopeDecisions = _extractDecisionsBySc.pageWideScopeDecisions,
- nonPageWideScopeDecisions = _extractDecisionsBySc.nonPageWideScopeDecisions,
- viewScopeDecisions = _extractDecisionsBySc.viewScopeDecisions;
-
- return {
- redirectDecisions: decisionsGroupedByRedirectItemSchema.matchedDecisions,
- pageWideScopeDecisions: pageWideScopeDecisions,
- viewDecisions: viewScopeDecisions,
- nonAutoRenderableDecisions: [].concat(_toConsumableArray(mergedMetricDecisions.matchedDecisions), _toConsumableArray(decisionsGroupedByRenderableSchemas.unmatchedDecisions), _toConsumableArray(nonPageWideScopeDecisions))
- };
- };
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var DECISIONS_HANDLE = "personalization:decisions";
- var createOnResponseHandler = (function (_ref) {
- var autoRenderingHandler = _ref.autoRenderingHandler,
- nonRenderingHandler = _ref.nonRenderingHandler,
- groupDecisions = _ref.groupDecisions,
- handleRedirectDecisions = _ref.handleRedirectDecisions,
- showContainers = _ref.showContainers;
- return function (_ref2) {
- var decisionsDeferred = _ref2.decisionsDeferred,
- personalizationDetails = _ref2.personalizationDetails,
- response = _ref2.response;
- var unprocessedDecisions = response.getPayloadsByType(DECISIONS_HANDLE);
- var viewName = personalizationDetails.getViewName(); // if personalization payload is empty return empty decisions array
-
- if (unprocessedDecisions.length === 0) {
- showContainers();
- decisionsDeferred.resolve({});
- return {
- decisions: [],
- propositions: []
- };
- }
-
- var _groupDecisions = groupDecisions(unprocessedDecisions),
- redirectDecisions = _groupDecisions.redirectDecisions,
- pageWideScopeDecisions = _groupDecisions.pageWideScopeDecisions,
- viewDecisions = _groupDecisions.viewDecisions,
- nonAutoRenderableDecisions = _groupDecisions.nonAutoRenderableDecisions;
-
- if (personalizationDetails.isRenderDecisions() && isNonEmptyArray(redirectDecisions)) {
- decisionsDeferred.resolve({});
- return handleRedirectDecisions(redirectDecisions);
- } // save decisions for views in local cache
-
-
- decisionsDeferred.resolve(viewDecisions);
-
- if (personalizationDetails.isRenderDecisions()) {
- return autoRenderingHandler({
- viewName: viewName,
- pageWideScopeDecisions: pageWideScopeDecisions,
- nonAutoRenderableDecisions: nonAutoRenderableDecisions
- });
- }
-
- return nonRenderingHandler({
- viewName: viewName,
- redirectDecisions: redirectDecisions,
- pageWideScopeDecisions: pageWideScopeDecisions,
- nonAutoRenderableDecisions: nonAutoRenderableDecisions
- });
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var metasToArray = function metasToArray(metas) {
- return Object.keys(metas).map(function (key) {
- return {
- id: key,
- scope: metas[key].scope,
- scopeDetails: metas[key].scopeDetails,
- trackingLabel: metas[key].trackingLabel
- };
- });
- };
-
- var createClickStorage = (function () {
- var clickStorage = {};
-
- var storeClickMetrics = function storeClickMetrics(value) {
- if (!clickStorage[value.selector]) {
- clickStorage[value.selector] = {};
- }
-
- clickStorage[value.selector][value.meta.id] = {
- scope: value.meta.scope,
- scopeDetails: value.meta.scopeDetails,
- trackingLabel: value.meta.trackingLabel
- };
- };
-
- var getClickSelectors = function getClickSelectors() {
- return Object.keys(clickStorage);
- };
-
- var getClickMetasBySelector = function getClickMetasBySelector(selector) {
- var metas = clickStorage[selector];
-
- if (!metas) {
- return {};
- }
-
- return metasToArray(clickStorage[selector]);
- };
-
- return {
- storeClickMetrics: storeClickMetrics,
- getClickSelectors: getClickSelectors,
- getClickMetasBySelector: getClickMetasBySelector
- };
- });
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var getRedirectDetails = function getRedirectDetails(redirectDecisions) {
- var decision = redirectDecisions[0];
- var items = decision.items,
- id = decision.id,
- scope = decision.scope,
- scopeDetails = decision.scopeDetails;
- var content = items[0].data.content;
- return {
- content: content,
- decisions: [{
- id: id,
- scope: scope,
- scopeDetails: scopeDetails
- }]
- };
- };
-
- var createRedirectHandler = (function (_ref) {
- var collect = _ref.collect,
- window = _ref.window,
- logger = _ref.logger,
- showContainers = _ref.showContainers;
- return function (redirectDecisions) {
- var _getRedirectDetails = getRedirectDetails(redirectDecisions),
- content = _getRedirectDetails.content,
- decisions = _getRedirectDetails.decisions;
-
- var documentMayUnload = true;
- return collect({
- decisionsMeta: decisions,
- documentMayUnload: documentMayUnload
- }).then(function () {
- window.location.replace(content);
- }).catch(function () {
- showContainers();
- logger.warn(REDIRECT_EXECUTION_ERROR);
- });
- };
- });
-
- var getPropositions = function getPropositions(_ref) {
- var viewCache = _ref.viewCache,
- viewName = _ref.viewName,
- pageWideScopeDecisions = _ref.pageWideScopeDecisions;
-
- if (!viewName) {
- return {
- pageWideScopeDecisions: pageWideScopeDecisions,
- viewPropositions: []
- };
- }
-
- return viewCache.getView(viewName).then(function (viewPropositions) {
- return {
- pageWideScopeDecisions: pageWideScopeDecisions,
- viewPropositions: viewPropositions
- };
- });
- };
-
- var createAutorenderingHandler = (function (_ref2) {
- var viewCache = _ref2.viewCache,
- executeDecisions = _ref2.executeDecisions,
- showContainers = _ref2.showContainers,
- collect = _ref2.collect;
- return function (_ref3) {
- var viewName = _ref3.viewName,
- pageWideScopeDecisions = _ref3.pageWideScopeDecisions,
- nonAutoRenderableDecisions = _ref3.nonAutoRenderableDecisions;
- return Promise.resolve(pageWideScopeDecisions).then(function (propositions) {
- return getPropositions({
- viewCache: viewCache,
- viewName: viewName,
- executeDecisions: executeDecisions,
- pageWideScopeDecisions: propositions
- });
- }).then(function (propositions) {
- executeDecisions(propositions.pageWideScopeDecisions).then(function (decisionsMeta) {
- if (isNonEmptyArray(decisionsMeta)) {
- collect({
- decisionsMeta: decisionsMeta
- });
- }
- });
-
- if (viewName) {
- executeDecisions(propositions.viewPropositions).then(function (decisionsMeta) {
- collect({
- decisionsMeta: decisionsMeta,
- viewName: viewName
- });
- });
- }
-
- showContainers();
- return [].concat(_toConsumableArray(propositions.pageWideScopeDecisions), _toConsumableArray(propositions.viewPropositions));
- }).then(function (renderablePropositions) {
- return {
- decisions: _toConsumableArray(nonAutoRenderableDecisions),
- propositions: [].concat(_toConsumableArray(addRenderAttemptedToDecisions({
- decisions: renderablePropositions,
- renderAttempted: true
- })), _toConsumableArray(addRenderAttemptedToDecisions({
- decisions: nonAutoRenderableDecisions,
- renderAttempted: false
- })))
- };
- });
- };
- });
-
- var getViewPropositions = function getViewPropositions(_ref) {
- var viewCache = _ref.viewCache,
- viewName = _ref.viewName,
- propositions = _ref.propositions;
-
- if (!viewName) {
- return propositions;
- }
-
- return viewCache.getView(viewName).then(function (viewPropositions) {
- return [].concat(_toConsumableArray(viewPropositions), _toConsumableArray(propositions));
- });
- };
-
- var buildFinalResult = function buildFinalResult(_ref2) {
- var propositions = _ref2.propositions;
- return {
- decisions: propositions,
- propositions: addRenderAttemptedToDecisions({
- decisions: propositions,
- renderAttempted: false
- })
- };
- };
-
- var createNonRenderingHandler = (function (_ref3) {
- var viewCache = _ref3.viewCache;
- return function (_ref4) {
- var viewName = _ref4.viewName,
- redirectDecisions = _ref4.redirectDecisions,
- pageWideScopeDecisions = _ref4.pageWideScopeDecisions,
- nonAutoRenderableDecisions = _ref4.nonAutoRenderableDecisions;
- var propositions = [].concat(_toConsumableArray(redirectDecisions), _toConsumableArray(pageWideScopeDecisions), _toConsumableArray(nonAutoRenderableDecisions));
- return Promise.resolve(propositions).then(function (items) {
- return getViewPropositions({
- viewCache: viewCache,
- viewName: viewName,
- propositions: items
- });
- }).then(function (items) {
- return buildFinalResult({
- propositions: items
- });
- });
- };
- });
-
- var SUPPORTED_SCHEMAS = [DOM_ACTION, HTML_CONTENT_ITEM];
- var createApplyPropositions = (function (_ref) {
- var executeDecisions = _ref.executeDecisions;
-
- var filterItemsPredicate = function filterItemsPredicate(item) {
- return SUPPORTED_SCHEMAS.indexOf(item.schema) > -1;
- };
-
- var updatePropositionItems = function updatePropositionItems(_ref2) {
- var items = _ref2.items,
- metadataForScope = _ref2.metadataForScope;
- return items.filter(filterItemsPredicate).map(function (item) {
- if (item.schema !== HTML_CONTENT_ITEM) {
- return _objectSpread2({}, item);
- }
-
- if (isObject(metadataForScope)) {
- return _objectSpread2(_objectSpread2({}, item), {}, {
- data: _objectSpread2(_objectSpread2({}, item.data), {}, {
- selector: metadataForScope.selector,
- type: metadataForScope.actionType
- })
- });
- }
-
- return undefined;
- }).filter(function (item) {
- return item;
- });
- };
-
- var filterPropositionsPredicate = function filterPropositionsPredicate(proposition) {
- return !(proposition.scope === PAGE_WIDE_SCOPE && proposition.renderAttempted);
- };
-
- var preparePropositions = function preparePropositions(_ref3) {
- var propositions = _ref3.propositions,
- metadata = _ref3.metadata;
- return propositions.filter(filterPropositionsPredicate).map(function (proposition) {
- if (isNonEmptyArray(proposition.items)) {
- var id = proposition.id,
- scope = proposition.scope,
- scopeDetails = proposition.scopeDetails;
- return {
- id: id,
- scope: scope,
- scopeDetails: scopeDetails,
- items: updatePropositionItems({
- items: proposition.items,
- metadataForScope: metadata[proposition.scope]
- })
- };
- }
-
- return proposition;
- }).filter(function (proposition) {
- return isNonEmptyArray(proposition.items);
- });
- };
-
- var applyPropositions = function applyPropositions(_ref4) {
- var propositions = _ref4.propositions,
- metadata = _ref4.metadata;
- var propositionsToExecute = preparePropositions({
- propositions: propositions,
- metadata: metadata
- });
- return executeDecisions(propositionsToExecute).then(function () {
- return composePersonalizationResultingObject(propositionsToExecute, true);
- });
- };
-
- return function (_ref5) {
- var propositions = _ref5.propositions,
- _ref5$metadata = _ref5.metadata,
- metadata = _ref5$metadata === void 0 ? {} : _ref5$metadata;
-
- if (isNonEmptyArray(propositions)) {
- return applyPropositions({
- propositions: propositions,
- metadata: metadata
- });
- }
-
- return Promise.resolve(EMPTY_PROPOSITIONS);
- };
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createGetPageLocation = (function (_ref) {
- var window = _ref.window;
- return function () {
- return window.location;
- };
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createSetTargetMigration = (function (_ref) {
- var targetMigrationEnabled = _ref.targetMigrationEnabled;
-
- if (targetMigrationEnabled) {
- return function (request) {
- request.getPayload().mergeMeta({
- target: {
- migration: true
- }
- });
- };
- }
-
- return noop$1;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var createPersonalization = function createPersonalization(_ref) {
- var config = _ref.config,
- logger = _ref.logger,
- eventManager = _ref.eventManager;
- var targetMigrationEnabled = config.targetMigrationEnabled,
- prehidingStyle = config.prehidingStyle;
- var collect = createCollect({
- eventManager: eventManager,
- mergeDecisionsMeta: mergeDecisionsMeta
- });
-
- var _createClickStorage = createClickStorage(),
- getClickMetasBySelector = _createClickStorage.getClickMetasBySelector,
- getClickSelectors = _createClickStorage.getClickSelectors,
- storeClickMetrics = _createClickStorage.storeClickMetrics;
-
- var getPageLocation = createGetPageLocation({
- window: window
- });
- var viewCache = createViewCacheManager();
- var modules = initDomActionsModules(storeClickMetrics);
- var executeDecisions = createExecuteDecisions({
- modules: modules,
- logger: logger,
- executeActions: executeActions
- });
- var handleRedirectDecisions = createRedirectHandler({
- collect: collect,
- window: window,
- logger: logger,
- showContainers: showContainers
- });
- var autoRenderingHandler = createAutorenderingHandler({
- viewCache: viewCache,
- executeDecisions: executeDecisions,
- showContainers: showContainers,
- collect: collect
- });
- var applyPropositions = createApplyPropositions({
- executeDecisions: executeDecisions
- });
- var nonRenderingHandler = createNonRenderingHandler({
- viewCache: viewCache
- });
- var responseHandler = createOnResponseHandler({
- autoRenderingHandler: autoRenderingHandler,
- nonRenderingHandler: nonRenderingHandler,
- groupDecisions: groupDecisions,
- handleRedirectDecisions: handleRedirectDecisions,
- showContainers: showContainers
- });
- var fetchDataHandler = createFetchDataHandler({
- prehidingStyle: prehidingStyle,
- responseHandler: responseHandler,
- hideContainers: hideContainers,
- mergeQuery: mergeQuery
- });
- var onClickHandler = createOnClickHandler({
- mergeDecisionsMeta: mergeDecisionsMeta,
- collectClicks: collectClicks,
- getClickSelectors: getClickSelectors,
- getClickMetasBySelector: getClickMetasBySelector
- });
- var viewChangeHandler = createViewChangeHandler({
- mergeDecisionsMeta: mergeDecisionsMeta,
- collect: collect,
- executeDecisions: executeDecisions,
- viewCache: viewCache
- });
- var setTargetMigration = createSetTargetMigration({
- targetMigrationEnabled: targetMigrationEnabled
- });
- return createComponent$3({
- getPageLocation: getPageLocation,
- logger: logger,
- fetchDataHandler: fetchDataHandler,
- viewChangeHandler: viewChangeHandler,
- onClickHandler: onClickHandler,
- isAuthoringModeEnabled: isAuthoringModeEnabled,
- mergeQuery: mergeQuery,
- viewCache: viewCache,
- showContainers: showContainers,
- applyPropositions: applyPropositions,
- setTargetMigration: setTargetMigration
- });
- };
-
- createPersonalization.namespace = "Personalization";
- createPersonalization.configValidators = {
- prehidingStyle: boundString().nonEmpty(),
- targetMigrationEnabled: boundBoolean().default(false)
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectWeb = (function (window) {
- return function (xdm) {
- var web = {
- webPageDetails: {
- URL: window.location.href || window.location
- },
- webReferrer: {
- URL: window.document.referrer
- }
- };
- deepAssign(xdm, {
- web: web
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var getScreenOrientationViaProperty = function getScreenOrientationViaProperty(window) {
- var orientation = window.screen.orientation;
-
- if (orientation == null || orientation.type == null) {
- return null;
- }
-
- var parts = orientation.type.split("-");
-
- if (parts.length === 0) {
- return null;
- }
-
- if (parts[0] !== "portrait" && parts[0] !== "landscape") {
- return null;
- }
-
- return parts[0];
- };
-
- var getScreenOrientationViaMediaQuery = function getScreenOrientationViaMediaQuery(window) {
- if (isFunction(window.matchMedia)) {
- if (window.matchMedia("(orientation: portrait)").matches) {
- return "portrait";
- }
-
- if (window.matchMedia("(orientation: landscape)").matches) {
- return "landscape";
- }
- }
-
- return null;
- };
-
- var injectDevice = (function (window) {
- return function (xdm) {
- var _window$screen = window.screen,
- width = _window$screen.width,
- height = _window$screen.height;
- var device = {};
- var screenHeight = toInteger(height);
-
- if (screenHeight >= 0) {
- device.screenHeight = screenHeight;
- }
-
- var screenWidth = toInteger(width);
-
- if (screenWidth >= 0) {
- device.screenWidth = screenWidth;
- }
-
- var orientation = getScreenOrientationViaProperty(window) || getScreenOrientationViaMediaQuery(window);
-
- if (orientation) {
- device.screenOrientation = orientation;
- }
-
- if (Object.keys(device).length > 0) {
- deepAssign(xdm, {
- device: device
- });
- }
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectEnvironment = (function (window) {
- return function (xdm) {
- var _window$document$docu = window.document.documentElement;
- _window$document$docu = _window$document$docu === void 0 ? {} : _window$document$docu;
- var clientWidth = _window$document$docu.clientWidth,
- clientHeight = _window$document$docu.clientHeight;
- var environment = {
- type: "browser"
- };
- var viewportWidth = toInteger(clientWidth);
-
- if (viewportWidth >= 0) {
- environment.browserDetails = {
- viewportWidth: viewportWidth
- };
- }
-
- var viewportHeight = toInteger(clientHeight);
-
- if (viewportHeight >= 0) {
- environment.browserDetails = environment.browserDetails || {};
- environment.browserDetails.viewportHeight = viewportHeight;
- }
-
- deepAssign(xdm, {
- environment: environment
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectPlaceContext = (function (dateProvider) {
- return function (xdm) {
- var date = dateProvider();
- var placeContext = {};
- var localTimezoneOffset = toInteger(date.getTimezoneOffset());
-
- if (localTimezoneOffset !== undefined) {
- placeContext.localTimezoneOffset = localTimezoneOffset;
- } // make sure the timezone offset only uses two digits
-
-
- if (localTimezoneOffset === undefined || Math.abs(localTimezoneOffset) < 6000) {
- placeContext.localTime = toISOStringLocal(date);
- }
-
- deepAssign(xdm, {
- placeContext: placeContext
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectTimestamp = (function (dateProvider) {
- return function (xdm) {
- var timestamp = dateProvider().toISOString();
- deepAssign(xdm, {
- timestamp: timestamp
- });
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var libraryName = "https://ns.adobe.com/experience/alloy";
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- // The __VERSION__ keyword will be replace at alloy build time with the package.json version.
- // see babel-plugin-version
- var libraryVersion = "2.17.0";
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var implementationDetails = (function (xdm) {
- var implementationDetails = {
- name: libraryName,
- version: libraryVersion,
- environment: "browser"
- };
- deepAssign(xdm, {
- implementationDetails: implementationDetails
- });
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createComponent$2 = (function (config, logger, optionalContexts, requiredContexts) {
- var configuredContexts = config.context;
- var contexts = flatMap(configuredContexts, function (context, i) {
- if (optionalContexts[context]) {
- return [optionalContexts[context]];
- }
-
- logger.warn("Invalid context[" + i + "]: '" + context + "' is not available.");
- return [];
- }).concat(requiredContexts);
- return {
- namespace: "Context",
- lifecycle: {
- onBeforeEvent: function onBeforeEvent(_ref) {
- var event = _ref.event;
- var xdm = {};
- return Promise.all(contexts.map(function (context) {
- return Promise.resolve(context(xdm, logger));
- })).then(function () {
- return event.mergeXdm(xdm);
- });
- }
- }
- };
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var highEntropyUserAgentHints$1 = [["architecture", "string"], ["bitness", "string"], ["model", "string"], ["platformVersion", "string"], ["wow64", "boolean"]];
-
- var browserSupportsUserAgentClientHints = function browserSupportsUserAgentClientHints(navigator) {
- return typeof navigator.userAgentData !== "undefined";
- };
-
- var injectHighEntropyUserAgentHints = (function (navigator) {
- if (!browserSupportsUserAgentClientHints(navigator)) {
- return noop$1;
- }
-
- return function (xdm, logger) {
- try {
- return navigator.userAgentData.getHighEntropyValues(highEntropyUserAgentHints$1.map(function (hint) {
- return hint[0];
- })).then(function (hints) {
- var userAgentClientHints = {};
- highEntropyUserAgentHints$1.forEach(function (_ref) {
- var _ref2 = _slicedToArray(_ref, 2),
- hintName = _ref2[0],
- hintType = _ref2[1];
-
- if (Object.prototype.hasOwnProperty.call(hints, hintName) &&
- /* eslint-disable-next-line valid-typeof */
- _typeof(hints[hintName]) === hintType) {
- userAgentClientHints[hintName] = hints[hintName];
- }
- });
- deepAssign(xdm, {
- environment: {
- browserDetails: {
- userAgentClientHints: userAgentClientHints
- }
- }
- });
- });
- } catch (error) {
- logger.warn("Unable to collect user-agent client hints. " + error.message);
- return noop$1;
- }
- };
- });
-
- var web = injectWeb(window);
- var device = injectDevice(window);
- var environment = injectEnvironment(window);
- var placeContext = injectPlaceContext(function () {
- return new Date();
- });
- var timestamp = injectTimestamp(function () {
- return new Date();
- });
- var highEntropyUserAgentHints = injectHighEntropyUserAgentHints(navigator);
- var defaultEnabledContexts = {
- web: web,
- device: device,
- environment: environment,
- placeContext: placeContext
- };
- var defaultDisabledContexts = {
- highEntropyUserAgentHints: highEntropyUserAgentHints
- };
-
- var optionalContexts = _objectSpread2(_objectSpread2({}, defaultEnabledContexts), defaultDisabledContexts);
-
- var requiredContexts = [timestamp, implementationDetails];
-
- var createContext = function createContext(_ref) {
- var config = _ref.config,
- logger = _ref.logger;
- return createComponent$2(config, logger, optionalContexts, requiredContexts);
- };
-
- createContext.namespace = "Context";
- createContext.configValidators = {
- context: boundArrayOf(boundString()).default(Object.keys(defaultEnabledContexts))
- };
-
- var createComponent$1 = (function (_ref) {
- var storedConsent = _ref.storedConsent,
- taskQueue = _ref.taskQueue,
- defaultConsent = _ref.defaultConsent,
- consent = _ref.consent,
- sendSetConsentRequest = _ref.sendSetConsentRequest,
- validateSetConsentOptions = _ref.validateSetConsentOptions,
- consentHashStore = _ref.consentHashStore,
- doesIdentityCookieExist = _ref.doesIdentityCookieExist;
-
- var defaultConsentByPurpose = _defineProperty({}, GENERAL, defaultConsent);
-
- var storedConsentByPurpose = storedConsent.read();
- var identityCookieExists = doesIdentityCookieExist();
- var consentCookieExists = storedConsentByPurpose[GENERAL] !== undefined;
-
- if (!identityCookieExists || !consentCookieExists) {
- consentHashStore.clear();
- } // If the identity cookie is gone, remove the consent cookie because the
- // consent info is tied to the identity.
-
-
- if (!identityCookieExists) {
- storedConsent.clear();
- storedConsentByPurpose = {};
- }
-
- consent.initializeConsent(defaultConsentByPurpose, storedConsentByPurpose);
-
- var readCookieIfQueueEmpty = function readCookieIfQueueEmpty() {
- if (taskQueue.length === 0) {
- var storedConsentObject = storedConsent.read(); // Only read cookies when there are no outstanding setConsent
- // requests. This helps with race conditions.
-
- if (storedConsentObject[GENERAL] !== undefined) {
- consent.setConsent(storedConsentObject);
- }
- }
- };
-
- return {
- commands: {
- setConsent: {
- optionsValidator: validateSetConsentOptions,
- run: function run(_ref2) {
- var consentOptions = _ref2.consent,
- identityMap = _ref2.identityMap,
- edgeConfigOverrides = _ref2.edgeConfigOverrides;
- consent.suspend();
- var consentHashes = consentHashStore.lookup(consentOptions);
- return taskQueue.addTask(function () {
- if (consentHashes.isNew()) {
- return sendSetConsentRequest({
- consentOptions: consentOptions,
- identityMap: identityMap,
- edgeConfigOverrides: edgeConfigOverrides
- });
- }
-
- return Promise.resolve();
- }).then(function () {
- return consentHashes.save();
- }).finally(readCookieIfQueueEmpty);
- }
- }
- },
- lifecycle: {
- // Read the cookie here too because the consent cookie may change on any request
- onResponse: readCookieIfQueueEmpty,
- // Even when we get a failure HTTP status code, the consent cookie can
- // still get updated. This could happen, for example, if the user is
- // opted out in AudienceManager, but no consent cookie exists on the
- // client. The request will be sent and the server will respond with a
- // 403 Forbidden and a consent cookie.
- onRequestFailure: readCookieIfQueueEmpty
- }
- };
- });
-
- var serialize = function serialize(obj) {
- if (Array.isArray(obj)) {
- return obj.map(function (i) {
- return serialize(i);
- });
- }
-
- if (_typeof(obj) === "object" && obj !== null) {
- return Object.keys(obj).sort().reduce(function (memo, key) {
- memo[key] = serialize(obj[key]);
- return memo;
- }, {});
- }
-
- return obj;
- };
-
- var computeConsentHash = (function (obj) {
- return crc32(JSON.stringify(serialize(obj)));
- });
-
- var _excluded = ["standard", "version"];
-
- var getKey = function getKey(_ref) {
- var standard = _ref.standard,
- version = _ref.version;
- return standard + "." + version;
- };
-
- var createConsentHashStore = (function (_ref2) {
- var storage = _ref2.storage;
- return {
- clear: function clear() {
- storage.clear();
- },
- lookup: function lookup(consentObjects) {
- var currentHashes = {};
-
- var getCurrentHash = function getCurrentHash(consentObject) {
- var key = getKey(consentObject);
-
- consentObject.standard;
- consentObject.version;
- var rest = _objectWithoutProperties(consentObject, _excluded);
-
- if (!currentHashes[key]) {
- currentHashes[key] = computeConsentHash(rest).toString();
- }
-
- return currentHashes[key];
- };
-
- return {
- isNew: function isNew() {
- return consentObjects.some(function (consentObject) {
- var key = getKey(consentObject);
- var previousHash = storage.getItem(key);
- return previousHash === null || previousHash !== getCurrentHash(consentObject);
- });
- },
- save: function save() {
- consentObjects.forEach(function (consentObject) {
- var key = getKey(consentObject);
- storage.setItem(key, getCurrentHash(consentObject));
- });
- }
- };
- }
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createConsentRequestPayload = (function () {
- var content = {};
- var payload = createRequestPayload({
- content: content,
- addIdentity: function addIdentity(namespaceCode, identity) {
- content.identityMap = content.identityMap || {};
- content.identityMap[namespaceCode] = content.identityMap[namespaceCode] || [];
- content.identityMap[namespaceCode].push(identity);
- },
- hasIdentity: function hasIdentity(namespaceCode) {
- return (content.identityMap && content.identityMap[namespaceCode]) !== undefined;
- }
- });
-
- payload.setConsent = function (consent) {
- content.consent = consent;
- };
-
- return payload;
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createConsentRequest = (function (consentRequestPayload) {
- return createRequest({
- payload: consentRequestPayload,
- getAction: function getAction() {
- return "privacy/set-consent";
- },
- getUseSendBeacon: function getUseSendBeacon() {
- return false;
- }
- });
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createStoredConsent = (function (_ref) {
- var parseConsentCookie = _ref.parseConsentCookie,
- orgId = _ref.orgId,
- cookieJar = _ref.cookieJar;
- var consentCookieName = getNamespacedCookieName(orgId, CONSENT);
- return {
- read: function read() {
- var cookieValue = cookieJar.get(consentCookieName);
- return cookieValue ? parseConsentCookie(cookieValue) : {};
- },
- clear: function clear() {
- cookieJar.remove(consentCookieName);
- }
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectSendSetConsentRequest = (function (_ref) {
- var createConsentRequestPayload = _ref.createConsentRequestPayload,
- createConsentRequest = _ref.createConsentRequest,
- sendEdgeNetworkRequest = _ref.sendEdgeNetworkRequest,
- globalConfigOverrides = _ref.edgeConfigOverrides;
- return function (_ref2) {
- var consentOptions = _ref2.consentOptions,
- identityMap = _ref2.identityMap,
- localConfigOverrides = _ref2.edgeConfigOverrides;
- var payload = createConsentRequestPayload();
- payload.setConsent(consentOptions);
- payload.mergeConfigOverride(globalConfigOverrides);
- payload.mergeConfigOverride(localConfigOverrides);
-
- if (isObject(identityMap)) {
- Object.keys(identityMap).forEach(function (key) {
- identityMap[key].forEach(function (identity) {
- payload.addIdentity(key, identity);
- });
- });
- }
-
- var request = createConsentRequest(payload);
- return sendEdgeNetworkRequest({
- request: request
- }).then(function () {// Don't let response data disseminate beyond this
- // point unless necessary.
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- /**
- * Parses a consent cookie.
- * @param {string} cookieValue Must be in the format a=b;c=d
- * @returns {Object} An object where the keys are purpose names and the values
- * are the consent status for the purpose.
- */
- var parseConsentCookie = (function (cookieValue) {
- var categoryPairs = cookieValue.split(";");
- return categoryPairs.reduce(function (consentByPurpose, categoryPair) {
- var _categoryPair$split = categoryPair.split("="),
- _categoryPair$split2 = _slicedToArray(_categoryPair$split, 2),
- name = _categoryPair$split2[0],
- value = _categoryPair$split2[1];
-
- consentByPurpose[name] = value;
- return consentByPurpose;
- }, {});
- });
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var validateSetConsentOptions = boundObjectOf({
- consent: boundArrayOf(boundAnything()).required().nonEmpty(),
- identityMap: validateIdentityMap,
- edgeConfigOverrides: validateConfigOverride
- }).noUnknownFields().required();
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var createPrivacy = function createPrivacy(_ref) {
- var config = _ref.config,
- consent = _ref.consent,
- sendEdgeNetworkRequest = _ref.sendEdgeNetworkRequest,
- createNamespacedStorage = _ref.createNamespacedStorage;
- var orgId = config.orgId,
- defaultConsent = config.defaultConsent;
- var storedConsent = createStoredConsent({
- parseConsentCookie: parseConsentCookie,
- orgId: orgId,
- cookieJar: cookieJar
- });
- var taskQueue = createTaskQueue();
- var sendSetConsentRequest = injectSendSetConsentRequest({
- createConsentRequestPayload: createConsentRequestPayload,
- createConsentRequest: createConsentRequest,
- sendEdgeNetworkRequest: sendEdgeNetworkRequest,
- edgeConfigOverrides: config.edgeConfigOverrides
- });
- var storage = createNamespacedStorage(sanitizeOrgIdForCookieName(orgId) + ".consentHashes.");
- var consentHashStore = createConsentHashStore({
- storage: storage.persistent
- });
- var doesIdentityCookieExist = injectDoesIdentityCookieExist({
- orgId: orgId
- });
- return createComponent$1({
- storedConsent: storedConsent,
- taskQueue: taskQueue,
- defaultConsent: defaultConsent,
- consent: consent,
- sendSetConsentRequest: sendSetConsentRequest,
- validateSetConsentOptions: validateSetConsentOptions,
- consentHashStore: consentHashStore,
- doesIdentityCookieExist: doesIdentityCookieExist
- });
- };
-
- createPrivacy.namespace = "Privacy";
-
- /*
- Copyright 20219 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createEventMergeId = (function () {
- return {
- eventMergeId: v4_1()
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createComponent = (function (_ref) {
- var createEventMergeId = _ref.createEventMergeId;
- return {
- commands: {
- createEventMergeId: {
- run: createEventMergeId
- }
- }
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var createEventMerge = function createEventMerge() {
- return createComponent({
- createEventMergeId: createEventMergeId
- });
- };
-
- createEventMerge.namespace = "EventMerge";
- createEventMerge.configValidators = {};
-
- var prepareLibraryInfo = function prepareLibraryInfo(_ref) {
- var config = _ref.config,
- componentRegistry = _ref.componentRegistry;
- var allCommands = [].concat(_toConsumableArray(componentRegistry.getCommandNames()), [CONFIGURE, SET_DEBUG]).sort();
-
- var resultConfig = _objectSpread2({}, config);
-
- Object.keys(config).forEach(function (key) {
- var value = config[key];
-
- if (typeof value !== "function") {
- return;
- }
-
- resultConfig[key] = value.toString();
- });
- return {
- version: libraryVersion,
- configs: resultConfig,
- commands: allCommands
- };
- };
-
- var createLibraryInfo = function createLibraryInfo(_ref2) {
- var config = _ref2.config,
- componentRegistry = _ref2.componentRegistry;
- var libraryInfo = prepareLibraryInfo({
- config: config,
- componentRegistry: componentRegistry
- });
- return {
- commands: {
- getLibraryInfo: {
- run: function run() {
- return {
- libraryInfo: libraryInfo
- };
- }
- }
- }
- };
- };
-
- createLibraryInfo.namespace = "LibraryInfo";
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var processResponse = (function (_ref) {
- var response = _ref.response;
- return {
- inferences: response.getPayloadsByType("rtml:inferences")
- };
- });
-
- /*
- Copyright 2021 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var createMachineLearning = function createMachineLearning() {
- return {
- lifecycle: {
- onResponse: processResponse
- },
- commands: {}
- };
- };
-
- createMachineLearning.namespace = "MachineLearning";
- createMachineLearning.configValidators = {};
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- // TODO: Figure out how sub-components will be made available/registered
-
- var componentCreators = [createDataCollector, createActivityCollector, createIdentity, createAudiences, createPersonalization, createContext, createPrivacy, createEventMerge, createLibraryInfo, createMachineLearning];
-
- var CONFIG_DOC_URI = "https://adobe.ly/3sHh553";
-
- var buildSchema = function buildSchema(coreConfigValidators, componentCreators) {
- var schema = {};
- reactorObjectAssign(schema, coreConfigValidators);
- componentCreators.forEach(function (createComponent) {
- var configValidators = createComponent.configValidators;
- reactorObjectAssign(schema, configValidators);
- });
- return schema;
- };
-
- var transformOptions = function transformOptions(schema, options) {
- try {
- var validator = boundObjectOf(schema).noUnknownFields().required();
- return validator(options);
- } catch (e) {
- throw new Error("Resolve these configuration problems:\n\t - " + e.message.split("\n").join("\n\t - ") + "\nFor configuration documentation see: " + CONFIG_DOC_URI);
- }
- };
-
- var buildAllOnInstanceConfiguredExtraParams = function buildAllOnInstanceConfiguredExtraParams(config, logger, componentCreators) {
- return componentCreators.reduce(function (memo, _ref) {
- var buildOnInstanceConfiguredExtraParams = _ref.buildOnInstanceConfiguredExtraParams;
-
- if (buildOnInstanceConfiguredExtraParams) {
- reactorObjectAssign(memo, buildOnInstanceConfiguredExtraParams({
- config: config,
- logger: logger
- }));
- }
-
- return memo;
- }, {});
- };
-
- var buildAndValidateConfig = (function (_ref2) {
- var options = _ref2.options,
- componentCreators = _ref2.componentCreators,
- coreConfigValidators = _ref2.coreConfigValidators,
- createConfig = _ref2.createConfig,
- logger = _ref2.logger,
- setDebugEnabled = _ref2.setDebugEnabled;
- var schema = buildSchema(coreConfigValidators, componentCreators);
- var config = createConfig(transformOptions(schema, options));
- setDebugEnabled(config.debugEnabled, {
- fromConfig: true
- }); // eslint-disable-next-line no-underscore-dangle
-
- var extraParams = buildAllOnInstanceConfiguredExtraParams(config, logger, componentCreators);
- logger.logOnInstanceConfigured(_objectSpread2(_objectSpread2({}, extraParams), {}, {
- config: config
- }));
- return config;
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var initializeComponents = (function (_ref) {
- var componentCreators = _ref.componentCreators,
- lifecycle = _ref.lifecycle,
- componentRegistry = _ref.componentRegistry,
- getImmediatelyAvailableTools = _ref.getImmediatelyAvailableTools;
- componentCreators.forEach(function (createComponent) {
- var namespace = createComponent.namespace; // TO-DOCUMENT: Helpers that we inject into factories.
-
- var tools = getImmediatelyAvailableTools(namespace);
- var component;
-
- try {
- component = createComponent(tools);
- } catch (error) {
- throw stackError({
- error: error,
- message: "[" + namespace + "] An error occurred during component creation."
- });
- }
-
- componentRegistry.register(namespace, component);
- });
- return lifecycle.onComponentsRegistered({
- lifecycle: lifecycle
- }).then(function () {
- return componentRegistry;
- });
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var createConfig = function createConfig(options) {
- return reactorObjectAssign({}, options);
- };
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var EDGE = "edge.adobedc.net";
- var ID_THIRD_PARTY = "adobedc.demdex.net";
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var EDGE_BASE_PATH = "ee";
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createCoreConfigs = (function () {
- return {
- debugEnabled: boundBoolean().default(false),
- defaultConsent: boundEnumOf(IN, OUT, PENDING).default(IN),
- edgeConfigId: boundString().unique().required(),
- edgeDomain: boundString().domain().default(EDGE),
- edgeBasePath: boundString().nonEmpty().default(EDGE_BASE_PATH),
- orgId: boundString().unique().required(),
- onBeforeEventSend: boundCallback().default(noop$1),
- edgeConfigOverrides: validateConfigOverride
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectHandleError = (function (_ref) {
- var errorPrefix = _ref.errorPrefix,
- logger = _ref.logger;
- return function (error, operation) {
- var err = toError(error); // In the case of declined consent, we've opted to not reject the promise
- // returned to the customer, but instead resolve the promise with an
- // empty result object.
-
- if (err.code === DECLINED_CONSENT_ERROR_CODE) {
- logger.warn("The " + operation + " could not fully complete. " + err.message);
- return {};
- }
-
- updateErrorMessage({
- error: err,
- message: errorPrefix + " " + err.message
- });
- throw err;
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectSendFetchRequest = (function (_ref) {
- var fetch = _ref.fetch;
- return function (url, body) {
- return fetch(url, {
- method: "POST",
- cache: "no-cache",
- credentials: "include",
- // To set the cookie header in the request.
- headers: {
- "Content-Type": "text/plain; charset=UTF-8"
- },
- referrerPolicy: "no-referrer-when-downgrade",
- body: body
- }).then(function (response) {
- return response.text().then(function (responseBody) {
- return {
- statusCode: response.status,
- // We expose headers through a function instead of creating an object
- // with all the headers up front largely because the native
- // request.getResponseHeader method is case-insensitive but also because it prevents
- // us from having to add header parsing logic when using XHR to make requests.
- getHeader: function getHeader(name) {
- return response.headers.get(name);
- },
- body: responseBody
- };
- });
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectSendXhrRequest = (function (_ref) {
- var XMLHttpRequest = _ref.XMLHttpRequest;
- return function (url, body) {
- return new Promise(function (resolve, reject) {
- var request = new XMLHttpRequest();
-
- request.onreadystatechange = function () {
- if (request.readyState === 4) {
- if (request.status === 0) {
- reject(new Error("Request aborted."));
- } else {
- resolve({
- statusCode: request.status,
- // We expose headers through a function instead of creating an object
- // with all the headers up front because:
- // 1. It avoids having to add header parsing code to get all headers.
- // 2. The native request.getResponseHeader method is case-insensitive.
- getHeader: function getHeader(name) {
- return request.getResponseHeader(name);
- },
- body: request.responseText
- });
- }
- }
- };
-
- request.onloadstart = function () {
- request.responseType = "text";
- };
-
- request.open("POST", url, true);
- request.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
- request.withCredentials = true;
- request.onerror = reject;
- request.onabort = reject;
- request.send(body);
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectSendBeaconRequest = (function (_ref) {
- var sendBeacon = _ref.sendBeacon,
- sendFetchRequest = _ref.sendFetchRequest,
- logger = _ref.logger;
- return function (url, body) {
- var blob = new Blob([body], {
- type: "text/plain; charset=UTF-8"
- });
-
- if (!sendBeacon(url, blob)) {
- logger.info("Unable to use `sendBeacon`; falling back to `fetch`.");
- return sendFetchRequest(url, body);
- } // Using sendBeacon, we technically don't get a response back from
- // the server, but we'll resolve the promise with an object to maintain
- // consistency with other network strategies.
-
-
- return Promise.resolve({
- statusCode: 204,
- getHeader: function getHeader() {
- return null;
- },
- body: ""
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createLogger = (function (_ref) {
- var getDebugEnabled = _ref.getDebugEnabled,
- console = _ref.console,
- getMonitors = _ref.getMonitors,
- context = _ref.context;
- var prefix = "[" + context.instanceName + "]";
-
- if (context.componentName) {
- prefix += " [" + context.componentName + "]";
- }
-
- var notifyMonitors = function notifyMonitors(method, data) {
- var monitors = getMonitors();
-
- if (monitors.length > 0) {
- var dataWithContext = reactorObjectAssign({}, context, data);
- monitors.forEach(function (monitor) {
- if (monitor[method]) {
- monitor[method](dataWithContext);
- }
- });
- }
- };
-
- var log = function log(level) {
- for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- rest[_key - 1] = arguments[_key];
- }
-
- notifyMonitors("onBeforeLog", {
- level: level,
- arguments: rest
- });
-
- if (getDebugEnabled()) {
- console[level].apply(console, [prefix].concat(rest));
- }
- };
-
- return {
- get enabled() {
- return getMonitors().length > 0 || getDebugEnabled();
- },
-
- logOnInstanceCreated: function logOnInstanceCreated(data) {
- notifyMonitors("onInstanceCreated", data);
- log("info", "Instance initialized.");
- },
- logOnInstanceConfigured: function logOnInstanceConfigured(data) {
- notifyMonitors("onInstanceConfigured", data);
- log("info", "Instance configured. Computed configuration:", data.config);
- },
- logOnBeforeCommand: function logOnBeforeCommand(data) {
- notifyMonitors("onBeforeCommand", data);
- log("info", "Executing " + data.commandName + " command. Options:", data.options);
- },
- logOnCommandResolved: function logOnCommandResolved(data) {
- notifyMonitors("onCommandResolved", data);
- log("info", data.commandName + " command resolved. Result:", data.result);
- },
- logOnCommandRejected: function logOnCommandRejected(data) {
- notifyMonitors("onCommandRejected", data);
- log("error", data.commandName + " command was rejected. Error:", data.error);
- },
- logOnBeforeNetworkRequest: function logOnBeforeNetworkRequest(data) {
- notifyMonitors("onBeforeNetworkRequest", data);
- log("info", "Request " + data.requestId + ": Sending request.", data.payload);
- },
- logOnNetworkResponse: function logOnNetworkResponse(data) {
- notifyMonitors("onNetworkResponse", data);
- var messagesSuffix = data.parsedBody || data.body ? "response body:" : "no response body.";
- log("info", "Request " + data.requestId + ": Received response with status code " + data.statusCode + " and " + messagesSuffix, data.parsedBody || data.body);
- },
- logOnNetworkError: function logOnNetworkError(data) {
- notifyMonitors("onNetworkError", data);
- log("error", "Request " + data.requestId + ": Network request failed.", data.error);
- },
-
- /**
- * Outputs informational message to the web console. In some
- * browsers a small "i" icon is displayed next to these items
- * in the web console's log.
- * @param {...*} arg Any argument to be logged.
- */
- info: log.bind(null, "info"),
-
- /**
- * Outputs a warning message to the web console.
- * @param {...*} arg Any argument to be logged.
- */
- warn: log.bind(null, "warn"),
-
- /**
- * Outputs an error message to the web console.
- * @param {...*} arg Any argument to be logged.
- */
- error: log.bind(null, "error")
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var EVENT_CANCELLATION_MESSAGE = "Event was canceled because the onBeforeEventSend callback returned false.";
- var createEventManager = (function (_ref) {
- var config = _ref.config,
- logger = _ref.logger,
- lifecycle = _ref.lifecycle,
- consent = _ref.consent,
- createEvent = _ref.createEvent,
- createDataCollectionRequestPayload = _ref.createDataCollectionRequestPayload,
- createDataCollectionRequest = _ref.createDataCollectionRequest,
- sendEdgeNetworkRequest = _ref.sendEdgeNetworkRequest,
- _applyResponse = _ref.applyResponse;
- var onBeforeEventSend = config.onBeforeEventSend,
- globalConfigOverrides = config.edgeConfigOverrides;
- return {
- createEvent: createEvent,
-
- /**
- * Sends an event. This includes running the event and payload through
- * the appropriate lifecycle hooks, sending the request to the server,
- * and handling the response.
- * @param {Object} event This will be JSON stringified and used inside
- * the request payload.
- * @param {Object} [options]
- * @param {boolean} [options.renderDecisions=false]
- * @param {Array} [options.decisionScopes] Note: this option will soon
- * be deprecated, please use *personalization.decisionScopes* instead
- * @param {Object} [options.personalization]
- * @param {Object} [options.serverState]
- * This will be passed to components
- * so they can take appropriate action.
- * @returns {*}
- */
- sendEvent: function sendEvent(event) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var _options$renderDecisi = options.renderDecisions,
- renderDecisions = _options$renderDecisi === void 0 ? false : _options$renderDecisi,
- decisionScopes = options.decisionScopes,
- localConfigOverrides = options.edgeConfigOverrides,
- personalization = options.personalization;
- var payload = createDataCollectionRequestPayload();
- var request = createDataCollectionRequest(payload);
- var onResponseCallbackAggregator = createCallbackAggregator();
- var onRequestFailureCallbackAggregator = createCallbackAggregator();
- payload.mergeConfigOverride(globalConfigOverrides);
- payload.mergeConfigOverride(localConfigOverrides);
- return lifecycle.onBeforeEvent({
- event: event,
- renderDecisions: renderDecisions,
- decisionScopes: decisionScopes,
- personalization: personalization,
- onResponse: onResponseCallbackAggregator.add,
- onRequestFailure: onRequestFailureCallbackAggregator.add
- }).then(function () {
- payload.addEvent(event);
- return consent.awaitConsent();
- }).then(function () {
- try {
- // NOTE: this calls onBeforeEventSend callback (if configured)
- event.finalize(onBeforeEventSend);
- } catch (error) {
- var throwError = function throwError() {
- throw error;
- };
-
- onRequestFailureCallbackAggregator.add(lifecycle.onRequestFailure);
- return onRequestFailureCallbackAggregator.call({
- error: error
- }).then(throwError, throwError);
- } // if the callback returns false, the event should not be sent
-
-
- if (!event.shouldSend()) {
- onRequestFailureCallbackAggregator.add(lifecycle.onRequestFailure);
- logger.info(EVENT_CANCELLATION_MESSAGE);
- var error = new Error(EVENT_CANCELLATION_MESSAGE);
- return onRequestFailureCallbackAggregator.call({
- error: error
- }).then(function () {// Ensure the promise gets resolved with undefined instead
- // of an array of return values from the callbacks.
- });
- }
-
- return sendEdgeNetworkRequest({
- request: request,
- runOnResponseCallbacks: onResponseCallbackAggregator.call,
- runOnRequestFailureCallbacks: onRequestFailureCallbackAggregator.call
- });
- });
- },
- applyResponse: function applyResponse(event) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var _options$renderDecisi2 = options.renderDecisions,
- renderDecisions = _options$renderDecisi2 === void 0 ? false : _options$renderDecisi2,
- _options$responseHead = options.responseHeaders,
- responseHeaders = _options$responseHead === void 0 ? {} : _options$responseHead,
- _options$responseBody = options.responseBody,
- responseBody = _options$responseBody === void 0 ? {
- handle: []
- } : _options$responseBody;
- var payload = createDataCollectionRequestPayload();
- var request = createDataCollectionRequest(payload);
- var onResponseCallbackAggregator = createCallbackAggregator();
- return lifecycle.onBeforeEvent({
- event: event,
- renderDecisions: renderDecisions,
- decisionScopes: [PAGE_WIDE_SCOPE],
- personalization: {},
- onResponse: onResponseCallbackAggregator.add,
- onRequestFailure: noop$1
- }).then(function () {
- payload.addEvent(event);
- return _applyResponse({
- request: request,
- responseHeaders: responseHeaders,
- responseBody: responseBody,
- runOnResponseCallbacks: onResponseCallbackAggregator.call
- });
- });
- }
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var STATE_STORE_HANDLE_TYPE = "state:store";
- var createCookieTransfer = (function (_ref) {
- var cookieJar = _ref.cookieJar,
- shouldTransferCookie = _ref.shouldTransferCookie,
- apexDomain = _ref.apexDomain,
- dateProvider = _ref.dateProvider;
- return {
- /**
- * When sending to a third-party endpoint, the endpoint won't be able to
- * access first-party cookies, therefore we transfer cookies into
- * the request body so they can be read by the server.
- */
- cookiesToPayload: function cookiesToPayload(payload, endpointDomain) {
- var isEndpointFirstParty = endsWith(endpointDomain, apexDomain);
- var state = {
- domain: apexDomain,
- cookiesEnabled: true
- }; // If the endpoint is first-party, there's no need to transfer cookies
- // to the payload since they'll be automatically passed through cookie
- // headers.
-
- if (!isEndpointFirstParty) {
- var cookies = cookieJar.get();
- var entries = Object.keys(cookies).filter(shouldTransferCookie).map(function (qualifyingCookieName) {
- return {
- key: qualifyingCookieName,
- value: cookies[qualifyingCookieName]
- };
- });
-
- if (entries.length) {
- state.entries = entries;
- }
- }
-
- payload.mergeState(state);
- },
-
- /**
- * When receiving from a third-party endpoint, the endpoint won't be able to
- * write first-party cookies, therefore we write first-party cookies
- * as directed in the response body.
- */
- responseToCookies: function responseToCookies(response) {
- response.getPayloadsByType(STATE_STORE_HANDLE_TYPE).forEach(function (stateItem) {
- var options = {
- domain: apexDomain
- };
- var sameSite = stateItem.attrs && stateItem.attrs.SameSite && stateItem.attrs.SameSite.toLowerCase();
-
- if (stateItem.maxAge !== undefined) {
- // cookieJar expects "expires" as a date object
- options.expires = new Date(dateProvider().getTime() + stateItem.maxAge * 1000);
- }
-
- if (sameSite !== undefined) {
- options.sameSite = sameSite;
- } // When sameSite is set to none, the secure flag must be set.
- // Experience edge will not set the secure flag in these cases.
-
-
- if (sameSite === "none") {
- options.secure = true;
- }
-
- cookieJar.set(stateItem.key, stateItem.value, options);
- });
- }
- };
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var MBOX_EDGE_CLUSTER = "mboxEdgeCluster";
- var AT_QA_MODE = "at_qa_mode";
- var MBOX = "mbox";
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectShouldTransferCookie = (function (_ref) {
- var orgId = _ref.orgId,
- targetMigrationEnabled = _ref.targetMigrationEnabled;
- return function (name) {
- // We have a contract with the server that we will pass
- // all cookies whose names are namespaced according to the
- // logic in isNamespacedCookieName as well as any legacy
- // cookie names (so that the server can handle migrating
- // identities on websites previously using Visitor.js)
- return isNamespacedCookieName(orgId, name) || name === AT_QA_MODE || targetMigrationEnabled && name === MBOX;
- };
- });
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var apiVersion = "v1";
-
- var mergeLifecycleResponses = (function (returnValues) {
- // Merges all returned objects from all `onResponse` callbacks into
- // a single object that can later be returned to the customer.
- var lifecycleOnResponseReturnValues = returnValues.shift() || [];
- var consumerOnResponseReturnValues = returnValues.shift() || [];
- var lifecycleOnBeforeRequestReturnValues = returnValues;
- return reactorObjectAssign.apply(void 0, [{}].concat(_toConsumableArray(lifecycleOnResponseReturnValues), _toConsumableArray(consumerOnResponseReturnValues), _toConsumableArray(lifecycleOnBeforeRequestReturnValues)));
- });
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var handleRequestFailure = (function (onRequestFailureCallbackAggregator) {
- return function (error) {
- // Regardless of whether the network call failed, an unexpected status
- // code was returned, or the response body was malformed, we want to call
- // the onRequestFailure callbacks, but still throw the exception.
- var throwError = function throwError() {
- throw error;
- };
-
- return onRequestFailureCallbackAggregator.call({
- error: error
- }).then(throwError, throwError);
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectSendEdgeNetworkRequest = (function (_ref) {
- var config = _ref.config,
- lifecycle = _ref.lifecycle,
- cookieTransfer = _ref.cookieTransfer,
- sendNetworkRequest = _ref.sendNetworkRequest,
- createResponse = _ref.createResponse,
- processWarningsAndErrors = _ref.processWarningsAndErrors,
- getLocationHint = _ref.getLocationHint,
- getAssuranceValidationTokenParams = _ref.getAssuranceValidationTokenParams;
- var edgeDomain = config.edgeDomain,
- edgeBasePath = config.edgeBasePath,
- edgeConfigId = config.edgeConfigId;
- /**
- * Sends a network request that is aware of payload interfaces,
- * lifecycle methods, configured edge domains, response structures, etc.
- */
-
- return function (_ref2) {
- var request = _ref2.request,
- _ref2$runOnResponseCa = _ref2.runOnResponseCallbacks,
- runOnResponseCallbacks = _ref2$runOnResponseCa === void 0 ? noop$1 : _ref2$runOnResponseCa,
- _ref2$runOnRequestFai = _ref2.runOnRequestFailureCallbacks,
- runOnRequestFailureCallbacks = _ref2$runOnRequestFai === void 0 ? noop$1 : _ref2$runOnRequestFai;
- var onResponseCallbackAggregator = createCallbackAggregator();
- onResponseCallbackAggregator.add(lifecycle.onResponse);
- onResponseCallbackAggregator.add(runOnResponseCallbacks);
- var onRequestFailureCallbackAggregator = createCallbackAggregator();
- onRequestFailureCallbackAggregator.add(lifecycle.onRequestFailure);
- onRequestFailureCallbackAggregator.add(runOnRequestFailureCallbacks);
- return lifecycle.onBeforeRequest({
- request: request,
- onResponse: onResponseCallbackAggregator.add,
- onRequestFailure: onRequestFailureCallbackAggregator.add
- }).then(function () {
- var endpointDomain = request.getUseIdThirdPartyDomain() ? ID_THIRD_PARTY : edgeDomain;
- var locationHint = getLocationHint();
- var edgeBasePathWithLocationHint = locationHint ? edgeBasePath + "/" + locationHint : edgeBasePath;
- var url = "https://" + endpointDomain + "/" + edgeBasePathWithLocationHint + "/" + apiVersion + "/" + request.getAction() + "?configId=" + edgeConfigId + "&requestId=" + request.getId() + getAssuranceValidationTokenParams();
- cookieTransfer.cookiesToPayload(request.getPayload(), endpointDomain);
- return sendNetworkRequest({
- requestId: request.getId(),
- url: url,
- payload: request.getPayload(),
- useSendBeacon: request.getUseSendBeacon()
- });
- }).then(function (networkResponse) {
- processWarningsAndErrors(networkResponse);
- return networkResponse;
- }).catch(handleRequestFailure(onRequestFailureCallbackAggregator)).then(function (_ref3) {
- var parsedBody = _ref3.parsedBody,
- getHeader = _ref3.getHeader;
- // Note that networkResponse.parsedBody may be undefined if it was a
- // 204 No Content response. That's fine.
- var response = createResponse({
- content: parsedBody,
- getHeader: getHeader
- });
- cookieTransfer.responseToCookies(response); // Notice we're calling the onResponse lifecycle method even if there are errors
- // inside the response body. This is because the full request didn't actually fail--
- // only portions of it that are considered non-fatal (a specific, non-critical
- // Konductor plugin, for example).
-
- return onResponseCallbackAggregator.call({
- response: response
- }).then(mergeLifecycleResponses);
- });
- };
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var NO_CONTENT = 204;
- var TOO_MANY_REQUESTS = 429;
- var BAD_GATEWAY = 502;
- var SERVICE_UNAVAILABLE = 503;
- var GATEWAY_TIMEOUT = 504;
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var MESSAGE_PREFIX = "The server responded with a";
- var injectProcessWarningsAndErrors = (function (_ref) {
- var logger = _ref.logger;
- return function (networkResponse) {
- var statusCode = networkResponse.statusCode,
- body = networkResponse.body,
- parsedBody = networkResponse.parsedBody;
-
- if (statusCode < 200 || statusCode >= 300 || !parsedBody && statusCode !== NO_CONTENT || parsedBody && !Array.isArray(parsedBody.handle)) {
- var bodyToLog = parsedBody ? JSON.stringify(parsedBody, null, 2) : body;
- var messageSuffix = bodyToLog ? "response body:\n" + bodyToLog : "no response body.";
- throw new Error(MESSAGE_PREFIX + " status code " + statusCode + " and " + messageSuffix);
- }
-
- if (parsedBody) {
- var _parsedBody$warnings = parsedBody.warnings,
- warnings = _parsedBody$warnings === void 0 ? [] : _parsedBody$warnings,
- _parsedBody$errors = parsedBody.errors,
- errors = _parsedBody$errors === void 0 ? [] : _parsedBody$errors;
- warnings.forEach(function (warning) {
- logger.warn(MESSAGE_PREFIX + " warning:", warning);
- });
- errors.forEach(function (error) {
- logger.error(MESSAGE_PREFIX + " non-fatal error:", error);
- });
- }
- };
- });
-
- /*
- Copyright 2022 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var injectGetLocationHint = (function (_ref) {
- var orgId = _ref.orgId,
- cookieJar = _ref.cookieJar;
- var clusterCookieName = getNamespacedCookieName(orgId, CLUSTER);
-
- var fromClusterCookie = function fromClusterCookie() {
- return cookieJar.get(clusterCookieName);
- };
-
- var fromTarget = function fromTarget() {
- var mboxEdgeCluster = cookieJar.get(MBOX_EDGE_CLUSTER);
-
- if (mboxEdgeCluster) {
- return "t" + mboxEdgeCluster;
- }
-
- return undefined;
- };
-
- return function () {
- return fromClusterCookie() || fromTarget();
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var MAX_RETRIES = 3;
- var RETRYABLE_STATUS_CODES = [TOO_MANY_REQUESTS, SERVICE_UNAVAILABLE, BAD_GATEWAY, GATEWAY_TIMEOUT]; // These rules are in accordance with
- // https://git.corp.adobe.com/pages/experience-edge/konductor/#/apis/errors?id=handling-4xx-and-5xx-responses
-
- var isRequestRetryable = (function (_ref) {
- var response = _ref.response,
- retriesAttempted = _ref.retriesAttempted;
- return retriesAttempted < MAX_RETRIES && includes(RETRYABLE_STATUS_CODES, response.statusCode);
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
-
- var FIRST_DELAY_MILLIS = 1000;
- var INCREMENTAL_DELAY_MILLIS = 1000; // When the target delay is randomized, make it within the range of this percentage above or below the target delay.
-
- var MAX_RANDOM_VARIANCE_PERCENTAGE = 0.3;
-
- var calculateRetryDelay = function calculateRetryDelay(retriesAttempted) {
- var targetDelay = FIRST_DELAY_MILLIS + retriesAttempted * INCREMENTAL_DELAY_MILLIS;
- var maxVariance = targetDelay * MAX_RANDOM_VARIANCE_PERCENTAGE;
- var minDelay = targetDelay - maxVariance;
- var maxDelay = targetDelay + maxVariance;
- var randomizedDelayWithinRange = Math.round(minDelay + Math.random() * (maxDelay - minDelay));
- return randomizedDelayWithinRange;
- };
-
- var getDelayFromHeader = function getDelayFromHeader(response) {
- // According to the HTTP spec, if the header is defined, its value will be a string that
- // represents either:
- // * An integer indicating the number of seconds to delay.
- // * A date after which a retry may occur. The date would be in HTTP-date
- // format (https://tools.ietf.org/html/rfc7231#section-7.1.1.1). When debugging, it can
- // be helpful to know that this is the same format that a JavaScript date's
- // toGMTString() returns.
- var headerValue = response.getHeader(RETRY_AFTER);
- var delayInMillis;
-
- if (headerValue) {
- var headerValueInt = parseInt(headerValue, 10);
-
- if (isInteger(headerValueInt)) {
- delayInMillis = headerValueInt * 1000;
- } else {
- delayInMillis = Math.max(0, new Date(headerValue).getTime() - new Date().getTime());
- }
- }
-
- return delayInMillis;
- }; // These rules are in accordance with
- // https://git.corp.adobe.com/pages/experience-edge/konductor/#/apis/errors?id=handling-4xx-and-5xx-responses
- // For retry delays that don't come from a Retry-After response header, we try to stick with the following best
- // practices outlined in https://docs.microsoft.com/en-us/azure/architecture/best-practices/transient-faults:
- // * Incremental retry
- // * Random interval
-
-
- var getRequestRetryDelay = (function (_ref) {
- var response = _ref.response,
- retriesAttempted = _ref.retriesAttempted;
- // Technically, only 429 or 503 responses should have a Retry-After header, but we'll respect the
- // header if we find it on any response.
- var delayInMillis = getDelayFromHeader(response); // Note that the value of delay may be 0 at this point, which would be a valid delay we want to use
- // and not override, which is why we don't do:
- // if (!delay) { ... }
-
- if (delayInMillis === undefined) {
- delayInMillis = calculateRetryDelay(retriesAttempted);
- }
-
- return delayInMillis;
- });
-
- /*
- Copyright 2023 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var HTTP_STATUS_OK = 200;
- var injectApplyResponse = (function (_ref) {
- var cookieTransfer = _ref.cookieTransfer,
- lifecycle = _ref.lifecycle,
- createResponse = _ref.createResponse,
- processWarningsAndErrors = _ref.processWarningsAndErrors;
- return function (_ref2) {
- var request = _ref2.request,
- responseHeaders = _ref2.responseHeaders,
- responseBody = _ref2.responseBody,
- _ref2$runOnResponseCa = _ref2.runOnResponseCallbacks,
- runOnResponseCallbacks = _ref2$runOnResponseCa === void 0 ? noop$1 : _ref2$runOnResponseCa,
- _ref2$runOnRequestFai = _ref2.runOnRequestFailureCallbacks,
- runOnRequestFailureCallbacks = _ref2$runOnRequestFai === void 0 ? noop$1 : _ref2$runOnRequestFai;
- var onResponseCallbackAggregator = createCallbackAggregator();
- onResponseCallbackAggregator.add(lifecycle.onResponse);
- onResponseCallbackAggregator.add(runOnResponseCallbacks);
- var onRequestFailureCallbackAggregator = createCallbackAggregator();
- onRequestFailureCallbackAggregator.add(lifecycle.onRequestFailure);
- onRequestFailureCallbackAggregator.add(runOnRequestFailureCallbacks);
-
- var getHeader = function getHeader(key) {
- return responseHeaders[key];
- };
-
- return lifecycle.onBeforeRequest({
- request: request,
- onResponse: onResponseCallbackAggregator.add,
- onRequestFailure: onRequestFailureCallbackAggregator.add
- }).then(function () {
- return processWarningsAndErrors({
- statusCode: HTTP_STATUS_OK,
- getHeader: getHeader,
- body: JSON.stringify(responseBody),
- parsedBody: responseBody
- });
- }).catch(handleRequestFailure(onRequestFailureCallbackAggregator)).then(function () {
- var response = createResponse({
- content: responseBody,
- getHeader: getHeader
- }); // This will clobber any cookies set via HTTP from the server. So care should be given to remove any state:store handles if that is not desirable
-
- cookieTransfer.responseToCookies(response);
- return onResponseCallbackAggregator.call({
- response: response
- }).then(mergeLifecycleResponses);
- });
- };
- });
-
- /*
- Copyright 2019 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- var createNamespacedStorage = injectStorage(window);
- var _window = window,
- console$1 = _window.console,
- fetch = _window.fetch,
- navigator$1 = _window.navigator,
- XMLHttpRequest = _window.XMLHttpRequest; // set this up as a function so that monitors can be added at anytime
- // eslint-disable-next-line no-underscore-dangle
-
- var getMonitors = function getMonitors() {
- return window.__alloyMonitors || [];
- };
-
- var coreConfigValidators = createCoreConfigs();
- var apexDomain = getApexDomain(window, cookieJar);
- var sendFetchRequest = isFunction(fetch) ? injectSendFetchRequest({
- fetch: fetch
- }) : injectSendXhrRequest({
- XMLHttpRequest: XMLHttpRequest
- });
- var fireReferrerHideableImage = injectFireReferrerHideableImage();
- var getAssuranceValidationTokenParams = createGetAssuranceValidationTokenParams({
- window: window,
- createNamespacedStorage: createNamespacedStorage
- });
- var createExecuteCommand = function createExecuteCommand(_ref) {
- var instanceName = _ref.instanceName,
- _ref$logController = _ref.logController,
- setDebugEnabled = _ref$logController.setDebugEnabled,
- logger = _ref$logController.logger,
- createComponentLogger = _ref$logController.createComponentLogger;
- var componentRegistry = createComponentRegistry();
- var lifecycle = createLifecycle(componentRegistry);
-
- var setDebugCommand = function setDebugCommand(options) {
- setDebugEnabled(options.enabled, {
- fromConfig: false
- });
- };
-
- var loggingCookieJar = createLoggingCookieJar({
- logger: logger,
- cookieJar: cookieJar
- });
-
- var configureCommand = function configureCommand(options) {
- var config = buildAndValidateConfig({
- options: options,
- componentCreators: componentCreators,
- coreConfigValidators: coreConfigValidators,
- createConfig: createConfig,
- logger: logger,
- setDebugEnabled: setDebugEnabled
- });
- var orgId = config.orgId,
- targetMigrationEnabled = config.targetMigrationEnabled;
- var shouldTransferCookie = injectShouldTransferCookie({
- orgId: orgId,
- targetMigrationEnabled: targetMigrationEnabled
- });
- var cookieTransfer = createCookieTransfer({
- cookieJar: loggingCookieJar,
- shouldTransferCookie: shouldTransferCookie,
- apexDomain: apexDomain,
- dateProvider: function dateProvider() {
- return new Date();
- }
- });
- var sendBeaconRequest = isFunction(navigator$1.sendBeacon) ? injectSendBeaconRequest({
- // Without the bind(), the browser will complain about an
- // illegal invocation.
- sendBeacon: navigator$1.sendBeacon.bind(navigator$1),
- sendFetchRequest: sendFetchRequest,
- logger: logger
- }) : sendFetchRequest;
- var sendNetworkRequest = injectSendNetworkRequest({
- logger: logger,
- sendFetchRequest: sendFetchRequest,
- sendBeaconRequest: sendBeaconRequest,
- isRequestRetryable: isRequestRetryable,
- getRequestRetryDelay: getRequestRetryDelay
- });
- var processWarningsAndErrors = injectProcessWarningsAndErrors({
- logger: logger
- });
- var extractEdgeInfo = injectExtractEdgeInfo({
- logger: logger
- });
- var createResponse = injectCreateResponse({
- extractEdgeInfo: extractEdgeInfo
- });
- var getLocationHint = injectGetLocationHint({
- orgId: orgId,
- cookieJar: cookieJar
- });
- var sendEdgeNetworkRequest = injectSendEdgeNetworkRequest({
- config: config,
- lifecycle: lifecycle,
- cookieTransfer: cookieTransfer,
- sendNetworkRequest: sendNetworkRequest,
- createResponse: createResponse,
- processWarningsAndErrors: processWarningsAndErrors,
- getLocationHint: getLocationHint,
- getAssuranceValidationTokenParams: getAssuranceValidationTokenParams
- });
- var applyResponse = injectApplyResponse({
- lifecycle: lifecycle,
- cookieTransfer: cookieTransfer,
- createResponse: createResponse,
- processWarningsAndErrors: processWarningsAndErrors
- });
- var generalConsentState = createConsentStateMachine({
- logger: logger
- });
- var consent = createConsent({
- generalConsentState: generalConsentState,
- logger: logger
- });
- var eventManager = createEventManager({
- config: config,
- logger: logger,
- lifecycle: lifecycle,
- consent: consent,
- createEvent: createEvent,
- createDataCollectionRequestPayload: createDataCollectionRequestPayload,
- createDataCollectionRequest: createDataCollectionRequest,
- sendEdgeNetworkRequest: sendEdgeNetworkRequest,
- applyResponse: applyResponse
- });
- return initializeComponents({
- componentCreators: componentCreators,
- lifecycle: lifecycle,
- componentRegistry: componentRegistry,
- getImmediatelyAvailableTools: function getImmediatelyAvailableTools(componentName) {
- var componentLogger = createComponentLogger(componentName);
- return {
- config: config,
- componentRegistry: componentRegistry,
- consent: consent,
- eventManager: eventManager,
- fireReferrerHideableImage: fireReferrerHideableImage,
- logger: componentLogger,
- lifecycle: lifecycle,
- sendEdgeNetworkRequest: sendEdgeNetworkRequest,
- handleError: injectHandleError({
- errorPrefix: "[" + instanceName + "] [" + componentName + "]",
- logger: componentLogger
- }),
- createNamespacedStorage: createNamespacedStorage,
- apexDomain: apexDomain
- };
- }
- });
- };
-
- var handleError = injectHandleError({
- errorPrefix: "[" + instanceName + "]",
- logger: logger
- });
- var executeCommand = injectExecuteCommand({
- logger: logger,
- configureCommand: configureCommand,
- setDebugCommand: setDebugCommand,
- handleError: handleError,
- validateCommandOptions: validateCommandOptions
- });
- return executeCommand;
- };
- var core = (function () {
- // eslint-disable-next-line no-underscore-dangle
- var instanceNames = window.__alloyNS;
-
- if (instanceNames) {
- instanceNames.forEach(function (instanceName) {
- var logController = createLogController({
- console: console$1,
- locationSearch: window.location.search,
- createLogger: createLogger,
- instanceName: instanceName,
- createNamespacedStorage: createNamespacedStorage,
- getMonitors: getMonitors
- });
- var executeCommand = createExecuteCommand({
- instanceName: instanceName,
- logController: logController
- });
- var instance = createInstanceFunction(executeCommand);
- var queue = window[instanceName].q;
- queue.push = instance;
- logController.logger.logOnInstanceCreated({
- instance: instance
- });
- queue.forEach(instance);
- });
- }
- });
-
- /*
- Copyright 2020 Adobe. All rights reserved.
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- OF ANY KIND, either express or implied. See the License for the specific language
- governing permissions and limitations under the License.
- */
- core();
-
-})();
diff --git a/scripts/analytics/alloy.min.js b/scripts/analytics/alloy.min.js
deleted file mode 100644
index aacf2bf3..00000000
--- a/scripts/analytics/alloy.min.js
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Copyright 2019 Adobe. All rights reserved.
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License. You may obtain a copy
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
- * OF ANY KIND, either express or implied. See the License for the specific language
- * governing permissions and limitations under the License.
- */
-
-!function(){"use strict";if(document.documentMode&&document.documentMode<11)console.warn("The Adobe Experience Cloud Web SDK does not support IE 10 and below.");else{var e="Chrome",n="Edge",t="EdgeChromium",r="Unknown",o=function(e,n){return-1!==e.indexOf(n)},i=[e,n,t,"IE",r],a=function(e){return o(i,e)},c=Object.getOwnPropertySymbols,u=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,d=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var n={},t=0;t<10;t++)n["_"+String.fromCharCode(t)]=t;if("0123456789"!==Object.getOwnPropertyNames(n).map((function(e){return n[e]})).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach((function(e){r[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(e,n){for(var t,r,o=Ci(e),i=1;i1?t-1:0),o=1;o>>1:t>>>1;e.push(t)}return function(n,t){n=unescape(encodeURIComponent(n)),t||(t=0),t^=-1;for(var r=0;r>>8^e[o]}return(t^=-1)>>>0}}(),I=function(){var e={};return e.promise=new Promise((function(n,t){e.resolve=n,e.reject=t})),e},D=function(e,n){for(var t=0;t1&&void 0!==arguments[1]?arguments[1]:{},t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:document,i=o.createElement(e);return Object.keys(n).forEach((function(e){i.setAttribute(e,n[e])})),k(i,t),r.forEach((function(e){return R(i,e)})),i},O="BODY",P="IFRAME",x="IMG",q="STYLE",N="SCRIPT",A=function(e){var n=e.src,t=e.currentDocument,r=void 0===t?document:t;return new Promise((function(e,t){S(x,{src:n},{onload:e,onerror:t,onabort:t},[],r)}))},M=function(e){return"function"==typeof e},T=function(e){return Array.isArray(e)&&e.length>0},j=function(e){return Array.isArray(e)?e:null==e?[]:[].slice.call(e)},U=/^\s*>/,L=function(e,n){if(!U.test(n))return j(e.querySelectorAll(n));var t="alloy-"+Date.now();try{return e.classList.add(t),j(e.querySelectorAll("."+t+" "+n))}finally{e.classList.remove(t)}},B=function(e,n){return e.substr(0,n.length)===n},F=":shadow",_=function(e,n){var t=n.trim();return B(t,">")?window.document.documentMode?t.substring(1).trim():(e instanceof Element||e instanceof HTMLDocument?":scope":":host")+" "+t:t},H=function(e,n){if(!window.document.documentElement.attachShadow)return L(e,n.replace(F,""));var t=function(e){return e.split(F)}(n);if(t.length<2)return L(e,n);for(var r=e,o=0;o1&&void 0!==arguments[1]?arguments[1]:document;return V(e)?H(n,e):L(n,e)},J={childList:!0,subtree:!0},W=function(e){return new Error("Could not find: "+e)},Q=function(e){return new Promise(e)},X=function(e){return M(e.MutationObserver)},$=function(e,n,t,r,o){return Q((function(i,a){var c=new e.MutationObserver((function(){var e=o(t);T(e)&&(c.disconnect(),i(e))}));setTimeout((function(){c.disconnect(),a(W(t))}),r),c.observe(n,J)}))},Y=function(e){return"visible"===e.visibilityState},G=function(e,n,t,r){return Q((function(o,i){!function t(){var i=r(n);T(i)?o(i):e.requestAnimationFrame(t)}(),setTimeout((function(){i(W(n))}),t)}))},K=function(e,n,t){return Q((function(r,o){!function n(){var o=t(e);T(o)?r(o):setTimeout(n,100)}(),setTimeout((function(){o(W(e))}),n)}))},Z=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:z,t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:5e3,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:window,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:document,i=n(e);return T(i)?Promise.resolve(i):X(r)?$(r,o,e,t,n):Y(o)?G(r,e,t,n):K(e,t,n)},ee=function(e){var n=e.parentNode;return n?n.removeChild(e):null},ne={name:"Adobe Alloy"},te={style:{display:"none",width:0,height:0}},re=function(e){return m(e)&&0===Object.keys(e).length},oe=function e(n,t){return v(n)||!m(n)?n:Object.keys(n).reduce((function(r,o){var i=n[o];if(m(i)){var a=e(i,t);return re(a)?r:Di(Di({},r),{},ki({},o,a))}return t(i)?Di(Di({},r),{},ki({},o,i)):r}),{})},ie=function(e,n){return Array.prototype.concat.apply([],e.map(n))},ae="com.adobe.alloy.",ce=ae+"getTld",ue=function(e){return e.replace("@","_")},se=function(e,n){return"kndctr_"+ue(e)+"_"+n},de=function(e){var n=e.orgId,t=se(n,"identity");return function(){return Boolean(p.get(t))}},fe=function(e,n,t){return{getItem:function(r){try{return e[n].getItem(t+r)}catch(e){return null}},setItem:function(r,o){try{return e[n].setItem(t+r,o),!0}catch(e){return!1}},clear:function(){try{return Object.keys(e[n]).forEach((function(r){B(r,t)&&e[n].removeItem(r)})),!0}catch(e){return!1}}}},le=function(e,n){return e.filter((function(e){return o(n,e)}))},ge=function(e){return"boolean"==typeof e},pe=function(e){return"number"==typeof e&&!isNaN(e)},ve=function(e){var n=parseInt(e,10);return pe(n)&&e===n},me=function(e){return"string"==typeof e},he=function(e){return me(e)&&e.length>0},ye=function(){},we=function(e,n,t){var r=String(e),o=String(t);if(r.length>=n||0===o.length)return r;for(var i=n-r.length;i>o.length;)o+=o;return o.slice(0,i)+r},be=function(e){if(v(e)||"object"!==Ri(e))return null;var n=oe(e,(function(e){return!v(e)&&(!!ge(e)||(!!pe(e)||(!!he(e)||!!T(e))))}));return re(n)?null:n},Ce=function(e,n,t,r){n=n||"&",t=t||"=";var o={};if("string"!=typeof e||0===e.length)return o;var i=/\+/g;e=e.split(n);var a=1e3;r&&"number"==typeof r.maxKeys&&(a=r.maxKeys);var c=e.length;a>0&&c>a&&(c=a);for(var u=0;u=0?(s=g.substr(0,p),d=g.substr(p+1)):(s=g,d=""),f=decodeURIComponent(s),l=decodeURIComponent(d),Ni(o,f)?Array.isArray(o[f])?o[f].push(l):o[f]=[o[f],l]:o[f]=l}return o},Ee=function(e){switch(Ri(e)){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}},Ie=function(e,n,t,r){return n=n||"&",t=t||"=",null===e&&(e=void 0),"object"===Ri(e)?Object.keys(e).map((function(r){var o=encodeURIComponent(Ee(r))+t;return Array.isArray(e[r])?e[r].map((function(e){return o+encodeURIComponent(Ee(e))})).join(n):o+encodeURIComponent(Ee(e[r]))})).join(n):r?encodeURIComponent(Ee(r))+t+encodeURIComponent(Ee(e)):""},De=Ei((function(e,n){n.decode=n.parse=Ce,n.encode=n.stringify=Ie}));De.decode,De.parse,De.encode,De.stringify;for(var Re=function(e){return"string"==typeof e&&(e=e.trim().replace(/^[?#&]/,"")),De.parse(e)},ke=function(e){return De.stringify(e)},Se=function(e){return e instanceof Error?e:new Error(e)},Oe=function(e){var n=e.error,t=e.message;try{n.message=t}catch(e){}},Pe=function(e){var n=e.error,t=e.message,r=Se(n),o=t+"\nCaused by: "+r.message;return Oe({error:r,message:o}),r},xe=function(e,n){if(pe(e)||me(e)){var t=Math.round(Number(e));if(!isNaN(t))return t}return n},qe=Ei((function(e){var n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(n){var t=new Uint8Array(16);e.exports=function(){return n(t),t}}else{var r=new Array(16);e.exports=function(){for(var e,n=0;n<16;n++)0==(3&n)&&(e=4294967296*Math.random()),r[n]=e>>>((3&n)<<3)&255;return r}}})),Ne=[],Ae=0;Ae<256;++Ae)Ne[Ae]=(Ae+256).toString(16).substr(1);var Me=function(e,n){var t=n||0,r=Ne;return[r[e[t++]],r[e[t++]],r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],r[e[t++]],r[e[t++]],r[e[t++]],r[e[t++]]].join("")},Te=function(e,n,t){var r=n&&t||0;"string"==typeof e&&(n="binary"===e?new Array(16):null,e=null);var o=(e=e||{}).random||(e.rng||qe)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,n)for(var i=0;i<16;++i)n[r+i]=o[i];return n||Me(o)},je=function(e,n){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=function(t,r){return n(e(t,r),r)};return f(r,e,t),r},Ue=function(e,n,t){return je(e,(function(e,t){return null==e?e:n(e,t)}),t)},Le=function(e,n,t,r){if(!e)throw new Error("'"+t+"': Expected "+r+", but got "+JSON.stringify(n)+".")},Be=function(e,n){return Le(ge(e),e,n,"true or false"),e},Fe=function(e,n){return Le(M(e),e,n,"a function"),e},_e=function(e,n){return function(t,r){return Le(t>=n,t,r,e+" greater than or equal to "+n),t}},He=function(e){return function(n,t){return m(n)?Le(!re(n),n,t,e):Le(n.length>0,n,t,e),n}},Ve=function(){return function(e,n){Le(function(e){for(var n=Object.create(null),t=0;t1&&void 0!==arguments[1]?arguments[1]:{},r=le(Object.keys(n),Object.keys(t));if(r.length)throw new Error("[ComponentRegistry] Could not register "+e+" because it has existing command(s): "+r.join(","));Object.keys(t).forEach((function(r){var o=t[r];o.commandName=r,o.run=Dn(o.run,"["+e+"] An error occurred while executing the "+r+" command."),n[r]=o}))}(r,i),function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Object.keys(n).forEach((function(r){t[r]=t[r]||[],t[r].push(Dn(n[r],"["+e+"] An error occurred while executing the "+r+" lifecycle hook."))}))}(r,a),e[r]=o},getCommand:function(e){return n[e]},getCommandNames:function(){return Object.keys(n)},getLifecycleCallbacks:function(e){return t[e]||[]}}},kn="in",Sn="pending",On="general",Pn="declinedConsent",xn="default",qn="initial",Nn="new",An=function(e){var n=new Error(e);return n.code=Pn,n.message=e,n},Mn=function(e){var n=e.logger,t=[],r=function(){return Promise.resolve()},o=function(){return Promise.resolve()},i=function(){return Promise.reject(An("No consent preferences have been set."))},a=function(){return Promise.reject(An("The user declined consent."))},c=function(e){if(e)return Promise.reject(new Error("Consent is pending."));var n=I();return t.push(n),n.promise};return{in:function(e){e===xn?this.awaitConsent=r:(e===qn?n.info("Loaded user consent preferences. The user previously consented."):e===Nn&&this.awaitConsent!==o&&n.info("User consented."),function(){for(;t.length;)t.shift().resolve()}(),this.awaitConsent=o)},out:function(e){e===xn?(n.warn("User consent preferences not found. Default consent of out will be used."),this.awaitConsent=i):(e===qn?n.warn("Loaded user consent preferences. The user previously declined consent."):e===Nn&&this.awaitConsent!==a&&n.warn("User declined consent."),function(){for(;t.length;)t.shift().reject(An("The user declined consent."))}(),this.awaitConsent=a)},pending:function(e){e===xn&&n.info("User consent preferences not found. Default consent of pending will be used. Some commands may be delayed."),this.awaitConsent=c},awaitConsent:function(){return Promise.reject(new Error("Consent has not been initialized."))},withConsent:function(){return this.awaitConsent(!0)}}},Tn=function(){var e,n,t={},r=!1,o=!1,i=!0,a=function(e){if(o)throw new Error(e+" cannot be called after event is finalized.")},c={setUserXdm:function(n){a("setUserXdm"),e=n},setUserData:function(e){a("setUserData"),n=e},mergeXdm:function(e){a("mergeXdm"),e&&y(t,{xdm:e})},mergeMeta:function(e){a("mergeMeta"),e&&y(t,{meta:e})},mergeQuery:function(e){a("mergeQuery"),e&&y(t,{query:e})},documentMayUnload:function(){r=!0},finalize:function(r){if(!o&&(e&&c.mergeXdm(e),n&&(t.data=n),o=!0,r)){i=!1;var a={xdm:t.xdm||{},data:t.data||{}},u=r(a);i=!1!==u,t.xdm=a.xdm||{},t.data=a.data||{},re(t.xdm)&&delete t.xdm,re(t.data)&&delete t.data}},getDocumentMayUnload:function(){return r},isEmpty:function(){return re(t)&&(!e||re(e))&&(!n||re(n))},shouldSend:function(){return i},getViewName:function(){if(e&&e.web&&e.web.webPageDetails)return e.web.webPageDetails.viewName},toJSON:function(){if(!o)throw new Error("toJSON called before finalize");return t}};return c},jn="configure",Un="setDebug",Ln=function(e){var n=e.command,t=e.options,r=n.commandName,o=n.documentationUri,i=void 0===o?"https://adobe.ly/3sHgQHb":o,a=n.optionsValidator,c=t;if(a)try{c=a(t)}catch(e){throw new Error("Invalid "+r+" command options:\n\t - "+e+" For command documentation see: "+i)}return c},Bn=function(e){var n=e.eventManager,t=e.logger;return{commands:{sendEvent:{documentationUri:"https://adobe.ly/3GQ3Q7t",optionsValidator:function(e){return function(e){var n=e.options;return mn({type:hn(),xdm:mn({eventType:hn(),identityMap:wn}),data:mn({}),documentUnloading:ln(),renderDecisions:ln(),decisionScopes:fn(hn()).uniqueItems(),personalization:mn({decisionScopes:fn(hn()).uniqueItems(),surfaces:fn(hn()).uniqueItems()}),datasetId:hn(),mergeId:hn(),edgeConfigOverrides:bn}).required().noUnknownFields()(n)}({options:e})},run:function(e){var r=e.xdm,o=e.data,i=e.documentUnloading,a=void 0!==i&&i,c=e.type,u=e.mergeId,s=e.renderDecisions,d=void 0!==s&&s,f=e.decisionScopes,l=void 0===f?[]:f,g=e.personalization,p=void 0===g?{}:g,v=e.datasetId,m=e.edgeConfigOverrides,h=n.createEvent();a&&h.documentMayUnload(),h.setUserXdm(r),h.setUserData(o),c&&h.mergeXdm({eventType:c}),u&&h.mergeXdm({eventMergeId:u});var w={renderDecisions:d,decisionScopes:l,personalization:p};return m&&(w.edgeConfigOverrides=m),v&&(t.warn("The 'datasetId' option has been deprecated. Please use 'edgeConfigOverrides.experience_platform.datasets.event' instead."),w.edgeConfigOverrides=m||{},y(w.edgeConfigOverrides,{com_adobe_experience_platform:{datasets:{event:{datasetId:v}}}})),n.sendEvent(h,w)}},applyResponse:{documentationUri:"",optionsValidator:function(e){return function(e){var n=e.options;return mn({renderDecisions:ln(),responseHeaders:vn(hn().required()),responseBody:mn({handle:fn(mn({type:hn().required(),payload:dn().required()})).required()}).required()}).noUnknownFields()(n)}({options:e})},run:function(e){var t=e.renderDecisions,r=void 0!==t&&t,o=e.responseHeaders,i=void 0===o?{}:o,a=e.responseBody,c=void 0===a?{handle:[]}:a,u=n.createEvent();return n.applyResponse(u,{renderDecisions:r,responseHeaders:i,responseBody:c})}}}}};Bn.namespace="DataCollector",Bn.configValidators={};var Fn=function(e){var n=function(e){var n=e.eventManager,t=e.lifecycle,r=e.handleError;return function(e){var o=e.target,i=n.createEvent();return i.documentMayUnload(),t.onClick({event:i,clickedElement:o}).then((function(){return i.isEmpty()?Promise.resolve():n.sendEvent(i)})).then(ye).catch((function(e){r(e,"click collection")}))}}({eventManager:e.eventManager,lifecycle:e.lifecycle,handleError:e.handleError});document.addEventListener("click",n,!0)},_n={clickCollectionEnabled:ln().default(!0),downloadLinkQualifier:hn().regexp().default("\\.(exe|zip|wav|mp3|mov|mpg|avi|wmv|pdf|doc|docx|xls|xlsx|ppt|pptx)$"),onBeforeLinkClickSend:gn()},Hn=function(e){return e&&e.replace(/\s+/g," ").trim()},Vn=/^(SCRIPT|STYLE|LINK|CANVAS|NOSCRIPT|#COMMENT)$/i,zn=function e(n){var t=[],r=!1;(function(e){return!(e&&e.nodeName&&e.nodeName.match(Vn))})(n)?(t.push(n),n.childNodes&&Array.prototype.slice.call(n.childNodes).forEach((function(n){var o=e(n);t=t.concat(o.supportedNodes),r=r||o.includesUnsupportedNodes}))):r=!0;return{supportedNodes:t,includesUnsupportedNodes:r}},Jn=function(e,n,t){var r;return t&&t!==e.nodeName.toUpperCase()||(r=e.getAttribute(n)),r},Wn=/^(HEADER|MAIN|FOOTER|NAV)$/i,Qn=function(e){var n;return"region"===e.role&&he(e["aria-label"])&&(n=e["aria-label"]),n},Xn=function(e){var n;return e&&e.nodeName&&e.nodeName.match(Wn)&&(n=e.nodeName),n},$n=function(e){var n=e.window,t=e.getLinkName,r=e.getLinkRegion,o=e.getAbsoluteUrlFromAnchorElement,i=e.findSupportedAnchorElement,a=e.determineLinkType;return function(e){var c=e.targetElement,u=e.config,s=e.logger,d=i(c);if(d){var f=o(n,d);if(f){var l=a(n,u,f,d),g=r(d),p=t(d),v=u.onBeforeLinkClickSend,m={xdm:{eventType:"web.webinteraction.linkClicks",web:{webInteraction:{name:p,region:g,type:l,URL:f,linkClicks:{value:1}}}},data:{},clickedElement:c};if(!v)return m;if(!1!==v(m))return m;s.info("This link click event is not triggered because it was canceled in onBeforeLinkClickSend.")}else s.info("This link click event is not triggered because the HTML element doesn't have an URL.")}else s.info("This link click event is not triggered because the HTML element is not an anchor.")}}({window:window,getLinkName:function(e){var n=Hn(e.innerText||e.textContent),t=zn(e);if(!n||t.includesUnsupportedNodes){var r=function(e){var n={texts:[]};return e.supportedNodes.forEach((function(e){e.getAttribute&&(n.alt||(n.alt=Hn(e.getAttribute("alt"))),n.title||(n.title=Hn(e.getAttribute("title"))),n.inputValue||(n.inputValue=Hn(Jn(e,"value","INPUT"))),n.imgSrc||(n.imgSrc=Hn(Jn(e,"src","IMG")))),e.nodeValue&&n.texts.push(e.nodeValue)})),n}(t);(n=Hn(r.texts.join("")))||(n=r.alt||r.title||r.inputValue||r.imgSrc)}return n||""},getLinkRegion:function(e){for(var n,t=e.parentNode;t;){if(n=Hn(t.id||Qn(t)||Xn(t)))return n;t=t.parentNode}return"BODY"},getAbsoluteUrlFromAnchorElement:function(e,n){var t=e.location,r=n.href?n.href:"",o=n.protocol,i=n.host;if(!function(e){return e&&/^[a-z0-9]+:\/\//i.test(e)}(r)){o||(o=t.protocol?t.protocol:""),o=o?o+"//":"",i||(i=t.host?t.host:"");var a="";if("/"!==r.substring(0,1)){var c=t.pathname.lastIndexOf("/");c=c<0?0:c,a=t.pathname.substring(0,c)}r=""+o+i+a+"/"+r}return r},findSupportedAnchorElement:function(e){for(var n,t=e;t;){if((n=t).href&&("A"===n.tagName||"AREA"===n.tagName)&&(!n.onclick||!n.protocol||n.protocol.toLowerCase().indexOf("javascript")<0))return t;t=t.parentNode}return null},determineLinkType:function(e,n,t,r){var o="other";return!function(e,n,t){var r=new RegExp(e);return!!t.download||r.test(n.toLowerCase())}(n.downloadLinkQualifier,t,r)?function(e,n){var t=e.location.hostname.toLowerCase();return!(n.toLowerCase().indexOf(t)>=0)}(e,t)&&(o="exit"):o="download",o}}),Yn=function(e){var n=e.config,t=e.eventManager,r=e.handleError,o=e.logger,i=function(e){var n=e.getLinkDetails,t=e.config,r=e.logger;return t.clickCollectionEnabled?function(e){var o=e.targetElement,i=e.event,a=n({targetElement:o,config:t,logger:r});a&&(i.mergeXdm(a.xdm),i.setUserData(a.data))}:function(){}}({getLinkDetails:$n,config:n,logger:o});return{lifecycle:{onComponentsRegistered:function(e){var n=e.lifecycle;Fn({eventManager:t,lifecycle:n,handleError:r})},onClick:function(e){var n=e.event,t=e.clickedElement;i({targetElement:t,event:n})}}}};Yn.namespace="ActivityCollector",Yn.configValidators=_n,Yn.buildOnInstanceConfiguredExtraParams=function(e){var n=e.config,t=e.logger;return{getLinkDetails:function(e){return $n({targetElement:e,config:n,logger:t})}}};var Gn,Kn,Zn,et=function(e,n){return"ID sync "+(n?"succeeded":"failed")+": "+e.spec.url},nt={thirdPartyCookiesEnabled:ln().default(!0),idMigrationEnabled:ln().default(!0)},tt=mn({namespaces:fn(pn("ECID")).nonEmpty().uniqueItems().default(["ECID"]),edgeConfigOverrides:bn}).noUnknownFields().default({namespaces:["ECID"]}),rt=mn({url:hn().required().nonEmpty(),edgeConfigOverrides:bn}).required().noUnknownFields(),ot=function(e){var n=e.logger;return new Promise((function(e,t){if(m(window.adobe)&&m(window.adobe.optIn)){var r=window.adobe.optIn;n.info("Delaying request while waiting for legacy opt-in to let Visitor retrieve ECID from server."),r.fetchPermissions((function(){r.isApproved([r.Categories.ECID])?(n.info("Received legacy opt-in approval to let Visitor retrieve ECID from server."),e()):t(new Error("Legacy opt-in was declined."))}),!0)}else e()}))},it=function(e){var n=e.logger,t=e.orgId,r=e.awaitVisitorOptIn;return function(){var e=function(e){var n=e.Visitor;return M(n)&&M(n.getInstance)&&n}(window);return e?r({logger:n}).then((function(){return n.info("Delaying request while using Visitor to retrieve ECID from server."),new Promise((function(r){e.getInstance(t,{}).getMarketingCloudVisitorID((function(e){n.info("Resuming previously delayed request that was waiting for ECID from Visitor."),r(e)}),!0)}))})).catch((function(e){e?n.info(e.message+", retrieving ECID from experience edge"):n.info("An error occurred while obtaining the ECID from Visitor.")})):Promise.resolve()}},at="ECID",ct=function(e){e.mergeQuery({identity:{fetch:[at]}})},ut=(Gn=function(o){var i,a;return(ki(i={},n,/Edge\/([0-9\._]+)/),ki(i,t,/Edg\/([0-9\.]+)/),ki(i,e,/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/),ki(i,"Firefox",/Firefox\/([0-9\.]+)(?:\s|$)/),ki(i,"IE",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/),ki(i,"Safari",/Version\/([0-9\._]+).*Safari/),a=i,function(e){for(var n=Object.keys(a),t=0;t0&&void 0!==arguments[0]?arguments[0]:{},i=e.namespaces,a=e.edgeConfigOverrides,c=t(i),u=r(c);return c.mergeConfigOverride(o),c.mergeConfigOverride(a),n({request:u})}}({sendEdgeNetworkRequest:i,createIdentityRequestPayload:wt,createIdentityRequest:yt,globalConfigOverrides:d}),m=function(e){var n=e.thirdPartyCookiesEnabled,t=e.areThirdPartyCookiesSupportedByDefault;return function(e){n&&t(ut(window))&&e.setUseIdThirdPartyDomain()}}({thirdPartyCookiesEnabled:s,areThirdPartyCookiesSupportedByDefault:a}),h=function(e){var n=e.getLegacyEcid,t=e.addEcidToPayload;return function(e){return e.hasIdentity(at)?Promise.resolve():n().then((function(n){n&&t(e,n)}))}}({getLegacyEcid:l.getEcid,addEcidToPayload:st}),y=function(e){var n=e.locationSearch,t=e.dateProvider,r=e.orgId,o=e.logger;return function(e){if(!e.hasIdentity(at)){var i=Re(n).adobe_mc;if(void 0!==i){var a=i.split("|").reduce((function(e,n){var t=Oi(n.split("="),2),r=t[0],o=t[1];return e[r]=o,e}),{}),c=parseInt(a.TS,10),u=a.MCMID,s=decodeURIComponent(a.MCORGID);t().getTime()/1e3<=c+300&&s===r&&u?(o.info("Found valid ECID identity "+u+" from the adobe_mc query string parameter."),e.addIdentity(at,{id:u})):o.info("Detected invalid or expired adobe_mc query string parameter.")}}}}({locationSearch:window.document.location.search,dateProvider:function(){return new Date},orgId:u,logger:t}),w=function(e){var n=e.doesIdentityCookieExist,t=e.orgId;return function(e){var r=e.onResponse,o=e.onRequestFailure;return new Promise((function(e,i){r((function(){if(!n()){var r=new Error("An identity was not set properly. Please verify that the org ID "+t+" configured in Alloy matches the org ID specified in the edge configuration.");throw i(r),r}e()})),o((function(){n()?e():i(new Error("No identity was set on response."))}))}))}}({doesIdentityCookieExist:g,orgId:u}),b=function(e){var n,t=e.doesIdentityCookieExist,r=e.setDomainForInitialIdentityPayload,o=e.addLegacyEcidToPayload,i=e.awaitIdentityCookie,a=e.logger,c=function(e){return r(e),o(e.getPayload())};return function(e){var r=e.request,o=e.onResponse,u=e.onRequestFailure;if(t())return r.setIsIdentityEstablished(),Promise.resolve();if(n){a.info("Delaying request while retrieving ECID from server.");var s=n;return n=s.catch((function(){return i({onResponse:o,onRequestFailure:u})})),s.then((function(){a.info("Resuming previously delayed request."),r.setIsIdentityEstablished()})).catch((function(){return c(r)}))}return n=i({onResponse:o,onRequestFailure:u}),c(r)}}({doesIdentityCookieExist:g,setDomainForInitialIdentityPayload:m,addLegacyEcidToPayload:h,awaitIdentityCookie:w,logger:t}),E=function(e){var n=e.fireReferrerHideableImage,t=e.logger;return function(e){var r=e.filter((function(e){return"url"===e.type}));return r.length?Promise.all(r.map((function(e){return n(e.spec).then((function(){t.info(et(e,!0))})).catch((function(){t.error(et(e,!1))}))}))).then(ye):Promise.resolve()}}({fireReferrerHideableImage:o,logger:t}),I=function(e){var n=e.processIdSyncs;return function(e){return n(e.getPayloadsByType("identity:exchange"))}}({processIdSyncs:E}),D=function(e){var n=e.dateProvider,t=e.orgId;return function(e,r){var o=Math.round(n().getTime()/1e3),i=encodeURIComponent("TS="+o+"|MCMID="+e+"|MCORGID="+encodeURIComponent(t)),a=Oi(r.match(bt),4),c=a[1],u=a[2],s=a[3],d=function(e){return""===e?"?":"?"===e?"":"&"}(u);return""+c+u+d+"adobe_mc="+i+s}}({dateProvider:function(){return new Date},orgId:u,globalConfigOverrides:d});return function(e){var n,t=e.addEcidQueryToPayload,r=e.addQueryStringIdentityToPayload,o=e.ensureSingleIdentity,i=e.setLegacyEcid,a=e.handleResponseForIdSyncs,c=e.getEcidFromResponse,u=e.getIdentity,s=e.consent,d=e.appendIdentityToUrl,l=e.logger,g={};return{lifecycle:{onBeforeRequest:function(e){var n=e.request,i=e.onResponse,a=e.onRequestFailure;return t(n.getPayload()),r(n.getPayload()),o({request:n,onResponse:i,onRequestFailure:a})},onResponse:function(e){var t=e.response;return n||(n=c(t))&&i(n),g=f(g,t.getEdge()),a(t)}},commands:{getIdentity:{optionsValidator:tt,run:function(e){return s.awaitConsent().then((function(){return n?void 0:u(e)})).then((function(){return{identity:{ECID:n},edge:g}}))}},appendIdentityToUrl:{optionsValidator:rt,run:function(e){return s.withConsent().then((function(){return n?void 0:u(e)})).then((function(){return{url:d(n,e.url)}})).catch((function(n){return l.warn("Unable to append identity to url. "+n.message),e}))}}}}}({addEcidQueryToPayload:ct,addQueryStringIdentityToPayload:y,ensureSingleIdentity:b,setLegacyEcid:l.setEcid,handleResponseForIdSyncs:I,getEcidFromResponse:dt,getIdentity:v,consent:r,appendIdentityToUrl:D,logger:t,config:n})};Ct.namespace="Identity",Ct.configValidators=nt;var Et=function(e){var n=e.fireReferrerHideableImage,t=e.logger,r=e.cookieJar,o=e.isPageSsl?{sameSite:"none",secure:!0}:{};return function(e){return function(e){e.filter((function(e){return"cookie"===e.type})).forEach((function(e){var n=e.spec,t=n.name,i=n.value,a=n.domain,c=n.ttlDays;r.set(t,i||"",Di({domain:a||"",expires:c||10},o))}))}(e),function(e){var r=e.filter((function(e){return"url"===e.type}));return Promise.all(r.map((function(e){return n(e.spec).then((function(){t.info(function(e,n){return"URL destination "+(!0?"succeeded":"failed")+": "+e.spec.url}(e))})).catch((function(){}))}))).then(ye)}(e)}},It=function(e){var n=e.processDestinations;return function(e){var t,r,o=e.response;return(t={response:o},r=t.response.getPayloadsByType("activation:push"),n(r)).then((function(){return{destinations:{response:o}.response.getPayloadsByType("activation:pull")}}))}},Dt=function(e){var n=e.logger,t=e.fireReferrerHideableImage,r=p.withConverter({write:function(e){return encodeURIComponent(e)}}),o=C({logger:n,cookieJar:r}),i=Et({fireReferrerHideableImage:t,logger:n,cookieJar:o,isPageSsl:"https:"===window.location.protocol});return{lifecycle:{onResponse:It({processDestinations:i})},commands:{}}};Dt.namespace="Audiences",Dt.configValidators={};var Rt,kt="web",St="://",Ot=/^(\w+):\/\/([^/#]+)(\/[^#]*)?(#.*)?$/,Pt=/^(?:.*@)?(?:[a-z\d\u00a1-\uffff.-]+|\[[a-f\d:]+])(?::\d+)?$/,xt=/^\/(?:[/\w\u00a1-\uffff-.~]|%[a-fA-F\d]{2})*$/,qt=/^#(?:[/\w\u00a1-\uffff-.~]|%[a-fA-F\d]{2})+$/,Nt=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/",n=e.length;n>0&&-1!=="/".indexOf(e.charAt(n-1));)n-=1;return e.substring(0,n)||"/"},At=function(e){return""+e.surfaceType+St+e.authority+(e.path||"")+(e.fragment||"")},Mt=function(e){var n=e(),t=n.host.toLowerCase(),r=n.pathname;return"web://"+t+Nt(r)},Tt=function(e,n,t){var r=function(e){return t.warn(e),null};if(!he(e))return r("Invalid surface: "+e);var i,a,c,u,s=function(e,n){return B(e,"#")?Mt(n)+e:e}(e,n),d=(u=s.match(Ot))?{surfaceType:(c=u[1],he(c)?c.toLowerCase():""),authority:(a=u[2],he(a)?a.toLowerCase():""),path:(i=u[3],he(i)?Nt(i):"/"),fragment:u[4]}:null;return null===d?r("Invalid surface: "+e):o([kt,"webapp"],d.surfaceType)?d.authority&&Pt.test(d.authority)?d.path&&!xt.test(d.path)?r("Invalid path "+d.path+" in surface: "+e):d.fragment&&!qt.test(d.fragment)?r("Invalid fragment "+d.fragment+" in surface: "+e):d:r("Invalid authority "+d.authority+" in surface: "+e):r("Unsupported surface type "+d.surfaceType+" in surface: "+e)},jt="__view__",Ut="https://ns.adobe.com/personalization/default-content-item",Lt="https://ns.adobe.com/personalization/dom-action",Bt="https://ns.adobe.com/personalization/html-content-item",Ft="https://ns.adobe.com/personalization/redirect-item",_t=function(e){return e.filter((function(n,t){return e.indexOf(n)===t}))},Ht=function(e){var n=e.getPageLocation,t=e.renderDecisions,r=e.decisionScopes,i=e.personalization,a=e.event,c=e.viewCache,u=e.logger,s=a.getViewName();return{isRenderDecisions:function(){return t},getViewName:function(){return s},hasScopes:function(){return r.length>0||T(i.decisionScopes)},hasSurfaces:function(){return T(i.surfaces)},hasViewName:function(){return he(s)},createQueryDetails:function(){var e=Pi(r);T(i.decisionScopes)&&e.push.apply(e,Pi(i.decisionScopes));var t=function(){var e=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0;return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]).map((function(t){return Tt(t,e,n)})).filter((function(e){return!v(e)})).map(At)}(i.surfaces,n,u);this.isCacheInitialized()||(function(e){o(e,jt)||e.push(jt)}(e),function(e,n){var t=Mt(n);o(e,t)||e.push(t)}(t,n));var a=[Ut,Bt,"https://ns.adobe.com/personalization/json-content-item",Ft];return o(e,jt)&&a.push(Lt),{schemas:a,decisionScopes:_t(e),surfaces:_t(t)}},isCacheInitialized:function(){return c.isInitialized()},shouldFetchData:function(){return this.hasScopes()||this.hasSurfaces()||!this.isCacheInitialized()},shouldUseCachedData:function(){return this.hasViewName()&&this.isCacheInitialized()}}},Vt={propositions:[]},zt=function(e){var n=e.getPageLocation,t=e.logger,r=e.fetchDataHandler,o=e.viewChangeHandler,i=e.onClickHandler,a=e.isAuthoringModeEnabled,c=e.mergeQuery,u=e.viewCache,s=e.showContainers,d=e.applyPropositions,f=e.setTargetMigration;return{lifecycle:{onBeforeRequest:function(e){var n=e.request;return f(n),Promise.resolve()},onBeforeEvent:function(e){var i=e.event,d=e.renderDecisions,f=e.decisionScopes,l=void 0===f?[]:f,g=e.personalization,p=void 0===g?{}:g,v=e.onResponse,m=void 0===v?ye:v,h=e.onRequestFailure,y=void 0===h?ye:h;if(m((function(){return{propositions:[]}})),y((function(){return s()})),a())return t.warn("Rendering is disabled for authoring mode."),void c(i,{enabled:!1});var w=Ht({getPageLocation:n,renderDecisions:d,decisionScopes:l,personalization:p,event:i,viewCache:u,logger:t});if(w.shouldFetchData()){var b=I();return u.storeViews(b.promise),y((function(){return b.reject()})),void r({decisionsDeferred:b,personalizationDetails:w,event:i,onResponse:m})}return w.shouldUseCachedData()?o({personalizationDetails:w,event:i,onResponse:m,onRequestFailure:y}):void 0},onClick:function(e){var n=e.event,t=e.clickedElement;i({event:n,clickedElement:t})}},commands:{applyPropositions:{optionsValidator:function(e){return function(e){var n=e.logger,t=e.options,r=mn({propositions:fn(mn(dn())).nonEmpty(),metadata:mn(dn())}).required();try{return r(t)}catch(e){return n.warn("Invalid options for applyPropositions. No propositions will be applied.",e),Vt}}({logger:t,options:e})},run:d}}}},Jt=function(e){return S("DIV",{},{innerHTML:e})},Wt=Ei((function(e,n){var t;t=l,e.exports=function(e){if(e.CSS&&e.CSS.escape)return e.CSS.escape;var n=function(e){if(0==arguments.length)throw new TypeError("`CSS.escape` requires an argument.");for(var n,t=String(e),r=t.length,o=-1,i="",a=t.charCodeAt(0);++o=1&&n<=31||127==n||0==o&&n>=48&&n<=57||1==o&&n>=48&&n<=57&&45==a?"\\"+n.toString(16)+" ":0==o&&1==r&&45==n||!(n>=128||45==n||95==n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122)?"\\"+t.charAt(o):t.charAt(o):i+="�";return i};return e.CSS||(e.CSS={}),e.CSS.escape=n,n}(t)})),Qt=/:eq\((\d+)\)/g,Xt=function(e){return-1===e.indexOf(":eq(")},$t=/(#|\.)(-?\w+)/g,Yt=function(e,n,t){return""+n+Wt(t)},Gt=function(e){for(var n=[],t=function(e){return e.split(Qt).filter(he)}(function(e){return e.replace($t,Yt)}(e.trim())),r=t.length,o=0;of-1)break;if(a1&&void 0!==arguments[1]?arguments[1]:document;return n.getElementById(e)},er=function(e,n,t){e.setAttribute(n,t)},nr=function(e,n){return e.getAttribute(n)},tr=function(e){return e.parentNode},rr=function(e,n){if(e){var t=tr(e);t&&t.insertBefore(n,function(e){return e.nextElementSibling}(e))}},or=function(e,n){if(e){var t=tr(e);t&&t.insertBefore(n,e)}},ir=function(e){var n=e.childNodes;return n?j(n):[]},ar=function(e){return e.firstElementChild},cr=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;if(void 0===Rt){var n=e.querySelector("[nonce]");Rt=n&&(n.nonce||n.getAttribute("nonce"))}return Rt},ur="alloy-prehiding",sr={},dr=function(e){var n=sr[e];n&&(ee(n),delete sr[e])},fr=function(e){if(e&&!Zt(ur)){var n=cr(),t=Di({id:ur},n&&{nonce:n}),r=S(q,t,{textContent:e});R(document.head,r)}},lr=function(){var e=Zt(ur);e&&ee(e)},gr=function(e,n){e.textContent=n},pr="src",vr=function(e){return S(x,{src:e})},mr=function(e){z(x,e).forEach((function(e){var n=nr(e,pr);n&&vr(n)}))},hr=function(e){return function(e,n){return e.tagName===n}(e,q)&&!nr(e,pr)},yr=function(e){var n=z(q,e),t=n.length,r=cr();if(r)for(var o=0;o=0;){var c=r[a],u=ar(e);u?or(u,c):R(e,c),a-=1}return Pr(e,o),xr(i)},Mr=function(e,n){var t=Jt(n);yr(t);var r=ir(t),o=Sr(t),i=Or(t);return mr(t),r.forEach((function(n){or(e,n)})),Pr(e,o),xr(i)},Tr=function(e,n){Mr(e,n),ee(e)},jr=function(e,n){var t=Jt(n);yr(t);var r=ir(t),o=Sr(t),i=Or(t);return mr(t),r.forEach((function(n){rr(e,n)})),Pr(e,o),xr(i)},Ur=["priority"],Lr=function(e,n){var t=n.priority,r=Si(n,Ur);Object.keys(r).forEach((function(n){!function(e,n,t,r){var o;o=r?n+":"+t+" !"+r+";":n+":"+t+";",e.style.cssText+=";"+o}(e,n,r[n],t)}))},Br=function(e,n){Object.keys(n).forEach((function(t){er(e,t,n[t])}))},Fr=function(e,n){e.tagName===x&&(vr(n),function(e,n){e.removeAttribute(n)}(e,pr),er(e,pr,n))},_r=function(e,n){var t=n.from,r=n.to,o=function(e){var n=e.children;return n?j(n):[]}(e),i=o[t],a=o[r];i&&a&&(t *:eq(0)"!==n?e:f({},e,{selector:"BODY"})}],Wr=function(e,n,t){var r=e.map((function(e){var r=function(e){return Jr.reduce((function(e,n){return f(e,n(e))}),e)}(e),o=r.type;return function(e,n,t,r){var o=n[t];if(!o){var i=new Error('DOM action "'+t+'" not found');throw zr(e,r[0],i),i}return o.apply(void 0,Pi(r))}(t,n,o,[r]).then((function(e){return function(e,n){if(e.enabled){var t=JSON.stringify(n);e.info("Action "+t+" executed.")}}(t,r),e})).catch((function(e){throw zr(t,r,e),e}))}));return Promise.all(r)},Qr="display",Xr="interact",$r=function(e){return e},Yr=function(e,n){return e.characteristics&&e.characteristics.trackingLabel?f({trackingLabel:e.characteristics.trackingLabel},n):n},Gr=function(e){var n=e.modules,t=e.logger,r=e.executeActions;return function(e){var o=e.map((function(e){var o=function(e){var n={id:e.id,scope:e.scope,scopeDetails:e.scopeDetails};return e.items.map((function(e){return f({type:"defaultContent"},e.data,{meta:Yr(e,n)})}))}(e);return r(o,n,t)}));return Promise.all(o).then((function(e){return function(e,n){var t=ie(n,$r),r=[],o=new Set;return t.forEach((function(n){if(n)if(n.error)e.warn(n);else{var t=n.meta;o.has(t.id)||(o.add(t.id),r.push(t))}})),r}(t,e)})).catch((function(e){t.error(e)}))}},Kr=function(e,n){if(Xt(e))return function(e,n){return n.matches?n.matches(e):n.msMatchesSelector(e)}(e,n);for(var t=Kt(e),r=!1,o=0;o0&&void 0!==arguments[0]?arguments[0]:document;return-1!==e.location.href.indexOf("adobe_authoring_enabled")},oo=function(e,n,t){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",o={_experience:{decisioning:{propositions:n,propositionEventType:ki({},t,1)}}};r&&(o._experience.decisioning.propositionAction={label:r}),e.mergeXdm(o)},io=function(e,n){e.mergeQuery({personalization:Di({},n)})},ao=function(e){var n=e.decisions,t=e.renderAttempted;return n.map((function(e){return f({renderAttempted:t},e)}))},co=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1?arguments[1]:void 0,t={propositions:ao({decisions:e,renderAttempted:n})};return n||(t.decisions=e),t},uo=function(e,n){var t=[],r=[];return e.forEach((function(e){o(n,e.schema)?t.push(e):r.push(e)})),[t,r]},so=function(e,n){return{id:e.id,scope:e.scope,items:n,scopeDetails:e.scopeDetails}},fo=function(e){for(var n=arguments.length,t=new Array(n>1?n-1:0),r=1;r-1},r=function(e){return!(e.scope===jt&&e.renderAttempted)},o=function(e){var o=function(e){var n=e.propositions,o=e.metadata;return n.filter(r).map((function(e){var n,r,i;return T(e.items)?{id:e.id,scope:e.scope,scopeDetails:e.scopeDetails,items:(n={items:e.items,metadataForScope:o[e.scope]},r=n.items,i=n.metadataForScope,r.filter(t).map((function(e){return e.schema!==Bt?Di({},e):m(i)?Di(Di({},e),{},{data:Di(Di({},e.data),{},{selector:i.selector,type:i.actionType})}):void 0})).filter((function(e){return e})))}:e})).filter((function(e){return T(e.items)}))}({propositions:e.propositions,metadata:e.metadata});return n(o).then((function(){return co(o,!0)}))};return function(e){var n=e.propositions,t=e.metadata,r=void 0===t?{}:t;return T(n)?o({propositions:n,metadata:r}):Promise.resolve(Vt)}},yo=function(e){var n,t,r=e.config,o=e.logger,i=e.eventManager,a=r.targetMigrationEnabled,c=r.prehidingStyle,u=function(e){var n=e.eventManager,t=e.mergeDecisionsMeta;return function(e){var r=e.decisionsMeta,o=void 0===r?[]:r,i=e.documentMayUnload,a=void 0!==i&&i,c=e.viewName,u=n.createEvent(),s={eventType:"decisioning.propositionDisplay"};return c&&(s.web={webPageDetails:{viewName:c}}),T(o)&&t(u,o,Qr),u.mergeXdm(s),a&&u.documentMayUnload(),n.sendEvent(u)}}({eventManager:i,mergeDecisionsMeta:oo}),s=po(),d=s.getClickMetasBySelector,l=s.getClickSelectors,g=s.storeClickMetrics,p=function(e){var n=e.window;return function(){return n.location}}({window:window}),v=(t=I(),{storeViews:function(e){e.then((function(e){void 0===n&&(n={}),f(n,e),t.resolve()})).catch((function(){void 0===n&&(n={}),t.resolve()}))},getView:function(e){return t.promise.then((function(){return n[e]||[]}))},isInitialized:function(){return!(void 0===n)}}),m=Vr(g),h=Gr({modules:m,logger:o,executeActions:Wr}),y=function(e){var n=e.collect,t=e.window,r=e.logger,o=e.showContainers;return function(e){var i=function(e){var n=e[0],t=n.items,r=n.id,o=n.scope,i=n.scopeDetails;return{content:t[0].data.content,decisions:[{id:r,scope:o,scopeDetails:i}]}}(e),a=i.content,c=i.decisions;return n({decisionsMeta:c,documentMayUnload:!0}).then((function(){t.location.replace(a)})).catch((function(){o(),r.warn("An error occurred while executing the redirect offer.")}))}}({collect:u,window:window,logger:o,showContainers:lr}),w=function(e){var n=e.viewCache,t=e.executeDecisions,r=e.showContainers,o=e.collect;return function(e){var i=e.viewName,a=e.pageWideScopeDecisions,c=e.nonAutoRenderableDecisions;return Promise.resolve(a).then((function(e){return function(e){var n=e.viewCache,t=e.viewName,r=e.pageWideScopeDecisions;return t?n.getView(t).then((function(e){return{pageWideScopeDecisions:r,viewPropositions:e}})):{pageWideScopeDecisions:r,viewPropositions:[]}}({viewCache:n,viewName:i,executeDecisions:t,pageWideScopeDecisions:e})})).then((function(e){return t(e.pageWideScopeDecisions).then((function(e){T(e)&&o({decisionsMeta:e})})),i&&t(e.viewPropositions).then((function(e){o({decisionsMeta:e,viewName:i})})),r(),[].concat(Pi(e.pageWideScopeDecisions),Pi(e.viewPropositions))})).then((function(e){return{decisions:Pi(c),propositions:[].concat(Pi(ao({decisions:e,renderAttempted:!0})),Pi(ao({decisions:c,renderAttempted:!1})))}}))}}({viewCache:v,executeDecisions:h,showContainers:lr,collect:u}),b=ho({executeDecisions:h}),C=function(e){var n=e.autoRenderingHandler,t=e.nonRenderingHandler,r=e.groupDecisions,o=e.handleRedirectDecisions,i=e.showContainers;return function(e){var a=e.decisionsDeferred,c=e.personalizationDetails,u=e.response.getPayloadsByType("personalization:decisions"),s=c.getViewName();if(0===u.length)return i(),a.resolve({}),{decisions:[],propositions:[]};var d=r(u),f=d.redirectDecisions,l=d.pageWideScopeDecisions,g=d.viewDecisions,p=d.nonAutoRenderableDecisions;return c.isRenderDecisions()&&T(f)?(a.resolve({}),o(f)):(a.resolve(g),c.isRenderDecisions()?n({viewName:s,pageWideScopeDecisions:l,nonAutoRenderableDecisions:p}):t({viewName:s,redirectDecisions:f,pageWideScopeDecisions:l,nonAutoRenderableDecisions:p}))}}({autoRenderingHandler:w,nonRenderingHandler:vo({viewCache:v}),groupDecisions:go,handleRedirectDecisions:y,showContainers:lr}),E=function(e){var n=e.prehidingStyle,t=e.responseHandler,r=e.hideContainers,o=e.mergeQuery;return function(e){var i=e.decisionsDeferred,a=e.personalizationDetails,c=e.event,u=e.onResponse;a.isRenderDecisions()&&r(n),o(c,a.createQueryDetails()),u((function(e){var n=e.response;return t({decisionsDeferred:i,personalizationDetails:a,response:n})}))}}({prehidingStyle:c,responseHandler:C,hideContainers:fr,mergeQuery:io}),D=function(e){var n=e.mergeDecisionsMeta,t=e.collectClicks,r=e.getClickSelectors,o=e.getClickMetasBySelector;return function(e){var i=e.event,a=e.clickedElement,c=r();if(T(c)){var u=t(a,c,o),s=u.decisionsMeta,d=u.eventLabel;if(T(s)){var f={eventType:"decisioning.propositionInteract"},l=s[0].scope;l!==jt&&(f.web={webPageDetails:{viewName:l}}),i.mergeXdm(f),n(i,s,Xr,d)}}}}({mergeDecisionsMeta:oo,collectClicks:to,getClickSelectors:l,getClickMetasBySelector:d}),R=function(e){var n=e.mergeDecisionsMeta,t=e.collect,r=e.executeDecisions,o=e.viewCache;return function(e){var i=e.personalizationDetails,a=e.event,c=e.onResponse,u=i.getViewName();return o.getView(u).then((function(e){return i.isRenderDecisions()?r(e).then((function(r){if(T(r))return n(a,r,Qr),void c((function(){return co(e,!0)}));c((function(){return t({decisionsMeta:[],viewName:u}),co(e,!0)}))})):(c((function(){return co(e,!1)})),{})}))}}({mergeDecisionsMeta:oo,collect:u,executeDecisions:h,viewCache:v}),k=function(e){return e.targetMigrationEnabled?function(e){e.getPayload().mergeMeta({target:{migration:!0}})}:ye}({targetMigrationEnabled:a});return zt({getPageLocation:p,logger:o,fetchDataHandler:E,viewChangeHandler:R,onClickHandler:D,isAuthoringModeEnabled:ro,mergeQuery:io,viewCache:v,showContainers:lr,applyPropositions:b,setTargetMigration:k})};yo.namespace="Personalization",yo.configValidators={prehidingStyle:hn().nonEmpty(),targetMigrationEnabled:ln().default(!1)};var wo,bo="2.17.0",Co=[["architecture","string"],["bitness","string"],["model","string"],["platformVersion","string"],["wow64","boolean"]],Eo=function(e){return function(n){var t={webPageDetails:{URL:e.location.href||e.location},webReferrer:{URL:e.document.referrer}};y(n,{web:t})}}(window),Io=function(e){return function(n){var t=e.screen,r=t.width,o=t.height,i={},a=xe(o);a>=0&&(i.screenHeight=a);var c=xe(r);c>=0&&(i.screenWidth=c);var u=function(e){var n=e.screen.orientation;if(null==n||null==n.type)return null;var t=n.type.split("-");return 0===t.length||"portrait"!==t[0]&&"landscape"!==t[0]?null:t[0]}(e)||function(e){if(M(e.matchMedia)){if(e.matchMedia("(orientation: portrait)").matches)return"portrait";if(e.matchMedia("(orientation: landscape)").matches)return"landscape"}return null}(e);u&&(i.screenOrientation=u),Object.keys(i).length>0&&y(n,{device:i})}}(window),Do=function(e){return function(n){var t=e.document.documentElement,r=(t=void 0===t?{}:t).clientWidth,o=t.clientHeight,i={type:"browser"},a=xe(r);a>=0&&(i.browserDetails={viewportWidth:a});var c=xe(o);c>=0&&(i.browserDetails=i.browserDetails||{},i.browserDetails.viewportHeight=c),y(n,{environment:i})}}(window),Ro=(wo=function(){return new Date},function(e){var n=wo(),t={},r=xe(n.getTimezoneOffset());void 0!==r&&(t.localTimezoneOffset=r),(void 0===r||Math.abs(r)<6e3)&&(t.localTime=function(e){var n=e.getFullYear(),t=we(e.getMonth()+1,2,"0"),r=we(e.getDate(),2,"0"),o=we(e.getHours(),2,"0"),i=we(e.getMinutes(),2,"0"),a=we(e.getSeconds(),2,"0"),c=we(e.getMilliseconds(),3,"0"),u=xe(e.getTimezoneOffset(),0);return n+"-"+t+"-"+r+"T"+o+":"+i+":"+a+"."+c+(u>0?"-":"+")+we(Math.floor(Math.abs(u)/60),2,"0")+":"+we(Math.abs(u)%60,2,"0")}(n)),y(e,{placeContext:t})}),ko=function(e){return function(n){var t=e().toISOString();y(n,{timestamp:t})}}((function(){return new Date})),So={web:Eo,device:Io,environment:Do,placeContext:Ro},Oo={highEntropyUserAgentHints:function(e){return function(e){return void 0!==e.userAgentData}(e)?function(n,t){try{return e.userAgentData.getHighEntropyValues(Co.map((function(e){return e[0]}))).then((function(e){var t={};Co.forEach((function(n){var r=Oi(n,2),o=r[0],i=r[1];Object.prototype.hasOwnProperty.call(e,o)&&Ri(e[o])===i&&(t[o]=e[o])})),y(n,{environment:{browserDetails:{userAgentClientHints:t}}})}))}catch(e){return t.warn("Unable to collect user-agent client hints. "+e.message),ye}}:ye}(navigator)},Po=Di(Di({},So),Oo),xo=[ko,function(e){y(e,{implementationDetails:{name:"https://ns.adobe.com/experience/alloy",version:bo,environment:"browser"}})}],qo=function(e){return function(e,n,t,r){var o=e.context,i=ie(o,(function(e,r){return t[e]?[t[e]]:(n.warn("Invalid context["+r+"]: '"+e+"' is not available."),[])})).concat(r);return{namespace:"Context",lifecycle:{onBeforeEvent:function(e){var t=e.event,r={};return Promise.all(i.map((function(e){return Promise.resolve(e(r,n))}))).then((function(){return t.mergeXdm(r)}))}}}}(e.config,e.logger,Po,xo)};qo.namespace="Context",qo.configValidators={context:fn(hn()).default(Object.keys(So))};var No=function e(n){return Array.isArray(n)?n.map((function(n){return e(n)})):"object"===Ri(n)&&null!==n?Object.keys(n).sort().reduce((function(t,r){return t[r]=e(n[r]),t}),{}):n},Ao=function(e){return E(JSON.stringify(No(e)))},Mo=["standard","version"],To=function(e){return e.standard+"."+e.version},jo=function(){var e={},n=pt({content:e,addIdentity:function(n,t){e.identityMap=e.identityMap||{},e.identityMap[n]=e.identityMap[n]||[],e.identityMap[n].push(t)},hasIdentity:function(n){return void 0!==(e.identityMap&&e.identityMap[n])}});return n.setConsent=function(n){e.consent=n},n},Uo=function(e){return lt({payload:e,getAction:function(){return"privacy/set-consent"},getUseSendBeacon:function(){return!1}})},Lo=function(e){return e.split(";").reduce((function(e,n){var t=Oi(n.split("="),2),r=t[0],o=t[1];return e[r]=o,e}),{})},Bo=mn({consent:fn(dn()).required().nonEmpty(),identityMap:wn,edgeConfigOverrides:bn}).noUnknownFields().required(),Fo=function(e){var n,t,r=e.config,o=e.consent,i=e.sendEdgeNetworkRequest,a=e.createNamespacedStorage,c=r.orgId,u=r.defaultConsent,s=function(e){var n=e.parseConsentCookie,t=e.orgId,r=e.cookieJar,o=se(t,"consent");return{read:function(){var e=r.get(o);return e?n(e):{}},clear:function(){r.remove(o)}}}({parseConsentCookie:Lo,orgId:c,cookieJar:p}),d=(n=0,t=Promise.resolve(),{addTask:function(e){n+=1;var r=function(){return e().finally((function(){n-=1}))};return t=t.then(r,r)},get length(){return n}}),f=function(e){var n=e.createConsentRequestPayload,t=e.createConsentRequest,r=e.sendEdgeNetworkRequest,o=e.edgeConfigOverrides;return function(e){var i=e.consentOptions,a=e.identityMap,c=e.edgeConfigOverrides,u=n();u.setConsent(i),u.mergeConfigOverride(o),u.mergeConfigOverride(c),m(a)&&Object.keys(a).forEach((function(e){a[e].forEach((function(n){u.addIdentity(e,n)}))}));var s=t(u);return r({request:s}).then((function(){}))}}({createConsentRequestPayload:jo,createConsentRequest:Uo,sendEdgeNetworkRequest:i,edgeConfigOverrides:r.edgeConfigOverrides}),l=function(e){var n=e.storage;return{clear:function(){n.clear()},lookup:function(e){var t={},r=function(e){var n=To(e);e.standard,e.version;var r=Si(e,Mo);return t[n]||(t[n]=Ao(r).toString()),t[n]};return{isNew:function(){return e.some((function(e){var t=To(e),o=n.getItem(t);return null===o||o!==r(e)}))},save:function(){e.forEach((function(e){var t=To(e);n.setItem(t,r(e))}))}}}}}({storage:a(ue(c)+".consentHashes.").persistent}),g=de({orgId:c});return function(e){var n=e.storedConsent,t=e.taskQueue,r=e.defaultConsent,o=e.consent,i=e.sendSetConsentRequest,a=e.validateSetConsentOptions,c=e.consentHashStore,u=e.doesIdentityCookieExist,s=ki({},On,r),d=n.read(),f=u(),l=void 0!==d.general;f&&l||c.clear(),f||(n.clear(),d={}),o.initializeConsent(s,d);var g=function(){if(0===t.length){var e=n.read();void 0!==e.general&&o.setConsent(e)}};return{commands:{setConsent:{optionsValidator:a,run:function(e){var n=e.consent,r=e.identityMap,a=e.edgeConfigOverrides;o.suspend();var u=c.lookup(n);return t.addTask((function(){return u.isNew()?i({consentOptions:n,identityMap:r,edgeConfigOverrides:a}):Promise.resolve()})).then((function(){return u.save()})).finally(g)}}},lifecycle:{onResponse:g,onRequestFailure:g}}}({storedConsent:s,taskQueue:d,defaultConsent:u,consent:o,sendSetConsentRequest:f,validateSetConsentOptions:Bo,consentHashStore:l,doesIdentityCookieExist:g})};Fo.namespace="Privacy";var _o=function(){return{eventMergeId:Te()}},Ho=function(){return{commands:{createEventMergeId:{run:{createEventMergeId:_o}.createEventMergeId}}}};Ho.namespace="EventMerge",Ho.configValidators={};var Vo=function(e){var n=function(e){var n=e.config,t=e.componentRegistry,r=[].concat(Pi(t.getCommandNames()),[jn,Un]).sort(),o=Di({},n);return Object.keys(n).forEach((function(e){var t=n[e];"function"==typeof t&&(o[e]=t.toString())})),{version:bo,configs:o,commands:r}}({config:e.config,componentRegistry:e.componentRegistry});return{commands:{getLibraryInfo:{run:function(){return{libraryInfo:n}}}}}};Vo.namespace="LibraryInfo";var zo=function(e){return{inferences:e.response.getPayloadsByType("rtml:inferences")}},Jo=function(){return{lifecycle:{onResponse:zo},commands:{}}};Jo.namespace="MachineLearning",Jo.configValidators={};var Wo,Qo,Xo=[Bn,Yn,Ct,Dt,yo,qo,Fo,Ho,Vo,Jo],$o=function(e){var n=e.options,t=e.componentCreators,r=e.coreConfigValidators,o=e.createConfig,i=e.logger,a=e.setDebugEnabled,c=function(e,n){var t={};return f(t,e),n.forEach((function(e){var n=e.configValidators;f(t,n)})),t}(r,t),u=o(function(e,n){try{return mn(e).noUnknownFields().required()(n)}catch(e){throw new Error("Resolve these configuration problems:\n\t - "+e.message.split("\n").join("\n\t - ")+"\nFor configuration documentation see: https://adobe.ly/3sHh553")}}(c,n));a(u.debugEnabled,{fromConfig:!0});var s=function(e,n,t){return t.reduce((function(t,r){var o=r.buildOnInstanceConfiguredExtraParams;return o&&f(t,o({config:e,logger:n})),t}),{})}(u,i,t);return i.logOnInstanceConfigured(Di(Di({},s),{},{config:u})),u},Yo=function(e){return f({},e)},Go=function(e){var n=e.errorPrefix,t=e.logger;return function(e,r){var o=Se(e);if(o.code===Pn)return t.warn("The "+r+" could not fully complete. "+o.message),{};throw Oe({error:o,message:n+" "+o.message}),o}},Ko=function(e){var n=e.getDebugEnabled,t=e.console,r=e.getMonitors,o=e.context,i="["+o.instanceName+"]";o.componentName&&(i+=" ["+o.componentName+"]");var a=function(e,n){var t=r();if(t.length>0){var i=f({},o,n);t.forEach((function(n){n[e]&&n[e](i)}))}},c=function(e){for(var r=arguments.length,o=new Array(r>1?r-1:0),c=1;c0||n()},logOnInstanceCreated:function(e){a("onInstanceCreated",e),c("info","Instance initialized.")},logOnInstanceConfigured:function(e){a("onInstanceConfigured",e),c("info","Instance configured. Computed configuration:",e.config)},logOnBeforeCommand:function(e){a("onBeforeCommand",e),c("info","Executing "+e.commandName+" command. Options:",e.options)},logOnCommandResolved:function(e){a("onCommandResolved",e),c("info",e.commandName+" command resolved. Result:",e.result)},logOnCommandRejected:function(e){a("onCommandRejected",e),c("error",e.commandName+" command was rejected. Error:",e.error)},logOnBeforeNetworkRequest:function(e){a("onBeforeNetworkRequest",e),c("info","Request "+e.requestId+": Sending request.",e.payload)},logOnNetworkResponse:function(e){a("onNetworkResponse",e);var n=e.parsedBody||e.body?"response body:":"no response body.";c("info","Request "+e.requestId+": Received response with status code "+e.statusCode+" and "+n,e.parsedBody||e.body)},logOnNetworkError:function(e){a("onNetworkError",e),c("error","Request "+e.requestId+": Network request failed.",e.error)},info:c.bind(null,"info"),warn:c.bind(null,"warn"),error:c.bind(null,"error")}},Zo="Event was canceled because the onBeforeEventSend callback returned false.",ei=function(e){var n=e.orgId,t=e.targetMigrationEnabled;return function(e){return function(e,n){return 0===n.indexOf("kndctr_"+ue(e)+"_")}(n,e)||"at_qa_mode"===e||t&&"mbox"===e}},ni=function(e){var n=e.shift()||[],t=e.shift()||[],r=e;return f.apply(void 0,[{}].concat(Pi(n),Pi(t),Pi(r)))},ti=function(e){return function(n){var t=function(){throw n};return e.call({error:n}).then(t,t)}},ri="The server responded with a",oi=function(e){var n=e.orgId,t=e.cookieJar,r=se(n,"cluster");return function(){return t.get(r)||function(){var e=t.get("mboxEdgeCluster");if(e)return"t"+e}()}},ii=[429,503,502,504],ai=function(e){var n=e.response;return e.retriesAttempted<3&&o(ii,n.statusCode)},ci=function(e){var n=e.response,t=e.retriesAttempted,r=function(e){var n,t=e.getHeader("Retry-After");if(t){var r=parseInt(t,10);n=ve(r)?1e3*r:Math.max(0,new Date(t).getTime()-(new Date).getTime())}return n}(n);return void 0===r&&(r=function(e){var n=1e3+1e3*e,t=.3*n,r=n-t,o=n+t;return Math.round(r+Math.random()*(o-r))}(t)),r},ui=(Wo=window,function(e){var n=ae+e;return{session:fe(Wo,"sessionStorage",n),persistent:fe(Wo,"localStorage",n)}}),si=window,di=si.console,fi=si.fetch,li=si.navigator,gi=si.XMLHttpRequest,pi=function(){return window.__alloyMonitors||[]},vi={debugEnabled:ln().default(!1),defaultConsent:yn(kn,"out",Sn).default(kn),edgeConfigId:hn().unique().required(),edgeDomain:hn().domain().default("edge.adobedc.net"),edgeBasePath:hn().nonEmpty().default("ee"),orgId:hn().unique().required(),onBeforeEventSend:gn().default(ye),edgeConfigOverrides:bn},mi=function(e,n){for(var t,r,o="",i=e.location.hostname.toLowerCase().split("."),a=1;a0&&void 0!==arguments[0]?arguments[0]:{},t=n.appendNode,r=void 0===t?R:t,o=n.awaitSelector,i=void 0===o?Z:o,a=n.createNode,c=void 0===a?S:a,u=n.fireImage,s=void 0===u?A:u,d=s,f=function(){return i(O).then((function(n){var t=Oi(n,1)[0];return e||(e=c(P,ne,te),r(t,e))}))},l=function(e){var n=e.src;return f().then((function(e){var t=e.contentWindow.document;return s({src:n,currentDocument:t})}))};return function(e){var n=e.hideReferrer,t=e.url;return n?l({src:t}):d({src:t})}}(),wi=function(e){var n=e.window,t=(0,e.createNamespacedStorage)("validation.");return function(){var e=Re(n.location.search).adb_validation_sessionid;if(!e)return"";var r=function(e){var n=e.persistent.getItem(ht);return n||(n=Te(),e.persistent.setItem(ht,n)),n}(t);return"&"+ke({adobeAepValidationToken:e+"|"+r})}}({window:window,createNamespacedStorage:ui}),bi=function(e){var n=e.instanceName,t=e.logController,r=t.setDebugEnabled,o=t.logger,i=t.createComponentLogger,a=Rn(),c=In(a),u=C({logger:o,cookieJar:p}),s=Go({errorPrefix:"["+n+"]",logger:o}),d=function(e){var n,t=e.logger,r=e.configureCommand,o=e.setDebugCommand,i=e.handleError,a=e.validateCommandOptions,c=function(e,i){var c;if(e===jn){if(n)throw new Error("The library has already been configured and may only be configured once.");c=function(){return(n=r(i)).then((function(){}))}}else{if(!n)throw new Error("The library must be configured first. Please do so by executing the configure command.");c=e===Un?function(){return o(i)}:function(){return n.then((function(n){var t=n.getCommand(e);if(!t||!M(t.run)){var r=[jn,Un].concat(n.getCommandNames()).join(", ");throw new Error("The "+e+" command does not exist. List of available commands: "+r+".")}var o=a({command:t,options:i});return t.run(o)}),(function(){return t.warn("An error during configuration is preventing the "+e+" command from executing."),new Promise((function(){}))}))}}return c};return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(r){var o=c(e,n);t.logOnBeforeCommand({commandName:e,options:n}),r(o())})).catch((function(n){return i(n,e+" command")})).catch((function(r){throw t.logOnCommandRejected({commandName:e,options:n,error:r}),r})).then((function(r){var o=m(r)?r:{};return t.logOnCommandResolved({commandName:e,options:n,result:o}),o}))}}({logger:o,configureCommand:function(e){var t=$o({options:e,componentCreators:Xo,coreConfigValidators:vi,createConfig:Yo,logger:o,setDebugEnabled:r}),s=t.orgId,d=t.targetMigrationEnabled,f=ei({orgId:s,targetMigrationEnabled:d}),l=function(e){var n=e.cookieJar,t=e.shouldTransferCookie,r=e.apexDomain,o=e.dateProvider;return{cookiesToPayload:function(e,o){var i,a=(i=r,o.substr(-i.length)===i),c={domain:r,cookiesEnabled:!0};if(!a){var u=n.get(),s=Object.keys(u).filter(t).map((function(e){return{key:e,value:u[e]}}));s.length&&(c.entries=s)}e.mergeState(c)},responseToCookies:function(e){e.getPayloadsByType("state:store").forEach((function(e){var t={domain:r},i=e.attrs&&e.attrs.SameSite&&e.attrs.SameSite.toLowerCase();void 0!==e.maxAge&&(t.expires=new Date(o().getTime()+1e3*e.maxAge)),void 0!==i&&(t.sameSite=i),"none"===i&&(t.secure=!0),n.set(e.key,e.value,t)}))}}}({cookieJar:u,shouldTransferCookie:f,apexDomain:mi,dateProvider:function(){return new Date}}),g=M(li.sendBeacon)?function(e){var n=e.sendBeacon,t=e.sendFetchRequest,r=e.logger;return function(e,o){var i=new Blob([o],{type:"text/plain; charset=UTF-8"});return n(e,i)?Promise.resolve({statusCode:204,getHeader:function(){return null},body:""}):(r.info("Unable to use `sendBeacon`; falling back to `fetch`."),t(e,o))}}({sendBeacon:li.sendBeacon.bind(li),sendFetchRequest:hi,logger:o}):hi,v=function(e){var n=e.logger,t=e.sendFetchRequest,r=e.sendBeaconRequest,o=e.isRequestRetryable,i=e.getRequestRetryDelay;return function(e){var a=e.requestId,c=e.url,u=e.payload,s=e.useSendBeacon,d=JSON.stringify(u),f=JSON.parse(d);return n.logOnBeforeNetworkRequest({url:c,requestId:a,payload:f}),function e(){var u=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return(s?r:t)(c,d).then((function(t){var r;if(o({response:t,retriesAttempted:u})){var s=i({response:t,retriesAttempted:u});return new Promise((function(n){setTimeout((function(){n(e(u+1))}),s)}))}try{r=JSON.parse(t.body)}catch(e){}return n.logOnNetworkResponse(Di(Di({requestId:a,url:c,payload:f},t),{},{parsedBody:r,retriesAttempted:u})),{statusCode:t.statusCode,body:t.body,parsedBody:r,getHeader:t.getHeader}}))}().catch((function(e){throw n.logOnNetworkError({requestId:a,url:c,payload:f,error:e}),Pe({error:e,message:"Network request failed."})}))}}({logger:o,sendFetchRequest:hi,sendBeaconRequest:g,isRequestRetryable:ai,getRequestRetryDelay:ci}),m=function(e){var n=e.logger;return function(e){var t=e.statusCode,r=e.body,o=e.parsedBody;if(t<200||t>=300||!o&&204!==t||o&&!Array.isArray(o.handle)){var i=o?JSON.stringify(o,null,2):r;throw new Error(ri+" status code "+t+" and "+(i?"response body:\n"+i:"no response body."))}if(o){var a=o.warnings,c=void 0===a?[]:a,u=o.errors,s=void 0===u?[]:u;c.forEach((function(e){n.warn(ri+" warning:",e)})),s.forEach((function(e){n.error(ri+" non-fatal error:",e)}))}}}({logger:o}),h=function(e){var n=e.logger;return function(e){if(e){var t=e.split(";");if(t.length>=2&&t[1].length>0)try{var r=parseInt(t[1],10);if(!isNaN(r))return{regionId:r}}catch(e){}n.warn('Invalid adobe edge: "'+e+'"')}return{}}}({logger:o}),y=function(e){var n=e.extractEdgeInfo;return function(e){var t=e.content,r=void 0===t?{}:t,o=e.getHeader,i=r.handle,a=void 0===i?[]:i,c=r.errors,u=void 0===c?[]:c,s=r.warnings,d=void 0===s?[]:s;return{getPayloadsByType:function(e){return ie(a.filter((function(n){return n.type===e})),(function(e){return e.payload}))},getErrors:function(){return u},getWarnings:function(){return d},getEdge:function(){return n(o("x-adobe-edge"))},toJSON:function(){return r}}}}({extractEdgeInfo:h}),w=oi({orgId:s,cookieJar:p}),C=function(e){var n=e.config,t=e.lifecycle,r=e.cookieTransfer,o=e.sendNetworkRequest,i=e.createResponse,a=e.processWarningsAndErrors,c=e.getLocationHint,u=e.getAssuranceValidationTokenParams,s=n.edgeDomain,d=n.edgeBasePath,f=n.edgeConfigId;return function(e){var n=e.request,l=e.runOnResponseCallbacks,g=void 0===l?ye:l,p=e.runOnRequestFailureCallbacks,v=void 0===p?ye:p,m=b();m.add(t.onResponse),m.add(g);var h=b();return h.add(t.onRequestFailure),h.add(v),t.onBeforeRequest({request:n,onResponse:m.add,onRequestFailure:h.add}).then((function(){var e=n.getUseIdThirdPartyDomain()?"adobedc.demdex.net":s,t=c(),i="https://"+e+"/"+(t?d+"/"+t:d)+"/v1/"+n.getAction()+"?configId="+f+"&requestId="+n.getId()+u();return r.cookiesToPayload(n.getPayload(),e),o({requestId:n.getId(),url:i,payload:n.getPayload(),useSendBeacon:n.getUseSendBeacon()})})).then((function(e){return a(e),e})).catch(ti(h)).then((function(e){var n=e.parsedBody,t=e.getHeader,o=i({content:n,getHeader:t});return r.responseToCookies(o),m.call({response:o}).then(ni)}))}}({config:t,lifecycle:c,cookieTransfer:l,sendNetworkRequest:v,createResponse:y,processWarningsAndErrors:m,getLocationHint:w,getAssuranceValidationTokenParams:wi}),E=function(e){var n=e.cookieTransfer,t=e.lifecycle,r=e.createResponse,o=e.processWarningsAndErrors;return function(e){var i=e.request,a=e.responseHeaders,c=e.responseBody,u=e.runOnResponseCallbacks,s=void 0===u?ye:u,d=e.runOnRequestFailureCallbacks,f=void 0===d?ye:d,l=b();l.add(t.onResponse),l.add(s);var g=b();g.add(t.onRequestFailure),g.add(f);var p=function(e){return a[e]};return t.onBeforeRequest({request:i,onResponse:l.add,onRequestFailure:g.add}).then((function(){return o({statusCode:200,getHeader:p,body:JSON.stringify(c),parsedBody:c})})).catch(ti(g)).then((function(){var e=r({content:c,getHeader:p});return n.responseToCookies(e),l.call({response:e}).then(ni)}))}}({lifecycle:c,cookieTransfer:l,createResponse:y,processWarningsAndErrors:m}),I=function(e){var n=e.generalConsentState,t=e.logger,r=function(e,r){switch(e.general){case kn:n.in(r);break;case"out":n.out(r);break;case Sn:n.pending(r);break;default:t.warn("Unknown consent value: "+e.general)}};return{initializeConsent:function(e,n){n.general?r(n,qn):r(e,xn)},setConsent:function(e){r(e,Nn)},suspend:function(){n.pending()},awaitConsent:function(){return n.awaitConsent()},withConsent:function(){return n.withConsent()}}}({generalConsentState:Mn({logger:o}),logger:o}),D=function(e){var n=e.config,t=e.logger,r=e.lifecycle,o=e.consent,i=e.createEvent,a=e.createDataCollectionRequestPayload,c=e.createDataCollectionRequest,u=e.sendEdgeNetworkRequest,s=e.applyResponse,d=n.onBeforeEventSend,f=n.edgeConfigOverrides;return{createEvent:i,sendEvent:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=n.renderDecisions,s=void 0!==i&&i,l=n.decisionScopes,g=n.edgeConfigOverrides,p=n.personalization,v=a(),m=c(v),h=b(),y=b();return v.mergeConfigOverride(f),v.mergeConfigOverride(g),r.onBeforeEvent({event:e,renderDecisions:s,decisionScopes:l,personalization:p,onResponse:h.add,onRequestFailure:y.add}).then((function(){return v.addEvent(e),o.awaitConsent()})).then((function(){try{e.finalize(d)}catch(o){var n=function(){throw o};return y.add(r.onRequestFailure),y.call({error:o}).then(n,n)}if(!e.shouldSend()){y.add(r.onRequestFailure),t.info(Zo);var o=new Error(Zo);return y.call({error:o}).then((function(){}))}return u({request:m,runOnResponseCallbacks:h.call,runOnRequestFailureCallbacks:y.call})}))},applyResponse:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},t=n.renderDecisions,o=void 0!==t&&t,i=n.responseHeaders,u=void 0===i?{}:i,d=n.responseBody,f=void 0===d?{handle:[]}:d,l=a(),g=c(l),p=b();return r.onBeforeEvent({event:e,renderDecisions:o,decisionScopes:[jt],personalization:{},onResponse:p.add,onRequestFailure:ye}).then((function(){return l.addEvent(e),s({request:g,responseHeaders:u,responseBody:f,runOnResponseCallbacks:p.call})}))}}}({config:t,logger:o,lifecycle:c,consent:I,createEvent:Tn,createDataCollectionRequestPayload:mt,createDataCollectionRequest:gt,sendEdgeNetworkRequest:C,applyResponse:E});return function(e){var n=e.componentCreators,t=e.lifecycle,r=e.componentRegistry,o=e.getImmediatelyAvailableTools;return n.forEach((function(e){var n,t=e.namespace,i=o(t);try{n=e(i)}catch(e){throw Pe({error:e,message:"["+t+"] An error occurred during component creation."})}r.register(t,n)})),t.onComponentsRegistered({lifecycle:t}).then((function(){return r}))}({componentCreators:Xo,lifecycle:c,componentRegistry:a,getImmediatelyAvailableTools:function(e){var r=i(e);return{config:t,componentRegistry:a,consent:I,eventManager:D,fireReferrerHideableImage:yi,logger:r,lifecycle:c,sendEdgeNetworkRequest:C,handleError:Go({errorPrefix:"["+n+"] ["+e+"]",logger:r}),createNamespacedStorage:ui,apexDomain:mi}}})},setDebugCommand:function(e){r(e.enabled,{fromConfig:!1})},handleError:s,validateCommandOptions:Ln});return d};(Qo=window.__alloyNS)&&Qo.forEach((function(e){var n=Cn({console:di,locationSearch:window.location.search,createLogger:Ko,instanceName:e,createNamespacedStorage:ui,getMonitors:pi}),t=function(e){return function(n){var t=n[0],r=n[1],o=n[2],i=o[0],a=o[1];e(i,a).then(t,r)}}(bi({instanceName:e,logController:n})),r=window[e].q;r.push=t,n.logger.logOnInstanceCreated({instance:t}),r.forEach(t)}))}function Ci(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function Ei(e,n){return e(n={exports:{}},n.exports),n.exports}function Ii(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n&&(r=r.filter((function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable}))),t.push.apply(t,r)}return t}function Di(e){for(var n=1;n=0||(o[t]=e[t]);return o}(e,n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(o[t]=e[t])}return o}function Oi(e,n){return function(e){if(Array.isArray(e))return e}(e)||function(e,n){var t=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==t)return;var r,o,i=[],a=!0,c=!1;try{for(t=t.call(e);!(a=(r=t.next()).done)&&(i.push(r.value),!n||i.length!==n);a=!0);}catch(e){c=!0,o=e}finally{try{a||null==t.return||t.return()}finally{if(c)throw o}}return i}(e,n)||xi(e,n)||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 Pi(e){return function(e){if(Array.isArray(e))return qi(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||xi(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function xi(e,n){if(e){if("string"==typeof e)return qi(e,n);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?qi(e,n):void 0}}function qi(e,n){(null==n||n>e.length)&&(n=e.length);for(var t=0,r=new Array(n);t enhanceAnalyticsEvent(options),
- };
-}
-
-/**
- * Create inline script
- * @param document
- * @param element where to create the script element
- * @param innerHTML the script
- * @param type the type of the script element
- * @returns {HTMLScriptElement}
- */
-function createInlineScript(document, element, innerHTML, type) {
- const script = document.createElement('script');
- script.type = type;
- script.innerHTML = innerHTML;
- element.appendChild(script);
- return script;
-}
-
-/**
- * Sends an analytics event to alloy
- * @param xdmData - the xdm data object
- * @returns {Promise<*>}
- */
-async function sendAnalyticsEvent(xdmData) {
- // eslint-disable-next-line no-undef
- if (!alloy) {
- console.warn('alloy not initialized, cannot send analytics event');
- return Promise.resolve();
- }
- // eslint-disable-next-line no-undef
- return alloy('sendEvent', {
- documentUnloading: true,
- xdm: xdmData,
- });
-}
-
-/**
- * Sets Adobe standard v1.0 consent for alloy based on the input
- * Documentation: https://experienceleague.adobe.com/docs/experience-platform/edge/consent/supporting-consent.html?lang=en#using-the-adobe-standard-version-1.0
- * @param approved
- * @returns {Promise<*>}
- */
-export async function analyticsSetConsent(approved) {
- // eslint-disable-next-line no-undef
- if (!alloy) {
- console.warn('alloy not initialized, cannot set consent');
- return Promise.resolve();
- }
- // eslint-disable-next-line no-undef
- return alloy('setConsent', {
- consent: [{
- standard: 'Adobe',
- version: '1.0',
- value: {
- general: approved ? 'in' : 'out',
- },
- }],
- });
-}
-
-/**
- * Basic tracking for page views with alloy
- * @param document
- * @param additionalXdmFields
- * @returns {Promise<*>}
- */
-export async function analyticsTrackPageViews(document, additionalXdmFields = {}) {
- const xdmData = {
- eventType: 'web.webpagedetails.pageViews',
- web: {
- webPageDetails: {
- pageViews: {
- value: 1,
- },
- name: `${document.title}`,
- },
- },
- [CUSTOM_SCHEMA_NAMESPACE]: {
- ...additionalXdmFields,
- },
- };
-
- return sendAnalyticsEvent(xdmData);
-}
-
-/**
- * Initializes event queue for analytics tracking using alloy
- * @returns {Promise}
- */
-export async function initAnalyticsTrackingQueue() {
- createInlineScript(document, document.body, getAlloyInitScript(), 'text/javascript');
-}
-
-/**
- * Sets up analytics tracking with alloy (initializes and configures alloy)
- * @param document
- * @returns {Promise}
- */
-export async function setupAnalyticsTrackingWithAlloy(document) {
- // eslint-disable-next-line no-undef
- if (!alloy) {
- console.warn('alloy not initialized, cannot configure');
- return;
- }
- // eslint-disable-next-line no-undef
- const configurePromise = alloy('configure', getAlloyConfiguration(document));
-
- // Custom logic can be inserted here in order to support early tracking before alloy library
- // loads, for e.g. for page views
- const pageViewPromise = analyticsTrackPageViews(document); // track page view early
-
- await import('./alloy.min.js');
- await Promise.all([configurePromise, pageViewPromise]);
-}
-
-/**
- * Basic tracking for link clicks with alloy
- * Documentation: https://experienceleague.adobe.com/docs/experience-platform/edge/data-collection/track-links.html
- * @param element
- * @param linkType
- * @param additionalXdmFields
- * @returns {Promise<*>}
- */
-export async function analyticsTrackLinkClicks(element, linkType = 'other', additionalXdmFields = {}) {
- const xdmData = {
- eventType: 'web.webinteraction.linkClicks',
- web: {
- webInteraction: {
- URL: `${element.href}`,
- // eslint-disable-next-line no-nested-ternary
- name: `${element.text ? element.text.trim() : (element.innerHTML ? element.innerHTML.trim() : '')}`,
- linkClicks: {
- value: 1,
- },
- type: linkType,
- },
- },
- [CUSTOM_SCHEMA_NAMESPACE]: {
- ...additionalXdmFields,
- },
- };
-
- return sendAnalyticsEvent(xdmData);
-}
-
-/**
- * Basic tracking for CWV events with alloy
- * @param cwv
- * @returns {Promise<*>}
- */
-export async function analyticsTrackCWV(cwv) {
- const xdmData = {
- eventType: 'web.performance.measurements',
- [CUSTOM_SCHEMA_NAMESPACE]: {
- cwv,
- },
- };
-
- return sendAnalyticsEvent(xdmData);
-}
-
-/**
- * Basic tracking for 404 errors with alloy
- * @param data
- * @param additionalXdmFields
- * @returns {Promise<*>}
- */
-export async function analyticsTrack404(data, additionalXdmFields = {}) {
- const xdmData = {
- eventType: 'web.webpagedetails.pageViews',
- web: {
- webPageDetails: {
- pageViews: {
- value: 0,
- },
- },
- },
- [CUSTOM_SCHEMA_NAMESPACE]: {
- isPageNotFound: true,
- ...additionalXdmFields,
- },
- };
-
- return sendAnalyticsEvent(xdmData);
-}
-
-export async function analyticsTrackError(data, additionalXdmFields = {}) {
- const xdmData = {
- eventType: 'web.webpagedetails.pageViews',
- web: {
- webPageDetails: {
- pageViews: {
- value: 0,
- },
- isErrorPage: true,
- },
- },
- [CUSTOM_SCHEMA_NAMESPACE]: {
- ...additionalXdmFields,
- },
- };
-
- return sendAnalyticsEvent(xdmData);
-}
-
-export async function analyticsTrackConversion(data, additionalXdmFields = {}) {
- const { source: conversionName, target: conversionValue, element } = data;
-
- const xdmData = {
- eventType: 'web.webinteraction.conversion',
- [CUSTOM_SCHEMA_NAMESPACE]: {
- conversion: {
- conversionComplete: 1,
- conversionName,
- conversionValue,
- },
- ...additionalXdmFields,
- },
- };
-
- if (element.tagName === 'FORM') {
- xdmData.eventType = 'web.formFilledOut';
- const formId = element?.id || element?.dataset?.action;
- xdmData[CUSTOM_SCHEMA_NAMESPACE].form = {
- ...(formId && { formId }),
- // don't count as form complete, as this event should be tracked separately,
- // track only the details of the form together with the conversion
- formComplete: 0,
- };
- } else if (element.tagName === 'A') {
- xdmData.eventType = 'web.webinteraction.linkClicks';
- xdmData.web = {
- webInteraction: {
- URL: `${element.href}`,
- // eslint-disable-next-line no-nested-ternary
- name: `${element.text ? element.text.trim() : (element.innerHTML ? element.innerHTML.trim() : '')}`,
- linkClicks: {
- // don't count as link click, as this event should be tracked separately,
- // track only the details of the link with the conversion
- value: 0,
- },
- type: 'other',
- },
- };
- }
-
- return sendAnalyticsEvent(xdmData);
-}
-
-/**
- * Basic tracking for form submissions with alloy
- * @param element
- * @param additionalXdmFields
- * @returns {Promise<*>}
- */
-export async function analyticsTrackFormSubmission(element, additionalXdmFields = {}) {
- const formId = element?.id || element?.dataset?.action;
- const xdmData = {
- eventType: 'web.formFilledOut',
- [CUSTOM_SCHEMA_NAMESPACE]: {
- form: {
- ...(formId && { formId }),
- formComplete: 1,
- },
- ...additionalXdmFields,
- },
- };
-
- return sendAnalyticsEvent(xdmData);
-}
-
-/**
- * Basic tracking for video play with alloy
- * @param element
- * @param additionalXdmFields
- * @returns {Promise<*>}
- */
-export async function analyticsTrackVideo({
- id, name, type, hasStarted, hasCompleted, progressMarker,
-}, additionalXdmFields) {
- const primaryAssetReference = {
- id: `${id}`,
- dc: {
- title: `${name}`,
- },
- showType: `${type}`,
- };
- const baseXdm = {
- [CUSTOM_SCHEMA_NAMESPACE]: {
- media: {
- mediaTimed: {
- primaryAssetReference,
- },
- },
- ...additionalXdmFields,
- },
- };
-
- if (hasStarted) {
- baseXdm[CUSTOM_SCHEMA_NAMESPACE].media.mediaTimed.impressions = { value: 1 };
- } else if (hasCompleted) {
- baseXdm[CUSTOM_SCHEMA_NAMESPACE].media.mediaTimed.completes = { value: 1 };
- } else if (progressMarker) {
- baseXdm[CUSTOM_SCHEMA_NAMESPACE].media.mediaTimed[progressMarker] = { value: 1 };
- } else {
- return Promise.resolve();
- }
-
- return sendAnalyticsEvent(baseXdm);
-}
diff --git a/scripts/cookie-consent/lib-cookie-consent.js b/scripts/cookie-consent/lib-cookie-consent.js
index d9c82895..d52689d3 100644
--- a/scripts/cookie-consent/lib-cookie-consent.js
+++ b/scripts/cookie-consent/lib-cookie-consent.js
@@ -4,7 +4,7 @@
* https://github.com/sandstreamdev/cookieconsent
*/
import { getPlaceholderOrDefault } from '../lib-franklin.js';
-import { analyticsSetConsent } from '../analytics/lib-analytics.js';
+import { updateUserConsent } from '../adobe-martech/index.js';
const REVOKE_CONSENT_ELEMENT_ID = 'cc-revoke-choice';
const configureCookieConsent = () => {
@@ -76,7 +76,12 @@ const configureCookieConsent = () => {
function applyConsent() {
if (window.alloy) {
- analyticsSetConsent(getConsentForCategory(CC.ANALYTICS));
+ updateUserConsent({
+ collect: !!getConsentForCategory(CC.ANALYTICS),
+ marketing: !!getConsentForCategory(CC.MARKETING),
+ personalize: !!getConsentForCategory(CC.PERSONALIZATION),
+ share: !!getConsentForCategory(CC.MARKETING),
+ });
}
}
diff --git a/scripts/delayed.js b/scripts/delayed.js
index 3ec6aebf..6b84b90b 100644
--- a/scripts/delayed.js
+++ b/scripts/delayed.js
@@ -1,7 +1,7 @@
// eslint-disable-next-line import/no-cycle
import { fetchPlaceholders, sampleRUM } from './lib-franklin.js';
import loadCookieConsent from './cookie-consent/lib-cookie-consent.js';
-import { analyticsSetConsent } from './analytics/lib-analytics.js';
+import { updateUserConsent } from './adobe-martech/index.js';
// Core Web Vitals RUM collection
sampleRUM('cwv');
@@ -16,6 +16,14 @@ loadCookieConsent();
// also check consent stored in localstorage used while developing
const analyticsConsent = localStorage.getItem('consent_status_ANALYTICS');
-if (analyticsConsent) {
- await analyticsSetConsent(analyticsConsent === 'ALLOW');
+const targetingConsent = localStorage.getItem('consent_status_PERSONALIZATION');
+const marketingConsent = localStorage.getItem('consent_status_MARKETING');
+if (analyticsConsent || targetingConsent) {
+ await updateUserConsent(analyticsConsent === 'ALLOW');
+ updateUserConsent({
+ collect: analyticsConsent === 'ALLOW',
+ marketing: marketingConsent === 'ALLOW',
+ personalize: targetingConsent === 'ALLOW',
+ share: marketingConsent === 'ALLOW',
+ });
}
diff --git a/scripts/lib-franklin.js b/scripts/lib-franklin.js
index 0ef41a82..97c3a29e 100644
--- a/scripts/lib-franklin.js
+++ b/scripts/lib-franklin.js
@@ -17,10 +17,12 @@
* @param {Object} data additional data for RUM sample
*/
export function sampleRUM(checkpoint, data = {}) {
+ const SESSION_STORAGE_KEY = 'aem-rum';
+ sampleRUM.baseURL = sampleRUM.baseURL
+ || new URL(window.RUM_BASE == null ? 'https://rum.hlx.page' : window.RUM_BASE, window.location);
sampleRUM.defer = sampleRUM.defer || [];
const defer = (fnname) => {
- sampleRUM[fnname] = sampleRUM[fnname]
- || ((...args) => sampleRUM.defer.push({ fnname, args }));
+ sampleRUM[fnname] = sampleRUM[fnname] || ((...args) => sampleRUM.defer.push({ fnname, args }));
};
sampleRUM.drain = sampleRUM.drain
|| ((dfnname, fn) => {
@@ -30,48 +32,109 @@ export function sampleRUM(checkpoint, data = {}) {
.forEach(({ fnname, args }) => sampleRUM[fnname](...args));
});
sampleRUM.always = sampleRUM.always || [];
- sampleRUM.always.on = (chkpnt, fn) => { sampleRUM.always[chkpnt] = fn; };
- sampleRUM.on = (chkpnt, fn) => { sampleRUM.cases[chkpnt] = fn; };
+ sampleRUM.always.on = (chkpnt, fn) => {
+ sampleRUM.always[chkpnt] = fn;
+ };
+ sampleRUM.on = (chkpnt, fn) => {
+ sampleRUM.cases[chkpnt] = fn;
+ };
defer('observe');
defer('cwv');
try {
window.hlx = window.hlx || {};
if (!window.hlx.rum) {
const usp = new URLSearchParams(window.location.search);
- const weight = (usp.get('rum') === 'on') ? 1 : 100; // with parameter, weight is 1. Defaults to 100.
- // eslint-disable-next-line no-bitwise
- const hashCode = (s) => s.split('').reduce((a, b) => (((a << 5) - a) + b.charCodeAt(0)) | 0, 0);
- const id = `${hashCode(window.location.href)}-${new Date().getTime()}-${Math.random().toString(16).substr(2, 14)}`;
+ const weight = usp.get('rum') === 'on' ? 1 : 100; // with parameter, weight is 1. Defaults to 100.
+ const id = Array.from({ length: 75 }, (_, i) => String.fromCharCode(48 + i))
+ .filter((a) => /\d|[A-Z]/i.test(a))
+ .filter(() => Math.random() * 75 > 70)
+ .join('');
const random = Math.random();
- const isSelected = (random * weight < 1);
- // eslint-disable-next-line object-curly-newline
- window.hlx.rum = { weight, id, random, isSelected, sampleRUM };
+ const isSelected = random * weight < 1;
+ const firstReadTime = window.performance ? window.performance.timeOrigin : Date.now();
+ const urlSanitizers = {
+ full: () => window.location.href,
+ origin: () => window.location.origin,
+ path: () => window.location.href.replace(/\?.*$/, ''),
+ };
+ // eslint-disable-next-line max-len
+ const rumSessionStorage = sessionStorage.getItem(SESSION_STORAGE_KEY)
+ ? JSON.parse(sessionStorage.getItem(SESSION_STORAGE_KEY))
+ : {};
+ // eslint-disable-next-line max-len
+ rumSessionStorage.pages = (rumSessionStorage.pages ? rumSessionStorage.pages : 0)
+ + 1
+ /* noise */ + (Math.floor(Math.random() * 20) - 10);
+ sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(rumSessionStorage));
+ // eslint-disable-next-line object-curly-newline, max-len
+ window.hlx.rum = {
+ weight,
+ id,
+ random,
+ isSelected,
+ firstReadTime,
+ sampleRUM,
+ sanitizeURL: urlSanitizers[window.hlx.RUM_MASK_URL || 'path'],
+ rumSessionStorage,
+ };
}
- const { weight, id } = window.hlx.rum;
+
+ const { weight, id, firstReadTime } = window.hlx.rum;
if (window.hlx && window.hlx.rum && window.hlx.rum.isSelected) {
+ const knownProperties = [
+ 'weight',
+ 'id',
+ 'referer',
+ 'checkpoint',
+ 't',
+ 'source',
+ 'target',
+ 'cwv',
+ 'CLS',
+ 'FID',
+ 'LCP',
+ 'INP',
+ 'TTFB',
+ ];
const sendPing = (pdata = data) => {
+ // eslint-disable-next-line max-len
+ const t = Math.round(
+ window.performance ? window.performance.now() : Date.now() - firstReadTime,
+ );
// eslint-disable-next-line object-curly-newline, max-len, no-use-before-define
- const body = JSON.stringify({ weight, id, referer: window.location.href, generation: window.hlx.RUM_GENERATION, checkpoint, ...data });
- const url = `https://rum.hlx.page/.rum/${weight}`;
- // eslint-disable-next-line no-unused-expressions
+ const body = JSON.stringify(
+ {
+ weight, id, referer: window.hlx.rum.sanitizeURL(), checkpoint, t, ...data,
+ },
+ knownProperties,
+ );
+ const url = new URL(`.rum/${weight}`, sampleRUM.baseURL).href;
navigator.sendBeacon(url, body);
// eslint-disable-next-line no-console
console.debug(`ping:${checkpoint}`, pdata);
};
sampleRUM.cases = sampleRUM.cases || {
+ load: () => sampleRUM('pagesviewed', { source: window.hlx.rum.rumSessionStorage.pages }) || true,
cwv: () => sampleRUM.cwv(data) || true,
lazy: () => {
// use classic script to avoid CORS issues
const script = document.createElement('script');
- script.src = 'https://rum.hlx.page/.rum/@adobe/helix-rum-enhancer@^1/src/index.js';
+ script.src = new URL(
+ '.rum/@adobe/helix-rum-enhancer@^1/src/index.js',
+ sampleRUM.baseURL,
+ ).href;
document.head.appendChild(script);
return true;
},
};
sendPing(data);
- if (sampleRUM.cases[checkpoint]) { sampleRUM.cases[checkpoint](); }
+ if (sampleRUM.cases[checkpoint]) {
+ sampleRUM.cases[checkpoint]();
+ }
+ }
+ if (sampleRUM.always[checkpoint]) {
+ sampleRUM.always[checkpoint](data);
}
- if (sampleRUM.always[checkpoint]) { sampleRUM.always[checkpoint](data); }
} catch (error) {
// something went wrong
}
diff --git a/scripts/rum-to-analytics.js b/scripts/rum-to-analytics.js
new file mode 100644
index 00000000..cfe21d2c
--- /dev/null
+++ b/scripts/rum-to-analytics.js
@@ -0,0 +1,185 @@
+import { sampleRUM } from './lib-franklin.js';
+import { initRumTracking, pushEventToDataLayer } from './adobe-martech/index.js';
+
+// Define RUM tracking function
+const track = initRumTracking(sampleRUM, { withRumEnhancer: true });
+
+// Track page views when the page is fully rendered
+// The data will be automatically enriched with applied propositions for personalization use cases
+track('lazy', () => {
+ const { pathname, hostname } = window.location;
+ const canonicalMeta = document.head.querySelector('link[rel="canonical"]');
+ const url = canonicalMeta ? new URL(canonicalMeta.href).pathname : pathname;
+ const is404 = window.isErrorPage;
+ pushEventToDataLayer('web.webpagedetails.pageViews', {
+ web: {
+ webPageDetails: {
+ pageViews: {
+ value: is404 ? 0 : 1,
+ },
+ isHomePage: pathname === '/',
+ },
+ },
+ }, {
+ __adobe: {
+ analytics: {
+ channel: !is404 ? pathname.split('/')[1] || 'home' : '404',
+ cookiesEnabled: navigator.cookieEnabled ? 'Y' : 'N',
+ pageName: !is404
+ ? pathname.split('/').slice(1).join(':') + (pathname.endsWith('/') ? 'home' : '')
+ : undefined,
+ pageType: is404 ? 'errorPage' : undefined,
+ server: window.location.hostname,
+ contextData: {
+ canonical: !is404 ? url : '/404',
+ environment: (hostname === 'localhost' && 'dev')
+ || (hostname.endsWith('.page') && 'preview')
+ || (hostname.endsWith('.live') && 'live')
+ || 'prod',
+ language: document.documentElement.getAttribute('lang') || 'en',
+ template: document.head.querySelector('meta[name="template"]')?.content || 'default',
+ },
+ },
+ },
+ });
+});
+
+track('cwv', (data) => {
+ if (!data.cwv) {
+ return;
+ }
+ pushEventToDataLayer('web.performance.measurements', {
+ _sitesinternal: { cwv: data.cwv },
+ });
+});
+
+track('click', (data) => {
+ const { source, target } = data;
+ pushEventToDataLayer('web.webinteraction.linkClicks', {
+ web: {
+ webInteraction: {
+ URL: target,
+ // eslint-disable-next-line no-nested-ternary
+ name: source,
+ linkClicks: { value: 1 },
+ type: target && new URL(target).origin !== window.location.origin
+ ? 'exit'
+ : 'other',
+ },
+ },
+ });
+});
+
+track('formsubmit', (ev) => pushEventToDataLayer('rum:form-submitted', {}, {
+ __adobe: {
+ analytics: {
+ contextData: { form: ev.source },
+ },
+ },
+}));
+
+// // Declare conversionEvent, bufferTimeoutId and tempConversionEvent,
+// // outside the convert function to persist them for buffering between
+// // subsequent convert calls
+// const CONVERSION_EVENT_TIMEOUT_MS = 100;
+// let bufferTimeoutId;
+// let conversionEvent;
+// let tempConversionEvent;
+// sampleRUM.always.on('convert', (data) => {
+// debug('convert', data);
+// const { source: conversionName, target: conversionValue, element } = data;
+// // eslint-disable-next-line no-undef
+// if (!element) {
+// return;
+// }
+
+// function analyticsTrackConversion() {
+// const xdmData = {
+// eventType: 'web.webinteraction.conversion',
+// _sitesinternal: {
+// conversion: {
+// conversionComplete: 1,
+// conversionName,
+// conversionValue,
+// },
+// },
+// };
+
+// if (element.tagName === 'FORM') {
+// xdmData.eventType = 'web.formFilledOut';
+// const formId = element?.id || element?.dataset?.action;
+// // eslint-disable-next-line no-underscore-dangle
+// xdmData._sitesinternal.form = {
+// ...(formId && { formId }),
+// // don't count as form complete, as this event should be tracked separately,
+// // track only the details of the form together with the conversion
+// formComplete: 0,
+// };
+// } else if (element.tagName === 'A') {
+// xdmData.eventType = 'web.webinteraction.linkClicks';
+// xdmData.web = {
+// webInteraction: {
+// URL: element.href,
+// // eslint-disable-next-line no-nested-ternary
+// name: element.text
+// ? element.text.trim()
+// : (element.innerHTML ? element.innerHTML.trim() : ''),
+// linkClicks: {
+// // don't count as link click, as this event should be tracked separately,
+// // track only the details of the link with the conversion
+// value: 0,
+// },
+// type: 'other',
+// },
+// };
+// }
+// pushEventToDataLayer(xdmData);
+// }
+
+// if (element.tagName === 'FORM') {
+// conversionEvent = {
+// ...data,
+// event: 'Form Complete',
+// };
+
+// if (conversionEvent.event === 'Form Complete'
+// // Check for undefined, since target can contain value 0 as well, which is falsy
+// && (data.target === undefined || data.source === undefined)
+// ) {
+// // If a buffer has already been set and tempConversionEvent exists,
+// // merge the two conversionEvent objects to send to alloy
+// if (bufferTimeoutId && tempConversionEvent) {
+// conversionEvent = { ...tempConversionEvent, ...conversionEvent };
+// } else {
+// // Temporarily hold the conversionEvent object until the timeout is complete
+// tempConversionEvent = { ...conversionEvent };
+
+// // If there is partial form conversion data,
+// // set the timeout buffer to wait for additional data
+// bufferTimeoutId = setTimeout(async () => {
+// analyticsTrackConversion({ ...conversionEvent });
+// tempConversionEvent = undefined;
+// conversionEvent = undefined;
+// }, CONVERSION_EVENT_TIMEOUT_MS);
+// }
+// }
+// return;
+// }
+
+// analyticsTrackConversion({ ...data });
+// tempConversionEvent = undefined;
+// conversionEvent = undefined;
+// });
+
+track('convert', (ev) => pushEventToDataLayer('rum:conversion', { element: ev.source, value: ev.target }));
+track('navigate', (ev) => pushEventToDataLayer('rum:internal-navigation', { url: ev.source }));
+track('search', (ev) => pushEventToDataLayer('rum:search', { element: ev.source, query: ev.target }));
+track('nullsearch', (ev) => pushEventToDataLayer('rum:search', { element: ev.source, query: ev.target, hasResults: false }));
+track('leave', () => pushEventToDataLayer('rum:page-lost-focus', { duration: performance.now() - performance.timeOrigin }));
+
+// track('viewblock', (ev) => pushEventToDataLayer('rum:block-viewed', {
+// element: ev.source, value: ev.target,
+// }));
+// track('viewmedia', (ev) => pushEventToDataLayer('rum:media-viewed', {
+// element: ev.source, value: ev.target,
+// }));
diff --git a/scripts/scripts.js b/scripts/scripts.js
index 3ed722bb..7250e3a5 100644
--- a/scripts/scripts.js
+++ b/scripts/scripts.js
@@ -1,8 +1,7 @@
+/* eslint-disable no-underscore-dangle */
import {
sampleRUM,
buildBlock,
- getAllMetadata,
- getMetadata,
loadHeader,
loadFooter,
decorateButtons,
@@ -13,41 +12,75 @@ import {
waitForLCP,
loadBlocks,
loadCSS,
+ getMetadata,
} from './lib-franklin.js';
import {
- analyticsTrack404,
- analyticsTrackConversion,
- analyticsTrackCWV,
- analyticsTrackError,
- initAnalyticsTrackingQueue,
- setupAnalyticsTrackingWithAlloy,
-} from './analytics/lib-analytics.js';
-
-const LCP_BLOCKS = []; // add your LCP blocks to the list
+ initMartech,
+ updateUserConsent,
+ martechEager,
+ martechLazy,
+ martechDelayed,
+} from './adobe-martech/index.js';
+
+const LCP_BLOCKS = ['carousel']; // add your LCP blocks to the list
window.hlx.RUM_GENERATION = 'project-1'; // add your RUM generation information here
-// Define the custom audiences mapping for experience decisioning
-const AUDIENCES = {
- mobile: () => window.innerWidth < 600,
- desktop: () => window.innerWidth >= 600,
- 'new-visitor': () => !localStorage.getItem('franklin-visitor-returning'),
- 'returning-visitor': () => !!localStorage.getItem('franklin-visitor-returning'),
-};
+const martechLoadedPromise = initMartech({
+ datastreamId: 'cc68fdd3-4db1-432c-adce-288917ddf108',
+ orgId: '908936ED5D35CC220A495CD4@AdobeOrg',
+ defaultConsent: 'in', // 'pending',
+ onBeforeEventSend: (options) => {
+ if (options.xdm.eventType === 'decisioning.propositionFetch') {
+ options.data ||= {};
+ options.data.__adobe ||= {};
+ options.data.__adobe.target = {
+ /* add target parameters here.
+ documentation: https://experienceleague.adobe.com/en/docs/platform-learn/migrate-target-to-websdk/send-parameters#parameter-mapping-summary */
+ };
+ }
+
+ /* add marketing campaign detail to analytics */
+ if (options.xdm.eventType === 'web.webpagedetails.pageViews' && options.data?.__adobe?.analytics) {
+ const usp = new URLSearchParams(window.Location.search);
+ options.data.__adobe.analytics.campaign = usp.get('utm_campaign') || undefined;
+ }
+
+ /* add experiment details to XDM */
+ const { experiment } = window.hlx;
+ options.xdm._sitesinternal = {
+ ...options.xdm._sitesinternal,
+ ...(experiment && { experiment }), // add experiment details, if existing, to all events
+ };
+ },
+}, {
+ launchUrls: [
+ 'https://assets.adobedtm.com/51b39232f128/2609377b4aba/launch-6c3a8fffe137-development.min.js',
+ ],
+ personalization: getMetadata('target') || new URLSearchParams(window.location.search).has('target'),
+});
+
+window.addEventListener('consent', (ev) => {
+ updateUserConsent({
+ collect: ev.detail.categories.includes('CC_ANALYTICS'),
+ marketing: ev.detail.categories.includes('CC_MARKETING'),
+ personalize: ev.detail.categories.includes('CC_PERSONALIZATION'),
+ share: ev.detail.categories.includes('CC_MARKETING'),
+ });
+});
+window.addEventListener('consent-updated', (ev) => {
+ updateUserConsent({
+ collect: ev.detail.categories.includes('CC_ANALYTICS'),
+ marketing: ev.detail.categories.includes('CC_MARKETING'),
+ personalize: ev.detail.categories.includes('CC_PERSONALIZATION'),
+ share: ev.detail.categories.includes('CC_MARKETING'),
+ });
+});
window.hlx.plugins.add('rum-conversion', {
url: '/plugins/rum-conversion/src/index.js',
load: 'lazy',
});
-window.hlx.plugins.add('experimentation', {
- condition: () => getMetadata('experiment')
- || Object.keys(getAllMetadata('campaign')).length
- || Object.keys(getAllMetadata('audience')).length,
- options: { audiences: AUDIENCES },
- load: 'eager',
- url: '/plugins/experimentation/src/index.js',
-});
-
/**
* Determine if we are serving content for the block-library, if so don't load the header or footer
* @returns {boolean} True if we are loading block library content
@@ -190,9 +223,11 @@ async function loadEager(doc) {
const main = doc.querySelector('main');
if (main) {
- await initAnalyticsTrackingQueue();
decorateMain(main);
- await waitForLCP(LCP_BLOCKS);
+ await Promise.all([
+ martechLoadedPromise.then(martechEager),
+ waitForLCP(LCP_BLOCKS),
+ ]);
}
}
@@ -241,6 +276,8 @@ async function loadLazy(doc) {
loadCSS(`${window.hlx.codeBasePath}/styles/lazy-styles.css`);
}
addFavIcon(`${window.wknd.demoConfig.demoBase || window.hlx.codeBasePath}/favicon.png`);
+ await import('./rum-to-analytics.js');
+ await martechLazy();
sampleRUM('lazy');
sampleRUM.observe(main.querySelectorAll('div[data-block-name]'));
sampleRUM.observe(main.querySelectorAll('picture > img'));
@@ -260,6 +297,7 @@ function loadDelayed() {
window.setTimeout(() => {
window.hlx.plugins.load('delayed');
window.hlx.plugins.run('loadDelayed');
+ martechDelayed();
return import('./delayed.js');
}, 3000);
// load anything that can be postponed to the latest here
@@ -270,75 +308,9 @@ async function loadPage() {
await loadEager(document);
await window.hlx.plugins.load('lazy');
await loadLazy(document);
- const setupAnalytics = setupAnalyticsTrackingWithAlloy(document);
+ // const setupAnalytics = setupAnalyticsTrackingWithAlloy(document);
loadDelayed();
- await setupAnalytics;
+ // await setupAnalytics;
}
-const cwv = {};
-
-// Forward the RUM CWV cached measurements to edge using WebSDK before the page unloads
-window.addEventListener('beforeunload', () => {
- if (!Object.keys(cwv).length) return;
- analyticsTrackCWV(cwv);
-});
-
-// Callback to RUM CWV checkpoint in order to cache the measurements
-sampleRUM.always.on('cwv', async (data) => {
- if (!data.cwv) return;
- Object.assign(cwv, data.cwv);
-});
-
-sampleRUM.always.on('404', analyticsTrack404);
-sampleRUM.always.on('error', analyticsTrackError);
-
-// Declare conversionEvent, bufferTimeoutId and tempConversionEvent,
-// outside the convert function to persist them for buffering between
-// subsequent convert calls
-const CONVERSION_EVENT_TIMEOUT_MS = 100;
-let bufferTimeoutId;
-let conversionEvent;
-let tempConversionEvent;
-sampleRUM.always.on('convert', (data) => {
- const { element } = data;
- // eslint-disable-next-line no-undef
- if (!element || !alloy) {
- return;
- }
-
- if (element.tagName === 'FORM') {
- conversionEvent = {
- ...data,
- event: 'Form Complete',
- };
-
- if (conversionEvent.event === 'Form Complete'
- // Check for undefined, since target can contain value 0 as well, which is falsy
- && (data.target === undefined || data.source === undefined)
- ) {
- // If a buffer has already been set and tempConversionEvent exists,
- // merge the two conversionEvent objects to send to alloy
- if (bufferTimeoutId && tempConversionEvent) {
- conversionEvent = { ...tempConversionEvent, ...conversionEvent };
- } else {
- // Temporarily hold the conversionEvent object until the timeout is complete
- tempConversionEvent = { ...conversionEvent };
-
- // If there is partial form conversion data,
- // set the timeout buffer to wait for additional data
- bufferTimeoutId = setTimeout(async () => {
- analyticsTrackConversion({ ...conversionEvent });
- tempConversionEvent = undefined;
- conversionEvent = undefined;
- }, CONVERSION_EVENT_TIMEOUT_MS);
- }
- }
- return;
- }
-
- analyticsTrackConversion({ ...data });
- tempConversionEvent = undefined;
- conversionEvent = undefined;
-});
-
loadPage();