@bringweb3/chrome-extension-kit 1.3.11 → 1.4.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.mts CHANGED
@@ -49,6 +49,9 @@ interface Configuration {
49
49
  apiEndpoint: string;
50
50
  whitelistEndpoint?: string;
51
51
  cashbackPagePath?: string;
52
+ isEnabledByDefault: boolean;
53
+ showNotifications?: boolean;
54
+ notificationCallback?: () => void;
52
55
  }
53
56
  /**
54
57
  * Initializes the background script for the Bring extension.
@@ -60,6 +63,8 @@ interface Configuration {
60
63
  * @param {string} configuration.apiEndpoint - The API endpoint ('prod' or 'sandbox').
61
64
  * @param {string} configuration.whitelistEndpoint - Endpoint for whitelist of redirect urls.
62
65
  * @param {string} [configuration.cashbackPagePath] - Optional path to the cashback page.
66
+ * @param {boolean} [configuration.isEnabledByDefault] - Determine if the user see the popup by default. defaults to true.
67
+ * @param {boolean} [configuration.showNotifications] - Determine if the extension should show notifications about new rewards. defaults to true.
63
68
  * @throws {Error} Throws an error if identifier or apiEndpoint is missing, or if apiEndpoint is invalid.
64
69
  * @returns {Promise<void>}
65
70
  *
@@ -82,10 +87,11 @@ interface Configuration {
82
87
  * identifier: '<bring_identifier>',
83
88
  * apiEndpoint: 'sandbox',
84
89
  * whitelistEndpoint: 'https://example.com/whitelist.json',
90
+ * isEnabledByDefault: true,
85
91
  * cashbackPagePath: '/cashback.html'
86
92
  * });
87
93
  */
88
- declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint }: Configuration) => Promise<void>;
94
+ declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint, isEnabledByDefault, showNotifications, notificationCallback }: Configuration) => Promise<void>;
89
95
 
90
96
  interface TurnOff {
91
97
  isTurnedOff: boolean;
@@ -106,4 +112,23 @@ declare const getTurnOff: () => Promise<TurnOff>;
106
112
  */
107
113
  declare const setTurnOff: (state: boolean) => Promise<TurnOff>;
108
114
 
109
- export { bringInitBackground, bringInitContentScript, getTurnOff, setTurnOff };
115
+ interface PopupEnabled {
116
+ isPopupEnabled: boolean;
117
+ }
118
+ /**
119
+ * Retrieves the current "turn off" status, true means turned off and false is turned on
120
+ *
121
+ * @returns A Promise resolving to the turn-off state
122
+ * @throws Will reject if there's an error communicating with the background script
123
+ */
124
+ declare const getPopupEnabled: () => Promise<PopupEnabled>;
125
+ /**
126
+ * Sets if popup feature is enabled or disabled
127
+ *
128
+ * @param state - Boolean indicating whether popup feature is enabled (true) or disabled (false)
129
+ * @returns A Promise resolving to the new turn-off state
130
+ * @throws Will reject if there's an error communicating with the background script
131
+ */
132
+ declare const setPopupEnabled: (state: boolean) => Promise<PopupEnabled>;
133
+
134
+ export { bringInitBackground, bringInitContentScript, getPopupEnabled, getTurnOff, setPopupEnabled, setTurnOff };
package/dist/index.d.ts CHANGED
@@ -49,6 +49,9 @@ interface Configuration {
49
49
  apiEndpoint: string;
50
50
  whitelistEndpoint?: string;
51
51
  cashbackPagePath?: string;
52
+ isEnabledByDefault: boolean;
53
+ showNotifications?: boolean;
54
+ notificationCallback?: () => void;
52
55
  }
53
56
  /**
54
57
  * Initializes the background script for the Bring extension.
@@ -60,6 +63,8 @@ interface Configuration {
60
63
  * @param {string} configuration.apiEndpoint - The API endpoint ('prod' or 'sandbox').
61
64
  * @param {string} configuration.whitelistEndpoint - Endpoint for whitelist of redirect urls.
62
65
  * @param {string} [configuration.cashbackPagePath] - Optional path to the cashback page.
66
+ * @param {boolean} [configuration.isEnabledByDefault] - Determine if the user see the popup by default. defaults to true.
67
+ * @param {boolean} [configuration.showNotifications] - Determine if the extension should show notifications about new rewards. defaults to true.
63
68
  * @throws {Error} Throws an error if identifier or apiEndpoint is missing, or if apiEndpoint is invalid.
64
69
  * @returns {Promise<void>}
65
70
  *
@@ -82,10 +87,11 @@ interface Configuration {
82
87
  * identifier: '<bring_identifier>',
83
88
  * apiEndpoint: 'sandbox',
84
89
  * whitelistEndpoint: 'https://example.com/whitelist.json',
90
+ * isEnabledByDefault: true,
85
91
  * cashbackPagePath: '/cashback.html'
86
92
  * });
87
93
  */
88
- declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint }: Configuration) => Promise<void>;
94
+ declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint, isEnabledByDefault, showNotifications, notificationCallback }: Configuration) => Promise<void>;
89
95
 
