@givefreely/adunit 2.3.0-dev.0 → 2.3.1-dev.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.
@@ -1,2 +1,2 @@
1
- "use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var t={exports:{}};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){if(!(globalThis.chrome&&globalThis.chrome.runtime&&globalThis.chrome.runtime.id))throw new Error("This script should only be loaded in a browser extension.");if(globalThis.browser&&globalThis.browser.runtime&&globalThis.browser.runtime.id)e.exports=globalThis.browser;else{const t="The message port closed before a response was received.",r=e=>{const r={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(0===Object.keys(r).length)throw new Error("api-metadata.json has not been included in browser-polyfill");class i extends WeakMap{constructor(e,t=void 0){super(t),this.createItem=e}get(e){return this.has(e)||this.set(e,this.createItem(e)),super.get(e)}}const n=(t,r)=>(...i)=>{e.runtime.lastError?t.reject(new Error(e.runtime.lastError.message)):r.singleCallbackArg||i.length<=1&&!1!==r.singleCallbackArg?t.resolve(i[0]):t.resolve(i)},s=e=>1==e?"argument":"arguments",a=(e,t,r)=>new Proxy(t,{apply:(t,i,n)=>r.call(i,e,...n)});let o=Function.call.bind(Object.prototype.hasOwnProperty);const c=(e,t={},r={})=>{let i=Object.create(null),l={has:(t,r)=>r in e||r in i,get(l,g,h){if(g in i)return i[g];if(!(g in e))return;let d=e[g];if("function"==typeof d)if("function"==typeof t[g])d=a(e,e[g],t[g]);else if(o(r,g)){let t=((e,t)=>function(r,...i){if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${s(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${s(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((s,a)=>{if(t.fallbackToNoCallback)try{r[e](...i,n({resolve:s,reject:a},t))}catch(n){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,n),r[e](...i),t.fallbackToNoCallback=!1,t.noCallback=!0,s()}else t.noCallback?(r[e](...i),s()):r[e](...i,n({resolve:s,reject:a},t))}))})(g,r[g]);d=a(e,e[g],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(o(t,g)||o(r,g)))d=c(d,t[g],r[g]);else{if(!o(r,"*"))return Object.defineProperty(i,g,{configurable:!0,enumerable:!0,get:()=>e[g],set(t){e[g]=t}}),d;d=c(d,t[g],r["*"])}return i[g]=d,d},set:(t,r,n,s)=>(r in i?i[r]=n:e[r]=n,!0),defineProperty:(e,t,r)=>Reflect.defineProperty(i,t,r),deleteProperty:(e,t)=>Reflect.deleteProperty(i,t)},g=Object.create(e);return new Proxy(g,l)},l=e=>({addListener(t,r,...i){t.addListener(e.get(r),...i)},hasListener:(t,r)=>t.hasListener(e.get(r)),removeListener(t,r){t.removeListener(e.get(r))}}),g=new i((e=>"function"!=typeof e?e:function(t){const r=c(t,{},{getContent:{minArgs:0,maxArgs:0}});e(r)})),h=new i((e=>"function"!=typeof e?e:function(t,r,i){let n,s,a=!1,o=new Promise((e=>{n=function(t){a=!0,e(t)}}));try{s=e(t,r,n)}catch(e){s=Promise.reject(e)}const c=!0!==s&&((l=s)&&"object"==typeof l&&"function"==typeof l.then);var l;if(!0!==s&&!c&&!a)return!1;return(c?s:o).then((e=>{i(e)}),(e=>{let t;t=e&&(e instanceof Error||"string"==typeof e.message)?e.message:"An unexpected error occurred",i({__mozWebExtensionPolyfillReject__:!0,message:t})})).catch((e=>{console.error("Failed to send onMessage rejected reply",e)})),!0})),d=({reject:r,resolve:i},n)=>{e.runtime.lastError?e.runtime.lastError.message===t?i():r(new Error(e.runtime.lastError.message)):n&&n.__mozWebExtensionPolyfillReject__?r(new Error(n.message)):i(n)},u=(e,t,r,...i)=>{if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${s(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${s(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((e,t)=>{const n=d.bind(null,{resolve:e,reject:t});i.push(n),r.sendMessage(...i)}))},m={devtools:{network:{onRequestFinished:l(g)}},runtime:{onMessage:l(h),onMessageExternal:l(h),sendMessage:u.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:u.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},f={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return r.privacy={network:{"*":f},services:{"*":f},websites:{"*":f}},c(e,m,r)};e.exports=r(chrome)}}(t);var r,i,browser=e(t.exports);class n{constructor(){this.isLocal=!0}log({level:e,message:t,timestamp:r,data:i,title:s}){let a;switch(e){case"debug":default:a="log";break;case"info":a="info";break;case"warn":a="warn";break;case"error":case"critical":case"fatal":a="error"}const o=s?`[${s}]`:"";void 0!==i?console[a](`[${r}] - ${n.LOGGER_PREFIX} ${o} ${t}`,i):console[a](`[${r}] - ${n.LOGGER_PREFIX} ${o} ${t}`)}}n.LOGGER_PREFIX="[DonationPopup] -",function(e){e.checkoutPopupShown="CHECKOUT-POPUP-SHOWN",e.checkoutPopupNotShown="CHECKOUT-POPUP-NOT-SHOWN",e.checkoutPopupSupressed="CHECKOUT-POPUP-SUPRESSED",e.checkoutPopupDonation="CHECKOUT-POPUP-DONATION",e.checkoutPopupFailedActivation="CHECKOUT-POPUP-FAILED-ACTIVATION",e.checkoutPopupPurchaseConfirmed="CHECKOUT-POPUP-PURCHASE-CONFIRMED",e.checkoutPopupHealthCheck="CHECKOUT-POPUP-HEALTH-CHECK",e.checkouPopupActivationFailed="CHECKOUT-POPUP-ACTIVATION-FAILED",e.checkoutPopupOfferDetailsClicked="CHECKOUT-POPUP-OFFER-DETAILS-CLICKED",e.checkoutPopupWhyAmISeeingThisClicked="CHECKOUT-POPUP-WHY-AM-I-SEEING-THIS-CLICKED",e.checkoutPopupLooserExtension="CHECKOUT-POPUP-LOOSER-EXTENSION",e.checkoutPopupActiveDomain="CHECKOUT-POPUP-ACTIVE-DOMAIN",e.checkoutPopupSiteMatches="CHECKOUT-POPUP-SITE-MATCHES",e.checkoutPopupMerchantInResultsFound="CHECKOUT-MERCHANT-IN-RESULTS-FOUND",e.checkoutPopupNotShownPerViewportSize="CHECKOUT-POPUP-NOT-SHOWN-PER-VIEWPORT-SIZE",e.checkoutPopupHiddenProgrammatically="CHECKOUT-POPUP-HIDDEN-PROGRAMMATICALLY",e.checkoutPopupGoogleSearch="CHECKOUT-POPUP-GOOGLE-SEARCH",e.checkoutPopupGooglePartnerAnnCreated="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-CREATED",e.checkoutPopupGooglePartnerAnnClicked="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-CLICKED",e.checkoutPopupGooglePartnerAnnHidden="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-HIDDEN",e.checkoutPopupStoodDown="CHECKOUT-POPUP-STOOD-DOWN"}(r||(r={})),function(e){e.libLog="GFLIB-LOG"}(i||(i={}));class s{constructor(e){this.isLocal=!1,this.backgroundService=e}log({level:e,message:t,data:r,title:n}){this.backgroundService.trackEvent(i.libLog,{log:{level:e,message:t,data:r,title:n}})}}const a=["debug","info","warn","error","critical","fatal"];class o{constructor(e){this.config={minLevel:e?.minLevel??"debug",enabled:e?.enabled??!1,transports:e?.transports??[new n],title:e?.title??""}}static getInstance(e){return o.instance||(o.instance=new o(e)),o.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&a.indexOf(e)>=a.indexOf(this.config.minLevel)}createLogMessage(e,t,r){return{level:e,version:"2.2.1",message:t,timestamp:(new Date).toISOString(),data:r,title:this.config.title}}log(e,t,r,i){if(!this.shouldLog(e))return;const n=this.createLogMessage(e,t,i);this.config.transports.filter((e=>!r||e.isLocal)).forEach((e=>e.log(n)))}debug(e,t,r=!1){this.log("debug",e,r,t)}info(e,t,r=!1){this.log("info",e,r,t)}warn(e,t,r=!1){this.log("warn",e,r,t)}error(e,t,r=!1){this.log("error",e,r,t)}critical(e,t,r=!1){this.log("critical",e,r,t)}fatal(e,t,r=!1){this.log("fatal",e,r,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}const c=3,l=e=>1e3*e;async function g(e,t={},r){const{maxAttempts:i=c,delayFn:n=l}=t;let s=null;for(let t=1;t<=i;t+=1)try{return await e()}catch(e){s=e,t<i&&await new Promise((e=>{setTimeout(e,n(t))}))}throw s&&t.logger&&t.operationName&&t.logger.error(`Operation ${t.operationName} failed after ${i} attempts.`,s,!0),s||new Error("Operation failed after multiple attempts")}const h=browser,d={TRACK_EVENT:"GF_TRACK_EVENT",HIDE_POPUP:"GF_HIDE_POPUP",GET_POPUP_CONFIG:"GF_GET_POPUP_CONFIG",IS_ACTIVE_DOMAIN:"GF_IS_ACTIVE_DOMAIN",LOG_MERCHANTS_IN_SEARCH_RESULTS:"GF_LOG_MERCHANTS_IN_SEARCH_RESULTS",SHOULD_STAND_DOWN:"GF_SHOULD_STAND_DOWN",ACTIVATE_OFFER:"GF_ACTIVATE_OFFER",STORE_SHOPIFY_SHOP_ID:"GF_STORE_SHOPIFY_SHOP_ID",GET_DOMAIN_BY_SHOP_ID:"GF_GET_DOMAIN_BY_SHOP_ID",GET_LANGUAGE_CONTENT:"GF_GET_LANGUAGE_CONTENT",GET_ACTIVE_DOMAINS:"GF_GET_ACTIVE_DOMAINS",MUTE_PARTNER_SERP_BOX:"GF_MUTE_PARTNER_SERP_BOX"},u="shopify_shop_ids",m="gf_last_health_check",f="gf_partner_config",p="gf_global_config",A="countryCode",y="version",w="gf_anonymous_user_info",v="gf_anonymous_encrypted_token",C="gf_event_history",E="gf_popup_everywhere",S={DEVICE:"wfDevice",DOMAINS:"wfDomains",STANDDOWN_POLICY:"wfStanddownPolicy",STANDDOWN_HISTORY:"wfStanddownHistory",STANDDOWN_ACTIVATIONS:"wfStanddownActivations",LAST_CACHE_REFRESH:"wfLastCacheRefresh",MERCHANT_RATES:"wfMerchantRates"},b="gfPreActivation",P="gfStanddownHistory",T="gfStanddownActivations",_="en",O="GIVE_FREELY_",x={async get(e){const t=`${O}${e}`;return(await browser.storage.local.get(t))[t]||null},async set(e,t){const r=`${O}${e}`;await browser.storage.local.set({[r]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${O}${e}`)):`${O}${e}`;await browser.storage.local.remove(t)}},I=()=>String("2.2.1"),F=async(e=!0)=>{const t=await x.get(y),r=await I(),i=t!==r;var n;return e&&i&&await(n=r,x.set(y,n)),i},k=o.getInstance(),U={async get(e,t,r,i=!1,n){let s=await x.get(e);const a=s;let o=!1,c=r??s?.retentionInSeconds??600;if(s&&Date.now()<=s.lastFetch+1e3*c&&!i)return{content:s.content,isStale:o};try{const r=await t(),i=n?n(r):null;null!=i&&(c=i),s=await this.set(e,r,c)}catch(e){k.error("Error getting cached value",{error:e}),o=!0}return{content:s?.content??a?.content,isStale:o}},async set(e,t,r){const i=r??600,n={content:t,lastFetch:Date.now(),retentionInSeconds:i};return await x.set(e,n),n},async clear(e){await x.remove(e)}};class D{constructor(){this.listeners=new Map,this.wildcardListeners=new Set}on(e,t){return this.addListener(e,t,!1)}once(e,t){return this.addListener(e,t,!0)}off(e,t){if(!t)return this.listeners.delete(e),void(this.wildcardListeners=new Set(Array.from(this.wildcardListeners).filter((t=>t.pattern!==e))));if(e.includes("*"))this.wildcardListeners=new Set(Array.from(this.wildcardListeners).filter((r=>!(r.pattern===e&&r.callback===t))));else{const r=this.listeners.get(e);if(r){const i=Array.from(r).filter((e=>e.callback!==t));i.length>0?this.listeners.set(e,new Set(i)):this.listeners.delete(e)}}}emit(e){const t=this.listeners.get(e.path)||new Set,r=new Set;for(const e of t)r.add(e);for(const t of this.wildcardListeners)this.matchesPattern(e.path,t.pattern)&&r.add(t);for(const t of r)t.callback(e),t.once&&this.removeListener(t)}clear(){this.listeners.clear(),this.wildcardListeners.clear()}addListener(e,t,r){const i={pattern:e,callback:t,once:r};if(e.includes("*"))this.wildcardListeners.add(i);else{const t=this.listeners.get(e);t?t.add(i):this.listeners.set(e,new Set([i]))}return()=>this.off(e,t)}removeListener(e){if(e.pattern.includes("*"))this.wildcardListeners.delete(e);else{const t=this.listeners.get(e.pattern);t&&(t.delete(e),0===t.size&&this.listeners.delete(e.pattern))}}matchesPattern(e,t){if("*"===t)return!0;const r=t.split(".").map((e=>"*"===e?"[^.]+":"**"===e?".*":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"))).join("\\.");return new RegExp(`^${r}$`).test(e)}}function L(e,t,r=""){const i=[];if(e===t)return i;if(R(e)||R(t))return e!==t&&i.push({path:r||"root",oldValue:e,newValue:t}),i;if(Array.isArray(e)&&Array.isArray(t))return JSON.stringify(e)!==JSON.stringify(t)&&i.push({path:r||"root",oldValue:e,newValue:t}),i;if(N(e)&&N(t)){const n=e,s=t,a=new Set([...Object.keys(n),...Object.keys(s)]);for(const e of a){const t=r?`${r}.${e}`:e,a=n[e],o=s[e];if(e in n)if(e in s){const e=L(a,o,t);i.push(...e)}else i.push({path:t,oldValue:a,newValue:void 0});else i.push({path:t,oldValue:void 0,newValue:o})}}else e!==t&&i.push({path:r||"root",oldValue:e,newValue:t});return i}function R(e){return null==e||"object"!=typeof e}function N(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var H;!function(e){e.CLOSED="CLOSED",e.OPEN="OPEN",e.HALF_OPEN="HALF_OPEN"}(H||(H={}));class G{constructor(e={}){this.state=H.CLOSED,this.failures=[],this.lastFailureTime=0,this.halfOpenCalls=0,this.logger=o.getInstance({minLevel:"warn"}),this.options={failureThreshold:5,recoveryTimeout:6e4,monitoringWindow:3e5,halfOpenMaxCalls:3,storageKey:"circuit_breaker_state",...e},this.storageKey=this.options.storageKey}async initialize(){await this.loadFromStorage()}static async create(e={}){const t=new G(e);return await t.initialize(),t}async loadFromStorage(){try{if("undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local){const e=(await chrome.storage.local.get(this.storageKey))[this.storageKey];e&&(this.state=e.state,this.failures=e.failures||[],this.lastFailureTime=e.lastFailureTime||0,this.halfOpenCalls=e.halfOpenCalls||0,this.cleanupOldFailures())}else if("undefined"!=typeof localStorage){const e=localStorage.getItem(this.storageKey);if(e){const t=JSON.parse(e);this.state=t.state,this.failures=t.failures||[],this.lastFailureTime=t.lastFailureTime||0,this.halfOpenCalls=t.halfOpenCalls||0,this.cleanupOldFailures()}}}catch(e){this.logger.warn("Failed to load circuit breaker state from storage:",e)}}async saveToStorage(){try{const e={state:this.state,failures:this.failures,lastFailureTime:this.lastFailureTime,halfOpenCalls:this.halfOpenCalls};"undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local?await chrome.storage.local.set({[this.storageKey]:e}):"undefined"!=typeof localStorage&&localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){this.logger.warn("Failed to save circuit breaker state to storage:",e)}}cleanupOldFailures(){const e=Date.now();this.failures=this.failures.filter((t=>e-t.timestamp<=this.options.monitoringWindow))}async execute(e,t){if(this.state===H.OPEN){if(!this.shouldAttemptRecovery()){if(t)return t();throw new Error("Circuit breaker is OPEN - service temporarily unavailable")}this.state=H.HALF_OPEN,this.halfOpenCalls=0,await this.saveToStorage()}if(this.state===H.HALF_OPEN){if(this.halfOpenCalls>=this.options.halfOpenMaxCalls)throw new Error("Circuit breaker HALF_OPEN call limit exceeded");this.halfOpenCalls+=1,await this.saveToStorage()}try{const t=await e();return await this.onSuccess(),t}catch(e){throw await this.onFailure(e),e}}async onSuccess(){this.state===H.HALF_OPEN&&(this.state=H.CLOSED,this.failures=[],await this.saveToStorage())}async onFailure(e){const t=Date.now();this.lastFailureTime=t,this.failures.push({timestamp:t,error:e.message}),this.failures=this.failures.filter((e=>t-e.timestamp<=this.options.monitoringWindow)),this.failures.length>=this.options.failureThreshold&&(this.state=H.OPEN),await this.saveToStorage()}shouldAttemptRecovery(){return Date.now()-this.lastFailureTime>=this.options.recoveryTimeout}getState(){return this.state}getFailureCount(){const e=Date.now();return this.failures.filter((t=>e-t.timestamp<=this.options.monitoringWindow)).length}async reset(){this.state=H.CLOSED,this.failures=[],this.lastFailureTime=0,this.halfOpenCalls=0,await this.saveToStorage()}async clearStorage(){"undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local?await chrome.storage.local.remove(this.storageKey):"undefined"!=typeof localStorage&&localStorage.removeItem(this.storageKey)}getStatus(){return{state:this.state,failureCount:this.getFailureCount(),nextAttemptTime:this.state===H.OPEN?this.lastFailureTime+this.options.recoveryTimeout:null}}}const $="https://cdn.givefreely.com/data/behavioral/";class M{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.mergedConfig=null,this.globalConfigRefreshInterval=null,this.partnerConfigRefreshInterval=null,this.eventEmitter=new D,this.isInitialized=!1,this.partnerCircuitBreaker=new G({failureThreshold:3,recoveryTimeout:6e4,monitoringWindow:3e5,storageKey:`gf_partner_circuit_breaker_${e}`}),this.globalCircuitBreaker=new G({failureThreshold:3,recoveryTimeout:6e4,monitoringWindow:3e5,storageKey:"gf_global_circuit_breaker"})}async initialize(){this.isInitialized||(await Promise.all([this.partnerCircuitBreaker.initialize(),this.globalCircuitBreaker.initialize()]),this.isInitialized=!0)}ensureInitialized(){if(!this.isInitialized)throw new Error("GiveFreelyConfigService must be initialized before use. Call initialize() or use create() method.")}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchPartnerConfig(){const e=await g((async()=>{const e=await fetch(`${$}${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions());if(!e)throw new Error("Failed to fetch or get from cache partner config");return this.partnerConfigRefreshInterval=e.configRefreshInterval||this.partnerConfigRefreshInterval,e}async fetchGlobalConfig(){const e=await g((async()=>{const e=await fetch(`${$}global.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config => Status code: ${e.status} .${e.statusText}`);return e.json()}),this.getRetryOptions());if(!e)throw new Error("Failed to fetch or get from cache global config",e);return this.globalConfigRefreshInterval=e.configRefreshInterval||this.globalConfigRefreshInterval,e}async getCachedConfig(){return this.mergedConfig}async getConfig(e=!1){this.ensureInitialized();let t=!1;e&&(t=await F());const[r,i]=await Promise.all([U.get(f,this.fetchPartnerConfig.bind(this),this.partnerConfigRefreshInterval,t,(e=>e?.configRefreshInterval??null)),U.get(p,this.fetchGlobalConfig.bind(this),this.globalConfigRefreshInterval,t,(e=>e?.configRefreshInterval??null))]);if(!i.content)throw new Error("Global config is required");if(!r.content)throw new Error("Partner config is required");this.partnerConfig=r.content,this.globalConfig=i.content;const n=this.mergeConfigs(JSON.parse(JSON.stringify(this.globalConfig)),JSON.parse(JSON.stringify(this.partnerConfig)));if(!n)throw new Error("Was not able to merge configs");return((e,t,r)=>{const i=[...t.merchantExclusions??[],...r.merchantExclusions??[]];e.merchantExclusions=i})(n,this.globalConfig,this.partnerConfig),this.emitConfigChanges(n),n}async clearCache(){this.ensureInitialized(),await Promise.all([U.clear(f),U.clear(p)]),this.partnerConfig=null,this.globalConfig=null,this.mergedConfig=null,this.eventEmitter.clear(),await Promise.all([this.partnerCircuitBreaker.reset(),this.globalCircuitBreaker.reset()])}getCircuitBreakerStatus(){return this.ensureInitialized(),{partner:this.partnerCircuitBreaker.getStatus(),global:this.globalCircuitBreaker.getStatus()}}mergeConfigs(e,t){if(!t)return e;if(!e)return t;const r={...e};return Object.keys(t).forEach((i=>{if(!Object.prototype.hasOwnProperty.call(t,i))return;const n=e[i],s=t[i];void 0!==s&&(Array.isArray(s)?r[i]=[...s]:r[i]=null===s||"object"!=typeof s||null===n||"object"!=typeof n?s:this.mergeConfigs(n,s))})),r}on(e,t){return this.eventEmitter.on(e,t)}once(e,t){return this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.off(e,t)}emitConfigChanges(e){if(!this.mergedConfig)return this.mergedConfig=e,void this.eventEmitter.emit({path:"root",oldValue:null,newValue:e,config:e});const t=L(this.mergedConfig,e);for(const r of t)this.eventEmitter.emit({path:r.path,oldValue:r.oldValue,newValue:r.newValue,config:e});this.mergedConfig=e}}class z{constructor(e,t,r,i=60){this.track=async(e,t,r=!1,i=!1)=>{const n={partner:`gfLib_${this._partnerApiKey}`,eventType:e,eventData:{userId:r?void 0:this._userService?.user?.id,libVersion:I(),...t}};try{const e=JSON.stringify(n,((e,t)=>t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t)),t=await this.getEventsUrl();return t?await this.BroadcastEvent(t,e,n,i):(this._logger.info("Cant broadcast event. eventsUrl cant be retrieved from config",n,!0),!1)}catch(e){return this._logger.error("Something unexpected happened when dispatching a gf event",{error:e,event:n},!0),!1}},this.getEventsHistory=async()=>{const e=await x.get(C),t=(e=>{const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()})(-this._debounceWindowInMinutes),r=(e||[]).filter((e=>e.createdAt>t));return await x.set(C,r),r},this.shouldBroadcastEvent=async(e,t)=>!!t||!(await this.getEventsHistory()).some((t=>t.payload===e)),this.pushEventToHistory=async e=>{const t=await this.getEventsHistory();t.push({createdAt:Date.now(),payload:e}),await x.set(C,t)},this._partnerApiKey=e,this._userService=t,this._debounceWindowInMinutes=i,this._logger=o.getInstance({title:"Analytics"}),this._configService=r}async BroadcastEvent(e,t,r,i){if(await this.shouldBroadcastEvent(t,i)){const i=await fetch(e,{headers:{"Content-Type":"application/json"},method:"POST",body:t,cache:"no-store"});return i.ok?(await this.pushEventToHistory(t),!0):(this._logger.error("Something unexpected happened when dispatching an event",{status:i.status,statusText:i.statusText,event:r},!0),!1)}return this._logger.info("This event has already been broadcasted during the past hour",r,!0),!1}async getEventsUrl(){const e=await this._configService.getCachedConfig();return e?.eventsUrl}}z.trackEvent=async(e,t,r=!1,i=!1)=>{await async function(e){return await h.runtime.sendMessage(e)}({type:d.TRACK_EVENT,payload:{eventType:e,eventData:t,anonymous:r,skipThrottling:i}})};class K{constructor(e,t){this.lastCheck=null,this.trackEvent=e,this.logger=t}async initialize(){const e=await x.get(m);e&&(this.lastCheck=e)}getToday(){return(new Date).toISOString().split("T")[0]}async check(){try{const e=this.lastCheck??0,t=this.getToday();(e?new Date(e).toISOString().split("T")[0]:null)!==t&&(this.lastCheck=Date.now(),await x.set(m,this.lastCheck),await this.trackEvent(r.checkoutPopupHealthCheck,{language:browser.i18n.getUILanguage()}))}catch(e){this.logger.error("Health check failed",{error:e instanceof Error?e.message:"Unknown error"},!0)}}}var j;!function(e){e[e.Pending=0]="Pending",e[e.Ready=1]="Ready",e[e.Received=2]="Received",e[e.Donated=3]="Donated",e[e.Disqualified=4]="Disqualified"}(j||(j={}));class B{constructor(e,t,r){this.libraryId=e,this.config=t,this.logger=r}async getAnonymousUserCommissions(e,t){try{const r=new URLSearchParams(t).toString(),i=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.getAnonymousUserComissionsPath}?${r}`,{method:"GET",headers:{"Content-Type":"application/json","X-AnonymousUserToken":e}});if(!i.ok)throw new Error(`Failed to fetch commissions. Status code: ${i.status} .${i.statusText}`);return await i.json()}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error fetching anonymous user's commissions:",{error:e}),e}}async createOrUpdateAnonymousUser(e,t){try{const r=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.createAnonymousUserPath}?gfLibId=${this.libraryId}`,{method:"PUT",headers:{"Content-Type":"application/json","X-GF-Platform":"GFLibrary","X-AnonymousUserToken":t??""},body:JSON.stringify(e)});if(!r.ok)throw this.logger.error(`Failed to create/update anonymous user. Status code: ${r.status}. ${r.statusText}`),new Error(`Failed to create/update anonymous user. Status code: ${r.status}. ${r.statusText}`);this.logger.info("[GiveFreelyApiClient] anonymous user created/updated successfully.");const i=await r.json(),n=r.headers.get("X-AnonymousUserToken");return{resultUser:{...i,charity:{ein:i.selectedCharity,thirdPartyId:i.selectedCharityThirdPartyIdentifier,name:void 0}},resultToken:n}}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error creating anonymous user:",{error:e},!0),e}}}class V{constructor(e,t){this._giveFreelyApiClient=e,this._logger=t,this.user=null}async resetUser(){await x.remove(v),await x.remove(w)}async upsertUser(e){let t=await this.fetchUser();try{const r={selectedCharity:e?.ein,selectedCharityThirdPartyIdentifier:e?.thirdPartyId};if(!await this.shouldCreateOrUpdateUser(t,r))return t;const i=await x.get(v),{resultUser:n,resultToken:s}=await this._giveFreelyApiClient.createOrUpdateAnonymousUser(r,i);s&&await x.set(v,s),n&&(await x.set(w,n),t=n)}catch(e){this._logger.error("Error creating/updating anonymous user:",e)}return this.user=t,t}async fetchUser(){const e=await x.get(w);return this.user=e,e}async shouldCreateOrUpdateUser(e,t){return!e||e.charity?.ein!==t.selectedCharity||e.charity?.thirdPartyId!==t.selectedCharityThirdPartyIdentifier}}const W=e=>{try{return new URL(e),!0}catch{return!1}};async function q(e,t,r){try{const i=(await J())?.[t],n=await this.getStanddownPolicy(),s=ee(n,new URL(r).search);if(i&&i>Date.now())return e.info("Standing down because current affiliate stand down session has not expired"),X(t,void 0,!s&&null),{result:!0,reason:"sessionNotExpired"};if(ee(n,new URL(r).search))return e.info("Standing down because url has affiliate params"),X(t,void 0,!1),{result:!0,reason:"hasAffiliateParams"};e.info("No need to stand down.")}catch(t){e.error("Exception produced when trying to determine if it should stand down",t)}return{result:!1}}function Y(e,t){if(!this.standDownPolicy)return this.logger.warn("Could not check affiliation. No stand down policy found"),this.getStanddownPolicy().then((e=>{this.standDownPolicy=e})),!1;const r=e.some((e=>Q(this.standDownPolicy,e)))||ee(this.standDownPolicy,t);return this.logger.info("Affiliation result:",r),r}const J=async()=>x.get(P),X=async(e,t=1,r=null)=>{const i=await J()??{},n=i?.[e]??0,s=Date.now()+60*t*60*1e3;if(i[e]=s,await x.set(P,i),null!==r){const t=await Z(e);if(r||!r&&t&&s-n>2e4){const t=await x.get(T)??{};t[e]=r,await x.set(T,t)}}},Z=async e=>{const t=await x.get(T);return t?.[e]??!1},Q=(e,t)=>{if(!t)return!1;const{Domains:r}=e;return r.some((e=>t.includes(e)))},ee=(e,t)=>{if(!t)return!1;const{Params:r}=e;return r.some((e=>t.toLowerCase().includes(`?${e.toLowerCase()}`)))||r.some((e=>t.toLowerCase().includes(`&${e.toLowerCase()}`)))},te=new Set,re=new Set,ie={urls:["<all_urls>"],types:["main_frame"]};class ne extends Error{constructor(e="Service not initialized"){super(e),this.name="UninitializedServiceError"}}const se=e=>{if(!e)throw new ne};class ae{static register(e,t){this.strategies.set(e,t)}static get(e){return this.strategies.get(e)}static exists(e){return!!function(e){return"object"==typeof e&&null!==e&&"type"in e&&"payload"in e&&"string"==typeof e.type}(e)&&this.knownMessageTypes.has(e.type)}}ae.strategies=new Map,ae.knownMessageTypes=new Set([...Object.values(d)]);const oe=e=>{let t;if(browser.webRequest){const i=(e=>{const t=e.getLogger();return({requestId:r,url:i,initiator:n})=>{try{if(te.has(r)||re.has(r)||!W(i))return;const{hostname:s,search:a}=new URL(i);let o;n&&W(n)&&(o=new URL(n).hostname),(e.hasAffiliation([s,o],a)||e.isCustomStandownMatch([i,n]))&&(t.info("Affiliation found or custom standown match on url, adding request id to track"),te.add(r))}catch(e){t.error("Error on handleAffiliateOnBeforeRequest",e)}}})(e);browser.webRequest.onBeforeRequest.addListener(i,ie);const n=(e=>{const t=e.getLogger();return async({requestId:i,redirectUrl:n})=>{try{if(!te.has(i))return;t.info("Attempting to find active domain");const{hostname:s}=new URL(n),a=(await e.getActiveDomains()).find((e=>s===e.domain||s.endsWith(`.${e.domain}`)));if(!a)return;t.info("Found active domain. Updating standdown state"),await X(a.domain,void 0,!1),(await e.getCachedConfig()).enhancedLogging&&e.trackEvent(r.checkoutPopupStoodDown,{domain:a.domain,reason:"vendorPolicy (at webReq listener)"})}catch(e){t.error("Error on handleAffiliateOnBeforeRedirect",e)}}})(e);browser.webRequest.onBeforeRedirect.addListener(n,ie);const s=(e=>{const t=e.getLogger();return({requestId:e})=>{try{te.has(e)&&(t.info("Tracking request completed. Request Id:",e),te.delete(e))}catch(e){t.error("Error on handleAffiliateOnCompleted",e)}}})(e);browser.webRequest.onCompleted.addListener(s,ie),t=()=>{browser.webRequest.onBeforeRequest.removeListener(i),browser.webRequest.onBeforeRedirect.removeListener(n),browser.webRequest.onCompleted.removeListener(s)}}const i=function(){const t=o.getInstance(),r=(r,i,n)=>{function s(e){n(e)}const a=(async t=>(e.getLogger().debug("Received message",{type:t.type,payload:t.payload}),ce(e,t)))(r,0);return a instanceof Promise?(a.then((e=>{e&&s(e)})).catch((e=>{t.warn("Async message callback error:",e)})),!0):!0===a||void 0};return h.runtime.onMessage.addListener(r),r}();return function(){t&&t(),browser.runtime.onMessage.removeListener(i)}},ce=async(e,t)=>{se(e.isInitialized());const r=ae.get(t.type);if(!r)return;const i={giveFreelyService:e};return r.handle(t,i)};class le{async handle(e,t){const{activeDomain:i,originalUrl:n,selectedCharity:s,gfCommissionUniqueId:a,openTab:o}=e.payload,{giveFreelyService:c}=t,l=c.getLogger();l.debug("Activating offer",{activeDomain:i,selectedCharity:s});try{if(i?.merchantId&&(async e=>{try{const t=await(async()=>await x.get(E)??{})();t[e]&&delete t[e],await x.set(E,t)}catch{}})(parseInt(i.merchantId)),!s?.ein||!s?.thirdPartyId)throw new Error("Missing charity information");const e=await c.upsertUser(s);l.debug("Upserted user",{currentUser:e}),e||l.info("Failed to create user. Using default bucket's user");const t=await c.getProviderPreActivation(i.provider),r=await c.generateAffiliateUrl(i,n,e,a,t);return l.debug("Generated affiliate URL",{affiliateUrl:r}),!1!==o?((async e=>{const t=h.tabs.getCurrent(),r=await t,i=await h.tabs.create({url:e,openerTabId:r?.id,active:!1,pinned:!0});await(async e=>new Promise((t=>{h.tabs.onUpdated.addListener((async function r(i,n){if(i===e&&"complete"===n.status){if(h.tabs.onUpdated.removeListener(r),!(await h.tabs.get(e)).url)return void t(!1);t(!0)}}))})))(i.id)&&setTimeout((()=>{i?.id&&h.tabs.remove(i.id)}),3e4)})(r),await c.updateStanddownHistory(i.domain,!0)):await c.updateStanddownHistoryByMerchantId(i.merchantId,!0),l.debug("Activated offer",{activeDomain:i,selectedCharity:s,gfCommissionUniqueId:a}),{type:d.ACTIVATE_OFFER,payload:{response:!0,activationLink:r}}}catch(e){return l.error("Error activating offer",{activeDomain:i,error:e}),c.trackEvent(r.checkoutPopupFailedActivation,{activeDomain:i,error:e}),{type:d.ACTIVATE_OFFER,payload:{response:!1}}}}}class ge{async handle(e,t){const{urls:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=await i.getActiveDomains();if(!e||0===e.length)throw new Error("No active domains");const t={},n=r.map((async r=>{try{const{hostname:n}=new URL(r),s=e.find((e=>n===e.domain||n.endsWith(`.${e.domain}`)));if(s){const{result:e}=await i.shouldStandDown(s.domain,r);t[r]={activeDomain:s,shouldStandDown:e,currentlyActivated:await i.wasLastStandDownAnActivation(s.domain)}}}catch{}}));return await Promise.all(n),{type:d.GET_ACTIVE_DOMAINS,payload:{result:t}}}catch(e){return n.error("Error checking domain",{urls:r,error:e}),{type:d.GET_ACTIVE_DOMAINS,payload:{result:{}}}}}}class he{async handle(e,t){const{shopId:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=u,t=await x.get(e)||[];if(t.length>0&&"Merchant"in t[0].domain)return n.warn("Detected legacy WildfireActiveDomain in Shopify storage — data should have been pruned. Clearing stale entries."),await x.remove(e),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}};const i=t.find((e=>e.shopId===r));return i?(n.debug("Found domain for shop ID",{shopId:r,domain:i.domain}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!0,domain:i.domain,shopInfo:i}}):(n.debug("No domain found for shop ID",{shopId:r}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}})}catch(e){return n.error("Error getting domain for shop ID",{shopId:r,error:e}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}}}}}class de{async handle(e,t){const{lang:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();n.debug("Getting language strings",{lang:r});try{const e=await i.getLanguage(r);return n.debug("Language strings fetched",{language:e}),{type:d.GET_LANGUAGE_CONTENT,payload:{translations:e.translations,charities:e.charities}}}catch(e){return n.error("Error getting language strings",{error:e}),{type:d.GET_LANGUAGE_CONTENT,payload:{translations:null,charities:null}}}}}class ue{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger(),n=await r.getCachedConfig();try{return i.debug("Fetching popup config"),{type:d.GET_POPUP_CONFIG,payload:{config:n}}}catch(e){return i.error("Error fetching popup config",{error:e}),{type:d.GET_POPUP_CONFIG,payload:{config:null}}}}}class me{async handle(e,t){const{days:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=new Date;return e.setDate(e.getDate()+r),await x.set("popup_hide",{popupHide:e.getTime()}),n.debug("Popup hidden",{days:r,expiry:e}),{type:d.HIDE_POPUP,payload:{ack:!0}}}catch(e){return n.error("Error hiding popup",{days:r,error:e}),{type:d.HIDE_POPUP,payload:{ack:!1}}}}}class fe{async handle(e,t){const{hostname:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const{merchantExclusions:e}=await i.getConfig();if(n.debug("Checking hostname",{hostname:r}),i.healthCheck(),e.some((e=>e.disableDomain&&(r===e.domain||r.endsWith(`.${e.domain}`)))))return n.debug("Hostname is in merchant exclusions",{hostname:r}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!1,domain:void 0}};const t=await i.getActiveDomains();n.debug("Retrieved active domains",{count:t.length});const s=t.find((e=>r===e.domain||r.endsWith(`.${e.domain}`)));return n.debug("Domain check result",{hostname:r,isActive:!!s}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!!s,domain:s}}}catch(e){return n.error("Error checking domain",{hostname:r,error:e}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!1,domain:void 0}}}}}class pe{async handle(e,t){const{currentUrl:i,searchResults:n,source:s}=e.payload,{giveFreelyService:a}=t,o=a.getLogger();try{const e=await a.getActiveDomains();o.debug("Finding merchants in search results",{currentUrl:i});const c=n.filter((t=>{try{const{hostname:r}=new URL(t.url);return e.some((e=>e.domain===r||r.endsWith(`.${e.domain}`)))}catch{return o.debug("Couldn't parse the following search result url",{x:t}),!1}}));if(o.info("Number of merchants identified in the search result",{number:c.length}),c.length>0){const e=Math.floor(Math.random()*Date.now());for(const n of c)t.giveFreelyService.trackEvent(r.checkoutPopupMerchantInResultsFound,{source:s,searchResultsId:e,currentUrl:i,searchResultUrl:n.url,sponsored:n.isSponsored},!0)}return{type:d.LOG_MERCHANTS_IN_SEARCH_RESULTS,payload:{result:!0}}}catch(e){return o.error("Error sending logs for merchants in search results",{currentUrl:i,error:e}),{type:d.LOG_MERCHANTS_IN_SEARCH_RESULTS,payload:{result:!1}}}}}class Ae{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger();try{return await x.set("gf_partner_serp_muted",!0),i.debug("Partner Serp box hidden"),{type:d.MUTE_PARTNER_SERP_BOX,payload:{ack:!0}}}catch(e){return i.error("Error hiding partner serp box",{error:e}),{type:d.MUTE_PARTNER_SERP_BOX,payload:{ack:!1}}}}}class ye{async handle(e,t){const r=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=u;let t=await x.get(e)||[];t.length>0&&"Merchant"in t[0].domain&&(n.warn("Detected legacy WildfireActiveDomain in Shopify storage — data should have been pruned. Clearing stale entries."),t=[],await x.remove(e));const i=t.findIndex((e=>e.shopId===r.shopId));return i>=0?t[i]=r:t.push(r),await x.set(e,t),n.debug("Stored Shopify shop ID",{shopInfo:r}),{type:d.STORE_SHOPIFY_SHOP_ID,payload:{success:!0}}}catch(e){return n.error("Error storing Shopify shop ID",{shopInfo:r,error:e}),{type:d.STORE_SHOPIFY_SHOP_ID,payload:{success:!1}}}}}class we{async handle(e,t){const{activeDomain:r,url:i}=e.payload,{giveFreelyService:n}=t,s=n.getLogger();s.debug("Checking if we should stand down",{activeDomain:r});try{const e=await n.shouldStandDown(r,i);return{type:d.SHOULD_STAND_DOWN,payload:e}}catch(e){return s.error("Error checking if we should stand down. Returning false",{activeDomain:r,error:e}),{type:d.SHOULD_STAND_DOWN,payload:{result:!1}}}}}class ve{async handle(e,t){const{eventType:r,eventData:i,anonymous:n,skipThrottling:s}=e.payload,{giveFreelyService:a}=t,o=a.getLogger();o.debug("Broadcasting event",{eventType:r,eventData:i,anonymous:n,skipThrottling:s});try{const e=await a.trackEvent(r,i,n,s);return{type:d.TRACK_EVENT,payload:{result:e}}}catch(e){return o.error("Error broadcasting event. Returning false",{eventType:r,eventData:i,error:e}),{type:d.TRACK_EVENT,payload:{result:!1}}}}}const Ce=o.getInstance(),Ee=async()=>await x.get(A)||(async()=>{Ce.debug("detecting country");const e={method:"GET",headers:{"Content-Type":"application/json",Authorization:"Basic OTEzOTkxOnFlYmpaWF9DOGNRY0lxSHA4WTVjNGxzU1pRSlM2VW9MMExzTF9tbWs="}};try{const t=await fetch("https://geoip.maxmind.com/geoip/v2.1/country/me",e);if(Ce.debug("Received geolocation response",{status:t.status}),!t.ok)return void Ce.error("Failed to get geolocation data",{status:t.status,statusText:t.statusText});const r=await t.json();if(!r)throw new Error("There was an error fetching geoip look up");return await x.set(A,r.country.iso_code),r.country.iso_code}catch(e){return void Ce.error("Failed to get geolocation data",{error:e},!0)}})(),Se="https://cdn.givefreely.com/data/language",be=async(e,t,r,i,n=[],s=!1)=>{const a=(n??[]).includes(r)?_:r;e.debug(`Requested lang ${r} and current lang ${a}`);const o=`lang-${_}`,c=await U.get(o,(async()=>(e.debug(`Fetching default language ${_} for partner ${t}`),Pe(t,_))),i||600,s);if(!c.content)throw new Error(`Failed to fetch default language ${_} and no cache version available`);if(_===a)return c.content;const l=`lang-${a}`,g=await U.get(l,(async()=>(e.debug(`Fetching language ${a} for partner ${t}`),Pe(t,a))),i||600,s);if(!g.content)return c.content;const h=Oe(c.content,g.content);return await U.set(l,h,i||600),h},Pe=async(e,t)=>{const r=`/global-${t}.json`,i=`/${e}/${t}.json`,[n,s]=await Promise.allSettled([Te(`${Se}${r}`),Te(`${Se}${i}`)]);let a,o;"fulfilled"===n.status&&(a=n.value),"fulfilled"===s.status&&(o=s.value);const c=_e(a,o);return{translations:c.translations,charities:c.charities}},Te=async e=>{const t=await fetch(e,{cache:"no-store"});if(!t.ok)throw new Error(`Failed to fetch partner language file ${e}. Status: ${t.status}. Reason: ${t.statusText}`);return t.json()},_e=(e,t)=>({translations:{...e?.translations??{},...t??{}},charities:{...e?.charities??{}}}),Oe=(e,t)=>({translations:{...e.translations,...t.translations},charities:{...e.charities,...t.charities}});class xe{constructor(e,t,r,i){this._logger=e,this.feedUrl=t,this.activationUrl=r,this.preActivationUrl=i}async getRawFeed(){try{const e=`${this.feedUrl}`,t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch feed from ${e}. Status ${t.status}. ${t.statusText}`);return t.json()}catch(e){throw this._logger.error("Failed to fetch the feed",{err:e}),new Error("Failed to fetch the feed")}}async preActivation(e,t){try{const r=await fetch(this.preActivationUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({partnerId:e,...t&&{provider:t}})});if(!r.ok)throw new Error(`Failed to pre-activate. Status ${r.status}. ${r.statusText}`);return r.json()}catch(e){throw this._logger.error("Failed to pre-activate",{err:e}),new Error("Failed to pre-activate")}}async generateAffiliateUrl(e,t,r,i,n,s){try{const a=await fetch(`${this.activationUrl}?redirect=false`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e.provider,partnerId:i,userId:r?.id||"",ein:r?.charity?.ein||"",tpi:r?.charity?.thirdPartyId||"",url:t,gfCommissionUniqueId:n,merchantId:e.merchantId,domainId:e.id,providerCustom:s})});if(!a.ok)throw new Error(`Failed to generate affiliate url. Status ${a.status}. ${a.statusText}`);return(await a.json()).affiliateLink}catch(e){throw this._logger.error("Failed to generate affiliate url",{err:e}),new Error("Failed to generate affiliate url")}}}class Ie{constructor(e){this.raw=e}static mapKind(e){return 1===e?"FLAT":"PERCENTAGE"}static mapOfferRate(e){return{Kind:Ie.mapKind(e.k),Amount:e.a,Name:e.n,Currency:e.c??void 0}}static fromRawArray(e){return e.map((e=>new Ie(e)))}static fromRaw(e){return new Ie(e)}get id(){return parseInt(this.raw.di,10)||0}get domain(){return this.raw.d}get provider(){return this.raw.p}get merchantId(){return this.raw.mi}get merchantName(){return this.raw.mn}get commission(){return{amount:this.raw.c.a,kind:Ie.mapKind(this.raw.c.k)}}get rates(){return this.raw.r?.map(Ie.mapOfferRate)??[]}toRaw(){return this.raw}toJSON(){return{id:this.id,domain:this.domain,provider:this.provider,merchantId:this.merchantId,merchantName:this.merchantName,commission:this.commission,rates:this.rates}}}class Fe{constructor(e,t,r=600){this.standDownPolicy=null,this.shouldStandDown=q.bind(this),this.hasAffiliation=Y.bind(this),this.updateStanddownHistory=X,this.refreshInterval=r,this.giveFreelyFeedClient=e,this.logger=t}async getActiveDomains(e=!1){try{const t=await U.get("gfFeed",(async()=>this.fetchRawActiveDomains()),this.refreshInterval,e);if(!t.content)throw new Error("Failed to retrieve feed from cache");return Ie.fromRawArray(t.content)}catch(e){return this.logger.error("Failed to get active domains:",e),[]}}async preActivation(e,t){return this.giveFreelyFeedClient.preActivation(e,t)}async generateAffiliateUrl(e,t,r,i,n,s){return this.giveFreelyFeedClient.generateAffiliateUrl(e,t,r,i,n,s)}async fetchRawActiveDomains(){const e=await this.giveFreelyFeedClient.getRawFeed();return this.standDownPolicy=e.standdownRules,e.activeDomains}async getStanddownPolicy(){if(this.standDownPolicy)return this.standDownPolicy;const e=await this.giveFreelyFeedClient.getRawFeed();return this.standDownPolicy=e.standdownRules,this.standDownPolicy}static async createGiveFreelyFeedService(e,t){e.debug("Initializing givefreely feed service with config",t);const{feedUrl:r,activationUrl:i,preActivationUrl:n}=t.multiAffiliate??{};if(!r||!i||!n)throw new Error("multiAffiliate config is missing required URLs (feedUrl, activationUrl, preActivationUrl)");const s=new xe(e,r,i,n),a=new Fe(s,e,t.multiAffiliate?.feedRefreshInterval);return await a.getActiveDomains(),a}}async function ke(e){const t=[...Object.values(S),u];try{await Promise.all(t.map((e=>x.remove(e)))),e.info("Pruned legacy Wildfire storage keys",{keys:t})}catch(t){e.debug("Failed to prune legacy Wildfire storage keys",t)}}var Ue=Object.freeze({__proto__:null,generateAffiliateUrl:async function(e,t,r,i,n){return se(this.state.initialized),this.state.giveFreelyFeedService.generateAffiliateUrl(e,t,r,this.state.partnerApiKey,i,n)},getActiveDomains:async function(){return se(this.state.initialized),this.state.giveFreelyFeedService.getActiveDomains()},pruneLegacyWildfireStorage:ke});async function De(e,t,r){try{const i={...t};for(const e of r)delete i[e];return await x.set(b,i),e.info("Pruned preActivation providers",{providers:r}),i}catch(r){return e.debug("Failed to prune preActivation providers",r),t}}var Le=Object.freeze({__proto__:null,getCurrentUser:function(){return se(this.state.initialized),this.state.giveFreelyUserService.user},getLanguage:async function(e){return se(this.state.initialized),be(this.logger,this.state.partnerApiKey,e,this.state.config?.configRefreshInterval,this.state.config?.ignoredLanguages)},getProviderPreActivation:async function(e){if(se(this.state.initialized),this.state.preActivation&&e in this.state.preActivation)return this.state.preActivation[e];const t=await x.get(b);if(t&&e in t)return this.state.preActivation=t,t[e];const r=(await this.state.giveFreelyFeedService.preActivation(this.state.partnerApiKey,e))[e]??{},i={...t||{},...this.state.preActivation||{},[e]:r};return this.state.preActivation=i,await x.set(b,i),r},initializePreActivation:async function(e){const t=await x.get(b);if(t&&Object.keys(t).length>0)return this.state.preActivation=t,t;const r=await e.preActivation(this.state.partnerApiKey);return this.state.preActivation=r,await x.set(b,r),r},prunePreActivationProviders:De,upsertUser:function(e){return se(this.state.initialized),this.state.giveFreelyUserService.upsertUser(e)}});async function Re(e=async()=>(this.logger.debug("Using default partnerFilter."),!0)){if(!this.state.initialized){this.logger.info("Starting initialization with mutex protection");try{await this.dependencies.configService.initialize();const t=await F(!1),r=await this.dependencies.configService.getConfig(!0);this.logger.configure({enabled:r.loggingEnabled??!0,minLevel:r.backgroundMinLogLevel??"error"}),this.logger.info("Initializing GiveFreelyService",{partnerApiKey:this.partnerApiKey}),!r.multiAffiliate?.skipWildfirePruning&&t&&await ke(this.logger);const i=await Fe.createGiveFreelyFeedService(this.logger,r);this.state.healthCheck=new K(this.trackEvent.bind(this),this.logger),await this.state.healthCheck.initialize();const n=new B(this.partnerApiKey,r,this.logger);this.state.giveFreelyUserService=new V(n,this.logger),await this.state.giveFreelyUserService.fetchUser(),this.state.giveFreelyUserService.user?.id||await this.state.giveFreelyUserService.upsertUser(),this.state.analytics=new z(this.partnerApiKey,this.state.giveFreelyUserService,this.dependencies.configService);try{if(r.multiAffiliate?.prunePreActivationProviders?.length){const e=await x.get(b);e&&await De(this.logger,e,r.multiAffiliate.prunePreActivationProviders)}await this.initializePreActivation(i)}catch(e){this.logger.debug("Pre-activation initialization failed — will retry on first offer activation",e)}ae.register(d.IS_ACTIVE_DOMAIN,new fe),ae.register(d.GET_POPUP_CONFIG,new ue),ae.register(d.HIDE_POPUP,new me),ae.register(d.SHOULD_STAND_DOWN,new we),ae.register(d.TRACK_EVENT,new ve),ae.register(d.ACTIVATE_OFFER,new le),ae.register(d.STORE_SHOPIFY_SHOP_ID,new ye),ae.register(d.GET_DOMAIN_BY_SHOP_ID,new he),ae.register(d.GET_LANGUAGE_CONTENT,new de),ae.register(d.LOG_MERCHANTS_IN_SEARCH_RESULTS,new pe),ae.register(d.GET_ACTIVE_DOMAINS,new ge),ae.register(d.MUTE_PARTNER_SERP_BOX,new Ae),await(async e=>{try{await Ee()}catch(t){e.debug("Failed to get geolocation data",{error:t})}})(this.logger),await(async(e,t,r)=>{t.purgeLanguages&&t.purgeLanguages.length>0&&await Promise.all(t.purgeLanguages.flatMap((e=>[U.clear(`lang-${e}`),U.clear(`global-${e}`)]))),g((async()=>{e.debug("Initializing default language with partner API key",{partnerApiKey:r}),await be(e,r,_,t.configRefreshInterval)}))})(this.logger,r,this.partnerApiKey),this.state=((e,t)=>{const{partnerFilter:r,config:i,giveFreelyFeedService:n}=t;return{...e,initialized:!0,partnerFilter:r,config:i,giveFreelyFeedService:n}})(this.state,{partnerFilter:e,config:r,giveFreelyFeedService:i}),this.logger.addTransport(new s(this)),this.cleanupListeners=oe(this),this.logger.info("GiveFreelyService initialized successfully")}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw this.logger.error("Failed to initialize GiveFreelyService",{error:t}),new Error(`Failed to initialize GiveFreelyService: ${t}`)}}}function Ne(){return this.state.initialized}var He={config:Object.freeze({__proto__:null,getCachedConfig:async function(){return se(this.state.initialized),this.state.config=await this.dependencies.configService.getConfig(),this.logger.configure({minLevel:this.state.config.backgroundMinLogLevel??"error"}),this.state.config},getConfig:function(){return se(this.state.initialized),this.state.config},offConfigChange:function(e,t){se(this.state.initialized),this.dependencies.configService.off(e,t)},onConfigChange:function(e,t){return se(this.state.initialized),this.dependencies.configService.on(e,t)},onceConfigChange:function(e,t){return se(this.state.initialized),this.dependencies.configService.once(e,t)}}),merchants:Ue,observability:Object.freeze({__proto__:null,getLogger:function(){return se(this.state.initialized),this.logger},healthCheck:async function(){se(this.state.initialized),await this.state.healthCheck.check()},trackEvent:function(e,t,r=!1,i=!1){return se(this.state.initialized),this.state.analytics.track(e,t,r,i)}}),standdown:Object.freeze({__proto__:null,hasAffiliation:function(e,t){if(!this.state.giveFreelyFeedService)return this.logger.warn("GiveFreely Feed service not initialized yet"),!1;const r=this.state.giveFreelyFeedService.hasAffiliation(e,t);return r&&this.logger.info("Affiliation identified"),r},isCustomStandownMatch:function(e){const t=e.some((e=>this.getConfig().customStandownPolicy?.urlRegex?.some((t=>!!e&&function(e,t){return new RegExp(t).test(e)}(e,t)))));return t&&this.logger.info("Custom Standown identified"),t},shouldStandDown:async function(e,t){se(this.state.initialized);const r=new URL(t);if(!await this.state.partnerFilter(r.hostname))return this.logger.info("Should standdown due to partner filter."),{result:!0,reason:"partner filter"};if(this.getConfig().merchantExclusions.some((t=>t.mutePopups&&e===t.domain)))return this.logger.info("Should standdown due to merchant exclusions"),{result:!0,reason:"merchant exclusions"};const i=await this.state.giveFreelyFeedService.shouldStandDown(this.logger,e,t);return i.result&&this.logger.info(`Should standdown due to ${i.reason}`),i},updateStanddownHistory:function(e,t=null){return se(this.state.initialized),X(e,void 0,t)},updateStanddownHistoryByMerchantId:function(e,t=null){return se(this.state.initialized),this.state.giveFreelyFeedService.getActiveDomains().then((r=>{const i=r.find((t=>t.merchantId===e));if(i)return X(i.domain,void 0,t)}))},wasLastStandDownAnActivation:async function(e){return Z(e)}}),identity:Le};class Ge{constructor(e){this.partnerApiKey=e,this.cleanupListeners=null,this.initialize=Re.bind(this),this.isInitialized=Ne.bind(this),this.getConfig=He.config.getConfig.bind(this),this.getCachedConfig=He.config.getCachedConfig.bind(this),this.onConfigChange=He.config.onConfigChange.bind(this),this.onceConfigChange=He.config.onceConfigChange.bind(this),this.offConfigChange=He.config.offConfigChange.bind(this),this.getLogger=He.observability.getLogger.bind(this),this.healthCheck=He.observability.healthCheck.bind(this),this.trackEvent=He.observability.trackEvent.bind(this),this.getProviderPreActivation=He.identity.getProviderPreActivation.bind(this),this.initializePreActivation=He.identity.initializePreActivation.bind(this),this.upsertUser=He.identity.upsertUser.bind(this),this.getCurrentUser=He.identity.getCurrentUser.bind(this),this.getLanguage=He.identity.getLanguage.bind(this),this.getActiveDomains=He.merchants.getActiveDomains.bind(this),this.generateAffiliateUrl=He.merchants.generateAffiliateUrl.bind(this),this.shouldStandDown=He.standdown.shouldStandDown.bind(this),this.updateStanddownHistory=He.standdown.updateStanddownHistory.bind(this),this.updateStanddownHistoryByMerchantId=He.standdown.updateStanddownHistoryByMerchantId.bind(this),this.wasLastStandDownAnActivation=He.standdown.wasLastStandDownAnActivation.bind(this),this.hasAffiliation=He.standdown.hasAffiliation.bind(this),this.isCustomStandownMatch=He.standdown.isCustomStandownMatch.bind(this),this.dependencies={configService:new M(e)},this.logger=o.getInstance(),this.logger.configure({enabled:!0,title:"Background - GiveFreelyService"}),this.state=(e=>({initialized:!1,giveFreelyFeedService:null,partnerFilter:null,config:null,preActivation:null,analytics:null,giveFreelyUserService:null,partnerApiKey:e,healthCheck:null}))(e)}async destroy(){var e;this.logger.info("Destroying GiveFreelyService"),await Promise.all([this.dependencies.configService.clearCache(),this.state.giveFreelyUserService?.resetUser()]),this.cleanupListeners&&(this.cleanupListeners(),this.logger.info("Event listeners cleared."),this.cleanupListeners=null),this.state=(e=this.state,{...e,initialized:!1,giveFreelyFeedService:null,partnerFilter:null,analytics:null,config:null})}}exports.GiveFreelyService=class{constructor(e){this.partnerApiKey=e,this.initialize=e=>this._coreService.initialize(e),this.destroy=()=>this._coreService.destroy(),this._coreService=new Ge(e)}},exports.browser=browser,exports.isGiveFreelyMessage=e=>ae.exists(e);
1
+ "use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var t={exports:{}};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){if(!(globalThis.chrome&&globalThis.chrome.runtime&&globalThis.chrome.runtime.id))throw new Error("This script should only be loaded in a browser extension.");if(globalThis.browser&&globalThis.browser.runtime&&globalThis.browser.runtime.id)e.exports=globalThis.browser;else{const t="The message port closed before a response was received.",r=e=>{const r={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(0===Object.keys(r).length)throw new Error("api-metadata.json has not been included in browser-polyfill");class i extends WeakMap{constructor(e,t=void 0){super(t),this.createItem=e}get(e){return this.has(e)||this.set(e,this.createItem(e)),super.get(e)}}const n=(t,r)=>(...i)=>{e.runtime.lastError?t.reject(new Error(e.runtime.lastError.message)):r.singleCallbackArg||i.length<=1&&!1!==r.singleCallbackArg?t.resolve(i[0]):t.resolve(i)},s=e=>1==e?"argument":"arguments",a=(e,t,r)=>new Proxy(t,{apply:(t,i,n)=>r.call(i,e,...n)});let o=Function.call.bind(Object.prototype.hasOwnProperty);const c=(e,t={},r={})=>{let i=Object.create(null),l={has:(t,r)=>r in e||r in i,get(l,g,h){if(g in i)return i[g];if(!(g in e))return;let d=e[g];if("function"==typeof d)if("function"==typeof t[g])d=a(e,e[g],t[g]);else if(o(r,g)){let t=((e,t)=>function(r,...i){if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${s(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${s(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((s,a)=>{if(t.fallbackToNoCallback)try{r[e](...i,n({resolve:s,reject:a},t))}catch(n){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,n),r[e](...i),t.fallbackToNoCallback=!1,t.noCallback=!0,s()}else t.noCallback?(r[e](...i),s()):r[e](...i,n({resolve:s,reject:a},t))}))})(g,r[g]);d=a(e,e[g],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(o(t,g)||o(r,g)))d=c(d,t[g],r[g]);else{if(!o(r,"*"))return Object.defineProperty(i,g,{configurable:!0,enumerable:!0,get:()=>e[g],set(t){e[g]=t}}),d;d=c(d,t[g],r["*"])}return i[g]=d,d},set:(t,r,n,s)=>(r in i?i[r]=n:e[r]=n,!0),defineProperty:(e,t,r)=>Reflect.defineProperty(i,t,r),deleteProperty:(e,t)=>Reflect.deleteProperty(i,t)},g=Object.create(e);return new Proxy(g,l)},l=e=>({addListener(t,r,...i){t.addListener(e.get(r),...i)},hasListener:(t,r)=>t.hasListener(e.get(r)),removeListener(t,r){t.removeListener(e.get(r))}}),g=new i((e=>"function"!=typeof e?e:function(t){const r=c(t,{},{getContent:{minArgs:0,maxArgs:0}});e(r)})),h=new i((e=>"function"!=typeof e?e:function(t,r,i){let n,s,a=!1,o=new Promise((e=>{n=function(t){a=!0,e(t)}}));try{s=e(t,r,n)}catch(e){s=Promise.reject(e)}const c=!0!==s&&((l=s)&&"object"==typeof l&&"function"==typeof l.then);var l;if(!0!==s&&!c&&!a)return!1;return(c?s:o).then((e=>{i(e)}),(e=>{let t;t=e&&(e instanceof Error||"string"==typeof e.message)?e.message:"An unexpected error occurred",i({__mozWebExtensionPolyfillReject__:!0,message:t})})).catch((e=>{console.error("Failed to send onMessage rejected reply",e)})),!0})),d=({reject:r,resolve:i},n)=>{e.runtime.lastError?e.runtime.lastError.message===t?i():r(new Error(e.runtime.lastError.message)):n&&n.__mozWebExtensionPolyfillReject__?r(new Error(n.message)):i(n)},u=(e,t,r,...i)=>{if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${s(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${s(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((e,t)=>{const n=d.bind(null,{resolve:e,reject:t});i.push(n),r.sendMessage(...i)}))},m={devtools:{network:{onRequestFinished:l(g)}},runtime:{onMessage:l(h),onMessageExternal:l(h),sendMessage:u.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:u.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},f={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return r.privacy={network:{"*":f},services:{"*":f},websites:{"*":f}},c(e,m,r)};e.exports=r(chrome)}}(t);var r,i,browser=e(t.exports);class n{constructor(){this.isLocal=!0}log({level:e,message:t,timestamp:r,data:i,title:s}){let a;switch(e){case"debug":default:a="log";break;case"info":a="info";break;case"warn":a="warn";break;case"error":case"critical":case"fatal":a="error"}const o=s?`[${s}]`:"";void 0!==i?console[a](`[${r}] - ${n.LOGGER_PREFIX} ${o} ${t}`,i):console[a](`[${r}] - ${n.LOGGER_PREFIX} ${o} ${t}`)}}n.LOGGER_PREFIX="[DonationPopup] -",function(e){e.checkoutPopupShown="CHECKOUT-POPUP-SHOWN",e.checkoutPopupNotShown="CHECKOUT-POPUP-NOT-SHOWN",e.checkoutPopupSupressed="CHECKOUT-POPUP-SUPRESSED",e.checkoutPopupDonation="CHECKOUT-POPUP-DONATION",e.checkoutPopupFailedActivation="CHECKOUT-POPUP-FAILED-ACTIVATION",e.checkoutPopupPurchaseConfirmed="CHECKOUT-POPUP-PURCHASE-CONFIRMED",e.checkoutPopupHealthCheck="CHECKOUT-POPUP-HEALTH-CHECK",e.checkouPopupActivationFailed="CHECKOUT-POPUP-ACTIVATION-FAILED",e.checkoutPopupOfferDetailsClicked="CHECKOUT-POPUP-OFFER-DETAILS-CLICKED",e.checkoutPopupWhyAmISeeingThisClicked="CHECKOUT-POPUP-WHY-AM-I-SEEING-THIS-CLICKED",e.checkoutPopupLooserExtension="CHECKOUT-POPUP-LOOSER-EXTENSION",e.checkoutPopupActiveDomain="CHECKOUT-POPUP-ACTIVE-DOMAIN",e.checkoutPopupSiteMatches="CHECKOUT-POPUP-SITE-MATCHES",e.checkoutPopupMerchantInResultsFound="CHECKOUT-MERCHANT-IN-RESULTS-FOUND",e.checkoutPopupNotShownPerViewportSize="CHECKOUT-POPUP-NOT-SHOWN-PER-VIEWPORT-SIZE",e.checkoutPopupHiddenProgrammatically="CHECKOUT-POPUP-HIDDEN-PROGRAMMATICALLY",e.checkoutPopupGoogleSearch="CHECKOUT-POPUP-GOOGLE-SEARCH",e.checkoutPopupGooglePartnerAnnCreated="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-CREATED",e.checkoutPopupGooglePartnerAnnClicked="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-CLICKED",e.checkoutPopupGooglePartnerAnnHidden="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-HIDDEN",e.checkoutPopupStoodDown="CHECKOUT-POPUP-STOOD-DOWN"}(r||(r={})),function(e){e.libLog="GFLIB-LOG"}(i||(i={}));class s{constructor(e){this.isLocal=!1,this.backgroundService=e}log({level:e,message:t,data:r,title:n}){this.backgroundService.trackEvent(i.libLog,{log:{level:e,message:t,data:r,title:n}})}}const a=["debug","info","warn","error","critical","fatal"];class o{constructor(e){this.config={minLevel:e?.minLevel??"debug",enabled:e?.enabled??!1,transports:e?.transports??[new n],title:e?.title??""}}static getInstance(e){return o.instance||(o.instance=new o(e)),o.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&a.indexOf(e)>=a.indexOf(this.config.minLevel)}createLogMessage(e,t,r){return{level:e,version:"2.3.0",message:t,timestamp:(new Date).toISOString(),data:r,title:this.config.title}}log(e,t,r,i){if(!this.shouldLog(e))return;const n=this.createLogMessage(e,t,i);this.config.transports.filter((e=>!r||e.isLocal)).forEach((e=>e.log(n)))}debug(e,t,r=!1){this.log("debug",e,r,t)}info(e,t,r=!1){this.log("info",e,r,t)}warn(e,t,r=!1){this.log("warn",e,r,t)}error(e,t,r=!1){this.log("error",e,r,t)}critical(e,t,r=!1){this.log("critical",e,r,t)}fatal(e,t,r=!1){this.log("fatal",e,r,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}const c=3,l=e=>1e3*e;async function g(e,t={},r){const{maxAttempts:i=c,delayFn:n=l}=t;let s=null;for(let t=1;t<=i;t+=1)try{return await e()}catch(e){s=e,t<i&&await new Promise((e=>{setTimeout(e,n(t))}))}throw s&&t.logger&&t.operationName&&t.logger.error(`Operation ${t.operationName} failed after ${i} attempts.`,s,!0),s||new Error("Operation failed after multiple attempts")}const h=browser,d={TRACK_EVENT:"GF_TRACK_EVENT",HIDE_POPUP:"GF_HIDE_POPUP",GET_POPUP_CONFIG:"GF_GET_POPUP_CONFIG",IS_ACTIVE_DOMAIN:"GF_IS_ACTIVE_DOMAIN",LOG_MERCHANTS_IN_SEARCH_RESULTS:"GF_LOG_MERCHANTS_IN_SEARCH_RESULTS",SHOULD_STAND_DOWN:"GF_SHOULD_STAND_DOWN",ACTIVATE_OFFER:"GF_ACTIVATE_OFFER",STORE_SHOPIFY_SHOP_ID:"GF_STORE_SHOPIFY_SHOP_ID",GET_DOMAIN_BY_SHOP_ID:"GF_GET_DOMAIN_BY_SHOP_ID",GET_LANGUAGE_CONTENT:"GF_GET_LANGUAGE_CONTENT",GET_ACTIVE_DOMAINS:"GF_GET_ACTIVE_DOMAINS",MUTE_PARTNER_SERP_BOX:"GF_MUTE_PARTNER_SERP_BOX"},u="shopify_shop_ids",m="gf_last_health_check",f="gf_partner_config",p="gf_global_config",A="countryCode",y="version",w="gf_anonymous_user_info",v="gf_anonymous_encrypted_token",C="gf_event_history",E="gf_popup_everywhere",S={DEVICE:"wfDevice",DOMAINS:"wfDomains",STANDDOWN_POLICY:"wfStanddownPolicy",STANDDOWN_HISTORY:"wfStanddownHistory",STANDDOWN_ACTIVATIONS:"wfStanddownActivations",LAST_CACHE_REFRESH:"wfLastCacheRefresh",MERCHANT_RATES:"wfMerchantRates"},b="gfPreActivation",P="gfStanddownHistory",T="gfStanddownActivations",_="en",O="GIVE_FREELY_",x={async get(e){const t=`${O}${e}`;return(await browser.storage.local.get(t))[t]||null},async set(e,t){const r=`${O}${e}`;await browser.storage.local.set({[r]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${O}${e}`)):`${O}${e}`;await browser.storage.local.remove(t)}},I=()=>String("2.3.0"),F=async(e=!0)=>{const t=await x.get(y),r=await I(),i=t!==r;var n;return e&&i&&await(n=r,x.set(y,n)),i},k=o.getInstance(),U={async get(e,t,r,i=!1,n){let s=await x.get(e);const a=s;let o=!1,c=r??s?.retentionInSeconds??600;if(s&&Date.now()<=s.lastFetch+1e3*c&&!i)return{content:s.content,isStale:o};try{const r=await t(),i=n?n(r):null;null!=i&&(c=i),s=await this.set(e,r,c)}catch(e){k.error("Error getting cached value",{error:e}),o=!0}return{content:s?.content??a?.content,isStale:o}},async set(e,t,r){const i=r??600,n={content:t,lastFetch:Date.now(),retentionInSeconds:i};return await x.set(e,n),n},async clear(e){await x.remove(e)}};class D{constructor(){this.listeners=new Map,this.wildcardListeners=new Set}on(e,t){return this.addListener(e,t,!1)}once(e,t){return this.addListener(e,t,!0)}off(e,t){if(!t)return this.listeners.delete(e),void(this.wildcardListeners=new Set(Array.from(this.wildcardListeners).filter((t=>t.pattern!==e))));if(e.includes("*"))this.wildcardListeners=new Set(Array.from(this.wildcardListeners).filter((r=>!(r.pattern===e&&r.callback===t))));else{const r=this.listeners.get(e);if(r){const i=Array.from(r).filter((e=>e.callback!==t));i.length>0?this.listeners.set(e,new Set(i)):this.listeners.delete(e)}}}emit(e){const t=this.listeners.get(e.path)||new Set,r=new Set;for(const e of t)r.add(e);for(const t of this.wildcardListeners)this.matchesPattern(e.path,t.pattern)&&r.add(t);for(const t of r)t.callback(e),t.once&&this.removeListener(t)}clear(){this.listeners.clear(),this.wildcardListeners.clear()}addListener(e,t,r){const i={pattern:e,callback:t,once:r};if(e.includes("*"))this.wildcardListeners.add(i);else{const t=this.listeners.get(e);t?t.add(i):this.listeners.set(e,new Set([i]))}return()=>this.off(e,t)}removeListener(e){if(e.pattern.includes("*"))this.wildcardListeners.delete(e);else{const t=this.listeners.get(e.pattern);t&&(t.delete(e),0===t.size&&this.listeners.delete(e.pattern))}}matchesPattern(e,t){if("*"===t)return!0;const r=t.split(".").map((e=>"*"===e?"[^.]+":"**"===e?".*":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"))).join("\\.");return new RegExp(`^${r}$`).test(e)}}function L(e,t,r=""){const i=[];if(e===t)return i;if(R(e)||R(t))return e!==t&&i.push({path:r||"root",oldValue:e,newValue:t}),i;if(Array.isArray(e)&&Array.isArray(t))return JSON.stringify(e)!==JSON.stringify(t)&&i.push({path:r||"root",oldValue:e,newValue:t}),i;if(N(e)&&N(t)){const n=e,s=t,a=new Set([...Object.keys(n),...Object.keys(s)]);for(const e of a){const t=r?`${r}.${e}`:e,a=n[e],o=s[e];if(e in n)if(e in s){const e=L(a,o,t);i.push(...e)}else i.push({path:t,oldValue:a,newValue:void 0});else i.push({path:t,oldValue:void 0,newValue:o})}}else e!==t&&i.push({path:r||"root",oldValue:e,newValue:t});return i}function R(e){return null==e||"object"!=typeof e}function N(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var H;!function(e){e.CLOSED="CLOSED",e.OPEN="OPEN",e.HALF_OPEN="HALF_OPEN"}(H||(H={}));class G{constructor(e={}){this.state=H.CLOSED,this.failures=[],this.lastFailureTime=0,this.halfOpenCalls=0,this.logger=o.getInstance({minLevel:"warn"}),this.options={failureThreshold:5,recoveryTimeout:6e4,monitoringWindow:3e5,halfOpenMaxCalls:3,storageKey:"circuit_breaker_state",...e},this.storageKey=this.options.storageKey}async initialize(){await this.loadFromStorage()}static async create(e={}){const t=new G(e);return await t.initialize(),t}async loadFromStorage(){try{if("undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local){const e=(await chrome.storage.local.get(this.storageKey))[this.storageKey];e&&(this.state=e.state,this.failures=e.failures||[],this.lastFailureTime=e.lastFailureTime||0,this.halfOpenCalls=e.halfOpenCalls||0,this.cleanupOldFailures())}else if("undefined"!=typeof localStorage){const e=localStorage.getItem(this.storageKey);if(e){const t=JSON.parse(e);this.state=t.state,this.failures=t.failures||[],this.lastFailureTime=t.lastFailureTime||0,this.halfOpenCalls=t.halfOpenCalls||0,this.cleanupOldFailures()}}}catch(e){this.logger.warn("Failed to load circuit breaker state from storage:",e)}}async saveToStorage(){try{const e={state:this.state,failures:this.failures,lastFailureTime:this.lastFailureTime,halfOpenCalls:this.halfOpenCalls};"undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local?await chrome.storage.local.set({[this.storageKey]:e}):"undefined"!=typeof localStorage&&localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){this.logger.warn("Failed to save circuit breaker state to storage:",e)}}cleanupOldFailures(){const e=Date.now();this.failures=this.failures.filter((t=>e-t.timestamp<=this.options.monitoringWindow))}async execute(e,t){if(this.state===H.OPEN){if(!this.shouldAttemptRecovery()){if(t)return t();throw new Error("Circuit breaker is OPEN - service temporarily unavailable")}this.state=H.HALF_OPEN,this.halfOpenCalls=0,await this.saveToStorage()}if(this.state===H.HALF_OPEN){if(this.halfOpenCalls>=this.options.halfOpenMaxCalls)throw new Error("Circuit breaker HALF_OPEN call limit exceeded");this.halfOpenCalls+=1,await this.saveToStorage()}try{const t=await e();return await this.onSuccess(),t}catch(e){throw await this.onFailure(e),e}}async onSuccess(){this.state===H.HALF_OPEN&&(this.state=H.CLOSED,this.failures=[],await this.saveToStorage())}async onFailure(e){const t=Date.now();this.lastFailureTime=t,this.failures.push({timestamp:t,error:e.message}),this.failures=this.failures.filter((e=>t-e.timestamp<=this.options.monitoringWindow)),this.failures.length>=this.options.failureThreshold&&(this.state=H.OPEN),await this.saveToStorage()}shouldAttemptRecovery(){return Date.now()-this.lastFailureTime>=this.options.recoveryTimeout}getState(){return this.state}getFailureCount(){const e=Date.now();return this.failures.filter((t=>e-t.timestamp<=this.options.monitoringWindow)).length}async reset(){this.state=H.CLOSED,this.failures=[],this.lastFailureTime=0,this.halfOpenCalls=0,await this.saveToStorage()}async clearStorage(){"undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local?await chrome.storage.local.remove(this.storageKey):"undefined"!=typeof localStorage&&localStorage.removeItem(this.storageKey)}getStatus(){return{state:this.state,failureCount:this.getFailureCount(),nextAttemptTime:this.state===H.OPEN?this.lastFailureTime+this.options.recoveryTimeout:null}}}const $="https://cdn.givefreely.com/data/behavioral/";class M{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.mergedConfig=null,this.globalConfigRefreshInterval=null,this.partnerConfigRefreshInterval=null,this.eventEmitter=new D,this.isInitialized=!1,this.partnerCircuitBreaker=new G({failureThreshold:3,recoveryTimeout:6e4,monitoringWindow:3e5,storageKey:`gf_partner_circuit_breaker_${e}`}),this.globalCircuitBreaker=new G({failureThreshold:3,recoveryTimeout:6e4,monitoringWindow:3e5,storageKey:"gf_global_circuit_breaker"})}async initialize(){this.isInitialized||(await Promise.all([this.partnerCircuitBreaker.initialize(),this.globalCircuitBreaker.initialize()]),this.isInitialized=!0)}ensureInitialized(){if(!this.isInitialized)throw new Error("GiveFreelyConfigService must be initialized before use. Call initialize() or use create() method.")}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchPartnerConfig(){const e=await g((async()=>{const e=await fetch(`${$}${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions());if(!e)throw new Error("Failed to fetch or get from cache partner config");return this.partnerConfigRefreshInterval=e.configRefreshInterval||this.partnerConfigRefreshInterval,e}async fetchGlobalConfig(){const e=await g((async()=>{const e=await fetch(`${$}global.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config => Status code: ${e.status} .${e.statusText}`);return e.json()}),this.getRetryOptions());if(!e)throw new Error("Failed to fetch or get from cache global config",e);return this.globalConfigRefreshInterval=e.configRefreshInterval||this.globalConfigRefreshInterval,e}async getCachedConfig(){return this.mergedConfig}async getConfig(e=!1){this.ensureInitialized();let t=!1;e&&(t=await F());const[r,i]=await Promise.all([U.get(f,this.fetchPartnerConfig.bind(this),this.partnerConfigRefreshInterval,t,(e=>e?.configRefreshInterval??null)),U.get(p,this.fetchGlobalConfig.bind(this),this.globalConfigRefreshInterval,t,(e=>e?.configRefreshInterval??null))]);if(!i.content)throw new Error("Global config is required");if(!r.content)throw new Error("Partner config is required");this.partnerConfig=r.content,this.globalConfig=i.content;const n=this.mergeConfigs(JSON.parse(JSON.stringify(this.globalConfig)),JSON.parse(JSON.stringify(this.partnerConfig)));if(!n)throw new Error("Was not able to merge configs");return((e,t,r)=>{const i=[...t.merchantExclusions??[],...r.merchantExclusions??[]];e.merchantExclusions=i})(n,this.globalConfig,this.partnerConfig),this.emitConfigChanges(n),n}async clearCache(){this.ensureInitialized(),await Promise.all([U.clear(f),U.clear(p)]),this.partnerConfig=null,this.globalConfig=null,this.mergedConfig=null,this.eventEmitter.clear(),await Promise.all([this.partnerCircuitBreaker.reset(),this.globalCircuitBreaker.reset()])}getCircuitBreakerStatus(){return this.ensureInitialized(),{partner:this.partnerCircuitBreaker.getStatus(),global:this.globalCircuitBreaker.getStatus()}}mergeConfigs(e,t){if(!t)return e;if(!e)return t;const r={...e};return Object.keys(t).forEach((i=>{if(!Object.prototype.hasOwnProperty.call(t,i))return;const n=e[i],s=t[i];void 0!==s&&(Array.isArray(s)?r[i]=[...s]:r[i]=null===s||"object"!=typeof s||null===n||"object"!=typeof n?s:this.mergeConfigs(n,s))})),r}on(e,t){return this.eventEmitter.on(e,t)}once(e,t){return this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.off(e,t)}emitConfigChanges(e){if(!this.mergedConfig)return this.mergedConfig=e,void this.eventEmitter.emit({path:"root",oldValue:null,newValue:e,config:e});const t=L(this.mergedConfig,e);for(const r of t)this.eventEmitter.emit({path:r.path,oldValue:r.oldValue,newValue:r.newValue,config:e});this.mergedConfig=e}}class z{constructor(e,t,r,i=60){this.track=async(e,t,r=!1,i=!1)=>{const n={partner:`gfLib_${this._partnerApiKey}`,eventType:e,eventData:{userId:r?void 0:this._userService?.user?.id,libVersion:I(),...t}};try{const e=JSON.stringify(n,((e,t)=>t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t)),t=await this.getEventsUrl();return t?await this.BroadcastEvent(t,e,n,i):(this._logger.info("Cant broadcast event. eventsUrl cant be retrieved from config",n,!0),!1)}catch(e){return this._logger.error("Something unexpected happened when dispatching a gf event",{error:e,event:n},!0),!1}},this.getEventsHistory=async()=>{const e=await x.get(C),t=(e=>{const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()})(-this._debounceWindowInMinutes),r=(e||[]).filter((e=>e.createdAt>t));return await x.set(C,r),r},this.shouldBroadcastEvent=async(e,t)=>!!t||!(await this.getEventsHistory()).some((t=>t.payload===e)),this.pushEventToHistory=async e=>{const t=await this.getEventsHistory();t.push({createdAt:Date.now(),payload:e}),await x.set(C,t)},this._partnerApiKey=e,this._userService=t,this._debounceWindowInMinutes=i,this._logger=o.getInstance({title:"Analytics"}),this._configService=r}async BroadcastEvent(e,t,r,i){if(await this.shouldBroadcastEvent(t,i)){const i=await fetch(e,{headers:{"Content-Type":"application/json"},method:"POST",body:t,cache:"no-store"});return i.ok?(await this.pushEventToHistory(t),!0):(this._logger.error("Something unexpected happened when dispatching an event",{status:i.status,statusText:i.statusText,event:r},!0),!1)}return this._logger.info("This event has already been broadcasted during the past hour",r,!0),!1}async getEventsUrl(){const e=await this._configService.getCachedConfig();return e?.eventsUrl}}z.trackEvent=async(e,t,r=!1,i=!1)=>{await async function(e){return await h.runtime.sendMessage(e)}({type:d.TRACK_EVENT,payload:{eventType:e,eventData:t,anonymous:r,skipThrottling:i}})};class K{constructor(e,t){this.lastCheck=null,this.trackEvent=e,this.logger=t}async initialize(){const e=await x.get(m);e&&(this.lastCheck=e)}getToday(){return(new Date).toISOString().split("T")[0]}async check(){try{const e=this.lastCheck??0,t=this.getToday();(e?new Date(e).toISOString().split("T")[0]:null)!==t&&(this.lastCheck=Date.now(),await x.set(m,this.lastCheck),await this.trackEvent(r.checkoutPopupHealthCheck,{language:browser.i18n.getUILanguage()}))}catch(e){this.logger.error("Health check failed",{error:e instanceof Error?e.message:"Unknown error"},!0)}}}var j;!function(e){e[e.Pending=0]="Pending",e[e.Ready=1]="Ready",e[e.Received=2]="Received",e[e.Donated=3]="Donated",e[e.Disqualified=4]="Disqualified"}(j||(j={}));class B{constructor(e,t,r){this.libraryId=e,this.config=t,this.logger=r}async getAnonymousUserCommissions(e,t){try{const r=new URLSearchParams(t).toString(),i=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.getAnonymousUserComissionsPath}?${r}`,{method:"GET",headers:{"Content-Type":"application/json","X-AnonymousUserToken":e}});if(!i.ok)throw new Error(`Failed to fetch commissions. Status code: ${i.status} .${i.statusText}`);return await i.json()}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error fetching anonymous user's commissions:",{error:e}),e}}async createOrUpdateAnonymousUser(e,t){try{const r=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.createAnonymousUserPath}?gfLibId=${this.libraryId}`,{method:"PUT",headers:{"Content-Type":"application/json","X-GF-Platform":"GFLibrary","X-AnonymousUserToken":t??""},body:JSON.stringify(e)});if(!r.ok)throw this.logger.error(`Failed to create/update anonymous user. Status code: ${r.status}. ${r.statusText}`),new Error(`Failed to create/update anonymous user. Status code: ${r.status}. ${r.statusText}`);this.logger.info("[GiveFreelyApiClient] anonymous user created/updated successfully.");const i=await r.json(),n=r.headers.get("X-AnonymousUserToken");return{resultUser:{...i,charity:{ein:i.selectedCharity,thirdPartyId:i.selectedCharityThirdPartyIdentifier,name:void 0}},resultToken:n}}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error creating anonymous user:",{error:e},!0),e}}}class V{constructor(e,t){this._giveFreelyApiClient=e,this._logger=t,this.user=null}async resetUser(){await x.remove(v),await x.remove(w)}async upsertUser(e){let t=await this.fetchUser();try{const r={selectedCharity:e?.ein,selectedCharityThirdPartyIdentifier:e?.thirdPartyId};if(!await this.shouldCreateOrUpdateUser(t,r))return t;const i=await x.get(v),{resultUser:n,resultToken:s}=await this._giveFreelyApiClient.createOrUpdateAnonymousUser(r,i);s&&await x.set(v,s),n&&(await x.set(w,n),t=n)}catch(e){this._logger.error("Error creating/updating anonymous user:",e)}return this.user=t,t}async fetchUser(){const e=await x.get(w);return this.user=e,e}async shouldCreateOrUpdateUser(e,t){return!e||e.charity?.ein!==t.selectedCharity||e.charity?.thirdPartyId!==t.selectedCharityThirdPartyIdentifier}}const W=e=>{try{return new URL(e),!0}catch{return!1}};async function q(e,t,r,i){try{const n=(await J())?.[t],s=await this.getStanddownPolicy(),a=ee(s,new URL(r).search);if(n&&n>Date.now())return e.info("Standing down because current affiliate stand down session has not expired"),X(t,void 0,!a&&null),{result:!0,reason:"sessionNotExpired"};if(ee(s,new URL(r).search))return e.info("Standing down because url has affiliate params"),X(t,void 0,!1),{result:!0,reason:"hasAffiliateParams"};if(te(s,i))return e.info("Standing down because a standdown cookie is present"),X(t,void 0,!1),{result:!0,reason:"hasAffiliateCookies"};e.info("No need to stand down.")}catch(t){e.error("Exception produced when trying to determine if it should stand down",t)}return{result:!1}}function Y(e,t){if(!this.standDownPolicy)return this.logger.warn("Could not check affiliation. No stand down policy found"),this.getStanddownPolicy().then((e=>{this.standDownPolicy=e})),!1;const r=e.some((e=>Q(this.standDownPolicy,e)))||ee(this.standDownPolicy,t);return this.logger.info("Affiliation result:",r),r}const J=async()=>x.get(P),X=async(e,t=1,r=null)=>{const i=await J()??{},n=i?.[e]??0,s=Date.now()+60*t*60*1e3;if(i[e]=s,await x.set(P,i),null!==r){const t=await Z(e);if(r||!r&&t&&s-n>2e4){const t=await x.get(T)??{};t[e]=r,await x.set(T,t)}}},Z=async e=>{const t=await x.get(T);return t?.[e]??!1},Q=(e,t)=>{if(!t)return!1;const{Domains:r}=e;return r.some((e=>t.includes(e)))},ee=(e,t)=>{if(!t)return!1;const{Params:r}=e;return r.some((e=>t.toLowerCase().includes(`?${e.toLowerCase()}`)))||r.some((e=>t.toLowerCase().includes(`&${e.toLowerCase()}`)))},te=(e,t)=>{if(!t)return!1;const{Cookies:r}=e;return!!r?.length&&r.some((e=>t.includes(e)))},re=new Set,ie=new Set,ne={urls:["<all_urls>"],types:["main_frame"]};class se extends Error{constructor(e="Service not initialized"){super(e),this.name="UninitializedServiceError"}}const ae=e=>{if(!e)throw new se};class oe{static register(e,t){this.strategies.set(e,t)}static get(e){return this.strategies.get(e)}static exists(e){return!!function(e){return"object"==typeof e&&null!==e&&"type"in e&&"payload"in e&&"string"==typeof e.type}(e)&&this.knownMessageTypes.has(e.type)}}oe.strategies=new Map,oe.knownMessageTypes=new Set([...Object.values(d)]);const ce=e=>{let t;if(browser.webRequest){const i=(e=>{const t=e.getLogger();return({requestId:r,url:i,initiator:n})=>{try{if(re.has(r)||ie.has(r)||!W(i))return;const{hostname:s,search:a}=new URL(i);let o;n&&W(n)&&(o=new URL(n).hostname),(e.hasAffiliation([s,o],a)||e.isCustomStandownMatch([i,n]))&&(t.info("Affiliation found or custom standown match on url, adding request id to track"),re.add(r))}catch(e){t.error("Error on handleAffiliateOnBeforeRequest",e)}}})(e);browser.webRequest.onBeforeRequest.addListener(i,ne);const n=(e=>{const t=e.getLogger();return async({requestId:i,redirectUrl:n})=>{try{if(!re.has(i))return;t.info("Attempting to find active domain");const{hostname:s}=new URL(n),a=(await e.getActiveDomains()).find((e=>s===e.domain||s.endsWith(`.${e.domain}`)));if(!a)return;t.info("Found active domain. Updating standdown state"),await X(a.domain,void 0,!1),(await e.getCachedConfig()).enhancedLogging&&e.trackEvent(r.checkoutPopupStoodDown,{domain:a.domain,reason:"vendorPolicy (at webReq listener)"})}catch(e){t.error("Error on handleAffiliateOnBeforeRedirect",e)}}})(e);browser.webRequest.onBeforeRedirect.addListener(n,ne);const s=(e=>{const t=e.getLogger();return({requestId:e})=>{try{re.has(e)&&(t.info("Tracking request completed. Request Id:",e),re.delete(e))}catch(e){t.error("Error on handleAffiliateOnCompleted",e)}}})(e);browser.webRequest.onCompleted.addListener(s,ne),t=()=>{browser.webRequest.onBeforeRequest.removeListener(i),browser.webRequest.onBeforeRedirect.removeListener(n),browser.webRequest.onCompleted.removeListener(s)}}const i=function(){const t=o.getInstance(),r=(r,i,n)=>{function s(e){n(e)}const a=(async t=>(e.getLogger().debug("Received message",{type:t.type,payload:t.payload}),le(e,t)))(r,0);return a instanceof Promise?(a.then((e=>{e&&s(e)})).catch((e=>{t.warn("Async message callback error:",e)})),!0):!0===a||void 0};return h.runtime.onMessage.addListener(r),r}();return function(){t&&t(),browser.runtime.onMessage.removeListener(i)}},le=async(e,t)=>{ae(e.isInitialized());const r=oe.get(t.type);if(!r)return;const i={giveFreelyService:e};return r.handle(t,i)};class ge{async handle(e,t){const{activeDomain:i,originalUrl:n,selectedCharity:s,gfCommissionUniqueId:a,openTab:o}=e.payload,{giveFreelyService:c}=t,l=c.getLogger();l.debug("Activating offer",{activeDomain:i,selectedCharity:s});try{if(i?.merchantId&&(async e=>{try{const t=await(async()=>await x.get(E)??{})();t[e]&&delete t[e],await x.set(E,t)}catch{}})(parseInt(i.merchantId)),!s?.ein||!s?.thirdPartyId)throw new Error("Missing charity information");const e=await c.upsertUser(s);l.debug("Upserted user",{currentUser:e}),e||l.info("Failed to create user. Using default bucket's user");const t=await c.getProviderPreActivation(i.provider),r=await c.generateAffiliateUrl(i,n,e,a,t);return l.debug("Generated affiliate URL",{affiliateUrl:r}),!1!==o?((async e=>{const t=h.tabs.getCurrent(),r=await t,i=await h.tabs.create({url:e,openerTabId:r?.id,active:!1,pinned:!0});await(async e=>new Promise((t=>{h.tabs.onUpdated.addListener((async function r(i,n){if(i===e&&"complete"===n.status){if(h.tabs.onUpdated.removeListener(r),!(await h.tabs.get(e)).url)return void t(!1);t(!0)}}))})))(i.id)&&setTimeout((()=>{i?.id&&h.tabs.remove(i.id)}),3e4)})(r),await c.updateStanddownHistory(i.domain,!0)):await c.updateStanddownHistoryByMerchantId(i.merchantId,!0),l.debug("Activated offer",{activeDomain:i,selectedCharity:s,gfCommissionUniqueId:a}),{type:d.ACTIVATE_OFFER,payload:{response:!0,activationLink:r}}}catch(e){return l.error("Error activating offer",{activeDomain:i,error:e}),c.trackEvent(r.checkoutPopupFailedActivation,{activeDomain:i,error:e}),{type:d.ACTIVATE_OFFER,payload:{response:!1}}}}}class he{async handle(e,t){const{urls:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=await i.getActiveDomains();if(!e||0===e.length)throw new Error("No active domains");const t={},n=r.map((async r=>{try{const{hostname:n}=new URL(r),s=e.find((e=>n===e.domain||n.endsWith(`.${e.domain}`)));if(s){const{result:e}=await i.shouldStandDown(s.domain,r);t[r]={activeDomain:s,shouldStandDown:e,currentlyActivated:await i.wasLastStandDownAnActivation(s.domain)}}}catch{}}));return await Promise.all(n),{type:d.GET_ACTIVE_DOMAINS,payload:{result:t}}}catch(e){return n.error("Error checking domain",{urls:r,error:e}),{type:d.GET_ACTIVE_DOMAINS,payload:{result:{}}}}}}class de{async handle(e,t){const{shopId:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=u,t=await x.get(e)||[];if(t.length>0&&"Merchant"in t[0].domain)return n.warn("Detected legacy WildfireActiveDomain in Shopify storage — data should have been pruned. Clearing stale entries."),await x.remove(e),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}};const i=t.find((e=>e.shopId===r));return i?(n.debug("Found domain for shop ID",{shopId:r,domain:i.domain}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!0,domain:i.domain,shopInfo:i}}):(n.debug("No domain found for shop ID",{shopId:r}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}})}catch(e){return n.error("Error getting domain for shop ID",{shopId:r,error:e}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}}}}}class ue{async handle(e,t){const{lang:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();n.debug("Getting language strings",{lang:r});try{const e=await i.getLanguage(r);return n.debug("Language strings fetched",{language:e}),{type:d.GET_LANGUAGE_CONTENT,payload:{translations:e.translations,charities:e.charities}}}catch(e){return n.error("Error getting language strings",{error:e}),{type:d.GET_LANGUAGE_CONTENT,payload:{translations:null,charities:null}}}}}class me{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger(),n=await r.getCachedConfig();try{return i.debug("Fetching popup config"),{type:d.GET_POPUP_CONFIG,payload:{config:n}}}catch(e){return i.error("Error fetching popup config",{error:e}),{type:d.GET_POPUP_CONFIG,payload:{config:null}}}}}class fe{async handle(e,t){const{days:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=new Date;return e.setDate(e.getDate()+r),await x.set("popup_hide",{popupHide:e.getTime()}),n.debug("Popup hidden",{days:r,expiry:e}),{type:d.HIDE_POPUP,payload:{ack:!0}}}catch(e){return n.error("Error hiding popup",{days:r,error:e}),{type:d.HIDE_POPUP,payload:{ack:!1}}}}}class pe{async handle(e,t){const{hostname:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const{merchantExclusions:e}=await i.getConfig();if(n.debug("Checking hostname",{hostname:r}),i.healthCheck(),e.some((e=>e.disableDomain&&(r===e.domain||r.endsWith(`.${e.domain}`)))))return n.debug("Hostname is in merchant exclusions",{hostname:r}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!1,domain:void 0}};const t=await i.getActiveDomains();n.debug("Retrieved active domains",{count:t.length});const s=t.find((e=>r===e.domain||r.endsWith(`.${e.domain}`)));return n.debug("Domain check result",{hostname:r,isActive:!!s}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!!s,domain:s}}}catch(e){return n.error("Error checking domain",{hostname:r,error:e}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!1,domain:void 0}}}}}class Ae{async handle(e,t){const{currentUrl:i,searchResults:n,source:s}=e.payload,{giveFreelyService:a}=t,o=a.getLogger();try{const e=await a.getActiveDomains();o.debug("Finding merchants in search results",{currentUrl:i});const c=n.filter((t=>{try{const{hostname:r}=new URL(t.url);return e.some((e=>e.domain===r||r.endsWith(`.${e.domain}`)))}catch{return o.debug("Couldn't parse the following search result url",{x:t}),!1}}));if(o.info("Number of merchants identified in the search result",{number:c.length}),c.length>0){const e=Math.floor(Math.random()*Date.now());for(const n of c)t.giveFreelyService.trackEvent(r.checkoutPopupMerchantInResultsFound,{source:s,searchResultsId:e,currentUrl:i,searchResultUrl:n.url,sponsored:n.isSponsored},!0)}return{type:d.LOG_MERCHANTS_IN_SEARCH_RESULTS,payload:{result:!0}}}catch(e){return o.error("Error sending logs for merchants in search results",{currentUrl:i,error:e}),{type:d.LOG_MERCHANTS_IN_SEARCH_RESULTS,payload:{result:!1}}}}}class ye{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger();try{return await x.set("gf_partner_serp_muted",!0),i.debug("Partner Serp box hidden"),{type:d.MUTE_PARTNER_SERP_BOX,payload:{ack:!0}}}catch(e){return i.error("Error hiding partner serp box",{error:e}),{type:d.MUTE_PARTNER_SERP_BOX,payload:{ack:!1}}}}}class we{async handle(e,t){const r=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=u;let t=await x.get(e)||[];t.length>0&&"Merchant"in t[0].domain&&(n.warn("Detected legacy WildfireActiveDomain in Shopify storage — data should have been pruned. Clearing stale entries."),t=[],await x.remove(e));const i=t.findIndex((e=>e.shopId===r.shopId));return i>=0?t[i]=r:t.push(r),await x.set(e,t),n.debug("Stored Shopify shop ID",{shopInfo:r}),{type:d.STORE_SHOPIFY_SHOP_ID,payload:{success:!0}}}catch(e){return n.error("Error storing Shopify shop ID",{shopInfo:r,error:e}),{type:d.STORE_SHOPIFY_SHOP_ID,payload:{success:!1}}}}}class ve{async handle(e,t){const{activeDomain:r,url:i,cookies:n}=e.payload,{giveFreelyService:s}=t,a=s.getLogger();a.debug("Checking if we should stand down",{activeDomain:r});try{const e=await s.shouldStandDown(r,i,n);return{type:d.SHOULD_STAND_DOWN,payload:e}}catch(e){return a.error("Error checking if we should stand down. Returning false",{activeDomain:r,error:e}),{type:d.SHOULD_STAND_DOWN,payload:{result:!1}}}}}class Ce{async handle(e,t){const{eventType:r,eventData:i,anonymous:n,skipThrottling:s}=e.payload,{giveFreelyService:a}=t,o=a.getLogger();o.debug("Broadcasting event",{eventType:r,eventData:i,anonymous:n,skipThrottling:s});try{const e=await a.trackEvent(r,i,n,s);return{type:d.TRACK_EVENT,payload:{result:e}}}catch(e){return o.error("Error broadcasting event. Returning false",{eventType:r,eventData:i,error:e}),{type:d.TRACK_EVENT,payload:{result:!1}}}}}const Ee=o.getInstance(),Se=async()=>await x.get(A)||(async()=>{Ee.debug("detecting country");const e={method:"GET",headers:{"Content-Type":"application/json",Authorization:"Basic OTEzOTkxOnFlYmpaWF9DOGNRY0lxSHA4WTVjNGxzU1pRSlM2VW9MMExzTF9tbWs="}};try{const t=await fetch("https://geoip.maxmind.com/geoip/v2.1/country/me",e);if(Ee.debug("Received geolocation response",{status:t.status}),!t.ok)return void Ee.error("Failed to get geolocation data",{status:t.status,statusText:t.statusText});const r=await t.json();if(!r)throw new Error("There was an error fetching geoip look up");return await x.set(A,r.country.iso_code),r.country.iso_code}catch(e){return void Ee.error("Failed to get geolocation data",{error:e},!0)}})(),be="https://cdn.givefreely.com/data/language",Pe=async(e,t,r,i,n=[],s=!1)=>{const a=(n??[]).includes(r)?_:r;e.debug(`Requested lang ${r} and current lang ${a}`);const o=`lang-${_}`,c=await U.get(o,(async()=>(e.debug(`Fetching default language ${_} for partner ${t}`),Te(t,_))),i||600,s);if(!c.content)throw new Error(`Failed to fetch default language ${_} and no cache version available`);if(_===a)return c.content;const l=`lang-${a}`,g=await U.get(l,(async()=>(e.debug(`Fetching language ${a} for partner ${t}`),Te(t,a))),i||600,s);if(!g.content)return c.content;const h=xe(c.content,g.content);return await U.set(l,h,i||600),h},Te=async(e,t)=>{const r=`/global-${t}.json`,i=`/${e}/${t}.json`,[n,s]=await Promise.allSettled([_e(`${be}${r}`),_e(`${be}${i}`)]);let a,o;"fulfilled"===n.status&&(a=n.value),"fulfilled"===s.status&&(o=s.value);const c=Oe(a,o);return{translations:c.translations,charities:c.charities}},_e=async e=>{const t=await fetch(e,{cache:"no-store"});if(!t.ok)throw new Error(`Failed to fetch partner language file ${e}. Status: ${t.status}. Reason: ${t.statusText}`);return t.json()},Oe=(e,t)=>({translations:{...e?.translations??{},...t??{}},charities:{...e?.charities??{}}}),xe=(e,t)=>({translations:{...e.translations,...t.translations},charities:{...e.charities,...t.charities}});class Ie{constructor(e,t,r,i){this._logger=e,this.feedUrl=t,this.activationUrl=r,this.preActivationUrl=i}async getRawFeed(){try{const e=`${this.feedUrl}`,t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch feed from ${e}. Status ${t.status}. ${t.statusText}`);return t.json()}catch(e){throw this._logger.error("Failed to fetch the feed",{err:e}),new Error("Failed to fetch the feed")}}async preActivation(e,t){try{const r=await fetch(this.preActivationUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({partnerId:e,...t&&{provider:t}})});if(!r.ok)throw new Error(`Failed to pre-activate. Status ${r.status}. ${r.statusText}`);return r.json()}catch(e){throw this._logger.error("Failed to pre-activate",{err:e}),new Error("Failed to pre-activate")}}async generateAffiliateUrl(e,t,r,i,n,s){try{const a=await fetch(`${this.activationUrl}?redirect=false`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e.provider,partnerId:i,userId:r?.id||"",ein:r?.charity?.ein||"",tpi:r?.charity?.thirdPartyId||"",url:t,gfCommissionUniqueId:n,merchantId:e.merchantId,domainId:e.id,providerCustom:s})});if(!a.ok)throw new Error(`Failed to generate affiliate url. Status ${a.status}. ${a.statusText}`);return(await a.json()).affiliateLink}catch(e){throw this._logger.error("Failed to generate affiliate url",{err:e}),new Error("Failed to generate affiliate url")}}}class Fe{constructor(e){this.raw=e}static mapKind(e){return 1===e?"FLAT":"PERCENTAGE"}static mapOfferRate(e){return{Kind:Fe.mapKind(e.k),Amount:e.a,Name:e.n,Currency:e.c??void 0}}static fromRawArray(e){return e.map((e=>new Fe(e)))}static fromRaw(e){return new Fe(e)}get id(){return parseInt(this.raw.di,10)||0}get domain(){return this.raw.d}get provider(){return this.raw.p}get merchantId(){return this.raw.mi}get merchantName(){return this.raw.mn}get commission(){return{amount:this.raw.c.a,kind:Fe.mapKind(this.raw.c.k)}}get rates(){return this.raw.r?.map(Fe.mapOfferRate)??[]}toRaw(){return this.raw}toJSON(){return{id:this.id,domain:this.domain,provider:this.provider,merchantId:this.merchantId,merchantName:this.merchantName,commission:this.commission,rates:this.rates}}}class ke{constructor(e,t,r=600){this.standDownPolicy=null,this.shouldStandDown=q.bind(this),this.hasAffiliation=Y.bind(this),this.updateStanddownHistory=X,this.refreshInterval=r,this.giveFreelyFeedClient=e,this.logger=t}async getActiveDomains(e=!1){try{const t=await U.get("gfFeed",(async()=>this.fetchRawActiveDomains()),this.refreshInterval,e);if(!t.content)throw new Error("Failed to retrieve feed from cache");return Fe.fromRawArray(t.content)}catch(e){return this.logger.error("Failed to get active domains:",e),[]}}async preActivation(e,t){return this.giveFreelyFeedClient.preActivation(e,t)}async generateAffiliateUrl(e,t,r,i,n,s){return this.giveFreelyFeedClient.generateAffiliateUrl(e,t,r,i,n,s)}async fetchRawActiveDomains(){const e=await this.giveFreelyFeedClient.getRawFeed();return this.standDownPolicy=e.standdownRules,e.activeDomains}async getStanddownPolicy(){if(this.standDownPolicy)return this.standDownPolicy;const e=await this.giveFreelyFeedClient.getRawFeed();return this.standDownPolicy=e.standdownRules,this.standDownPolicy}static async createGiveFreelyFeedService(e,t){e.debug("Initializing givefreely feed service with config",t);const{feedUrl:r,activationUrl:i,preActivationUrl:n}=t.multiAffiliate??{};if(!r||!i||!n)throw new Error("multiAffiliate config is missing required URLs (feedUrl, activationUrl, preActivationUrl)");const s=new Ie(e,r,i,n),a=new ke(s,e,t.multiAffiliate?.feedRefreshInterval);return await a.getActiveDomains(),a}}async function Ue(e){const t=[...Object.values(S),u];try{await Promise.all(t.map((e=>x.remove(e)))),e.info("Pruned legacy Wildfire storage keys",{keys:t})}catch(t){e.debug("Failed to prune legacy Wildfire storage keys",t)}}var De=Object.freeze({__proto__:null,generateAffiliateUrl:async function(e,t,r,i,n){return ae(this.state.initialized),this.state.giveFreelyFeedService.generateAffiliateUrl(e,t,r,this.state.partnerApiKey,i,n)},getActiveDomains:async function(){return ae(this.state.initialized),this.state.giveFreelyFeedService.getActiveDomains()},pruneLegacyWildfireStorage:Ue});async function Le(e,t,r){try{const i={...t};for(const e of r)delete i[e];return await x.set(b,i),e.info("Pruned preActivation providers",{providers:r}),i}catch(r){return e.debug("Failed to prune preActivation providers",r),t}}var Re=Object.freeze({__proto__:null,getCurrentUser:function(){return ae(this.state.initialized),this.state.giveFreelyUserService.user},getLanguage:async function(e){return ae(this.state.initialized),Pe(this.logger,this.state.partnerApiKey,e,this.state.config?.configRefreshInterval,this.state.config?.ignoredLanguages)},getProviderPreActivation:async function(e){if(ae(this.state.initialized),this.state.preActivation&&e in this.state.preActivation)return this.state.preActivation[e];const t=await x.get(b);if(t&&e in t)return this.state.preActivation=t,t[e];const r=(await this.state.giveFreelyFeedService.preActivation(this.state.partnerApiKey,e))[e]??{},i={...t||{},...this.state.preActivation||{},[e]:r};return this.state.preActivation=i,await x.set(b,i),r},initializePreActivation:async function(e){const t=await x.get(b);if(t&&Object.keys(t).length>0)return this.state.preActivation=t,t;const r=await e.preActivation(this.state.partnerApiKey);return this.state.preActivation=r,await x.set(b,r),r},prunePreActivationProviders:Le,upsertUser:function(e){return ae(this.state.initialized),this.state.giveFreelyUserService.upsertUser(e)}});async function Ne(e=async()=>(this.logger.debug("Using default partnerFilter."),!0)){if(!this.state.initialized){this.logger.info("Starting initialization with mutex protection");try{await this.dependencies.configService.initialize();const t=await F(!1),r=await this.dependencies.configService.getConfig(!0);this.logger.configure({enabled:r.loggingEnabled??!0,minLevel:r.backgroundMinLogLevel??"error"}),this.logger.info("Initializing GiveFreelyService",{partnerApiKey:this.partnerApiKey}),!r.multiAffiliate?.skipWildfirePruning&&t&&await Ue(this.logger);const i=await ke.createGiveFreelyFeedService(this.logger,r);this.state.healthCheck=new K(this.trackEvent.bind(this),this.logger),await this.state.healthCheck.initialize();const n=new B(this.partnerApiKey,r,this.logger);this.state.giveFreelyUserService=new V(n,this.logger),await this.state.giveFreelyUserService.fetchUser(),this.state.giveFreelyUserService.user?.id||await this.state.giveFreelyUserService.upsertUser(),this.state.analytics=new z(this.partnerApiKey,this.state.giveFreelyUserService,this.dependencies.configService);try{if(r.multiAffiliate?.prunePreActivationProviders?.length){const e=await x.get(b);e&&await Le(this.logger,e,r.multiAffiliate.prunePreActivationProviders)}await this.initializePreActivation(i)}catch(e){this.logger.debug("Pre-activation initialization failed — will retry on first offer activation",e)}oe.register(d.IS_ACTIVE_DOMAIN,new pe),oe.register(d.GET_POPUP_CONFIG,new me),oe.register(d.HIDE_POPUP,new fe),oe.register(d.SHOULD_STAND_DOWN,new ve),oe.register(d.TRACK_EVENT,new Ce),oe.register(d.ACTIVATE_OFFER,new ge),oe.register(d.STORE_SHOPIFY_SHOP_ID,new we),oe.register(d.GET_DOMAIN_BY_SHOP_ID,new de),oe.register(d.GET_LANGUAGE_CONTENT,new ue),oe.register(d.LOG_MERCHANTS_IN_SEARCH_RESULTS,new Ae),oe.register(d.GET_ACTIVE_DOMAINS,new he),oe.register(d.MUTE_PARTNER_SERP_BOX,new ye),await(async e=>{try{await Se()}catch(t){e.debug("Failed to get geolocation data",{error:t})}})(this.logger),await(async(e,t,r)=>{t.purgeLanguages&&t.purgeLanguages.length>0&&await Promise.all(t.purgeLanguages.flatMap((e=>[U.clear(`lang-${e}`),U.clear(`global-${e}`)]))),g((async()=>{e.debug("Initializing default language with partner API key",{partnerApiKey:r}),await Pe(e,r,_,t.configRefreshInterval)}))})(this.logger,r,this.partnerApiKey),this.state=((e,t)=>{const{partnerFilter:r,config:i,giveFreelyFeedService:n}=t;return{...e,initialized:!0,partnerFilter:r,config:i,giveFreelyFeedService:n}})(this.state,{partnerFilter:e,config:r,giveFreelyFeedService:i}),this.logger.addTransport(new s(this)),this.cleanupListeners=ce(this),this.logger.info("GiveFreelyService initialized successfully")}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw this.logger.error("Failed to initialize GiveFreelyService",{error:t}),new Error(`Failed to initialize GiveFreelyService: ${t}`)}}}function He(){return this.state.initialized}var Ge={config:Object.freeze({__proto__:null,getCachedConfig:async function(){return ae(this.state.initialized),this.state.config=await this.dependencies.configService.getConfig(),this.logger.configure({minLevel:this.state.config.backgroundMinLogLevel??"error"}),this.state.config},getConfig:function(){return ae(this.state.initialized),this.state.config},offConfigChange:function(e,t){ae(this.state.initialized),this.dependencies.configService.off(e,t)},onConfigChange:function(e,t){return ae(this.state.initialized),this.dependencies.configService.on(e,t)},onceConfigChange:function(e,t){return ae(this.state.initialized),this.dependencies.configService.once(e,t)}}),merchants:De,observability:Object.freeze({__proto__:null,getLogger:function(){return ae(this.state.initialized),this.logger},healthCheck:async function(){ae(this.state.initialized),await this.state.healthCheck.check()},trackEvent:function(e,t,r=!1,i=!1){return ae(this.state.initialized),this.state.analytics.track(e,t,r,i)}}),standdown:Object.freeze({__proto__:null,hasAffiliation:function(e,t){if(!this.state.giveFreelyFeedService)return this.logger.warn("GiveFreely Feed service not initialized yet"),!1;const r=this.state.giveFreelyFeedService.hasAffiliation(e,t);return r&&this.logger.info("Affiliation identified"),r},isCustomStandownMatch:function(e){const t=e.some((e=>this.getConfig().customStandownPolicy?.urlRegex?.some((t=>!!e&&function(e,t){return new RegExp(t).test(e)}(e,t)))));return t&&this.logger.info("Custom Standown identified"),t},shouldStandDown:async function(e,t,r){ae(this.state.initialized);const i=new URL(t);if(!await this.state.partnerFilter(i.hostname))return this.logger.info("Should standdown due to partner filter."),{result:!0,reason:"partner filter"};if(this.getConfig().merchantExclusions.some((t=>t.mutePopups&&e===t.domain)))return this.logger.info("Should standdown due to merchant exclusions"),{result:!0,reason:"merchant exclusions"};const n=await this.state.giveFreelyFeedService.shouldStandDown(this.logger,e,t,r);return n.result&&this.logger.info(`Should standdown due to ${n.reason}`),n},updateStanddownHistory:function(e,t=null){return ae(this.state.initialized),X(e,void 0,t)},updateStanddownHistoryByMerchantId:function(e,t=null){return ae(this.state.initialized),this.state.giveFreelyFeedService.getActiveDomains().then((r=>{const i=r.find((t=>t.merchantId===e));if(i)return X(i.domain,void 0,t)}))},wasLastStandDownAnActivation:async function(e){return Z(e)}}),identity:Re};class $e{constructor(e){this.partnerApiKey=e,this.cleanupListeners=null,this.initialize=Ne.bind(this),this.isInitialized=He.bind(this),this.getConfig=Ge.config.getConfig.bind(this),this.getCachedConfig=Ge.config.getCachedConfig.bind(this),this.onConfigChange=Ge.config.onConfigChange.bind(this),this.onceConfigChange=Ge.config.onceConfigChange.bind(this),this.offConfigChange=Ge.config.offConfigChange.bind(this),this.getLogger=Ge.observability.getLogger.bind(this),this.healthCheck=Ge.observability.healthCheck.bind(this),this.trackEvent=Ge.observability.trackEvent.bind(this),this.getProviderPreActivation=Ge.identity.getProviderPreActivation.bind(this),this.initializePreActivation=Ge.identity.initializePreActivation.bind(this),this.upsertUser=Ge.identity.upsertUser.bind(this),this.getCurrentUser=Ge.identity.getCurrentUser.bind(this),this.getLanguage=Ge.identity.getLanguage.bind(this),this.getActiveDomains=Ge.merchants.getActiveDomains.bind(this),this.generateAffiliateUrl=Ge.merchants.generateAffiliateUrl.bind(this),this.shouldStandDown=Ge.standdown.shouldStandDown.bind(this),this.updateStanddownHistory=Ge.standdown.updateStanddownHistory.bind(this),this.updateStanddownHistoryByMerchantId=Ge.standdown.updateStanddownHistoryByMerchantId.bind(this),this.wasLastStandDownAnActivation=Ge.standdown.wasLastStandDownAnActivation.bind(this),this.hasAffiliation=Ge.standdown.hasAffiliation.bind(this),this.isCustomStandownMatch=Ge.standdown.isCustomStandownMatch.bind(this),this.dependencies={configService:new M(e)},this.logger=o.getInstance(),this.logger.configure({enabled:!0,title:"Background - GiveFreelyService"}),this.state=(e=>({initialized:!1,giveFreelyFeedService:null,partnerFilter:null,config:null,preActivation:null,analytics:null,giveFreelyUserService:null,partnerApiKey:e,healthCheck:null}))(e)}async destroy(){var e;this.logger.info("Destroying GiveFreelyService"),await Promise.all([this.dependencies.configService.clearCache(),this.state.giveFreelyUserService?.resetUser()]),this.cleanupListeners&&(this.cleanupListeners(),this.logger.info("Event listeners cleared."),this.cleanupListeners=null),this.state=(e=this.state,{...e,initialized:!1,giveFreelyFeedService:null,partnerFilter:null,analytics:null,config:null})}}exports.GiveFreelyService=class{constructor(e){this.partnerApiKey=e,this.initialize=e=>this._coreService.initialize(e),this.destroy=()=>this._coreService.destroy(),this._coreService=new $e(e)}},exports.browser=browser,exports.isGiveFreelyMessage=e=>oe.exists(e);
2
2
  //# sourceMappingURL=GiveFreely-background.cjs.js.map