@bringweb3/chrome-extension-kit 1.0.2 → 1.0.4

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/README.md CHANGED
@@ -1,6 +1,7 @@
1
- <img src="https://avatars.githubusercontent.com/u/122225882?s=96&v=4"/>
1
+ <a href="https://bringweb3.io/"><img width="200px" src="https://bringweb3.io/wp-content/uploads/2024/05/logo-trans_black.png"/></a><br>
2
+ <br><br>
3
+ <h1>@bringweb3/chrome-extension-kit</h1>
2
4
  <br><br>
3
- <h1 align="center">@bringweb3/chrome-extension-kit</h1>
4
5
 
5
6
  ## Table of content
6
7
  - [Table of content](#table-of-content)
@@ -10,9 +11,12 @@
10
11
  - [Package](#package)
11
12
  - [Manifest](#manifest)
12
13
  - [Importing](#importing)
14
+ - [import](#import)
15
+ - [require](#require)
13
16
  - [Example](#example)
14
17
  - [background.js](#backgroundjs)
15
18
  - [contentScript.js](#contentscriptjs)
19
+ - [Contact us](#contact-us)
16
20
 
17
21
  ## Description
18
22
  This integration kit is designed to enhance existing Chrome extensions by adding functionality that enables automatic crypto cashback on online purchases.
@@ -25,7 +29,7 @@ When a user visits supported online retailer websites, the Crypto Cashback syste
25
29
 
26
30
  - Node.js >= 14
27
31
  - Chrome extension manifest >= V3 with required permissions
28
- - Obtain an identifier key from Bringweb3
32
+ - Obtain an identifier key from [Bringweb3](https://bringweb3.io/#contact)
29
33
  - Provide a specific logo for the specific outlet
30
34
 
31
35
  ## Installing
@@ -73,14 +77,23 @@ Include this configuration inside your `manifest.json` file:
73
77
  ]
74
78
  ```
75
79
 
76
- Once the package is installed, you can import the library using `import` or `require` approach:
77
-
78
-
79
80
  ## Importing
81
+ Once the package is installed, you can import the library using `import` or `require` approach:
80
82
 
83
+ ### import
81
84
  ```js
82
85
  import { bringInitBackground } from '@bringweb3/chrome-extension-kit';
83
86
  ```
87
+ ```js
88
+ import { bringInitContentScript } from '@bringweb3/chrome-extension-kit';
89
+ ```
90
+ ### require
91
+ ```js
92
+ const { bringInitBackground } = require('@bringweb3/chrome-extension-kit');
93
+ ```
94
+ ```js
95
+ const { bringInitContentScript } = require('@bringweb3/chrome-extension-kit');
96
+ ```
84
97
 
85
98
  ## Example
86
99
 
@@ -107,60 +120,96 @@ bringInitContentScript({
107
120
  getWalletAddress: async () => await new Promise(resolve => setTimeout(() => resolve('<USER_WALLET_ADDRESS>'), 200)),// Async function that returns the current user's wallet address
108
121
  promptLogin: () => {...}, // Function that prompts a UI element asking the user to login
109
122
  walletAddressListeners: ["customEvent:addressChanged"], // A list of custom events that dispatched when the user's wallet address had changed
110
- customTheme: { // All optional
123
+ customTheme: {
124
+ // font
111
125
  fontUrl: 'https://fonts.googleapis.com/css2?family=Matemasie&display=swap',
112
126
  fontFamily: "'Matemasie', system-ui",
113
-
127
+ // Popup
114
128
  popupBg: "#192E34",
115
129
  popupShadow: "",
116
-
130
+ // Primary button
117
131
  primaryBtnBg: "linear-gradient(135deg, #5DEB5A 0%, #FDFC47 100%)",
118
- primaryBtnColor: "#041417",
119
- primaryBtnBorderColor: "transparent",
132
+ primaryBtnFC: "#041417",
133
+ primaryBtnFW: "600",
134
+ primaryBtnFS: "14px",
135
+ primaryBtnBorderC: "transparent",
120
136
  primaryBtnBorderW: "0",
121
137
  primaryBtnRadius: "8px",
122
-
138
+ // Secondary button
123
139
  secondaryBtnBg: "transparent",
124
- secondaryBtnColor: "white",
125
- secondaryBtnBorderColor: "rgba(149, 176, 178, 0.50)",
140
+ secondaryBtnFS: "12px",
141
+ secondaryBtnFW: "500",
142
+ secondaryBtnFC: "white",
143
+ secondaryBtnBorderC: "rgba(149, 176, 178, 0.50)",
126
144
  secondaryBtnBorderW: "2px",
127
145
  secondaryBtnRadius: "8px",
128
-
146
+ // Markdown
129
147
  markdownBg: "#07131766",
130
- markdownColor: "#DADCE5",
148
+ markdownFS: "12px",
149
+ markdownFC: "#DADCE5",
131
150
  markdownBorderW: "0",
132
151
  markdownRadius: "4px",
133
- markdownBorderColor: "black",
134
- markdownScrollbarColor: "#DADCE5",
135
-
136
- walletColor: "white",
152
+ markdownBorderC: "black",
153
+ markdownScrollbarC: "#DADCE5",
154
+ // Wallet address
137
155
  walletBg: "#33535B",
138
- walletBorderColor: "white",
156
+ walletFS: "10px",
157
+ walletFW: "400",
158
+ walletFC: "white",
159
+ walletBorderC: "white",
139
160
  walletBorderW: "0",
140
161
  walletRadius: "4px",
141
-
162
+ // Details of offering
142
163
  detailsBg: "#33535B",
143
- detailsColor: "white",
164
+ detailsTitleFS: "15px",
165
+ detailsTitleFW: "600",
166
+ detailsTitleFC: "white",
167
+ detailsSubtitleFS: "14px",
168
+ detailsSubtitleFW: "500",
169
+ detailsSubtitleFC: "#A8ADBF",
144
170
  detailsRadius: "8px",
145
171
  detailsBorderW: "0",
146
- detailsBorderColor: "transparent",
147
- detailsCashbackColor: "linear-gradient(135deg, #5DEB5A 0%, #FDFC47 100%)",
148
-
172
+ detailsBorderC: "transparent",
173
+ detailsAmountFC: "#5DEB5A",
174
+ detailsAmountFW: "700",
175
+ // Overlay
149
176
  overlayBg: "#192E34E6",
150
- overlayColor: "#DADCE5",
151
-
177
+ overlayFS: "13px",
178
+ overlayFW: "400",
179
+ overlayFC: "#DADCE5",
180
+ loaderBg: "#0A2EC0",
181
+ // Optout \ Turn off
152
182
  optoutBg: "#192E34",
153
- optoutColor: "white",
183
+ optoutFS: "14px",
184
+ optoutFW: "400",
185
+ optoutFC: "white",
154
186
  optoutRadius: "56px",
155
-
156
- closeColor: "#B9BBBF",
157
-
187
+ // X Button and close buttons
188
+ closeFS: "9px",
189
+ closeFW: "300",
190
+ closeFC: "#B9BBBF",
191
+ // Token name
158
192
  tokenBg: "transparent",
159
- tokenColor: "#DADCE5",
160
-
161
- notificationBtnColor: "#041417",
193
+ tokenFS: "13px",
194
+ tokenFW: "600",
195
+ tokenFC: "#DADCE5",
196
+ tokenBorderW: "2px",
197
+ tokenBorderC: "#DADCE5",
198
+ // Notification popup
199
+ notificationFS: "14px",
200
+ notificationFW: "500",
201
+ notificationFC: "white",
162
202
  notificationBtnBg: "linear-gradient(135deg, #5DEB5A 0%, #FDFC47 100%)",
203
+ notificationBtnFS: "12px",
204
+ notificationBtnFW: "500",
205
+ notificationBtnFC: "#041417",
206
+ notificationBtnBorderW: "0",
207
+ notificationBtnBorderC: "transparent",
163
208
  notificationBtnRadius: "8px"
164
209
  }
165
210
  });
166
- ```
211
+ ```
212
+
213
+ ## Contact us
214
+
215
+ For more information: [contact us](https://bringweb3.io/#contact)
@@ -0,0 +1,77 @@
1
+ interface Configuration$1 {
2
+ iframeEndpoint: string;
3
+ getWalletAddress: () => Promise<WalletAddress>;
4
+ promptLogin: () => Promise<WalletAddress>;
5
+ walletAddressListeners: string[];
6
+ customTheme?: Style;
7
+ }
8
+ /**
9
+ * Initializes the content script for the Bring extension.
10
+ *
11
+ * @async
12
+ * @function bringInitContentScript
13
+ * @param {Object} configuration - The configuration object.
14
+ * @param {Function} configuration.getWalletAddress - A function that returns a Promise resolving to the wallet address.
15
+ * @param {Function} configuration.promptLogin - A function to prompt the user to login.
16
+ * @param {string[]} configuration.walletAddressListeners - An array of strings representing wallet address listeners.
17
+ * @param {Object} [configuration.customTheme] - Optional custom theme settings.
18
+ * @param {string} configuration.iframeEndpoint - The endpoint URL for the iframe.
19
+ * @throws {Error} Throws an error if any required configuration is missing.
20
+ * @returns {Promise<void>}
21
+ *
22
+ * @description
23
+ * This function sets up event listeners for wallet address changes, iframe messages,
24
+ * and Chrome runtime messages. It handles actions such as getting the wallet address
25
+ * and injecting iframes based on received messages.
26
+ *
27
+ * @example
28
+ * bringInitContentScript({
29
+ * getWalletAddress: async () => '0x1234...',
30
+ * promptLogin: () => { ... },
31
+ * walletAddressListeners: ["listener1", "listener2"],
32
+ * iframeEndpoint: 'https://example.com/iframe'
33
+ * });
34
+ */
35
+ declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAddressListeners, customTheme, iframeEndpoint }: Configuration$1) => Promise<void>;
36
+
37
+ interface Configuration {
38
+ identifier: string;
39
+ apiEndpoint: string;
40
+ cashbackPagePath?: string;
41
+ }
42
+ /**
43
+ * Initializes the background script for the Bring extension.
44
+ *
45
+ * @async
46
+ * @function bringInitBackground
47
+ * @param {Object} configuration - The configuration object.
48
+ * @param {string} configuration.identifier - The identifier for the extension.
49
+ * @param {string} configuration.apiEndpoint - The API endpoint ('prod' or 'sandbox').
50
+ * @param {string} [configuration.cashbackPagePath] - Optional path to the cashback page.
51
+ * @throws {Error} Throws an error if identifier or apiEndpoint is missing, or if apiEndpoint is invalid.
52
+ * @returns {Promise<void>}
53
+ *
54
+ * @description
55
+ * This function sets up the background processes for the Bring extension. It initializes
56
+ * the API endpoint, sets up listeners for alarms, runtime messages, and tab updates.
57
+ * It handles various actions such as opting out, closing notifications, injecting content
58
+ * based on URL changes, and managing quiet domains.
59
+ *
60
+ * The function performs the following tasks:
61
+ * - Validates and sets the API endpoint
62
+ * - Updates the cache
63
+ * - Sets up listeners for alarms to update cache periodically
64
+ * - Handles runtime messages for opting out and closing notifications
65
+ * - Monitors tab updates to inject content or show notifications based on URL changes
66
+ * - Validates domains and manages quiet domains
67
+ *
68
+ * @example
69
+ * bringInitBackground({
70
+ * identifier: 'my-extension-id',
71
+ * apiEndpoint: 'sandbox',
72
+ * cashbackPagePath: '/cashback.html'
73
+ * });
74
+ */
75
+ declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath }: Configuration) => Promise<void>;
76
+
77
+ export { bringInitBackground, bringInitContentScript };
@@ -0,0 +1,77 @@
1
+ interface Configuration$1 {
2
+ iframeEndpoint: string;
3
+ getWalletAddress: () => Promise<WalletAddress>;
4
+ promptLogin: () => Promise<WalletAddress>;
5
+ walletAddressListeners: string[];
6
+ customTheme?: Style;
7
+ }
8
+ /**
9
+ * Initializes the content script for the Bring extension.
10
+ *
11
+ * @async
12
+ * @function bringInitContentScript
13
+ * @param {Object} configuration - The configuration object.
14
+ * @param {Function} configuration.getWalletAddress - A function that returns a Promise resolving to the wallet address.
15
+ * @param {Function} configuration.promptLogin - A function to prompt the user to login.
16
+ * @param {string[]} configuration.walletAddressListeners - An array of strings representing wallet address listeners.
17
+ * @param {Object} [configuration.customTheme] - Optional custom theme settings.
18
+ * @param {string} configuration.iframeEndpoint - The endpoint URL for the iframe.
19
+ * @throws {Error} Throws an error if any required configuration is missing.
20
+ * @returns {Promise<void>}
21
+ *
22
+ * @description
23
+ * This function sets up event listeners for wallet address changes, iframe messages,
24
+ * and Chrome runtime messages. It handles actions such as getting the wallet address
25
+ * and injecting iframes based on received messages.
26
+ *
27
+ * @example
28
+ * bringInitContentScript({
29
+ * getWalletAddress: async () => '0x1234...',
30
+ * promptLogin: () => { ... },
31
+ * walletAddressListeners: ["listener1", "listener2"],
32
+ * iframeEndpoint: 'https://example.com/iframe'
33
+ * });
34
+ */
35
+ declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAddressListeners, customTheme, iframeEndpoint }: Configuration$1) => Promise<void>;
36
+
37
+ interface Configuration {
38
+ identifier: string;
39
+ apiEndpoint: string;
40
+ cashbackPagePath?: string;
41
+ }
42
+ /**
43
+ * Initializes the background script for the Bring extension.
44
+ *
45
+ * @async
46
+ * @function bringInitBackground
47
+ * @param {Object} configuration - The configuration object.
48
+ * @param {string} configuration.identifier - The identifier for the extension.
49
+ * @param {string} configuration.apiEndpoint - The API endpoint ('prod' or 'sandbox').
50
+ * @param {string} [configuration.cashbackPagePath] - Optional path to the cashback page.
51
+ * @throws {Error} Throws an error if identifier or apiEndpoint is missing, or if apiEndpoint is invalid.
52
+ * @returns {Promise<void>}
53
+ *
54
+ * @description
55
+ * This function sets up the background processes for the Bring extension. It initializes
56
+ * the API endpoint, sets up listeners for alarms, runtime messages, and tab updates.
57
+ * It handles various actions such as opting out, closing notifications, injecting content
58
+ * based on URL changes, and managing quiet domains.
59
+ *
60
+ * The function performs the following tasks:
61
+ * - Validates and sets the API endpoint
62
+ * - Updates the cache
63
+ * - Sets up listeners for alarms to update cache periodically
64
+ * - Handles runtime messages for opting out and closing notifications
65
+ * - Monitors tab updates to inject content or show notifications based on URL changes
66
+ * - Validates domains and manages quiet domains
67
+ *
68
+ * @example
69
+ * bringInitBackground({
70
+ * identifier: 'my-extension-id',
71
+ * apiEndpoint: 'sandbox',
72
+ * cashbackPagePath: '/cashback.html'
73
+ * });
74
+ */
75
+ declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath }: Configuration) => Promise<void>;
76
+
77
+ export { bringInitBackground, bringInitContentScript };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var h=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var F=Object.prototype.hasOwnProperty;var K=(e,t)=>{for(var r in t)h(e,r,{get:t[r],enumerable:!0})},V=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of j(t))!F.call(e,s)&&s!==r&&h(e,s,{get:()=>t[s],enumerable:!(n=W(t,s))||n.enumerable});return e};var Q=e=>V(h({},"__esModule",{value:!0}),e);var ue={};K(ue,{bringInitBackground:()=>q,bringInitContentScript:()=>v});module.exports=Q(ue);var B=e=>{let t=new URLSearchParams,{query:r,prefix:n}=e;return Object.entries(r).forEach(([s,o])=>{o&&(n&&(s=`${n}_${s}`),s==="url"?t.append(s,encodeURIComponent(o)):t.append(s,o))}),t.toString()},f=B;var G=({query:e,theme:t,iframeSrc:r})=>{let n=chrome.runtime.id,s=f({query:{...e,extensionId:n}}),o=t?`&${f({query:t,prefix:"t"})}`:"",i=document.createElement("iframe");return i.id=`bringweb3-iframe:${n}`,i.src=`${r}?${s}${o}`,i.setAttribute("sandbox","allow-popups allow-scripts allow-same-origin allow-top-navigation-by-user-activation"),i.style.position="fixed",i.scrolling="no",i.style.overflow="hidden",i.style.width="1px",i.style.height="1px",i.style.right="8px",i.style.borderRadius="10px",i.style.border="none",i.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(i.style.boxShadow=t.popupShadow),document.documentElement.appendChild(i),i},b=G;var J=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([r,n])=>{r in e.style&&(e.style[r]=n)})},T=J;var H=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:s})=>{r.insertRule(`@keyframes ${n} { ${s} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},k=H;var u={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES"},Y=[u.ACTIVATE],z=({event:e,iframeEl:t,promptLogin:r})=>{let{data:n}=e,{from:s,action:o,style:i,keyFrames:a,time:c,extensionId:p}=n;if(s==="bringweb3"&&!(p!==chrome.runtime.id&&!Y.includes(o)))switch(o){case u.OPEN:T(t,i);break;case u.CLOSE:t&&t.parentNode?.removeChild(t),c&&chrome.runtime.sendMessage({action:o,time:c});break;case u.PROMPT_LOGIN:r();break;case u.ACTIVATE:chrome.runtime.sendMessage({action:o});break;case u.OPT_OUT:chrome.runtime.sendMessage({action:o,time:c});break;case u.ADD_KEYFRAMES:k(a);break;default:break}},x=z;var X=({walletAddressListeners:e,getWalletAddress:t,iframeEl:r})=>{for(let n=0;n<e.length;n++){let s=e[n];s&&window.addEventListener(s,async o=>{if(!r&&(r=document.querySelector(`#bringweb3-iframe:${chrome.runtime.id}`),!r)||!r.contentWindow)return;let i=await t();r.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:i},"*")})}},D=X;var w=null,C=!1,Z=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:r,customTheme:n,iframeEndpoint:s})=>{if(!e||!t||!r?.length||!s)throw new Error("Missing configuration");D({walletAddressListeners:r,getWalletAddress:e,iframeEl:w}),window.addEventListener("message",o=>x({event:o,iframeEl:w,promptLogin:t})),chrome.runtime.onMessage.addListener((o,i,a)=>{let{action:c}=o;switch(c){case"GET_WALLET_ADDRESS":return e().then(g=>a({status:"success",walletAddress:g})).catch(g=>a({status:"success",walletAddress:void 0})),!0;case"INJECT":if(C)return;let{token:p,page:m}=o;return w=b({query:{token:p},iframeSrc:m==="notification"?`${s}notification`:s,theme:n}),C=!0,a({status:"success"}),!0;default:console.error(`Unknown action: ${c}`);break}})},v=Z;var l=class e{static instance=null;apiEndpoint="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}};var ee=async e=>{let t=l.getInstance().getApiEndpoint();return await(await fetch(`${t}/domains`,{headers:{"x-api-key":e}})).json()},P=ee;var te=async({apiKey:e,query:t})=>{let r=l.getInstance().getApiEndpoint(),n=f({query:{...t,country:"us"}});return await(await fetch(`${r}/token?${n.toString()}`,{headers:{"x-api-key":e}})).json()},S=te;var ne=async({apiKey:e,walletAddress:t,cashbackUrl:r})=>{let n=l.getInstance().getApiEndpoint(),s={walletAddress:t};return r&&(s.cashbackUrl=r),await(await fetch(`${n}/check-events`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(s)})).json()},R=ne;var y="updateCache";var re=async(e,t)=>{chrome.storage.local.set({[e]:t})},se=async e=>(await chrome.storage.local.get(e))[e],ie=async e=>{chrome.storage.local.remove(e)},d={set:re,get:se,remove:ie};var O=30*60*1e3,_=async e=>{let t=await d.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 E(e,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&t!==r?.walletAddress&&(t=r?.walletAddress,await d.set("walletAddress",t))}catch{}return t},oe=e=>{let t=Date.now();return(e-t)/1e3/60},L=async e=>{let t=await P(e);d.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:r}=t,n=oe(r);chrome.alarms.create(y,{delayInMinutes:n})},ae=async(e,t,r,n)=>{let s={showNotification:!1,token:""},o=await d.get("notificationCheck");if(o?.check&&Date.now()<o.check)return s;let i=await _(t);if(!i)return s;let a=await R({apiKey:e,walletAddress:i,cashbackUrl:r}),c={check:n?a.nextRequestTimestampActivated:a.nextRequestTimestampRegular,nextRequestTimestampActivated:a.nextRequestTimestampActivated,nextRequestTimestampRegular:a.nextRequestTimestampRegular};return d.set("notificationCheck",c),{showNotification:a.showNotification,token:a.token}},ce=e=>e.replace(/^(https?:\/\/)?(www\.)?/,""),I=async e=>{let t=await d.get("relevantDomains");if(!e||!t||!t.length)return"";let r=ce(e);for(let n of t)if(r.startsWith(n)){let s=await d.get("quietDomains");return s&&s[n]&&Date.now()<s[n]?"":n}return""},M=async(e,t)=>{t||(t=O);let r=await d.get("quietDomains");typeof r=="object"?r[e]=Date.now()+t:r={[e]:Date.now()+O},d.set("quietDomains",r)},de=e=>e?chrome.runtime.getURL(e):void 0,E=async(e,t)=>{for(let s=0;s<5;s++)try{let o=await chrome.tabs.get(e);return chrome.runtime.lastError?void 0:await chrome.tabs.sendMessage(e,t)}catch{s<4&&await new Promise(i=>setTimeout(i,1e3*Math.pow(2,s)))}},N=async(e,t,r)=>{let n=await ae(e,t,de(r));n.showNotification&&await E(t,{action:"INJECT",token:n.token,page:"notification"})},A={},le=async({identifier:e,apiEndpoint:t,cashbackPagePath:r})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");l.getInstance().setApiEndpoint(t),L(e),chrome.alarms.onAlarm.addListener(async n=>{let{name:s}=n;switch(s){case y:L(e);break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener(async(n,s)=>{let{action:o,time:i}=n;switch(o){case"ACTIVATE":let a=await d.get("notificationCheck");if(!a.check||!a.nextRequestTimestampActivated)break;a.check=a.nextRequestTimestampActivated,d.set("notificationCheck",a);break;case"OPT_OUT":d.set("optOut",Date.now()+i);break;case"CLOSE":let c=await I(s.tab?.url||s.origin);if(!c)break;M(c,i);break;default:console.warn(`Bring unknown action: ${o}`);break}}),chrome.tabs.onUpdated.addListener(async(n,s,o)=>{let i=await d.get("optOut");if(i&&i>Date.now()){await N(e,n,r);return}if(!o.url)return;let a=new URL(o.url),c=`${a.hostname.replace("www.","")}${a.pathname}`,p=A[n];if(s.status!=="complete"||c===p)return;A[n]=c;let m=await I(o.url);if(!m||!m.length){await N(e,n,r);return}let g=await _(n),{token:U,isValid:$}=await S({apiKey:e,query:{domain:m,url:o.url,address:g}});if(!$){M(m);return}E(n,{action:"INJECT",token:U,domain:c})}),chrome.tabs.onRemoved.addListener(n=>delete A[n])},q=le;0&&(module.exports={bringInitBackground,bringInitContentScript});
1
+ "use strict";var h=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var K=(e,t)=>{for(var s in t)h(e,s,{get:t[s],enumerable:!0})},Q=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of F(t))!V.call(e,r)&&r!==s&&h(e,r,{get:()=>t[r],enumerable:!(n=$(t,r))||n.enumerable});return e};var B=e=>Q(h({},"__esModule",{value:!0}),e);var fe={};K(fe,{bringInitBackground:()=>U,bringInitContentScript:()=>S});module.exports=B(fe);var G=e=>{let t=new URLSearchParams,{query:s,prefix:n}=e;return Object.entries(s).forEach(([r,o])=>{o&&(n&&(r=`${n}_${r}`),r==="url"?t.append(r,encodeURIComponent(o)):t.append(r,o))}),t.toString()},p=G;var b={name:"@bringweb3/chrome-extension-kit",version:"1.0.4",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"},scripts:{watch:"tsup index.ts --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"}};var H=()=>b.version,x=H;var Y=({query:e,theme:t,iframeSrc:s})=>{let n=chrome.runtime.id,r=p({query:{...e,extensionId:n,v:x()}}),o=t?`&${p({query:t,prefix:"t"})}`:"",i=document.createElement("iframe");return i.id=`bringweb3-iframe:${n}`,i.src=`${s}?${r}${o}`,i.setAttribute("sandbox","allow-popups allow-scripts allow-same-origin allow-top-navigation-by-user-activation"),i.style.position="fixed",i.scrolling="no",i.style.overflow="hidden",i.style.width="1px",i.style.height="1px",i.style.right="8px",i.style.borderRadius="10px",i.style.border="none",i.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(i.style.boxShadow=t.popupShadow),document.documentElement.appendChild(i),i},T=Y;var z=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([s,n])=>{s in e.style&&(e.style[s]=n)})},k=z;var X=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let s=t.sheet;s?e.forEach(({name:n,rules:r})=>{s.insertRule(`@keyframes ${n} { ${r} }`,s.cssRules.length)}):console.error("Failed to create stylesheet")},v=X;var m={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES"},Z=[m.ACTIVATE],ee=({event:e,iframeEl:t,promptLogin:s})=>{let{data:n}=e,{from:r,action:o,style:i,keyFrames:a,time:d,extensionId:u}=n;if(r==="bringweb3"&&!(u!==chrome.runtime.id&&!Z.includes(o)))switch(o){case m.OPEN:k(t,i);break;case m.CLOSE:t&&t.parentNode?.removeChild(t),d&&chrome.runtime.sendMessage({action:o,time:d});break;case m.PROMPT_LOGIN:s();break;case m.ACTIVATE:chrome.runtime.sendMessage({action:o});break;case m.OPT_OUT:chrome.runtime.sendMessage({action:o,time:d});break;case m.ADD_KEYFRAMES:v(a);break;default:break}},D=ee;var te=({walletAddressListeners:e,getWalletAddress:t,iframeEl:s})=>{for(let n=0;n<e.length;n++){let r=e[n];r&&window.addEventListener(r,async o=>{if(!s&&(s=document.querySelector(`#bringweb3-iframe:${chrome.runtime.id}`),!s)||!s.contentWindow)return;let i=await t();s.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:i},"*")})}},C=te;var w=null,P=!1,ne=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:s,customTheme:n,iframeEndpoint:r})=>{if(!e||!t||!s?.length||!r)throw new Error("Missing configuration");C({walletAddressListeners:s,getWalletAddress:e,iframeEl:w}),window.addEventListener("message",o=>D({event:o,iframeEl:w,promptLogin:t})),chrome.runtime.onMessage.addListener((o,i,a)=>{let{action:d}=o;switch(d){case"GET_WALLET_ADDRESS":return e().then(f=>a({status:"success",walletAddress:f})).catch(f=>a({status:"success",walletAddress:void 0})),!0;case"INJECT":if(P)return;let{token:u,page:g}=o;return w=T({query:{token:u},iframeSrc:g==="notification"?`${r}notification`:r,theme:n}),P=!0,a({status:"success"}),!0;default:console.error(`Unknown action: ${d}`);break}})},S=ne;var l=class e{static instance=null;apiEndpoint="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}};var se=async e=>{let t=l.getInstance().getApiEndpoint();return await(await fetch(`${t}/domains`,{headers:{"x-api-key":e}})).json()},R=se;var re=async({apiKey:e,query:t})=>{let s=l.getInstance().getApiEndpoint(),n=p({query:{...t,country:"us"}});return await(await fetch(`${s}/token?${n.toString()}`,{headers:{"x-api-key":e}})).json()},O=re;var ie=async({apiKey:e,walletAddress:t,cashbackUrl:s})=>{let n=l.getInstance().getApiEndpoint(),r={walletAddress:t};return s&&(r.cashbackUrl=s),await(await fetch(`${n}/check-events`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(r)})).json()},I=ie;var y="updateCache";var oe=async(e,t)=>{chrome.storage.local.set({[e]:t})},ae=async e=>(await chrome.storage.local.get(e))[e],ce=async e=>{chrome.storage.local.remove(e)},c={set:oe,get:ae,remove:ce};var L=30*60*1e3,j=async e=>{let t=await c.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 s=await E(e,{action:"GET_WALLET_ADDRESS"});s?.walletAddress&&t!==s?.walletAddress&&(t=s?.walletAddress,await c.set("walletAddress",t))}catch{}return t},de=e=>{let t=Date.now();return(e-t)/1e3/60},M=async e=>{let t=await R(e);c.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:s}=t,n=de(s);chrome.alarms.create(y,{delayInMinutes:n})},le=async(e,t,s,n)=>{let r={showNotification:!1,token:""},o=await c.get("notificationCheck");if(o?.check&&Date.now()<o.check)return r;let i=await j(t);if(!i)return r;let a=await I({apiKey:e,walletAddress:i,cashbackUrl:s}),d={check:n?a.nextRequestTimestampActivated:a.nextRequestTimestampRegular,nextRequestTimestampActivated:a.nextRequestTimestampActivated,nextRequestTimestampRegular:a.nextRequestTimestampRegular};return c.set("notificationCheck",d),{showNotification:a.showNotification,token:a.token}},ue=e=>e.replace(/^(https?:\/\/)?(www\.)?/,""),N=async e=>{let t=await c.get("relevantDomains");if(!e||!t||!t.length)return"";let s=ue(e);for(let n of t)if(s.startsWith(n)){let r=await c.get("quietDomains");return r&&r[n]&&Date.now()<r[n]?"":n}return""},_=async(e,t)=>{t||(t=L);let s=await c.get("quietDomains");typeof s=="object"?s[e]=Date.now()+t:s={[e]:Date.now()+L},c.set("quietDomains",s)},me=e=>e?chrome.runtime.getURL(e):void 0,E=async(e,t)=>{for(let r=0;r<5;r++)try{let o=await chrome.tabs.get(e);return chrome.runtime.lastError?void 0:await chrome.tabs.sendMessage(e,t)}catch{r<4&&await new Promise(i=>setTimeout(i,1e3*Math.pow(2,r)))}},q=async(e,t,s)=>{let n=await le(e,t,me(s));n.showNotification&&await E(t,{action:"INJECT",token:n.token,page:"notification"})},A={},pe=async({identifier:e,apiEndpoint:t,cashbackPagePath:s})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");l.getInstance().setApiEndpoint(t),M(e),chrome.alarms.onAlarm.addListener(async n=>{let{name:r}=n;switch(r){case y:M(e);break;default:console.error("alarm with no use case:",r);break}}),chrome.runtime.onMessage.addListener(async(n,r)=>{let{action:o,time:i}=n;switch(o){case"ACTIVATE":let a=await c.get("notificationCheck");if(!a.check||!a.nextRequestTimestampActivated)break;a.check=a.nextRequestTimestampActivated,c.set("notificationCheck",a);break;case"OPT_OUT":c.set("optOut",Date.now()+i);break;case"CLOSE":let d=await N(r.tab?.url||r.origin);if(!d)break;_(d,i);break;default:console.warn(`Bring unknown action: ${o}`);break}}),chrome.tabs.onUpdated.addListener(async(n,r,o)=>{let i=await c.get("optOut");if(i&&i>Date.now()){await q(e,n,s);return}if(!o.url)return;let a=o.url.replace("www.",""),d=A[n];if(r.status!=="complete"||a===d)return;A[n]=a;let u=await N(o.url);if(!u||!u.length){await q(e,n,s);return}let g=await j(n),{token:f,isValid:W}=await O({apiKey:e,query:{domain:u,url:o.url,address:g}});if(!W){_(u);return}E(n,{action:"INJECT",token:f,domain:a})}),chrome.tabs.onRemoved.addListener(n=>delete A[n])},U=pe;0&&(module.exports={bringInitBackground,bringInitContentScript});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var q=e=>{let t=new URLSearchParams,{query:r,prefix:n}=e;return Object.entries(r).forEach(([s,o])=>{o&&(n&&(s=`${n}_${s}`),s==="url"?t.append(s,encodeURIComponent(o)):t.append(s,o))}),t.toString()},f=q;var U=({query:e,theme:t,iframeSrc:r})=>{let n=chrome.runtime.id,s=f({query:{...e,extensionId:n}}),o=t?`&${f({query:t,prefix:"t"})}`:"",i=document.createElement("iframe");return i.id=`bringweb3-iframe:${n}`,i.src=`${r}?${s}${o}`,i.setAttribute("sandbox","allow-popups allow-scripts allow-same-origin allow-top-navigation-by-user-activation"),i.style.position="fixed",i.scrolling="no",i.style.overflow="hidden",i.style.width="1px",i.style.height="1px",i.style.right="8px",i.style.borderRadius="10px",i.style.border="none",i.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(i.style.boxShadow=t.popupShadow),document.documentElement.appendChild(i),i},E=U;var $=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([r,n])=>{r in e.style&&(e.style[r]=n)})},b=$;var W=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:s})=>{r.insertRule(`@keyframes ${n} { ${s} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},T=W;var u={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES"},j=[u.ACTIVATE],F=({event:e,iframeEl:t,promptLogin:r})=>{let{data:n}=e,{from:s,action:o,style:i,keyFrames:a,time:c,extensionId:p}=n;if(s==="bringweb3"&&!(p!==chrome.runtime.id&&!j.includes(o)))switch(o){case u.OPEN:b(t,i);break;case u.CLOSE:t&&t.parentNode?.removeChild(t),c&&chrome.runtime.sendMessage({action:o,time:c});break;case u.PROMPT_LOGIN:r();break;case u.ACTIVATE:chrome.runtime.sendMessage({action:o});break;case u.OPT_OUT:chrome.runtime.sendMessage({action:o,time:c});break;case u.ADD_KEYFRAMES:T(a);break;default:break}},k=F;var K=({walletAddressListeners:e,getWalletAddress:t,iframeEl:r})=>{for(let n=0;n<e.length;n++){let s=e[n];s&&window.addEventListener(s,async o=>{if(!r&&(r=document.querySelector(`#bringweb3-iframe:${chrome.runtime.id}`),!r)||!r.contentWindow)return;let i=await t();r.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:i},"*")})}},x=K;var h=null,D=!1,V=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:r,customTheme:n,iframeEndpoint:s})=>{if(!e||!t||!r?.length||!s)throw new Error("Missing configuration");x({walletAddressListeners:r,getWalletAddress:e,iframeEl:h}),window.addEventListener("message",o=>k({event:o,iframeEl:h,promptLogin:t})),chrome.runtime.onMessage.addListener((o,i,a)=>{let{action:c}=o;switch(c){case"GET_WALLET_ADDRESS":return e().then(g=>a({status:"success",walletAddress:g})).catch(g=>a({status:"success",walletAddress:void 0})),!0;case"INJECT":if(D)return;let{token:p,page:m}=o;return h=E({query:{token:p},iframeSrc:m==="notification"?`${s}notification`:s,theme:n}),D=!0,a({status:"success"}),!0;default:console.error(`Unknown action: ${c}`);break}})},Q=V;var l=class e{static instance=null;apiEndpoint="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}};var B=async e=>{let t=l.getInstance().getApiEndpoint();return await(await fetch(`${t}/domains`,{headers:{"x-api-key":e}})).json()},C=B;var G=async({apiKey:e,query:t})=>{let r=l.getInstance().getApiEndpoint(),n=f({query:{...t,country:"us"}});return await(await fetch(`${r}/token?${n.toString()}`,{headers:{"x-api-key":e}})).json()},v=G;var J=async({apiKey:e,walletAddress:t,cashbackUrl:r})=>{let n=l.getInstance().getApiEndpoint(),s={walletAddress:t};return r&&(s.cashbackUrl=r),await(await fetch(`${n}/check-events`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(s)})).json()},P=J;var w="updateCache";var H=async(e,t)=>{chrome.storage.local.set({[e]:t})},Y=async e=>(await chrome.storage.local.get(e))[e],z=async e=>{chrome.storage.local.remove(e)},d={set:H,get:Y,remove:z};var S=30*60*1e3,M=async e=>{let t=await d.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 A(e,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&t!==r?.walletAddress&&(t=r?.walletAddress,await d.set("walletAddress",t))}catch{}return t},X=e=>{let t=Date.now();return(e-t)/1e3/60},R=async e=>{let t=await C(e);d.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:r}=t,n=X(r);chrome.alarms.create(w,{delayInMinutes:n})},Z=async(e,t,r,n)=>{let s={showNotification:!1,token:""},o=await d.get("notificationCheck");if(o?.check&&Date.now()<o.check)return s;let i=await M(t);if(!i)return s;let a=await P({apiKey:e,walletAddress:i,cashbackUrl:r}),c={check:n?a.nextRequestTimestampActivated:a.nextRequestTimestampRegular,nextRequestTimestampActivated:a.nextRequestTimestampActivated,nextRequestTimestampRegular:a.nextRequestTimestampRegular};return d.set("notificationCheck",c),{showNotification:a.showNotification,token:a.token}},ee=e=>e.replace(/^(https?:\/\/)?(www\.)?/,""),O=async e=>{let t=await d.get("relevantDomains");if(!e||!t||!t.length)return"";let r=ee(e);for(let n of t)if(r.startsWith(n)){let s=await d.get("quietDomains");return s&&s[n]&&Date.now()<s[n]?"":n}return""},L=async(e,t)=>{t||(t=S);let r=await d.get("quietDomains");typeof r=="object"?r[e]=Date.now()+t:r={[e]:Date.now()+S},d.set("quietDomains",r)},te=e=>e?chrome.runtime.getURL(e):void 0,A=async(e,t)=>{for(let s=0;s<5;s++)try{let o=await chrome.tabs.get(e);return chrome.runtime.lastError?void 0:await chrome.tabs.sendMessage(e,t)}catch{s<4&&await new Promise(i=>setTimeout(i,1e3*Math.pow(2,s)))}},I=async(e,t,r)=>{let n=await Z(e,t,te(r));n.showNotification&&await A(t,{action:"INJECT",token:n.token,page:"notification"})},y={},ne=async({identifier:e,apiEndpoint:t,cashbackPagePath:r})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");l.getInstance().setApiEndpoint(t),R(e),chrome.alarms.onAlarm.addListener(async n=>{let{name:s}=n;switch(s){case w:R(e);break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener(async(n,s)=>{let{action:o,time:i}=n;switch(o){case"ACTIVATE":let a=await d.get("notificationCheck");if(!a.check||!a.nextRequestTimestampActivated)break;a.check=a.nextRequestTimestampActivated,d.set("notificationCheck",a);break;case"OPT_OUT":d.set("optOut",Date.now()+i);break;case"CLOSE":let c=await O(s.tab?.url||s.origin);if(!c)break;L(c,i);break;default:console.warn(`Bring unknown action: ${o}`);break}}),chrome.tabs.onUpdated.addListener(async(n,s,o)=>{let i=await d.get("optOut");if(i&&i>Date.now()){await I(e,n,r);return}if(!o.url)return;let a=new URL(o.url),c=`${a.hostname.replace("www.","")}${a.pathname}`,p=y[n];if(s.status!=="complete"||c===p)return;y[n]=c;let m=await O(o.url);if(!m||!m.length){await I(e,n,r);return}let g=await M(n),{token:N,isValid:_}=await v({apiKey:e,query:{domain:m,url:o.url,address:g}});if(!_){L(m);return}A(n,{action:"INJECT",token:N,domain:c})}),chrome.tabs.onRemoved.addListener(n=>delete y[n])},re=ne;export{re as bringInitBackground,Q as bringInitContentScript};
1
+ var j=e=>{let t=new URLSearchParams,{query:s,prefix:n}=e;return Object.entries(s).forEach(([r,o])=>{o&&(n&&(r=`${n}_${r}`),r==="url"?t.append(r,encodeURIComponent(o)):t.append(r,o))}),t.toString()},p=j;var E={name:"@bringweb3/chrome-extension-kit",version:"1.0.4",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"},scripts:{watch:"tsup index.ts --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"}};var W=()=>E.version,b=W;var $=({query:e,theme:t,iframeSrc:s})=>{let n=chrome.runtime.id,r=p({query:{...e,extensionId:n,v:b()}}),o=t?`&${p({query:t,prefix:"t"})}`:"",i=document.createElement("iframe");return i.id=`bringweb3-iframe:${n}`,i.src=`${s}?${r}${o}`,i.setAttribute("sandbox","allow-popups allow-scripts allow-same-origin allow-top-navigation-by-user-activation"),i.style.position="fixed",i.scrolling="no",i.style.overflow="hidden",i.style.width="1px",i.style.height="1px",i.style.right="8px",i.style.borderRadius="10px",i.style.border="none",i.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(i.style.boxShadow=t.popupShadow),document.documentElement.appendChild(i),i},x=$;var F=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([s,n])=>{s in e.style&&(e.style[s]=n)})},T=F;var V=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let s=t.sheet;s?e.forEach(({name:n,rules:r})=>{s.insertRule(`@keyframes ${n} { ${r} }`,s.cssRules.length)}):console.error("Failed to create stylesheet")},k=V;var m={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES"},K=[m.ACTIVATE],Q=({event:e,iframeEl:t,promptLogin:s})=>{let{data:n}=e,{from:r,action:o,style:i,keyFrames:a,time:d,extensionId:u}=n;if(r==="bringweb3"&&!(u!==chrome.runtime.id&&!K.includes(o)))switch(o){case m.OPEN:T(t,i);break;case m.CLOSE:t&&t.parentNode?.removeChild(t),d&&chrome.runtime.sendMessage({action:o,time:d});break;case m.PROMPT_LOGIN:s();break;case m.ACTIVATE:chrome.runtime.sendMessage({action:o});break;case m.OPT_OUT:chrome.runtime.sendMessage({action:o,time:d});break;case m.ADD_KEYFRAMES:k(a);break;default:break}},v=Q;var B=({walletAddressListeners:e,getWalletAddress:t,iframeEl:s})=>{for(let n=0;n<e.length;n++){let r=e[n];r&&window.addEventListener(r,async o=>{if(!s&&(s=document.querySelector(`#bringweb3-iframe:${chrome.runtime.id}`),!s)||!s.contentWindow)return;let i=await t();s.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:i},"*")})}},D=B;var h=null,C=!1,G=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:s,customTheme:n,iframeEndpoint:r})=>{if(!e||!t||!s?.length||!r)throw new Error("Missing configuration");D({walletAddressListeners:s,getWalletAddress:e,iframeEl:h}),window.addEventListener("message",o=>v({event:o,iframeEl:h,promptLogin:t})),chrome.runtime.onMessage.addListener((o,i,a)=>{let{action:d}=o;switch(d){case"GET_WALLET_ADDRESS":return e().then(f=>a({status:"success",walletAddress:f})).catch(f=>a({status:"success",walletAddress:void 0})),!0;case"INJECT":if(C)return;let{token:u,page:g}=o;return h=x({query:{token:u},iframeSrc:g==="notification"?`${r}notification`:r,theme:n}),C=!0,a({status:"success"}),!0;default:console.error(`Unknown action: ${d}`);break}})},J=G;var l=class e{static instance=null;apiEndpoint="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}};var H=async e=>{let t=l.getInstance().getApiEndpoint();return await(await fetch(`${t}/domains`,{headers:{"x-api-key":e}})).json()},P=H;var Y=async({apiKey:e,query:t})=>{let s=l.getInstance().getApiEndpoint(),n=p({query:{...t,country:"us"}});return await(await fetch(`${s}/token?${n.toString()}`,{headers:{"x-api-key":e}})).json()},S=Y;var z=async({apiKey:e,walletAddress:t,cashbackUrl:s})=>{let n=l.getInstance().getApiEndpoint(),r={walletAddress:t};return s&&(r.cashbackUrl=s),await(await fetch(`${n}/check-events`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(r)})).json()},R=z;var w="updateCache";var X=async(e,t)=>{chrome.storage.local.set({[e]:t})},Z=async e=>(await chrome.storage.local.get(e))[e],ee=async e=>{chrome.storage.local.remove(e)},c={set:X,get:Z,remove:ee};var O=30*60*1e3,_=async e=>{let t=await c.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 s=await A(e,{action:"GET_WALLET_ADDRESS"});s?.walletAddress&&t!==s?.walletAddress&&(t=s?.walletAddress,await c.set("walletAddress",t))}catch{}return t},te=e=>{let t=Date.now();return(e-t)/1e3/60},I=async e=>{let t=await P(e);c.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:s}=t,n=te(s);chrome.alarms.create(w,{delayInMinutes:n})},ne=async(e,t,s,n)=>{let r={showNotification:!1,token:""},o=await c.get("notificationCheck");if(o?.check&&Date.now()<o.check)return r;let i=await _(t);if(!i)return r;let a=await R({apiKey:e,walletAddress:i,cashbackUrl:s}),d={check:n?a.nextRequestTimestampActivated:a.nextRequestTimestampRegular,nextRequestTimestampActivated:a.nextRequestTimestampActivated,nextRequestTimestampRegular:a.nextRequestTimestampRegular};return c.set("notificationCheck",d),{showNotification:a.showNotification,token:a.token}},se=e=>e.replace(/^(https?:\/\/)?(www\.)?/,""),L=async e=>{let t=await c.get("relevantDomains");if(!e||!t||!t.length)return"";let s=se(e);for(let n of t)if(s.startsWith(n)){let r=await c.get("quietDomains");return r&&r[n]&&Date.now()<r[n]?"":n}return""},M=async(e,t)=>{t||(t=O);let s=await c.get("quietDomains");typeof s=="object"?s[e]=Date.now()+t:s={[e]:Date.now()+O},c.set("quietDomains",s)},re=e=>e?chrome.runtime.getURL(e):void 0,A=async(e,t)=>{for(let r=0;r<5;r++)try{let o=await chrome.tabs.get(e);return chrome.runtime.lastError?void 0:await chrome.tabs.sendMessage(e,t)}catch{r<4&&await new Promise(i=>setTimeout(i,1e3*Math.pow(2,r)))}},N=async(e,t,s)=>{let n=await ne(e,t,re(s));n.showNotification&&await A(t,{action:"INJECT",token:n.token,page:"notification"})},y={},ie=async({identifier:e,apiEndpoint:t,cashbackPagePath:s})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");l.getInstance().setApiEndpoint(t),I(e),chrome.alarms.onAlarm.addListener(async n=>{let{name:r}=n;switch(r){case w:I(e);break;default:console.error("alarm with no use case:",r);break}}),chrome.runtime.onMessage.addListener(async(n,r)=>{let{action:o,time:i}=n;switch(o){case"ACTIVATE":let a=await c.get("notificationCheck");if(!a.check||!a.nextRequestTimestampActivated)break;a.check=a.nextRequestTimestampActivated,c.set("notificationCheck",a);break;case"OPT_OUT":c.set("optOut",Date.now()+i);break;case"CLOSE":let d=await L(r.tab?.url||r.origin);if(!d)break;M(d,i);break;default:console.warn(`Bring unknown action: ${o}`);break}}),chrome.tabs.onUpdated.addListener(async(n,r,o)=>{let i=await c.get("optOut");if(i&&i>Date.now()){await N(e,n,s);return}if(!o.url)return;let a=o.url.replace("www.",""),d=y[n];if(r.status!=="complete"||a===d)return;y[n]=a;let u=await L(o.url);if(!u||!u.length){await N(e,n,s);return}let g=await _(n),{token:f,isValid:q}=await S({apiKey:e,query:{domain:u,url:o.url,address:g}});if(!q){M(u);return}A(n,{action:"INJECT",token:f,domain:a})}),chrome.tabs.onRemoved.addListener(n=>delete y[n])},oe=ie;export{oe as bringInitBackground,J as bringInitContentScript};
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@bringweb3/chrome-extension-kit",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
+ "description": "Crypto cashback integration kit for crypto outlets extension",
4
5
  "main": "dist/index.js",
5
6
  "module": "dist/index.mjs",
6
7
  "types": "dist/index.d.ts",
@@ -14,7 +15,7 @@
14
15
  "build": "tsup index.ts --format cjs,esm --dts --minify",
15
16
  "lint": "tsc",
16
17
  "test": "vitest --coverage",
17
- "release": "yarn build & changeset publish"
18
+ "release": "yarn build && changeset publish"
18
19
  },
19
20
  "files": [
20
21
  "dist",