90
96
  interface TurnOff {
91
97
  isTurnedOff: boolean;
@@ -106,4 +112,23 @@ declare const getTurnOff: () => Promise<TurnOff>;
106
112
  */
107
113
  declare const setTurnOff: (state: boolean) => Promise<TurnOff>;
108
114
 
109
- export { bringInitBackground, bringInitContentScript, getTurnOff, setTurnOff };
115
+ interface PopupEnabled {
116
+ isPopupEnabled: boolean;
117
+ }
118
+ /**
119
+ * Retrieves the current "turn off" status, true means turned off and false is turned on
120
+ *
121
+ * @returns A Promise resolving to the turn-off state
122
+ * @throws Will reject if there's an error communicating with the background script
123
+ */
124
+ declare const getPopupEnabled: () => Promise<PopupEnabled>;
125
+ /**
126
+ * Sets if popup feature is enabled or disabled
127
+ *
128
+ * @param state - Boolean indicating whether popup feature is enabled (true) or disabled (false)
129
+ * @returns A Promise resolving to the new turn-off state
130
+ * @throws Will reject if there's an error communicating with the background script
131
+ */
132
+ declare const setPopupEnabled: (state: boolean) => Promise<PopupEnabled>;
133
+
134
+ export { bringInitBackground, bringInitContentScript, getPopupEnabled, getTurnOff, setPopupEnabled, setTurnOff };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var U=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var ft=Object.prototype.hasOwnProperty;var pt=(t,e)=>{for(var r in e)U(t,r,{get:e[r],enumerable:!0})},gt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ut(e))!ft.call(t,i)&&i!==r&&U(t,i,{get:()=>e[i],enumerable:!(n=dt(e,i))||n.enumerable});return t};var ht=t=>gt(U({},"__esModule",{value:!0}),t);var Zt={};pt(Zt,{bringInitBackground:()=>at,bringInitContentScript:()=>H,getTurnOff:()=>ct,setTurnOff:()=>mt});module.exports=ht(Zt);var wt=t=>{let e=new URLSearchParams,{query:r,prefix:n}=t;return Object.entries(r).forEach(([i,s])=>{s&&(n&&(i=`${n}_${i}`),i==="url"?e.append(i,encodeURIComponent(s)):e.append(i,s))}),e.toString()},M=wt;var F={name:"@bringweb3/chrome-extension-kit",version:"1.3.11",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify",lint:"tsc",test:"vitest --coverage",release:"yarn build && changeset publish"},files:["dist","README.md"],devDependencies:{"@changesets/cli":"^2.27.7","@types/chrome":"^0.0.268","@vitest/coverage-v8":"^2.0.5",tsup:"^8.2.1",typescript:"^5.5.3",vitest:"^2.0.5"},keywords:["cashback","crypto","bringweb3"],dependencies:{uuid:"^11.0.3"}};var At=()=>F.version,O=At;var yt=({query:t,theme:e,themeMode:r,text:n,iframeUrl:i,page:s,switchWallet:a})=>{let c=chrome.runtime.id,d=`bringweb3-iframe-${c}`,m=document.getElementById(d),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:i;if(m)return m;let p=M({query:{...t,extensionId:c,v:O(),themeMode:r,textMode:n,switchWallet:String(a)}}),h=e?`&${M({query:e,prefix:"t"})}`:"",l=document.createElement("iframe");return l.id=d,l.src=`${u}?${p}${h}`,l.setAttribute("sandbox","allow-scripts allow-same-origin"),l.style.position="fixed",l.scrolling="no",l.style.overflow="hidden",l.style.width="1px",l.style.height="1px",l.style.right="8px",l.style.borderRadius="10px",l.style.border="none",l.style.cssText+="z-index: 99999999999999 !important;",e?.popupShadow&&(l.style.boxShadow=e.popupShadow),document.documentElement.appendChild(l),l},K=yt;var bt=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,n])=>{r in t.style&&(t.style[r]=n)})},$=bt;var Ot=t=>{if(!t||!t.length)return;let e=document.createElement("style");document.head.appendChild(e);let r=e.sheet;r?t.forEach(({name:n,rules:i})=>{r.insertRule(`@keyframes ${n} { ${i} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},j=Ot;var g={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},Tt=[g.ACTIVATE],vt=({event:t,iframeEl:e,promptLogin:r})=>{if(!t?.data)return;let{from:n,action:i,style:s,keyFrames:a,time:c,extensionId:d,url:m,domain:u,redirectUrl:p}=t.data;if(n==="bringweb3"&&!(d!==chrome.runtime.id&&!Tt.includes(i)))switch(i){case g.OPEN:$(e,s);break;case g.CLOSE:e&&e.parentNode?.removeChild(e),c&&chrome.runtime.sendMessage({action:i,time:c,domain:u,from:"bringweb3"});break;case g.PROMPT_LOGIN:r();break;case g.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3",domain:u,extensionId:d,time:c,redirectUrl:p});break;case g.OPT_OUT:chrome.runtime.sendMessage({action:i,time:c,from:"bringweb3"});break;case g.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:i,from:"bringweb3"});case g.ADD_KEYFRAMES:j(a);break;case g.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:i,url:m,from:"bringweb3"});break;default:break}},G=vt;var B=async({iframeEl:t,getWalletAddress:e})=>{if(!t&&(t=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!t)||!t.contentWindow)return;let r=await e();t.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},xt=({walletAddressListeners:t,walletAddressUpdateCallback:e,getWalletAddress:r,iframeEl:n})=>{if(e)e(()=>B({iframeEl:n,getWalletAddress:r}));else if(t)for(let i=0;i<t.length;i++){let s=t[i];s&&window.addEventListener(s,async()=>B({iframeEl:n,getWalletAddress:r}))}},q=xt;var Pt=t=>t.endsWith("/")?t.slice(0,-1):t,T=Pt;var Dt=["www.","www1.","www2."],It=t=>{for(let r of Dt)t=t.replace(r,"");let e="";try{e=new URL(t).host}catch{e=new URL(`https://${t}`).host}return e=T(e),e},N=It;var L=null,V=!1,Ct=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:i,darkTheme:s,theme:a,text:c,switchWallet:d=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof n!="function")throw new Error("Missing configuration");q({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:t,iframeEl:L}),window.addEventListener("message",m=>G({event:m,iframeEl:L,promptLogin:e})),chrome.runtime.onMessage.addListener((m,u,p)=>{if(m?.from!=="bringweb3")return;let{action:h}=m;switch(h){case"GET_WALLET_ADDRESS":return t().then(l=>p({status:"success",walletAddress:l})).catch(l=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":try{if(N(location.href)!==N(m.domain))return p({status:"failed",message:"Domain already changed"}),!0;if(V)return p({status:"failed",message:"iframe already open"}),!0;let{token:l,iframeUrl:b,userId:x}=m,P={token:l};return x&&(P.userId=x),L=K({query:P,iframeUrl:b,theme:a==="dark"?s:i,themeMode:a||"light",text:c,switchWallet:d,page:m.page}),V=!0,p({status:"success"}),!0}catch(l){return l instanceof Error?p({status:"failed",message:l.message}):p({status:"failed",message:String(l)}),!0}default:console.error(`Unknown action: ${h}`);break}})}},H=Ct;var Q=t=>{t&&chrome.tabs.create({url:t})};var f=class t{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}setWhitelistEndpoint(e){this.whitelistEndpoint=e}setApiEndpoint(e){this.apiEndpoint=e==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(e){this.apiKey=e}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var St=async(t,e)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),_t=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(n[`bring_${t}`])})}),kt=async t=>new Promise((e,r)=>{chrome.storage.local.remove([`bring_${t}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e()})}),o={set:St,get:_t,remove:kt};var J=require("uuid"),Ut=async()=>{let t=await o.get("id");return t||(t=(0,J.v4)(),o.set("id",t)),t},E=Ut;var Mt=async t=>{let{path:e,method:r,params:n}=t;if(!t||!e||!r||!n&&r==="POST")throw new Error("Missing endpoint or method");let i=f.getInstance().getApiEndpoint();i+=e;let s=f.getInstance().getApiKey();if(r==="GET"){let d=new URLSearchParams({...n,version:O(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await E()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});i+=`?${d.toString()}`}else r==="POST"&&(n={...n,version:O(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await E()||void 0,walletAddress:n?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(i,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(n):void 0})).json()},w=Mt;var Nt=async({body:t})=>await w({path:"/check/popup",method:"POST",params:t}),Y=Nt;var Lt=["www.","www1.","www2."],Wt=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of Lt)t.startsWith(e)&&(t=t.replace(e,""));return t},z=Wt;var D="updateCache";var Rt=async(t,e)=>{let r=await o.get("quietDomains");typeof r=="object"?r[t]=e:r={[t]:e},o.set("quietDomains",r)},v=Rt;var Ft=async({walletAddress:t,cashbackUrl:e,lastActivation:r})=>{let n={walletAddress:t};return r&&(n.lastActivation=r),e&&(n.cashbackUrl=e),await w({path:"/check/notification",method:"POST",params:n})},X=Ft;var Kt=(t,e)=>new Promise((i,s)=>{let a=c=>{chrome.tabs.get(t,d=>{if(chrome.runtime.lastError){i(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},m=>{chrome.runtime.lastError?c<4?setTimeout(()=>a(c+1),1e3*Math.pow(2,c)):i(null):i(m||null)})})};a(0)}),A=Kt;var $t=async t=>{let e=await o.get("walletAddress");try{if(!t){let n=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n[0]||!n[0].id)return e;t=n[0].id}let r=await A(t,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&e!==r?.walletAddress&&(e=r?.walletAddress,await o.set("walletAddress",e))}catch{}return e},I=$t;var jt=async(t,e,r)=>{let n={showNotification:!1,token:"",iframeUrl:""},i=await o.get("notificationCheck");if(i&&Date.now()<i)return n;let s=e?await I(e):await o.get("walletAddress");if(!s)return n;let a=await o.get("lastActivation"),c=await X({walletAddress:s,cashbackUrl:r,lastActivation:a});o.set("notificationCheck",c.nextCall);let d={showNotification:c.showNotification,token:c.token,iframeUrl:c.iframeUrl,expiration:c.expiration};return d.showNotification&&await o.set("notification",d),d},C=jt;var Gt=t=>t?chrome.runtime.getURL(t):"",S=Gt;var Bt=async()=>{let t=f.getInstance().getWhitelistEndpoint(),e={path:"/domains",method:"GET"};return t&&(e.params={whitelist:encodeURIComponent(t)}),await w(e)},Z=Bt;var tt=async()=>{try{let t=f.getInstance().getWhitelistEndpoint();if(!t)return[];let e=await fetch(t,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!e.ok)throw new Error("Failed to fetch whitelist");let r=await e.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(t){return console.error("Error fetching whitelist:",t),[]}};var qt=t=>{let e=Date.now();return(t-e)/1e3/60},y=async()=>{let t=await o.get("relevantDomainsCheck"),e=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),n=f.getInstance().getApiKey(),i=f.getInstance().getWhitelistEndpoint();if(e?.length&&t&&t>Date.now()&&(!i||i&&r?.length))return e;let s=await Z(),{nextUpdateTimestamp:a,relevantDomains:c}=s;o.set("relevantDomains",c),o.set("relevantDomainsCheck",a),r=await tt(),r&&o.set("redirectsWhitelist",r);let d=qt(a);return chrome.alarms.create(D,{delayInMinutes:d||60*24*2}),c};var Vt=async(t,e)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!e?.length&&(await y(),e=await o.get("redirectsWhitelist")),!e?.length)return!r;let i=new URL(t).hostname.toLowerCase();return i=i.replace("www.",""),e.includes(i)?!0:e.some(s=>{if(s.startsWith("*.")){let a=s.slice(2);return i.endsWith(a)}return!1})}catch{return console.error("Invalid URL:",t),!1}},_=Vt;var Ht=async(t,e,r,n,i,s,a)=>{if(e===chrome.runtime.id&&await o.set("lastActivation",Date.now()),t&&v(t,i||Date.now()+24*60*60*1e3),s&&a){let c=await o.get("redirectsWhitelist");await _(a,c)&&chrome.tabs.update(s,{url:a})}await C(r,void 0,S(n))},et=Ht;var rt=async t=>t<0?(await o.remove("optOut"),{isOptedOut:!1}):(await o.set("optOut",Date.now()+t),{isOptedOut:!0}),it=async()=>{let t=await o.get("optOut");return{isOptedOut:!!(t&&t>Date.now())}};var nt=async(t,e,r)=>{await A(t,{action:"INJECT",page:"notification",token:e.token,iframeUrl:e.iframeUrl,userId:await E(),domain:r})},Qt=async(t,e,r,n)=>{let i=await o.get("notification");if(i?.expiration<Date.now())await o.remove("notification");else if(i)return await nt(e,i,n);let s=await C(t,e,S(r));if(s.showNotification)return await nt(e,s,n)},st=Qt;var Jt=async t=>{t.category=t?.category||"system",await w({path:"/analytics",method:"POST",params:t})},ot=Jt;var Yt=["www.","www1.","www2."],zt=async t=>{let e=await y();if(!t||!e||!e.length)return"";let r=null;try{r=new URL(t)}catch{r=new URL(`https://${t}`)}let n=r.hostname,i=T(r.pathname);for(let s of Yt)n=n.replace(s,"");for(let s of e){let a=s;s=T(s);let c=!1;s.startsWith("*.")&&(c=!0);let d="/"+s.split("/").slice(1).join("/")||"";if(d!=="/"&&i.startsWith(d)&&(n+=d),n===s||c&&n.endsWith(s.replace("*.",""))){let m=await o.get("quietDomains");return m&&m[s]&&Date.now()<m[s]&&m[s]<Date.now()+60*24*60*60*1e3?"":a}}return""},W={},Xt=async({identifier:t,apiEndpoint:e,cashbackPagePath:r,whitelistEndpoint:n})=>{if(!t||!e)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(e))throw new Error("unknown apiEndpoint");f.getInstance().setApiEndpoint(e),f.getInstance().setWhitelistEndpoint(n||""),f.getInstance().setApiKey(t),y(),chrome.alarms.onAlarm.addListener(async i=>{let{name:s}=i;switch(s){case D:y();break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener((i,s,a)=>{if(i?.from!=="bringweb3")return;let{action:c}=i;switch(c){case"ACTIVATE":{let{domain:m,extensionId:u,time:p,redirectUrl:h}=i;return et(m,u,t,r,p,s.tab?.id,h).then(()=>a()),!0}case"GET_OPT_OUT":return it().then(m=>a(m)),!0;case"OPT_OUT":{let{time:m}=i;return rt(m).then(u=>a(u)),!0}case"CLOSE":{let{time:m,domain:u}=i;return u&&(v(u,m),a({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:m}=i;return m?o.set("walletAddress",m).then(()=>a(m)):o.remove("walletAddress").then(()=>a({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>a({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${c}`),!0;case"OPEN_CASHBACK_PAGE":let{url:d}=i;return Q(d||r),a({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(i,s,a)=>{if(!a?.url?.startsWith("http")||!a.url)return;let c=z(a.url),d=await o.get("optOut");if(d&&d>Date.now())return;d&&(o.remove("optOut"),o.remove("optOutKey"));let m=W[i];if(s.status!=="complete"||c===m)return;W[i]=c;let u=await zt(a.url);if(!u||!u.length){await st(t,i,r,c);return}let p=await I(i),{token:h,isValid:l,iframeUrl:b,networkUrl:x,flowId:P,time:lt=Date.now()+24*60*60*1e3}=await Y({body:{domain:u,url:a.url,address:p}});if(!l){l===!1&&v(u,lt);return}if(!await _(x,await o.get("redirectsWhitelist")))return;let R=await E(),k=await A(i,{action:"INJECT",token:h,domain:c,iframeUrl:b,userId:R});k?.status!=="success"&&ot({type:"no_popup",userId:R,walletAddress:p,details:{url:a.url,match:u,iframeUrl:b,reason:k?.message,status:k?.status},flowId:P})}),chrome.tabs.onRemoved.addListener(i=>delete W[i])},at=Xt;var ct=()=>new Promise((t,e)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_OPT_OUT"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),e(chrome.runtime.lastError);return}t({isTurnedOff:r.isOptedOut})})}),mt=t=>new Promise((e,r)=>{let n=t?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:n},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?e({isTurnedOff:i.isOptedOut}):r("No response received")})});0&&(module.exports={bringInitBackground,bringInitContentScript,getTurnOff,setTurnOff});
1
+ "use strict";var N=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Te=Object.prototype.hasOwnProperty;var ve=(e,t)=>{for(var r in t)N(e,r,{get:t[r],enumerable:!0})},De=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Pe(t))!Te.call(e,i)&&i!==r&&N(e,i,{get:()=>t[i],enumerable:!(n=Oe(t,i))||n.enumerable});return e};var xe=e=>De(N({},"__esModule",{value:!0}),e);var dt={};ve(dt,{bringInitBackground:()=>pe,bringInitContentScript:()=>Y,getPopupEnabled:()=>he,getTurnOff:()=>fe,setPopupEnabled:()=>we,setTurnOff:()=>ge});module.exports=xe(dt);var Ie=e=>{let t=new URLSearchParams,{query:r,prefix:n}=e;return Object.entries(r).forEach(([i,s])=>{s&&(n&&(i=`${n}_${i}`),i==="url"?t.append(i,encodeURIComponent(s)):t.append(i,s))}),t.toString()},L=Ie;var G={name:"@bringweb3/chrome-extension-kit",version:"1.4.0",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify",lint:"tsc",test:"vitest --coverage",release:"yarn build && changeset publish"},files:["dist","README.md"],devDependencies:{"@changesets/cli":"^2.27.7","@types/chrome":"^0.0.268","@vitest/coverage-v8":"^2.0.5",tsup:"^8.2.1",typescript:"^5.5.3",vitest:"^2.0.5"},keywords:["cashback","crypto","bringweb3"],dependencies:{uuid:"^11.0.3"}};var _e=()=>G.version,v=_e;var Se=({query:e,theme:t,themeMode:r,text:n,iframeUrl:i,page:s,switchWallet:l})=>{let m=chrome.runtime.id,c=`bringweb3-iframe-${m}`,d=document.getElementById(c),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:i;if(d)return d;let p=L({query:{...e,extensionId:m,v:v(),themeMode:r,textMode:n,switchWallet:String(l)}}),h=t?`&${L({query:t,prefix:"t"})}`:"",a=document.createElement("iframe");return a.id=c,a.src=`${u}?${p}${h}`,a.setAttribute("sandbox","allow-scripts allow-same-origin"),a.style.position="fixed",a.scrolling="no",a.style.overflow="hidden",a.style.width="1px",a.style.height="1px",a.style.right="8px",a.style.borderRadius="10px",a.style.border="none",a.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(a.style.boxShadow=t.popupShadow),document.documentElement.appendChild(a),a},B=Se;var Ue=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([r,n])=>{r in e.style&&(e.style[r]=n)})},j=Ue;var ke=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let r=t.sheet;r?e.forEach(({name:n,rules:i})=>{r.insertRule(`@keyframes ${n} { ${i} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},V=ke;var E={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",OPT_OUT_SPECIFIC:"OPT_OUT_SPECIFIC",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},Ne=[E.ACTIVATE],Le=({event:e,iframeEl:t,promptLogin:r})=>{if(!e?.data)return;let{from:n,action:i,style:s,keyFrames:l,time:m,extensionId:c,url:d,domain:u,redirectUrl:p}=e.data;if(n==="bringweb3"&&!(c!==chrome.runtime.id&&!Ne.includes(i)))switch(i){case E.OPEN:j(t,s);break;case E.CLOSE:t&&t.parentNode?.removeChild(t),m&&chrome.runtime.sendMessage({action:i,time:m,domain:u,from:"bringweb3"});break;case E.PROMPT_LOGIN:r();break;case E.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3",domain:u,extensionId:c,time:m,redirectUrl:p});break;case E.OPT_OUT:chrome.runtime.sendMessage({action:i,time:m,from:"bringweb3"});break;case E.OPT_OUT_SPECIFIC:chrome.runtime.sendMessage({action:i,domain:u,time:m,from:"bringweb3"});break;case E.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:i,from:"bringweb3"});case E.ADD_KEYFRAMES:V(l);break;case E.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:i,url:d,from:"bringweb3"});break;default:break}},H=Le;var q=async({iframeEl:e,getWalletAddress:t})=>{if(!e&&(e=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!e)||!e.contentWindow)return;let r=await t();e.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},Me=({walletAddressListeners:e,walletAddressUpdateCallback:t,getWalletAddress:r,iframeEl:n})=>{if(t)t(()=>q({iframeEl:n,getWalletAddress:r}));else if(e)for(let i=0;i<e.length;i++){let s=e[i];s&&window.addEventListener(s,async()=>q({iframeEl:n,getWalletAddress:r}))}},Q=Me;var We=e=>e.endsWith("/")?e.slice(0,-1):e,D=We;var Re=["www.","www1.","www2."],Fe=e=>{for(let r of Re)e=e.replace(r,"");let t="";try{t=new URL(e).host}catch{t=new URL(`https://${e}`).host}return t=D(t),t},O=Fe;var M=null,J=!1,Ke=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:i,darkTheme:s,theme:l,text:m,switchWallet:c=!1})=>{if(window.self===window.top){if(!e||!t||!r?.length&&typeof n!="function")throw new Error("Missing configuration");Q({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:e,iframeEl:M}),window.addEventListener("message",d=>H({event:d,iframeEl:M,promptLogin:t})),chrome.runtime.onMessage.addListener((d,u,p)=>{if(d?.from!=="bringweb3")return;let{action:h}=d;switch(h){case"GET_WALLET_ADDRESS":return e().then(a=>p({status:"success",walletAddress:a})).catch(a=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":try{if(O(location.href)!==O(d.domain))return p({status:"failed",message:"Domain already changed"}),!0;if(J)return p({status:"failed",message:"iframe already open"}),!0;let{token:a,iframeUrl:g,userId:b}=d,w={token:a};return b&&(w.userId=b),M=B({query:w,iframeUrl:g,theme:l==="dark"?s:i,themeMode:l||"light",text:m,switchWallet:c,page:d.page}),J=!0,p({status:"success"}),!0}catch(a){return a instanceof Error?p({status:"failed",message:a.message}):p({status:"failed",message:String(a)}),!0}default:console.error(`Unknown action: ${h}`);break}})}},Y=Ke;var z=e=>{e&&chrome.tabs.create({url:e})};var f=class e{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setWhitelistEndpoint(t){this.whitelistEndpoint=t}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(t){this.apiKey=t}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var $e=async(e,t)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),Ge=async e=>new Promise((t,r)=>{chrome.storage.local.get([`bring_${e}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t(n[`bring_${e}`])})}),Be=async e=>new Promise((t,r)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t()})}),o={set:$e,get:Ge,remove:Be};var X=require("uuid"),je=async()=>{let e=await o.get("id");return e||(e=(0,X.v4)(),o.set("id",e)),e},y=je;var Ve=async e=>{let{path:t,method:r,params:n}=e;if(!e||!t||!r||!n&&r==="POST")throw new Error("Missing endpoint or method");let i=f.getInstance().getApiEndpoint();i+=t;let s=f.getInstance().getApiKey();if(r==="GET"){let c=new URLSearchParams({...n,version:v(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await y()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});i+=`?${c.toString()}`}else r==="POST"&&(n={...n,version:v(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await y()||void 0,walletAddress:n?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(i,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(n):void 0})).json()},A=Ve;var He=async({body:e})=>await A({path:"/check/popup",method:"POST",params:e}),Z=He;var qe=["www.","www1.","www2."],Qe=e=>{if(!e)return"";e=e.split("://").reverse()[0]||"";for(let t of qe)e.startsWith(t)&&(e=e.replace(t,""));return e},ee=Qe;var I="updateCache";var te="quietDomains",Je=async(e,t)=>{let r=await o.get(te);typeof r=="object"?r[e]=t:r={[e]:t},o.set(te,r)},x=Je;var Ye=async({walletAddress:e,cashbackUrl:t,lastActivation:r})=>{let n={walletAddress:e};return r&&(n.lastActivation=r),t&&(n.cashbackUrl=t),await A({path:"/check/notification",method:"POST",params:n})},re=Ye;var ze=(e,t)=>new Promise((i,s)=>{let l=m=>{chrome.tabs.get(e,c=>{if(chrome.runtime.lastError){i(null);return}chrome.tabs.sendMessage(e,{...t,from:"bringweb3"},d=>{chrome.runtime.lastError?m<4?setTimeout(()=>l(m+1),1e3*Math.pow(2,m)):i(null):i(d||null)})})};l(0)}),P=ze;var Xe=async e=>{let t=await o.get("walletAddress");try{if(!e){let n=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n[0]||!n[0].id)return t;e=n[0].id}let r=await P(e,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&t!==r?.walletAddress&&(t=r?.walletAddress,await o.set("walletAddress",t))}catch{}return t},C=Xe;var Ze=async(e,t,r)=>{let n={showNotification:!1,token:"",iframeUrl:""},i=await o.get("notificationCheck");if(i&&Date.now()<i)return n;let s=t?await C(t):await o.get("walletAddress");if(!s)return n;let l=await o.get("lastActivation"),m=await re({walletAddress:s,cashbackUrl:r,lastActivation:l});o.set("notificationCheck",m.nextCall);let c={showNotification:m.showNotification,token:m.token,iframeUrl:m.iframeUrl,expiration:m.expiration};return c.showNotification&&await o.set("notification",c),c},_=Ze;var et=e=>e?chrome.runtime.getURL(e):"",S=et;var tt=async()=>{let e=f.getInstance().getWhitelistEndpoint(),t={path:"/domains",method:"GET"};return e&&(t.params={whitelist:encodeURIComponent(e)}),await A(t)},ne=tt;var ie=async()=>{try{let e=f.getInstance().getWhitelistEndpoint();if(!e)return[];let t=await fetch(e,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!t.ok)throw new Error("Failed to fetch whitelist");let r=await t.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(e){return console.error("Error fetching whitelist:",e),[]}};var rt=e=>{let t=Date.now();return(e-t)/1e3/60},T=async()=>{let e=await o.get("relevantDomainsCheck"),t=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),n=f.getInstance().getApiKey(),i=f.getInstance().getWhitelistEndpoint();if(t?.length&&e&&e>Date.now()&&(!i||i&&r?.length))return t;let s=await ne(),{nextUpdateTimestamp:l,relevantDomains:m}=s;o.set("relevantDomains",m),o.set("relevantDomainsCheck",l),r=await ie(),r&&o.set("redirectsWhitelist",r);let c=rt(l);return chrome.alarms.create(I,{delayInMinutes:c||60*24*2}),m};var nt=async(e,t)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!t?.length&&(await T(),t=await o.get("redirectsWhitelist")),!t?.length)return!r;let i=new URL(e).hostname.toLowerCase();return i=i.replace("www.",""),t.includes(i)?!0:t.some(s=>{if(s.startsWith("*.")){let l=s.slice(2);return i.endsWith(l)}return!1})}catch{return console.error("Invalid URL:",e),!1}},U=nt;var it=async(e,t,r,n,i,s,l)=>{if(t===chrome.runtime.id&&await o.set("lastActivation",Date.now()),e&&x(e,i||Date.now()+24*60*60*1e3),s&&l){let m=await o.get("redirectsWhitelist");await U(l,m)&&chrome.tabs.update(s,{url:l})}await _(r,void 0,S(n))},oe=it;var se=async e=>e<0?(await o.remove("optOut"),{isOptedOut:!1}):(await o.set("optOut",Date.now()+e),{isOptedOut:!0}),ae=async()=>{let e=await o.get("optOut");return{isOptedOut:!!(e&&e>Date.now())}};var ce=async(e,t,r)=>{await P(e,{action:"INJECT",page:"notification",token:t.token,iframeUrl:t.iframeUrl,userId:await y(),domain:r})},ot=async(e,t,r,n,i,s)=>{let l=await o.get("notification");if(l?.expiration<Date.now())await o.remove("notification");else if(l)return await ce(t,l,n);let m=await _(e,t,S(r));m.showNotification&&(i&&await ce(t,m,n),s&&s())},me=ot;var st=async e=>{e.category=e?.category||"system",await A({path:"/analytics",method:"POST",params:e})},le=st;var de="optOutDomains",at=async(e,t)=>{if(!e)return;let r=await o.get(de);typeof r=="object"?r[e]=t:r={[e]:t},o.set(de,r)},ue=at;var ct=["www.","www1.","www2."],mt=async e=>{let t=await T();if(!e||!t||!t.length)return"";let r=null;try{r=new URL(e)}catch{r=new URL(`https://${e}`)}let n=r.hostname,i=D(r.pathname);for(let s of ct)n=n.replace(s,"");for(let s of t){let l=s;s=D(s);let m=!1;s.startsWith("*.")&&(m=!0);let c="/"+s.split("/").slice(1).join("/")||"";if(c!=="/"&&i.startsWith(c)&&(n+=c),n===s||m&&n.endsWith(s.replace("*.",""))){let d=await o.get("quietDomains");return d&&d[s]&&Date.now()<d[s]&&d[s]<Date.now()+60*24*60*60*1e3?"":l}}return""},W={},lt=async({identifier:e,apiEndpoint:t,cashbackPagePath:r,whitelistEndpoint:n,isEnabledByDefault:i=!0,showNotifications:s=!0,notificationCallback:l})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");f.getInstance().setApiEndpoint(t),f.getInstance().setWhitelistEndpoint(n||""),f.getInstance().setApiKey(e),await o.get("popupEnabled")===void 0&&await o.set("popupEnabled",i),T(),chrome.alarms.onAlarm.addListener(async c=>{let{name:d}=c;switch(d){case I:T();break;default:console.error("alarm with no use case:",d);break}}),chrome.runtime.onMessage.addListener((c,d,u)=>{if(c?.from!=="bringweb3")return;let{action:p}=c;switch(p){case"ACTIVATE":{let{domain:a,extensionId:g,time:b,redirectUrl:w}=c;return oe(a,g,e,r,b,d.tab?.id,w).then(()=>u()),!0}case"GET_OPT_OUT":return ae().then(a=>u(a)),!0;case"OPT_OUT":{let{time:a}=c;return se(a).then(g=>u(g)),!0}case"OPT_OUT_SPECIFIC":{let{domain:a,time:g}=c;return ue(a,g).then(b=>u(b)),!0}case"GET_POPUP_ENABLED":return o.get("popupEnabled").then(a=>u({isPopupEnabled:a})),!0;case"SET_POPUP_ENABLED":{let{isPopupEnabled:a}=c;return o.set("popupEnabled",a).then(()=>{u({isPopupEnabled:a})}).catch(g=>{console.error("Error setting popup enabled:",g),u({error:"Failed to set popup enabled state"})}),!0}case"CLOSE":{let{time:a,domain:g}=c;return g&&(x(g,a),u({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:a}=c;return a?o.set("walletAddress",a).then(()=>u(a)):o.remove("walletAddress").then(()=>u({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>u({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${p}`),!0;case"OPEN_CASHBACK_PAGE":let{url:h}=c;return z(h||r),u({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(c,d,u)=>{if(!u?.url?.startsWith("http")||!u.url)return;let p=ee(u.url),h=await o.get("optOut");if(!await o.get("popupEnabled")||h&&h>Date.now())return;h&&(o.remove("optOut"),o.remove("optOutKey"));let g=await o.get("optOutDomains");if(g&&g[O(p)]&&g[O(p)]>Date.now())return;let b=W[c];if(d.status!=="complete"||p===b)return;W[c]=p;let w=await mt(u.url);if(!w||!w.length){await me(e,c,r,p,s,l);return}let R=await C(c),{token:Ee,isValid:F,iframeUrl:K,networkUrl:be,flowId:Ae,time:ye=Date.now()+24*60*60*1e3}=await Z({body:{domain:w,url:u.url,address:R}});if(!F){F===!1&&x(w,ye);return}if(!await U(be,await o.get("redirectsWhitelist")))return;let $=await y(),k=await P(c,{action:"INJECT",token:Ee,domain:p,iframeUrl:K,userId:$});k?.status!=="success"&&le({type:"no_popup",userId:$,walletAddress:R,details:{url:u.url,match:w,iframeUrl:K,reason:k?.message,status:k?.status},flowId:Ae})}),chrome.tabs.onRemoved.addListener(c=>delete W[c])},pe=lt;var fe=()=>new Promise((e,t)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_OPT_OUT"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),t(chrome.runtime.lastError);return}e({isTurnedOff:r.isOptedOut})})}),ge=e=>new Promise((t,r)=>{let n=e?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:n},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?t({isTurnedOff:i.isOptedOut}):r("No response received")})});var he=()=>new Promise((e,t)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_POPUP_ENABLED"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),t(chrome.runtime.lastError);return}e(r)})}),we=e=>new Promise((t,r)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"SET_POPUP_ENABLED",isPopupEnabled:e},n=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}n?t({isPopupEnabled:n.isPopupEnabled}):r("No response received")})});0&&(module.exports={bringInitBackground,bringInitContentScript,getPopupEnabled,getTurnOff,setPopupEnabled,setTurnOff});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var st=t=>{let e=new URLSearchParams,{query:r,prefix:n}=t;return Object.entries(r).forEach(([i,s])=>{s&&(n&&(i=`${n}_${i}`),i==="url"?e.append(i,encodeURIComponent(s)):e.append(i,s))}),e.toString()},U=st;var R={name:"@bringweb3/chrome-extension-kit",version:"1.3.11",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify",lint:"tsc",test:"vitest --coverage",release:"yarn build && changeset publish"},files:["dist","README.md"],devDependencies:{"@changesets/cli":"^2.27.7","@types/chrome":"^0.0.268","@vitest/coverage-v8":"^2.0.5",tsup:"^8.2.1",typescript:"^5.5.3",vitest:"^2.0.5"},keywords:["cashback","crypto","bringweb3"],dependencies:{uuid:"^11.0.3"}};var at=()=>R.version,O=at;var ct=({query:t,theme:e,themeMode:r,text:n,iframeUrl:i,page:s,switchWallet:a})=>{let c=chrome.runtime.id,d=`bringweb3-iframe-${c}`,m=document.getElementById(d),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:i;if(m)return m;let p=U({query:{...t,extensionId:c,v:O(),themeMode:r,textMode:n,switchWallet:String(a)}}),h=e?`&${U({query:e,prefix:"t"})}`:"",l=document.createElement("iframe");return l.id=d,l.src=`${u}?${p}${h}`,l.setAttribute("sandbox","allow-scripts allow-same-origin"),l.style.position="fixed",l.scrolling="no",l.style.overflow="hidden",l.style.width="1px",l.style.height="1px",l.style.right="8px",l.style.borderRadius="10px",l.style.border="none",l.style.cssText+="z-index: 99999999999999 !important;",e?.popupShadow&&(l.style.boxShadow=e.popupShadow),document.documentElement.appendChild(l),l},F=ct;var mt=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,n])=>{r in t.style&&(t.style[r]=n)})},K=mt;var lt=t=>{if(!t||!t.length)return;let e=document.createElement("style");document.head.appendChild(e);let r=e.sheet;r?t.forEach(({name:n,rules:i})=>{r.insertRule(`@keyframes ${n} { ${i} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},$=lt;var g={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},dt=[g.ACTIVATE],ut=({event:t,iframeEl:e,promptLogin:r})=>{if(!t?.data)return;let{from:n,action:i,style:s,keyFrames:a,time:c,extensionId:d,url:m,domain:u,redirectUrl:p}=t.data;if(n==="bringweb3"&&!(d!==chrome.runtime.id&&!dt.includes(i)))switch(i){case g.OPEN:K(e,s);break;case g.CLOSE:e&&e.parentNode?.removeChild(e),c&&chrome.runtime.sendMessage({action:i,time:c,domain:u,from:"bringweb3"});break;case g.PROMPT_LOGIN:r();break;case g.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3",domain:u,extensionId:d,time:c,redirectUrl:p});break;case g.OPT_OUT:chrome.runtime.sendMessage({action:i,time:c,from:"bringweb3"});break;case g.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:i,from:"bringweb3"});case g.ADD_KEYFRAMES:$(a);break;case g.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:i,url:m,from:"bringweb3"});break;default:break}},j=ut;var G=async({iframeEl:t,getWalletAddress:e})=>{if(!t&&(t=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!t)||!t.contentWindow)return;let r=await e();t.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},ft=({walletAddressListeners:t,walletAddressUpdateCallback:e,getWalletAddress:r,iframeEl:n})=>{if(e)e(()=>G({iframeEl:n,getWalletAddress:r}));else if(t)for(let i=0;i<t.length;i++){let s=t[i];s&&window.addEventListener(s,async()=>G({iframeEl:n,getWalletAddress:r}))}},B=ft;var pt=t=>t.endsWith("/")?t.slice(0,-1):t,T=pt;var gt=["www.","www1.","www2."],ht=t=>{for(let r of gt)t=t.replace(r,"");let e="";try{e=new URL(t).host}catch{e=new URL(`https://${t}`).host}return e=T(e),e},M=ht;var N=null,q=!1,wt=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:i,darkTheme:s,theme:a,text:c,switchWallet:d=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof n!="function")throw new Error("Missing configuration");B({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:t,iframeEl:N}),window.addEventListener("message",m=>j({event:m,iframeEl:N,promptLogin:e})),chrome.runtime.onMessage.addListener((m,u,p)=>{if(m?.from!=="bringweb3")return;let{action:h}=m;switch(h){case"GET_WALLET_ADDRESS":return t().then(l=>p({status:"success",walletAddress:l})).catch(l=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":try{if(M(location.href)!==M(m.domain))return p({status:"failed",message:"Domain already changed"}),!0;if(q)return p({status:"failed",message:"iframe already open"}),!0;let{token:l,iframeUrl:b,userId:x}=m,P={token:l};return x&&(P.userId=x),N=F({query:P,iframeUrl:b,theme:a==="dark"?s:i,themeMode:a||"light",text:c,switchWallet:d,page:m.page}),q=!0,p({status:"success"}),!0}catch(l){return l instanceof Error?p({status:"failed",message:l.message}):p({status:"failed",message:String(l)}),!0}default:console.error(`Unknown action: ${h}`);break}})}},Et=wt;var V=t=>{t&&chrome.tabs.create({url:t})};var f=class t{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}setWhitelistEndpoint(e){this.whitelistEndpoint=e}setApiEndpoint(e){this.apiEndpoint=e==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(e){this.apiKey=e}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var At=async(t,e)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),yt=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(n[`bring_${t}`])})}),bt=async t=>new Promise((e,r)=>{chrome.storage.local.remove([`bring_${t}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e()})}),o={set:At,get:yt,remove:bt};import{v4 as Ot}from"uuid";var Tt=async()=>{let t=await o.get("id");return t||(t=Ot(),o.set("id",t)),t},E=Tt;var vt=async t=>{let{path:e,method:r,params:n}=t;if(!t||!e||!r||!n&&r==="POST")throw new Error("Missing endpoint or method");let i=f.getInstance().getApiEndpoint();i+=e;let s=f.getInstance().getApiKey();if(r==="GET"){let d=new URLSearchParams({...n,version:O(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await E()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});i+=`?${d.toString()}`}else r==="POST"&&(n={...n,version:O(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await E()||void 0,walletAddress:n?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(i,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(n):void 0})).json()},w=vt;var xt=async({body:t})=>await w({path:"/check/popup",method:"POST",params:t}),H=xt;var Pt=["www.","www1.","www2."],Dt=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of Pt)t.startsWith(e)&&(t=t.replace(e,""));return t},Q=Dt;var D="updateCache";var It=async(t,e)=>{let r=await o.get("quietDomains");typeof r=="object"?r[t]=e:r={[t]:e},o.set("quietDomains",r)},v=It;var Ct=async({walletAddress:t,cashbackUrl:e,lastActivation:r})=>{let n={walletAddress:t};return r&&(n.lastActivation=r),e&&(n.cashbackUrl=e),await w({path:"/check/notification",method:"POST",params:n})},J=Ct;var St=(t,e)=>new Promise((i,s)=>{let a=c=>{chrome.tabs.get(t,d=>{if(chrome.runtime.lastError){i(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},m=>{chrome.runtime.lastError?c<4?setTimeout(()=>a(c+1),1e3*Math.pow(2,c)):i(null):i(m||null)})})};a(0)}),A=St;var _t=async t=>{let e=await o.get("walletAddress");try{if(!t){let n=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n[0]||!n[0].id)return e;t=n[0].id}let r=await A(t,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&e!==r?.walletAddress&&(e=r?.walletAddress,await o.set("walletAddress",e))}catch{}return e},I=_t;var kt=async(t,e,r)=>{let n={showNotification:!1,token:"",iframeUrl:""},i=await o.get("notificationCheck");if(i&&Date.now()<i)return n;let s=e?await I(e):await o.get("walletAddress");if(!s)return n;let a=await o.get("lastActivation"),c=await J({walletAddress:s,cashbackUrl:r,lastActivation:a});o.set("notificationCheck",c.nextCall);let d={showNotification:c.showNotification,token:c.token,iframeUrl:c.iframeUrl,expiration:c.expiration};return d.showNotification&&await o.set("notification",d),d},C=kt;var Ut=t=>t?chrome.runtime.getURL(t):"",S=Ut;var Mt=async()=>{let t=f.getInstance().getWhitelistEndpoint(),e={path:"/domains",method:"GET"};return t&&(e.params={whitelist:encodeURIComponent(t)}),await w(e)},Y=Mt;var z=async()=>{try{let t=f.getInstance().getWhitelistEndpoint();if(!t)return[];let e=await fetch(t,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!e.ok)throw new Error("Failed to fetch whitelist");let r=await e.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(t){return console.error("Error fetching whitelist:",t),[]}};var Nt=t=>{let e=Date.now();return(t-e)/1e3/60},y=async()=>{let t=await o.get("relevantDomainsCheck"),e=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),n=f.getInstance().getApiKey(),i=f.getInstance().getWhitelistEndpoint();if(e?.length&&t&&t>Date.now()&&(!i||i&&r?.length))return e;let s=await Y(),{nextUpdateTimestamp:a,relevantDomains:c}=s;o.set("relevantDomains",c),o.set("relevantDomainsCheck",a),r=await z(),r&&o.set("redirectsWhitelist",r);let d=Nt(a);return chrome.alarms.create(D,{delayInMinutes:d||60*24*2}),c};var Lt=async(t,e)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!e?.length&&(await y(),e=await o.get("redirectsWhitelist")),!e?.length)return!r;let i=new URL(t).hostname.toLowerCase();return i=i.replace("www.",""),e.includes(i)?!0:e.some(s=>{if(s.startsWith("*.")){let a=s.slice(2);return i.endsWith(a)}return!1})}catch{return console.error("Invalid URL:",t),!1}},_=Lt;var Wt=async(t,e,r,n,i,s,a)=>{if(e===chrome.runtime.id&&await o.set("lastActivation",Date.now()),t&&v(t,i||Date.now()+24*60*60*1e3),s&&a){let c=await o.get("redirectsWhitelist");await _(a,c)&&chrome.tabs.update(s,{url:a})}await C(r,void 0,S(n))},X=Wt;var Z=async t=>t<0?(await o.remove("optOut"),{isOptedOut:!1}):(await o.set("optOut",Date.now()+t),{isOptedOut:!0}),tt=async()=>{let t=await o.get("optOut");return{isOptedOut:!!(t&&t>Date.now())}};var et=async(t,e,r)=>{await A(t,{action:"INJECT",page:"notification",token:e.token,iframeUrl:e.iframeUrl,userId:await E(),domain:r})},Rt=async(t,e,r,n)=>{let i=await o.get("notification");if(i?.expiration<Date.now())await o.remove("notification");else if(i)return await et(e,i,n);let s=await C(t,e,S(r));if(s.showNotification)return await et(e,s,n)},rt=Rt;var Ft=async t=>{t.category=t?.category||"system",await w({path:"/analytics",method:"POST",params:t})},it=Ft;var Kt=["www.","www1.","www2."],$t=async t=>{let e=await y();if(!t||!e||!e.length)return"";let r=null;try{r=new URL(t)}catch{r=new URL(`https://${t}`)}let n=r.hostname,i=T(r.pathname);for(let s of Kt)n=n.replace(s,"");for(let s of e){let a=s;s=T(s);let c=!1;s.startsWith("*.")&&(c=!0);let d="/"+s.split("/").slice(1).join("/")||"";if(d!=="/"&&i.startsWith(d)&&(n+=d),n===s||c&&n.endsWith(s.replace("*.",""))){let m=await o.get("quietDomains");return m&&m[s]&&Date.now()<m[s]&&m[s]<Date.now()+60*24*60*60*1e3?"":a}}return""},L={},jt=async({identifier:t,apiEndpoint:e,cashbackPagePath:r,whitelistEndpoint:n})=>{if(!t||!e)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(e))throw new Error("unknown apiEndpoint");f.getInstance().setApiEndpoint(e),f.getInstance().setWhitelistEndpoint(n||""),f.getInstance().setApiKey(t),y(),chrome.alarms.onAlarm.addListener(async i=>{let{name:s}=i;switch(s){case D:y();break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener((i,s,a)=>{if(i?.from!=="bringweb3")return;let{action:c}=i;switch(c){case"ACTIVATE":{let{domain:m,extensionId:u,time:p,redirectUrl:h}=i;return X(m,u,t,r,p,s.tab?.id,h).then(()=>a()),!0}case"GET_OPT_OUT":return tt().then(m=>a(m)),!0;case"OPT_OUT":{let{time:m}=i;return Z(m).then(u=>a(u)),!0}case"CLOSE":{let{time:m,domain:u}=i;return u&&(v(u,m),a({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:m}=i;return m?o.set("walletAddress",m).then(()=>a(m)):o.remove("walletAddress").then(()=>a({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>a({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${c}`),!0;case"OPEN_CASHBACK_PAGE":let{url:d}=i;return V(d||r),a({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(i,s,a)=>{if(!a?.url?.startsWith("http")||!a.url)return;let c=Q(a.url),d=await o.get("optOut");if(d&&d>Date.now())return;d&&(o.remove("optOut"),o.remove("optOutKey"));let m=L[i];if(s.status!=="complete"||c===m)return;L[i]=c;let u=await $t(a.url);if(!u||!u.length){await rt(t,i,r,c);return}let p=await I(i),{token:h,isValid:l,iframeUrl:b,networkUrl:x,flowId:P,time:nt=Date.now()+24*60*60*1e3}=await H({body:{domain:u,url:a.url,address:p}});if(!l){l===!1&&v(u,nt);return}if(!await _(x,await o.get("redirectsWhitelist")))return;let W=await E(),k=await A(i,{action:"INJECT",token:h,domain:c,iframeUrl:b,userId:W});k?.status!=="success"&&it({type:"no_popup",userId:W,walletAddress:p,details:{url:a.url,match:u,iframeUrl:b,reason:k?.message,status:k?.status},flowId:P})}),chrome.tabs.onRemoved.addListener(i=>delete L[i])},Gt=jt;var Bt=()=>new Promise((t,e)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_OPT_OUT"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),e(chrome.runtime.lastError);return}t({isTurnedOff:r.isOptedOut})})}),qt=t=>new Promise((e,r)=>{let n=t?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:n},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?e({isTurnedOff:i.isOptedOut}):r("No response received")})});export{Gt as bringInitBackground,Et as bringInitContentScript,Bt as getTurnOff,qt as setTurnOff};
1
+ var fe=e=>{let t=new URLSearchParams,{query:r,prefix:n}=e;return Object.entries(r).forEach(([o,s])=>{s&&(n&&(o=`${n}_${o}`),o==="url"?t.append(o,encodeURIComponent(s)):t.append(o,s))}),t.toString()},N=fe;var $={name:"@bringweb3/chrome-extension-kit",version:"1.4.0",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify",lint:"tsc",test:"vitest --coverage",release:"yarn build && changeset publish"},files:["dist","README.md"],devDependencies:{"@changesets/cli":"^2.27.7","@types/chrome":"^0.0.268","@vitest/coverage-v8":"^2.0.5",tsup:"^8.2.1",typescript:"^5.5.3",vitest:"^2.0.5"},keywords:["cashback","crypto","bringweb3"],dependencies:{uuid:"^11.0.3"}};var he=()=>$.version,v=he;var we=({query:e,theme:t,themeMode:r,text:n,iframeUrl:o,page:s,switchWallet:l})=>{let m=chrome.runtime.id,c=`bringweb3-iframe-${m}`,d=document.getElementById(c),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:o;if(d)return d;let p=N({query:{...e,extensionId:m,v:v(),themeMode:r,textMode:n,switchWallet:String(l)}}),h=t?`&${N({query:t,prefix:"t"})}`:"",a=document.createElement("iframe");return a.id=c,a.src=`${u}?${p}${h}`,a.setAttribute("sandbox","allow-scripts allow-same-origin"),a.style.position="fixed",a.scrolling="no",a.style.overflow="hidden",a.style.width="1px",a.style.height="1px",a.style.right="8px",a.style.borderRadius="10px",a.style.border="none",a.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(a.style.boxShadow=t.popupShadow),document.documentElement.appendChild(a),a},G=we;var Ee=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([r,n])=>{r in e.style&&(e.style[r]=n)})},B=Ee;var be=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let r=t.sheet;r?e.forEach(({name:n,rules:o})=>{r.insertRule(`@keyframes ${n} { ${o} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},j=be;var E={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",OPT_OUT_SPECIFIC:"OPT_OUT_SPECIFIC",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},Ae=[E.ACTIVATE],ye=({event:e,iframeEl:t,promptLogin:r})=>{if(!e?.data)return;let{from:n,action:o,style:s,keyFrames:l,time:m,extensionId:c,url:d,domain:u,redirectUrl:p}=e.data;if(n==="bringweb3"&&!(c!==chrome.runtime.id&&!Ae.includes(o)))switch(o){case E.OPEN:B(t,s);break;case E.CLOSE:t&&t.parentNode?.removeChild(t),m&&chrome.runtime.sendMessage({action:o,time:m,domain:u,from:"bringweb3"});break;case E.PROMPT_LOGIN:r();break;case E.ACTIVATE:chrome.runtime.sendMessage({action:o,from:"bringweb3",domain:u,extensionId:c,time:m,redirectUrl:p});break;case E.OPT_OUT:chrome.runtime.sendMessage({action:o,time:m,from:"bringweb3"});break;case E.OPT_OUT_SPECIFIC:chrome.runtime.sendMessage({action:o,domain:u,time:m,from:"bringweb3"});break;case E.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:o,from:"bringweb3"});case E.ADD_KEYFRAMES:j(l);break;case E.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:o,url:d,from:"bringweb3"});break;default:break}},V=ye;var H=async({iframeEl:e,getWalletAddress:t})=>{if(!e&&(e=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!e)||!e.contentWindow)return;let r=await t();e.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},Oe=({walletAddressListeners:e,walletAddressUpdateCallback:t,getWalletAddress:r,iframeEl:n})=>{if(t)t(()=>H({iframeEl:n,getWalletAddress:r}));else if(e)for(let o=0;o<e.length;o++){let s=e[o];s&&window.addEventListener(s,async()=>H({iframeEl:n,getWalletAddress:r}))}},q=Oe;var Pe=e=>e.endsWith("/")?e.slice(0,-1):e,D=Pe;var Te=["www.","www1.","www2."],ve=e=>{for(let r of Te)e=e.replace(r,"");let t="";try{t=new URL(e).host}catch{t=new URL(`https://${e}`).host}return t=D(t),t},O=ve;var L=null,Q=!1,De=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:o,darkTheme:s,theme:l,text:m,switchWallet:c=!1})=>{if(window.self===window.top){if(!e||!t||!r?.length&&typeof n!="function")throw new Error("Missing configuration");q({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:e,iframeEl:L}),window.addEventListener("message",d=>V({event:d,iframeEl:L,promptLogin:t})),chrome.runtime.onMessage.addListener((d,u,p)=>{if(d?.from!=="bringweb3")return;let{action:h}=d;switch(h){case"GET_WALLET_ADDRESS":return e().then(a=>p({status:"success",walletAddress:a})).catch(a=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":try{if(O(location.href)!==O(d.domain))return p({status:"failed",message:"Domain already changed"}),!0;if(Q)return p({status:"failed",message:"iframe already open"}),!0;let{token:a,iframeUrl:g,userId:b}=d,w={token:a};return b&&(w.userId=b),L=G({query:w,iframeUrl:g,theme:l==="dark"?s:o,themeMode:l||"light",text:m,switchWallet:c,page:d.page}),Q=!0,p({status:"success"}),!0}catch(a){return a instanceof Error?p({status:"failed",message:a.message}):p({status:"failed",message:String(a)}),!0}default:console.error(`Unknown action: ${h}`);break}})}},xe=De;var J=e=>{e&&chrome.tabs.create({url:e})};var f=class e{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setWhitelistEndpoint(t){this.whitelistEndpoint=t}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(t){this.apiKey=t}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var Ie=async(e,t)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),Ce=async e=>new Promise((t,r)=>{chrome.storage.local.get([`bring_${e}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t(n[`bring_${e}`])})}),_e=async e=>new Promise((t,r)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t()})}),i={set:Ie,get:Ce,remove:_e};import{v4 as Se}from"uuid";var Ue=async()=>{let e=await i.get("id");return e||(e=Se(),i.set("id",e)),e},y=Ue;var ke=async e=>{let{path:t,method:r,params:n}=e;if(!e||!t||!r||!n&&r==="POST")throw new Error("Missing endpoint or method");let o=f.getInstance().getApiEndpoint();o+=t;let s=f.getInstance().getApiKey();if(r==="GET"){let c=new URLSearchParams({...n,version:v(),timestamp:Date.now().toString(),opt_out:await i.get("optOut")||0,user_id:await y()||"undefined",wallet_address:await i.get("walletAddress")||"undefined"});o+=`?${c.toString()}`}else r==="POST"&&(n={...n,version:v(),timestamp:Date.now(),optOut:await i.get("optOut")||0,userId:await y()||void 0,walletAddress:n?.walletAddress||await i.get("walletAddress")||void 0});return await(await fetch(o,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(n):void 0})).json()},A=ke;var Ne=async({body:e})=>await A({path:"/check/popup",method:"POST",params:e}),Y=Ne;var Le=["www.","www1.","www2."],Me=e=>{if(!e)return"";e=e.split("://").reverse()[0]||"";for(let t of Le)e.startsWith(t)&&(e=e.replace(t,""));return e},z=Me;var I="updateCache";var X="quietDomains",We=async(e,t)=>{let r=await i.get(X);typeof r=="object"?r[e]=t:r={[e]:t},i.set(X,r)},x=We;var Re=async({walletAddress:e,cashbackUrl:t,lastActivation:r})=>{let n={walletAddress:e};return r&&(n.lastActivation=r),t&&(n.cashbackUrl=t),await A({path:"/check/notification",method:"POST",params:n})},Z=Re;var Fe=(e,t)=>new Promise((o,s)=>{let l=m=>{chrome.tabs.get(e,c=>{if(chrome.runtime.lastError){o(null);return}chrome.tabs.sendMessage(e,{...t,from:"bringweb3"},d=>{chrome.runtime.lastError?m<4?setTimeout(()=>l(m+1),1e3*Math.pow(2,m)):o(null):o(d||null)})})};l(0)}),P=Fe;var Ke=async e=>{let t=await i.get("walletAddress");try{if(!e){let n=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n[0]||!n[0].id)return t;e=n[0].id}let r=await P(e,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&t!==r?.walletAddress&&(t=r?.walletAddress,await i.set("walletAddress",t))}catch{}return t},C=Ke;var $e=async(e,t,r)=>{let n={showNotification:!1,token:"",iframeUrl:""},o=await i.get("notificationCheck");if(o&&Date.now()<o)return n;let s=t?await C(t):await i.get("walletAddress");if(!s)return n;let l=await i.get("lastActivation"),m=await Z({walletAddress:s,cashbackUrl:r,lastActivation:l});i.set("notificationCheck",m.nextCall);let c={showNotification:m.showNotification,token:m.token,iframeUrl:m.iframeUrl,expiration:m.expiration};return c.showNotification&&await i.set("notification",c),c},_=$e;var Ge=e=>e?chrome.runtime.getURL(e):"",S=Ge;var Be=async()=>{let e=f.getInstance().getWhitelistEndpoint(),t={path:"/domains",method:"GET"};return e&&(t.params={whitelist:encodeURIComponent(e)}),await A(t)},ee=Be;var te=async()=>{try{let e=f.getInstance().getWhitelistEndpoint();if(!e)return[];let t=await fetch(e,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!t.ok)throw new Error("Failed to fetch whitelist");let r=await t.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(e){return console.error("Error fetching whitelist:",e),[]}};var je=e=>{let t=Date.now();return(e-t)/1e3/60},T=async()=>{let e=await i.get("relevantDomainsCheck"),t=await i.get("relevantDomains"),r=await i.get("redirectsWhitelist"),n=f.getInstance().getApiKey(),o=f.getInstance().getWhitelistEndpoint();if(t?.length&&e&&e>Date.now()&&(!o||o&&r?.length))return t;let s=await ee(),{nextUpdateTimestamp:l,relevantDomains:m}=s;i.set("relevantDomains",m),i.set("relevantDomainsCheck",l),r=await te(),r&&i.set("redirectsWhitelist",r);let c=je(l);return chrome.alarms.create(I,{delayInMinutes:c||60*24*2}),m};var Ve=async(e,t)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!t?.length&&(await T(),t=await i.get("redirectsWhitelist")),!t?.length)return!r;let o=new URL(e).hostname.toLowerCase();return o=o.replace("www.",""),t.includes(o)?!0:t.some(s=>{if(s.startsWith("*.")){let l=s.slice(2);return o.endsWith(l)}return!1})}catch{return console.error("Invalid URL:",e),!1}},U=Ve;var He=async(e,t,r,n,o,s,l)=>{if(t===chrome.runtime.id&&await i.set("lastActivation",Date.now()),e&&x(e,o||Date.now()+24*60*60*1e3),s&&l){let m=await i.get("redirectsWhitelist");await U(l,m)&&chrome.tabs.update(s,{url:l})}await _(r,void 0,S(n))},re=He;var ne=async e=>e<0?(await i.remove("optOut"),{isOptedOut:!1}):(await i.set("optOut",Date.now()+e),{isOptedOut:!0}),ie=async()=>{let e=await i.get("optOut");return{isOptedOut:!!(e&&e>Date.now())}};var oe=async(e,t,r)=>{await P(e,{action:"INJECT",page:"notification",token:t.token,iframeUrl:t.iframeUrl,userId:await y(),domain:r})},qe=async(e,t,r,n,o,s)=>{let l=await i.get("notification");if(l?.expiration<Date.now())await i.remove("notification");else if(l)return await oe(t,l,n);let m=await _(e,t,S(r));m.showNotification&&(o&&await oe(t,m,n),s&&s())},se=qe;var Qe=async e=>{e.category=e?.category||"system",await A({path:"/analytics",method:"POST",params:e})},ae=Qe;var ce="optOutDomains",Je=async(e,t)=>{if(!e)return;let r=await i.get(ce);typeof r=="object"?r[e]=t:r={[e]:t},i.set(ce,r)},me=Je;var Ye=["www.","www1.","www2."],ze=async e=>{let t=await T();if(!e||!t||!t.length)return"";let r=null;try{r=new URL(e)}catch{r=new URL(`https://${e}`)}let n=r.hostname,o=D(r.pathname);for(let s of Ye)n=n.replace(s,"");for(let s of t){let l=s;s=D(s);let m=!1;s.startsWith("*.")&&(m=!0);let c="/"+s.split("/").slice(1).join("/")||"";if(c!=="/"&&o.startsWith(c)&&(n+=c),n===s||m&&n.endsWith(s.replace("*.",""))){let d=await i.get("quietDomains");return d&&d[s]&&Date.now()<d[s]&&d[s]<Date.now()+60*24*60*60*1e3?"":l}}return""},M={},Xe=async({identifier:e,apiEndpoint:t,cashbackPagePath:r,whitelistEndpoint:n,isEnabledByDefault:o=!0,showNotifications:s=!0,notificationCallback:l})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");f.getInstance().setApiEndpoint(t),f.getInstance().setWhitelistEndpoint(n||""),f.getInstance().setApiKey(e),await i.get("popupEnabled")===void 0&&await i.set("popupEnabled",o),T(),chrome.alarms.onAlarm.addListener(async c=>{let{name:d}=c;switch(d){case I:T();break;default:console.error("alarm with no use case:",d);break}}),chrome.runtime.onMessage.addListener((c,d,u)=>{if(c?.from!=="bringweb3")return;let{action:p}=c;switch(p){case"ACTIVATE":{let{domain:a,extensionId:g,time:b,redirectUrl:w}=c;return re(a,g,e,r,b,d.tab?.id,w).then(()=>u()),!0}case"GET_OPT_OUT":return ie().then(a=>u(a)),!0;case"OPT_OUT":{let{time:a}=c;return ne(a).then(g=>u(g)),!0}case"OPT_OUT_SPECIFIC":{let{domain:a,time:g}=c;return me(a,g).then(b=>u(b)),!0}case"GET_POPUP_ENABLED":return i.get("popupEnabled").then(a=>u({isPopupEnabled:a})),!0;case"SET_POPUP_ENABLED":{let{isPopupEnabled:a}=c;return i.set("popupEnabled",a).then(()=>{u({isPopupEnabled:a})}).catch(g=>{console.error("Error setting popup enabled:",g),u({error:"Failed to set popup enabled state"})}),!0}case"CLOSE":{let{time:a,domain:g}=c;return g&&(x(g,a),u({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:a}=c;return a?i.set("walletAddress",a).then(()=>u(a)):i.remove("walletAddress").then(()=>u({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return i.remove("notification").then(()=>u({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${p}`),!0;case"OPEN_CASHBACK_PAGE":let{url:h}=c;return J(h||r),u({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(c,d,u)=>{if(!u?.url?.startsWith("http")||!u.url)return;let p=z(u.url),h=await i.get("optOut");if(!await i.get("popupEnabled")||h&&h>Date.now())return;h&&(i.remove("optOut"),i.remove("optOutKey"));let g=await i.get("optOutDomains");if(g&&g[O(p)]&&g[O(p)]>Date.now())return;let b=M[c];if(d.status!=="complete"||p===b)return;M[c]=p;let w=await ze(u.url);if(!w||!w.length){await se(e,c,r,p,s,l);return}let W=await C(c),{token:le,isValid:R,iframeUrl:F,networkUrl:de,flowId:ue,time:pe=Date.now()+24*60*60*1e3}=await Y({body:{domain:w,url:u.url,address:W}});if(!R){R===!1&&x(w,pe);return}if(!await U(de,await i.get("redirectsWhitelist")))return;let K=await y(),k=await P(c,{action:"INJECT",token:le,domain:p,iframeUrl:F,userId:K});k?.status!=="success"&&ae({type:"no_popup",userId:K,walletAddress:W,details:{url:u.url,match:w,iframeUrl:F,reason:k?.message,status:k?.status},flowId:ue})}),chrome.tabs.onRemoved.addListener(c=>delete M[c])},Ze=Xe;var et=()=>new Promise((e,t)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_OPT_OUT"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),t(chrome.runtime.lastError);return}e({isTurnedOff:r.isOptedOut})})}),tt=e=>new Promise((t,r)=>{let n=e?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:n},o=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}o?t({isTurnedOff:o.isOptedOut}):r("No response received")})});var rt=()=>new Promise((e,t)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_POPUP_ENABLED"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),t(chrome.runtime.lastError);return}e(r)})}),nt=e=>new Promise((t,r)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"SET_POPUP_ENABLED",isPopupEnabled:e},n=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}n?t({isPopupEnabled:n.isPopupEnabled}):r("No response received")})});export{Ze as bringInitBackground,xe as bringInitContentScript,rt as getPopupEnabled,et as getTurnOff,nt as setPopupEnabled,tt as setTurnOff};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bringweb3/chrome-extension-kit",
3
- "version": "1.3.11",
3
+ "version": "1.4.0",
4
4
  "description": "Crypto cashback integration kit for crypto outlets extension",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",