@temple-wallet/extension-ads 2.0.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -107,12 +107,10 @@ interface AdActionBase {
107
107
  type: AdActionType;
108
108
  }
109
109
  interface InsertAdActionProps {
110
- ad: AdMetadata;
111
- fallbacks: AdMetadata[];
112
- /** @deprecated // Always wrapping now
113
- * TODO: Clean-up usage
110
+ /** A value of 'number' type stands for the value with respective index in `BANNER_ADS_META`. It is done to shorten
111
+ * ads stack Iframe URL search parameters.
114
112
  */
115
- shouldUseDivWrapper?: boolean;
113
+ adsMetadata: (number | AdMetadata)[];
116
114
  divWrapperStyle?: StringRecord<string>;
117
115
  elementStyle?: StringRecord<string>;
118
116
  stylesOverrides?: AdStylesOverrides[];
@@ -129,6 +127,7 @@ interface SimpleInsertAdAction extends AdActionBase, InsertAdActionProps {
129
127
  type: AdActionType.SimpleInsertAd;
130
128
  parent: HTMLElement;
131
129
  insertionIndex: number;
130
+ isSiblingReplacement: boolean;
132
131
  }
133
132
  interface RemoveElementAction extends AdActionBase {
134
133
  type: AdActionType.RemoveElement;
@@ -176,11 +175,20 @@ interface IAdsConfiguration {
176
175
  tkeyInpageAdUrl: string;
177
176
  swapTkeyUrl: string;
178
177
  externalAdsActivityMessageType: string;
178
+ getPersonaIframeURL: (id: string, shape: PersonaAdShape) => string;
179
+ getAdsStackIframeURL: (id: string, adsMetadataIds: (number | AdMetadata)[], origin: string) => string;
179
180
  }
180
181
  declare const configureAds: (config: IAdsConfiguration) => void;
181
182
 
182
183
  declare const executeAdsActions: (adsActions: AdAction[]) => Promise<PromiseSettledResult<void>[]>;
183
184
 
185
+ /**
186
+ * Tries to render specified ads one-by-one until one of them is loaded or loading of all of them failed. Use it
187
+ * in a dedicated iframe. Sends messages to the parent window on an attempt to render an ad, on successful rendering,
188
+ * on ad resize, and on error.
189
+ */
190
+ declare const renderAdsStack: (adId: string, adsMetadata: (number | AdMetadata)[], origin: string) => Promise<void>;
191
+
184
192
  declare const transformRawRules: (location: Location, rules: RawAllAdsRules) => AdsRules;
185
193
 
186
194
  declare class TempleWalletApi {
@@ -195,4 +203,4 @@ declare class TempleWalletApi {
195
203
  getAllRules: () => Promise<RawAllAdsRules>;
196
204
  }
197
205
 
198
- export { type AdAction, AdActionType, type AdsProviderName, AdsProviderTitle, type AdsRules, type PersonaAdShape, type RawAllAdsRules, TempleWalletApi, configureAds, executeAdsActions, getAdsActions, transformRawRules };
206
+ export { type AdAction, AdActionType, type AdsProviderName, AdsProviderTitle, type AdsRules, type PersonaAdShape, type RawAllAdsRules, TempleWalletApi, configureAds, executeAdsActions, getAdsActions, renderAdsStack, transformRawRules };
package/dist/index.js CHANGED
@@ -1,21 +1,22 @@
1
1
  'use strict';
2
2
 
3
3
  var nanoid = require('nanoid');
4
- var Ce = require('webextension-polyfill');
4
+ var Fe = require('webextension-polyfill');
5
5
  var lodash = require('lodash');
6
- var Ge = require('@vespaiach/axios-fetch-adapter');
7
- var $e = require('axios');
6
+ var nt = require('@vespaiach/axios-fetch-adapter');
7
+ var rt = require('axios');
8
8
 
9
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
10
 
11
- var Ce__default = /*#__PURE__*/_interopDefault(Ce);
12
- var Ge__default = /*#__PURE__*/_interopDefault(Ge);
13
- var $e__default = /*#__PURE__*/_interopDefault($e);
11
+ var Fe__default = /*#__PURE__*/_interopDefault(Fe);
12
+ var nt__default = /*#__PURE__*/_interopDefault(nt);
13
+ var rt__default = /*#__PURE__*/_interopDefault(rt);
14
14
 
15
- var xe=Object.defineProperty,Te=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var U=Object.getOwnPropertySymbols;var se=Object.prototype.hasOwnProperty,ie=Object.prototype.propertyIsEnumerable;var re=(e,t,n)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,y=(e,t)=>{for(var n in t||(t={}))se.call(t,n)&&re(e,n,t[n]);if(U)for(var n of U(t))ie.call(t,n)&&re(e,n,t[n]);return e},S=(e,t)=>Te(e,we(t));var g=(e,t)=>{var n={};for(var i in e)se.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(e!=null&&U)for(var i of U(e))t.indexOf(i)<0&&ie.call(e,i)&&(n[i]=e[i]);return n};var f=(e,t,n)=>new Promise((i,r)=>{var s=d=>{try{o(n.next(d));}catch(l){r(l);}},a=d=>{try{o(n.throw(d));}catch(l){r(l);}},o=d=>d.done?i(d.value):Promise.resolve(d.value).then(s,a);o((n=n.apply(e,t)).next());});var oe=e=>!!e;var I=(e=300)=>new Promise(t=>setTimeout(t,e));var h=class{};h.HYPELAB_NATIVE_PLACEMENT_SLUG="",h.HYPELAB_SMALL_PLACEMENT_SLUG="",h.HYPELAB_HIGH_PLACEMENT_SLUG="",h.HYPELAB_WIDE_PLACEMENT_SLUG="",h.HYPELAB_ADS_WINDOW_URL="",h.TKEY_INPAGE_AD_URL="",h.SWAP_TKEY_URL="",h.EXTERNAL_ADS_ACTIVITY_MESSAGE_TYPE="";var ve=e=>{let{hypelab:t,hypelabAdsWindowUrl:n,tkeyInpageAdUrl:i,swapTkeyUrl:r,externalAdsActivityMessageType:s}=e,{native:a,small:o,regular:d,wide:l}=t;h.HYPELAB_NATIVE_PLACEMENT_SLUG=a,h.HYPELAB_SMALL_PLACEMENT_SLUG=o,h.HYPELAB_HIGH_PLACEMENT_SLUG=d,h.HYPELAB_WIDE_PLACEMENT_SLUG=l,h.HYPELAB_ADS_WINDOW_URL=n,h.TKEY_INPAGE_AD_URL=i,h.SWAP_TKEY_URL=r,h.EXTERNAL_ADS_ACTIVITY_MESSAGE_TYPE=s;};var ae=[{source:{providerName:"Persona",shape:"wide"},dimensions:{width:970,height:90,minContainerWidth:600,minContainerHeight:60,maxContainerWidth:1440,maxContainerHeight:110}},{source:{providerName:"Temple"},dimensions:{width:728,height:90,minContainerWidth:600,minContainerHeight:60,maxContainerWidth:1440,maxContainerHeight:110}},{source:{providerName:"HypeLab",native:!1,size:"high"},dimensions:{width:300,height:250,minContainerWidth:210,minContainerHeight:170,maxContainerWidth:400,maxContainerHeight:300}},{source:{providerName:"Persona",shape:"squarish"},dimensions:{width:300,height:250,minContainerWidth:210,minContainerHeight:170,maxContainerWidth:400,maxContainerHeight:300}},{source:{providerName:"HypeLab",native:!1,size:"small",shouldNotUseStrictContainerLimits:!0},dimensions:{width:320,height:50,minContainerWidth:230,minContainerHeight:32,maxContainerWidth:420,maxContainerHeight:110}},{source:{providerName:"Persona",shape:"regular",shouldNotUseStrictContainerLimits:!0},dimensions:{width:321,height:101,minContainerWidth:230,minContainerHeight:32,maxContainerWidth:420,maxContainerHeight:110}}],le=(e,t)=>({source:{providerName:"HypeLab",native:!0,slug:h.HYPELAB_NATIVE_PLACEMENT_SLUG},dimensions:{width:Math.max(160,e),height:Math.max(16,t),minContainerWidth:2,minContainerHeight:2,maxContainerWidth:1/0,maxContainerHeight:1/0}});var v="twa";var b=`iframe[${v}], div[${v}]`,W=e=>{let t=e.tagName.toLowerCase();return (t==="iframe"||t==="div")&&e.hasAttribute(v)},de=e=>{let t=getComputedStyle(e),n={width:0,height:0},i=["width","height"];for(let r of i){let s=t[r],o=e.getAttribute(r)||s;if(/\d+px/.test(o))n[r]=Number(o.replace("px",""));else {let{width:d,height:l}=e.getBoundingClientRect();n[r]=r==="width"?d:l;}}return n},L=(e,t,n=document)=>e?t?[...n.querySelectorAll(e)]:[n.querySelector(e)].filter(i=>!!i):[],B=(e,t)=>{let n=e;for(let i=0;i<t;i++){let r=n.parentElement;if(!r)return null;n=r;}return n},ce=(e,t,n,i,r)=>e<2&&t<2?[]:r?[le(e,t)]:ae.filter(({source:s,dimensions:a})=>{let{minContainerWidth:o,maxContainerWidth:d,minContainerHeight:l,maxContainerHeight:u,width:m}=a,c=i?m:o;return !((n||!s.shouldNotUseStrictContainerLimits)&&(e<c||t<l&&t>=2)||n&&(e>d||t>u))});var me=(e,t,n)=>f(void 0,null,function*(){let{isMultiple:i,cssString:r,parentDepth:s}=e.parentSelector,a=L(r,i).map(o=>B(o,s)).filter(o=>!!o);return yield Promise.all(a.map(o=>f(void 0,null,function*(){yield I(0),Le(o,e,t,n);}))),a}),Le=(e,t,n,i)=>{var ee;let{shouldUseDivWrapper:r,divWrapperStyle:s,elementStyle:a,adSelector:o,insertionIndex:d,insertBeforeSelector:l,insertAfterSelector:u,insertionsCount:m=1,elementToMeasureSelector:c,stylesOverrides:A,shouldHideOriginal:E=!1,isNative:R}=t,{isMultiple:P,cssString:T,parentDepth:H}=o,J=L(b,!0,e).reduce((p,x)=>p.some(C=>C.contains(x)||x.contains(C))?p:[...p,x],[]).length,M=m-J;if(L(T,P,e).map(p=>B(p,H)).filter(p=>oe(p)&&!W(p)).forEach(p=>{var x,C;if(M<=0){let{display:N}=window.getComputedStyle(p);(!E||N!=="none")&&i.push({type:E?"hide-element":"remove-element",element:p});}else {let N=((x=p.parentElement)==null?void 0:x.children.length)===1?p.parentElement:p;c&&(N=(C=document.querySelector(c))!=null?C:N);let ye={type:"replace-element",element:p,shouldUseDivWrapper:r,divWrapperStyle:s,elementStyle:a,stylesOverrides:A},ge={type:"hide-element",element:p},Pe={type:"simple-insert-ad",shouldUseDivWrapper:r,divWrapperStyle:s,elementStyle:a,parent:p.parentElement,insertionIndex:Array.from(p.parentElement.children).indexOf(p),stylesOverrides:A},te=p.nextElementSibling,Se=te&&W(te),ne=E?Se?[]:[ge,Pe]:[ye];ne.length>0&&n(N,!1,!0,R,...ne)&&M--;}}),M<=0)return;let D=-1,Z=e,Y=e,j=l||u;if(j){let p=e.querySelector(j),x=p==null?void 0:p.parentElement;p&&x&&(Z=x,D=Array.from(e.children).indexOf(p)+(l?0:1),Y=c&&document.querySelector(c)||p);}else {let p=d!=null?d:0;D=p<0?Math.max(e.children.length+p,0):Math.min(p,e.children.length),Y=c&&document.querySelector(c)||((ee=e.children[D])!=null?ee:e);}if(D!==-1){let p={type:"simple-insert-ad",shouldUseDivWrapper:r,divWrapperStyle:s,elementStyle:a,parent:Z,insertionIndex:D,stylesOverrides:A};n(Y,!1,!0,R,...Array(M).fill(p));}};var Ae=(e,t,n)=>f(void 0,null,function*(){let{cssString:i,isMultiple:r}=e.selector,s=L(i,r);yield Promise.all(s.map(a=>f(void 0,null,function*(){yield I(0),Ie(a,e,t,n);})));}),Ie=(e,t,n,i)=>{let{selector:{shouldUseDivWrapper:r,parentDepth:s,divWrapperStyle:a},stylesOverrides:o,shouldHideOriginal:d}=t,l=B(e,s);if(!l||n.some(c=>c.contains(l))||W(l)||l.querySelector(b))return;let u={shouldUseDivWrapper:r,divWrapperStyle:a},m;if(r&&d){let c=l.parentElement,A=y({type:"simple-insert-ad",parent:c,insertionIndex:Array.from(c.children).indexOf(l),stylesOverrides:o==null?void 0:o.map(P=>{var T=P,{parentDepth:E}=T,R=g(T,["parentDepth"]);return S(y({},R),{parentDepth:E-1})})},u);m=[],window.getComputedStyle(l).display!=="none"&&m.push({type:"hide-element",element:l}),c.querySelector(b)||m.push(A);}else if(r)m=[y({type:"replace-element",element:l,stylesOverrides:o==null?void 0:o.map(R=>{var P=R,{parentDepth:A}=P,E=g(P,["parentDepth"]);return S(y({},E),{parentDepth:A-1})})},u)];else if(d){let c=y({type:"simple-insert-ad",parent:l,insertionIndex:0,stylesOverrides:o},u);m=Array.from(l.children).filter(A=>window.getComputedStyle(A).display!=="none").map(A=>({type:"hide-element",element:A})),l.querySelector(b)||m.push(c);}else m=[y({type:"replace-all-children",parent:l,stylesOverrides:o},u)];m.length>0&&i(l,!1,!1,!1,...m);};var He=i=>f(void 0,[i],function*({providersSelector:e,adPlacesRules:t,permanentAdPlacesRules:n}){var d,l,u;let r=[],s=(m,c,A,E,...R)=>{let{width:P,height:T}=de(m),H=ce(P,T,c,A,E);return H.length?(r.push(...R.map(w=>w.type==="hide-element"||w.type==="remove-element"?w:S(y({},w),{ad:H[0],fallbacks:H.slice(1)}))),!0):!1},a=[];yield Promise.all(n.map(m=>f(void 0,null,function*(){yield I(0),a=a.concat(yield me(m,s,r));}))),yield Promise.all(t.map(m=>f(void 0,null,function*(){yield I(0),yield Ae(m,a,s);})));let o=L(e,!0);for(let m of o){if(a.some(E=>E.contains(m)))continue;let c={type:"replace-element",element:m,shouldUseDivWrapper:!1},A=(u=(l=(d=m.parentElement)==null?void 0:d.closest("div, article, aside, footer, header"))!=null?l:m.parentElement)!=null?u:m;s(A,!0,!1,!1,c);}return r});var k=(e,t,n)=>{let i=document.createElement("div");i.id=nanoid.nanoid(),i.style.width=`${e}px`,i.style.height=`${t}px`;for(let o in n)i.style.setProperty(o,n[o]);let r=document.createElement("div");r.style.width=`${e}px`,r.style.height=`${t}px`,i.appendChild(r);let s=document.createElement("a");s.href=h.SWAP_TKEY_URL,s.target="_blank",s.rel="noopener noreferrer",s.style.width="100%",s.style.height="100%",r.appendChild(s);let a=document.createElement("img");return a.src=h.TKEY_INPAGE_AD_URL,a.style.width="100%",a.style.height="100%",s.appendChild(a),{element:i}};var V=(e,t,n)=>{let{width:i,height:r}=t,s=document.createElement("iframe");s.id=nanoid.nanoid(),s.src=_e(e,window.location.href,i,r,s.id),s.style.width=`${i}px`,s.style.height=`${r}px`,s.style.border="none";for(let a in n)s.style.setProperty(a,n[a]);return {element:s}},_e=(e,t,n,i,r)=>{let s,a,o;if(e.native)o=h.HYPELAB_NATIVE_PLACEMENT_SLUG,s=360,a=110;else switch(e.size){case"small":s=320,a=50,o=h.HYPELAB_SMALL_PLACEMENT_SLUG;break;case"high":s=300,a=250,o=h.HYPELAB_HIGH_PLACEMENT_SLUG;break;case"wide":s=728,a=90,o=h.HYPELAB_WIDE_PLACEMENT_SLUG;break}let d=new URL(h.HYPELAB_ADS_WINDOW_URL);return d.searchParams.set("w",String(n!=null?n:s)),d.searchParams.set("h",String(i!=null?i:a)),d.searchParams.set("p",o),d.searchParams.set("o",t),r&&d.searchParams.set("id",r),d.toString()};var G=(e,{width:t,height:n},i)=>{let r=nanoid.nanoid(),s=document.createElement("iframe");s.src=Ce__default.default.runtime.getURL(`iframes/persona-ad.html?id=${r}&shape=${e}`),s.id=r,s.style.width=`${t}px`,s.style.height=`${n}px`,s.style.border="none";for(let a in i)s.style.setProperty(a,i[a]);return {element:s}};var $=(r=>(r.Optimal="Optimal",r.HypeLab="HypeLab",r.Persona="Persona",r.Temple="Temple Wallet",r))($||{});var q=new Set,pe=new Set,ue=new Set,We=1e4,Ee=(e,t,n)=>{if(!q.has(e))return q.add(e),new Promise((i,r)=>{setTimeout(()=>{window.removeEventListener("message",s),r(new Error(`Timeout exceeded for ${e}`));},We);let s=a=>{var o;if(a.source===n.contentWindow)try{let d=typeof a.data=="string"?JSON.parse(a.data):a.data;if(d.id!==e)return;d.type==="ready"?(window.removeEventListener("message",s),i()):d.type==="error"&&(window.removeEventListener("message",s),r(new Error((o=d.reason)!=null?o:"Unknown error")));}catch(d){console.error("Observing error:",d);}};window.addEventListener("message",s);}).then(()=>{if(pe.has(e))return;pe.add(e),Be(n)?fe(e,t):K(n,t);}).finally(()=>void q.delete(e))},K=(e,t)=>{let n=new IntersectionObserver(i=>{i.some(r=>r.isIntersecting)&&(fe(e.id,t),n.disconnect());},{threshold:.5});n.observe(e);},fe=(e,t)=>{if(ue.has(e))return;ue.add(e);let n=window.parent.location.href;Ce__default.default.runtime.sendMessage({type:h.EXTERNAL_ADS_ACTIVITY_MESSAGE_TYPE,url:n,provider:$[t]}).catch(i=>void console.error(i));},Be=e=>{let t=e.getBoundingClientRect(),n=window.visualViewport;if(!n)return !1;let i=Math.min(Math.max(0,t.x),n.width),r=Math.min(Math.max(0,t.x+t.width),n.width),s=Math.min(Math.max(0,t.y),n.height),a=Math.min(Math.max(0,t.y+t.height),n.height),o=t.width*t.height;return (r-i)*(a-s)/o>=.5};var z=(e,t)=>{for(let n in t)e.style.setProperty(n,t[n]);};var Ue=(e,t,n)=>f(void 0,null,function*(){let{source:i,dimensions:r}=t,{elementStyle:s={},stylesOverrides:a=[]}=e;a.sort((c,A)=>c.parentDepth-A.parentDepth);let o,{providerName:d}=i,{element:l,postAppend:u}=d==="Temple"?k(r.width,r.height,s):d==="HypeLab"?V(i,r,s):G(i.shape,r,s);switch(l.setAttribute(v,"true"),n.appendChild(l),e.type){case"replace-all-children":o=e.parent,e.parent.innerHTML="",e.parent.appendChild(n);break;case"replace-element":o=e.element.parentElement,e.element.replaceWith(n);break;default:o=e.parent,e.parent.insertBefore(n,e.parent.children[e.insertionIndex]);break}u&&(yield u()),l instanceof HTMLIFrameElement?yield Ee(l.id,i.providerName,l):K(l,i.providerName);let m=0;a.forEach(({parentDepth:c,style:A})=>{for(;c>m&&o;)o=o.parentElement,m++;o&&z(o,A);});}),Q=(e,t)=>f(void 0,null,function*(){let{shouldUseDivWrapper:n,divWrapperStyle:i={}}=e,r=document.createElement("div");r.setAttribute(v,"true"),n?z(r,i):r.style.display="contents",yield Ue(e,t,r).catch(s=>{console.error("Inserting an ad attempt error:",s);let a=e.fallbacks.shift();if(a){let{ad:d,fallbacks:l,divWrapperStyle:u,elementStyle:m,stylesOverrides:c}=e,A={type:"replace-element",element:r,ad:d,fallbacks:l,divWrapperStyle:u,elementStyle:m,stylesOverrides:c};return Q(A,a)}let o=document.createElement("div");throw o.setAttribute(v,"true"),o.style.display="none",r.replaceWith(o),s});});var Oe=e=>Promise.allSettled(e.map(t=>f(void 0,null,function*(){t.type==="remove-element"?t.element.remove():t.type==="hide-element"?t.element.style.setProperty("display","none"):yield Q(t,t.ad);})));var Fe=(e,t)=>{let{adPlacesRulesForAllDomains:n,providersRulesForAllDomains:i,providersSelectors:r,providersToReplaceAtAllSites:s,permanentAdPlacesRulesForAllDomains:a,permanentNativeAdPlacesRulesForAllDomains:o={},timestamp:d}=t,{hostname:l,href:u}=e,m=u.replace(/#.*$/,""),c=A=>{let E=A.source.includes("#")?u:m;return A.test(E)};return {adPlacesRules:Ye(l,c,n),permanentAdPlacesRules:ke(l,c,a,o),providersSelector:Ve(l,c,i,r,s),timestamp:d}},Ye=(e,t,n)=>{var s;return ((s=n[e])!=null?s:[]).map(d=>{var l=d,{urlRegexes:a}=l,o=g(l,["urlRegexes"]);return S(y({},o),{urlRegexes:a.map(u=>new RegExp(u))})}).reduce((a,u)=>{var m=u,{urlRegexes:o,selector:d}=m,l=g(m,["urlRegexes","selector"]);if(!o.some(t))return a;let R=d,{cssString:c}=R,A=g(R,["cssString"]),E=a.findIndex(H=>{var w=H,{selector:P}=w,T=g(w,["selector"]);let F=P,M=g(F,["cssString"]);return lodash.isEqual(A,M)&&lodash.isEqual(l,T)});return E===-1?a.push(y({selector:d},l)):a[E].selector.cssString+=", ".concat(c),a},[])},ke=(e,t,n,i={})=>{var o,d;let r=(o=n[e])!=null?o:[],s=(d=i[e])!=null?d:[];return r.map(m=>{var c=m,{urlRegexes:l}=c,u=g(c,["urlRegexes"]);return S(y({},u),{urlRegexes:l.map(A=>new RegExp(A)),isNative:!1})}).concat(s.map(m=>{var c=m,{urlRegexes:l}=c,u=g(c,["urlRegexes"]);return S(y({},u),{urlRegexes:l.map(A=>new RegExp(A)),isNative:!0})})).filter(({urlRegexes:l})=>l.some(t))},Ve=(e,t,n,i,r)=>{var m;let a=((m=n[e])!=null?m:[]).map(E=>{var R=E,{urlRegexes:c}=R,A=g(R,["urlRegexes"]);return S(y({},A),{urlRegexes:c.map(P=>new RegExp(P))})}).filter(({urlRegexes:c})=>c.some(t)),o=new Set,d=new Set,l=c=>{var E;if(o.has(c))return;((E=i[c])!=null?E:[]).forEach(R=>d.add(R)),o.add(c);};r.forEach(l),a.forEach(({providers:c})=>c.forEach(l));let u="";return d.forEach(c=>{u+=c+", ";}),u&&(u=u.slice(0,-2)),u};var _=e=>(...t)=>f(void 0,null,function*(){let{data:n}=yield e(...t);return n}),X=class{constructor(t){this.getAdPlacesRulesForAllDomains=_(()=>this.api.get("/slise-ad-rules/ad-places"));this.getProvidersToReplaceAtAllSites=_(()=>this.api.get("/slise-ad-rules/providers/all-sites"));this.getProvidersRulesForAllDomains=_(()=>this.api.get("/slise-ad-rules/providers/by-sites"));this.getSelectorsForAllProviders=_(()=>this.api.get("/slise-ad-rules/providers"));this.getPermanentAdPlacesRulesForAllDomains=_(()=>this.api.get("/slise-ad-rules/ad-places/permanent"));this.getPermanentNativeAdPlacesRulesForAllDomains=_(()=>this.api.get("/slise-ad-rules/ad-places/permanent-native"));this.getAllRules=()=>f(this,null,function*(){let[t,n,i,r,s,a]=yield Promise.all([this.getAdPlacesRulesForAllDomains(),this.getProvidersRulesForAllDomains(),this.getSelectorsForAllProviders(),this.getProvidersToReplaceAtAllSites(),this.getPermanentAdPlacesRulesForAllDomains(),this.getPermanentNativeAdPlacesRulesForAllDomains()]);return {adPlacesRulesForAllDomains:t,providersRulesForAllDomains:n,providersSelectors:i,providersToReplaceAtAllSites:r,permanentAdPlacesRulesForAllDomains:s,permanentNativeAdPlacesRulesForAllDomains:a,timestamp:Date.now()}});this.api=$e__default.default.create({baseURL:new URL("/api",t).href,adapter:Ge__default.default});}};
15
+ var Ce=Object.defineProperty,Ne=Object.defineProperties;var We=Object.getOwnPropertyDescriptors;var $=Object.getOwnPropertySymbols;var he=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var ue=(e,t,r)=>t in e?Ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,g=(e,t)=>{for(var r in t||(t={}))he.call(t,r)&&ue(e,r,t[r]);if($)for(var r of $(t))Ee.call(t,r)&&ue(e,r,t[r]);return e},P=(e,t)=>Ne(e,We(t));var T=(e,t)=>{var r={};for(var o in e)he.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(e!=null&&$)for(var o of $(e))t.indexOf(o)<0&&Ee.call(e,o)&&(r[o]=e[o]);return r};var f=(e,t,r)=>new Promise((o,n)=>{var s=m=>{try{i(r.next(m));}catch(l){n(l);}},a=m=>{try{i(r.throw(m));}catch(l){n(l);}},i=m=>m.done?o(m.value):Promise.resolve(m.value).then(s,a);i((r=r.apply(e,t)).next());});var fe=e=>!!e;var v=(e=300)=>new Promise(t=>setTimeout(t,e));var p=class{};p.HYPELAB_NATIVE_PLACEMENT_SLUG="",p.HYPELAB_SMALL_PLACEMENT_SLUG="",p.HYPELAB_HIGH_PLACEMENT_SLUG="",p.HYPELAB_WIDE_PLACEMENT_SLUG="",p.HYPELAB_ADS_WINDOW_URL="",p.TKEY_INPAGE_AD_URL="",p.SWAP_TKEY_URL="",p.EXTERNAL_ADS_ACTIVITY_MESSAGE_TYPE="",p.getPersonaIframeURL=()=>"",p.getAdsStackIframeURL=()=>"";var Oe=e=>{let{hypelab:t,hypelabAdsWindowUrl:r,tkeyInpageAdUrl:o,swapTkeyUrl:n,externalAdsActivityMessageType:s,getPersonaIframeURL:a,getAdsStackIframeURL:i}=e,{native:m,small:l,regular:c,wide:A}=t;p.HYPELAB_NATIVE_PLACEMENT_SLUG=m,p.HYPELAB_SMALL_PLACEMENT_SLUG=l,p.HYPELAB_HIGH_PLACEMENT_SLUG=c,p.HYPELAB_WIDE_PLACEMENT_SLUG=A,p.HYPELAB_ADS_WINDOW_URL=r,p.TKEY_INPAGE_AD_URL=o,p.SWAP_TKEY_URL=n,p.EXTERNAL_ADS_ACTIVITY_MESSAGE_TYPE=s,p.getPersonaIframeURL=a,p.getAdsStackIframeURL=i;};var b=[{source:{providerName:"Persona",shape:"wide"},dimensions:{width:970,height:90,minContainerWidth:900,minContainerHeight:60,maxContainerWidth:1/0,maxContainerHeight:300}},{source:{providerName:"Temple"},dimensions:{width:728,height:90,minContainerWidth:701,minContainerHeight:60,maxContainerWidth:1/0,maxContainerHeight:300}},{source:{providerName:"Persona",shape:"medium"},dimensions:{width:600,height:160,minContainerWidth:600,minContainerHeight:80,maxContainerWidth:800,maxContainerHeight:300}},{source:{providerName:"HypeLab",native:!1,size:"high"},dimensions:{width:300,height:250,minContainerWidth:300,minContainerHeight:170,maxContainerWidth:700,maxContainerHeight:1/0}},{source:{providerName:"Persona",shape:"squarish"},dimensions:{width:300,height:250,minContainerWidth:300,minContainerHeight:170,maxContainerWidth:700,maxContainerHeight:1/0}},{source:{providerName:"HypeLab",native:!1,size:"small",shouldNotUseStrictContainerLimits:!0},dimensions:{width:320,height:50,minContainerWidth:230,minContainerHeight:32,maxContainerWidth:420,maxContainerHeight:110}},{source:{providerName:"Persona",shape:"regular",shouldNotUseStrictContainerLimits:!0},dimensions:{width:321,height:101,minContainerWidth:230,minContainerHeight:32,maxContainerWidth:420,maxContainerHeight:110}}],ye=(e,t)=>({source:{providerName:"HypeLab",native:!0,slug:p.HYPELAB_NATIVE_PLACEMENT_SLUG},dimensions:{width:Math.max(160,e),height:Math.max(16,t),minContainerWidth:2,minContainerHeight:2,maxContainerWidth:1/0,maxContainerHeight:1/0}});var H="twa",z="twa-sibling-replacement";var K="adRenderStart",q="resize",D="ready",Y="error";var _=`iframe[${H}], div[${H}]`,C=e=>!!e.closest(_),N=e=>{var t;return !!((t=e.previousElementSibling)!=null&&t.getAttribute(z))},Q=e=>{let t=getComputedStyle(e),{x:r,right:o,width:n,height:s}=e.getBoundingClientRect(),a={width:n,height:s},i=["width","height"];for(let m of i){let l=t[m],A=e.getAttribute(m)||l;/\d+px/.test(A)&&(a[m]=Number(A.replace("px",""))),m==="width"&&r<0?a.width+=r:m==="width"&&o>window.innerWidth&&(a.width=window.innerWidth-r);}return a},L=(e,t,r=document)=>e?t?[...r.querySelectorAll(e)]:[r.querySelector(e)].filter(o=>!!o):[],F=(e,t)=>{let r=e;for(let o=0;o<t;o++){let n=r.parentElement;if(!n)return null;r=n;}return r},Re=b.length-2,ge=(e,t,r,o)=>e<2&&t<2?[]:o?[ye(e,t)]:b.reduce((n,{dimensions:s},a)=>{let{minContainerWidth:i,maxContainerWidth:m,minContainerHeight:l,maxContainerHeight:c,width:A}=s,d=!1;switch(r){case"permanent":d=a===Re||e>=A&&(t>=l||t<2);break;case"slot-replacement":d=a===Re||e>=i&&(t>=l||t<2);break;default:d=e>=i&&t>=l&&e<=m&&t<=c;}return d&&n.push(a),n},[]);var Se=(e,t,r)=>f(void 0,null,function*(){let{isMultiple:o,cssString:n,parentDepth:s}=e.parentSelector,a=L(n,o).map(i=>F(i,s)).filter(i=>!!i);return yield Promise.all(a.map(i=>f(void 0,null,function*(){yield v(0),Ue(i,e,t,r);}))),a}),Ue=(e,t,r,o)=>{var me;let{shouldUseDivWrapper:n,divWrapperStyle:s,elementStyle:a,adSelector:i,insertionIndex:m,insertBeforeSelector:l,insertAfterSelector:c,insertionsCount:A=1,elementToMeasureSelector:d,stylesOverrides:u,shouldHideOriginal:E=!1,isNative:y}=t,R=n?s:{display:"contents"},{isMultiple:w,cssString:I,parentDepth:M}=i,O=L(_,!0,e).reduce((h,x)=>h.some(B=>B.contains(x)||x.contains(B))?h:[...h,x],[]).length,S=A-O;if(L(I,w,e).map(h=>F(h,M)).filter(h=>fe(h)&&!C(h)).forEach(h=>{var B,ce;let x=window.getComputedStyle(h).display==="none";if(S<=0)(!E||!x)&&o.push({type:E?"hide-element":"remove-element",element:h});else {let J=((B=h.parentElement)==null?void 0:B.children.length)===1?h.parentElement:h;d&&(J=(ce=document.querySelector(d))!=null?ce:J);let He={type:"replace-element",element:h,divWrapperStyle:R,elementStyle:a,stylesOverrides:u},Ae={type:"hide-element",element:h},De={type:"simple-insert-ad",divWrapperStyle:R,elementStyle:a,parent:h.parentElement,insertionIndex:Array.from(h.parentElement.children).indexOf(h),isSiblingReplacement:!0,stylesOverrides:u},k=[],pe=N(h);E&&pe&&!x?k=[Ae]:E&&!pe?k=[Ae,De]:E||(k=[He]),k.length>0&&r(J,"permanent",y,...k)&&S--;}}),S<=0)return;let U=-1,le=e,j=e,de=l||c;if(de){let h=e.querySelector(de),x=h==null?void 0:h.parentElement;h&&x&&(le=x,U=Array.from(e.children).indexOf(h)+(l?0:1),j=d&&document.querySelector(d)||h);}else {let h=m!=null?m:0;U=h<0?Math.max(e.children.length+h,0):Math.min(h,e.children.length),j=d&&document.querySelector(d)||((me=e.children[U])!=null?me:e);}if(U!==-1){let h={type:"simple-insert-ad",divWrapperStyle:R,elementStyle:a,parent:le,insertionIndex:U,isSiblingReplacement:!1,stylesOverrides:u};r(j,"permanent",y,...Array(S).fill(h));}};var Be=["align-items","align-self","bottom","display","flex","flex-grow","flex-shrink","float","justify-content","justify-self","left","margin","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","padding","position","right","top","vertical-align","z-index"],Pe=(e,t,r)=>f(void 0,null,function*(){let o=L(e,!0).reduce((n,s)=>{let a=n.findIndex(d=>d.contains(s)),i=s.parentElement&&window.getComputedStyle(s.parentElement),{width:m,height:l}=Q(s),c=r.some(d=>{var u;return d.type==="replace-all-children"||d.type==="simple-insert-ad"?d.parent.contains(s)||s.contains(d.parent):((u=d.element.parentElement)==null?void 0:u.contains(s))||s.contains(d.element)}),A=(i==null?void 0:i.display)==="none"||(i==null?void 0:i.visibility)==="hidden";return c||m===0||l===0||A||(a>=0?n.splice(a,1,s):n.some(d=>d.contains(s))||n.push(s)),n},[]);yield Promise.all(o.map(n=>f(void 0,null,function*(){var i,m,l,c,A,d,u,E;yield v(0);let s=n.parentElement,a=(m=(i=s==null?void 0:s.closest("div, article, aside, footer, header"))!=null?i:(s==null?void 0:s.tagName.toLowerCase())==="body"?void 0:s)!=null?m:n;if(!C(n)&&!n.querySelector(_)&&!r.some(y=>y.type==="simple-insert-ad"?!1:y.type==="replace-all-children"?y.parent.contains(n):y.element===n)){let y=(l=n.getAttribute("style"))!=null?l:"",R=Object.fromEntries(y.split(";").filter(Boolean).map(S=>S.split(":").map(ae=>ae.trim())));if((c=R.width)!=null&&c.match(/^0[a-z]/)||(A=R.height)!=null&&A.match(/^0[a-z]/))return;let w=window.getComputedStyle(n),I=g(g({},Object.fromEntries(Be.map(S=>[S,w.getPropertyValue(S)]))),R),M={type:"hide-element",element:n},X={type:"simple-insert-ad",divWrapperStyle:I,parent:(d=n.parentElement)!=null?d:document.body,insertionIndex:Array.from((E=(u=n.parentElement)==null?void 0:u.children)!=null?E:[]).indexOf(n),isSiblingReplacement:!0},O=N(n)?window.getComputedStyle(n).display==="none"?[]:[M]:[M,X];t(a,"provider-replacement",!1,...O);}})));});var Te=(e,t,r)=>f(void 0,null,function*(){let{cssString:o,isMultiple:n}=e.selector,s=L(o,n);yield Promise.all(s.map(a=>f(void 0,null,function*(){yield v(0),ke(a,e,t,r);})));}),ke=(e,t,r,o)=>{let{selector:{shouldUseDivWrapper:n,parentDepth:s,divWrapperStyle:a},stylesOverrides:i,shouldHideOriginal:m}=t,l=F(e,s);if(!l||r.some(d=>d.contains(l))||C(l)||l.querySelector(_))return;let c={shouldUseDivWrapper:n,divWrapperStyle:a},A;if(n&&m){let d=l.parentElement,u=window.getComputedStyle(l).display==="none",E=g({type:"simple-insert-ad",parent:d,insertionIndex:Array.from(d.children).indexOf(l),stylesOverrides:i==null?void 0:i.map(w=>{var I=w,{parentDepth:y}=I,R=T(I,["parentDepth"]);return P(g({},R),{parentDepth:y-1})}),isSiblingReplacement:!0},c);A=[],u||A.push({type:"hide-element",element:l}),N(l)||A.push(E);}else if(n)A=[g({type:"replace-element",element:l,stylesOverrides:i==null?void 0:i.map(y=>{var R=y,{parentDepth:u}=R,E=T(R,["parentDepth"]);return P(g({},E),{parentDepth:u-1})})},c)];else if(m){let d={type:"simple-insert-ad",parent:l,insertionIndex:0,stylesOverrides:i,isSiblingReplacement:!0,divWrapperStyle:{display:"contents"}};A=Array.from(l.children).filter(u=>window.getComputedStyle(u).display!=="none").map(u=>({type:"hide-element",element:u})),l.querySelector(_)||A.push(d);}else A=[{type:"replace-all-children",parent:l,stylesOverrides:i,divWrapperStyle:{display:"contents"}}];A.length>0&&o(l,"slot-replacement",!1,...A);};var Ye=o=>f(void 0,[o],function*({providersSelector:e,adPlacesRules:t,permanentAdPlacesRules:r}){let n=[],s=(i,m,l,...c)=>{let{width:A,height:d}=Q(i),u=ge(A,d,m,l);return u.length?(n.push(...c.map(E=>E.type==="hide-element"||E.type==="remove-element"?E:P(g({},E),{adsMetadata:u}))),!0):!1},a=[];return yield Promise.all(r.map(i=>f(void 0,null,function*(){yield v(0),a=a.concat(yield Se(i,s,n));}))),yield Promise.all(t.map(i=>f(void 0,null,function*(){yield v(0),yield Te(i,a,s);}))),yield Pe(e,s,n),n});var ee=(n=>(n.Optimal="Optimal",n.HypeLab="HypeLab",n.Persona="Persona",n.Temple="Temple Wallet",n))(ee||{});var te=new Set,Ie=new Set,we=new Set,Ge=3e4,ve=e=>f(void 0,null,function*(){let t=e.id;if(!te.has(t))return te.add(t),new Promise((r,o)=>{setTimeout(()=>{window.removeEventListener("message",n),o(new Error(`Timeout exceeded for ${t}`));},Ge);let n=s=>{var a;if(s.source===e.contentWindow)try{let i=typeof s.data=="string"?JSON.parse(s.data):s.data;if(i.id!==t)return;switch(i.type){case D:r(i.adMetadata.source.providerName);break;case Y:window.removeEventListener("message",n),e.style.display="none",o(new Error((a=i.reason)!=null?a:"Unknown error"));break;case K:let{dimensions:m}=i.adMetadata,{width:l,height:c}=m;l>0&&c>0&&(e.style.width=`${m.width}px`,e.style.height=`${m.height}px`);break;case q:let{width:A,height:d}=i;e.style.width=`${A}px`,e.style.height=`${d}px`;}}catch(i){console.error("Observing error:",i);}};window.addEventListener("message",n);}).then(r=>{if(Ie.has(t))return;Ie.add(t),$e(e)?_e(t,r):Ve(e,r);}).catch(console.error).finally(()=>void te.delete(t))}),Ve=(e,t)=>{let r=new IntersectionObserver(o=>{o.some(n=>n.isIntersecting)&&(_e(e.id,t),r.disconnect());},{threshold:.5});r.observe(e);},_e=(e,t)=>{if(we.has(e))return;we.add(e);let r=window.parent.location.href;Fe__default.default.runtime.sendMessage({type:p.EXTERNAL_ADS_ACTIVITY_MESSAGE_TYPE,url:r,provider:ee[t]}).catch(o=>void console.error(o));},$e=e=>{let t=e.getBoundingClientRect(),r=window.visualViewport;if(!r)return !1;let o=Math.min(Math.max(0,t.x),r.width),n=Math.min(Math.max(0,t.x+t.width),r.width),s=Math.min(Math.max(0,t.y),r.height),a=Math.min(Math.max(0,t.y+t.height),r.height),i=t.width*t.height;return (n-o)*(a-s)/i>=.5};var ne=(e,t)=>{for(let r in t)e.style.setProperty(r,t[r]);};var Ke=(e,t)=>{["width","height"].forEach(o=>{var s;let n=(s=e.style[o])!=null?s:"";/^\d+(px)?$/.test(n)&&parseInt(n,10)<t[o]&&e.style.removeProperty(o);});},qe=(e,t)=>f(void 0,null,function*(){let{elementStyle:r={},stylesOverrides:o=[]}=e;o.sort((c,A)=>c.parentDepth-A.parentDepth);let n,s=nanoid.nanoid(),a=document.createElement("iframe");a.src=p.getAdsStackIframeURL(s,e.adsMetadata,window.location.href),a.id=s;let i=e.adsMetadata[0],{dimensions:m}=typeof i=="number"?b[i]:i;a.style.width=`${m.width}px`,a.style.height=`${m.height}px`,a.style.border="none";for(let c in r)a.style.setProperty(c,r[c]);switch(a.setAttribute(H,"true"),Ke(t,m),t.appendChild(a),e.type){case"replace-all-children":n=e.parent,e.parent.innerHTML="",e.parent.appendChild(t);break;case"replace-element":n=e.element.parentElement,e.element.replaceWith(t);break;default:e.isSiblingReplacement&&t.setAttribute(z,"true"),n=e.parent,e.parent.insertBefore(t,e.parent.children[e.insertionIndex]);break}ve(a);let l=0;o.forEach(({parentDepth:c,style:A})=>{for(;c>l&&n;)n=n.parentElement,l++;n&&ne(n,A);});}),Le=e=>f(void 0,null,function*(){let{divWrapperStyle:t={}}=e,r=document.createElement("div");r.setAttribute(H,"true"),ne(r,t),yield qe(e,r).catch(o=>{console.error("Inserting an ad attempt error:",o);let n=document.createElement("div");throw n.setAttribute(H,"true"),n.style.display="none",r.replaceWith(n),o});});var Qe=e=>Promise.allSettled(e.map(t=>f(void 0,null,function*(){t.type==="remove-element"?t.element.remove():t.type==="hide-element"?t.element.style.setProperty("display","none"):yield Le(t);})));var re=(e,t)=>{let r=document.createElement("div");r.style.width=`${e}px`,r.style.height=`${t}px`;let o=document.createElement("div");o.style.width=`${e}px`,o.style.height=`${t}px`,r.appendChild(o);let n=document.createElement("a");n.href=p.SWAP_TKEY_URL,n.target="_blank",n.rel="noopener noreferrer",n.style.width="100%",n.style.height="100%",o.appendChild(n);let s=document.createElement("img");return s.src=p.TKEY_INPAGE_AD_URL,s.style.width="100%",s.style.height="100%",n.appendChild(s),{element:r}};var se=(e,t,r)=>{let{width:o,height:n}=t,s=document.createElement("iframe");return s.src=Xe(e,r,o,n,s.id),s.style.width=`${o}px`,s.style.height=`${n}px`,s.style.border="none",{element:s}},Xe=(e,t,r,o,n)=>{let s,a,i;if(e.native)i=p.HYPELAB_NATIVE_PLACEMENT_SLUG,s=360,a=110;else switch(e.size){case"small":s=320,a=50,i=p.HYPELAB_SMALL_PLACEMENT_SLUG;break;case"high":s=300,a=250,i=p.HYPELAB_HIGH_PLACEMENT_SLUG;break;case"wide":s=728,a=90,i=p.HYPELAB_WIDE_PLACEMENT_SLUG;break}let m=new URL(p.HYPELAB_ADS_WINDOW_URL);return m.searchParams.set("w",String(r!=null?r:s)),m.searchParams.set("h",String(o!=null?o:a)),m.searchParams.set("p",i),m.searchParams.set("o",t),n&&m.searchParams.set("id",n),m.toString()};var ie=(e,t,{width:r,height:o})=>{let n=document.createElement("iframe");return n.src=p.getPersonaIframeURL(e,t),n.id=e,n.style.width=`${r}px`,n.style.height=`${o}px`,n.style.border="none",{element:n}};var je=3e4,V=e=>window.parent.postMessage(JSON.stringify(e),"*"),Me=(e,t,r)=>f(void 0,null,function*(){if(t.length===0){V({id:e,type:Y,reason:"No more ads to render"});return}let[o,...n]=t,s=typeof o=="number"?b[o]:o;V({id:e,type:K,adMetadata:s});let{source:a,dimensions:i}=s,m;switch(a.providerName){case"Temple":m=re(i.width,i.height);break;case"HypeLab":m=se(a,i,r);break;default:m=ie(e,a.shape,i);}let{element:l}=m;if(document.body.replaceChildren(l),l instanceof HTMLIFrameElement)return new Promise((c,A)=>{setTimeout(()=>{window.removeEventListener("message",u),A(new Error(`Timeout exceeded for ${e}, ad source: ${JSON.stringify(a)}`));},je);let d=!1,u=E=>{var y;if(E.source===l.contentWindow)try{let R=typeof E.data=="string"?JSON.parse(E.data):E.data;switch(R.type){case D:d||(d=!0,V({id:e,type:D,adMetadata:s}),c());break;case Y:window.removeEventListener("message",u),A(new Error((y=R.reason)!=null?y:"Unknown error"));break;case q:let{width:w,height:I}=R;w>0&&I>0&&(l.style.width=`${w}px`,l.style.height=`${I}px`,V(P(g({},R),{id:e})));}}catch(R){console.error("Observing error:",R);}};window.addEventListener("message",u);}).catch(c=>(console.error(c),Me(e,n,r)));V({id:e,type:D,adMetadata:s});});var Je=(e,t)=>{let{adPlacesRulesForAllDomains:r,providersRulesForAllDomains:o,providersSelectors:n,providersToReplaceAtAllSites:s,permanentAdPlacesRulesForAllDomains:a,permanentNativeAdPlacesRulesForAllDomains:i={},timestamp:m}=t,{hostname:l,href:c}=e,A=c.replace(/#.*$/,""),d=u=>{let E=u.source.includes("#")?c:A;return u.test(E)};return {adPlacesRules:Ze(l,d,r),permanentAdPlacesRules:et(l,d,a,i),providersSelector:tt(l,d,o,n,s),timestamp:m}},Ze=(e,t,r)=>{var s;return ((s=r[e])!=null?s:[]).map(m=>{var l=m,{urlRegexes:a}=l,i=T(l,["urlRegexes"]);return P(g({},i),{urlRegexes:a.map(c=>new RegExp(c))})}).reduce((a,c)=>{var A=c,{urlRegexes:i,selector:m}=A,l=T(A,["urlRegexes","selector"]);if(!i.some(t))return a;let y=m,{cssString:d}=y,u=T(y,["cssString"]),E=a.findIndex(I=>{var M=I,{selector:R}=M,w=T(M,["selector"]);let S=R,O=T(S,["cssString"]);return lodash.isEqual(u,O)&&lodash.isEqual(l,w)});return E===-1?a.push(g({selector:m},l)):a[E].selector.cssString+=", ".concat(d),a},[])},et=(e,t,r,o={})=>{var i,m;let n=(i=r[e])!=null?i:[],s=(m=o[e])!=null?m:[];return n.map(A=>{var d=A,{urlRegexes:l}=d,c=T(d,["urlRegexes"]);return P(g({},c),{urlRegexes:l.map(u=>new RegExp(u)),isNative:!1})}).concat(s.map(A=>{var d=A,{urlRegexes:l}=d,c=T(d,["urlRegexes"]);return P(g({},c),{urlRegexes:l.map(u=>new RegExp(u)),isNative:!0})})).filter(({urlRegexes:l})=>l.some(t))},tt=(e,t,r,o,n)=>{var A;let a=((A=r[e])!=null?A:[]).map(E=>{var y=E,{urlRegexes:d}=y,u=T(y,["urlRegexes"]);return P(g({},u),{urlRegexes:d.map(R=>new RegExp(R))})}).filter(({urlRegexes:d})=>d.some(t)),i=new Set,m=new Set,l=d=>{var E;if(i.has(d))return;((E=o[d])!=null?E:[]).forEach(y=>m.add(y)),i.add(d);};n.forEach(l),a.forEach(({providers:d})=>d.forEach(l));let c="";return m.forEach(d=>{c+=d+", ";}),c&&(c=c.slice(0,-2)),c};var W=e=>(...t)=>f(void 0,null,function*(){let{data:r}=yield e(...t);return r}),oe=class{constructor(t){this.getAdPlacesRulesForAllDomains=W(()=>this.api.get("/slise-ad-rules/ad-places"));this.getProvidersToReplaceAtAllSites=W(()=>this.api.get("/slise-ad-rules/providers/all-sites"));this.getProvidersRulesForAllDomains=W(()=>this.api.get("/slise-ad-rules/providers/by-sites"));this.getSelectorsForAllProviders=W(()=>this.api.get("/slise-ad-rules/providers"));this.getPermanentAdPlacesRulesForAllDomains=W(()=>this.api.get("/slise-ad-rules/ad-places/permanent"));this.getPermanentNativeAdPlacesRulesForAllDomains=W(()=>this.api.get("/slise-ad-rules/ad-places/permanent-native"));this.getAllRules=()=>f(this,null,function*(){let[t,r,o,n,s,a]=yield Promise.all([this.getAdPlacesRulesForAllDomains(),this.getProvidersRulesForAllDomains(),this.getSelectorsForAllProviders(),this.getProvidersToReplaceAtAllSites(),this.getPermanentAdPlacesRulesForAllDomains(),this.getPermanentNativeAdPlacesRulesForAllDomains()]);return {adPlacesRulesForAllDomains:t,providersRulesForAllDomains:r,providersSelectors:o,providersToReplaceAtAllSites:n,permanentAdPlacesRulesForAllDomains:s,permanentNativeAdPlacesRulesForAllDomains:a,timestamp:Date.now()}});this.api=rt__default.default.create({baseURL:new URL("/api",t).href,adapter:nt__default.default});}};
16
16
 
17
- exports.TempleWalletApi = X;
18
- exports.configureAds = ve;
19
- exports.executeAdsActions = Oe;
20
- exports.getAdsActions = He;
21
- exports.transformRawRules = Fe;
17
+ exports.TempleWalletApi = oe;
18
+ exports.configureAds = Oe;
19
+ exports.executeAdsActions = Qe;
20
+ exports.getAdsActions = Ye;
21
+ exports.renderAdsStack = Me;
22
+ exports.transformRawRules = Je;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@temple-wallet/extension-ads",
3
- "version": "2.0.1",
3
+ "version": "3.0.0",
4
4
  "main": "dist/index.js",
5
5
  "repository": {
6
6
  "type": "git",
@@ -11,6 +11,7 @@
11
11
  "scripts": {
12
12
  "build:dev": "tsup src/index.ts --dts --treeshake",
13
13
  "build": "tsup src/index.ts --dts --minify --treeshake",
14
+ "ts": "tsc --pretty",
14
15
  "lint": "eslint --quiet src",
15
16
  "lint:fix": "prettier \"./**/*\" --write --ignore-unknown",
16
17
  "clear:lint": "rimraf node_modules/.cache/.eslintcache",
@@ -1,18 +1,19 @@
1
1
  import { BANNER_ADS_META, buildHypeLabNativeMeta } from 'src/ads-meta';
2
- import { TEMPLE_WALLET_AD_ATTRIBUTE_NAME } from 'src/constants';
2
+ import { SIBLING_REPLACEMENT_ATTRIBUTE_NAME, TEMPLE_WALLET_AD_ATTRIBUTE_NAME } from 'src/constants';
3
+ import { AdType } from 'src/types/ads-actions';
3
4
  import { AdMetadata } from 'src/types/ads-meta';
4
5
 
5
6
  export const ourAdQuerySelector = `iframe[${TEMPLE_WALLET_AD_ATTRIBUTE_NAME}], div[${TEMPLE_WALLET_AD_ATTRIBUTE_NAME}]`;
6
7
 
7
- export const elementIsOurAd = (element: HTMLElement) => {
8
- const tagName = element.tagName.toLowerCase();
8
+ export const elementIsOurAd = (element: Element) => Boolean(element.closest(ourAdQuerySelector));
9
9
 
10
- return (tagName === 'iframe' || tagName === 'div') && element.hasAttribute(TEMPLE_WALLET_AD_ATTRIBUTE_NAME);
11
- };
10
+ export const prevBannerSiblingIsReplacement = (banner: Element) =>
11
+ Boolean(banner.previousElementSibling?.getAttribute(SIBLING_REPLACEMENT_ATTRIBUTE_NAME));
12
12
 
13
13
  export const getFinalSize = (element: Element) => {
14
14
  const elementStyle = getComputedStyle(element);
15
- const size = { width: 0, height: 0 };
15
+ const { x, right, width: rectWidth, height: rectHeight } = element.getBoundingClientRect();
16
+ const size = { width: rectWidth, height: rectHeight };
16
17
  const dimensions = ['width', 'height'] as const;
17
18
 
18
19
  for (const dimension of dimensions) {
@@ -22,9 +23,11 @@ export const getFinalSize = (element: Element) => {
22
23
 
23
24
  if (/\d+px/.test(rawDimension)) {
24
25
  size[dimension] = Number(rawDimension.replace('px', ''));
25
- } else {
26
- const { width, height } = element.getBoundingClientRect();
27
- size[dimension] = dimension === 'width' ? width : height;
26
+ }
27
+ if (dimension === 'width' && x < 0) {
28
+ size.width += x;
29
+ } else if (dimension === 'width' && right > window.innerWidth) {
30
+ size.width = window.innerWidth - x;
28
31
  }
29
32
  }
30
33
 
@@ -61,13 +64,14 @@ export const getParentOfDepth = (element: HTMLElement, depth: number) => {
61
64
  return parent;
62
65
  };
63
66
 
67
+ const smallestBannerAdsMetaIndex = BANNER_ADS_META.length - 2;
68
+
64
69
  export const pickAdsToDisplay = (
65
70
  containerWidth: number,
66
71
  containerHeight: number,
67
- shouldUseStrictContainerLimits: boolean,
68
- minContainerWidthIsBannerWidth: boolean,
72
+ adType: AdType,
69
73
  adIsNative: boolean
70
- ): AdMetadata[] => {
74
+ ): (number | AdMetadata)[] => {
71
75
  if (containerWidth < 2 && containerHeight < 2) {
72
76
  return [];
73
77
  }
@@ -76,25 +80,33 @@ export const pickAdsToDisplay = (
76
80
  return [buildHypeLabNativeMeta(containerWidth, containerHeight)];
77
81
  }
78
82
 
79
- return BANNER_ADS_META.filter(({ source, dimensions }) => {
83
+ return BANNER_ADS_META.reduce<number[]>((acc, { dimensions }, i) => {
80
84
  const { minContainerWidth, maxContainerWidth, minContainerHeight, maxContainerHeight, width } = dimensions;
81
85
 
82
- const actualMinContainerWidth = minContainerWidthIsBannerWidth ? width : minContainerWidth;
83
-
84
- if (
85
- (shouldUseStrictContainerLimits || !source.shouldNotUseStrictContainerLimits) &&
86
- (containerWidth < actualMinContainerWidth || (containerHeight < minContainerHeight && containerHeight >= 2))
87
- ) {
88
- return false;
86
+ let matches = false;
87
+ switch (adType) {
88
+ case AdType.Permanent:
89
+ matches =
90
+ i === smallestBannerAdsMetaIndex ||
91
+ (containerWidth >= width && (containerHeight >= minContainerHeight || containerHeight < 2));
92
+ break;
93
+ case AdType.SlotReplacement:
94
+ matches =
95
+ i === smallestBannerAdsMetaIndex ||
96
+ (containerWidth >= minContainerWidth && (containerHeight >= minContainerHeight || containerHeight < 2));
97
+ break;
98
+ default:
99
+ matches =
100
+ containerWidth >= minContainerWidth &&
101
+ containerHeight >= minContainerHeight &&
102
+ containerWidth <= maxContainerWidth &&
103
+ containerHeight <= maxContainerHeight;
89
104
  }
90
105
 
91
- if (
92
- shouldUseStrictContainerLimits &&
93
- (containerWidth > maxContainerWidth || containerHeight > maxContainerHeight)
94
- ) {
95
- return false;
106
+ if (matches) {
107
+ acc.push(i);
96
108
  }
97
109
 
98
- return true;
99
- });
110
+ return acc;
111
+ }, []);
100
112
  };
@@ -2,17 +2,17 @@ import {
2
2
  AddActionsIfAdResolutionAvailable,
3
3
  AdAction,
4
4
  AdActionType,
5
+ AdType,
5
6
  HideElementAction,
6
7
  InsertAdActionWithoutMeta,
7
- OmitAdInAction,
8
- RemoveElementAction,
9
- ReplaceElementWithAdAction
8
+ RemoveElementAction
10
9
  } from 'src/types/ads-actions';
11
10
  import type { AdsRules } from 'src/types/ads-rules';
12
11
  import { delay } from 'src/utils';
13
12
 
14
- import { applyQuerySelector, getFinalSize, pickAdsToDisplay } from './helpers';
13
+ import { getFinalSize, pickAdsToDisplay } from './helpers';
15
14
  import { processPermanentAdPlacesRule } from './process-permanent-rule';
15
+ import { processProvidersAds } from './process-providers-ads';
16
16
  import { processAdPlacesRule } from './process-rule';
17
17
 
18
18
  export const getAdsActions = async ({ providersSelector, adPlacesRules, permanentAdPlacesRules }: AdsRules) => {
@@ -20,27 +20,20 @@ export const getAdsActions = async ({ providersSelector, adPlacesRules, permanen
20
20
 
21
21
  const addActionsIfAdResolutionAvailable: AddActionsIfAdResolutionAvailable = (
22
22
  elementToMeasure: Element,
23
- shouldUseStrictContainerLimits: boolean,
24
- minContainerWidthIsBannerWidth: boolean,
23
+ adType: AdType,
25
24
  adIsNative: boolean,
26
25
  ...actionsBases: (InsertAdActionWithoutMeta | HideElementAction | RemoveElementAction)[]
27
26
  ): boolean => {
28
27
  const { width, height } = getFinalSize(elementToMeasure);
29
- const stack = pickAdsToDisplay(
30
- width,
31
- height,
32
- shouldUseStrictContainerLimits,
33
- minContainerWidthIsBannerWidth,
34
- adIsNative
35
- );
28
+ const adsMetadata = pickAdsToDisplay(width, height, adType, adIsNative);
36
29
 
37
- if (!stack.length) return false;
30
+ if (!adsMetadata.length) return false;
38
31
 
39
32
  result.push(
40
33
  ...actionsBases.map<AdAction>(actionBase =>
41
34
  actionBase.type === AdActionType.HideElement || actionBase.type === AdActionType.RemoveElement
42
35
  ? actionBase
43
- : { ...actionBase, ad: stack[0]!, fallbacks: stack.slice(1) }
36
+ : { ...actionBase, adsMetadata }
44
37
  )
45
38
  );
46
39
 
@@ -73,24 +66,7 @@ export const getAdsActions = async ({ providersSelector, adPlacesRules, permanen
73
66
  })
74
67
  );
75
68
 
76
- const bannersFromProviders = applyQuerySelector(providersSelector, true);
77
-
78
- for (const banner of bannersFromProviders) {
79
- if (permanentAdsParents.some(parent => parent.contains(banner))) continue;
80
-
81
- const actionBase: OmitAdInAction<ReplaceElementWithAdAction> = {
82
- type: AdActionType.ReplaceElement,
83
- element: banner as HTMLElement,
84
- shouldUseDivWrapper: false
85
- };
86
-
87
- const elementToMeasure =
88
- banner.parentElement?.closest<HTMLElement>('div, article, aside, footer, header') ??
89
- banner.parentElement ??
90
- banner;
91
-
92
- addActionsIfAdResolutionAvailable(elementToMeasure, true, false, false, actionBase);
93
- }
69
+ await processProvidersAds(providersSelector, addActionsIfAdResolutionAvailable, result);
94
70
 
95
71
  return result;
96
72
  };
@@ -1,16 +1,25 @@
1
1
  import {
2
2
  AdAction,
3
3
  AdActionType,
4
+ AdType,
4
5
  AddActionsIfAdResolutionAvailable,
5
6
  HideElementAction,
7
+ InsertAdActionWithoutMeta,
6
8
  OmitAdInAction,
9
+ RemoveElementAction,
7
10
  ReplaceElementWithAdAction,
8
11
  SimpleInsertAdAction
9
12
  } from 'src/types/ads-actions';
10
13
  import { PermanentAdPlacesRule } from 'src/types/ads-rules';
11
14
  import { delay, isTruthy } from 'src/utils';
12
15
 
13
- import { applyQuerySelector, elementIsOurAd, getParentOfDepth, ourAdQuerySelector } from './helpers';
16
+ import {
17
+ applyQuerySelector,
18
+ elementIsOurAd,
19
+ getParentOfDepth,
20
+ ourAdQuerySelector,
21
+ prevBannerSiblingIsReplacement
22
+ } from './helpers';
14
23
 
15
24
  export const processPermanentAdPlacesRule = async (
16
25
  rule: PermanentAdPlacesRule,
@@ -46,7 +55,7 @@ const processPermanentAdsParent = (
46
55
  ) => {
47
56
  const {
48
57
  shouldUseDivWrapper,
49
- divWrapperStyle,
58
+ divWrapperStyle: originalDivWrapperStyle,
50
59
  elementStyle,
51
60
  adSelector,
52
61
  insertionIndex,
@@ -58,6 +67,7 @@ const processPermanentAdsParent = (
58
67
  shouldHideOriginal = false,
59
68
  isNative
60
69
  } = rule;
70
+ const divWrapperStyle = shouldUseDivWrapper ? originalDivWrapperStyle : { display: 'contents' };
61
71
 
62
72
  const {
63
73
  isMultiple: shouldSearchForManyBannersInParent,
@@ -81,9 +91,9 @@ const processPermanentAdsParent = (
81
91
  .filter((value): value is HTMLElement => isTruthy(value) && !elementIsOurAd(value));
82
92
 
83
93
  banners.forEach(banner => {
94
+ const bannerIsHidden = window.getComputedStyle(banner).display === 'none';
84
95
  if (insertionsLeft <= 0) {
85
- const { display: bannerDisplay } = window.getComputedStyle(banner);
86
- if (!shouldHideOriginal || bannerDisplay !== 'none') {
96
+ if (!shouldHideOriginal || !bannerIsHidden) {
87
97
  result.push({
88
98
  type: shouldHideOriginal ? AdActionType.HideElement : AdActionType.RemoveElement,
89
99
  element: banner
@@ -97,7 +107,6 @@ const processPermanentAdsParent = (
97
107
  const replaceActionBase: OmitAdInAction<ReplaceElementWithAdAction> = {
98
108
  type: AdActionType.ReplaceElement,
99
109
  element: banner,
100
- shouldUseDivWrapper,
101
110
  divWrapperStyle,
102
111
  elementStyle,
103
112
  stylesOverrides
@@ -108,24 +117,26 @@ const processPermanentAdsParent = (
108
117
  };
109
118
  const insertActionBase: OmitAdInAction<SimpleInsertAdAction> = {
110
119
  type: AdActionType.SimpleInsertAd,
111
- shouldUseDivWrapper,
112
120
  divWrapperStyle,
113
121
  elementStyle,
114
122
  parent: banner.parentElement!,
115
123
  insertionIndex: Array.from(banner.parentElement!.children).indexOf(banner),
124
+ isSiblingReplacement: true,
116
125
  stylesOverrides
117
126
  };
118
127
 
119
- const nextBannerSibling = banner.nextElementSibling;
120
- const nextBannerSiblingIsOurAd = nextBannerSibling && elementIsOurAd(nextBannerSibling as HTMLElement);
121
- const actionsToInsert = shouldHideOriginal
122
- ? nextBannerSiblingIsOurAd
123
- ? []
124
- : [hideActionBase, insertActionBase]
125
- : [replaceActionBase];
128
+ let actionsToInsert: (InsertAdActionWithoutMeta | HideElementAction | RemoveElementAction)[] = [];
129
+ const ourAdAlreadyInserted = prevBannerSiblingIsReplacement(banner);
130
+ if (shouldHideOriginal && ourAdAlreadyInserted && !bannerIsHidden) {
131
+ actionsToInsert = [hideActionBase];
132
+ } else if (shouldHideOriginal && !ourAdAlreadyInserted) {
133
+ actionsToInsert = [hideActionBase, insertActionBase];
134
+ } else if (!shouldHideOriginal) {
135
+ actionsToInsert = [replaceActionBase];
136
+ }
126
137
  if (
127
138
  actionsToInsert.length > 0 &&
128
- addActionsIfAdResolutionAvailable(elementToMeasure, false, true, isNative, ...actionsToInsert)
139
+ addActionsIfAdResolutionAvailable(elementToMeasure, AdType.Permanent, isNative, ...actionsToInsert)
129
140
  ) {
130
141
  insertionsLeft--;
131
142
  }
@@ -168,18 +179,17 @@ const processPermanentAdsParent = (
168
179
  if (normalizedInsertionIndex !== -1) {
169
180
  const actionBase: OmitAdInAction<SimpleInsertAdAction> = {
170
181
  type: AdActionType.SimpleInsertAd,
171
- shouldUseDivWrapper,
172
182
  divWrapperStyle,
173
183
  elementStyle,
174
184
  parent: insertionParentElement,
175
185
  insertionIndex: normalizedInsertionIndex,
186
+ isSiblingReplacement: false,
176
187
  stylesOverrides
177
188
  };
178
189
 
179
190
  addActionsIfAdResolutionAvailable(
180
191
  elementToMeasure,
181
- false,
182
- true,
192
+ AdType.Permanent,
183
193
  isNative,
184
194
  ...Array<typeof actionBase>(insertionsLeft).fill(actionBase)
185
195
  );
@@ -0,0 +1,140 @@
1
+ import {
2
+ AdAction,
3
+ AdActionType,
4
+ AdType,
5
+ AddActionsIfAdResolutionAvailable,
6
+ HideElementAction,
7
+ OmitAdInAction,
8
+ SimpleInsertAdAction
9
+ } from 'src/types/ads-actions';
10
+ import { delay } from 'src/utils';
11
+
12
+ import {
13
+ applyQuerySelector,
14
+ elementIsOurAd,
15
+ prevBannerSiblingIsReplacement,
16
+ getFinalSize,
17
+ ourAdQuerySelector
18
+ } from './helpers';
19
+
20
+ const styleToAdjustProps = [
21
+ 'align-items',
22
+ 'align-self',
23
+ 'bottom',
24
+ 'display',
25
+ 'flex',
26
+ 'flex-grow',
27
+ 'flex-shrink',
28
+ 'float',
29
+ 'justify-content',
30
+ 'justify-self',
31
+ 'left',
32
+ 'margin',
33
+ 'max-block-size',
34
+ 'max-height',
35
+ 'max-inline-size',
36
+ 'max-width',
37
+ 'min-block-size',
38
+ 'min-height',
39
+ 'min-inline-size',
40
+ 'min-width',
41
+ 'padding',
42
+ 'position',
43
+ 'right',
44
+ 'top',
45
+ 'vertical-align',
46
+ 'z-index'
47
+ ] as const;
48
+
49
+ export const processProvidersAds = async (
50
+ providersSelector: string,
51
+ addActionsIfAdResolutionAvailable: AddActionsIfAdResolutionAvailable,
52
+ result: AdAction[]
53
+ ) => {
54
+ const bannersFromProviders = applyQuerySelector(providersSelector, true).reduce<Element[]>((acc, newBanner) => {
55
+ const parentElementIndex = acc.findIndex(banner => banner.contains(newBanner));
56
+
57
+ const parentStyles = newBanner.parentElement && window.getComputedStyle(newBanner.parentElement);
58
+ const { width, height } = getFinalSize(newBanner);
59
+ const bannerIsTouchedByOtherActions = result.some(action => {
60
+ if (action.type === AdActionType.ReplaceAllChildren || action.type === AdActionType.SimpleInsertAd) {
61
+ return action.parent.contains(newBanner) || newBanner.contains(action.parent);
62
+ }
63
+
64
+ return action.element.parentElement?.contains(newBanner) || newBanner.contains(action.element);
65
+ });
66
+ const bannerIsHiddenByParent = parentStyles?.display === 'none' || parentStyles?.visibility === 'hidden';
67
+
68
+ if (bannerIsTouchedByOtherActions || width === 0 || height === 0 || bannerIsHiddenByParent) {
69
+ return acc;
70
+ }
71
+
72
+ if (parentElementIndex >= 0) {
73
+ acc.splice(parentElementIndex, 1, newBanner);
74
+ } else if (!acc.some(ancestorCandidate => ancestorCandidate.contains(newBanner))) {
75
+ acc.push(newBanner);
76
+ }
77
+
78
+ return acc;
79
+ }, []);
80
+
81
+ await Promise.all(
82
+ bannersFromProviders.map(async banner => {
83
+ await delay(0);
84
+
85
+ const parent = banner.parentElement;
86
+ const elementToMeasure =
87
+ parent?.closest<HTMLElement>('div, article, aside, footer, header') ??
88
+ (parent?.tagName.toLowerCase() === 'body' ? undefined : parent) ??
89
+ banner;
90
+
91
+ if (
92
+ !elementIsOurAd(banner) &&
93
+ !banner.querySelector(ourAdQuerySelector) &&
94
+ !result.some(action =>
95
+ action.type === AdActionType.SimpleInsertAd
96
+ ? false
97
+ : action.type === AdActionType.ReplaceAllChildren
98
+ ? action.parent.contains(banner)
99
+ : action.element === banner
100
+ )
101
+ ) {
102
+ const bannerStyleAttribute = banner.getAttribute('style') ?? '';
103
+ const bannerStyleFromAttribute = Object.fromEntries(
104
+ bannerStyleAttribute
105
+ .split(';')
106
+ .filter(Boolean)
107
+ .map(style => style.split(':').map(part => part.trim()) as [string, string])
108
+ );
109
+
110
+ if (bannerStyleFromAttribute.width?.match(/^0[a-z]/) || bannerStyleFromAttribute.height?.match(/^0[a-z]/)) {
111
+ return;
112
+ }
113
+
114
+ const bannerStyle = window.getComputedStyle(banner as HTMLElement);
115
+
116
+ const divWrapperStyle = {
117
+ ...Object.fromEntries(styleToAdjustProps.map(propName => [propName, bannerStyle.getPropertyValue(propName)])),
118
+ ...bannerStyleFromAttribute
119
+ };
120
+ const hideAction: HideElementAction = {
121
+ type: AdActionType.HideElement,
122
+ element: banner as HTMLElement
123
+ };
124
+ const insertAdAction: OmitAdInAction<SimpleInsertAdAction> = {
125
+ type: AdActionType.SimpleInsertAd,
126
+ divWrapperStyle,
127
+ parent: banner.parentElement ?? document.body,
128
+ insertionIndex: Array.from(banner.parentElement?.children ?? []).indexOf(banner),
129
+ isSiblingReplacement: true
130
+ };
131
+ const actions = prevBannerSiblingIsReplacement(banner)
132
+ ? window.getComputedStyle(banner).display === 'none'
133
+ ? []
134
+ : [hideAction]
135
+ : [hideAction, insertAdAction];
136
+ addActionsIfAdResolutionAvailable(elementToMeasure, AdType.ProviderReplacement, false, ...actions);
137
+ }
138
+ })
139
+ );
140
+ };