lucia-sdk 0.9.10 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -1,2 +1,2 @@
1
- function e(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class t{constructor(e){this.store=e}log(e,...t){var n;(null===(n=this.store.config)||void 0===n?void 0:n.debug)&&console[e](t)}}const n="0.9.10";class i{constructor(e){this.requestQueue=[],this.isProcessingQueue=!1,this.initComplete=!1,this.store=e,this.baseURL=this.getBaseURL(),this.logger=new t(this.store)}getBaseURL(){const{config:e}=this.store;return(null==e?void 0:e.debugURL)?e.debugURL:(null==e?void 0:e.testENV)?"http://52.22.177.60/fk":"https://api.clickinsights.xyz"}get(t){return e(this,void 0,void 0,function*(){if(!this.store.config)return this.logger.log("error","Config is not set"),null;try{const e=yield fetch(`${this.baseURL}${t}`,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":n}});return yield e.json()}catch(e){this.logger.log("error",e)}return null})}post(t,n){return e(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;const i="/api/sdk/init"===e;if(!i&&!this.initComplete)return new Promise((r,o)=>{this.requestQueue.push({url:e,data:t,fireAndForget:n,resolve:r,reject:o,isInit:i}),this.processQueue()});if(i){const i=yield this.executePost(e,t,n);return this.initComplete=!0,yield this.processQueue(),i}return this.executePost(e,t,n)})}processQueue(){return e(this,void 0,void 0,function*(){if(!this.isProcessingQueue&&this.initComplete&&0!==this.requestQueue.length){this.isProcessingQueue=!0;try{const t=()=>e(this,void 0,void 0,function*(){if(0===this.requestQueue.length)return;const e=this.requestQueue.shift();try{const t=yield this.executePost(e.url,e.data,e.fireAndForget);e.resolve(t)}catch(t){e.reject(t)}yield t()});yield t()}finally{this.isProcessingQueue=!1}}})}executePost(t,i){return e(this,arguments,void 0,function*(e,t,i=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;if(i&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){try{const n=`${this.baseURL}${e}`,i=t&&"object"==typeof t&&!Array.isArray(t)?t:{payload:t},r=JSON.stringify(Object.assign(Object.assign({},i),{_apiKey:this.store.config.apiKey})),o=new Blob([r],{type:"application/json"});navigator.sendBeacon(n,o)||this.logger.log("error","sendBeacon failed")}catch(e){this.logger.log("error",e)}return null}try{const i=yield fetch(`${this.baseURL}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":n},body:JSON.stringify(t)});return yield i.json()}catch(e){this.logger.log("error",e)}return null})}}class r{static dispatch(e){Object.keys(e).forEach(t=>{if(Object.keys(r.store).includes(t)){const n=e[t];r.store[t]="object"==typeof n?Array.isArray(n)?[...n]:Object.assign({},n):n}})}}r.store={isInitialized:!1,config:null,session:null};const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));let s;const a=new Uint8Array(16);var l={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function c(e,t,n){const i=(e=e||{}).random??e.rng?.()??function(){if(!s){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");s=crypto.getRandomValues.bind(crypto)}return s(a)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}(i)}const u="luci_session",d=new t(r.store);function h(){try{const e=sessionStorage.getItem(u);return e?JSON.parse(e):null}catch(e){return d.log("error","Error retrieving session data:",e),null}}function g(){var e;const t={id:l.randomUUID&&!e?l.randomUUID():c(e),timestamp:Date.now()};return sessionStorage.setItem(u,JSON.stringify(t)),t}function f(){const e=localStorage.getItem("lid");return"undefined"===e||"null"===e?(localStorage.removeItem("lid"),null):e}function w(){const e=localStorage.getItem("luc_uid");return"undefined"===e||"null"===e?(localStorage.removeItem("luc_uid"),null):e}class m{constructor(e){this.store=r.store,this.dispatch=r.dispatch,this.dispatch({config:e}),this.httpClient=new i(this.store),this.logger=new t(this.store)}}class p{constructor(e,t,n,i){this.enabled=!1,this.sdkConfig=e,this.config=t,this.callback=n,this.logger=i}enable(){this.enabled||(this.enabled=!0,this.attachListeners(),this.logger.log("log",`${this.name}: Enabled`))}disable(){this.enabled&&(this.enabled=!1,this.logger.log("log",`${this.name}: Disabled`))}destroy(){this.disable(),this.detachListeners(),this.logger.log("log",`${this.name}: Destroyed`)}isEnabled(){return this.enabled}}const y=new class{constructor(){this.registrations=new Map,this.activeTrackers=new Map,this.logger=null}register(e){this.registrations.set(e.name,e)}initAll(e,t,n){this.logger=n;for(const[i,r]of this.registrations){const o=e[r.configKey],s=r.normalizeConfig(o);if(null===s)continue;const a=t[i];if(a)try{const t=r.factory(e,s,a,n);this.activeTrackers.set(i,t),t.enable(),n.log("log",`AutoTrackerRegistry: Initialized ${i}`)}catch(e){n.log("error",`AutoTrackerRegistry: Failed to initialize ${i}`,e)}else n.log("warn",`AutoTrackerRegistry: No callback registered for ${i}`)}}get(e){return this.activeTrackers.get(e)}enable(e){const t=this.activeTrackers.get(e);return!!t&&(t.enable(),!0)}disable(e){const t=this.activeTrackers.get(e);return!!t&&(t.disable(),!0)}destroyAll(){var e;for(const[t,n]of this.activeTrackers)try{n.destroy()}catch(n){null===(e=this.logger)||void 0===e||e.log("error",`AutoTrackerRegistry: Error destroying ${t}`,n)}this.activeTrackers.clear()}getRegisteredTrackers(){return Array.from(this.registrations.keys())}getActiveTrackers(){return Array.from(this.activeTrackers.keys())}reset(){this.destroyAll(),this.logger=null}},v=['input[type="password"]','input[type="text"][autocomplete*="cc-"]','input[type="text"][autocomplete*="card"]','input[type="text"][name*="card"]','input[type="text"][name*="cvv"]','input[type="text"][name*="cvc"]','input[name*="ssn"]','input[name*="social"]',"[data-sensitive]","[data-private]"],b=[/\b\d{3}-\d{2}-\d{4}\b/,/\b\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4}\b/,/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i];const k=new class{constructor(e=[]){this.sensitiveSelectors=[...v,...e]}isSensitive(e){if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;let t=e.parentElement;for(;t;){const e=t;if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;t=t.parentElement}return!1}containsSensitiveData(e){return!!e&&b.some(t=>t.test(e))}sanitizeText(e){if(!e)return"";let t=e;return t=t.replace(/\b\d{3}-\d{2}-\d{4}\b/g,"***-**-****"),t=t.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,"****-****-****-****"),t=t.replace(/\b([A-Z0-9._%+-]+)@([A-Z0-9.-]+\.[A-Z]{2,})\b/gi,"***@$2"),t}},C=["button","a[href]",'[role="button"]'],T=["[data-lucia-ignore]",'[data-lucia-track="false"]'];class A extends p{constructor(e,t,n,i){var r,o,s;super(e,{enabled:null===(r=t.enabled)||void 0===r||r,selectors:null!==(o=t.selectors)&&void 0!==o?o:C,ignore:null!==(s=t.ignore)&&void 0!==s?s:T},n,i),this.name="clicks",this.configKey="autoTrackClicks",this.debounceTimers=new Map,this.listenerAttached=!1,this.boundHandleClick=null,this.privacyGuard=k}attachListeners(){this.listenerAttached||("undefined"!=typeof document?(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,{passive:!0,capture:!1}),this.listenerAttached=!0,this.logger.log("log","ClickTracker: Delegated click listener attached")):this.logger.log("warn","ClickTracker: document not available, cannot attach listener"))}detachListeners(){this.listenerAttached&&this.boundHandleClick&&"undefined"!=typeof document&&(document.removeEventListener("click",this.boundHandleClick),this.listenerAttached=!1),this.debounceTimers.clear(),this.boundHandleClick=null}handleClick(e){if(!this.enabled)return;const t=e.target;if(!t)return;const n=this.findTrackableElement(t);if(!n)return;if(this.shouldIgnore(n))return void this.logger.log("log","ClickTracker: Element ignored",n);if(this.privacyGuard.isSensitive(n))return void this.logger.log("warn","ClickTracker: Sensitive element not tracked",n);if(this.isDebounced(n))return void this.logger.log("log","ClickTracker: Click debounced",n);const i=this.extractTrackingData(n);i&&(this.logger.log("log","ClickTracker: Tracking click",i),this.callback(i))}findTrackableElement(e){const t=this.config.selectors||C;try{const n=e.closest('[data-lucia-track]:not([data-lucia-track="false"])');if(n&&n!==document.body&&document.body.contains(n)){if(this.config.selectors&&this.config.selectors!==C){return t.some(e=>{try{return n.matches(e)}catch(e){return!1}})?n:null}return n}const i=t.join(", "),r=e.closest(i);return r&&r!==document.body&&document.body.contains(r)?r:null}catch(t){this.logger.log("warn","ClickTracker: Invalid combined selector, using fallback",t);let n=e;for(;n&&n!==document.body;){if(this.isTrackable(n))return n;n=n.parentElement}return null}}isTrackable(e){return(this.config.selectors||C).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid selector "${t}"`,e),!1}})}shouldIgnore(e){return(this.config.ignore||T).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid ignore selector "${t}"`,e),!1}})}isDebounced(e){const t=Date.now(),n=this.debounceTimers.get(e);return!!(n&&t-n<500)||(this.debounceTimers.set(e,t),this.debounceTimers.size>100&&this.cleanupDebounceTimers(),!1)}cleanupDebounceTimers(){const e=Date.now();Array.from(this.debounceTimers.entries()).forEach(([t,n])=>{e-n>1e3&&this.debounceTimers.delete(t)})}extractTrackingData(e){var t;const n=this.getElementIdentifier(e);if(!n)return this.logger.log("warn","ClickTracker: Could not generate identifier for element",e),null;const i={button:n,elementType:this.getElementType(e),timestamp:Date.now()},r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&(this.privacyGuard.containsSensitiveData(r)||(i.text=this.sanitizeText(r))),"a"===e.tagName.toLowerCase()?i.href=e.getAttribute("href"):i.href=null;const o=this.extractMetadata(e);return o&&Object.keys(o).length>0&&(i.meta=o),i}getElementIdentifier(e){var t;const n=e.getAttribute("data-lucia-track");if(n&&"false"!==n)return n;const i=e.getAttribute("id");if(i)return i;const r=e.getAttribute("name");if(r)return r;const o=e.getAttribute("aria-label");if(o)return o;if("a"===e.tagName.toLowerCase()){const t=e.getAttribute("href");if(t)return`link:${t}`}const s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(s)return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using text content as identifier for element. Consider adding data-lucia-track attribute.",e),`text:${this.sanitizeText(s).substring(0,50)}`;const a=this.generateCSSPath(e);return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using CSS path as identifier. Consider adding data-lucia-track attribute.",e),`path:${a}`}getElementType(e){const t=e.tagName.toLowerCase();if("a"===t)return"link";if("button"===t)return"button";const n=e.getAttribute("role");return n||t}sanitizeText(e){return e.trim().replace(/\s+/g," ").substring(0,100)}generateCSSPath(e){const t=[];let n=e;for(;n&&n!==document.body&&t.length<5;){let e=n.tagName.toLowerCase();if(n.id){e+=`#${n.id}`,t.unshift(e);break}const i=n.getAttribute("class");if(i){const t=i.trim().split(/\s+/).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}t.unshift(e),n=n.parentElement}return t.join(" > ")}extractMetadata(e){const t={},{attributes:n}=e;return Array.from(n).forEach(e=>{if(e.name.startsWith("data-lucia-meta-")){const n=e.name.replace("data-lucia-meta-","").replace(/-([a-z])/g,e=>e[1].toUpperCase());t[n]=e.value}}),Object.keys(t).length>0?t:null}}const S={name:"clicks",configKey:"autoTrackClicks",factory:(e,t,n,i)=>new A(e,t,n,i),normalizeConfig:function(e){return void 0===e||!1===e?null:!0===e?{enabled:!0}:!1===e.enabled?null:e}},I=new t(r.store);function P(){return e(this,void 0,void 0,function*(){try{const{ethereum:e}=window;if(!(null==e?void 0:e.request))return null;const t=yield e.request({method:"eth_accounts"});return t&&t.length>0?t[0]:null}catch(e){return I.log("error","Error checking connected wallet:",e),null}})}function E(){return e(this,void 0,void 0,function*(){try{if(!window.ethereum)return null;if(window.ethereum.isMetaMask)return"MetaMask";if(!window.ethereum.request)return null;return(yield window.ethereum.request({method:"wallet_getName"}))||null}catch(e){return I.log("error","Error getting wallet name:",e),null}})}function O(){return e(this,void 0,void 0,function*(){if(!window.ethereum)return null;const e={isMetaMask:!!window.ethereum.isMetaMask,isCoinbaseWallet:!!window.ethereum.isCoinbaseWallet||!!window.ethereum.isCoinbase,isWalletConnect:!!window.ethereum.isWalletConnect,isTrust:!!window.ethereum.isTrust||!!window.ethereum.isTrustWallet,isImToken:!!window.ethereum.isImToken,isBraveWallet:!!window.ethereum.isBraveWallet,isTokenPocket:!!window.ethereum.isTokenPocket,isStatus:!!window.ethereum.isStatus,isTally:!(!window.ethereum.isTally&&!window.ethereum.isTallyWallet),isAlphaWallet:!!window.ethereum.isAlphaWallet,isOpera:!!window.ethereum.isOpera,isCoin98:!!window.ethereum.isCoin98,isMathWallet:!!window.ethereum.isMathWallet,isOneInch:!(!window.ethereum.isOneInchIOSWallet&&!window.ethereum.isOneInchAndroidWallet),isRainbow:!!window.ethereum.isRainbow,isBinanceChainWallet:!1,isFrame:!!window.ethereum.isFrame,userAgent:window.navigator.userAgent,chainId:window.ethereum.chainId||void 0,networkVersion:window.ethereum.networkVersion||void 0,name:""};return Object.values(e).some(Boolean)||(Object.prototype.hasOwnProperty.call(window.ethereum,"_metamask")&&(e.isMetaMask=!0),window.BinanceChain&&(e.isBinanceChainWallet=!0),window.ethereum.isFrame&&(e.isFrame=!0),"function"==typeof window.ethereum.request&&void 0===window.ethereum._metamask&&(e.isPossiblyGenericInjectedProvider=!0)),e.name=function(e){if(e.isMetaMask)return"MetaMask";if(e.isCoinbaseWallet)return"Coinbase Wallet";if(e.isWalletConnect)return"WalletConnect";if(e.isTrust)return"Trust Wallet";if(e.isImToken)return"imToken";if(e.isBraveWallet)return"Brave Wallet";if(e.isTokenPocket)return"TokenPocket";if(e.isStatus)return"Status";if(e.isTally)return"Tally";if(e.isAlphaWallet)return"AlphaWallet";if(e.isOpera)return"Opera";if(e.isCoin98)return"Coin98";if(e.isMathWallet)return"MathWallet";if(e.isOneInch)return"1inch Wallet";if(e.isRainbow)return"Rainbow";if(e.isBinanceChainWallet)return"Binance Chain Wallet";if(e.isFrame)return"Frame";const t=e.userAgent.toLowerCase();return t.includes("trust")?"Trust Wallet (UA)":t.includes("rainbow")?"Rainbow (UA)":"Unknown Provider"}(e),e})}const x=new t(r.store);function W(){return e(this,void 0,void 0,function*(){var e,t,n;try{if(window.solana){if(window.solana.isConnected&&window.solana.publicKey)return window.solana.publicKey.toString()}else if(window.solflare){if(window.solflare.isConnected&&window.solflare.publicKey)return window.solflare.publicKey.toString()}else if(null===(e=window.phantom)||void 0===e?void 0:e.solana)try{if((yield window.phantom.solana.connect({onlyIfTrusted:!0}))&&window.phantom.solana.publicKey)return window.phantom.solana.publicKey.toString()}catch(e){x.log("error","Error silently connecting to Phantom wallet:",e)}const i=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&i.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&i.push(window.SolanaWalletAdapterContext.current);const r=i.find(e=>e.connected&&e.publicKey);return r?r.publicKey.toString():null}catch(e){return x.log("error","Error detecting Solana wallet:",e),null}})}function j(){return e(this,void 0,void 0,function*(){var e,t,n;const i=yield W();if(!i)return null;if(null===(e=window.phantom)||void 0===e?void 0:e.solana)return"Phantom";if(window.solflare)return"Solflare";const r=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&r.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&r.push(window.SolanaWalletAdapterContext.current);const o=r.find(e=>e.connected&&e.publicKey&&e.publicKey.toString()===i);return o?o.name||"Unknown Wallet":null})}function D(){return e(this,void 0,void 0,function*(){if(K)return K;const e={device:{cores:U(()=>navigator.hardwareConcurrency),memory:U(()=>navigator.deviceMemory),cpuClass:U(()=>navigator.cpuClass),touch:N(),devicePixelRatio:U(()=>window.devicePixelRatio)},screen:{width:U(()=>window.screen.width),height:U(()=>window.screen.height),colorDepth:U(()=>window.screen.colorDepth),availHeight:U(()=>window.screen.availHeight),availWidth:U(()=>window.screen.availWidth),orientation:{type:U(()=>window.screen.orientation.type),angle:U(()=>window.screen.orientation.angle)}},browser:{language:U(()=>navigator.language),encoding:U(()=>TextDecoder.encoding),timezone:U(()=>-(new Date).getTimezoneOffset()/60),pluginsLength:U(()=>navigator.plugins.length),pluginNames:U(()=>Array.from(navigator.plugins,e=>e.name)),applePayAvailable:_(),uniqueHash:yield $(),colorGamut:B(),contrastPreference:q()},permissions:{navPer:U(()=>navigator.permissions.webglVersion),renderedPer:U(()=>navigator.permissions.RENDERER),geoPer:U(()=>navigator.permissions.geolocation)},storage:{localStorage:U(()=>!!window.localStorage),indexedDB:U(()=>!!window.indexedDB),openDB:U(()=>window.openDatabase)}};return K=e,e})}function R(){return e(this,void 0,void 0,function*(){const[e,t,n,i,r]=yield Promise.all([W(),P(),E(),j(),O()]);return{walletAddress:t,solanaAddress:e,providerInfo:r&&L(r),walletName:n,solWalletName:i}})}function M(){const e=new URL(window.location.href).searchParams,t={};return e.forEach((e,n)=>{(n.startsWith("utm_")||n.includes("id")||"ref"===n||"source"===n)&&(t[n]=e)}),t}function U(e,t){try{return e()}catch(e){return t}}function L(e){const t={};return Object.keys(e).forEach(n=>{const i=n;e[i]&&(t[i]=e[i])}),t}let K=null;function $(){return e(this,void 0,void 0,function*(){try{const t=document.createElement("canvas"),n=t.getContext("2d",{willReadFrequently:!0});if(!n)return;const i=200,r=120;t.width=i,t.height=r,t.style.width=`${i}px`,t.style.height=`${r}px`,n.fillStyle="#ffffff",n.fillRect(0,0,i,r),n.fillStyle="#ff00ff",n.fillRect(10,10,100,100),n.fillStyle="#00ffff",n.beginPath(),n.arc(150,50,40,0,2*Math.PI,!0),n.fill();const{data:o}=n.getImageData(0,0,i,r);return function(t){return e(this,void 0,void 0,function*(){const e=(new TextEncoder).encode(t),n=yield crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")})}([[20,20],[60,60],[100,100],[150,50],[150,60],[140,50],[5,5]].map(([e,t])=>{const n=4*(t*i+e);return`${o[n]},${o[n+1]},${o[n+2]},${o[n+3]};`}).join(""))}catch(e){return}})}function N(){try{return!!document.createEvent("TouchEvent")}catch(e){return!1}}function _(){var e;try{return"function"==typeof(null===(e=window.ApplePaySession)||void 0===e?void 0:e.canMakePayments)&&window.ApplePaySession.canMakePayments()}catch(e){return}}function q(){try{const{matchMedia:e}=window,t=t=>e(`(prefers-contrast: ${t})`).matches;return t("no-preference")?"None":t("high")||t("more")?"More":t("low")||t("less")?"Less":t("forced")?"ForcedColors":void 0}catch(e){return}}function B(){try{return["rec2020","p3","srgb","display-p3","adobe-rgb"].filter(e=>window.matchMedia(`(color-gamut: ${e})`).matches)}catch(e){return[]}}y.register(S);let z=class extends m{authenticate(){this.httpClient.post("/api/key/auth",{})}init(){return e(this,void 0,void 0,function*(){let e=h();e||(e=g());const t=yield D(),n=new URL(window.location.href).searchParams.get("lucia"),i=yield R(),r={id:e.id};e.hash&&(r.hash=e.hash);const o=yield this.httpClient.post("/api/sdk/init",{user:{name:w()},data:t,walletData:i,session:r,redirectHash:n,utm:M()},!1);o&&(o.lid&&localStorage.setItem("lid",o.lid),o.session&&function(e){const t={id:e.id,hash:e.hash,timestamp:Date.now()};sessionStorage.setItem(u,JSON.stringify(t))}(o.session)),y.initAll(this.store.config,{clicks:this.handleAutoTrackedClick.bind(this)},this.logger)})}handleAutoTrackedClick(e){const t=e,n={elementType:t.elementType,text:t.text,href:t.href,meta:t.meta};this.buttonClick(t.button,n)}userInfo(t,n){return e(this,void 0,void 0,function*(){const e=f(),i=h();t&&localStorage.setItem("luc_uid",t);const r=Object.assign({user:{name:t,userInfo:n},session:i},e&&{lid:e});yield this.httpClient.post("/api/sdk/user",r)})}pageView(t){return e(this,void 0,void 0,function*(){const e=f(),n=h(),i=Object.assign({page:t,user:{name:w()},session:n},e&&{lid:e});yield this.httpClient.post("/api/sdk/page",i)})}trackConversion(t,n,i){return e(this,void 0,void 0,function*(){const e=f(),r=h(),o=Object.assign({tag:t,amount:n,event:i,user:{name:w()},session:r},e&&{lid:e});yield this.httpClient.post("/api/sdk/conversion",o)})}buttonClick(t,n){return e(this,void 0,void 0,function*(){const e=f(),i=h(),r=Object.assign(Object.assign({button:t,user:{name:w()},session:i},e&&{lid:e}),n&&Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n.elementType&&{elementType:n.elementType}),n.text&&{text:n.text}),void 0!==n.href&&{href:n.href}),n.meta&&{meta:n.meta}),{timestamp:Date.now()}));yield this.httpClient.post("/api/sdk/click",r)})}sendWalletInfo(t,n,i){return e(this,void 0,void 0,function*(){const e=f(),r=h(),o=Object.assign({walletAddress:t,chainId:n,walletName:i,user:{name:w()},session:r},e&&{lid:e});yield this.httpClient.post("/api/sdk/wallet",o)})}trackUserAcquisition(t){return e(this,arguments,void 0,function*(e,t={}){const n=yield D(),i=M(),r=h();yield this.httpClient.post("/api/sdk/acquisition",{user:{name:e},session:r,data:Object.assign({timestamp:(new Date).toISOString(),browserData:n,utmParams:i},t)})})}checkMetaMaskConnection(){var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))}destroy(){y.destroyAll()}},V=null;const Q=()=>{const e=V||"undefined"!=typeof window&&window.__luciaInitPromise;if(!e)throw new Error("LuciaSDK not initialized. Please call LuciaSDK.init() first");return e},F=()=>{const e=V||"undefined"!=typeof window&&window.__luciaInitPromise;e&&e.then(e=>e.destroy()).catch(()=>{}),V=null,"undefined"!=typeof window&&delete window.__luciaInitPromise,y.reset()},H={init:t=>{if("undefined"==typeof window)return Promise.reject(new Error("LuciaSDK requires a browser environment"));if(V)return V;if(window.__luciaInitPromise)return V=window.__luciaInitPromise,V;if(!(null==t?void 0:t.apiKey))return Promise.reject(new Error("apiKey is required in config"));const n=e(void 0,void 0,void 0,function*(){const e=new z(t);return yield e.init(),e});return V=n,window.__luciaInitPromise=n,n},userInfo:(t,n)=>e(void 0,void 0,void 0,function*(){return(yield Q()).userInfo(t,n)}),pageView:t=>e(void 0,void 0,void 0,function*(){return(yield Q()).pageView(t)}),trackConversion:(t,n,i)=>e(void 0,void 0,void 0,function*(){return(yield Q()).trackConversion(t,n,i)}),buttonClick:(t,n)=>e(void 0,void 0,void 0,function*(){return(yield Q()).buttonClick(t,n)}),sendWalletInfo:(t,n,i)=>e(void 0,void 0,void 0,function*(){return(yield Q()).sendWalletInfo(t,n,i)}),trackUserAcquisition:(t,...n)=>e(void 0,[t,...n],void 0,function*(e,t={}){return(yield Q()).trackUserAcquisition(e,t)}),checkMetaMaskConnection:()=>{var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))},VERSION:n};if("undefined"!=typeof window){window.LuciaSDK=H;const e=()=>{const e=document.currentScript||document.querySelector("script[data-api-key]"),t=null==e?void 0:e.getAttribute("data-api-key");if(!t)return;const n=e.getAttribute("data-debug-url"),i=e.getAttribute("data-auto-track-clicks"),r=e.getAttribute("data-track-selectors");H.init(Object.assign(Object.assign(Object.assign({apiKey:t},n&&{debugURL:n}),"true"===i&&{autoTrackClicks:!r||{enabled:!0,selectors:r.split(",").map(e=>e.trim())}}),"false"===i&&{autoTrackClicks:!1})).catch(e=>console.error("LuciaSDK auto-init failed:",e))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}export{F as __resetInstance,H as default,L as filterObject,_ as getApplePayAvailable,D as getBrowserData,$ as getCanvasFingerprint,B as getColorGamut,q as getContrastPreference,M as getUtmParams,R as getWalletData,N as isTouchEnabled,U as safeAccess};
1
+ function e(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class t{constructor(e){this.store=e}log(e,...t){var n;(null===(n=this.store.config)||void 0===n?void 0:n.debug)&&console[e](t)}}const n="0.9.12";class i{constructor(e){this.requestQueue=[],this.isProcessingQueue=!1,this.initComplete=!1,this.store=e,this.baseURL=this.getBaseURL(),this.logger=new t(this.store)}getBaseURL(){const{config:e}=this.store;return(null==e?void 0:e.debugURL)?e.debugURL:(null==e?void 0:e.testENV)?"http://52.22.177.60/fk":"https://api.clickinsights.xyz"}get(t){return e(this,void 0,void 0,function*(){if(!this.store.config)return this.logger.log("error","Config is not set"),null;try{const e=yield fetch(`${this.baseURL}${t}`,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":n}});return yield e.json()}catch(e){this.logger.log("error",e)}return null})}post(t,n){return e(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;const i="/api/sdk/init"===e;if(!i&&!this.initComplete)return new Promise((r,o)=>{this.requestQueue.push({url:e,data:t,fireAndForget:n,resolve:r,reject:o,isInit:i}),this.processQueue()});if(i){const i=yield this.executePost(e,t,n);return this.initComplete=!0,yield this.processQueue(),i}return this.executePost(e,t,n)})}processQueue(){return e(this,void 0,void 0,function*(){if(!this.isProcessingQueue&&this.initComplete&&0!==this.requestQueue.length){this.isProcessingQueue=!0;try{const t=()=>e(this,void 0,void 0,function*(){if(0===this.requestQueue.length)return;const e=this.requestQueue.shift();try{const t=yield this.executePost(e.url,e.data,e.fireAndForget);e.resolve(t)}catch(t){e.reject(t)}yield t()});yield t()}finally{this.isProcessingQueue=!1}}})}executePost(t,i){return e(this,arguments,void 0,function*(e,t,i=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;if(i&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){try{const n=`${this.baseURL}${e}`,i=t&&"object"==typeof t&&!Array.isArray(t)?t:{payload:t},r=JSON.stringify(Object.assign(Object.assign({},i),{_apiKey:this.store.config.apiKey})),o=new Blob([r],{type:"application/json"});navigator.sendBeacon(n,o)||this.logger.log("error","sendBeacon failed")}catch(e){this.logger.log("error",e)}return null}try{const i=yield fetch(`${this.baseURL}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":n},body:JSON.stringify(t)});return yield i.json()}catch(e){this.logger.log("error",e)}return null})}}class r{static dispatch(e){Object.keys(e).forEach(t=>{if(Object.keys(r.store).includes(t)){const n=e[t];r.store[t]="object"==typeof n?Array.isArray(n)?[...n]:Object.assign({},n):n}})}}r.store={isInitialized:!1,config:null,session:null};const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));let s;const a=new Uint8Array(16);var l={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function c(e,t,n){const i=(e=e||{}).random??e.rng?.()??function(){if(!s){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");s=crypto.getRandomValues.bind(crypto)}return s(a)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}(i)}const u="luci_session",d=new t(r.store);function h(){try{const e=sessionStorage.getItem(u);return e?JSON.parse(e):null}catch(e){return d.log("error","Error retrieving session data:",e),null}}function g(){var e;const t={id:l.randomUUID&&!e?l.randomUUID():c(e),timestamp:Date.now()};return sessionStorage.setItem(u,JSON.stringify(t)),t}function f(){const e=localStorage.getItem("lid");return"undefined"===e||"null"===e?(localStorage.removeItem("lid"),null):e}function w(){const e=localStorage.getItem("luc_uid");return"undefined"===e||"null"===e?(localStorage.removeItem("luc_uid"),null):e}class m{constructor(e){this.store=r.store,this.dispatch=r.dispatch,this.dispatch({config:e}),this.httpClient=new i(this.store),this.logger=new t(this.store)}}class p{constructor(e,t,n,i){this.enabled=!1,this.sdkConfig=e,this.config=t,this.callback=n,this.logger=i}enable(){this.enabled||(this.enabled=!0,this.attachListeners(),this.logger.log("log",`${this.name}: Enabled`))}disable(){this.enabled&&(this.enabled=!1,this.logger.log("log",`${this.name}: Disabled`))}destroy(){this.disable(),this.detachListeners(),this.logger.log("log",`${this.name}: Destroyed`)}isEnabled(){return this.enabled}}const y=new class{constructor(){this.registrations=new Map,this.activeTrackers=new Map,this.logger=null}register(e){this.registrations.set(e.name,e)}initAll(e,t,n){this.logger=n;for(const[i,r]of this.registrations){const o=e[r.configKey],s=r.normalizeConfig(o);if(null===s)continue;const a=t[i];if(a)try{const t=r.factory(e,s,a,n);this.activeTrackers.set(i,t),t.enable(),n.log("log",`AutoTrackerRegistry: Initialized ${i}`)}catch(e){n.log("error",`AutoTrackerRegistry: Failed to initialize ${i}`,e)}else n.log("warn",`AutoTrackerRegistry: No callback registered for ${i}`)}}get(e){return this.activeTrackers.get(e)}enable(e){const t=this.activeTrackers.get(e);return!!t&&(t.enable(),!0)}disable(e){const t=this.activeTrackers.get(e);return!!t&&(t.disable(),!0)}destroyAll(){var e;for(const[t,n]of this.activeTrackers)try{n.destroy()}catch(n){null===(e=this.logger)||void 0===e||e.log("error",`AutoTrackerRegistry: Error destroying ${t}`,n)}this.activeTrackers.clear()}getRegisteredTrackers(){return Array.from(this.registrations.keys())}getActiveTrackers(){return Array.from(this.activeTrackers.keys())}reset(){this.destroyAll(),this.logger=null}},v=['input[type="password"]','input[type="text"][autocomplete*="cc-"]','input[type="text"][autocomplete*="card"]','input[type="text"][name*="card"]','input[type="text"][name*="cvv"]','input[type="text"][name*="cvc"]','input[name*="ssn"]','input[name*="social"]',"[data-sensitive]","[data-private]"],b=[/\b\d{3}-\d{2}-\d{4}\b/,/\b\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4}\b/,/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i];const k=new class{constructor(e=[]){this.sensitiveSelectors=[...v,...e]}isSensitive(e){if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;let t=e.parentElement;for(;t;){const e=t;if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;t=t.parentElement}return!1}containsSensitiveData(e){return!!e&&b.some(t=>t.test(e))}sanitizeText(e){if(!e)return"";let t=e;return t=t.replace(/\b\d{3}-\d{2}-\d{4}\b/g,"***-**-****"),t=t.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,"****-****-****-****"),t=t.replace(/\b([A-Z0-9._%+-]+)@([A-Z0-9.-]+\.[A-Z]{2,})\b/gi,"***@$2"),t}},C=["button","a[href]",'[role="button"]'],T=["[data-lucia-ignore]",'[data-lucia-track="false"]'];class A extends p{constructor(e,t,n,i){var r,o,s;super(e,{enabled:null===(r=t.enabled)||void 0===r||r,selectors:null!==(o=t.selectors)&&void 0!==o?o:C,ignore:null!==(s=t.ignore)&&void 0!==s?s:T},n,i),this.name="clicks",this.configKey="autoTrackClicks",this.debounceTimers=new Map,this.listenerAttached=!1,this.boundHandleClick=null,this.privacyGuard=k}attachListeners(){this.listenerAttached||("undefined"!=typeof document?(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,{passive:!0,capture:!1}),this.listenerAttached=!0,this.logger.log("log","ClickTracker: Delegated click listener attached")):this.logger.log("warn","ClickTracker: document not available, cannot attach listener"))}detachListeners(){this.listenerAttached&&this.boundHandleClick&&"undefined"!=typeof document&&(document.removeEventListener("click",this.boundHandleClick),this.listenerAttached=!1),this.debounceTimers.clear(),this.boundHandleClick=null}handleClick(e){if(!this.enabled)return;const t=e.target;if(!t)return;const n=this.findTrackableElement(t);if(!n)return;if(this.shouldIgnore(n))return void this.logger.log("log","ClickTracker: Element ignored",n);if(this.privacyGuard.isSensitive(n))return void this.logger.log("warn","ClickTracker: Sensitive element not tracked",n);if(this.isDebounced(n))return void this.logger.log("log","ClickTracker: Click debounced",n);const i=this.extractTrackingData(n);i&&(this.logger.log("log","ClickTracker: Tracking click",i),this.callback(i))}findTrackableElement(e){const t=this.config.selectors||C;try{const n=e.closest('[data-lucia-track]:not([data-lucia-track="false"])');if(n&&n!==document.body&&document.body.contains(n)){if(this.config.selectors&&this.config.selectors!==C){return t.some(e=>{try{return n.matches(e)}catch(e){return!1}})?n:null}return n}const i=t.join(", "),r=e.closest(i);return r&&r!==document.body&&document.body.contains(r)?r:null}catch(t){this.logger.log("warn","ClickTracker: Invalid combined selector, using fallback",t);let n=e;for(;n&&n!==document.body;){if(this.isTrackable(n))return n;n=n.parentElement}return null}}isTrackable(e){return(this.config.selectors||C).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid selector "${t}"`,e),!1}})}shouldIgnore(e){return(this.config.ignore||T).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid ignore selector "${t}"`,e),!1}})}isDebounced(e){const t=Date.now(),n=this.debounceTimers.get(e);return!!(n&&t-n<500)||(this.debounceTimers.set(e,t),this.debounceTimers.size>100&&this.cleanupDebounceTimers(),!1)}cleanupDebounceTimers(){const e=Date.now();Array.from(this.debounceTimers.entries()).forEach(([t,n])=>{e-n>1e3&&this.debounceTimers.delete(t)})}extractTrackingData(e){var t;const n=this.getElementIdentifier(e);if(!n)return this.logger.log("warn","ClickTracker: Could not generate identifier for element",e),null;const i={button:n,elementType:this.getElementType(e),timestamp:Date.now()},r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&(this.privacyGuard.containsSensitiveData(r)||(i.text=this.sanitizeText(r))),"a"===e.tagName.toLowerCase()?i.href=e.getAttribute("href"):i.href=null;const o=this.extractMetadata(e);return o&&Object.keys(o).length>0&&(i.meta=o),i}getElementIdentifier(e){var t;const n=e.getAttribute("data-lucia-track");if(n&&"false"!==n)return n;const i=e.getAttribute("id");if(i)return i;const r=e.getAttribute("name");if(r)return r;const o=e.getAttribute("aria-label");if(o)return o;if("a"===e.tagName.toLowerCase()){const t=e.getAttribute("href");if(t)return`link:${t}`}const s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(s)return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using text content as identifier for element. Consider adding data-lucia-track attribute.",e),`text:${this.sanitizeText(s).substring(0,50)}`;const a=this.generateCSSPath(e);return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using CSS path as identifier. Consider adding data-lucia-track attribute.",e),`path:${a}`}getElementType(e){const t=e.tagName.toLowerCase();if("a"===t)return"link";if("button"===t)return"button";const n=e.getAttribute("role");return n||t}sanitizeText(e){return e.trim().replace(/\s+/g," ").substring(0,100)}generateCSSPath(e){const t=[];let n=e;for(;n&&n!==document.body&&t.length<5;){let e=n.tagName.toLowerCase();if(n.id){e+=`#${n.id}`,t.unshift(e);break}const i=n.getAttribute("class");if(i){const t=i.trim().split(/\s+/).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}t.unshift(e),n=n.parentElement}return t.join(" > ")}extractMetadata(e){const t={},{attributes:n}=e;return Array.from(n).forEach(e=>{if(e.name.startsWith("data-lucia-meta-")){const n=e.name.replace("data-lucia-meta-","").replace(/-([a-z])/g,e=>e[1].toUpperCase());t[n]=e.value}}),Object.keys(t).length>0?t:null}}const S={name:"clicks",configKey:"autoTrackClicks",factory:(e,t,n,i)=>new A(e,t,n,i),normalizeConfig:function(e){return void 0===e||!1===e?null:!0===e?{enabled:!0}:!1===e.enabled?null:e}},I=new t(r.store);function P(){return e(this,void 0,void 0,function*(){try{const{ethereum:e}=window;if(!(null==e?void 0:e.request))return null;const t=yield e.request({method:"eth_accounts"});return t&&t.length>0?t[0]:null}catch(e){return I.log("error","Error checking connected wallet:",e),null}})}function E(){return e(this,void 0,void 0,function*(){try{if(!window.ethereum)return null;if(window.ethereum.isMetaMask)return"MetaMask";if(!window.ethereum.request)return null;return(yield window.ethereum.request({method:"wallet_getName"}))||null}catch(e){return I.log("error","Error getting wallet name:",e),null}})}function O(){return e(this,void 0,void 0,function*(){if(!window.ethereum)return null;const e={isMetaMask:!!window.ethereum.isMetaMask,isCoinbaseWallet:!!window.ethereum.isCoinbaseWallet||!!window.ethereum.isCoinbase,isWalletConnect:!!window.ethereum.isWalletConnect,isTrust:!!window.ethereum.isTrust||!!window.ethereum.isTrustWallet,isImToken:!!window.ethereum.isImToken,isBraveWallet:!!window.ethereum.isBraveWallet,isTokenPocket:!!window.ethereum.isTokenPocket,isStatus:!!window.ethereum.isStatus,isTally:!(!window.ethereum.isTally&&!window.ethereum.isTallyWallet),isAlphaWallet:!!window.ethereum.isAlphaWallet,isOpera:!!window.ethereum.isOpera,isCoin98:!!window.ethereum.isCoin98,isMathWallet:!!window.ethereum.isMathWallet,isOneInch:!(!window.ethereum.isOneInchIOSWallet&&!window.ethereum.isOneInchAndroidWallet),isRainbow:!!window.ethereum.isRainbow,isBinanceChainWallet:!1,isFrame:!!window.ethereum.isFrame,userAgent:window.navigator.userAgent,chainId:window.ethereum.chainId||void 0,networkVersion:window.ethereum.networkVersion||void 0,name:""};return Object.values(e).some(Boolean)||(Object.prototype.hasOwnProperty.call(window.ethereum,"_metamask")&&(e.isMetaMask=!0),window.BinanceChain&&(e.isBinanceChainWallet=!0),window.ethereum.isFrame&&(e.isFrame=!0),"function"==typeof window.ethereum.request&&void 0===window.ethereum._metamask&&(e.isPossiblyGenericInjectedProvider=!0)),e.name=function(e){if(e.isMetaMask)return"MetaMask";if(e.isCoinbaseWallet)return"Coinbase Wallet";if(e.isWalletConnect)return"WalletConnect";if(e.isTrust)return"Trust Wallet";if(e.isImToken)return"imToken";if(e.isBraveWallet)return"Brave Wallet";if(e.isTokenPocket)return"TokenPocket";if(e.isStatus)return"Status";if(e.isTally)return"Tally";if(e.isAlphaWallet)return"AlphaWallet";if(e.isOpera)return"Opera";if(e.isCoin98)return"Coin98";if(e.isMathWallet)return"MathWallet";if(e.isOneInch)return"1inch Wallet";if(e.isRainbow)return"Rainbow";if(e.isBinanceChainWallet)return"Binance Chain Wallet";if(e.isFrame)return"Frame";const t=e.userAgent.toLowerCase();return t.includes("trust")?"Trust Wallet (UA)":t.includes("rainbow")?"Rainbow (UA)":"Unknown Provider"}(e),e})}const x=new t(r.store);function W(){return e(this,void 0,void 0,function*(){var e,t,n;try{if(window.solana){if(window.solana.isConnected&&window.solana.publicKey)return window.solana.publicKey.toString()}else if(window.solflare){if(window.solflare.isConnected&&window.solflare.publicKey)return window.solflare.publicKey.toString()}else if(null===(e=window.phantom)||void 0===e?void 0:e.solana)try{if((yield window.phantom.solana.connect({onlyIfTrusted:!0}))&&window.phantom.solana.publicKey)return window.phantom.solana.publicKey.toString()}catch(e){x.log("error","Error silently connecting to Phantom wallet:",e)}const i=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&i.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&i.push(window.SolanaWalletAdapterContext.current);const r=i.find(e=>e.connected&&e.publicKey);return r?r.publicKey.toString():null}catch(e){return x.log("error","Error detecting Solana wallet:",e),null}})}function j(){return e(this,void 0,void 0,function*(){var e,t,n;const i=yield W();if(!i)return null;if(null===(e=window.phantom)||void 0===e?void 0:e.solana)return"Phantom";if(window.solflare)return"Solflare";const r=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&r.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&r.push(window.SolanaWalletAdapterContext.current);const o=r.find(e=>e.connected&&e.publicKey&&e.publicKey.toString()===i);return o?o.name||"Unknown Wallet":null})}function D(){return e(this,void 0,void 0,function*(){if(K)return K;const e={device:{cores:U(()=>navigator.hardwareConcurrency),memory:U(()=>navigator.deviceMemory),cpuClass:U(()=>navigator.cpuClass),touch:N(),devicePixelRatio:U(()=>window.devicePixelRatio)},screen:{width:U(()=>window.screen.width),height:U(()=>window.screen.height),colorDepth:U(()=>window.screen.colorDepth),availHeight:U(()=>window.screen.availHeight),availWidth:U(()=>window.screen.availWidth),orientation:{type:U(()=>window.screen.orientation.type),angle:U(()=>window.screen.orientation.angle)}},browser:{language:U(()=>navigator.language),encoding:U(()=>TextDecoder.encoding),timezone:U(()=>-(new Date).getTimezoneOffset()/60),pluginsLength:U(()=>navigator.plugins.length),pluginNames:U(()=>Array.from(navigator.plugins,e=>e.name)),applePayAvailable:_(),uniqueHash:yield $(),colorGamut:B(),contrastPreference:q()},permissions:{navPer:U(()=>navigator.permissions.webglVersion),renderedPer:U(()=>navigator.permissions.RENDERER),geoPer:U(()=>navigator.permissions.geolocation)},storage:{localStorage:U(()=>!!window.localStorage),indexedDB:U(()=>!!window.indexedDB),openDB:U(()=>window.openDatabase)}};return K=e,e})}function R(){return e(this,void 0,void 0,function*(){const[e,t,n,i,r]=yield Promise.all([W(),P(),E(),j(),O()]);return{walletAddress:t,solanaAddress:e,providerInfo:r&&L(r),walletName:n,solWalletName:i}})}function M(){const e=new URL(window.location.href).searchParams,t={};return e.forEach((e,n)=>{(n.startsWith("utm_")||n.includes("id")||"ref"===n||"source"===n)&&(t[n]=e)}),t}function U(e,t){try{return e()}catch(e){return t}}function L(e){const t={};return Object.keys(e).forEach(n=>{const i=n;e[i]&&(t[i]=e[i])}),t}let K=null;function $(){return e(this,void 0,void 0,function*(){try{const t=document.createElement("canvas"),n=t.getContext("2d",{willReadFrequently:!0});if(!n)return;const i=200,r=120;t.width=i,t.height=r,t.style.width=`${i}px`,t.style.height=`${r}px`,n.fillStyle="#ffffff",n.fillRect(0,0,i,r),n.fillStyle="#ff00ff",n.fillRect(10,10,100,100),n.fillStyle="#00ffff",n.beginPath(),n.arc(150,50,40,0,2*Math.PI,!0),n.fill();const{data:o}=n.getImageData(0,0,i,r);return function(t){return e(this,void 0,void 0,function*(){const e=(new TextEncoder).encode(t),n=yield crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")})}([[20,20],[60,60],[100,100],[150,50],[150,60],[140,50],[5,5]].map(([e,t])=>{const n=4*(t*i+e);return`${o[n]},${o[n+1]},${o[n+2]},${o[n+3]};`}).join(""))}catch(e){return}})}function N(){try{return!!document.createEvent("TouchEvent")}catch(e){return!1}}function _(){var e;try{return"function"==typeof(null===(e=window.ApplePaySession)||void 0===e?void 0:e.canMakePayments)&&window.ApplePaySession.canMakePayments()}catch(e){return}}function q(){try{const{matchMedia:e}=window,t=t=>e(`(prefers-contrast: ${t})`).matches;return t("no-preference")?"None":t("high")||t("more")?"More":t("low")||t("less")?"Less":t("forced")?"ForcedColors":void 0}catch(e){return}}function B(){try{return["rec2020","p3","srgb","display-p3","adobe-rgb"].filter(e=>window.matchMedia(`(color-gamut: ${e})`).matches)}catch(e){return[]}}y.register(S);let z=class extends m{authenticate(){this.httpClient.post("/api/key/auth",{})}init(){return e(this,void 0,void 0,function*(){let e=h();e||(e=g());const t=yield D(),n=new URL(window.location.href).searchParams.get("lucia"),i=yield R(),r={id:e.id};e.hash&&(r.hash=e.hash);const o=yield this.httpClient.post("/api/sdk/init",{user:{name:w()},data:t,walletData:i,session:r,redirectHash:n,utm:M()},!1);o&&(o.lid&&localStorage.setItem("lid",o.lid),o.session&&function(e){const t={id:e.id,hash:e.hash,timestamp:Date.now()};sessionStorage.setItem(u,JSON.stringify(t))}(o.session)),y.initAll(this.store.config,{clicks:this.handleAutoTrackedClick.bind(this)},this.logger)})}handleAutoTrackedClick(e){const t=e,n={elementType:t.elementType,text:t.text,href:t.href,meta:t.meta};this.buttonClick(t.button,n)}userInfo(t,n){return e(this,void 0,void 0,function*(){const e=f(),i=h();t&&localStorage.setItem("luc_uid",t);const r=Object.assign({user:{name:t,userInfo:n},session:i},e&&{lid:e});yield this.httpClient.post("/api/sdk/user",r)})}pageView(t){return e(this,void 0,void 0,function*(){const e=f(),n=h(),i=Object.assign({page:t,user:{name:w()},session:n},e&&{lid:e});yield this.httpClient.post("/api/sdk/page",i)})}trackConversion(t,n,i){return e(this,void 0,void 0,function*(){const e=f(),r=h(),o=Object.assign({tag:t,amount:n,event:i,user:{name:w()},session:r},e&&{lid:e});yield this.httpClient.post("/api/sdk/conversion",o)})}buttonClick(t,n){return e(this,void 0,void 0,function*(){const e=f(),i=h(),r=Object.assign(Object.assign({button:t,user:{name:w()},session:i},e&&{lid:e}),n&&Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n.elementType&&{elementType:n.elementType}),n.text&&{text:n.text}),void 0!==n.href&&{href:n.href}),n.meta&&{meta:n.meta}),{timestamp:Date.now()}));yield this.httpClient.post("/api/sdk/click",r)})}sendWalletInfo(t,n,i){return e(this,void 0,void 0,function*(){const e=f(),r=h(),o=Object.assign({walletAddress:t,chainId:n,walletName:i,user:{name:w()},session:r},e&&{lid:e});yield this.httpClient.post("/api/sdk/wallet",o)})}trackUserAcquisition(t){return e(this,arguments,void 0,function*(e,t={}){const n=yield D(),i=M(),r=h();yield this.httpClient.post("/api/sdk/acquisition",{user:{name:e},session:r,data:Object.assign({timestamp:(new Date).toISOString(),browserData:n,utmParams:i},t)})})}checkMetaMaskConnection(){var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))}destroy(){y.destroyAll()}},V=null;const Q=()=>{const e=V||"undefined"!=typeof window&&window.__luciaInitPromise;if(!e)throw new Error("LuciaSDK not initialized. Please call LuciaSDK.init() first");return e},F=()=>{const e=V||"undefined"!=typeof window&&window.__luciaInitPromise;e&&e.then(e=>e.destroy()).catch(()=>{}),V=null,"undefined"!=typeof window&&delete window.__luciaInitPromise,y.reset()},H={init:t=>{if("undefined"==typeof window)return Promise.reject(new Error("LuciaSDK requires a browser environment"));if(V)return V;if(window.__luciaInitPromise)return V=window.__luciaInitPromise,V;if(!(null==t?void 0:t.apiKey))return Promise.reject(new Error("apiKey is required in config"));const n=e(void 0,void 0,void 0,function*(){const e=new z(t);return yield e.init(),e});return V=n,window.__luciaInitPromise=n,n},userInfo:(t,n)=>e(void 0,void 0,void 0,function*(){return(yield Q()).userInfo(t,n)}),pageView:t=>e(void 0,void 0,void 0,function*(){return(yield Q()).pageView(t)}),trackConversion:(t,n,i)=>e(void 0,void 0,void 0,function*(){return(yield Q()).trackConversion(t,n,i)}),buttonClick:(t,n)=>e(void 0,void 0,void 0,function*(){return(yield Q()).buttonClick(t,n)}),sendWalletInfo:(t,n,i)=>e(void 0,void 0,void 0,function*(){return(yield Q()).sendWalletInfo(t,n,i)}),trackUserAcquisition:(t,...n)=>e(void 0,[t,...n],void 0,function*(e,t={}){return(yield Q()).trackUserAcquisition(e,t)}),checkMetaMaskConnection:()=>{var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))},VERSION:n};if("undefined"!=typeof window){window.LuciaSDK=H;const e=()=>{const e=document.currentScript||document.querySelector("script[data-api-key]"),t=null==e?void 0:e.getAttribute("data-api-key");if(!t)return;const n=e.getAttribute("data-debug-url"),i=e.getAttribute("data-auto-track-clicks"),r=e.getAttribute("data-track-selectors");H.init(Object.assign(Object.assign(Object.assign({apiKey:t},n&&{debugURL:n}),"true"===i&&{autoTrackClicks:!r||{enabled:!0,selectors:r.split(",").map(e=>e.trim())}}),"false"===i&&{autoTrackClicks:!1})).catch(e=>console.error("LuciaSDK auto-init failed:",e))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}export{F as __resetInstance,H as default,L as filterObject,_ as getApplePayAvailable,D as getBrowserData,$ as getCanvasFingerprint,B as getColorGamut,q as getContrastPreference,M as getUtmParams,R as getWalletData,N as isTouchEnabled,U as safeAccess};
2
2
  //# sourceMappingURL=index.es.js.map
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";function e(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})}Object.defineProperty(exports,"__esModule",{value:!0}),"function"==typeof SuppressedError&&SuppressedError;class t{constructor(e){this.store=e}log(e,...t){var n;(null===(n=this.store.config)||void 0===n?void 0:n.debug)&&console[e](t)}}const n="0.9.10";class i{constructor(e){this.requestQueue=[],this.isProcessingQueue=!1,this.initComplete=!1,this.store=e,this.baseURL=this.getBaseURL(),this.logger=new t(this.store)}getBaseURL(){const{config:e}=this.store;return(null==e?void 0:e.debugURL)?e.debugURL:(null==e?void 0:e.testENV)?"http://52.22.177.60/fk":"https://api.clickinsights.xyz"}get(t){return e(this,void 0,void 0,function*(){if(!this.store.config)return this.logger.log("error","Config is not set"),null;try{const e=yield fetch(`${this.baseURL}${t}`,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":n}});return yield e.json()}catch(e){this.logger.log("error",e)}return null})}post(t,n){return e(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;const i="/api/sdk/init"===e;if(!i&&!this.initComplete)return new Promise((r,o)=>{this.requestQueue.push({url:e,data:t,fireAndForget:n,resolve:r,reject:o,isInit:i}),this.processQueue()});if(i){const i=yield this.executePost(e,t,n);return this.initComplete=!0,yield this.processQueue(),i}return this.executePost(e,t,n)})}processQueue(){return e(this,void 0,void 0,function*(){if(!this.isProcessingQueue&&this.initComplete&&0!==this.requestQueue.length){this.isProcessingQueue=!0;try{const t=()=>e(this,void 0,void 0,function*(){if(0===this.requestQueue.length)return;const e=this.requestQueue.shift();try{const t=yield this.executePost(e.url,e.data,e.fireAndForget);e.resolve(t)}catch(t){e.reject(t)}yield t()});yield t()}finally{this.isProcessingQueue=!1}}})}executePost(t,i){return e(this,arguments,void 0,function*(e,t,i=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;if(i&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){try{const n=`${this.baseURL}${e}`,i=t&&"object"==typeof t&&!Array.isArray(t)?t:{payload:t},r=JSON.stringify(Object.assign(Object.assign({},i),{_apiKey:this.store.config.apiKey})),o=new Blob([r],{type:"application/json"});navigator.sendBeacon(n,o)||this.logger.log("error","sendBeacon failed")}catch(e){this.logger.log("error",e)}return null}try{const i=yield fetch(`${this.baseURL}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":n},body:JSON.stringify(t)});return yield i.json()}catch(e){this.logger.log("error",e)}return null})}}class r{static dispatch(e){Object.keys(e).forEach(t=>{if(Object.keys(r.store).includes(t)){const n=e[t];r.store[t]="object"==typeof n?Array.isArray(n)?[...n]:Object.assign({},n):n}})}}r.store={isInitialized:!1,config:null,session:null};const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));let s;const a=new Uint8Array(16);var l={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function c(e,t,n){const i=(e=e||{}).random??e.rng?.()??function(){if(!s){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");s=crypto.getRandomValues.bind(crypto)}return s(a)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}(i)}const u="luci_session",d=new t(r.store);function h(){try{const e=sessionStorage.getItem(u);return e?JSON.parse(e):null}catch(e){return d.log("error","Error retrieving session data:",e),null}}function g(){var e;const t={id:l.randomUUID&&!e?l.randomUUID():c(e),timestamp:Date.now()};return sessionStorage.setItem(u,JSON.stringify(t)),t}function f(){const e=localStorage.getItem("lid");return"undefined"===e||"null"===e?(localStorage.removeItem("lid"),null):e}function w(){const e=localStorage.getItem("luc_uid");return"undefined"===e||"null"===e?(localStorage.removeItem("luc_uid"),null):e}class m{constructor(e){this.store=r.store,this.dispatch=r.dispatch,this.dispatch({config:e}),this.httpClient=new i(this.store),this.logger=new t(this.store)}}class p{constructor(e,t,n,i){this.enabled=!1,this.sdkConfig=e,this.config=t,this.callback=n,this.logger=i}enable(){this.enabled||(this.enabled=!0,this.attachListeners(),this.logger.log("log",`${this.name}: Enabled`))}disable(){this.enabled&&(this.enabled=!1,this.logger.log("log",`${this.name}: Disabled`))}destroy(){this.disable(),this.detachListeners(),this.logger.log("log",`${this.name}: Destroyed`)}isEnabled(){return this.enabled}}const y=new class{constructor(){this.registrations=new Map,this.activeTrackers=new Map,this.logger=null}register(e){this.registrations.set(e.name,e)}initAll(e,t,n){this.logger=n;for(const[i,r]of this.registrations){const o=e[r.configKey],s=r.normalizeConfig(o);if(null===s)continue;const a=t[i];if(a)try{const t=r.factory(e,s,a,n);this.activeTrackers.set(i,t),t.enable(),n.log("log",`AutoTrackerRegistry: Initialized ${i}`)}catch(e){n.log("error",`AutoTrackerRegistry: Failed to initialize ${i}`,e)}else n.log("warn",`AutoTrackerRegistry: No callback registered for ${i}`)}}get(e){return this.activeTrackers.get(e)}enable(e){const t=this.activeTrackers.get(e);return!!t&&(t.enable(),!0)}disable(e){const t=this.activeTrackers.get(e);return!!t&&(t.disable(),!0)}destroyAll(){var e;for(const[t,n]of this.activeTrackers)try{n.destroy()}catch(n){null===(e=this.logger)||void 0===e||e.log("error",`AutoTrackerRegistry: Error destroying ${t}`,n)}this.activeTrackers.clear()}getRegisteredTrackers(){return Array.from(this.registrations.keys())}getActiveTrackers(){return Array.from(this.activeTrackers.keys())}reset(){this.destroyAll(),this.logger=null}},v=['input[type="password"]','input[type="text"][autocomplete*="cc-"]','input[type="text"][autocomplete*="card"]','input[type="text"][name*="card"]','input[type="text"][name*="cvv"]','input[type="text"][name*="cvc"]','input[name*="ssn"]','input[name*="social"]',"[data-sensitive]","[data-private]"],b=[/\b\d{3}-\d{2}-\d{4}\b/,/\b\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4}\b/,/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i];const k=new class{constructor(e=[]){this.sensitiveSelectors=[...v,...e]}isSensitive(e){if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;let t=e.parentElement;for(;t;){const e=t;if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;t=t.parentElement}return!1}containsSensitiveData(e){return!!e&&b.some(t=>t.test(e))}sanitizeText(e){if(!e)return"";let t=e;return t=t.replace(/\b\d{3}-\d{2}-\d{4}\b/g,"***-**-****"),t=t.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,"****-****-****-****"),t=t.replace(/\b([A-Z0-9._%+-]+)@([A-Z0-9.-]+\.[A-Z]{2,})\b/gi,"***@$2"),t}},C=["button","a[href]",'[role="button"]'],T=["[data-lucia-ignore]",'[data-lucia-track="false"]'];class A extends p{constructor(e,t,n,i){var r,o,s;super(e,{enabled:null===(r=t.enabled)||void 0===r||r,selectors:null!==(o=t.selectors)&&void 0!==o?o:C,ignore:null!==(s=t.ignore)&&void 0!==s?s:T},n,i),this.name="clicks",this.configKey="autoTrackClicks",this.debounceTimers=new Map,this.listenerAttached=!1,this.boundHandleClick=null,this.privacyGuard=k}attachListeners(){this.listenerAttached||("undefined"!=typeof document?(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,{passive:!0,capture:!1}),this.listenerAttached=!0,this.logger.log("log","ClickTracker: Delegated click listener attached")):this.logger.log("warn","ClickTracker: document not available, cannot attach listener"))}detachListeners(){this.listenerAttached&&this.boundHandleClick&&"undefined"!=typeof document&&(document.removeEventListener("click",this.boundHandleClick),this.listenerAttached=!1),this.debounceTimers.clear(),this.boundHandleClick=null}handleClick(e){if(!this.enabled)return;const t=e.target;if(!t)return;const n=this.findTrackableElement(t);if(!n)return;if(this.shouldIgnore(n))return void this.logger.log("log","ClickTracker: Element ignored",n);if(this.privacyGuard.isSensitive(n))return void this.logger.log("warn","ClickTracker: Sensitive element not tracked",n);if(this.isDebounced(n))return void this.logger.log("log","ClickTracker: Click debounced",n);const i=this.extractTrackingData(n);i&&(this.logger.log("log","ClickTracker: Tracking click",i),this.callback(i))}findTrackableElement(e){const t=this.config.selectors||C;try{const n=e.closest('[data-lucia-track]:not([data-lucia-track="false"])');if(n&&n!==document.body&&document.body.contains(n)){if(this.config.selectors&&this.config.selectors!==C){return t.some(e=>{try{return n.matches(e)}catch(e){return!1}})?n:null}return n}const i=t.join(", "),r=e.closest(i);return r&&r!==document.body&&document.body.contains(r)?r:null}catch(t){this.logger.log("warn","ClickTracker: Invalid combined selector, using fallback",t);let n=e;for(;n&&n!==document.body;){if(this.isTrackable(n))return n;n=n.parentElement}return null}}isTrackable(e){return(this.config.selectors||C).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid selector "${t}"`,e),!1}})}shouldIgnore(e){return(this.config.ignore||T).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid ignore selector "${t}"`,e),!1}})}isDebounced(e){const t=Date.now(),n=this.debounceTimers.get(e);return!!(n&&t-n<500)||(this.debounceTimers.set(e,t),this.debounceTimers.size>100&&this.cleanupDebounceTimers(),!1)}cleanupDebounceTimers(){const e=Date.now();Array.from(this.debounceTimers.entries()).forEach(([t,n])=>{e-n>1e3&&this.debounceTimers.delete(t)})}extractTrackingData(e){var t;const n=this.getElementIdentifier(e);if(!n)return this.logger.log("warn","ClickTracker: Could not generate identifier for element",e),null;const i={button:n,elementType:this.getElementType(e),timestamp:Date.now()},r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&(this.privacyGuard.containsSensitiveData(r)||(i.text=this.sanitizeText(r))),"a"===e.tagName.toLowerCase()?i.href=e.getAttribute("href"):i.href=null;const o=this.extractMetadata(e);return o&&Object.keys(o).length>0&&(i.meta=o),i}getElementIdentifier(e){var t;const n=e.getAttribute("data-lucia-track");if(n&&"false"!==n)return n;const i=e.getAttribute("id");if(i)return i;const r=e.getAttribute("name");if(r)return r;const o=e.getAttribute("aria-label");if(o)return o;if("a"===e.tagName.toLowerCase()){const t=e.getAttribute("href");if(t)return`link:${t}`}const s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(s)return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using text content as identifier for element. Consider adding data-lucia-track attribute.",e),`text:${this.sanitizeText(s).substring(0,50)}`;const a=this.generateCSSPath(e);return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using CSS path as identifier. Consider adding data-lucia-track attribute.",e),`path:${a}`}getElementType(e){const t=e.tagName.toLowerCase();if("a"===t)return"link";if("button"===t)return"button";const n=e.getAttribute("role");return n||t}sanitizeText(e){return e.trim().replace(/\s+/g," ").substring(0,100)}generateCSSPath(e){const t=[];let n=e;for(;n&&n!==document.body&&t.length<5;){let e=n.tagName.toLowerCase();if(n.id){e+=`#${n.id}`,t.unshift(e);break}const i=n.getAttribute("class");if(i){const t=i.trim().split(/\s+/).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}t.unshift(e),n=n.parentElement}return t.join(" > ")}extractMetadata(e){const t={},{attributes:n}=e;return Array.from(n).forEach(e=>{if(e.name.startsWith("data-lucia-meta-")){const n=e.name.replace("data-lucia-meta-","").replace(/-([a-z])/g,e=>e[1].toUpperCase());t[n]=e.value}}),Object.keys(t).length>0?t:null}}const S={name:"clicks",configKey:"autoTrackClicks",factory:(e,t,n,i)=>new A(e,t,n,i),normalizeConfig:function(e){return void 0===e||!1===e?null:!0===e?{enabled:!0}:!1===e.enabled?null:e}},I=new t(r.store);function x(){return e(this,void 0,void 0,function*(){try{const{ethereum:e}=window;if(!(null==e?void 0:e.request))return null;const t=yield e.request({method:"eth_accounts"});return t&&t.length>0?t[0]:null}catch(e){return I.log("error","Error checking connected wallet:",e),null}})}function P(){return e(this,void 0,void 0,function*(){try{if(!window.ethereum)return null;if(window.ethereum.isMetaMask)return"MetaMask";if(!window.ethereum.request)return null;return(yield window.ethereum.request({method:"wallet_getName"}))||null}catch(e){return I.log("error","Error getting wallet name:",e),null}})}function E(){return e(this,void 0,void 0,function*(){if(!window.ethereum)return null;const e={isMetaMask:!!window.ethereum.isMetaMask,isCoinbaseWallet:!!window.ethereum.isCoinbaseWallet||!!window.ethereum.isCoinbase,isWalletConnect:!!window.ethereum.isWalletConnect,isTrust:!!window.ethereum.isTrust||!!window.ethereum.isTrustWallet,isImToken:!!window.ethereum.isImToken,isBraveWallet:!!window.ethereum.isBraveWallet,isTokenPocket:!!window.ethereum.isTokenPocket,isStatus:!!window.ethereum.isStatus,isTally:!(!window.ethereum.isTally&&!window.ethereum.isTallyWallet),isAlphaWallet:!!window.ethereum.isAlphaWallet,isOpera:!!window.ethereum.isOpera,isCoin98:!!window.ethereum.isCoin98,isMathWallet:!!window.ethereum.isMathWallet,isOneInch:!(!window.ethereum.isOneInchIOSWallet&&!window.ethereum.isOneInchAndroidWallet),isRainbow:!!window.ethereum.isRainbow,isBinanceChainWallet:!1,isFrame:!!window.ethereum.isFrame,userAgent:window.navigator.userAgent,chainId:window.ethereum.chainId||void 0,networkVersion:window.ethereum.networkVersion||void 0,name:""};return Object.values(e).some(Boolean)||(Object.prototype.hasOwnProperty.call(window.ethereum,"_metamask")&&(e.isMetaMask=!0),window.BinanceChain&&(e.isBinanceChainWallet=!0),window.ethereum.isFrame&&(e.isFrame=!0),"function"==typeof window.ethereum.request&&void 0===window.ethereum._metamask&&(e.isPossiblyGenericInjectedProvider=!0)),e.name=function(e){if(e.isMetaMask)return"MetaMask";if(e.isCoinbaseWallet)return"Coinbase Wallet";if(e.isWalletConnect)return"WalletConnect";if(e.isTrust)return"Trust Wallet";if(e.isImToken)return"imToken";if(e.isBraveWallet)return"Brave Wallet";if(e.isTokenPocket)return"TokenPocket";if(e.isStatus)return"Status";if(e.isTally)return"Tally";if(e.isAlphaWallet)return"AlphaWallet";if(e.isOpera)return"Opera";if(e.isCoin98)return"Coin98";if(e.isMathWallet)return"MathWallet";if(e.isOneInch)return"1inch Wallet";if(e.isRainbow)return"Rainbow";if(e.isBinanceChainWallet)return"Binance Chain Wallet";if(e.isFrame)return"Frame";const t=e.userAgent.toLowerCase();return t.includes("trust")?"Trust Wallet (UA)":t.includes("rainbow")?"Rainbow (UA)":"Unknown Provider"}(e),e})}const O=new t(r.store);function j(){return e(this,void 0,void 0,function*(){var e,t,n;try{if(window.solana){if(window.solana.isConnected&&window.solana.publicKey)return window.solana.publicKey.toString()}else if(window.solflare){if(window.solflare.isConnected&&window.solflare.publicKey)return window.solflare.publicKey.toString()}else if(null===(e=window.phantom)||void 0===e?void 0:e.solana)try{if((yield window.phantom.solana.connect({onlyIfTrusted:!0}))&&window.phantom.solana.publicKey)return window.phantom.solana.publicKey.toString()}catch(e){O.log("error","Error silently connecting to Phantom wallet:",e)}const i=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&i.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&i.push(window.SolanaWalletAdapterContext.current);const r=i.find(e=>e.connected&&e.publicKey);return r?r.publicKey.toString():null}catch(e){return O.log("error","Error detecting Solana wallet:",e),null}})}function D(){return e(this,void 0,void 0,function*(){var e,t,n;const i=yield j();if(!i)return null;if(null===(e=window.phantom)||void 0===e?void 0:e.solana)return"Phantom";if(window.solflare)return"Solflare";const r=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&r.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&r.push(window.SolanaWalletAdapterContext.current);const o=r.find(e=>e.connected&&e.publicKey&&e.publicKey.toString()===i);return o?o.name||"Unknown Wallet":null})}function W(){return e(this,void 0,void 0,function*(){if(K)return K;const e={device:{cores:U(()=>navigator.hardwareConcurrency),memory:U(()=>navigator.deviceMemory),cpuClass:U(()=>navigator.cpuClass),touch:_(),devicePixelRatio:U(()=>window.devicePixelRatio)},screen:{width:U(()=>window.screen.width),height:U(()=>window.screen.height),colorDepth:U(()=>window.screen.colorDepth),availHeight:U(()=>window.screen.availHeight),availWidth:U(()=>window.screen.availWidth),orientation:{type:U(()=>window.screen.orientation.type),angle:U(()=>window.screen.orientation.angle)}},browser:{language:U(()=>navigator.language),encoding:U(()=>TextDecoder.encoding),timezone:U(()=>-(new Date).getTimezoneOffset()/60),pluginsLength:U(()=>navigator.plugins.length),pluginNames:U(()=>Array.from(navigator.plugins,e=>e.name)),applePayAvailable:N(),uniqueHash:yield $(),colorGamut:q(),contrastPreference:B()},permissions:{navPer:U(()=>navigator.permissions.webglVersion),renderedPer:U(()=>navigator.permissions.RENDERER),geoPer:U(()=>navigator.permissions.geolocation)},storage:{localStorage:U(()=>!!window.localStorage),indexedDB:U(()=>!!window.indexedDB),openDB:U(()=>window.openDatabase)}};return K=e,e})}function M(){return e(this,void 0,void 0,function*(){const[e,t,n,i,r]=yield Promise.all([j(),x(),P(),D(),E()]);return{walletAddress:t,solanaAddress:e,providerInfo:r&&L(r),walletName:n,solWalletName:i}})}function R(){const e=new URL(window.location.href).searchParams,t={};return e.forEach((e,n)=>{(n.startsWith("utm_")||n.includes("id")||"ref"===n||"source"===n)&&(t[n]=e)}),t}function U(e,t){try{return e()}catch(e){return t}}function L(e){const t={};return Object.keys(e).forEach(n=>{const i=n;e[i]&&(t[i]=e[i])}),t}let K=null;function $(){return e(this,void 0,void 0,function*(){try{const t=document.createElement("canvas"),n=t.getContext("2d",{willReadFrequently:!0});if(!n)return;const i=200,r=120;t.width=i,t.height=r,t.style.width=`${i}px`,t.style.height=`${r}px`,n.fillStyle="#ffffff",n.fillRect(0,0,i,r),n.fillStyle="#ff00ff",n.fillRect(10,10,100,100),n.fillStyle="#00ffff",n.beginPath(),n.arc(150,50,40,0,2*Math.PI,!0),n.fill();const{data:o}=n.getImageData(0,0,i,r);return function(t){return e(this,void 0,void 0,function*(){const e=(new TextEncoder).encode(t),n=yield crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")})}([[20,20],[60,60],[100,100],[150,50],[150,60],[140,50],[5,5]].map(([e,t])=>{const n=4*(t*i+e);return`${o[n]},${o[n+1]},${o[n+2]},${o[n+3]};`}).join(""))}catch(e){return}})}function _(){try{return!!document.createEvent("TouchEvent")}catch(e){return!1}}function N(){var e;try{return"function"==typeof(null===(e=window.ApplePaySession)||void 0===e?void 0:e.canMakePayments)&&window.ApplePaySession.canMakePayments()}catch(e){return}}function B(){try{const{matchMedia:e}=window,t=t=>e(`(prefers-contrast: ${t})`).matches;return t("no-preference")?"None":t("high")||t("more")?"More":t("low")||t("less")?"Less":t("forced")?"ForcedColors":void 0}catch(e){return}}function q(){try{return["rec2020","p3","srgb","display-p3","adobe-rgb"].filter(e=>window.matchMedia(`(color-gamut: ${e})`).matches)}catch(e){return[]}}y.register(S);let z=class extends m{authenticate(){this.httpClient.post("/api/key/auth",{})}init(){return e(this,void 0,void 0,function*(){let e=h();e||(e=g());const t=yield W(),n=new URL(window.location.href).searchParams.get("lucia"),i=yield M(),r={id:e.id};e.hash&&(r.hash=e.hash);const o=yield this.httpClient.post("/api/sdk/init",{user:{name:w()},data:t,walletData:i,session:r,redirectHash:n,utm:R()},!1);o&&(o.lid&&localStorage.setItem("lid",o.lid),o.session&&function(e){const t={id:e.id,hash:e.hash,timestamp:Date.now()};sessionStorage.setItem(u,JSON.stringify(t))}(o.session)),y.initAll(this.store.config,{clicks:this.handleAutoTrackedClick.bind(this)},this.logger)})}handleAutoTrackedClick(e){const t=e,n={elementType:t.elementType,text:t.text,href:t.href,meta:t.meta};this.buttonClick(t.button,n)}userInfo(t,n){return e(this,void 0,void 0,function*(){const e=f(),i=h();t&&localStorage.setItem("luc_uid",t);const r=Object.assign({user:{name:t,userInfo:n},session:i},e&&{lid:e});yield this.httpClient.post("/api/sdk/user",r)})}pageView(t){return e(this,void 0,void 0,function*(){const e=f(),n=h(),i=Object.assign({page:t,user:{name:w()},session:n},e&&{lid:e});yield this.httpClient.post("/api/sdk/page",i)})}trackConversion(t,n,i){return e(this,void 0,void 0,function*(){const e=f(),r=h(),o=Object.assign({tag:t,amount:n,event:i,user:{name:w()},session:r},e&&{lid:e});yield this.httpClient.post("/api/sdk/conversion",o)})}buttonClick(t,n){return e(this,void 0,void 0,function*(){const e=f(),i=h(),r=Object.assign(Object.assign({button:t,user:{name:w()},session:i},e&&{lid:e}),n&&Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n.elementType&&{elementType:n.elementType}),n.text&&{text:n.text}),void 0!==n.href&&{href:n.href}),n.meta&&{meta:n.meta}),{timestamp:Date.now()}));yield this.httpClient.post("/api/sdk/click",r)})}sendWalletInfo(t,n,i){return e(this,void 0,void 0,function*(){const e=f(),r=h(),o=Object.assign({walletAddress:t,chainId:n,walletName:i,user:{name:w()},session:r},e&&{lid:e});yield this.httpClient.post("/api/sdk/wallet",o)})}trackUserAcquisition(t){return e(this,arguments,void 0,function*(e,t={}){const n=yield W(),i=R(),r=h();yield this.httpClient.post("/api/sdk/acquisition",{user:{name:e},session:r,data:Object.assign({timestamp:(new Date).toISOString(),browserData:n,utmParams:i},t)})})}checkMetaMaskConnection(){var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))}destroy(){y.destroyAll()}},V=null;const F=()=>{const e=V||"undefined"!=typeof window&&window.__luciaInitPromise;if(!e)throw new Error("LuciaSDK not initialized. Please call LuciaSDK.init() first");return e},Q={init:t=>{if("undefined"==typeof window)return Promise.reject(new Error("LuciaSDK requires a browser environment"));if(V)return V;if(window.__luciaInitPromise)return V=window.__luciaInitPromise,V;if(!(null==t?void 0:t.apiKey))return Promise.reject(new Error("apiKey is required in config"));const n=e(void 0,void 0,void 0,function*(){const e=new z(t);return yield e.init(),e});return V=n,window.__luciaInitPromise=n,n},userInfo:(t,n)=>e(void 0,void 0,void 0,function*(){return(yield F()).userInfo(t,n)}),pageView:t=>e(void 0,void 0,void 0,function*(){return(yield F()).pageView(t)}),trackConversion:(t,n,i)=>e(void 0,void 0,void 0,function*(){return(yield F()).trackConversion(t,n,i)}),buttonClick:(t,n)=>e(void 0,void 0,void 0,function*(){return(yield F()).buttonClick(t,n)}),sendWalletInfo:(t,n,i)=>e(void 0,void 0,void 0,function*(){return(yield F()).sendWalletInfo(t,n,i)}),trackUserAcquisition:(t,...n)=>e(void 0,[t,...n],void 0,function*(e,t={}){return(yield F()).trackUserAcquisition(e,t)}),checkMetaMaskConnection:()=>{var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))},VERSION:n};if("undefined"!=typeof window){window.LuciaSDK=Q;const e=()=>{const e=document.currentScript||document.querySelector("script[data-api-key]"),t=null==e?void 0:e.getAttribute("data-api-key");if(!t)return;const n=e.getAttribute("data-debug-url"),i=e.getAttribute("data-auto-track-clicks"),r=e.getAttribute("data-track-selectors");Q.init(Object.assign(Object.assign(Object.assign({apiKey:t},n&&{debugURL:n}),"true"===i&&{autoTrackClicks:!r||{enabled:!0,selectors:r.split(",").map(e=>e.trim())}}),"false"===i&&{autoTrackClicks:!1})).catch(e=>console.error("LuciaSDK auto-init failed:",e))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}exports.__resetInstance=()=>{const e=V||"undefined"!=typeof window&&window.__luciaInitPromise;e&&e.then(e=>e.destroy()).catch(()=>{}),V=null,"undefined"!=typeof window&&delete window.__luciaInitPromise,y.reset()},exports.default=Q,exports.filterObject=L,exports.getApplePayAvailable=N,exports.getBrowserData=W,exports.getCanvasFingerprint=$,exports.getColorGamut=q,exports.getContrastPreference=B,exports.getUtmParams=R,exports.getWalletData=M,exports.isTouchEnabled=_,exports.safeAccess=U;
1
+ "use strict";function e(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})}Object.defineProperty(exports,"__esModule",{value:!0}),"function"==typeof SuppressedError&&SuppressedError;class t{constructor(e){this.store=e}log(e,...t){var n;(null===(n=this.store.config)||void 0===n?void 0:n.debug)&&console[e](t)}}const n="0.9.12";class i{constructor(e){this.requestQueue=[],this.isProcessingQueue=!1,this.initComplete=!1,this.store=e,this.baseURL=this.getBaseURL(),this.logger=new t(this.store)}getBaseURL(){const{config:e}=this.store;return(null==e?void 0:e.debugURL)?e.debugURL:(null==e?void 0:e.testENV)?"http://52.22.177.60/fk":"https://api.clickinsights.xyz"}get(t){return e(this,void 0,void 0,function*(){if(!this.store.config)return this.logger.log("error","Config is not set"),null;try{const e=yield fetch(`${this.baseURL}${t}`,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":n}});return yield e.json()}catch(e){this.logger.log("error",e)}return null})}post(t,n){return e(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;const i="/api/sdk/init"===e;if(!i&&!this.initComplete)return new Promise((r,o)=>{this.requestQueue.push({url:e,data:t,fireAndForget:n,resolve:r,reject:o,isInit:i}),this.processQueue()});if(i){const i=yield this.executePost(e,t,n);return this.initComplete=!0,yield this.processQueue(),i}return this.executePost(e,t,n)})}processQueue(){return e(this,void 0,void 0,function*(){if(!this.isProcessingQueue&&this.initComplete&&0!==this.requestQueue.length){this.isProcessingQueue=!0;try{const t=()=>e(this,void 0,void 0,function*(){if(0===this.requestQueue.length)return;const e=this.requestQueue.shift();try{const t=yield this.executePost(e.url,e.data,e.fireAndForget);e.resolve(t)}catch(t){e.reject(t)}yield t()});yield t()}finally{this.isProcessingQueue=!1}}})}executePost(t,i){return e(this,arguments,void 0,function*(e,t,i=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;if(i&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){try{const n=`${this.baseURL}${e}`,i=t&&"object"==typeof t&&!Array.isArray(t)?t:{payload:t},r=JSON.stringify(Object.assign(Object.assign({},i),{_apiKey:this.store.config.apiKey})),o=new Blob([r],{type:"application/json"});navigator.sendBeacon(n,o)||this.logger.log("error","sendBeacon failed")}catch(e){this.logger.log("error",e)}return null}try{const i=yield fetch(`${this.baseURL}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":n},body:JSON.stringify(t)});return yield i.json()}catch(e){this.logger.log("error",e)}return null})}}class r{static dispatch(e){Object.keys(e).forEach(t=>{if(Object.keys(r.store).includes(t)){const n=e[t];r.store[t]="object"==typeof n?Array.isArray(n)?[...n]:Object.assign({},n):n}})}}r.store={isInitialized:!1,config:null,session:null};const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));let s;const a=new Uint8Array(16);var l={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function c(e,t,n){const i=(e=e||{}).random??e.rng?.()??function(){if(!s){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");s=crypto.getRandomValues.bind(crypto)}return s(a)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}(i)}const u="luci_session",d=new t(r.store);function h(){try{const e=sessionStorage.getItem(u);return e?JSON.parse(e):null}catch(e){return d.log("error","Error retrieving session data:",e),null}}function g(){var e;const t={id:l.randomUUID&&!e?l.randomUUID():c(e),timestamp:Date.now()};return sessionStorage.setItem(u,JSON.stringify(t)),t}function f(){const e=localStorage.getItem("lid");return"undefined"===e||"null"===e?(localStorage.removeItem("lid"),null):e}function w(){const e=localStorage.getItem("luc_uid");return"undefined"===e||"null"===e?(localStorage.removeItem("luc_uid"),null):e}class m{constructor(e){this.store=r.store,this.dispatch=r.dispatch,this.dispatch({config:e}),this.httpClient=new i(this.store),this.logger=new t(this.store)}}class p{constructor(e,t,n,i){this.enabled=!1,this.sdkConfig=e,this.config=t,this.callback=n,this.logger=i}enable(){this.enabled||(this.enabled=!0,this.attachListeners(),this.logger.log("log",`${this.name}: Enabled`))}disable(){this.enabled&&(this.enabled=!1,this.logger.log("log",`${this.name}: Disabled`))}destroy(){this.disable(),this.detachListeners(),this.logger.log("log",`${this.name}: Destroyed`)}isEnabled(){return this.enabled}}const y=new class{constructor(){this.registrations=new Map,this.activeTrackers=new Map,this.logger=null}register(e){this.registrations.set(e.name,e)}initAll(e,t,n){this.logger=n;for(const[i,r]of this.registrations){const o=e[r.configKey],s=r.normalizeConfig(o);if(null===s)continue;const a=t[i];if(a)try{const t=r.factory(e,s,a,n);this.activeTrackers.set(i,t),t.enable(),n.log("log",`AutoTrackerRegistry: Initialized ${i}`)}catch(e){n.log("error",`AutoTrackerRegistry: Failed to initialize ${i}`,e)}else n.log("warn",`AutoTrackerRegistry: No callback registered for ${i}`)}}get(e){return this.activeTrackers.get(e)}enable(e){const t=this.activeTrackers.get(e);return!!t&&(t.enable(),!0)}disable(e){const t=this.activeTrackers.get(e);return!!t&&(t.disable(),!0)}destroyAll(){var e;for(const[t,n]of this.activeTrackers)try{n.destroy()}catch(n){null===(e=this.logger)||void 0===e||e.log("error",`AutoTrackerRegistry: Error destroying ${t}`,n)}this.activeTrackers.clear()}getRegisteredTrackers(){return Array.from(this.registrations.keys())}getActiveTrackers(){return Array.from(this.activeTrackers.keys())}reset(){this.destroyAll(),this.logger=null}},v=['input[type="password"]','input[type="text"][autocomplete*="cc-"]','input[type="text"][autocomplete*="card"]','input[type="text"][name*="card"]','input[type="text"][name*="cvv"]','input[type="text"][name*="cvc"]','input[name*="ssn"]','input[name*="social"]',"[data-sensitive]","[data-private]"],b=[/\b\d{3}-\d{2}-\d{4}\b/,/\b\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4}\b/,/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i];const k=new class{constructor(e=[]){this.sensitiveSelectors=[...v,...e]}isSensitive(e){if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;let t=e.parentElement;for(;t;){const e=t;if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;t=t.parentElement}return!1}containsSensitiveData(e){return!!e&&b.some(t=>t.test(e))}sanitizeText(e){if(!e)return"";let t=e;return t=t.replace(/\b\d{3}-\d{2}-\d{4}\b/g,"***-**-****"),t=t.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,"****-****-****-****"),t=t.replace(/\b([A-Z0-9._%+-]+)@([A-Z0-9.-]+\.[A-Z]{2,})\b/gi,"***@$2"),t}},C=["button","a[href]",'[role="button"]'],T=["[data-lucia-ignore]",'[data-lucia-track="false"]'];class A extends p{constructor(e,t,n,i){var r,o,s;super(e,{enabled:null===(r=t.enabled)||void 0===r||r,selectors:null!==(o=t.selectors)&&void 0!==o?o:C,ignore:null!==(s=t.ignore)&&void 0!==s?s:T},n,i),this.name="clicks",this.configKey="autoTrackClicks",this.debounceTimers=new Map,this.listenerAttached=!1,this.boundHandleClick=null,this.privacyGuard=k}attachListeners(){this.listenerAttached||("undefined"!=typeof document?(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,{passive:!0,capture:!1}),this.listenerAttached=!0,this.logger.log("log","ClickTracker: Delegated click listener attached")):this.logger.log("warn","ClickTracker: document not available, cannot attach listener"))}detachListeners(){this.listenerAttached&&this.boundHandleClick&&"undefined"!=typeof document&&(document.removeEventListener("click",this.boundHandleClick),this.listenerAttached=!1),this.debounceTimers.clear(),this.boundHandleClick=null}handleClick(e){if(!this.enabled)return;const t=e.target;if(!t)return;const n=this.findTrackableElement(t);if(!n)return;if(this.shouldIgnore(n))return void this.logger.log("log","ClickTracker: Element ignored",n);if(this.privacyGuard.isSensitive(n))return void this.logger.log("warn","ClickTracker: Sensitive element not tracked",n);if(this.isDebounced(n))return void this.logger.log("log","ClickTracker: Click debounced",n);const i=this.extractTrackingData(n);i&&(this.logger.log("log","ClickTracker: Tracking click",i),this.callback(i))}findTrackableElement(e){const t=this.config.selectors||C;try{const n=e.closest('[data-lucia-track]:not([data-lucia-track="false"])');if(n&&n!==document.body&&document.body.contains(n)){if(this.config.selectors&&this.config.selectors!==C){return t.some(e=>{try{return n.matches(e)}catch(e){return!1}})?n:null}return n}const i=t.join(", "),r=e.closest(i);return r&&r!==document.body&&document.body.contains(r)?r:null}catch(t){this.logger.log("warn","ClickTracker: Invalid combined selector, using fallback",t);let n=e;for(;n&&n!==document.body;){if(this.isTrackable(n))return n;n=n.parentElement}return null}}isTrackable(e){return(this.config.selectors||C).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid selector "${t}"`,e),!1}})}shouldIgnore(e){return(this.config.ignore||T).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid ignore selector "${t}"`,e),!1}})}isDebounced(e){const t=Date.now(),n=this.debounceTimers.get(e);return!!(n&&t-n<500)||(this.debounceTimers.set(e,t),this.debounceTimers.size>100&&this.cleanupDebounceTimers(),!1)}cleanupDebounceTimers(){const e=Date.now();Array.from(this.debounceTimers.entries()).forEach(([t,n])=>{e-n>1e3&&this.debounceTimers.delete(t)})}extractTrackingData(e){var t;const n=this.getElementIdentifier(e);if(!n)return this.logger.log("warn","ClickTracker: Could not generate identifier for element",e),null;const i={button:n,elementType:this.getElementType(e),timestamp:Date.now()},r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&(this.privacyGuard.containsSensitiveData(r)||(i.text=this.sanitizeText(r))),"a"===e.tagName.toLowerCase()?i.href=e.getAttribute("href"):i.href=null;const o=this.extractMetadata(e);return o&&Object.keys(o).length>0&&(i.meta=o),i}getElementIdentifier(e){var t;const n=e.getAttribute("data-lucia-track");if(n&&"false"!==n)return n;const i=e.getAttribute("id");if(i)return i;const r=e.getAttribute("name");if(r)return r;const o=e.getAttribute("aria-label");if(o)return o;if("a"===e.tagName.toLowerCase()){const t=e.getAttribute("href");if(t)return`link:${t}`}const s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(s)return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using text content as identifier for element. Consider adding data-lucia-track attribute.",e),`text:${this.sanitizeText(s).substring(0,50)}`;const a=this.generateCSSPath(e);return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using CSS path as identifier. Consider adding data-lucia-track attribute.",e),`path:${a}`}getElementType(e){const t=e.tagName.toLowerCase();if("a"===t)return"link";if("button"===t)return"button";const n=e.getAttribute("role");return n||t}sanitizeText(e){return e.trim().replace(/\s+/g," ").substring(0,100)}generateCSSPath(e){const t=[];let n=e;for(;n&&n!==document.body&&t.length<5;){let e=n.tagName.toLowerCase();if(n.id){e+=`#${n.id}`,t.unshift(e);break}const i=n.getAttribute("class");if(i){const t=i.trim().split(/\s+/).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}t.unshift(e),n=n.parentElement}return t.join(" > ")}extractMetadata(e){const t={},{attributes:n}=e;return Array.from(n).forEach(e=>{if(e.name.startsWith("data-lucia-meta-")){const n=e.name.replace("data-lucia-meta-","").replace(/-([a-z])/g,e=>e[1].toUpperCase());t[n]=e.value}}),Object.keys(t).length>0?t:null}}const S={name:"clicks",configKey:"autoTrackClicks",factory:(e,t,n,i)=>new A(e,t,n,i),normalizeConfig:function(e){return void 0===e||!1===e?null:!0===e?{enabled:!0}:!1===e.enabled?null:e}},I=new t(r.store);function x(){return e(this,void 0,void 0,function*(){try{const{ethereum:e}=window;if(!(null==e?void 0:e.request))return null;const t=yield e.request({method:"eth_accounts"});return t&&t.length>0?t[0]:null}catch(e){return I.log("error","Error checking connected wallet:",e),null}})}function P(){return e(this,void 0,void 0,function*(){try{if(!window.ethereum)return null;if(window.ethereum.isMetaMask)return"MetaMask";if(!window.ethereum.request)return null;return(yield window.ethereum.request({method:"wallet_getName"}))||null}catch(e){return I.log("error","Error getting wallet name:",e),null}})}function E(){return e(this,void 0,void 0,function*(){if(!window.ethereum)return null;const e={isMetaMask:!!window.ethereum.isMetaMask,isCoinbaseWallet:!!window.ethereum.isCoinbaseWallet||!!window.ethereum.isCoinbase,isWalletConnect:!!window.ethereum.isWalletConnect,isTrust:!!window.ethereum.isTrust||!!window.ethereum.isTrustWallet,isImToken:!!window.ethereum.isImToken,isBraveWallet:!!window.ethereum.isBraveWallet,isTokenPocket:!!window.ethereum.isTokenPocket,isStatus:!!window.ethereum.isStatus,isTally:!(!window.ethereum.isTally&&!window.ethereum.isTallyWallet),isAlphaWallet:!!window.ethereum.isAlphaWallet,isOpera:!!window.ethereum.isOpera,isCoin98:!!window.ethereum.isCoin98,isMathWallet:!!window.ethereum.isMathWallet,isOneInch:!(!window.ethereum.isOneInchIOSWallet&&!window.ethereum.isOneInchAndroidWallet),isRainbow:!!window.ethereum.isRainbow,isBinanceChainWallet:!1,isFrame:!!window.ethereum.isFrame,userAgent:window.navigator.userAgent,chainId:window.ethereum.chainId||void 0,networkVersion:window.ethereum.networkVersion||void 0,name:""};return Object.values(e).some(Boolean)||(Object.prototype.hasOwnProperty.call(window.ethereum,"_metamask")&&(e.isMetaMask=!0),window.BinanceChain&&(e.isBinanceChainWallet=!0),window.ethereum.isFrame&&(e.isFrame=!0),"function"==typeof window.ethereum.request&&void 0===window.ethereum._metamask&&(e.isPossiblyGenericInjectedProvider=!0)),e.name=function(e){if(e.isMetaMask)return"MetaMask";if(e.isCoinbaseWallet)return"Coinbase Wallet";if(e.isWalletConnect)return"WalletConnect";if(e.isTrust)return"Trust Wallet";if(e.isImToken)return"imToken";if(e.isBraveWallet)return"Brave Wallet";if(e.isTokenPocket)return"TokenPocket";if(e.isStatus)return"Status";if(e.isTally)return"Tally";if(e.isAlphaWallet)return"AlphaWallet";if(e.isOpera)return"Opera";if(e.isCoin98)return"Coin98";if(e.isMathWallet)return"MathWallet";if(e.isOneInch)return"1inch Wallet";if(e.isRainbow)return"Rainbow";if(e.isBinanceChainWallet)return"Binance Chain Wallet";if(e.isFrame)return"Frame";const t=e.userAgent.toLowerCase();return t.includes("trust")?"Trust Wallet (UA)":t.includes("rainbow")?"Rainbow (UA)":"Unknown Provider"}(e),e})}const O=new t(r.store);function j(){return e(this,void 0,void 0,function*(){var e,t,n;try{if(window.solana){if(window.solana.isConnected&&window.solana.publicKey)return window.solana.publicKey.toString()}else if(window.solflare){if(window.solflare.isConnected&&window.solflare.publicKey)return window.solflare.publicKey.toString()}else if(null===(e=window.phantom)||void 0===e?void 0:e.solana)try{if((yield window.phantom.solana.connect({onlyIfTrusted:!0}))&&window.phantom.solana.publicKey)return window.phantom.solana.publicKey.toString()}catch(e){O.log("error","Error silently connecting to Phantom wallet:",e)}const i=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&i.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&i.push(window.SolanaWalletAdapterContext.current);const r=i.find(e=>e.connected&&e.publicKey);return r?r.publicKey.toString():null}catch(e){return O.log("error","Error detecting Solana wallet:",e),null}})}function D(){return e(this,void 0,void 0,function*(){var e,t,n;const i=yield j();if(!i)return null;if(null===(e=window.phantom)||void 0===e?void 0:e.solana)return"Phantom";if(window.solflare)return"Solflare";const r=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&r.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&r.push(window.SolanaWalletAdapterContext.current);const o=r.find(e=>e.connected&&e.publicKey&&e.publicKey.toString()===i);return o?o.name||"Unknown Wallet":null})}function W(){return e(this,void 0,void 0,function*(){if(K)return K;const e={device:{cores:U(()=>navigator.hardwareConcurrency),memory:U(()=>navigator.deviceMemory),cpuClass:U(()=>navigator.cpuClass),touch:_(),devicePixelRatio:U(()=>window.devicePixelRatio)},screen:{width:U(()=>window.screen.width),height:U(()=>window.screen.height),colorDepth:U(()=>window.screen.colorDepth),availHeight:U(()=>window.screen.availHeight),availWidth:U(()=>window.screen.availWidth),orientation:{type:U(()=>window.screen.orientation.type),angle:U(()=>window.screen.orientation.angle)}},browser:{language:U(()=>navigator.language),encoding:U(()=>TextDecoder.encoding),timezone:U(()=>-(new Date).getTimezoneOffset()/60),pluginsLength:U(()=>navigator.plugins.length),pluginNames:U(()=>Array.from(navigator.plugins,e=>e.name)),applePayAvailable:N(),uniqueHash:yield $(),colorGamut:q(),contrastPreference:B()},permissions:{navPer:U(()=>navigator.permissions.webglVersion),renderedPer:U(()=>navigator.permissions.RENDERER),geoPer:U(()=>navigator.permissions.geolocation)},storage:{localStorage:U(()=>!!window.localStorage),indexedDB:U(()=>!!window.indexedDB),openDB:U(()=>window.openDatabase)}};return K=e,e})}function M(){return e(this,void 0,void 0,function*(){const[e,t,n,i,r]=yield Promise.all([j(),x(),P(),D(),E()]);return{walletAddress:t,solanaAddress:e,providerInfo:r&&L(r),walletName:n,solWalletName:i}})}function R(){const e=new URL(window.location.href).searchParams,t={};return e.forEach((e,n)=>{(n.startsWith("utm_")||n.includes("id")||"ref"===n||"source"===n)&&(t[n]=e)}),t}function U(e,t){try{return e()}catch(e){return t}}function L(e){const t={};return Object.keys(e).forEach(n=>{const i=n;e[i]&&(t[i]=e[i])}),t}let K=null;function $(){return e(this,void 0,void 0,function*(){try{const t=document.createElement("canvas"),n=t.getContext("2d",{willReadFrequently:!0});if(!n)return;const i=200,r=120;t.width=i,t.height=r,t.style.width=`${i}px`,t.style.height=`${r}px`,n.fillStyle="#ffffff",n.fillRect(0,0,i,r),n.fillStyle="#ff00ff",n.fillRect(10,10,100,100),n.fillStyle="#00ffff",n.beginPath(),n.arc(150,50,40,0,2*Math.PI,!0),n.fill();const{data:o}=n.getImageData(0,0,i,r);return function(t){return e(this,void 0,void 0,function*(){const e=(new TextEncoder).encode(t),n=yield crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")})}([[20,20],[60,60],[100,100],[150,50],[150,60],[140,50],[5,5]].map(([e,t])=>{const n=4*(t*i+e);return`${o[n]},${o[n+1]},${o[n+2]},${o[n+3]};`}).join(""))}catch(e){return}})}function _(){try{return!!document.createEvent("TouchEvent")}catch(e){return!1}}function N(){var e;try{return"function"==typeof(null===(e=window.ApplePaySession)||void 0===e?void 0:e.canMakePayments)&&window.ApplePaySession.canMakePayments()}catch(e){return}}function B(){try{const{matchMedia:e}=window,t=t=>e(`(prefers-contrast: ${t})`).matches;return t("no-preference")?"None":t("high")||t("more")?"More":t("low")||t("less")?"Less":t("forced")?"ForcedColors":void 0}catch(e){return}}function q(){try{return["rec2020","p3","srgb","display-p3","adobe-rgb"].filter(e=>window.matchMedia(`(color-gamut: ${e})`).matches)}catch(e){return[]}}y.register(S);let z=class extends m{authenticate(){this.httpClient.post("/api/key/auth",{})}init(){return e(this,void 0,void 0,function*(){let e=h();e||(e=g());const t=yield W(),n=new URL(window.location.href).searchParams.get("lucia"),i=yield M(),r={id:e.id};e.hash&&(r.hash=e.hash);const o=yield this.httpClient.post("/api/sdk/init",{user:{name:w()},data:t,walletData:i,session:r,redirectHash:n,utm:R()},!1);o&&(o.lid&&localStorage.setItem("lid",o.lid),o.session&&function(e){const t={id:e.id,hash:e.hash,timestamp:Date.now()};sessionStorage.setItem(u,JSON.stringify(t))}(o.session)),y.initAll(this.store.config,{clicks:this.handleAutoTrackedClick.bind(this)},this.logger)})}handleAutoTrackedClick(e){const t=e,n={elementType:t.elementType,text:t.text,href:t.href,meta:t.meta};this.buttonClick(t.button,n)}userInfo(t,n){return e(this,void 0,void 0,function*(){const e=f(),i=h();t&&localStorage.setItem("luc_uid",t);const r=Object.assign({user:{name:t,userInfo:n},session:i},e&&{lid:e});yield this.httpClient.post("/api/sdk/user",r)})}pageView(t){return e(this,void 0,void 0,function*(){const e=f(),n=h(),i=Object.assign({page:t,user:{name:w()},session:n},e&&{lid:e});yield this.httpClient.post("/api/sdk/page",i)})}trackConversion(t,n,i){return e(this,void 0,void 0,function*(){const e=f(),r=h(),o=Object.assign({tag:t,amount:n,event:i,user:{name:w()},session:r},e&&{lid:e});yield this.httpClient.post("/api/sdk/conversion",o)})}buttonClick(t,n){return e(this,void 0,void 0,function*(){const e=f(),i=h(),r=Object.assign(Object.assign({button:t,user:{name:w()},session:i},e&&{lid:e}),n&&Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n.elementType&&{elementType:n.elementType}),n.text&&{text:n.text}),void 0!==n.href&&{href:n.href}),n.meta&&{meta:n.meta}),{timestamp:Date.now()}));yield this.httpClient.post("/api/sdk/click",r)})}sendWalletInfo(t,n,i){return e(this,void 0,void 0,function*(){const e=f(),r=h(),o=Object.assign({walletAddress:t,chainId:n,walletName:i,user:{name:w()},session:r},e&&{lid:e});yield this.httpClient.post("/api/sdk/wallet",o)})}trackUserAcquisition(t){return e(this,arguments,void 0,function*(e,t={}){const n=yield W(),i=R(),r=h();yield this.httpClient.post("/api/sdk/acquisition",{user:{name:e},session:r,data:Object.assign({timestamp:(new Date).toISOString(),browserData:n,utmParams:i},t)})})}checkMetaMaskConnection(){var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))}destroy(){y.destroyAll()}},V=null;const F=()=>{const e=V||"undefined"!=typeof window&&window.__luciaInitPromise;if(!e)throw new Error("LuciaSDK not initialized. Please call LuciaSDK.init() first");return e},Q={init:t=>{if("undefined"==typeof window)return Promise.reject(new Error("LuciaSDK requires a browser environment"));if(V)return V;if(window.__luciaInitPromise)return V=window.__luciaInitPromise,V;if(!(null==t?void 0:t.apiKey))return Promise.reject(new Error("apiKey is required in config"));const n=e(void 0,void 0,void 0,function*(){const e=new z(t);return yield e.init(),e});return V=n,window.__luciaInitPromise=n,n},userInfo:(t,n)=>e(void 0,void 0,void 0,function*(){return(yield F()).userInfo(t,n)}),pageView:t=>e(void 0,void 0,void 0,function*(){return(yield F()).pageView(t)}),trackConversion:(t,n,i)=>e(void 0,void 0,void 0,function*(){return(yield F()).trackConversion(t,n,i)}),buttonClick:(t,n)=>e(void 0,void 0,void 0,function*(){return(yield F()).buttonClick(t,n)}),sendWalletInfo:(t,n,i)=>e(void 0,void 0,void 0,function*(){return(yield F()).sendWalletInfo(t,n,i)}),trackUserAcquisition:(t,...n)=>e(void 0,[t,...n],void 0,function*(e,t={}){return(yield F()).trackUserAcquisition(e,t)}),checkMetaMaskConnection:()=>{var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))},VERSION:n};if("undefined"!=typeof window){window.LuciaSDK=Q;const e=()=>{const e=document.currentScript||document.querySelector("script[data-api-key]"),t=null==e?void 0:e.getAttribute("data-api-key");if(!t)return;const n=e.getAttribute("data-debug-url"),i=e.getAttribute("data-auto-track-clicks"),r=e.getAttribute("data-track-selectors");Q.init(Object.assign(Object.assign(Object.assign({apiKey:t},n&&{debugURL:n}),"true"===i&&{autoTrackClicks:!r||{enabled:!0,selectors:r.split(",").map(e=>e.trim())}}),"false"===i&&{autoTrackClicks:!1})).catch(e=>console.error("LuciaSDK auto-init failed:",e))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}exports.__resetInstance=()=>{const e=V||"undefined"!=typeof window&&window.__luciaInitPromise;e&&e.then(e=>e.destroy()).catch(()=>{}),V=null,"undefined"!=typeof window&&delete window.__luciaInitPromise,y.reset()},exports.default=Q,exports.filterObject=L,exports.getApplePayAvailable=N,exports.getBrowserData=W,exports.getCanvasFingerprint=$,exports.getColorGamut=q,exports.getContrastPreference=B,exports.getUtmParams=R,exports.getWalletData=M,exports.isTouchEnabled=_,exports.safeAccess=U;
2
2
  //# sourceMappingURL=index.js.map
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lucia-sdk",
3
- "version": "0.9.10",
3
+ "version": "0.9.12",
4
4
  "license": "CC-BY-NC-4.0",
5
5
  "description": "Lucia JavaScript Library",
6
6
  "repository": {
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LuciaSDK={})}(this,function(e){"use strict";function t(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class n{constructor(e){this.store=e}log(e,...t){var n;(null===(n=this.store.config)||void 0===n?void 0:n.debug)&&console[e](t)}}const i="0.9.10";class r{constructor(e){this.requestQueue=[],this.isProcessingQueue=!1,this.initComplete=!1,this.store=e,this.baseURL=this.getBaseURL(),this.logger=new n(this.store)}getBaseURL(){const{config:e}=this.store;return(null==e?void 0:e.debugURL)?e.debugURL:(null==e?void 0:e.testENV)?"http://52.22.177.60/fk":"https://api.clickinsights.xyz"}get(e){return t(this,void 0,void 0,function*(){if(!this.store.config)return this.logger.log("error","Config is not set"),null;try{const t=yield fetch(`${this.baseURL}${e}`,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":i}});return yield t.json()}catch(e){this.logger.log("error",e)}return null})}post(e,n){return t(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;const i="/api/sdk/init"===e;if(!i&&!this.initComplete)return new Promise((r,o)=>{this.requestQueue.push({url:e,data:t,fireAndForget:n,resolve:r,reject:o,isInit:i}),this.processQueue()});if(i){const i=yield this.executePost(e,t,n);return this.initComplete=!0,yield this.processQueue(),i}return this.executePost(e,t,n)})}processQueue(){return t(this,void 0,void 0,function*(){if(!this.isProcessingQueue&&this.initComplete&&0!==this.requestQueue.length){this.isProcessingQueue=!0;try{const e=()=>t(this,void 0,void 0,function*(){if(0===this.requestQueue.length)return;const t=this.requestQueue.shift();try{const e=yield this.executePost(t.url,t.data,t.fireAndForget);t.resolve(e)}catch(e){t.reject(e)}yield e()});yield e()}finally{this.isProcessingQueue=!1}}})}executePost(e,n){return t(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;if(n&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){try{const n=`${this.baseURL}${e}`,i=t&&"object"==typeof t&&!Array.isArray(t)?t:{payload:t},r=JSON.stringify(Object.assign(Object.assign({},i),{_apiKey:this.store.config.apiKey})),o=new Blob([r],{type:"application/json"});navigator.sendBeacon(n,o)||this.logger.log("error","sendBeacon failed")}catch(e){this.logger.log("error",e)}return null}try{const n=yield fetch(`${this.baseURL}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":i},body:JSON.stringify(t)});return yield n.json()}catch(e){this.logger.log("error",e)}return null})}}class o{static dispatch(e){Object.keys(e).forEach(t=>{if(Object.keys(o.store).includes(t)){const n=e[t];o.store[t]="object"==typeof n?Array.isArray(n)?[...n]:Object.assign({},n):n}})}}o.store={isInitialized:!1,config:null,session:null};const s=[];for(let e=0;e<256;++e)s.push((e+256).toString(16).slice(1));let a;const l=new Uint8Array(16);var c={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function u(e,t,n){const i=(e=e||{}).random??e.rng?.()??function(){if(!a){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");a=crypto.getRandomValues.bind(crypto)}return a(l)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return(s[e[t+0]]+s[e[t+1]]+s[e[t+2]]+s[e[t+3]]+"-"+s[e[t+4]]+s[e[t+5]]+"-"+s[e[t+6]]+s[e[t+7]]+"-"+s[e[t+8]]+s[e[t+9]]+"-"+s[e[t+10]]+s[e[t+11]]+s[e[t+12]]+s[e[t+13]]+s[e[t+14]]+s[e[t+15]]).toLowerCase()}(i)}const d="luci_session",h=new n(o.store);function g(){try{const e=sessionStorage.getItem(d);return e?JSON.parse(e):null}catch(e){return h.log("error","Error retrieving session data:",e),null}}function f(){var e;const t={id:c.randomUUID&&!e?c.randomUUID():u(e),timestamp:Date.now()};return sessionStorage.setItem(d,JSON.stringify(t)),t}function w(){const e=localStorage.getItem("lid");return"undefined"===e||"null"===e?(localStorage.removeItem("lid"),null):e}function m(){const e=localStorage.getItem("luc_uid");return"undefined"===e||"null"===e?(localStorage.removeItem("luc_uid"),null):e}class p{constructor(e){this.store=o.store,this.dispatch=o.dispatch,this.dispatch({config:e}),this.httpClient=new r(this.store),this.logger=new n(this.store)}}class y{constructor(e,t,n,i){this.enabled=!1,this.sdkConfig=e,this.config=t,this.callback=n,this.logger=i}enable(){this.enabled||(this.enabled=!0,this.attachListeners(),this.logger.log("log",`${this.name}: Enabled`))}disable(){this.enabled&&(this.enabled=!1,this.logger.log("log",`${this.name}: Disabled`))}destroy(){this.disable(),this.detachListeners(),this.logger.log("log",`${this.name}: Destroyed`)}isEnabled(){return this.enabled}}const v=new class{constructor(){this.registrations=new Map,this.activeTrackers=new Map,this.logger=null}register(e){this.registrations.set(e.name,e)}initAll(e,t,n){this.logger=n;for(const[i,r]of this.registrations){const o=e[r.configKey],s=r.normalizeConfig(o);if(null===s)continue;const a=t[i];if(a)try{const t=r.factory(e,s,a,n);this.activeTrackers.set(i,t),t.enable(),n.log("log",`AutoTrackerRegistry: Initialized ${i}`)}catch(e){n.log("error",`AutoTrackerRegistry: Failed to initialize ${i}`,e)}else n.log("warn",`AutoTrackerRegistry: No callback registered for ${i}`)}}get(e){return this.activeTrackers.get(e)}enable(e){const t=this.activeTrackers.get(e);return!!t&&(t.enable(),!0)}disable(e){const t=this.activeTrackers.get(e);return!!t&&(t.disable(),!0)}destroyAll(){var e;for(const[t,n]of this.activeTrackers)try{n.destroy()}catch(n){null===(e=this.logger)||void 0===e||e.log("error",`AutoTrackerRegistry: Error destroying ${t}`,n)}this.activeTrackers.clear()}getRegisteredTrackers(){return Array.from(this.registrations.keys())}getActiveTrackers(){return Array.from(this.activeTrackers.keys())}reset(){this.destroyAll(),this.logger=null}},b=['input[type="password"]','input[type="text"][autocomplete*="cc-"]','input[type="text"][autocomplete*="card"]','input[type="text"][name*="card"]','input[type="text"][name*="cvv"]','input[type="text"][name*="cvc"]','input[name*="ssn"]','input[name*="social"]',"[data-sensitive]","[data-private]"],k=[/\b\d{3}-\d{2}-\d{4}\b/,/\b\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4}\b/,/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i];const C=new class{constructor(e=[]){this.sensitiveSelectors=[...b,...e]}isSensitive(e){if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;let t=e.parentElement;for(;t;){const e=t;if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;t=t.parentElement}return!1}containsSensitiveData(e){return!!e&&k.some(t=>t.test(e))}sanitizeText(e){if(!e)return"";let t=e;return t=t.replace(/\b\d{3}-\d{2}-\d{4}\b/g,"***-**-****"),t=t.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,"****-****-****-****"),t=t.replace(/\b([A-Z0-9._%+-]+)@([A-Z0-9.-]+\.[A-Z]{2,})\b/gi,"***@$2"),t}},T=["button","a[href]",'[role="button"]'],A=["[data-lucia-ignore]",'[data-lucia-track="false"]'];class S extends y{constructor(e,t,n,i){var r,o,s;super(e,{enabled:null===(r=t.enabled)||void 0===r||r,selectors:null!==(o=t.selectors)&&void 0!==o?o:T,ignore:null!==(s=t.ignore)&&void 0!==s?s:A},n,i),this.name="clicks",this.configKey="autoTrackClicks",this.debounceTimers=new Map,this.listenerAttached=!1,this.boundHandleClick=null,this.privacyGuard=C}attachListeners(){this.listenerAttached||("undefined"!=typeof document?(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,{passive:!0,capture:!1}),this.listenerAttached=!0,this.logger.log("log","ClickTracker: Delegated click listener attached")):this.logger.log("warn","ClickTracker: document not available, cannot attach listener"))}detachListeners(){this.listenerAttached&&this.boundHandleClick&&"undefined"!=typeof document&&(document.removeEventListener("click",this.boundHandleClick),this.listenerAttached=!1),this.debounceTimers.clear(),this.boundHandleClick=null}handleClick(e){if(!this.enabled)return;const t=e.target;if(!t)return;const n=this.findTrackableElement(t);if(!n)return;if(this.shouldIgnore(n))return void this.logger.log("log","ClickTracker: Element ignored",n);if(this.privacyGuard.isSensitive(n))return void this.logger.log("warn","ClickTracker: Sensitive element not tracked",n);if(this.isDebounced(n))return void this.logger.log("log","ClickTracker: Click debounced",n);const i=this.extractTrackingData(n);i&&(this.logger.log("log","ClickTracker: Tracking click",i),this.callback(i))}findTrackableElement(e){const t=this.config.selectors||T;try{const n=e.closest('[data-lucia-track]:not([data-lucia-track="false"])');if(n&&n!==document.body&&document.body.contains(n)){if(this.config.selectors&&this.config.selectors!==T){return t.some(e=>{try{return n.matches(e)}catch(e){return!1}})?n:null}return n}const i=t.join(", "),r=e.closest(i);return r&&r!==document.body&&document.body.contains(r)?r:null}catch(t){this.logger.log("warn","ClickTracker: Invalid combined selector, using fallback",t);let n=e;for(;n&&n!==document.body;){if(this.isTrackable(n))return n;n=n.parentElement}return null}}isTrackable(e){return(this.config.selectors||T).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid selector "${t}"`,e),!1}})}shouldIgnore(e){return(this.config.ignore||A).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid ignore selector "${t}"`,e),!1}})}isDebounced(e){const t=Date.now(),n=this.debounceTimers.get(e);return!!(n&&t-n<500)||(this.debounceTimers.set(e,t),this.debounceTimers.size>100&&this.cleanupDebounceTimers(),!1)}cleanupDebounceTimers(){const e=Date.now();Array.from(this.debounceTimers.entries()).forEach(([t,n])=>{e-n>1e3&&this.debounceTimers.delete(t)})}extractTrackingData(e){var t;const n=this.getElementIdentifier(e);if(!n)return this.logger.log("warn","ClickTracker: Could not generate identifier for element",e),null;const i={button:n,elementType:this.getElementType(e),timestamp:Date.now()},r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&(this.privacyGuard.containsSensitiveData(r)||(i.text=this.sanitizeText(r))),"a"===e.tagName.toLowerCase()?i.href=e.getAttribute("href"):i.href=null;const o=this.extractMetadata(e);return o&&Object.keys(o).length>0&&(i.meta=o),i}getElementIdentifier(e){var t;const n=e.getAttribute("data-lucia-track");if(n&&"false"!==n)return n;const i=e.getAttribute("id");if(i)return i;const r=e.getAttribute("name");if(r)return r;const o=e.getAttribute("aria-label");if(o)return o;if("a"===e.tagName.toLowerCase()){const t=e.getAttribute("href");if(t)return`link:${t}`}const s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(s)return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using text content as identifier for element. Consider adding data-lucia-track attribute.",e),`text:${this.sanitizeText(s).substring(0,50)}`;const a=this.generateCSSPath(e);return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using CSS path as identifier. Consider adding data-lucia-track attribute.",e),`path:${a}`}getElementType(e){const t=e.tagName.toLowerCase();if("a"===t)return"link";if("button"===t)return"button";const n=e.getAttribute("role");return n||t}sanitizeText(e){return e.trim().replace(/\s+/g," ").substring(0,100)}generateCSSPath(e){const t=[];let n=e;for(;n&&n!==document.body&&t.length<5;){let e=n.tagName.toLowerCase();if(n.id){e+=`#${n.id}`,t.unshift(e);break}const i=n.getAttribute("class");if(i){const t=i.trim().split(/\s+/).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}t.unshift(e),n=n.parentElement}return t.join(" > ")}extractMetadata(e){const t={},{attributes:n}=e;return Array.from(n).forEach(e=>{if(e.name.startsWith("data-lucia-meta-")){const n=e.name.replace("data-lucia-meta-","").replace(/-([a-z])/g,e=>e[1].toUpperCase());t[n]=e.value}}),Object.keys(t).length>0?t:null}}const I={name:"clicks",configKey:"autoTrackClicks",factory:(e,t,n,i)=>new S(e,t,n,i),normalizeConfig:function(e){return void 0===e||!1===e?null:!0===e?{enabled:!0}:!1===e.enabled?null:e}},P=new n(o.store);function E(){return t(this,void 0,void 0,function*(){try{const{ethereum:e}=window;if(!(null==e?void 0:e.request))return null;const t=yield e.request({method:"eth_accounts"});return t&&t.length>0?t[0]:null}catch(e){return P.log("error","Error checking connected wallet:",e),null}})}function O(){return t(this,void 0,void 0,function*(){try{if(!window.ethereum)return null;if(window.ethereum.isMetaMask)return"MetaMask";if(!window.ethereum.request)return null;return(yield window.ethereum.request({method:"wallet_getName"}))||null}catch(e){return P.log("error","Error getting wallet name:",e),null}})}function x(){return t(this,void 0,void 0,function*(){if(!window.ethereum)return null;const e={isMetaMask:!!window.ethereum.isMetaMask,isCoinbaseWallet:!!window.ethereum.isCoinbaseWallet||!!window.ethereum.isCoinbase,isWalletConnect:!!window.ethereum.isWalletConnect,isTrust:!!window.ethereum.isTrust||!!window.ethereum.isTrustWallet,isImToken:!!window.ethereum.isImToken,isBraveWallet:!!window.ethereum.isBraveWallet,isTokenPocket:!!window.ethereum.isTokenPocket,isStatus:!!window.ethereum.isStatus,isTally:!(!window.ethereum.isTally&&!window.ethereum.isTallyWallet),isAlphaWallet:!!window.ethereum.isAlphaWallet,isOpera:!!window.ethereum.isOpera,isCoin98:!!window.ethereum.isCoin98,isMathWallet:!!window.ethereum.isMathWallet,isOneInch:!(!window.ethereum.isOneInchIOSWallet&&!window.ethereum.isOneInchAndroidWallet),isRainbow:!!window.ethereum.isRainbow,isBinanceChainWallet:!1,isFrame:!!window.ethereum.isFrame,userAgent:window.navigator.userAgent,chainId:window.ethereum.chainId||void 0,networkVersion:window.ethereum.networkVersion||void 0,name:""};return Object.values(e).some(Boolean)||(Object.prototype.hasOwnProperty.call(window.ethereum,"_metamask")&&(e.isMetaMask=!0),window.BinanceChain&&(e.isBinanceChainWallet=!0),window.ethereum.isFrame&&(e.isFrame=!0),"function"==typeof window.ethereum.request&&void 0===window.ethereum._metamask&&(e.isPossiblyGenericInjectedProvider=!0)),e.name=function(e){if(e.isMetaMask)return"MetaMask";if(e.isCoinbaseWallet)return"Coinbase Wallet";if(e.isWalletConnect)return"WalletConnect";if(e.isTrust)return"Trust Wallet";if(e.isImToken)return"imToken";if(e.isBraveWallet)return"Brave Wallet";if(e.isTokenPocket)return"TokenPocket";if(e.isStatus)return"Status";if(e.isTally)return"Tally";if(e.isAlphaWallet)return"AlphaWallet";if(e.isOpera)return"Opera";if(e.isCoin98)return"Coin98";if(e.isMathWallet)return"MathWallet";if(e.isOneInch)return"1inch Wallet";if(e.isRainbow)return"Rainbow";if(e.isBinanceChainWallet)return"Binance Chain Wallet";if(e.isFrame)return"Frame";const t=e.userAgent.toLowerCase();return t.includes("trust")?"Trust Wallet (UA)":t.includes("rainbow")?"Rainbow (UA)":"Unknown Provider"}(e),e})}const j=new n(o.store);function D(){return t(this,void 0,void 0,function*(){var e,t,n;try{if(window.solana){if(window.solana.isConnected&&window.solana.publicKey)return window.solana.publicKey.toString()}else if(window.solflare){if(window.solflare.isConnected&&window.solflare.publicKey)return window.solflare.publicKey.toString()}else if(null===(e=window.phantom)||void 0===e?void 0:e.solana)try{if((yield window.phantom.solana.connect({onlyIfTrusted:!0}))&&window.phantom.solana.publicKey)return window.phantom.solana.publicKey.toString()}catch(e){j.log("error","Error silently connecting to Phantom wallet:",e)}const i=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&i.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&i.push(window.SolanaWalletAdapterContext.current);const r=i.find(e=>e.connected&&e.publicKey);return r?r.publicKey.toString():null}catch(e){return j.log("error","Error detecting Solana wallet:",e),null}})}function W(){return t(this,void 0,void 0,function*(){var e,t,n;const i=yield D();if(!i)return null;if(null===(e=window.phantom)||void 0===e?void 0:e.solana)return"Phantom";if(window.solflare)return"Solflare";const r=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&r.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&r.push(window.SolanaWalletAdapterContext.current);const o=r.find(e=>e.connected&&e.publicKey&&e.publicKey.toString()===i);return o?o.name||"Unknown Wallet":null})}function M(){return t(this,void 0,void 0,function*(){if($)return $;const e={device:{cores:L(()=>navigator.hardwareConcurrency),memory:L(()=>navigator.deviceMemory),cpuClass:L(()=>navigator.cpuClass),touch:N(),devicePixelRatio:L(()=>window.devicePixelRatio)},screen:{width:L(()=>window.screen.width),height:L(()=>window.screen.height),colorDepth:L(()=>window.screen.colorDepth),availHeight:L(()=>window.screen.availHeight),availWidth:L(()=>window.screen.availWidth),orientation:{type:L(()=>window.screen.orientation.type),angle:L(()=>window.screen.orientation.angle)}},browser:{language:L(()=>navigator.language),encoding:L(()=>TextDecoder.encoding),timezone:L(()=>-(new Date).getTimezoneOffset()/60),pluginsLength:L(()=>navigator.plugins.length),pluginNames:L(()=>Array.from(navigator.plugins,e=>e.name)),applePayAvailable:B(),uniqueHash:yield _(),colorGamut:z(),contrastPreference:q()},permissions:{navPer:L(()=>navigator.permissions.webglVersion),renderedPer:L(()=>navigator.permissions.RENDERER),geoPer:L(()=>navigator.permissions.geolocation)},storage:{localStorage:L(()=>!!window.localStorage),indexedDB:L(()=>!!window.indexedDB),openDB:L(()=>window.openDatabase)}};return $=e,e})}function R(){return t(this,void 0,void 0,function*(){const[e,t,n,i,r]=yield Promise.all([D(),E(),O(),W(),x()]);return{walletAddress:t,solanaAddress:e,providerInfo:r&&K(r),walletName:n,solWalletName:i}})}function U(){const e=new URL(window.location.href).searchParams,t={};return e.forEach((e,n)=>{(n.startsWith("utm_")||n.includes("id")||"ref"===n||"source"===n)&&(t[n]=e)}),t}function L(e,t){try{return e()}catch(e){return t}}function K(e){const t={};return Object.keys(e).forEach(n=>{const i=n;e[i]&&(t[i]=e[i])}),t}let $=null;function _(){return t(this,void 0,void 0,function*(){try{const e=document.createElement("canvas"),n=e.getContext("2d",{willReadFrequently:!0});if(!n)return;const i=200,r=120;e.width=i,e.height=r,e.style.width=`${i}px`,e.style.height=`${r}px`,n.fillStyle="#ffffff",n.fillRect(0,0,i,r),n.fillStyle="#ff00ff",n.fillRect(10,10,100,100),n.fillStyle="#00ffff",n.beginPath(),n.arc(150,50,40,0,2*Math.PI,!0),n.fill();const{data:o}=n.getImageData(0,0,i,r);return function(e){return t(this,void 0,void 0,function*(){const t=(new TextEncoder).encode(e),n=yield crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")})}([[20,20],[60,60],[100,100],[150,50],[150,60],[140,50],[5,5]].map(([e,t])=>{const n=4*(t*i+e);return`${o[n]},${o[n+1]},${o[n+2]},${o[n+3]};`}).join(""))}catch(e){return}})}function N(){try{return!!document.createEvent("TouchEvent")}catch(e){return!1}}function B(){var e;try{return"function"==typeof(null===(e=window.ApplePaySession)||void 0===e?void 0:e.canMakePayments)&&window.ApplePaySession.canMakePayments()}catch(e){return}}function q(){try{const{matchMedia:e}=window,t=t=>e(`(prefers-contrast: ${t})`).matches;return t("no-preference")?"None":t("high")||t("more")?"More":t("low")||t("less")?"Less":t("forced")?"ForcedColors":void 0}catch(e){return}}function z(){try{return["rec2020","p3","srgb","display-p3","adobe-rgb"].filter(e=>window.matchMedia(`(color-gamut: ${e})`).matches)}catch(e){return[]}}v.register(I);let V=class extends p{authenticate(){this.httpClient.post("/api/key/auth",{})}init(){return t(this,void 0,void 0,function*(){let e=g();e||(e=f());const t=yield M(),n=new URL(window.location.href).searchParams.get("lucia"),i=yield R(),r={id:e.id};e.hash&&(r.hash=e.hash);const o=yield this.httpClient.post("/api/sdk/init",{user:{name:m()},data:t,walletData:i,session:r,redirectHash:n,utm:U()},!1);o&&(o.lid&&localStorage.setItem("lid",o.lid),o.session&&function(e){const t={id:e.id,hash:e.hash,timestamp:Date.now()};sessionStorage.setItem(d,JSON.stringify(t))}(o.session)),v.initAll(this.store.config,{clicks:this.handleAutoTrackedClick.bind(this)},this.logger)})}handleAutoTrackedClick(e){const t=e,n={elementType:t.elementType,text:t.text,href:t.href,meta:t.meta};this.buttonClick(t.button,n)}userInfo(e,n){return t(this,void 0,void 0,function*(){const t=w(),i=g();e&&localStorage.setItem("luc_uid",e);const r=Object.assign({user:{name:e,userInfo:n},session:i},t&&{lid:t});yield this.httpClient.post("/api/sdk/user",r)})}pageView(e){return t(this,void 0,void 0,function*(){const t=w(),n=g(),i=Object.assign({page:e,user:{name:m()},session:n},t&&{lid:t});yield this.httpClient.post("/api/sdk/page",i)})}trackConversion(e,n,i){return t(this,void 0,void 0,function*(){const t=w(),r=g(),o=Object.assign({tag:e,amount:n,event:i,user:{name:m()},session:r},t&&{lid:t});yield this.httpClient.post("/api/sdk/conversion",o)})}buttonClick(e,n){return t(this,void 0,void 0,function*(){const t=w(),i=g(),r=Object.assign(Object.assign({button:e,user:{name:m()},session:i},t&&{lid:t}),n&&Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n.elementType&&{elementType:n.elementType}),n.text&&{text:n.text}),void 0!==n.href&&{href:n.href}),n.meta&&{meta:n.meta}),{timestamp:Date.now()}));yield this.httpClient.post("/api/sdk/click",r)})}sendWalletInfo(e,n,i){return t(this,void 0,void 0,function*(){const t=w(),r=g(),o=Object.assign({walletAddress:e,chainId:n,walletName:i,user:{name:m()},session:r},t&&{lid:t});yield this.httpClient.post("/api/sdk/wallet",o)})}trackUserAcquisition(e){return t(this,arguments,void 0,function*(e,t={}){const n=yield M(),i=U(),r=g();yield this.httpClient.post("/api/sdk/acquisition",{user:{name:e},session:r,data:Object.assign({timestamp:(new Date).toISOString(),browserData:n,utmParams:i},t)})})}checkMetaMaskConnection(){var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))}destroy(){v.destroyAll()}},F=null;const Q=()=>{const e=F||"undefined"!=typeof window&&window.__luciaInitPromise;if(!e)throw new Error("LuciaSDK not initialized. Please call LuciaSDK.init() first");return e},H={init:e=>{if("undefined"==typeof window)return Promise.reject(new Error("LuciaSDK requires a browser environment"));if(F)return F;if(window.__luciaInitPromise)return F=window.__luciaInitPromise,F;if(!(null==e?void 0:e.apiKey))return Promise.reject(new Error("apiKey is required in config"));const n=t(void 0,void 0,void 0,function*(){const t=new V(e);return yield t.init(),t});return F=n,window.__luciaInitPromise=n,n},userInfo:(e,n)=>t(void 0,void 0,void 0,function*(){return(yield Q()).userInfo(e,n)}),pageView:e=>t(void 0,void 0,void 0,function*(){return(yield Q()).pageView(e)}),trackConversion:(e,n,i)=>t(void 0,void 0,void 0,function*(){return(yield Q()).trackConversion(e,n,i)}),buttonClick:(e,n)=>t(void 0,void 0,void 0,function*(){return(yield Q()).buttonClick(e,n)}),sendWalletInfo:(e,n,i)=>t(void 0,void 0,void 0,function*(){return(yield Q()).sendWalletInfo(e,n,i)}),trackUserAcquisition:(e,...n)=>t(void 0,[e,...n],void 0,function*(e,t={}){return(yield Q()).trackUserAcquisition(e,t)}),checkMetaMaskConnection:()=>{var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))},VERSION:i};if("undefined"!=typeof window){window.LuciaSDK=H;const e=()=>{const e=document.currentScript||document.querySelector("script[data-api-key]"),t=null==e?void 0:e.getAttribute("data-api-key");if(!t)return;const n=e.getAttribute("data-debug-url"),i=e.getAttribute("data-auto-track-clicks"),r=e.getAttribute("data-track-selectors");H.init(Object.assign(Object.assign(Object.assign({apiKey:t},n&&{debugURL:n}),"true"===i&&{autoTrackClicks:!r||{enabled:!0,selectors:r.split(",").map(e=>e.trim())}}),"false"===i&&{autoTrackClicks:!1})).catch(e=>console.error("LuciaSDK auto-init failed:",e))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}e.__resetInstance=()=>{const e=F||"undefined"!=typeof window&&window.__luciaInitPromise;e&&e.then(e=>e.destroy()).catch(()=>{}),F=null,"undefined"!=typeof window&&delete window.__luciaInitPromise,v.reset()},e.default=H,e.filterObject=K,e.getApplePayAvailable=B,e.getBrowserData=M,e.getCanvasFingerprint=_,e.getColorGamut=z,e.getContrastPreference=q,e.getUtmParams=U,e.getWalletData=R,e.isTouchEnabled=N,e.safeAccess=L,Object.defineProperty(e,"__esModule",{value:!0})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LuciaSDK={})}(this,function(e){"use strict";function t(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class n{constructor(e){this.store=e}log(e,...t){var n;(null===(n=this.store.config)||void 0===n?void 0:n.debug)&&console[e](t)}}const i="0.9.12";class r{constructor(e){this.requestQueue=[],this.isProcessingQueue=!1,this.initComplete=!1,this.store=e,this.baseURL=this.getBaseURL(),this.logger=new n(this.store)}getBaseURL(){const{config:e}=this.store;return(null==e?void 0:e.debugURL)?e.debugURL:(null==e?void 0:e.testENV)?"http://52.22.177.60/fk":"https://api.clickinsights.xyz"}get(e){return t(this,void 0,void 0,function*(){if(!this.store.config)return this.logger.log("error","Config is not set"),null;try{const t=yield fetch(`${this.baseURL}${e}`,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":i}});return yield t.json()}catch(e){this.logger.log("error",e)}return null})}post(e,n){return t(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;const i="/api/sdk/init"===e;if(!i&&!this.initComplete)return new Promise((r,o)=>{this.requestQueue.push({url:e,data:t,fireAndForget:n,resolve:r,reject:o,isInit:i}),this.processQueue()});if(i){const i=yield this.executePost(e,t,n);return this.initComplete=!0,yield this.processQueue(),i}return this.executePost(e,t,n)})}processQueue(){return t(this,void 0,void 0,function*(){if(!this.isProcessingQueue&&this.initComplete&&0!==this.requestQueue.length){this.isProcessingQueue=!0;try{const e=()=>t(this,void 0,void 0,function*(){if(0===this.requestQueue.length)return;const t=this.requestQueue.shift();try{const e=yield this.executePost(t.url,t.data,t.fireAndForget);t.resolve(e)}catch(e){t.reject(e)}yield e()});yield e()}finally{this.isProcessingQueue=!1}}})}executePost(e,n){return t(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;if(n&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){try{const n=`${this.baseURL}${e}`,i=t&&"object"==typeof t&&!Array.isArray(t)?t:{payload:t},r=JSON.stringify(Object.assign(Object.assign({},i),{_apiKey:this.store.config.apiKey})),o=new Blob([r],{type:"application/json"});navigator.sendBeacon(n,o)||this.logger.log("error","sendBeacon failed")}catch(e){this.logger.log("error",e)}return null}try{const n=yield fetch(`${this.baseURL}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":i},body:JSON.stringify(t)});return yield n.json()}catch(e){this.logger.log("error",e)}return null})}}class o{static dispatch(e){Object.keys(e).forEach(t=>{if(Object.keys(o.store).includes(t)){const n=e[t];o.store[t]="object"==typeof n?Array.isArray(n)?[...n]:Object.assign({},n):n}})}}o.store={isInitialized:!1,config:null,session:null};const s=[];for(let e=0;e<256;++e)s.push((e+256).toString(16).slice(1));let a;const l=new Uint8Array(16);var c={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function u(e,t,n){const i=(e=e||{}).random??e.rng?.()??function(){if(!a){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");a=crypto.getRandomValues.bind(crypto)}return a(l)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return(s[e[t+0]]+s[e[t+1]]+s[e[t+2]]+s[e[t+3]]+"-"+s[e[t+4]]+s[e[t+5]]+"-"+s[e[t+6]]+s[e[t+7]]+"-"+s[e[t+8]]+s[e[t+9]]+"-"+s[e[t+10]]+s[e[t+11]]+s[e[t+12]]+s[e[t+13]]+s[e[t+14]]+s[e[t+15]]).toLowerCase()}(i)}const d="luci_session",h=new n(o.store);function g(){try{const e=sessionStorage.getItem(d);return e?JSON.parse(e):null}catch(e){return h.log("error","Error retrieving session data:",e),null}}function f(){var e;const t={id:c.randomUUID&&!e?c.randomUUID():u(e),timestamp:Date.now()};return sessionStorage.setItem(d,JSON.stringify(t)),t}function w(){const e=localStorage.getItem("lid");return"undefined"===e||"null"===e?(localStorage.removeItem("lid"),null):e}function m(){const e=localStorage.getItem("luc_uid");return"undefined"===e||"null"===e?(localStorage.removeItem("luc_uid"),null):e}class p{constructor(e){this.store=o.store,this.dispatch=o.dispatch,this.dispatch({config:e}),this.httpClient=new r(this.store),this.logger=new n(this.store)}}class y{constructor(e,t,n,i){this.enabled=!1,this.sdkConfig=e,this.config=t,this.callback=n,this.logger=i}enable(){this.enabled||(this.enabled=!0,this.attachListeners(),this.logger.log("log",`${this.name}: Enabled`))}disable(){this.enabled&&(this.enabled=!1,this.logger.log("log",`${this.name}: Disabled`))}destroy(){this.disable(),this.detachListeners(),this.logger.log("log",`${this.name}: Destroyed`)}isEnabled(){return this.enabled}}const v=new class{constructor(){this.registrations=new Map,this.activeTrackers=new Map,this.logger=null}register(e){this.registrations.set(e.name,e)}initAll(e,t,n){this.logger=n;for(const[i,r]of this.registrations){const o=e[r.configKey],s=r.normalizeConfig(o);if(null===s)continue;const a=t[i];if(a)try{const t=r.factory(e,s,a,n);this.activeTrackers.set(i,t),t.enable(),n.log("log",`AutoTrackerRegistry: Initialized ${i}`)}catch(e){n.log("error",`AutoTrackerRegistry: Failed to initialize ${i}`,e)}else n.log("warn",`AutoTrackerRegistry: No callback registered for ${i}`)}}get(e){return this.activeTrackers.get(e)}enable(e){const t=this.activeTrackers.get(e);return!!t&&(t.enable(),!0)}disable(e){const t=this.activeTrackers.get(e);return!!t&&(t.disable(),!0)}destroyAll(){var e;for(const[t,n]of this.activeTrackers)try{n.destroy()}catch(n){null===(e=this.logger)||void 0===e||e.log("error",`AutoTrackerRegistry: Error destroying ${t}`,n)}this.activeTrackers.clear()}getRegisteredTrackers(){return Array.from(this.registrations.keys())}getActiveTrackers(){return Array.from(this.activeTrackers.keys())}reset(){this.destroyAll(),this.logger=null}},b=['input[type="password"]','input[type="text"][autocomplete*="cc-"]','input[type="text"][autocomplete*="card"]','input[type="text"][name*="card"]','input[type="text"][name*="cvv"]','input[type="text"][name*="cvc"]','input[name*="ssn"]','input[name*="social"]',"[data-sensitive]","[data-private]"],k=[/\b\d{3}-\d{2}-\d{4}\b/,/\b\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4}\b/,/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i];const C=new class{constructor(e=[]){this.sensitiveSelectors=[...b,...e]}isSensitive(e){if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;let t=e.parentElement;for(;t;){const e=t;if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;t=t.parentElement}return!1}containsSensitiveData(e){return!!e&&k.some(t=>t.test(e))}sanitizeText(e){if(!e)return"";let t=e;return t=t.replace(/\b\d{3}-\d{2}-\d{4}\b/g,"***-**-****"),t=t.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,"****-****-****-****"),t=t.replace(/\b([A-Z0-9._%+-]+)@([A-Z0-9.-]+\.[A-Z]{2,})\b/gi,"***@$2"),t}},T=["button","a[href]",'[role="button"]'],A=["[data-lucia-ignore]",'[data-lucia-track="false"]'];class S extends y{constructor(e,t,n,i){var r,o,s;super(e,{enabled:null===(r=t.enabled)||void 0===r||r,selectors:null!==(o=t.selectors)&&void 0!==o?o:T,ignore:null!==(s=t.ignore)&&void 0!==s?s:A},n,i),this.name="clicks",this.configKey="autoTrackClicks",this.debounceTimers=new Map,this.listenerAttached=!1,this.boundHandleClick=null,this.privacyGuard=C}attachListeners(){this.listenerAttached||("undefined"!=typeof document?(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,{passive:!0,capture:!1}),this.listenerAttached=!0,this.logger.log("log","ClickTracker: Delegated click listener attached")):this.logger.log("warn","ClickTracker: document not available, cannot attach listener"))}detachListeners(){this.listenerAttached&&this.boundHandleClick&&"undefined"!=typeof document&&(document.removeEventListener("click",this.boundHandleClick),this.listenerAttached=!1),this.debounceTimers.clear(),this.boundHandleClick=null}handleClick(e){if(!this.enabled)return;const t=e.target;if(!t)return;const n=this.findTrackableElement(t);if(!n)return;if(this.shouldIgnore(n))return void this.logger.log("log","ClickTracker: Element ignored",n);if(this.privacyGuard.isSensitive(n))return void this.logger.log("warn","ClickTracker: Sensitive element not tracked",n);if(this.isDebounced(n))return void this.logger.log("log","ClickTracker: Click debounced",n);const i=this.extractTrackingData(n);i&&(this.logger.log("log","ClickTracker: Tracking click",i),this.callback(i))}findTrackableElement(e){const t=this.config.selectors||T;try{const n=e.closest('[data-lucia-track]:not([data-lucia-track="false"])');if(n&&n!==document.body&&document.body.contains(n)){if(this.config.selectors&&this.config.selectors!==T){return t.some(e=>{try{return n.matches(e)}catch(e){return!1}})?n:null}return n}const i=t.join(", "),r=e.closest(i);return r&&r!==document.body&&document.body.contains(r)?r:null}catch(t){this.logger.log("warn","ClickTracker: Invalid combined selector, using fallback",t);let n=e;for(;n&&n!==document.body;){if(this.isTrackable(n))return n;n=n.parentElement}return null}}isTrackable(e){return(this.config.selectors||T).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid selector "${t}"`,e),!1}})}shouldIgnore(e){return(this.config.ignore||A).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid ignore selector "${t}"`,e),!1}})}isDebounced(e){const t=Date.now(),n=this.debounceTimers.get(e);return!!(n&&t-n<500)||(this.debounceTimers.set(e,t),this.debounceTimers.size>100&&this.cleanupDebounceTimers(),!1)}cleanupDebounceTimers(){const e=Date.now();Array.from(this.debounceTimers.entries()).forEach(([t,n])=>{e-n>1e3&&this.debounceTimers.delete(t)})}extractTrackingData(e){var t;const n=this.getElementIdentifier(e);if(!n)return this.logger.log("warn","ClickTracker: Could not generate identifier for element",e),null;const i={button:n,elementType:this.getElementType(e),timestamp:Date.now()},r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&(this.privacyGuard.containsSensitiveData(r)||(i.text=this.sanitizeText(r))),"a"===e.tagName.toLowerCase()?i.href=e.getAttribute("href"):i.href=null;const o=this.extractMetadata(e);return o&&Object.keys(o).length>0&&(i.meta=o),i}getElementIdentifier(e){var t;const n=e.getAttribute("data-lucia-track");if(n&&"false"!==n)return n;const i=e.getAttribute("id");if(i)return i;const r=e.getAttribute("name");if(r)return r;const o=e.getAttribute("aria-label");if(o)return o;if("a"===e.tagName.toLowerCase()){const t=e.getAttribute("href");if(t)return`link:${t}`}const s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(s)return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using text content as identifier for element. Consider adding data-lucia-track attribute.",e),`text:${this.sanitizeText(s).substring(0,50)}`;const a=this.generateCSSPath(e);return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using CSS path as identifier. Consider adding data-lucia-track attribute.",e),`path:${a}`}getElementType(e){const t=e.tagName.toLowerCase();if("a"===t)return"link";if("button"===t)return"button";const n=e.getAttribute("role");return n||t}sanitizeText(e){return e.trim().replace(/\s+/g," ").substring(0,100)}generateCSSPath(e){const t=[];let n=e;for(;n&&n!==document.body&&t.length<5;){let e=n.tagName.toLowerCase();if(n.id){e+=`#${n.id}`,t.unshift(e);break}const i=n.getAttribute("class");if(i){const t=i.trim().split(/\s+/).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}t.unshift(e),n=n.parentElement}return t.join(" > ")}extractMetadata(e){const t={},{attributes:n}=e;return Array.from(n).forEach(e=>{if(e.name.startsWith("data-lucia-meta-")){const n=e.name.replace("data-lucia-meta-","").replace(/-([a-z])/g,e=>e[1].toUpperCase());t[n]=e.value}}),Object.keys(t).length>0?t:null}}const I={name:"clicks",configKey:"autoTrackClicks",factory:(e,t,n,i)=>new S(e,t,n,i),normalizeConfig:function(e){return void 0===e||!1===e?null:!0===e?{enabled:!0}:!1===e.enabled?null:e}},P=new n(o.store);function E(){return t(this,void 0,void 0,function*(){try{const{ethereum:e}=window;if(!(null==e?void 0:e.request))return null;const t=yield e.request({method:"eth_accounts"});return t&&t.length>0?t[0]:null}catch(e){return P.log("error","Error checking connected wallet:",e),null}})}function O(){return t(this,void 0,void 0,function*(){try{if(!window.ethereum)return null;if(window.ethereum.isMetaMask)return"MetaMask";if(!window.ethereum.request)return null;return(yield window.ethereum.request({method:"wallet_getName"}))||null}catch(e){return P.log("error","Error getting wallet name:",e),null}})}function x(){return t(this,void 0,void 0,function*(){if(!window.ethereum)return null;const e={isMetaMask:!!window.ethereum.isMetaMask,isCoinbaseWallet:!!window.ethereum.isCoinbaseWallet||!!window.ethereum.isCoinbase,isWalletConnect:!!window.ethereum.isWalletConnect,isTrust:!!window.ethereum.isTrust||!!window.ethereum.isTrustWallet,isImToken:!!window.ethereum.isImToken,isBraveWallet:!!window.ethereum.isBraveWallet,isTokenPocket:!!window.ethereum.isTokenPocket,isStatus:!!window.ethereum.isStatus,isTally:!(!window.ethereum.isTally&&!window.ethereum.isTallyWallet),isAlphaWallet:!!window.ethereum.isAlphaWallet,isOpera:!!window.ethereum.isOpera,isCoin98:!!window.ethereum.isCoin98,isMathWallet:!!window.ethereum.isMathWallet,isOneInch:!(!window.ethereum.isOneInchIOSWallet&&!window.ethereum.isOneInchAndroidWallet),isRainbow:!!window.ethereum.isRainbow,isBinanceChainWallet:!1,isFrame:!!window.ethereum.isFrame,userAgent:window.navigator.userAgent,chainId:window.ethereum.chainId||void 0,networkVersion:window.ethereum.networkVersion||void 0,name:""};return Object.values(e).some(Boolean)||(Object.prototype.hasOwnProperty.call(window.ethereum,"_metamask")&&(e.isMetaMask=!0),window.BinanceChain&&(e.isBinanceChainWallet=!0),window.ethereum.isFrame&&(e.isFrame=!0),"function"==typeof window.ethereum.request&&void 0===window.ethereum._metamask&&(e.isPossiblyGenericInjectedProvider=!0)),e.name=function(e){if(e.isMetaMask)return"MetaMask";if(e.isCoinbaseWallet)return"Coinbase Wallet";if(e.isWalletConnect)return"WalletConnect";if(e.isTrust)return"Trust Wallet";if(e.isImToken)return"imToken";if(e.isBraveWallet)return"Brave Wallet";if(e.isTokenPocket)return"TokenPocket";if(e.isStatus)return"Status";if(e.isTally)return"Tally";if(e.isAlphaWallet)return"AlphaWallet";if(e.isOpera)return"Opera";if(e.isCoin98)return"Coin98";if(e.isMathWallet)return"MathWallet";if(e.isOneInch)return"1inch Wallet";if(e.isRainbow)return"Rainbow";if(e.isBinanceChainWallet)return"Binance Chain Wallet";if(e.isFrame)return"Frame";const t=e.userAgent.toLowerCase();return t.includes("trust")?"Trust Wallet (UA)":t.includes("rainbow")?"Rainbow (UA)":"Unknown Provider"}(e),e})}const j=new n(o.store);function D(){return t(this,void 0,void 0,function*(){var e,t,n;try{if(window.solana){if(window.solana.isConnected&&window.solana.publicKey)return window.solana.publicKey.toString()}else if(window.solflare){if(window.solflare.isConnected&&window.solflare.publicKey)return window.solflare.publicKey.toString()}else if(null===(e=window.phantom)||void 0===e?void 0:e.solana)try{if((yield window.phantom.solana.connect({onlyIfTrusted:!0}))&&window.phantom.solana.publicKey)return window.phantom.solana.publicKey.toString()}catch(e){j.log("error","Error silently connecting to Phantom wallet:",e)}const i=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&i.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&i.push(window.SolanaWalletAdapterContext.current);const r=i.find(e=>e.connected&&e.publicKey);return r?r.publicKey.toString():null}catch(e){return j.log("error","Error detecting Solana wallet:",e),null}})}function W(){return t(this,void 0,void 0,function*(){var e,t,n;const i=yield D();if(!i)return null;if(null===(e=window.phantom)||void 0===e?void 0:e.solana)return"Phantom";if(window.solflare)return"Solflare";const r=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&r.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&r.push(window.SolanaWalletAdapterContext.current);const o=r.find(e=>e.connected&&e.publicKey&&e.publicKey.toString()===i);return o?o.name||"Unknown Wallet":null})}function M(){return t(this,void 0,void 0,function*(){if($)return $;const e={device:{cores:L(()=>navigator.hardwareConcurrency),memory:L(()=>navigator.deviceMemory),cpuClass:L(()=>navigator.cpuClass),touch:N(),devicePixelRatio:L(()=>window.devicePixelRatio)},screen:{width:L(()=>window.screen.width),height:L(()=>window.screen.height),colorDepth:L(()=>window.screen.colorDepth),availHeight:L(()=>window.screen.availHeight),availWidth:L(()=>window.screen.availWidth),orientation:{type:L(()=>window.screen.orientation.type),angle:L(()=>window.screen.orientation.angle)}},browser:{language:L(()=>navigator.language),encoding:L(()=>TextDecoder.encoding),timezone:L(()=>-(new Date).getTimezoneOffset()/60),pluginsLength:L(()=>navigator.plugins.length),pluginNames:L(()=>Array.from(navigator.plugins,e=>e.name)),applePayAvailable:B(),uniqueHash:yield _(),colorGamut:z(),contrastPreference:q()},permissions:{navPer:L(()=>navigator.permissions.webglVersion),renderedPer:L(()=>navigator.permissions.RENDERER),geoPer:L(()=>navigator.permissions.geolocation)},storage:{localStorage:L(()=>!!window.localStorage),indexedDB:L(()=>!!window.indexedDB),openDB:L(()=>window.openDatabase)}};return $=e,e})}function R(){return t(this,void 0,void 0,function*(){const[e,t,n,i,r]=yield Promise.all([D(),E(),O(),W(),x()]);return{walletAddress:t,solanaAddress:e,providerInfo:r&&K(r),walletName:n,solWalletName:i}})}function U(){const e=new URL(window.location.href).searchParams,t={};return e.forEach((e,n)=>{(n.startsWith("utm_")||n.includes("id")||"ref"===n||"source"===n)&&(t[n]=e)}),t}function L(e,t){try{return e()}catch(e){return t}}function K(e){const t={};return Object.keys(e).forEach(n=>{const i=n;e[i]&&(t[i]=e[i])}),t}let $=null;function _(){return t(this,void 0,void 0,function*(){try{const e=document.createElement("canvas"),n=e.getContext("2d",{willReadFrequently:!0});if(!n)return;const i=200,r=120;e.width=i,e.height=r,e.style.width=`${i}px`,e.style.height=`${r}px`,n.fillStyle="#ffffff",n.fillRect(0,0,i,r),n.fillStyle="#ff00ff",n.fillRect(10,10,100,100),n.fillStyle="#00ffff",n.beginPath(),n.arc(150,50,40,0,2*Math.PI,!0),n.fill();const{data:o}=n.getImageData(0,0,i,r);return function(e){return t(this,void 0,void 0,function*(){const t=(new TextEncoder).encode(e),n=yield crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")})}([[20,20],[60,60],[100,100],[150,50],[150,60],[140,50],[5,5]].map(([e,t])=>{const n=4*(t*i+e);return`${o[n]},${o[n+1]},${o[n+2]},${o[n+3]};`}).join(""))}catch(e){return}})}function N(){try{return!!document.createEvent("TouchEvent")}catch(e){return!1}}function B(){var e;try{return"function"==typeof(null===(e=window.ApplePaySession)||void 0===e?void 0:e.canMakePayments)&&window.ApplePaySession.canMakePayments()}catch(e){return}}function q(){try{const{matchMedia:e}=window,t=t=>e(`(prefers-contrast: ${t})`).matches;return t("no-preference")?"None":t("high")||t("more")?"More":t("low")||t("less")?"Less":t("forced")?"ForcedColors":void 0}catch(e){return}}function z(){try{return["rec2020","p3","srgb","display-p3","adobe-rgb"].filter(e=>window.matchMedia(`(color-gamut: ${e})`).matches)}catch(e){return[]}}v.register(I);let V=class extends p{authenticate(){this.httpClient.post("/api/key/auth",{})}init(){return t(this,void 0,void 0,function*(){let e=g();e||(e=f());const t=yield M(),n=new URL(window.location.href).searchParams.get("lucia"),i=yield R(),r={id:e.id};e.hash&&(r.hash=e.hash);const o=yield this.httpClient.post("/api/sdk/init",{user:{name:m()},data:t,walletData:i,session:r,redirectHash:n,utm:U()},!1);o&&(o.lid&&localStorage.setItem("lid",o.lid),o.session&&function(e){const t={id:e.id,hash:e.hash,timestamp:Date.now()};sessionStorage.setItem(d,JSON.stringify(t))}(o.session)),v.initAll(this.store.config,{clicks:this.handleAutoTrackedClick.bind(this)},this.logger)})}handleAutoTrackedClick(e){const t=e,n={elementType:t.elementType,text:t.text,href:t.href,meta:t.meta};this.buttonClick(t.button,n)}userInfo(e,n){return t(this,void 0,void 0,function*(){const t=w(),i=g();e&&localStorage.setItem("luc_uid",e);const r=Object.assign({user:{name:e,userInfo:n},session:i},t&&{lid:t});yield this.httpClient.post("/api/sdk/user",r)})}pageView(e){return t(this,void 0,void 0,function*(){const t=w(),n=g(),i=Object.assign({page:e,user:{name:m()},session:n},t&&{lid:t});yield this.httpClient.post("/api/sdk/page",i)})}trackConversion(e,n,i){return t(this,void 0,void 0,function*(){const t=w(),r=g(),o=Object.assign({tag:e,amount:n,event:i,user:{name:m()},session:r},t&&{lid:t});yield this.httpClient.post("/api/sdk/conversion",o)})}buttonClick(e,n){return t(this,void 0,void 0,function*(){const t=w(),i=g(),r=Object.assign(Object.assign({button:e,user:{name:m()},session:i},t&&{lid:t}),n&&Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n.elementType&&{elementType:n.elementType}),n.text&&{text:n.text}),void 0!==n.href&&{href:n.href}),n.meta&&{meta:n.meta}),{timestamp:Date.now()}));yield this.httpClient.post("/api/sdk/click",r)})}sendWalletInfo(e,n,i){return t(this,void 0,void 0,function*(){const t=w(),r=g(),o=Object.assign({walletAddress:e,chainId:n,walletName:i,user:{name:m()},session:r},t&&{lid:t});yield this.httpClient.post("/api/sdk/wallet",o)})}trackUserAcquisition(e){return t(this,arguments,void 0,function*(e,t={}){const n=yield M(),i=U(),r=g();yield this.httpClient.post("/api/sdk/acquisition",{user:{name:e},session:r,data:Object.assign({timestamp:(new Date).toISOString(),browserData:n,utmParams:i},t)})})}checkMetaMaskConnection(){var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))}destroy(){v.destroyAll()}},F=null;const Q=()=>{const e=F||"undefined"!=typeof window&&window.__luciaInitPromise;if(!e)throw new Error("LuciaSDK not initialized. Please call LuciaSDK.init() first");return e},H={init:e=>{if("undefined"==typeof window)return Promise.reject(new Error("LuciaSDK requires a browser environment"));if(F)return F;if(window.__luciaInitPromise)return F=window.__luciaInitPromise,F;if(!(null==e?void 0:e.apiKey))return Promise.reject(new Error("apiKey is required in config"));const n=t(void 0,void 0,void 0,function*(){const t=new V(e);return yield t.init(),t});return F=n,window.__luciaInitPromise=n,n},userInfo:(e,n)=>t(void 0,void 0,void 0,function*(){return(yield Q()).userInfo(e,n)}),pageView:e=>t(void 0,void 0,void 0,function*(){return(yield Q()).pageView(e)}),trackConversion:(e,n,i)=>t(void 0,void 0,void 0,function*(){return(yield Q()).trackConversion(e,n,i)}),buttonClick:(e,n)=>t(void 0,void 0,void 0,function*(){return(yield Q()).buttonClick(e,n)}),sendWalletInfo:(e,n,i)=>t(void 0,void 0,void 0,function*(){return(yield Q()).sendWalletInfo(e,n,i)}),trackUserAcquisition:(e,...n)=>t(void 0,[e,...n],void 0,function*(e,t={}){return(yield Q()).trackUserAcquisition(e,t)}),checkMetaMaskConnection:()=>{var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))},VERSION:i};if("undefined"!=typeof window){window.LuciaSDK=H;const e=()=>{const e=document.currentScript||document.querySelector("script[data-api-key]"),t=null==e?void 0:e.getAttribute("data-api-key");if(!t)return;const n=e.getAttribute("data-debug-url"),i=e.getAttribute("data-auto-track-clicks"),r=e.getAttribute("data-track-selectors");H.init(Object.assign(Object.assign(Object.assign({apiKey:t},n&&{debugURL:n}),"true"===i&&{autoTrackClicks:!r||{enabled:!0,selectors:r.split(",").map(e=>e.trim())}}),"false"===i&&{autoTrackClicks:!1})).catch(e=>console.error("LuciaSDK auto-init failed:",e))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}e.__resetInstance=()=>{const e=F||"undefined"!=typeof window&&window.__luciaInitPromise;e&&e.then(e=>e.destroy()).catch(()=>{}),F=null,"undefined"!=typeof window&&delete window.__luciaInitPromise,v.reset()},e.default=H,e.filterObject=K,e.getApplePayAvailable=B,e.getBrowserData=M,e.getCanvasFingerprint=_,e.getColorGamut=z,e.getContrastPreference=q,e.getUtmParams=U,e.getWalletData=R,e.isTouchEnabled=N,e.safeAccess=L,Object.defineProperty(e,"__esModule",{value:!0})});
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LuciaSDK={})}(this,function(e){"use strict";function t(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class n{constructor(e){this.store=e}log(e,...t){var n;(null===(n=this.store.config)||void 0===n?void 0:n.debug)&&console[e](t)}}const i="0.9.10";class r{constructor(e){this.requestQueue=[],this.isProcessingQueue=!1,this.initComplete=!1,this.store=e,this.baseURL=this.getBaseURL(),this.logger=new n(this.store)}getBaseURL(){const{config:e}=this.store;return(null==e?void 0:e.debugURL)?e.debugURL:(null==e?void 0:e.testENV)?"http://52.22.177.60/fk":"https://api.clickinsights.xyz"}get(e){return t(this,void 0,void 0,function*(){if(!this.store.config)return this.logger.log("error","Config is not set"),null;try{const t=yield fetch(`${this.baseURL}${e}`,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":i}});return yield t.json()}catch(e){this.logger.log("error",e)}return null})}post(e,n){return t(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;const i="/api/sdk/init"===e;if(!i&&!this.initComplete)return new Promise((r,o)=>{this.requestQueue.push({url:e,data:t,fireAndForget:n,resolve:r,reject:o,isInit:i}),this.processQueue()});if(i){const i=yield this.executePost(e,t,n);return this.initComplete=!0,yield this.processQueue(),i}return this.executePost(e,t,n)})}processQueue(){return t(this,void 0,void 0,function*(){if(!this.isProcessingQueue&&this.initComplete&&0!==this.requestQueue.length){this.isProcessingQueue=!0;try{const e=()=>t(this,void 0,void 0,function*(){if(0===this.requestQueue.length)return;const t=this.requestQueue.shift();try{const e=yield this.executePost(t.url,t.data,t.fireAndForget);t.resolve(e)}catch(e){t.reject(e)}yield e()});yield e()}finally{this.isProcessingQueue=!1}}})}executePost(e,n){return t(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;if(n&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){try{const n=`${this.baseURL}${e}`,i=t&&"object"==typeof t&&!Array.isArray(t)?t:{payload:t},r=JSON.stringify(Object.assign(Object.assign({},i),{_apiKey:this.store.config.apiKey})),o=new Blob([r],{type:"application/json"});navigator.sendBeacon(n,o)||this.logger.log("error","sendBeacon failed")}catch(e){this.logger.log("error",e)}return null}try{const n=yield fetch(`${this.baseURL}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":i},body:JSON.stringify(t)});return yield n.json()}catch(e){this.logger.log("error",e)}return null})}}class o{static dispatch(e){Object.keys(e).forEach(t=>{if(Object.keys(o.store).includes(t)){const n=e[t];o.store[t]="object"==typeof n?Array.isArray(n)?[...n]:Object.assign({},n):n}})}}o.store={isInitialized:!1,config:null,session:null};const s=[];for(let e=0;e<256;++e)s.push((e+256).toString(16).slice(1));let a;const l=new Uint8Array(16);var c={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function u(e,t,n){const i=(e=e||{}).random??e.rng?.()??function(){if(!a){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");a=crypto.getRandomValues.bind(crypto)}return a(l)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return(s[e[t+0]]+s[e[t+1]]+s[e[t+2]]+s[e[t+3]]+"-"+s[e[t+4]]+s[e[t+5]]+"-"+s[e[t+6]]+s[e[t+7]]+"-"+s[e[t+8]]+s[e[t+9]]+"-"+s[e[t+10]]+s[e[t+11]]+s[e[t+12]]+s[e[t+13]]+s[e[t+14]]+s[e[t+15]]).toLowerCase()}(i)}const d="luci_session",h=new n(o.store);function g(){try{const e=sessionStorage.getItem(d);return e?JSON.parse(e):null}catch(e){return h.log("error","Error retrieving session data:",e),null}}function f(){var e;const t={id:c.randomUUID&&!e?c.randomUUID():u(e),timestamp:Date.now()};return sessionStorage.setItem(d,JSON.stringify(t)),t}function w(){const e=localStorage.getItem("lid");return"undefined"===e||"null"===e?(localStorage.removeItem("lid"),null):e}function m(){const e=localStorage.getItem("luc_uid");return"undefined"===e||"null"===e?(localStorage.removeItem("luc_uid"),null):e}class p{constructor(e){this.store=o.store,this.dispatch=o.dispatch,this.dispatch({config:e}),this.httpClient=new r(this.store),this.logger=new n(this.store)}}class y{constructor(e,t,n,i){this.enabled=!1,this.sdkConfig=e,this.config=t,this.callback=n,this.logger=i}enable(){this.enabled||(this.enabled=!0,this.attachListeners(),this.logger.log("log",`${this.name}: Enabled`))}disable(){this.enabled&&(this.enabled=!1,this.logger.log("log",`${this.name}: Disabled`))}destroy(){this.disable(),this.detachListeners(),this.logger.log("log",`${this.name}: Destroyed`)}isEnabled(){return this.enabled}}const v=new class{constructor(){this.registrations=new Map,this.activeTrackers=new Map,this.logger=null}register(e){this.registrations.set(e.name,e)}initAll(e,t,n){this.logger=n;for(const[i,r]of this.registrations){const o=e[r.configKey],s=r.normalizeConfig(o);if(null===s)continue;const a=t[i];if(a)try{const t=r.factory(e,s,a,n);this.activeTrackers.set(i,t),t.enable(),n.log("log",`AutoTrackerRegistry: Initialized ${i}`)}catch(e){n.log("error",`AutoTrackerRegistry: Failed to initialize ${i}`,e)}else n.log("warn",`AutoTrackerRegistry: No callback registered for ${i}`)}}get(e){return this.activeTrackers.get(e)}enable(e){const t=this.activeTrackers.get(e);return!!t&&(t.enable(),!0)}disable(e){const t=this.activeTrackers.get(e);return!!t&&(t.disable(),!0)}destroyAll(){var e;for(const[t,n]of this.activeTrackers)try{n.destroy()}catch(n){null===(e=this.logger)||void 0===e||e.log("error",`AutoTrackerRegistry: Error destroying ${t}`,n)}this.activeTrackers.clear()}getRegisteredTrackers(){return Array.from(this.registrations.keys())}getActiveTrackers(){return Array.from(this.activeTrackers.keys())}reset(){this.destroyAll(),this.logger=null}},b=['input[type="password"]','input[type="text"][autocomplete*="cc-"]','input[type="text"][autocomplete*="card"]','input[type="text"][name*="card"]','input[type="text"][name*="cvv"]','input[type="text"][name*="cvc"]','input[name*="ssn"]','input[name*="social"]',"[data-sensitive]","[data-private]"],k=[/\b\d{3}-\d{2}-\d{4}\b/,/\b\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4}\b/,/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i];const C=new class{constructor(e=[]){this.sensitiveSelectors=[...b,...e]}isSensitive(e){if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;let t=e.parentElement;for(;t;){const e=t;if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;t=t.parentElement}return!1}containsSensitiveData(e){return!!e&&k.some(t=>t.test(e))}sanitizeText(e){if(!e)return"";let t=e;return t=t.replace(/\b\d{3}-\d{2}-\d{4}\b/g,"***-**-****"),t=t.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,"****-****-****-****"),t=t.replace(/\b([A-Z0-9._%+-]+)@([A-Z0-9.-]+\.[A-Z]{2,})\b/gi,"***@$2"),t}},T=["button","a[href]",'[role="button"]'],A=["[data-lucia-ignore]",'[data-lucia-track="false"]'];class S extends y{constructor(e,t,n,i){var r,o,s;super(e,{enabled:null===(r=t.enabled)||void 0===r||r,selectors:null!==(o=t.selectors)&&void 0!==o?o:T,ignore:null!==(s=t.ignore)&&void 0!==s?s:A},n,i),this.name="clicks",this.configKey="autoTrackClicks",this.debounceTimers=new Map,this.listenerAttached=!1,this.boundHandleClick=null,this.privacyGuard=C}attachListeners(){this.listenerAttached||("undefined"!=typeof document?(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,{passive:!0,capture:!1}),this.listenerAttached=!0,this.logger.log("log","ClickTracker: Delegated click listener attached")):this.logger.log("warn","ClickTracker: document not available, cannot attach listener"))}detachListeners(){this.listenerAttached&&this.boundHandleClick&&"undefined"!=typeof document&&(document.removeEventListener("click",this.boundHandleClick),this.listenerAttached=!1),this.debounceTimers.clear(),this.boundHandleClick=null}handleClick(e){if(!this.enabled)return;const t=e.target;if(!t)return;const n=this.findTrackableElement(t);if(!n)return;if(this.shouldIgnore(n))return void this.logger.log("log","ClickTracker: Element ignored",n);if(this.privacyGuard.isSensitive(n))return void this.logger.log("warn","ClickTracker: Sensitive element not tracked",n);if(this.isDebounced(n))return void this.logger.log("log","ClickTracker: Click debounced",n);const i=this.extractTrackingData(n);i&&(this.logger.log("log","ClickTracker: Tracking click",i),this.callback(i))}findTrackableElement(e){const t=this.config.selectors||T;try{const n=e.closest('[data-lucia-track]:not([data-lucia-track="false"])');if(n&&n!==document.body&&document.body.contains(n)){if(this.config.selectors&&this.config.selectors!==T){return t.some(e=>{try{return n.matches(e)}catch(e){return!1}})?n:null}return n}const i=t.join(", "),r=e.closest(i);return r&&r!==document.body&&document.body.contains(r)?r:null}catch(t){this.logger.log("warn","ClickTracker: Invalid combined selector, using fallback",t);let n=e;for(;n&&n!==document.body;){if(this.isTrackable(n))return n;n=n.parentElement}return null}}isTrackable(e){return(this.config.selectors||T).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid selector "${t}"`,e),!1}})}shouldIgnore(e){return(this.config.ignore||A).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid ignore selector "${t}"`,e),!1}})}isDebounced(e){const t=Date.now(),n=this.debounceTimers.get(e);return!!(n&&t-n<500)||(this.debounceTimers.set(e,t),this.debounceTimers.size>100&&this.cleanupDebounceTimers(),!1)}cleanupDebounceTimers(){const e=Date.now();Array.from(this.debounceTimers.entries()).forEach(([t,n])=>{e-n>1e3&&this.debounceTimers.delete(t)})}extractTrackingData(e){var t;const n=this.getElementIdentifier(e);if(!n)return this.logger.log("warn","ClickTracker: Could not generate identifier for element",e),null;const i={button:n,elementType:this.getElementType(e),timestamp:Date.now()},r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&(this.privacyGuard.containsSensitiveData(r)||(i.text=this.sanitizeText(r))),"a"===e.tagName.toLowerCase()?i.href=e.getAttribute("href"):i.href=null;const o=this.extractMetadata(e);return o&&Object.keys(o).length>0&&(i.meta=o),i}getElementIdentifier(e){var t;const n=e.getAttribute("data-lucia-track");if(n&&"false"!==n)return n;const i=e.getAttribute("id");if(i)return i;const r=e.getAttribute("name");if(r)return r;const o=e.getAttribute("aria-label");if(o)return o;if("a"===e.tagName.toLowerCase()){const t=e.getAttribute("href");if(t)return`link:${t}`}const s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(s)return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using text content as identifier for element. Consider adding data-lucia-track attribute.",e),`text:${this.sanitizeText(s).substring(0,50)}`;const a=this.generateCSSPath(e);return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using CSS path as identifier. Consider adding data-lucia-track attribute.",e),`path:${a}`}getElementType(e){const t=e.tagName.toLowerCase();if("a"===t)return"link";if("button"===t)return"button";const n=e.getAttribute("role");return n||t}sanitizeText(e){return e.trim().replace(/\s+/g," ").substring(0,100)}generateCSSPath(e){const t=[];let n=e;for(;n&&n!==document.body&&t.length<5;){let e=n.tagName.toLowerCase();if(n.id){e+=`#${n.id}`,t.unshift(e);break}const i=n.getAttribute("class");if(i){const t=i.trim().split(/\s+/).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}t.unshift(e),n=n.parentElement}return t.join(" > ")}extractMetadata(e){const t={},{attributes:n}=e;return Array.from(n).forEach(e=>{if(e.name.startsWith("data-lucia-meta-")){const n=e.name.replace("data-lucia-meta-","").replace(/-([a-z])/g,e=>e[1].toUpperCase());t[n]=e.value}}),Object.keys(t).length>0?t:null}}const I={name:"clicks",configKey:"autoTrackClicks",factory:(e,t,n,i)=>new S(e,t,n,i),normalizeConfig:function(e){return void 0===e||!1===e?null:!0===e?{enabled:!0}:!1===e.enabled?null:e}},P=new n(o.store);function E(){return t(this,void 0,void 0,function*(){try{const{ethereum:e}=window;if(!(null==e?void 0:e.request))return null;const t=yield e.request({method:"eth_accounts"});return t&&t.length>0?t[0]:null}catch(e){return P.log("error","Error checking connected wallet:",e),null}})}function O(){return t(this,void 0,void 0,function*(){try{if(!window.ethereum)return null;if(window.ethereum.isMetaMask)return"MetaMask";if(!window.ethereum.request)return null;return(yield window.ethereum.request({method:"wallet_getName"}))||null}catch(e){return P.log("error","Error getting wallet name:",e),null}})}function x(){return t(this,void 0,void 0,function*(){if(!window.ethereum)return null;const e={isMetaMask:!!window.ethereum.isMetaMask,isCoinbaseWallet:!!window.ethereum.isCoinbaseWallet||!!window.ethereum.isCoinbase,isWalletConnect:!!window.ethereum.isWalletConnect,isTrust:!!window.ethereum.isTrust||!!window.ethereum.isTrustWallet,isImToken:!!window.ethereum.isImToken,isBraveWallet:!!window.ethereum.isBraveWallet,isTokenPocket:!!window.ethereum.isTokenPocket,isStatus:!!window.ethereum.isStatus,isTally:!(!window.ethereum.isTally&&!window.ethereum.isTallyWallet),isAlphaWallet:!!window.ethereum.isAlphaWallet,isOpera:!!window.ethereum.isOpera,isCoin98:!!window.ethereum.isCoin98,isMathWallet:!!window.ethereum.isMathWallet,isOneInch:!(!window.ethereum.isOneInchIOSWallet&&!window.ethereum.isOneInchAndroidWallet),isRainbow:!!window.ethereum.isRainbow,isBinanceChainWallet:!1,isFrame:!!window.ethereum.isFrame,userAgent:window.navigator.userAgent,chainId:window.ethereum.chainId||void 0,networkVersion:window.ethereum.networkVersion||void 0,name:""};return Object.values(e).some(Boolean)||(Object.prototype.hasOwnProperty.call(window.ethereum,"_metamask")&&(e.isMetaMask=!0),window.BinanceChain&&(e.isBinanceChainWallet=!0),window.ethereum.isFrame&&(e.isFrame=!0),"function"==typeof window.ethereum.request&&void 0===window.ethereum._metamask&&(e.isPossiblyGenericInjectedProvider=!0)),e.name=function(e){if(e.isMetaMask)return"MetaMask";if(e.isCoinbaseWallet)return"Coinbase Wallet";if(e.isWalletConnect)return"WalletConnect";if(e.isTrust)return"Trust Wallet";if(e.isImToken)return"imToken";if(e.isBraveWallet)return"Brave Wallet";if(e.isTokenPocket)return"TokenPocket";if(e.isStatus)return"Status";if(e.isTally)return"Tally";if(e.isAlphaWallet)return"AlphaWallet";if(e.isOpera)return"Opera";if(e.isCoin98)return"Coin98";if(e.isMathWallet)return"MathWallet";if(e.isOneInch)return"1inch Wallet";if(e.isRainbow)return"Rainbow";if(e.isBinanceChainWallet)return"Binance Chain Wallet";if(e.isFrame)return"Frame";const t=e.userAgent.toLowerCase();return t.includes("trust")?"Trust Wallet (UA)":t.includes("rainbow")?"Rainbow (UA)":"Unknown Provider"}(e),e})}const j=new n(o.store);function D(){return t(this,void 0,void 0,function*(){var e,t,n;try{if(window.solana){if(window.solana.isConnected&&window.solana.publicKey)return window.solana.publicKey.toString()}else if(window.solflare){if(window.solflare.isConnected&&window.solflare.publicKey)return window.solflare.publicKey.toString()}else if(null===(e=window.phantom)||void 0===e?void 0:e.solana)try{if((yield window.phantom.solana.connect({onlyIfTrusted:!0}))&&window.phantom.solana.publicKey)return window.phantom.solana.publicKey.toString()}catch(e){j.log("error","Error silently connecting to Phantom wallet:",e)}const i=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&i.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&i.push(window.SolanaWalletAdapterContext.current);const r=i.find(e=>e.connected&&e.publicKey);return r?r.publicKey.toString():null}catch(e){return j.log("error","Error detecting Solana wallet:",e),null}})}function W(){return t(this,void 0,void 0,function*(){var e,t,n;const i=yield D();if(!i)return null;if(null===(e=window.phantom)||void 0===e?void 0:e.solana)return"Phantom";if(window.solflare)return"Solflare";const r=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&r.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&r.push(window.SolanaWalletAdapterContext.current);const o=r.find(e=>e.connected&&e.publicKey&&e.publicKey.toString()===i);return o?o.name||"Unknown Wallet":null})}function M(){return t(this,void 0,void 0,function*(){if($)return $;const e={device:{cores:L(()=>navigator.hardwareConcurrency),memory:L(()=>navigator.deviceMemory),cpuClass:L(()=>navigator.cpuClass),touch:N(),devicePixelRatio:L(()=>window.devicePixelRatio)},screen:{width:L(()=>window.screen.width),height:L(()=>window.screen.height),colorDepth:L(()=>window.screen.colorDepth),availHeight:L(()=>window.screen.availHeight),availWidth:L(()=>window.screen.availWidth),orientation:{type:L(()=>window.screen.orientation.type),angle:L(()=>window.screen.orientation.angle)}},browser:{language:L(()=>navigator.language),encoding:L(()=>TextDecoder.encoding),timezone:L(()=>-(new Date).getTimezoneOffset()/60),pluginsLength:L(()=>navigator.plugins.length),pluginNames:L(()=>Array.from(navigator.plugins,e=>e.name)),applePayAvailable:B(),uniqueHash:yield _(),colorGamut:z(),contrastPreference:q()},permissions:{navPer:L(()=>navigator.permissions.webglVersion),renderedPer:L(()=>navigator.permissions.RENDERER),geoPer:L(()=>navigator.permissions.geolocation)},storage:{localStorage:L(()=>!!window.localStorage),indexedDB:L(()=>!!window.indexedDB),openDB:L(()=>window.openDatabase)}};return $=e,e})}function R(){return t(this,void 0,void 0,function*(){const[e,t,n,i,r]=yield Promise.all([D(),E(),O(),W(),x()]);return{walletAddress:t,solanaAddress:e,providerInfo:r&&K(r),walletName:n,solWalletName:i}})}function U(){const e=new URL(window.location.href).searchParams,t={};return e.forEach((e,n)=>{(n.startsWith("utm_")||n.includes("id")||"ref"===n||"source"===n)&&(t[n]=e)}),t}function L(e,t){try{return e()}catch(e){return t}}function K(e){const t={};return Object.keys(e).forEach(n=>{const i=n;e[i]&&(t[i]=e[i])}),t}let $=null;function _(){return t(this,void 0,void 0,function*(){try{const e=document.createElement("canvas"),n=e.getContext("2d",{willReadFrequently:!0});if(!n)return;const i=200,r=120;e.width=i,e.height=r,e.style.width=`${i}px`,e.style.height=`${r}px`,n.fillStyle="#ffffff",n.fillRect(0,0,i,r),n.fillStyle="#ff00ff",n.fillRect(10,10,100,100),n.fillStyle="#00ffff",n.beginPath(),n.arc(150,50,40,0,2*Math.PI,!0),n.fill();const{data:o}=n.getImageData(0,0,i,r);return function(e){return t(this,void 0,void 0,function*(){const t=(new TextEncoder).encode(e),n=yield crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")})}([[20,20],[60,60],[100,100],[150,50],[150,60],[140,50],[5,5]].map(([e,t])=>{const n=4*(t*i+e);return`${o[n]},${o[n+1]},${o[n+2]},${o[n+3]};`}).join(""))}catch(e){return}})}function N(){try{return!!document.createEvent("TouchEvent")}catch(e){return!1}}function B(){var e;try{return"function"==typeof(null===(e=window.ApplePaySession)||void 0===e?void 0:e.canMakePayments)&&window.ApplePaySession.canMakePayments()}catch(e){return}}function q(){try{const{matchMedia:e}=window,t=t=>e(`(prefers-contrast: ${t})`).matches;return t("no-preference")?"None":t("high")||t("more")?"More":t("low")||t("less")?"Less":t("forced")?"ForcedColors":void 0}catch(e){return}}function z(){try{return["rec2020","p3","srgb","display-p3","adobe-rgb"].filter(e=>window.matchMedia(`(color-gamut: ${e})`).matches)}catch(e){return[]}}v.register(I);let V=class extends p{authenticate(){this.httpClient.post("/api/key/auth",{})}init(){return t(this,void 0,void 0,function*(){let e=g();e||(e=f());const t=yield M(),n=new URL(window.location.href).searchParams.get("lucia"),i=yield R(),r={id:e.id};e.hash&&(r.hash=e.hash);const o=yield this.httpClient.post("/api/sdk/init",{user:{name:m()},data:t,walletData:i,session:r,redirectHash:n,utm:U()},!1);o&&(o.lid&&localStorage.setItem("lid",o.lid),o.session&&function(e){const t={id:e.id,hash:e.hash,timestamp:Date.now()};sessionStorage.setItem(d,JSON.stringify(t))}(o.session)),v.initAll(this.store.config,{clicks:this.handleAutoTrackedClick.bind(this)},this.logger)})}handleAutoTrackedClick(e){const t=e,n={elementType:t.elementType,text:t.text,href:t.href,meta:t.meta};this.buttonClick(t.button,n)}userInfo(e,n){return t(this,void 0,void 0,function*(){const t=w(),i=g();e&&localStorage.setItem("luc_uid",e);const r=Object.assign({user:{name:e,userInfo:n},session:i},t&&{lid:t});yield this.httpClient.post("/api/sdk/user",r)})}pageView(e){return t(this,void 0,void 0,function*(){const t=w(),n=g(),i=Object.assign({page:e,user:{name:m()},session:n},t&&{lid:t});yield this.httpClient.post("/api/sdk/page",i)})}trackConversion(e,n,i){return t(this,void 0,void 0,function*(){const t=w(),r=g(),o=Object.assign({tag:e,amount:n,event:i,user:{name:m()},session:r},t&&{lid:t});yield this.httpClient.post("/api/sdk/conversion",o)})}buttonClick(e,n){return t(this,void 0,void 0,function*(){const t=w(),i=g(),r=Object.assign(Object.assign({button:e,user:{name:m()},session:i},t&&{lid:t}),n&&Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n.elementType&&{elementType:n.elementType}),n.text&&{text:n.text}),void 0!==n.href&&{href:n.href}),n.meta&&{meta:n.meta}),{timestamp:Date.now()}));yield this.httpClient.post("/api/sdk/click",r)})}sendWalletInfo(e,n,i){return t(this,void 0,void 0,function*(){const t=w(),r=g(),o=Object.assign({walletAddress:e,chainId:n,walletName:i,user:{name:m()},session:r},t&&{lid:t});yield this.httpClient.post("/api/sdk/wallet",o)})}trackUserAcquisition(e){return t(this,arguments,void 0,function*(e,t={}){const n=yield M(),i=U(),r=g();yield this.httpClient.post("/api/sdk/acquisition",{user:{name:e},session:r,data:Object.assign({timestamp:(new Date).toISOString(),browserData:n,utmParams:i},t)})})}checkMetaMaskConnection(){var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))}destroy(){v.destroyAll()}},F=null;const Q=()=>{const e=F||"undefined"!=typeof window&&window.__luciaInitPromise;if(!e)throw new Error("LuciaSDK not initialized. Please call LuciaSDK.init() first");return e},H={init:e=>{if("undefined"==typeof window)return Promise.reject(new Error("LuciaSDK requires a browser environment"));if(F)return F;if(window.__luciaInitPromise)return F=window.__luciaInitPromise,F;if(!(null==e?void 0:e.apiKey))return Promise.reject(new Error("apiKey is required in config"));const n=t(void 0,void 0,void 0,function*(){const t=new V(e);return yield t.init(),t});return F=n,window.__luciaInitPromise=n,n},userInfo:(e,n)=>t(void 0,void 0,void 0,function*(){return(yield Q()).userInfo(e,n)}),pageView:e=>t(void 0,void 0,void 0,function*(){return(yield Q()).pageView(e)}),trackConversion:(e,n,i)=>t(void 0,void 0,void 0,function*(){return(yield Q()).trackConversion(e,n,i)}),buttonClick:(e,n)=>t(void 0,void 0,void 0,function*(){return(yield Q()).buttonClick(e,n)}),sendWalletInfo:(e,n,i)=>t(void 0,void 0,void 0,function*(){return(yield Q()).sendWalletInfo(e,n,i)}),trackUserAcquisition:(e,...n)=>t(void 0,[e,...n],void 0,function*(e,t={}){return(yield Q()).trackUserAcquisition(e,t)}),checkMetaMaskConnection:()=>{var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))},VERSION:i};if("undefined"!=typeof window){window.LuciaSDK=H;const e=()=>{const e=document.currentScript||document.querySelector("script[data-api-key]"),t=null==e?void 0:e.getAttribute("data-api-key");if(!t)return;const n=e.getAttribute("data-debug-url"),i=e.getAttribute("data-auto-track-clicks"),r=e.getAttribute("data-track-selectors");H.init(Object.assign(Object.assign(Object.assign({apiKey:t},n&&{debugURL:n}),"true"===i&&{autoTrackClicks:!r||{enabled:!0,selectors:r.split(",").map(e=>e.trim())}}),"false"===i&&{autoTrackClicks:!1})).catch(e=>console.error("LuciaSDK auto-init failed:",e))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}e.__resetInstance=()=>{const e=F||"undefined"!=typeof window&&window.__luciaInitPromise;e&&e.then(e=>e.destroy()).catch(()=>{}),F=null,"undefined"!=typeof window&&delete window.__luciaInitPromise,v.reset()},e.default=H,e.filterObject=K,e.getApplePayAvailable=B,e.getBrowserData=M,e.getCanvasFingerprint=_,e.getColorGamut=z,e.getContrastPreference=q,e.getUtmParams=U,e.getWalletData=R,e.isTouchEnabled=N,e.safeAccess=L,Object.defineProperty(e,"__esModule",{value:!0})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LuciaSDK={})}(this,function(e){"use strict";function t(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class n{constructor(e){this.store=e}log(e,...t){var n;(null===(n=this.store.config)||void 0===n?void 0:n.debug)&&console[e](t)}}const i="0.9.12";class r{constructor(e){this.requestQueue=[],this.isProcessingQueue=!1,this.initComplete=!1,this.store=e,this.baseURL=this.getBaseURL(),this.logger=new n(this.store)}getBaseURL(){const{config:e}=this.store;return(null==e?void 0:e.debugURL)?e.debugURL:(null==e?void 0:e.testENV)?"http://52.22.177.60/fk":"https://api.clickinsights.xyz"}get(e){return t(this,void 0,void 0,function*(){if(!this.store.config)return this.logger.log("error","Config is not set"),null;try{const t=yield fetch(`${this.baseURL}${e}`,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":i}});return yield t.json()}catch(e){this.logger.log("error",e)}return null})}post(e,n){return t(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;const i="/api/sdk/init"===e;if(!i&&!this.initComplete)return new Promise((r,o)=>{this.requestQueue.push({url:e,data:t,fireAndForget:n,resolve:r,reject:o,isInit:i}),this.processQueue()});if(i){const i=yield this.executePost(e,t,n);return this.initComplete=!0,yield this.processQueue(),i}return this.executePost(e,t,n)})}processQueue(){return t(this,void 0,void 0,function*(){if(!this.isProcessingQueue&&this.initComplete&&0!==this.requestQueue.length){this.isProcessingQueue=!0;try{const e=()=>t(this,void 0,void 0,function*(){if(0===this.requestQueue.length)return;const t=this.requestQueue.shift();try{const e=yield this.executePost(t.url,t.data,t.fireAndForget);t.resolve(e)}catch(e){t.reject(e)}yield e()});yield e()}finally{this.isProcessingQueue=!1}}})}executePost(e,n){return t(this,arguments,void 0,function*(e,t,n=!0){if(!this.store.config)return this.logger.log("error","Config is not set"),null;if(n&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){try{const n=`${this.baseURL}${e}`,i=t&&"object"==typeof t&&!Array.isArray(t)?t:{payload:t},r=JSON.stringify(Object.assign(Object.assign({},i),{_apiKey:this.store.config.apiKey})),o=new Blob([r],{type:"application/json"});navigator.sendBeacon(n,o)||this.logger.log("error","sendBeacon failed")}catch(e){this.logger.log("error",e)}return null}try{const n=yield fetch(`${this.baseURL}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.store.config.apiKey,"SDK-VERSION":i},body:JSON.stringify(t)});return yield n.json()}catch(e){this.logger.log("error",e)}return null})}}class o{static dispatch(e){Object.keys(e).forEach(t=>{if(Object.keys(o.store).includes(t)){const n=e[t];o.store[t]="object"==typeof n?Array.isArray(n)?[...n]:Object.assign({},n):n}})}}o.store={isInitialized:!1,config:null,session:null};const s=[];for(let e=0;e<256;++e)s.push((e+256).toString(16).slice(1));let a;const l=new Uint8Array(16);var c={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function u(e,t,n){const i=(e=e||{}).random??e.rng?.()??function(){if(!a){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");a=crypto.getRandomValues.bind(crypto)}return a(l)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return(s[e[t+0]]+s[e[t+1]]+s[e[t+2]]+s[e[t+3]]+"-"+s[e[t+4]]+s[e[t+5]]+"-"+s[e[t+6]]+s[e[t+7]]+"-"+s[e[t+8]]+s[e[t+9]]+"-"+s[e[t+10]]+s[e[t+11]]+s[e[t+12]]+s[e[t+13]]+s[e[t+14]]+s[e[t+15]]).toLowerCase()}(i)}const d="luci_session",h=new n(o.store);function g(){try{const e=sessionStorage.getItem(d);return e?JSON.parse(e):null}catch(e){return h.log("error","Error retrieving session data:",e),null}}function f(){var e;const t={id:c.randomUUID&&!e?c.randomUUID():u(e),timestamp:Date.now()};return sessionStorage.setItem(d,JSON.stringify(t)),t}function w(){const e=localStorage.getItem("lid");return"undefined"===e||"null"===e?(localStorage.removeItem("lid"),null):e}function m(){const e=localStorage.getItem("luc_uid");return"undefined"===e||"null"===e?(localStorage.removeItem("luc_uid"),null):e}class p{constructor(e){this.store=o.store,this.dispatch=o.dispatch,this.dispatch({config:e}),this.httpClient=new r(this.store),this.logger=new n(this.store)}}class y{constructor(e,t,n,i){this.enabled=!1,this.sdkConfig=e,this.config=t,this.callback=n,this.logger=i}enable(){this.enabled||(this.enabled=!0,this.attachListeners(),this.logger.log("log",`${this.name}: Enabled`))}disable(){this.enabled&&(this.enabled=!1,this.logger.log("log",`${this.name}: Disabled`))}destroy(){this.disable(),this.detachListeners(),this.logger.log("log",`${this.name}: Destroyed`)}isEnabled(){return this.enabled}}const v=new class{constructor(){this.registrations=new Map,this.activeTrackers=new Map,this.logger=null}register(e){this.registrations.set(e.name,e)}initAll(e,t,n){this.logger=n;for(const[i,r]of this.registrations){const o=e[r.configKey],s=r.normalizeConfig(o);if(null===s)continue;const a=t[i];if(a)try{const t=r.factory(e,s,a,n);this.activeTrackers.set(i,t),t.enable(),n.log("log",`AutoTrackerRegistry: Initialized ${i}`)}catch(e){n.log("error",`AutoTrackerRegistry: Failed to initialize ${i}`,e)}else n.log("warn",`AutoTrackerRegistry: No callback registered for ${i}`)}}get(e){return this.activeTrackers.get(e)}enable(e){const t=this.activeTrackers.get(e);return!!t&&(t.enable(),!0)}disable(e){const t=this.activeTrackers.get(e);return!!t&&(t.disable(),!0)}destroyAll(){var e;for(const[t,n]of this.activeTrackers)try{n.destroy()}catch(n){null===(e=this.logger)||void 0===e||e.log("error",`AutoTrackerRegistry: Error destroying ${t}`,n)}this.activeTrackers.clear()}getRegisteredTrackers(){return Array.from(this.registrations.keys())}getActiveTrackers(){return Array.from(this.activeTrackers.keys())}reset(){this.destroyAll(),this.logger=null}},b=['input[type="password"]','input[type="text"][autocomplete*="cc-"]','input[type="text"][autocomplete*="card"]','input[type="text"][name*="card"]','input[type="text"][name*="cvv"]','input[type="text"][name*="cvc"]','input[name*="ssn"]','input[name*="social"]',"[data-sensitive]","[data-private]"],k=[/\b\d{3}-\d{2}-\d{4}\b/,/\b\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4}\b/,/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i];const C=new class{constructor(e=[]){this.sensitiveSelectors=[...b,...e]}isSensitive(e){if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;let t=e.parentElement;for(;t;){const e=t;if(this.sensitiveSelectors.some(t=>{try{return e.matches(t)}catch(e){return!1}}))return!0;t=t.parentElement}return!1}containsSensitiveData(e){return!!e&&k.some(t=>t.test(e))}sanitizeText(e){if(!e)return"";let t=e;return t=t.replace(/\b\d{3}-\d{2}-\d{4}\b/g,"***-**-****"),t=t.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,"****-****-****-****"),t=t.replace(/\b([A-Z0-9._%+-]+)@([A-Z0-9.-]+\.[A-Z]{2,})\b/gi,"***@$2"),t}},T=["button","a[href]",'[role="button"]'],A=["[data-lucia-ignore]",'[data-lucia-track="false"]'];class S extends y{constructor(e,t,n,i){var r,o,s;super(e,{enabled:null===(r=t.enabled)||void 0===r||r,selectors:null!==(o=t.selectors)&&void 0!==o?o:T,ignore:null!==(s=t.ignore)&&void 0!==s?s:A},n,i),this.name="clicks",this.configKey="autoTrackClicks",this.debounceTimers=new Map,this.listenerAttached=!1,this.boundHandleClick=null,this.privacyGuard=C}attachListeners(){this.listenerAttached||("undefined"!=typeof document?(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,{passive:!0,capture:!1}),this.listenerAttached=!0,this.logger.log("log","ClickTracker: Delegated click listener attached")):this.logger.log("warn","ClickTracker: document not available, cannot attach listener"))}detachListeners(){this.listenerAttached&&this.boundHandleClick&&"undefined"!=typeof document&&(document.removeEventListener("click",this.boundHandleClick),this.listenerAttached=!1),this.debounceTimers.clear(),this.boundHandleClick=null}handleClick(e){if(!this.enabled)return;const t=e.target;if(!t)return;const n=this.findTrackableElement(t);if(!n)return;if(this.shouldIgnore(n))return void this.logger.log("log","ClickTracker: Element ignored",n);if(this.privacyGuard.isSensitive(n))return void this.logger.log("warn","ClickTracker: Sensitive element not tracked",n);if(this.isDebounced(n))return void this.logger.log("log","ClickTracker: Click debounced",n);const i=this.extractTrackingData(n);i&&(this.logger.log("log","ClickTracker: Tracking click",i),this.callback(i))}findTrackableElement(e){const t=this.config.selectors||T;try{const n=e.closest('[data-lucia-track]:not([data-lucia-track="false"])');if(n&&n!==document.body&&document.body.contains(n)){if(this.config.selectors&&this.config.selectors!==T){return t.some(e=>{try{return n.matches(e)}catch(e){return!1}})?n:null}return n}const i=t.join(", "),r=e.closest(i);return r&&r!==document.body&&document.body.contains(r)?r:null}catch(t){this.logger.log("warn","ClickTracker: Invalid combined selector, using fallback",t);let n=e;for(;n&&n!==document.body;){if(this.isTrackable(n))return n;n=n.parentElement}return null}}isTrackable(e){return(this.config.selectors||T).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid selector "${t}"`,e),!1}})}shouldIgnore(e){return(this.config.ignore||A).some(t=>{try{return e.matches(t)}catch(e){return this.logger.log("warn",`ClickTracker: Invalid ignore selector "${t}"`,e),!1}})}isDebounced(e){const t=Date.now(),n=this.debounceTimers.get(e);return!!(n&&t-n<500)||(this.debounceTimers.set(e,t),this.debounceTimers.size>100&&this.cleanupDebounceTimers(),!1)}cleanupDebounceTimers(){const e=Date.now();Array.from(this.debounceTimers.entries()).forEach(([t,n])=>{e-n>1e3&&this.debounceTimers.delete(t)})}extractTrackingData(e){var t;const n=this.getElementIdentifier(e);if(!n)return this.logger.log("warn","ClickTracker: Could not generate identifier for element",e),null;const i={button:n,elementType:this.getElementType(e),timestamp:Date.now()},r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&(this.privacyGuard.containsSensitiveData(r)||(i.text=this.sanitizeText(r))),"a"===e.tagName.toLowerCase()?i.href=e.getAttribute("href"):i.href=null;const o=this.extractMetadata(e);return o&&Object.keys(o).length>0&&(i.meta=o),i}getElementIdentifier(e){var t;const n=e.getAttribute("data-lucia-track");if(n&&"false"!==n)return n;const i=e.getAttribute("id");if(i)return i;const r=e.getAttribute("name");if(r)return r;const o=e.getAttribute("aria-label");if(o)return o;if("a"===e.tagName.toLowerCase()){const t=e.getAttribute("href");if(t)return`link:${t}`}const s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(s)return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using text content as identifier for element. Consider adding data-lucia-track attribute.",e),`text:${this.sanitizeText(s).substring(0,50)}`;const a=this.generateCSSPath(e);return this.sdkConfig.debug&&this.logger.log("warn","ClickTracker: Using CSS path as identifier. Consider adding data-lucia-track attribute.",e),`path:${a}`}getElementType(e){const t=e.tagName.toLowerCase();if("a"===t)return"link";if("button"===t)return"button";const n=e.getAttribute("role");return n||t}sanitizeText(e){return e.trim().replace(/\s+/g," ").substring(0,100)}generateCSSPath(e){const t=[];let n=e;for(;n&&n!==document.body&&t.length<5;){let e=n.tagName.toLowerCase();if(n.id){e+=`#${n.id}`,t.unshift(e);break}const i=n.getAttribute("class");if(i){const t=i.trim().split(/\s+/).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}t.unshift(e),n=n.parentElement}return t.join(" > ")}extractMetadata(e){const t={},{attributes:n}=e;return Array.from(n).forEach(e=>{if(e.name.startsWith("data-lucia-meta-")){const n=e.name.replace("data-lucia-meta-","").replace(/-([a-z])/g,e=>e[1].toUpperCase());t[n]=e.value}}),Object.keys(t).length>0?t:null}}const I={name:"clicks",configKey:"autoTrackClicks",factory:(e,t,n,i)=>new S(e,t,n,i),normalizeConfig:function(e){return void 0===e||!1===e?null:!0===e?{enabled:!0}:!1===e.enabled?null:e}},P=new n(o.store);function E(){return t(this,void 0,void 0,function*(){try{const{ethereum:e}=window;if(!(null==e?void 0:e.request))return null;const t=yield e.request({method:"eth_accounts"});return t&&t.length>0?t[0]:null}catch(e){return P.log("error","Error checking connected wallet:",e),null}})}function O(){return t(this,void 0,void 0,function*(){try{if(!window.ethereum)return null;if(window.ethereum.isMetaMask)return"MetaMask";if(!window.ethereum.request)return null;return(yield window.ethereum.request({method:"wallet_getName"}))||null}catch(e){return P.log("error","Error getting wallet name:",e),null}})}function x(){return t(this,void 0,void 0,function*(){if(!window.ethereum)return null;const e={isMetaMask:!!window.ethereum.isMetaMask,isCoinbaseWallet:!!window.ethereum.isCoinbaseWallet||!!window.ethereum.isCoinbase,isWalletConnect:!!window.ethereum.isWalletConnect,isTrust:!!window.ethereum.isTrust||!!window.ethereum.isTrustWallet,isImToken:!!window.ethereum.isImToken,isBraveWallet:!!window.ethereum.isBraveWallet,isTokenPocket:!!window.ethereum.isTokenPocket,isStatus:!!window.ethereum.isStatus,isTally:!(!window.ethereum.isTally&&!window.ethereum.isTallyWallet),isAlphaWallet:!!window.ethereum.isAlphaWallet,isOpera:!!window.ethereum.isOpera,isCoin98:!!window.ethereum.isCoin98,isMathWallet:!!window.ethereum.isMathWallet,isOneInch:!(!window.ethereum.isOneInchIOSWallet&&!window.ethereum.isOneInchAndroidWallet),isRainbow:!!window.ethereum.isRainbow,isBinanceChainWallet:!1,isFrame:!!window.ethereum.isFrame,userAgent:window.navigator.userAgent,chainId:window.ethereum.chainId||void 0,networkVersion:window.ethereum.networkVersion||void 0,name:""};return Object.values(e).some(Boolean)||(Object.prototype.hasOwnProperty.call(window.ethereum,"_metamask")&&(e.isMetaMask=!0),window.BinanceChain&&(e.isBinanceChainWallet=!0),window.ethereum.isFrame&&(e.isFrame=!0),"function"==typeof window.ethereum.request&&void 0===window.ethereum._metamask&&(e.isPossiblyGenericInjectedProvider=!0)),e.name=function(e){if(e.isMetaMask)return"MetaMask";if(e.isCoinbaseWallet)return"Coinbase Wallet";if(e.isWalletConnect)return"WalletConnect";if(e.isTrust)return"Trust Wallet";if(e.isImToken)return"imToken";if(e.isBraveWallet)return"Brave Wallet";if(e.isTokenPocket)return"TokenPocket";if(e.isStatus)return"Status";if(e.isTally)return"Tally";if(e.isAlphaWallet)return"AlphaWallet";if(e.isOpera)return"Opera";if(e.isCoin98)return"Coin98";if(e.isMathWallet)return"MathWallet";if(e.isOneInch)return"1inch Wallet";if(e.isRainbow)return"Rainbow";if(e.isBinanceChainWallet)return"Binance Chain Wallet";if(e.isFrame)return"Frame";const t=e.userAgent.toLowerCase();return t.includes("trust")?"Trust Wallet (UA)":t.includes("rainbow")?"Rainbow (UA)":"Unknown Provider"}(e),e})}const j=new n(o.store);function D(){return t(this,void 0,void 0,function*(){var e,t,n;try{if(window.solana){if(window.solana.isConnected&&window.solana.publicKey)return window.solana.publicKey.toString()}else if(window.solflare){if(window.solflare.isConnected&&window.solflare.publicKey)return window.solflare.publicKey.toString()}else if(null===(e=window.phantom)||void 0===e?void 0:e.solana)try{if((yield window.phantom.solana.connect({onlyIfTrusted:!0}))&&window.phantom.solana.publicKey)return window.phantom.solana.publicKey.toString()}catch(e){j.log("error","Error silently connecting to Phantom wallet:",e)}const i=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&i.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&i.push(window.SolanaWalletAdapterContext.current);const r=i.find(e=>e.connected&&e.publicKey);return r?r.publicKey.toString():null}catch(e){return j.log("error","Error detecting Solana wallet:",e),null}})}function W(){return t(this,void 0,void 0,function*(){var e,t,n;const i=yield D();if(!i)return null;if(null===(e=window.phantom)||void 0===e?void 0:e.solana)return"Phantom";if(window.solflare)return"Solflare";const r=[];(null===(t=window.walletAdapterNetwork)||void 0===t?void 0:t.adapters)&&r.push(...window.walletAdapterNetwork.adapters),(null===(n=window.SolanaWalletAdapterContext)||void 0===n?void 0:n.current)&&r.push(window.SolanaWalletAdapterContext.current);const o=r.find(e=>e.connected&&e.publicKey&&e.publicKey.toString()===i);return o?o.name||"Unknown Wallet":null})}function M(){return t(this,void 0,void 0,function*(){if($)return $;const e={device:{cores:L(()=>navigator.hardwareConcurrency),memory:L(()=>navigator.deviceMemory),cpuClass:L(()=>navigator.cpuClass),touch:N(),devicePixelRatio:L(()=>window.devicePixelRatio)},screen:{width:L(()=>window.screen.width),height:L(()=>window.screen.height),colorDepth:L(()=>window.screen.colorDepth),availHeight:L(()=>window.screen.availHeight),availWidth:L(()=>window.screen.availWidth),orientation:{type:L(()=>window.screen.orientation.type),angle:L(()=>window.screen.orientation.angle)}},browser:{language:L(()=>navigator.language),encoding:L(()=>TextDecoder.encoding),timezone:L(()=>-(new Date).getTimezoneOffset()/60),pluginsLength:L(()=>navigator.plugins.length),pluginNames:L(()=>Array.from(navigator.plugins,e=>e.name)),applePayAvailable:B(),uniqueHash:yield _(),colorGamut:z(),contrastPreference:q()},permissions:{navPer:L(()=>navigator.permissions.webglVersion),renderedPer:L(()=>navigator.permissions.RENDERER),geoPer:L(()=>navigator.permissions.geolocation)},storage:{localStorage:L(()=>!!window.localStorage),indexedDB:L(()=>!!window.indexedDB),openDB:L(()=>window.openDatabase)}};return $=e,e})}function R(){return t(this,void 0,void 0,function*(){const[e,t,n,i,r]=yield Promise.all([D(),E(),O(),W(),x()]);return{walletAddress:t,solanaAddress:e,providerInfo:r&&K(r),walletName:n,solWalletName:i}})}function U(){const e=new URL(window.location.href).searchParams,t={};return e.forEach((e,n)=>{(n.startsWith("utm_")||n.includes("id")||"ref"===n||"source"===n)&&(t[n]=e)}),t}function L(e,t){try{return e()}catch(e){return t}}function K(e){const t={};return Object.keys(e).forEach(n=>{const i=n;e[i]&&(t[i]=e[i])}),t}let $=null;function _(){return t(this,void 0,void 0,function*(){try{const e=document.createElement("canvas"),n=e.getContext("2d",{willReadFrequently:!0});if(!n)return;const i=200,r=120;e.width=i,e.height=r,e.style.width=`${i}px`,e.style.height=`${r}px`,n.fillStyle="#ffffff",n.fillRect(0,0,i,r),n.fillStyle="#ff00ff",n.fillRect(10,10,100,100),n.fillStyle="#00ffff",n.beginPath(),n.arc(150,50,40,0,2*Math.PI,!0),n.fill();const{data:o}=n.getImageData(0,0,i,r);return function(e){return t(this,void 0,void 0,function*(){const t=(new TextEncoder).encode(e),n=yield crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")})}([[20,20],[60,60],[100,100],[150,50],[150,60],[140,50],[5,5]].map(([e,t])=>{const n=4*(t*i+e);return`${o[n]},${o[n+1]},${o[n+2]},${o[n+3]};`}).join(""))}catch(e){return}})}function N(){try{return!!document.createEvent("TouchEvent")}catch(e){return!1}}function B(){var e;try{return"function"==typeof(null===(e=window.ApplePaySession)||void 0===e?void 0:e.canMakePayments)&&window.ApplePaySession.canMakePayments()}catch(e){return}}function q(){try{const{matchMedia:e}=window,t=t=>e(`(prefers-contrast: ${t})`).matches;return t("no-preference")?"None":t("high")||t("more")?"More":t("low")||t("less")?"Less":t("forced")?"ForcedColors":void 0}catch(e){return}}function z(){try{return["rec2020","p3","srgb","display-p3","adobe-rgb"].filter(e=>window.matchMedia(`(color-gamut: ${e})`).matches)}catch(e){return[]}}v.register(I);let V=class extends p{authenticate(){this.httpClient.post("/api/key/auth",{})}init(){return t(this,void 0,void 0,function*(){let e=g();e||(e=f());const t=yield M(),n=new URL(window.location.href).searchParams.get("lucia"),i=yield R(),r={id:e.id};e.hash&&(r.hash=e.hash);const o=yield this.httpClient.post("/api/sdk/init",{user:{name:m()},data:t,walletData:i,session:r,redirectHash:n,utm:U()},!1);o&&(o.lid&&localStorage.setItem("lid",o.lid),o.session&&function(e){const t={id:e.id,hash:e.hash,timestamp:Date.now()};sessionStorage.setItem(d,JSON.stringify(t))}(o.session)),v.initAll(this.store.config,{clicks:this.handleAutoTrackedClick.bind(this)},this.logger)})}handleAutoTrackedClick(e){const t=e,n={elementType:t.elementType,text:t.text,href:t.href,meta:t.meta};this.buttonClick(t.button,n)}userInfo(e,n){return t(this,void 0,void 0,function*(){const t=w(),i=g();e&&localStorage.setItem("luc_uid",e);const r=Object.assign({user:{name:e,userInfo:n},session:i},t&&{lid:t});yield this.httpClient.post("/api/sdk/user",r)})}pageView(e){return t(this,void 0,void 0,function*(){const t=w(),n=g(),i=Object.assign({page:e,user:{name:m()},session:n},t&&{lid:t});yield this.httpClient.post("/api/sdk/page",i)})}trackConversion(e,n,i){return t(this,void 0,void 0,function*(){const t=w(),r=g(),o=Object.assign({tag:e,amount:n,event:i,user:{name:m()},session:r},t&&{lid:t});yield this.httpClient.post("/api/sdk/conversion",o)})}buttonClick(e,n){return t(this,void 0,void 0,function*(){const t=w(),i=g(),r=Object.assign(Object.assign({button:e,user:{name:m()},session:i},t&&{lid:t}),n&&Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n.elementType&&{elementType:n.elementType}),n.text&&{text:n.text}),void 0!==n.href&&{href:n.href}),n.meta&&{meta:n.meta}),{timestamp:Date.now()}));yield this.httpClient.post("/api/sdk/click",r)})}sendWalletInfo(e,n,i){return t(this,void 0,void 0,function*(){const t=w(),r=g(),o=Object.assign({walletAddress:e,chainId:n,walletName:i,user:{name:m()},session:r},t&&{lid:t});yield this.httpClient.post("/api/sdk/wallet",o)})}trackUserAcquisition(e){return t(this,arguments,void 0,function*(e,t={}){const n=yield M(),i=U(),r=g();yield this.httpClient.post("/api/sdk/acquisition",{user:{name:e},session:r,data:Object.assign({timestamp:(new Date).toISOString(),browserData:n,utmParams:i},t)})})}checkMetaMaskConnection(){var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))}destroy(){v.destroyAll()}},F=null;const Q=()=>{const e=F||"undefined"!=typeof window&&window.__luciaInitPromise;if(!e)throw new Error("LuciaSDK not initialized. Please call LuciaSDK.init() first");return e},H={init:e=>{if("undefined"==typeof window)return Promise.reject(new Error("LuciaSDK requires a browser environment"));if(F)return F;if(window.__luciaInitPromise)return F=window.__luciaInitPromise,F;if(!(null==e?void 0:e.apiKey))return Promise.reject(new Error("apiKey is required in config"));const n=t(void 0,void 0,void 0,function*(){const t=new V(e);return yield t.init(),t});return F=n,window.__luciaInitPromise=n,n},userInfo:(e,n)=>t(void 0,void 0,void 0,function*(){return(yield Q()).userInfo(e,n)}),pageView:e=>t(void 0,void 0,void 0,function*(){return(yield Q()).pageView(e)}),trackConversion:(e,n,i)=>t(void 0,void 0,void 0,function*(){return(yield Q()).trackConversion(e,n,i)}),buttonClick:(e,n)=>t(void 0,void 0,void 0,function*(){return(yield Q()).buttonClick(e,n)}),sendWalletInfo:(e,n,i)=>t(void 0,void 0,void 0,function*(){return(yield Q()).sendWalletInfo(e,n,i)}),trackUserAcquisition:(e,...n)=>t(void 0,[e,...n],void 0,function*(e,t={}){return(yield Q()).trackUserAcquisition(e,t)}),checkMetaMaskConnection:()=>{var e,t,n;return!(!(null===(t=null===(e=window.ethereum)||void 0===e?void 0:e.isConnected)||void 0===t?void 0:t.call(e))||!(null===(n=window.ethereum)||void 0===n?void 0:n.selectedAddress))},VERSION:i};if("undefined"!=typeof window){window.LuciaSDK=H;const e=()=>{const e=document.currentScript||document.querySelector("script[data-api-key]"),t=null==e?void 0:e.getAttribute("data-api-key");if(!t)return;const n=e.getAttribute("data-debug-url"),i=e.getAttribute("data-auto-track-clicks"),r=e.getAttribute("data-track-selectors");H.init(Object.assign(Object.assign(Object.assign({apiKey:t},n&&{debugURL:n}),"true"===i&&{autoTrackClicks:!r||{enabled:!0,selectors:r.split(",").map(e=>e.trim())}}),"false"===i&&{autoTrackClicks:!1})).catch(e=>console.error("LuciaSDK auto-init failed:",e))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}e.__resetInstance=()=>{const e=F||"undefined"!=typeof window&&window.__luciaInitPromise;e&&e.then(e=>e.destroy()).catch(()=>{}),F=null,"undefined"!=typeof window&&delete window.__luciaInitPromise,v.reset()},e.default=H,e.filterObject=K,e.getApplePayAvailable=B,e.getBrowserData=M,e.getCanvasFingerprint=_,e.getColorGamut=z,e.getContrastPreference=q,e.getUtmParams=U,e.getWalletData=R,e.isTouchEnabled=N,e.safeAccess=L,Object.defineProperty(e,"__esModule",{value:!0})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lucia-sdk",
3
- "version": "0.9.10",
3
+ "version": "0.9.12",
4
4
  "license": "CC-BY-NC-4.0",
5
5
  "description": "Lucia JavaScript Library",
6
6
  "repository": {