@sensorswave/js-sdk 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +93 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.es.js +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/types/Api.d.ts +4 -0
- package/dist/types/web/src/basic/store.d.ts +2 -0
- package/dist/types/web/src/constants/index.d.ts +1 -0
- package/dist/types/web/src/index.d.ts +2 -0
- package/dist/types/web/src/plugins/exception.d.ts +20 -0
- package/dist/types/web/src/utils/exception.d.ts +41 -0
- package/dist/types/web/src/utils/request.d.ts +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -56,6 +56,8 @@ SensorsWave.trackEvent('ButtonClick', {
|
|
|
56
56
|
| crossSubdomainCookie | boolean | true | Whether to share cookies across subdomains |
|
|
57
57
|
| enableAB | boolean | false | Whether to enable A/B testing feature |
|
|
58
58
|
| abRefreshInterval | number | 600000 (10 minutes) | The interval in milliseconds for refreshing A/B test configuration |
|
|
59
|
+
| enableErrorTrack | boolean | false | Whether to automatically capture error-level exceptions (`$Exception`): uncaught JS errors, unhandled promise rejections and resource load failures. Independent of `autoCapture`. Effective in web environment |
|
|
60
|
+
| enableCrashTrack | boolean | false | Whether to enable app crash tracking (fatal level). Only effective in app host environments (iOS/Android/HarmonyOS WebView); NOT effective in this pure web SDK (the option is reserved to keep one unified config spec across SDKs) |
|
|
59
61
|
| batchSend | boolean | false | Whether to use batch sending (sends events in batches up to 10 events every 5 seconds) |
|
|
60
62
|
| anonId | string | '' | User-provided anonymous ID. When set, it overrides the SDK-generated anonymous ID and persists locally (cookie), so it is reused on subsequent visits even if not passed again |
|
|
61
63
|
|
|
@@ -114,6 +116,25 @@ SensorsWave.track({
|
|
|
114
116
|
});
|
|
115
117
|
```
|
|
116
118
|
|
|
119
|
+
#### trackException
|
|
120
|
+
|
|
121
|
+
Manually report a caught exception as an `$Exception` event (level is fixed to `error`).
|
|
122
|
+
|
|
123
|
+
This method is NOT gated by `enableErrorTrack` / `enableCrashTrack`; it only respects the consent guard (SDK initialized and not opted out). The stack is normalized and truncated the same way as automatically captured exceptions.
|
|
124
|
+
|
|
125
|
+
**Parameters:**
|
|
126
|
+
- `error` (Error | string, required): The caught error (an `Error` instance or a string)
|
|
127
|
+
- `properties` (Object, optional): Additional properties to attach. Cannot override the reserved `$exception_*` properties
|
|
128
|
+
|
|
129
|
+
**Example:**
|
|
130
|
+
```javascript
|
|
131
|
+
try {
|
|
132
|
+
doSomethingRisky();
|
|
133
|
+
} catch (err) {
|
|
134
|
+
SensorsWave.trackException(err, { order_id: '123' });
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
117
138
|
### User Profile
|
|
118
139
|
|
|
119
140
|
#### profileSet
|
|
@@ -289,6 +310,24 @@ const anonId = SensorsWave.getAnonId();
|
|
|
289
310
|
console.log('Anonymous user ID:', anonId);
|
|
290
311
|
```
|
|
291
312
|
|
|
313
|
+
#### reset
|
|
314
|
+
|
|
315
|
+
Call when the user logs out to unbind the login ID from the current device. After calling `reset()`, subsequent events are no longer associated with the logged-in user.
|
|
316
|
+
|
|
317
|
+
By default the anonymous ID is preserved, so the device continues to be tracked as an anonymous user. Pass `true` to also reset the anonymous ID and generate a new one — useful for shared/public devices where the previous visitor's anonymous identity should not be reused.
|
|
318
|
+
|
|
319
|
+
**Parameters:**
|
|
320
|
+
- `resetAnonymousId` (boolean, optional, default `false`): Whether to also reset the anonymous ID
|
|
321
|
+
|
|
322
|
+
**Example:**
|
|
323
|
+
```javascript
|
|
324
|
+
// 用户登出时
|
|
325
|
+
SensorsWave.reset(); // 默认保留匿名 ID
|
|
326
|
+
|
|
327
|
+
// 如果需要同时重置匿名 ID(如公共设备场景)
|
|
328
|
+
SensorsWave.reset(true);
|
|
329
|
+
```
|
|
330
|
+
|
|
292
331
|
### Common Properties
|
|
293
332
|
|
|
294
333
|
#### registerCommonProperties
|
|
@@ -433,6 +472,56 @@ async function initFeatureConfig() {
|
|
|
433
472
|
}
|
|
434
473
|
```
|
|
435
474
|
|
|
475
|
+
## Error Tracking
|
|
476
|
+
|
|
477
|
+
The SDK reports exceptions as `$Exception` events. Exceptions come from two paths:
|
|
478
|
+
|
|
479
|
+
1. **Automatic capture** — enable it with `enableErrorTrack: true` in `init()`. The SDK installs global listeners (capture-phase `error` + `unhandledrejection`) and captures:
|
|
480
|
+
- Uncaught JS errors (with or without an `Error` object, including cross-origin `"Script error."`)
|
|
481
|
+
- Unhandled promise rejections
|
|
482
|
+
- Resource load failures (`<script>`, `<img>`, `<link>`, etc.)
|
|
483
|
+
2. **Manual reporting** — call `trackException(error, properties?)` anywhere you already catch an error (see [trackException](#trackexception)). This is NOT gated by `enableErrorTrack` / `enableCrashTrack`.
|
|
484
|
+
|
|
485
|
+
### `$Exception` Event Properties
|
|
486
|
+
|
|
487
|
+
Every `$Exception` event carries the following reserved `$exception_*` properties:
|
|
488
|
+
|
|
489
|
+
| Property | Type | Description |
|
|
490
|
+
|----------|------|-------------|
|
|
491
|
+
| $exception_level | string | Severity level. Always `error` in this SDK (the `fatal` crash level only exists in app-host SDKs) |
|
|
492
|
+
| $exception_type | string | Exception type. For an `Error` object: its `name` (e.g. `TypeError`, `RangeError`), falling back to the type inferred from the stack header, then `Error`. Special values: `UnhandledRejection` (non-`Error` promise rejection reason) and `ResourceLoadError` (resource load failure). Capped at 200 chars |
|
|
493
|
+
| $exception_message | string | Exception message: `error.message` for `Error` objects, the raw message for string-form errors, a stringified reason for rejections (JSON for objects), or `Failed to load <tag> from <url>` for resource failures. Capped at 1000 chars |
|
|
494
|
+
| $exception_frames | `ExceptionFrame[]` | Structured stack frames derived from parsing `error.stack` (see below). This is the input for server-side symbolication (sourcemap) and aggregation. Empty array `[]` when there is no stack source (resource load failures, non-`Error` rejections, string-form reports) |
|
|
495
|
+
|
|
496
|
+
Custom properties passed to `trackException()` are attached alongside these, but cannot override the reserved `$exception_*` properties.
|
|
497
|
+
|
|
498
|
+
### Stack Parsing
|
|
499
|
+
|
|
500
|
+
Stacks are parsed (V8/Gecko formats) before reporting:
|
|
501
|
+
|
|
502
|
+
- At most 30 frames are kept
|
|
503
|
+
- The page origin prefix, query string and hash are stripped from each frame's path (same-origin scripts become relative paths)
|
|
504
|
+
- Consecutive repeated frames are kept individually rather than collapsed
|
|
505
|
+
- Parsed frames are reported as the structured `$exception_frames` array (see below)
|
|
506
|
+
|
|
507
|
+
### Structured Frames (`$exception_frames`)
|
|
508
|
+
|
|
509
|
+
Each event carries the parsed stack as a structured frame array for server-side symbolication and aggregation. Field semantics follow PostHog's `StackFrame`:
|
|
510
|
+
|
|
511
|
+
| Field | Type | Description |
|
|
512
|
+
|-------|------|-------------|
|
|
513
|
+
| platform | string | Always `web:javascript` in this SDK |
|
|
514
|
+
| filename | string | Cleaned path (page-origin prefix, query string and hash stripped) — the symbolication and aggregation key |
|
|
515
|
+
| function | string | Original function name (minified in compressed builds); `?` for anonymous frames |
|
|
516
|
+
| lineno / colno | number | Line and column as numbers. Note V8 columns are 1-based — subtract 1 when indexing a sourcemap |
|
|
517
|
+
| abs_path | string | The original URL before cleaning (query/hash version hints preserved), capped at 1000 chars — `filename` cleaning is irreversible, this recovers the loss |
|
|
518
|
+
| module | string | Fully-qualified class name, only written by Java hosts — never set by this SDK |
|
|
519
|
+
|
|
520
|
+
Notes:
|
|
521
|
+
|
|
522
|
+
- No collapsing or char-length truncation — the 30-frame parse limit bounds the payload, each frame is kept individually
|
|
523
|
+
- Synthetic frames (no `Error` object, e.g. cross-origin `"Script error."` built from `filename:lineno:colno`) are also emitted as a single-element array
|
|
524
|
+
|
|
436
525
|
## Supported Event Types
|
|
437
526
|
|
|
438
527
|
The SDK automatically captures the following event types when `autoCapture` is enabled:
|
|
@@ -442,6 +531,10 @@ The SDK automatically captures the following event types when `autoCapture` is e
|
|
|
442
531
|
- **PageLeave**: Triggered when a user is about to leave a page
|
|
443
532
|
- **WebClick**: Triggered on element clicks (only when `enableClickTrack` is true)
|
|
444
533
|
|
|
534
|
+
Additional automatic events:
|
|
535
|
+
|
|
536
|
+
- **Exception** (`$Exception`): Triggered when an error-level exception is captured — uncaught JS errors, unhandled promise rejections, and resource load failures (only when `enableErrorTrack` is true), or reported manually via `trackException()`
|
|
537
|
+
|
|
445
538
|
Custom events can be tracked using the `trackEvent()` or `track()` methods.
|
|
446
539
|
|
|
447
540
|
## License
|
package/dist/index.cjs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";class t{constructor(){this.listeners={}}on(t,e,n=!1){if(t&&e){if(!s(e))throw new Error("listener must be a function");this.listeners[t]=this.listeners[t]||[],this.listeners[t].push({listener:e,once:n})}}off(t,e){const n=this.listeners[t];if(!n?.length)return;"number"==typeof e&&n.splice(e,1);const i=n.findIndex(t=>t.listener===e);-1!==i&&n.splice(i,1)}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((n,i)=>{n.listener.call(this,...e),n.listener.once&&this.off(t,i)})}once(t,e){this.on(t,e,!0)}removeAllListeners(t){t?this.listeners[t]=[]:this.listeners={}}}const e={get:function(t){const e=t+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let t=n[i];for(;" "==t.charAt(0);)t=t.substring(1,t.length);if(0==t.indexOf(e))return l(t.substring(e.length,t.length))}return null},set:function({name:t,value:e,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",u="",c="";if(0!==(n=null==n||void 0===n?365:n)){const t=new Date;"s"===String(n).slice(-1)?t.setTime(t.getTime()+1e3*Number(String(n).slice(0,-1))):t.setTime(t.getTime()+24*n*60*60*1e3),o="; expires="+t.toUTCString()}function h(t){return t?t.replace(/\r\n/g,""):""}i&&(u="; SameSite="+i),s&&(a="; secure");const l=h(t),d=h(e),p=h(r);p&&(c="; domain="+p),l&&d&&(document.cookie=l+"="+encodeURIComponent(d)+o+"; path=/"+c+u+a)},remove:function(t){this.set({name:t,value:"",expires:-1})},isSupport:function({samesite:t,secure:e}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:t,secure:e}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(t){return"[object Object]"===n.call(t)}function s(t){const e=n.call(t);return"[object Function]"==e||"[object AsyncFunction]"==e}function r(t){return"[object Array]"==n.call(t)}function o(t){return"[object String]"==n.call(t)}function a(t){return void 0===t}const u=Object.prototype.hasOwnProperty;function c(t){if(i(t)){for(let e in t)if(u.call(t,e))return!1;return!0}return!1}function h(t){return!(!t||1!==t.nodeType)}function l(t){let e=t;try{e=decodeURIComponent(t)}catch(n){e=t}return e}function d(t){try{return JSON.parse(t)}catch(e){return""}}const p=function(){let t=Date.now();return function(e){return Math.ceil((t=(9301*t+49297)%233280,t/233280*e))}}();function g(){if("function"==typeof Uint32Array){let t;if("undefined"!=typeof crypto&&(t=crypto),t&&i(t)&&t.getRandomValues)return t.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return p(1e19)/1e19}const f=function(){function t(t){return("0".repeat(t)+Date.now().toString(16)).slice(-t)}return function(){let e=String(screen.height*screen.width);e=e&&/\d{4,}/.test(e)?e.slice(-4):String(31242*g()).replace(".","").slice(0,4);return t(8)+"-"+g().toString(16).replace(".","").slice(-4)+"-"+function(){const t=navigator.userAgent;let e,n=[],i=0;function s(t,e){let i=0;for(let s=0;s<e.length;s++)i|=n[s]<<8*s;return(t^i)>>>0}for(let r=0;r<t.length;r++)e=t.charCodeAt(r),n.unshift(255&e),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+e+"-"+t(12)||(String(g())+String(g())+String(g())).slice(2,15)}}();function m(t,e){e&&"string"==typeof e||(e="");let n=null;try{n=new URL(t).hostname}catch(i){}return n||e}function E(t){let e=[];try{e=atob(t).split("").map(function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})}catch(n){e=[]}try{return decodeURIComponent(e.join(""))}catch(n){return e.join("")}}function _(t){let e="";try{e=btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}))}catch(n){e=t}return e}const I={get:function(t){return window.localStorage.getItem(t)},parse:function(t){let e;try{e=JSON.parse(I.get(t))||null}catch(n){console.warn(n)}return e},set:function(t,e){try{window.localStorage.setItem(t,e)}catch(n){console.warn(n)}},remove:function(t){window.localStorage.removeItem(t)},isSupport:function(){let t=!0;try{const e="__local_store_support__",n="testIsSupportStorage";I.set(e,n),I.get(e)!==n&&(t=!1),I.remove(e)}catch(e){t=!1}return t}};function S(t){return t.trim()}function w(t){if(!t||"string"!=typeof t)return"";try{return new URL(t,window.location.origin).pathname}catch(e){return""}}const O={},v="1.2.0",A="init-ready",y="spa-switch",R="ff-ready",T="$PageLeave";var b=(t=>(t[t.FEATURE_GATE=1]="FEATURE_GATE",t[t.FEATURE_CONFIG=2]="FEATURE_CONFIG",t[t.EXPERIMENT=3]="EXPERIMENT",t))(b||{});const C={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(t){this.commonProps=t},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(t,e){this._state[t]=e,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let t=JSON.parse(JSON.stringify(this._state));t.identities&&(t.identities=_(JSON.stringify(t.identities)));const n=JSON.stringify(t);e.set({name:this.getCookieName(),value:n,expires:365})},init:function(t){let n,s;this.crossSubdomain=t,e.isSupport()&&(n=e.get(this.getCookieName()),s=d(n)),C._state={...s||{}},C._state.identities&&(C._state.identities=d(E(C._state.identities))),C._state.identities&&i(C._state.identities)&&!c(C._state.identities)||(C._state.identities={$identity_cookie_id:f()}),C.save()},setLoginId(t){"number"==typeof t&&(t=String(t)),void 0!==t&&t&&(C.set("login_id",t),C.save())},setAnonId(t){"number"==typeof t&&(t=String(t)),"string"==typeof t&&t?(C.set("anon_id",t),C.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",t)},saveABData(t){if(!t||c(t))return;this._abData=t;let e=JSON.parse(JSON.stringify(this._abData));e=_(JSON.stringify(e));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:e,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(t=6e5){try{let e=localStorage.getItem(this.getABLSName());if(e){const{time:n,data:i,login_id:s,anon_id:r}=d(e)||{};if(n&&i&&Date.now()-n<t&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const t=d(E(i));return this._abData=Array.isArray(t)?t:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(e){console.warn("Failed to load abdata from localStorage",e),this._abData=[]}return this._abData||[]}};function N(t){var e;if(t.data)return{contentType:"application/json",body:(e=t.data,JSON.stringify(e,(t,e)=>"bigint"==typeof e?e.toString():e,undefined))}}const P=[];function k(t){const e={...t};e.timeout=e.timeout||6e4;const n=e.transport??"fetch",i=P.find(t=>t.transport===n)?.method??P[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(e)}function L(t){return o(t=t||document.referrer)&&(t=l(t=t.trim()))||""}function F(t){const e=m(t=t||L());if(!e)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let t=n[i];for(let n=0,s=t.length;n<s;n++)if(t[n].test(e))return i}return""}function B(t,e){return-1!==t.indexOf(e)}"function"==typeof fetch&&P.push({transport:"fetch",method:function(t){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const e=N(t),n=new Headers;t.headers&&Object.keys(t.headers).forEach(e=>{n.append(e,t.headers[e])}),e?.contentType&&n.append("Content-Type",e.contentType),fetch(t.url,{method:t.method||"GET",headers:n,body:e?.body}).then(e=>e.text().then(n=>{const i={statusCode:e.status,text:n};if(200===e.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}t.callback?.(i)})).catch(e=>{console.error("Request failed:",e),t.callback?.({statusCode:0,text:String(e)})})}}),"undefined"!=typeof XMLHttpRequest&&P.push({transport:"XHR",method:function(t){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const e=new XMLHttpRequest;e.open(t.method||"GET",t.url,!0);const n=N(t);t.headers&&Object.keys(t.headers).forEach(n=>{e.setRequestHeader(n,t.headers[n])}),n?.contentType&&e.setRequestHeader("Content-Type",n.contentType),e.timeout=t.timeout||6e4,e.withCredentials=!0,e.onreadystatechange=()=>{if(4===e.readyState){const i={statusCode:e.status,text:e.responseText};if(200===e.status)try{i.json=JSON.parse(e.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}t.callback?.(i)}},e.send(n?.body)}});const M={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},D="(\\d+(\\.\\d+)?)",$=new RegExp("Version/"+D),x=new RegExp(M.XBOX,"i"),U=new RegExp(M.PLAYSTATION+" \\w+","i"),H=new RegExp(M.NINTENDO+" \\w+","i"),X=new RegExp(M.BLACKBERRY+"|PlayBook|BB10","i"),q=new RegExp("(HUAWEI|honor|HONOR)","i"),W=new RegExp("(Xiaomi|Redmi)","i"),G=new RegExp("(OPPO|realme)","i"),j=new RegExp("(vivo|IQOO)","i"),z={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function Y(t,e){return e=e||"",B(t," OPR/")&&B(t,"Mini")?M.OPERA_MINI:B(t," OPR/")?M.OPERA:X.test(t)?M.BLACKBERRY:B(t,"IE"+M.MOBILE)||B(t,"WPDesktop")?M.INTERNET_EXPLORER_MOBILE:B(t,M.SAMSUNG_BROWSER)?M.SAMSUNG_INTERNET:B(t,M.EDGE)||B(t,"Edg/")?M.MICROSOFT_EDGE:B(t,"FBIOS")?M.FACEBOOK+" "+M.MOBILE:B(t,"UCWEB")||B(t,"UCBrowser")?M.UC_BROWSER:B(t,"CriOS")?M.CHROME_IOS:B(t,"CrMo")||B(t,M.CHROME)?M.CHROME:B(t,M.ANDROID)&&B(t,M.SAFARI)?M.ANDROID_MOBILE:B(t,"FxiOS")?M.FIREFOX_IOS:B(t.toLowerCase(),M.KONQUEROR.toLowerCase())?M.KONQUEROR:function(t,e){return e&&B(e,M.APPLE)||B(n=t,M.SAFARI)&&!B(n,M.CHROME)&&!B(n,M.ANDROID);var n}(t,e)?B(t,M.MOBILE)?M.MOBILE_SAFARI:M.SAFARI:B(t,M.FIREFOX)?M.FIREFOX:B(t,"MSIE")||B(t,"Trident/")?M.INTERNET_EXPLORER:B(t,"Gecko")?M.FIREFOX:""}const K={[M.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+D)],[M.MICROSOFT_EDGE]:[new RegExp(M.EDGE+"?\\/"+D)],[M.CHROME]:[new RegExp("("+M.CHROME+"|CrMo)\\/"+D)],[M.CHROME_IOS]:[new RegExp("CriOS\\/"+D)],[M.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+D)],[M.SAFARI]:[$],[M.MOBILE_SAFARI]:[$],[M.OPERA]:[new RegExp("("+M.OPERA+"|OPR)\\/"+D)],[M.FIREFOX]:[new RegExp(M.FIREFOX+"\\/"+D)],[M.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+D)],[M.KONQUEROR]:[new RegExp("Konqueror[:/]?"+D,"i")],[M.BLACKBERRY]:[new RegExp(M.BLACKBERRY+" "+D),$],[M.ANDROID_MOBILE]:[new RegExp("android\\s"+D,"i")],[M.SAMSUNG_INTERNET]:[new RegExp(M.SAMSUNG_BROWSER+"\\/"+D)],[M.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+D)],Mozilla:[new RegExp("rv:"+D)]};function J(t,e){const n=Y(t,e),i=K[n];if(a(i))return null;for(let s=0;s<i.length;s++){const e=i[s],n=t.match(e);if(n)return parseFloat(n[n.length-2])}return null}const Z=[[new RegExp(M.XBOX+"; "+M.XBOX+" (.*?)[);]","i"),t=>[M.XBOX,t&&t[1]||""]],[new RegExp(M.NINTENDO,"i"),[M.NINTENDO,""]],[new RegExp(M.PLAYSTATION,"i"),[M.PLAYSTATION,""]],[X,[M.BLACKBERRY,""]],[new RegExp(M.WINDOWS,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[M.WINDOWS_PHONE,""];if(new RegExp(M.MOBILE).test(e)&&!/IEMobile\b/.test(e))return[M.WINDOWS+" "+M.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){const t=n[1];let i=z[t]||"";return/arm/i.test(e)&&(i="RT"),[M.WINDOWS,i]}return[M.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){const e=[t[3],t[4],t[5]||"0"];return[M.IOS,e.join(".")]}return[M.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=a(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+M.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+M.ANDROID+")","i"),t=>{if(t&&t[2]){const e=[t[2],t[3],t[4]||"0"];return[M.ANDROID,e.join(".")]}return[M.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{const e=["Mac OS X",""];if(t&&t[1]){const n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[M.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function Q(){const t=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,e=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(t){for(let e=0;e<Z.length;e++){const[n,i]=Z[e],s=n.exec(t),r=s&&("function"==typeof i?i(s,t):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:Y(n),$browser_version:J(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:t,$viewport_width:e,$lib:"webjs",$lib_version:v,$search_engine:F(),$referrer:L(),$referrer_host:m(r=r||L()),$title:document.title,$language:navigator.language,$model:(s=n,(H.test(s)?M.NINTENDO:U.test(s)?M.PLAYSTATION:x.test(s)?M.XBOX:new RegExp(M.OUYA,"i").test(s)?M.OUYA:new RegExp("("+M.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?M.WINDOWS_PHONE:/iPad/.test(s)?M.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?M.APPLE_WATCH:X.test(s)?M.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp(M.NOKIA,"i").test(s)?M.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":q.test(s)?M.HUAWEI:W.test(s)?M.XIAOMI:G.test(s)?M.OPPO:j.test(s)?M.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp(M.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?M.ANDROID:M.ANDROID_TABLET:M.ANDROID:new RegExp("(pda|"+M.MOBILE+")","i").test(s)?M.GENERIC_MOBILE:new RegExp(M.TABLET,"i").test(s)&&!new RegExp(M.TABLET+" pc","i").test(s)?M.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-(new Date).getTimezoneOffset()};var s,r}const V=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const t=localStorage.getItem(this.STORAGE_KEY);t&&(this.queue=d(t)||[])}catch(t){console.warn("Failed to load queue from localStorage:",t),this.queue=[]}}cleanupExpiredItems(){const t=Date.now(),e=this.queue.filter(e=>t-e.timestamp<this.MAX_AGE_MS);e.length!==this.queue.length&&(this.queue=e,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(t){console.warn("Failed to save queue to localStorage:",t)}}enqueue(t,e,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:t,data:e,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(t){try{this.queue=this.queue.filter(e=>e.id!==t),this.saveToStorage()}catch(e){console.warn("Failed to dequeue request:",e)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(t){return console.warn("Failed to get queue items:",t),[]}}incrementRetryCount(t){const e=this.queue.find(e=>e.id===t);return!(!e||e.retryCount>=e.maxRetries||(e.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(t){console.warn("Failed to clear queue from localStorage:",t)}}getItemById(t){return this.queue.find(e=>e.id===t)}};class tt{constructor(t={}){this.flushTimer=null,this.isFlushing=!1,this.paused=!1,this.destroyed=!1,this.config={maxBatchSize:t.maxBatchSize||20,flushInterval:t.flushInterval||5e3},this.startFlushTimer()}pause(){this.paused=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}resume(){this.paused&&(this.paused=!1,this.startFlushTimer())}isPaused(){return this.paused}add(){V.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.paused||this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const t=V.getAll();if(0===t.length)return this.isFlushing=!1,void this.startFlushTimer();const e=[],n=[];t.forEach(t=>{Array.isArray(t.data)?e.push(...t.data):e.push(t.data),n.push(t.id)});const i=e.slice(0,this.config.maxBatchSize),s=t[t.length-1],r=s.url,o=s.headers;O.instance&&O.instance.config.debug&&console.log(JSON.stringify(i,null,2)),k({url:r,method:"POST",data:i,headers:o,callback:t=>{200===t.statusCode?n.forEach(t=>{V.dequeue(t)}):console.error("Failed to send batch events:",t),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.destroyed||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{V.getAll().length>0&&this.triggerFlush()},this.config.flushInterval))}destroy(){this.destroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush()}}let et=null;function nt(){const t=O.instance;return!(!t||!t.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}function it(){const t=O.instance;return!t||"function"!=typeof t.hasOptedOutCapturing||!t.hasOptedOutCapturing()}let st=null;function rt(){return I.isSupport()?(st||(et||(et=new tt({maxBatchSize:20,flushInterval:5e3})),st=et),st):null}function ot(t,e,n){return k({url:t,method:"POST",data:e.data,headers:e.headers,callback:t=>{if(200!==t.statusCode){if(n)if(V.incrementRetryCount(n)){const t=V.getItemById(n);if(t){const e=Math.min(1e3*Math.pow(2,t.retryCount),3e4);setTimeout(()=>{ot(t.url,{data:t.data,headers:t.headers},t.id)},e)}}else console.warn("Max retries reached for request:",n)}else n&&V.dequeue(n),e.callback&&e.callback(t.json)}})}function at(t){return`${t.apiHost}/in/track`}function ut(t){return`${t.apiHost}/ab/evalall`}function ct(t){return{"Content-Type":"application/json",SourceToken:t.sourceToken}}function ht(t,e,n){O.instance&&O.instance.config.debug&&console.log(JSON.stringify(e.data,null,2));const i=V.enqueue(t,e.data,e.headers);return ot(t,{...e,callback:void 0},i)}function lt(){try{const t=sessionStorage.getItem("sensorswave_utm");if(!t)return{};const e=JSON.parse(t),n={};return Object.entries(e).forEach(([t,e])=>{null!=e&&""!==e&&(n[`$${t}`]=e)}),n}catch(t){return{}}}function dt(t){const e={};return Object.entries(t).forEach(([t,n])=>{if("function"==typeof n)try{const i=n();e[t]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",t,i)}else e[t]=n}),e}function pt(t={},e=!0){const n={...e?Q():{},...dt(C.getCommonProps()),...t},i=lt();return Object.keys(i).length>0&&Object.assign(n,i),n}function gt(t,e,n=!0){if(!nt())return;if(!it())return;const i={time:Date.now(),trace_id:C.getTraceId(),event:t.event,properties:pt(t.properties,n)},s=lt();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),t.user_properties&&(t.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...t.user_properties.$set},delete t.user_properties.$set),i.user_properties={...i.user_properties,...t.user_properties});const r=C.getLoginId(),o=C.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=at(e),u=ct(e),c=!1!==e.batchSend&&rt();c?(V.enqueue(a,[i],u),c.add()):ht(a,{data:[i],headers:u})}function ft({userProps:t,opts:e}){if(!nt())return;if(!it())return;const n=C.getLoginId(),i=C.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:C.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:t,properties:pt()},r=at(e),o=ct(e),a=rt();if(!a)return ht(r,{data:[s],headers:o});V.enqueue(r,[s],o),a.add()}function mt(t){return t.typ===b.FEATURE_GATE||t.typ===b.FEATURE_CONFIG?`$feature_${t.id}`:t.typ===b.EXPERIMENT?`$exp_${t.id}`:""}function Et(t){const e=t.typ;return[b.FEATURE_GATE,b.EXPERIMENT,b.FEATURE_CONFIG].includes(e)?{[mt(t)]:t.vid}:{}}function _t(t){const e=t.typ;return e===b.FEATURE_GATE||e===b.FEATURE_CONFIG?{$feature_key:t.key,$feature_variant:t.vid}:e===b.EXPERIMENT?{$exp_key:t.key,$exp_variant:t.vid}:{}}function It({isUnset:t=!1,data:e,opts:n}){if(!nt())return;if(!it())return;if(!e||c(e)||e.disable_impress)return;const i=C.getLoginId(),s=C.getAnonId();if(!i&&!s)return;const r=e.typ===b.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=t?{$unset:{[mt(e)]:null}}:{$set:{...Et(e)}},gt({event:r,properties:_t(e),user_properties:o},n)}const St="sensorswave_opt_out";class wt{constructor(t){this.persist=t}read(){if(this.persist)try{const t=I.get(St);return"0"===t||"1"!==t&&void 0}catch{return}}write(t){if(this.persist)try{I.set(St,t?"0":"1")}catch{}}}class Ot{constructor({plugins:t,emitter:e,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=e,this.config=n,this.sdk=i,this.registerBuiltInPlugins(t),this.created(),this.emitter.on(A,()=>{this.init()})}registerBuiltInPlugins(t){for(let e=0,n=t.length;e<n;e++)this.registerPlugin(t[e])}registerPlugin(t){this.plugins.push(t)}getPlugins(){return this.plugins}getPlugin(t){return this.pluginInsMap[t]}created(){for(let t=0,e=this.plugins.length;t<e;t++){const e=this.plugins[t];if(!e.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new e({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[e.NAME]=n}}init(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.init&&e.init()}}destroy(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.destroy&&"function"==typeof e.destroy&&e.destroy()}this.pluginInsMap={},this.plugins=[]}}const vt=class{constructor({emitter:t,config:e,sdk:n}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;this.boundSend=()=>{gt({event:"$PageView",properties:{}},t)},this.sdk&&!0===this.sdk._postConsentInit||setTimeout(()=>{this.boundSend()},0),t.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=t=>{t!==location.href&&this.boundSend()},this.emitter.on(y,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(y,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};vt.NAME="pageview";let At=vt;const yt=class{constructor({emitter:t,config:e,sdk:n}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this._skipFirstPageEnd=!1,this.emitter=t,this.config=e,this.sdk=n}__canCapture(){return!this.sdk||"function"!=typeof this.sdk.hasOptedOutCapturing||!this.sdk.hasOptedOutCapturing()}init(){this.pageId=Number(String(g()).slice(2,5)+String(g()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),this.sdk&&!0===this.sdk._postConsentInit&&(this._skipFirstPageEnd=!0),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(t){console.log(t)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title,this._skipFirstPageEnd=!1}pageEndHandler(){if(!0===this.pageHiddenStatus)return;if(!this.__canCapture())return;const t=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete t.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,gt({event:T,properties:t},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const t=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",t),this.eventListeners.push({target:window,event:"pageshow",handler:t})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(y,t=>{t!==location.href&&(this.url=t,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(t=>{if(`on${t}`in window){const e=()=>{if(this._skipFirstPageEnd)return this._skipFirstPageEnd=!1,void this.stopHeartBeatInterval();this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(t,e),this.eventListeners.push({target:window,event:t,handler:e})}})}addPageSwitchListener(){const t=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",t),this.eventListeners.push({target:document,event:"visibilitychange",handler:t})}addHeartBeatInterval(){I.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.sdk&&!0===this.sdk._postConsentInit&&!0===this._skipFirstPageEnd||(this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData())}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(t){if(!this.__canCapture())return;const e=this.getPageLeaveProperties();e.$time=Date.now(),"is_first_heartbeat"===t&&(e.$event_duration=3);const n={type:"track",event:T,properties:e,time:e.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,I.isSupport()&&I.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(t){I.isSupport()&&I.remove(t||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){if(this.__canCapture())for(let t=window.localStorage.length-1;t>=0;t--){const e=window.localStorage.key(t);if(e&&e!==`${this.storageName}-${this.pageId}`&&0===e.indexOf(`${this.storageName}-`)){const t=I.parse(e);i(t)&&Date.now()-t.time>t.heartbeat_interval_time+5e3&&(delete t.heartbeat_interval_time,t._flush_time=(new Date).getTime(),gt({event:T,properties:t?.properties},this.config),this.delHeartBeatData(e))}}}getPageLeaveProperties(){let t=(Date.now()-this.startTime)/1e3;(isNaN(t)||t<0||t>this.maxDuration)&&(t=0),t=Number(t.toFixed(3));const e={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:w(this.url)};return 0!==t&&(e.$event_duration=t),e}destroy(){this.eventListeners.forEach(({target:t,event:e,handler:n})=>{t.removeEventListener(e,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};yt.NAME="pageleave";let Rt=yt;const Tt=class{constructor({emitter:t,config:e,sdk:n}){this.eventSended=!1,this.emitter=t,this.config=e,this.sdk=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit)return;const t=()=>{let e=0;const n={};if(window.performance){e=function(){let t=0;if("function"==typeof performance.getEntriesByType){const e=performance.getEntriesByType("navigation");e.length>0&&(t=e[0].domContentLoadedEventEnd||0)}return t}();const t=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const t=performance.getEntries();let e=0;for(const n of t)"transferSize"in n&&(e+=n.transferSize);if("number"==typeof e&&e>=0&&e<10737418240)return Number((e/1024).toFixed(3))}}();t&&(n.$page_resource_size=t)}else console.warn("Performance API is not supported.");e>0&&!Number.isFinite(e)&&(n.$event_duration=Number((e/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,gt({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",t)};"complete"===document.readyState?t():window.addEventListener&&window.addEventListener("load",t)}};Tt.NAME="pageload";let bt=Tt;function Ct(t,e){if(!h(t))return!1;const n=o(t.tagName)?t.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=t.getAttribute("name")||"",i.$element_id=t.getAttribute("id")||"",i.$element_class_name=o(t.className)?t.className:"",i.$element_target_url=t.getAttribute("href")||"",i.$element_content=function(t,e){return o(e)&&"input"===e.toLowerCase()?("button"===(n=t).type||"submit"===n.type)&&n.value||"":function(t,e){let n="",i="";return t.textContent?n=S(t.textContent):t.innerText&&(n=S(t.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==e&&"INPUT"!==e||(i=t.value||""),i}(t,e);var n}(t,n)||"",i.$element_selector=Nt(t)||"",i.$element_path=function(t){let e=[];for(;t.parentNode&&h(t);){if(!o(t.tagName))return"";if(t.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.id)){e.unshift(t.tagName.toLowerCase()+"#"+t.id);break}if(t===document.body){e.unshift("body");break}e.unshift(t.tagName.toLowerCase()),t=t.parentNode}return e.join(" > ")}(t)||"";const s=function(t,e){const n=e.pageX||e.clientX+Pt().scrollLeft||e.offsetX+kt(t).targetEleX,i=e.pageY||e.clientY+Pt().scrollTop||e.offsetY+kt(t).targetEleY;return{$page_x:Lt(n),$page_y:Lt(i)}}(t,e);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function Nt(t,e=[]){if(!(t&&t.parentNode&&t.parentNode.children&&o(t.tagName)))return"";e=Array.isArray(e)?e:[];const n=t.nodeName.toLowerCase();return t&&"body"!==n&&1==t.nodeType?(e.unshift(function(t){if(!t||!h(t)||!o(t.tagName))return"";let e=t.parentNode&&9==t.parentNode.nodeType?-1:function(t){if(!t.parentNode)return-1;let e=0;const n=t.tagName,i=t.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(t===i[s])return e;e++}return-1}(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~e?":nth-of-type("+(e+1)+")":"")}(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?e.join(" > "):Nt(t.parentNode,e)):(e.unshift("body"),e.join(" > "))}function Pt(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function kt(t){if(document.documentElement.getBoundingClientRect){const e=t.getBoundingClientRect();return{targetEleX:e.left+Pt().scrollLeft||0,targetEleY:e.top+Pt().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Lt(t){return Number(Number(t).toFixed(3))}const Ft=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(t){const e=t.target;if(!e)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(e.tagName))return;if("true"===e.getAttribute("sensorswave-disable"))return;gt({event:"$WebClick",properties:Ct(e,t)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};Ft.NAME="webclick";let Bt=Ft;const Mt=class{constructor({emitter:t,config:e,sdk:n}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;if(t.enableAB){if(this.sdk&&"function"==typeof this.sdk.hasOptedOutCapturing&&this.sdk.hasOptedOutCapturing())return;this.fastFetch().then(()=>{this.emitter.emit(R)}),t.abRefreshInterval<3e4&&(t.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},t.abRefreshInterval)}}async fastFetch(){const t=C.getABData(this.config.abRefreshInterval);return t&&t.length?(this.emitter.emit(R),Promise.resolve(t)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(t=>{!function({opts:t,cb:e}){if(!nt())return void(e&&e({}));if(!it())return void(e&&e({}));const n=C.getLoginId(),i=C.getAnonId();if(!n&&!i)return void(e&&e({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...Q(),...dt(C.getCommonProps())}},sdk:"webjs",sdk_version:v};k({url:ut(t),method:"POST",data:s,headers:ct(t),callback:t=>{200!==t.statusCode?(console.error("Failed to fetch feature flags"),e&&e({})):e&&e(t.json)}})}({opts:this.config,cb:e=>{C.saveABData(e?.data?.results||[]),t(e),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(t){return await this.fastFetch().catch(console.warn),C.getABData(this.config.abRefreshInterval).find(e=>e.typ===b.FEATURE_GATE&&e.key==t)}async checkFeatureGate(t){const e=await this.getFeatureGate(t);return!!e&&(!e.hasOwnProperty("vid")&&e.key?(It({isUnset:!0,data:e,opts:this.config}),!1):(It({data:e,opts:this.config}),"fail"!==e.vid))}async getExperiment(t){await this.fastFetch().catch(console.warn);const e=C.getABData(this.config.abRefreshInterval).find(e=>e.typ===b.EXPERIMENT&&e.key===t);return e?!e.hasOwnProperty("vid")&&e.key?(It({isUnset:!0,data:e,opts:this.config}),{}):(It({data:e,opts:this.config}),e?.value||{}):{}}async getFeatureConfig(t){await this.fastFetch().catch(console.warn);const e=C.getABData(this.config.abRefreshInterval).find(e=>e.typ===b.FEATURE_CONFIG&&e.key===t);if(!e)return{};if(!e.hasOwnProperty("vid")&&e.key)return It({isUnset:!0,data:e,opts:this.config}),{};It({data:e,opts:this.config});const n=e?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Mt.NAME="abtest";let Dt=Mt;const $t=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],xt="sensorswave_utm",Ut=class t{constructor({sdk:t,emitter:e,config:n}){this.sdk=t,this.emitter=e,this.config=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit){let e=t.readFromSessionStorage();return e&&0!==Object.keys(e).length||(e=t.captureAndStore(this.config?.debug)),void this.scheduleInitialUTM(e)}const e=t.getUTMFromURL();t.saveToSessionStorage(e,this.config?.debug),this.scheduleInitialUTM(e)}scheduleInitialUTM(t){setTimeout(()=>{this.sendInitialUTM(t)},0)}static getUTMFromURL(){try{const t=new URLSearchParams(window.location.search),e={};return $t.forEach(n=>{const i=t.get(n);i&&(e[n]=i)}),e}catch(e){return t.getUTMFromURLFallback()}}static getUTMFromURLFallback(){const t={};return window.location.search.substring(1).split("&").forEach(e=>{const[n,i]=e.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";$t.includes(s)&&(t[s]=r)}),t}static readFromSessionStorage(){try{const t=sessionStorage.getItem(xt);if(!t)return{};const e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch(t){return{}}}static saveToSessionStorage(t,e=!1){try{sessionStorage.setItem(xt,JSON.stringify(t))}catch(n){e&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",n)}}static captureAndStore(e=!1){const n=t.getUTMFromURL();return t.saveToSessionStorage(n,e),n}sendInitialUTM(t){const e={};$t.forEach(n=>{e[`$initial_${n}`]=null!=t[n]?t[n]:""});try{this.sdk.profileSetOnce(e)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};Ut.NAME="UTM";let Ht=Ut;const Xt=[],qt={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1,optOutCapturing:!1,persistOptOut:!1},Wt=new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new t,this.pluginCore={},this.commonProps={},this.spaCleanup=null,this._optOutCapturing=!1,this.consentStorage=new wt(!1),this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance=this}init(t,e={}){return this.inited?this:(O.instance=this,e.sourceToken=t,this.mergeConfig(e),this.consentStorage=new wt(!0===this.config.persistOptOut),this._optOutCapturing?this.consentStorage.write(!0):!0===this.config.optOutCapturing?(this._optOutCapturing=!0,this.consentStorage.write(!0)):!0===this.consentStorage.read()&&(this._optOutCapturing=!0),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0,this._optOutCapturing?(Ht.captureAndStore(this.config.debug),this.eventEmitter.emit(A),this.inited=!0,this):(this.__setupAfterConsent(),this.eventEmitter.emit(A),this.inited=!0,this))}__setupAfterConsent(){if(this._setupAfterConsentDone)return;this._setupAfterConsentDone=!0;const t=this.config;Xt.length=0,C.init(t.crossSubdomainCookie),t.anonId&&C.setAnonId(t.anonId),function(){if(window._swFailedRequestsInitialized)return;window._swFailedRequestsInitialized=!0;const t=O.instance;t&&"function"==typeof t.hasOptedOutCapturing&&t.hasOptedOutCapturing()||t&&!0===t._postConsentInit||function(){const t=V.getAll();if(0!==t.length)for(let e=0,n=t.length;e<n;e+=10){const n=t.slice(e,e+10),i=[],s=[];n.forEach(t=>{Array.isArray(t.data)?i.push(...t.data):i.push(t.data),s.push(t.id)});const r=n[n.length-1],o=r.url,a=r.headers;k({url:o,method:"POST",data:i,headers:a,callback:t=>{200!==t.statusCode?console.error("Failed to send batch stored requests:",t):s.forEach(t=>{V.dequeue(t)})}})}}()}(),Xt.push(Ht),t.autoCapture&&this.autoTrack(),t.enableAB&&Xt.push(Dt),t.enableClickTrack&&Xt.push(Bt),this.pluginCore=new Ot({plugins:Xt,emitter:this.eventEmitter,config:t,sdk:this}),this.spaCleanup=function(t){let e=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){t(e),e=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),t(e),e=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),t(e),e=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(t=>{this.eventEmitter.emit(y,t)})}mergeConfig(t){this.config={...qt,...t}}__canCapture(){return this.inited&&!this._optOutCapturing}track(t){this.__canCapture()&&function(t,e){if(!nt())return;if(!it())return;const n={...t};n.time||(n.time=Date.now()),n.login_id||(n.login_id=C.getLoginId()),n.anon_id||(n.anon_id=C.getAnonId()),n.trace_id||(n.trace_id=C.getTraceId()),n.properties={...Q(),...dt(C.getCommonProps()),...n.properties};const i=at(e),s=ct(e),r=!1!==e.batchSend&&rt();if(!r)return ht(i,{data:[n],headers:s});V.enqueue(i,[n],s),r.add()}(t,this.config)}trackEvent(t,e){this.__canCapture()&>({event:t,properties:e},this.config)}autoTrack(){Xt.push(At,bt,Rt)}profileSet(t){this.__canCapture()&&ft({userProps:{$set:t},opts:this.config})}profileSetOnce(t){this.__canCapture()&&ft({userProps:{$set_once:t},opts:this.config})}profileIncrement(t){this.__canCapture()&&ft({userProps:{$increment:t},opts:this.config})}profileAppend(t){this.__canCapture()&&ft({userProps:{$append:t},opts:this.config})}profileUnion(t){this.__canCapture()&&ft({userProps:{$union:t},opts:this.config})}profileUnset(t){if(!this.__canCapture())return;const e={};r(t)?t.forEach(function(t){e[t]=null}):e[t]=null,ft({userProps:{$unset:e},opts:this.config})}profileDelete(){this.__canCapture()&&ft({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(t){if(!i(t))return console.warn("Commmon Properties must be an object!");this.commonProps=t,C.setCommonProps(this.commonProps)}clearCommonProperties(t){if(!r(t))return console.warn("Commmon Properties to be cleared must be an array!");t.forEach(t=>{delete this.commonProps[t]}),C.setCommonProps(this.commonProps)}identify(t){this.__canCapture()&&(C.setLoginId(t),function(t){if(!nt())return;if(!it())return;const e=C.getLoginId(),n=C.getAnonId();if(!e||!n)return;const i={time:Date.now(),trace_id:C.getTraceId(),event:"$Identify",login_id:e,anon_id:n,properties:pt()},s=at(t),r=ct(t),o=rt();if(!o)return ht(s,{data:[i],headers:r});V.enqueue(s,[i],r),o.add()}(this.config))}setLoginId(t){this.__canCapture()&&C.setLoginId(t)}getAnonId(){return this.__canCapture()?C.getAnonId():""}setAnonId(t){this.__canCapture()&&C.setAnonId(t)}getLoginId(){return this.__canCapture()?C.getLoginId():""}checkFeatureGate(t){if(!this.__canCapture())return Promise.resolve(!1);const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.checkFeatureGate(t):Promise.reject("AB is disabled")}getExperiment(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getExperiment(t):Promise.reject("AB is disabled")}getFeatureConfig(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getFeatureConfig(t):Promise.reject("AB is disabled")}optOutCapturing(){this._optOutCapturing=!0,this.consentStorage.write(!0),st&&st.pause()}optInCapturing(){if(this._optOutCapturing=!1,this.consentStorage.write(!1),st&&st.resume(),this.inited&&!this._setupAfterConsentDone){this._postConsentInit=!0;try{this.__setupAfterConsent(),this.eventEmitter.emit(A)}finally{this._postConsentInit=!1}}}hasOptedOutCapturing(){return this._optOutCapturing}destroy(){st&&(st.destroy(),st=null),"undefined"!=typeof window&&(window._swFailedRequestsInitialized=!1),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.pluginCore={},this.eventEmitter&&this.eventEmitter.removeAllListeners(),this.consentStorage=new wt(!0===this.config?.persistOptOut),this._optOutCapturing=!1,this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance===this&&(O.instance=null)}};module.exports=Wt;
|
|
1
|
+
"use strict";class t{constructor(){this.listeners={}}on(t,e,n=!1){if(t&&e){if(!s(e))throw new Error("listener must be a function");this.listeners[t]=this.listeners[t]||[],this.listeners[t].push({listener:e,once:n})}}off(t,e){const n=this.listeners[t];if(!n?.length)return;"number"==typeof e&&n.splice(e,1);const i=n.findIndex(t=>t.listener===e);-1!==i&&n.splice(i,1)}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((n,i)=>{n.listener.call(this,...e),n.listener.once&&this.off(t,i)})}once(t,e){this.on(t,e,!0)}removeAllListeners(t){t?this.listeners[t]=[]:this.listeners={}}}const e={get:function(t){const e=t+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let t=n[i];for(;" "==t.charAt(0);)t=t.substring(1,t.length);if(0==t.indexOf(e))return h(t.substring(e.length,t.length))}return null},set:function({name:t,value:e,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",c="",u="";if(0!==(n=null==n||void 0===n?365:n)){const t=new Date;"s"===String(n).slice(-1)?t.setTime(t.getTime()+1e3*Number(String(n).slice(0,-1))):t.setTime(t.getTime()+24*n*60*60*1e3),o="; expires="+t.toUTCString()}function l(t){return t?t.replace(/\r\n/g,""):""}i&&(c="; SameSite="+i),s&&(a="; secure");const h=l(t),d=l(e),p=l(r);p&&(u="; domain="+p),h&&d&&(document.cookie=h+"="+encodeURIComponent(d)+o+"; path=/"+u+c+a)},remove:function(t){this.set({name:t,value:"",expires:-1})},isSupport:function({samesite:t,secure:e}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:t,secure:e}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(t){return"[object Object]"===n.call(t)}function s(t){const e=n.call(t);return"[object Function]"==e||"[object AsyncFunction]"==e}function r(t){return"[object Array]"==n.call(t)}function o(t){return"[object String]"==n.call(t)}function a(t){return void 0===t}const c=Object.prototype.hasOwnProperty;function u(t){if(i(t)){for(let e in t)if(c.call(t,e))return!1;return!0}return!1}function l(t){return!(!t||1!==t.nodeType)}function h(t){let e=t;try{e=decodeURIComponent(t)}catch(n){e=t}return e}function d(t){try{return JSON.parse(t)}catch(e){return""}}const p=function(){let t=Date.now();return function(e){return Math.ceil((t=(9301*t+49297)%233280,t/233280*e))}}();function g(){if("function"==typeof Uint32Array){let t;if("undefined"!=typeof crypto&&(t=crypto),t&&i(t)&&t.getRandomValues)return t.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return p(1e19)/1e19}const f=function(){function t(t){return("0".repeat(t)+Date.now().toString(16)).slice(-t)}return function(){let e=String(screen.height*screen.width);e=e&&/\d{4,}/.test(e)?e.slice(-4):String(31242*g()).replace(".","").slice(0,4);return t(8)+"-"+g().toString(16).replace(".","").slice(-4)+"-"+function(){const t=navigator.userAgent;let e,n=[],i=0;function s(t,e){let i=0;for(let s=0;s<e.length;s++)i|=n[s]<<8*s;return(t^i)>>>0}for(let r=0;r<t.length;r++)e=t.charCodeAt(r),n.unshift(255&e),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+e+"-"+t(12)||(String(g())+String(g())+String(g())).slice(2,15)}}();function m(t,e){e&&"string"==typeof e||(e="");let n=null;try{n=new URL(t).hostname}catch(i){}return n||e}function E(t){let e=[];try{e=atob(t).split("").map(function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})}catch(n){e=[]}try{return decodeURIComponent(e.join(""))}catch(n){return e.join("")}}function _(t){let e="";try{e=btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}))}catch(n){e=t}return e}const I={get:function(t){return window.localStorage.getItem(t)},parse:function(t){let e;try{e=JSON.parse(I.get(t))||null}catch(n){console.warn(n)}return e},set:function(t,e){try{window.localStorage.setItem(t,e)}catch(n){console.warn(n)}},remove:function(t){window.localStorage.removeItem(t)},isSupport:function(){let t=!0;try{const e="__local_store_support__",n="testIsSupportStorage";I.set(e,n),I.get(e)!==n&&(t=!1),I.remove(e)}catch(e){t=!1}return t}};function S(t){return t.trim()}function w(t){if(!t||"string"!=typeof t)return"";try{return new URL(t,window.location.origin).pathname}catch(e){return""}}const O={},v="1.4.0",b="init-ready",y="spa-switch",A="ff-ready",R="$PageLeave",T="$Exception";var C=(t=>(t[t.FEATURE_GATE=1]="FEATURE_GATE",t[t.FEATURE_CONFIG=2]="FEATURE_CONFIG",t[t.EXPERIMENT=3]="EXPERIMENT",t))(C||{});const N={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(t){this.commonProps=t},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(t,e){this._state[t]=e,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let t=JSON.parse(JSON.stringify(this._state));t.identities&&(t.identities=_(JSON.stringify(t.identities)));const n=JSON.stringify(t);e.set({name:this.getCookieName(),value:n,expires:365})},init:function(t){let n,s;this.crossSubdomain=t,e.isSupport()&&(n=e.get(this.getCookieName()),s=d(n)),N._state={...s||{}},N._state.identities&&(N._state.identities=d(E(N._state.identities))),N._state.identities&&i(N._state.identities)&&!u(N._state.identities)||(N._state.identities={$identity_cookie_id:f()}),N.save()},setLoginId(t){"number"==typeof t&&(t=String(t)),void 0!==t&&t&&(N.set("login_id",t),N.save())},clearLoginId(){this._state.login_id="",this.save()},resetAnonId(){this._state.anon_id="",this._state.identities={$identity_cookie_id:f()},this.save()},setAnonId(t){"number"==typeof t&&(t=String(t)),"string"==typeof t&&t?(N.set("anon_id",t),N.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",t)},saveABData(t){if(!t||u(t))return;this._abData=t;let e=JSON.parse(JSON.stringify(this._abData));e=_(JSON.stringify(e));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:e,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(t=6e5){try{let e=localStorage.getItem(this.getABLSName());if(e){const{time:n,data:i,login_id:s,anon_id:r}=d(e)||{};if(n&&i&&Date.now()-n<t&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const t=d(E(i));return this._abData=Array.isArray(t)?t:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(e){this._abData=[]}return this._abData||[]}};function P(t){return!(t>=400&&t<500)||408===t||429===t}function k(t){var e;if(t.data)return{contentType:"application/json",body:(e=t.data,JSON.stringify(e,(t,e)=>"bigint"==typeof e?e.toString():e,undefined))}}const L=[];function $(t){const e={...t};e.timeout=e.timeout||6e4;const n=e.transport??"fetch",i=L.find(t=>t.transport===n)?.method??L[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(e)}function F(t){return o(t=t||document.referrer)&&(t=h(t=t.trim()))||""}function B(t){const e=m(t=t||F());if(!e)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let t=n[i];for(let n=0,s=t.length;n<s;n++)if(t[n].test(e))return i}return""}function x(t,e){return-1!==t.indexOf(e)}"function"==typeof fetch&&L.push({transport:"fetch",method:function(t){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const e=k(t),n=new Headers;t.headers&&Object.keys(t.headers).forEach(e=>{n.append(e,t.headers[e])}),e?.contentType&&n.append("Content-Type",e.contentType),fetch(t.url,{method:t.method||"GET",headers:n,body:e?.body}).then(e=>e.text().then(n=>{const i={statusCode:e.status,text:n};if(200===e.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}t.callback?.(i)})).catch(e=>{console.error("Request failed:",e),t.callback?.({statusCode:0,text:String(e)})})}}),"undefined"!=typeof XMLHttpRequest&&L.push({transport:"XHR",method:function(t){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const e=new XMLHttpRequest;e.open(t.method||"GET",t.url,!0);const n=k(t);t.headers&&Object.keys(t.headers).forEach(n=>{e.setRequestHeader(n,t.headers[n])}),n?.contentType&&e.setRequestHeader("Content-Type",n.contentType),e.timeout=t.timeout||6e4,e.withCredentials=!0,e.onreadystatechange=()=>{if(4===e.readyState){const i={statusCode:e.status,text:e.responseText};if(200===e.status)try{i.json=JSON.parse(e.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}t.callback?.(i)}},e.send(n?.body)}});const M={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},D="(\\d+(\\.\\d+)?)",H=new RegExp("Version/"+D),U=new RegExp(M.XBOX,"i"),X=new RegExp(M.PLAYSTATION+" \\w+","i"),j=new RegExp(M.NINTENDO+" \\w+","i"),q=new RegExp(M.BLACKBERRY+"|PlayBook|BB10","i"),W=new RegExp("(HUAWEI|honor|HONOR)","i"),G=new RegExp("(Xiaomi|Redmi)","i"),z=new RegExp("(OPPO|realme)","i"),Y=new RegExp("(vivo|IQOO)","i"),K={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function J(t,e){return e=e||"",x(t," OPR/")&&x(t,"Mini")?M.OPERA_MINI:x(t," OPR/")?M.OPERA:q.test(t)?M.BLACKBERRY:x(t,"IE"+M.MOBILE)||x(t,"WPDesktop")?M.INTERNET_EXPLORER_MOBILE:x(t,M.SAMSUNG_BROWSER)?M.SAMSUNG_INTERNET:x(t,M.EDGE)||x(t,"Edg/")?M.MICROSOFT_EDGE:x(t,"FBIOS")?M.FACEBOOK+" "+M.MOBILE:x(t,"UCWEB")||x(t,"UCBrowser")?M.UC_BROWSER:x(t,"CriOS")?M.CHROME_IOS:x(t,"CrMo")||x(t,M.CHROME)?M.CHROME:x(t,M.ANDROID)&&x(t,M.SAFARI)?M.ANDROID_MOBILE:x(t,"FxiOS")?M.FIREFOX_IOS:x(t.toLowerCase(),M.KONQUEROR.toLowerCase())?M.KONQUEROR:function(t,e){return e&&x(e,M.APPLE)||x(n=t,M.SAFARI)&&!x(n,M.CHROME)&&!x(n,M.ANDROID);var n}(t,e)?x(t,M.MOBILE)?M.MOBILE_SAFARI:M.SAFARI:x(t,M.FIREFOX)?M.FIREFOX:x(t,"MSIE")||x(t,"Trident/")?M.INTERNET_EXPLORER:x(t,"Gecko")?M.FIREFOX:""}const Z={[M.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+D)],[M.MICROSOFT_EDGE]:[new RegExp(M.EDGE+"?\\/"+D)],[M.CHROME]:[new RegExp("("+M.CHROME+"|CrMo)\\/"+D)],[M.CHROME_IOS]:[new RegExp("CriOS\\/"+D)],[M.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+D)],[M.SAFARI]:[H],[M.MOBILE_SAFARI]:[H],[M.OPERA]:[new RegExp("("+M.OPERA+"|OPR)\\/"+D)],[M.FIREFOX]:[new RegExp(M.FIREFOX+"\\/"+D)],[M.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+D)],[M.KONQUEROR]:[new RegExp("Konqueror[:/]?"+D,"i")],[M.BLACKBERRY]:[new RegExp(M.BLACKBERRY+" "+D),H],[M.ANDROID_MOBILE]:[new RegExp("android\\s"+D,"i")],[M.SAMSUNG_INTERNET]:[new RegExp(M.SAMSUNG_BROWSER+"\\/"+D)],[M.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+D)],Mozilla:[new RegExp("rv:"+D)]};function Q(t,e){const n=J(t,e),i=Z[n];if(a(i))return null;for(let s=0;s<i.length;s++){const e=i[s],n=t.match(e);if(n)return parseFloat(n[n.length-2])}return null}const V=[[new RegExp(M.XBOX+"; "+M.XBOX+" (.*?)[);]","i"),t=>[M.XBOX,t&&t[1]||""]],[new RegExp(M.NINTENDO,"i"),[M.NINTENDO,""]],[new RegExp(M.PLAYSTATION,"i"),[M.PLAYSTATION,""]],[q,[M.BLACKBERRY,""]],[new RegExp(M.WINDOWS,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[M.WINDOWS_PHONE,""];if(new RegExp(M.MOBILE).test(e)&&!/IEMobile\b/.test(e))return[M.WINDOWS+" "+M.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){const t=n[1];let i=K[t]||"";return/arm/i.test(e)&&(i="RT"),[M.WINDOWS,i]}return[M.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){const e=[t[3],t[4],t[5]||"0"];return[M.IOS,e.join(".")]}return[M.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=a(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+M.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+M.ANDROID+")","i"),t=>{if(t&&t[2]){const e=[t[2],t[3],t[4]||"0"];return[M.ANDROID,e.join(".")]}return[M.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{const e=["Mac OS X",""];if(t&&t[1]){const n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[M.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function tt(){const t=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,e=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(t){for(let e=0;e<V.length;e++){const[n,i]=V[e],s=n.exec(t),r=s&&("function"==typeof i?i(s,t):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:J(n),$browser_version:Q(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:t,$viewport_width:e,$lib:"webjs",$lib_version:v,$search_engine:B(),$referrer:F(),$referrer_host:m(r=r||F()),$title:document.title,$language:navigator.language,$model:(s=n,(j.test(s)?M.NINTENDO:X.test(s)?M.PLAYSTATION:U.test(s)?M.XBOX:new RegExp(M.OUYA,"i").test(s)?M.OUYA:new RegExp("("+M.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?M.WINDOWS_PHONE:/iPad/.test(s)?M.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?M.APPLE_WATCH:q.test(s)?M.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp(M.NOKIA,"i").test(s)?M.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":W.test(s)?M.HUAWEI:G.test(s)?M.XIAOMI:z.test(s)?M.OPPO:Y.test(s)?M.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp(M.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?M.ANDROID:M.ANDROID_TABLET:M.ANDROID:new RegExp("(pda|"+M.MOBILE+")","i").test(s)?M.GENERIC_MOBILE:new RegExp(M.TABLET,"i").test(s)&&!new RegExp(M.TABLET+" pc","i").test(s)?M.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-(new Date).getTimezoneOffset()};var s,r}const et=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const t=localStorage.getItem(this.STORAGE_KEY);t&&(this.queue=d(t)||[])}catch(t){console.warn("Failed to load queue from localStorage:",t),this.queue=[]}}cleanupExpiredItems(){const t=Date.now(),e=this.queue.filter(e=>t-e.timestamp<this.MAX_AGE_MS);e.length!==this.queue.length&&(this.queue=e,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(t){console.warn("Failed to save queue to localStorage:",t)}}enqueue(t,e,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:t,data:e,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(t){try{this.queue=this.queue.filter(e=>e.id!==t),this.saveToStorage()}catch(e){console.warn("Failed to dequeue request:",e)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(t){return console.warn("Failed to get queue items:",t),[]}}incrementRetryCount(t){const e=this.queue.find(e=>e.id===t);return!(!e||e.retryCount>=e.maxRetries||(e.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(t){console.warn("Failed to clear queue from localStorage:",t)}}getItemById(t){return this.queue.find(e=>e.id===t)}};class nt{constructor(t={}){this.flushTimer=null,this.isFlushing=!1,this.paused=!1,this.destroyed=!1,this.config={maxBatchSize:t.maxBatchSize||20,flushInterval:t.flushInterval||5e3},this.startFlushTimer()}pause(){this.paused=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}resume(){this.paused&&(this.paused=!1,this.startFlushTimer())}isPaused(){return this.paused}add(){et.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.paused||this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const t=et.getAll();if(0===t.length)return this.isFlushing=!1,void this.startFlushTimer();const e=t.slice(0,this.config.maxBatchSize),n=[],i=[];e.forEach(t=>{Array.isArray(t.data)?n.push(...t.data):n.push(t.data),i.push(t.id)});const s=e[e.length-1],r=s.url,o=s.headers;O.instance&&O.instance.config.debug&&console.log(JSON.stringify(n,null,2)),$({url:r,method:"POST",data:n,headers:o,callback:t=>{200===t.statusCode?i.forEach(t=>{et.dequeue(t)}):P(t.statusCode)?console.error("Failed to send batch events:",t):i.forEach(t=>{et.dequeue(t)}),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.destroyed||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{et.getAll().length>0&&this.triggerFlush()},this.config.flushInterval))}destroy(){this.destroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.paused||this.flush()}}let it=null;function st(){const t=O.instance;return!(!t||!t.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}function rt(){const t=O.instance;return!t||"function"!=typeof t.hasOptedOutCapturing||!t.hasOptedOutCapturing()}let ot=null;function at(){return I.isSupport()?(ot||(it||(it=new nt({maxBatchSize:20,flushInterval:5e3})),ot=it),ot):null}function ct(t,e,n){if(rt())return $({url:t,method:"POST",data:e.data,headers:e.headers,callback:t=>{if(200!==t.statusCode){if(!P(t.statusCode))return void(n&&et.dequeue(n));if(n&&et.incrementRetryCount(n)){const t=et.getItemById(n);if(t){const e=Math.min(1e3*Math.pow(2,t.retryCount),3e4);setTimeout(()=>{ct(t.url,{data:t.data,headers:t.headers},t.id)},e)}}}else n&&et.dequeue(n),e.callback&&e.callback(t.json)}})}function ut(t){return`${t.apiHost}/in/track`}function lt(t){return`${t.apiHost}/ab/evalall`}function ht(t){return{"Content-Type":"application/json",SourceToken:t.sourceToken}}function dt(t,e,n){O.instance&&O.instance.config.debug&&console.log(JSON.stringify(e.data,null,2));const i=et.enqueue(t,e.data,e.headers);return ct(t,{...e,callback:void 0},i)}function pt(){try{const t=sessionStorage.getItem("sensorswave_utm");if(!t)return{};const e=JSON.parse(t),n={};return Object.entries(e).forEach(([t,e])=>{null!=e&&""!==e&&(n[`$${t}`]=e)}),n}catch(t){return{}}}function gt(t){const e={};return Object.entries(t).forEach(([t,n])=>{if("function"==typeof n)try{const i=n();e[t]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",t,i)}else e[t]=n}),e}function ft(t={},e=!0){const n={...e?tt():{},...gt(N.getCommonProps()),...t},i=pt();return Object.keys(i).length>0&&Object.assign(n,i),n}function mt(t,e,n=!0){if(!st())return;if(!rt())return;const i={time:Date.now(),trace_id:N.getTraceId(),event:t.event,properties:ft(t.properties,n)},s=pt();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),t.user_properties&&(t.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...t.user_properties.$set},delete t.user_properties.$set),i.user_properties={...i.user_properties,...t.user_properties});const r=N.getLoginId(),o=N.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=ut(e),c=ht(e),u=!1!==e.batchSend&&at();u?(et.enqueue(a,[i],c),u.add()):dt(a,{data:[i],headers:c})}function Et({userProps:t,opts:e}){if(!st())return;if(!rt())return;const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:N.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:t,properties:ft()},r=ut(e),o=ht(e),a=at();if(!a)return dt(r,{data:[s],headers:o});et.enqueue(r,[s],o),a.add()}function _t(t){return t.typ===C.FEATURE_GATE||t.typ===C.FEATURE_CONFIG?`$feature_${t.id}`:t.typ===C.EXPERIMENT?`$exp_${t.id}`:""}function It(t){const e=t.typ;return[C.FEATURE_GATE,C.EXPERIMENT,C.FEATURE_CONFIG].includes(e)?{[_t(t)]:t.vid}:{}}function St(t){const e=t.typ;return e===C.FEATURE_GATE||e===C.FEATURE_CONFIG?{$feature_key:t.key,$feature_variant:t.vid}:e===C.EXPERIMENT?{$exp_key:t.key,$exp_variant:t.vid}:{}}function wt({isUnset:t=!1,data:e,opts:n}){if(!st())return;if(!rt())return;if(!e||u(e)||e.disable_impress)return;const i=N.getLoginId(),s=N.getAnonId();if(!i&&!s)return;const r=e.typ===C.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=t?{$unset:{[_t(e)]:null}}:{$set:{...It(e)}},mt({event:r,properties:St(e),user_properties:o},n)}const Ot="sensorswave_opt_out";class vt{constructor(t){this.persist=t}read(){if(this.persist)try{const t=I.get(Ot);return"0"===t||"1"!==t&&void 0}catch{return}}write(t){if(this.persist)try{I.set(Ot,t?"0":"1")}catch{}}}class bt{constructor({plugins:t,emitter:e,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=e,this.config=n,this.sdk=i,this.registerBuiltInPlugins(t),this.created(),this.emitter.on(b,()=>{this.init()})}registerBuiltInPlugins(t){for(let e=0,n=t.length;e<n;e++)this.registerPlugin(t[e])}registerPlugin(t){this.plugins.push(t)}getPlugins(){return this.plugins}getPlugin(t){return this.pluginInsMap[t]}created(){for(let t=0,e=this.plugins.length;t<e;t++){const e=this.plugins[t];if(!e.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new e({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[e.NAME]=n}}init(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.init&&e.init()}}destroy(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.destroy&&"function"==typeof e.destroy&&e.destroy()}this.pluginInsMap={},this.plugins=[]}}const yt=class{constructor({emitter:t,config:e,sdk:n}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;this.boundSend=()=>{mt({event:"$PageView",properties:{}},t)},this.sdk&&!0===this.sdk._postConsentInit||setTimeout(()=>{this.boundSend()},0),t.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=t=>{t!==location.href&&this.boundSend()},this.emitter.on(y,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(y,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};yt.NAME="pageview";let At=yt;const Rt=class{constructor({emitter:t,config:e,sdk:n}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this._skipFirstPageEnd=!1,this.emitter=t,this.config=e,this.sdk=n}__canCapture(){return!this.sdk||"function"!=typeof this.sdk.hasOptedOutCapturing||!this.sdk.hasOptedOutCapturing()}init(){this.pageId=Number(String(g()).slice(2,5)+String(g()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),this.sdk&&!0===this.sdk._postConsentInit&&(this._skipFirstPageEnd=!0),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(t){console.log(t)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title,this._skipFirstPageEnd=!1}pageEndHandler(){if(!0===this.pageHiddenStatus)return;if(!this.__canCapture())return;const t=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete t.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,mt({event:R,properties:t},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const t=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",t),this.eventListeners.push({target:window,event:"pageshow",handler:t})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(y,t=>{t!==location.href&&(this.url=t,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(t=>{if(`on${t}`in window){const e=()=>{if(this._skipFirstPageEnd)return this._skipFirstPageEnd=!1,void this.stopHeartBeatInterval();this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(t,e),this.eventListeners.push({target:window,event:t,handler:e})}})}addPageSwitchListener(){const t=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",t),this.eventListeners.push({target:document,event:"visibilitychange",handler:t})}addHeartBeatInterval(){I.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.sdk&&!0===this.sdk._postConsentInit&&!0===this._skipFirstPageEnd||(this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData())}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(t){if(!this.__canCapture())return;const e=this.getPageLeaveProperties();e.$time=Date.now(),"is_first_heartbeat"===t&&(e.$event_duration=3);const n={type:"track",event:R,properties:e,time:e.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,I.isSupport()&&I.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(t){I.isSupport()&&I.remove(t||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){if(this.__canCapture())for(let t=window.localStorage.length-1;t>=0;t--){const e=window.localStorage.key(t);if(e&&e!==`${this.storageName}-${this.pageId}`&&0===e.indexOf(`${this.storageName}-`)){const t=I.parse(e);i(t)&&Date.now()-t.time>t.heartbeat_interval_time+5e3&&(delete t.heartbeat_interval_time,t._flush_time=(new Date).getTime(),mt({event:R,properties:t?.properties},this.config),this.delHeartBeatData(e))}}}getPageLeaveProperties(){let t=(Date.now()-this.startTime)/1e3;(isNaN(t)||t<0||t>this.maxDuration)&&(t=0),t=Number(t.toFixed(3));const e={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:w(this.url)};return 0!==t&&(e.$event_duration=t),e}destroy(){this.eventListeners.forEach(({target:t,event:e,handler:n})=>{t.removeEventListener(e,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};Rt.NAME="pageleave";let Tt=Rt;const Ct=class{constructor({emitter:t,config:e,sdk:n}){this.eventSended=!1,this.emitter=t,this.config=e,this.sdk=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit)return;const t=()=>{let e=0;const n={};if(window.performance){e=function(){let t=0;if("function"==typeof performance.getEntriesByType){const e=performance.getEntriesByType("navigation");e.length>0&&(t=e[0].domContentLoadedEventEnd||0)}return t}();const t=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const t=performance.getEntries();let e=0;for(const n of t)"transferSize"in n&&(e+=n.transferSize);if("number"==typeof e&&e>=0&&e<10737418240)return Number((e/1024).toFixed(3))}}();t&&(n.$page_resource_size=t)}else console.warn("Performance API is not supported.");e>0&&!Number.isFinite(e)&&(n.$event_duration=Number((e/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,mt({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",t)};"complete"===document.readyState?t():window.addEventListener&&window.addEventListener("load",t)}};Ct.NAME="pageload";let Nt=Ct;function Pt(t,e){if(!l(t))return!1;const n=o(t.tagName)?t.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=t.getAttribute("name")||"",i.$element_id=t.getAttribute("id")||"",i.$element_class_name=o(t.className)?t.className:"",i.$element_target_url=t.getAttribute("href")||"",i.$element_content=function(t,e){return o(e)&&"input"===e.toLowerCase()?("button"===(n=t).type||"submit"===n.type)&&n.value||"":function(t,e){let n="",i="";return t.textContent?n=S(t.textContent):t.innerText&&(n=S(t.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==e&&"INPUT"!==e||(i=t.value||""),i}(t,e);var n}(t,n)||"",i.$element_selector=kt(t)||"",i.$element_path=function(t){let e=[];for(;t.parentNode&&l(t);){if(!o(t.tagName))return"";if(t.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.id)){e.unshift(t.tagName.toLowerCase()+"#"+t.id);break}if(t===document.body){e.unshift("body");break}e.unshift(t.tagName.toLowerCase()),t=t.parentNode}return e.join(" > ")}(t)||"";const s=function(t,e){const n=e.pageX||e.clientX+Lt().scrollLeft||e.offsetX+$t(t).targetEleX,i=e.pageY||e.clientY+Lt().scrollTop||e.offsetY+$t(t).targetEleY;return{$page_x:Ft(n),$page_y:Ft(i)}}(t,e);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function kt(t,e=[]){if(!(t&&t.parentNode&&t.parentNode.children&&o(t.tagName)))return"";e=Array.isArray(e)?e:[];const n=t.nodeName.toLowerCase();return t&&"body"!==n&&1==t.nodeType?(e.unshift(function(t){if(!t||!l(t)||!o(t.tagName))return"";let e=t.parentNode&&9==t.parentNode.nodeType?-1:function(t){if(!t.parentNode)return-1;let e=0;const n=t.tagName,i=t.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(t===i[s])return e;e++}return-1}(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~e?":nth-of-type("+(e+1)+")":"")}(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?e.join(" > "):kt(t.parentNode,e)):(e.unshift("body"),e.join(" > "))}function Lt(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function $t(t){if(document.documentElement.getBoundingClientRect){const e=t.getBoundingClientRect();return{targetEleX:e.left+Lt().scrollLeft||0,targetEleY:e.top+Lt().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Ft(t){return Number(Number(t).toFixed(3))}const Bt=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(t){const e=t.target;if(!e)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(e.tagName))return;if("true"===e.getAttribute("sensorswave-disable"))return;mt({event:"$WebClick",properties:Pt(e,t)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};Bt.NAME="webclick";let xt=Bt;const Mt=class{constructor({emitter:t,config:e,sdk:n}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;if(t.enableAB){if(this.sdk&&"function"==typeof this.sdk.hasOptedOutCapturing&&this.sdk.hasOptedOutCapturing())return;this.fastFetch().then(()=>{this.emitter.emit(A)}),t.abRefreshInterval<3e4&&(t.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},t.abRefreshInterval)}}async fastFetch(){const t=N.getABData(this.config.abRefreshInterval);return t&&t.length?(this.emitter.emit(A),Promise.resolve(t)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(t=>{!function({opts:t,cb:e}){if(!st())return void(e&&e({}));if(!rt())return void(e&&e({}));const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return void(e&&e({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...tt(),...gt(N.getCommonProps())}},sdk:"webjs",sdk_version:v};$({url:lt(t),method:"POST",data:s,headers:ht(t),callback:t=>{200!==t.statusCode?(console.error("Failed to fetch feature flags"),e&&e({})):e&&e(t.json)}})}({opts:this.config,cb:e=>{N.saveABData(e?.data?.results||[]),t(e),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(t){return await this.fastFetch().catch(console.warn),N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_GATE&&e.key==t)}async checkFeatureGate(t){const e=await this.getFeatureGate(t);return!!e&&(!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),!1):(wt({data:e,opts:this.config}),"fail"!==e.vid))}async getExperiment(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.EXPERIMENT&&e.key===t);return e?!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),{}):(wt({data:e,opts:this.config}),e?.value||{}):{}}async getFeatureConfig(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_CONFIG&&e.key===t);if(!e)return{};if(!e.hasOwnProperty("vid")&&e.key)return wt({isUnset:!0,data:e,opts:this.config}),{};wt({data:e,opts:this.config});const n=e?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Mt.NAME="abtest";let Dt=Mt;const Ht=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],Ut="sensorswave_utm",Xt=class t{constructor({sdk:t,emitter:e,config:n}){this.sdk=t,this.emitter=e,this.config=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit){let e=t.readFromSessionStorage();return e&&0!==Object.keys(e).length||(e=t.captureAndStore(this.config?.debug)),void this.scheduleInitialUTM(e)}const e=t.getUTMFromURL();t.saveToSessionStorage(e,this.config?.debug),this.scheduleInitialUTM(e)}scheduleInitialUTM(t){setTimeout(()=>{this.sendInitialUTM(t)},0)}static getUTMFromURL(){try{const t=new URLSearchParams(window.location.search),e={};return Ht.forEach(n=>{const i=t.get(n);i&&(e[n]=i)}),e}catch(e){return t.getUTMFromURLFallback()}}static getUTMFromURLFallback(){const t={};return window.location.search.substring(1).split("&").forEach(e=>{const[n,i]=e.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";Ht.includes(s)&&(t[s]=r)}),t}static readFromSessionStorage(){try{const t=sessionStorage.getItem(Ut);if(!t)return{};const e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch(t){return{}}}static saveToSessionStorage(t,e=!1){try{sessionStorage.setItem(Ut,JSON.stringify(t))}catch(n){e&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",n)}}static captureAndStore(e=!1){const n=t.getUTMFromURL();return t.saveToSessionStorage(n,e),n}sendInitialUTM(t){const e={};Ht.forEach(n=>{e[`$initial_${n}`]=null!=t[n]?t[n]:""});try{this.sdk.profileSetOnce(e)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};Xt.NAME="UTM";let jt=Xt;const qt=1e3,Wt=/^\s*(?:async\s+)?at\s+(?:(.+)\s+\()?(.+?):(\d+):(\d+)\)?$/,Gt=/^(?:(.*)@)?(.+?):(\d+):(\d+)$/;function zt(t){let e=t;try{const t=location.origin;t&&0===e.indexOf(t)&&(e=e.substring(t.length))}catch(s){}const n=e.indexOf("?");n>-1&&(e=e.substring(0,n));const i=e.indexOf("#");return i>-1&&(e=e.substring(0,i)),e}function Yt(t){return t.map(t=>({platform:"web:javascript",filename:zt(t.file),function:t.fn||"?",lineno:Number(t.line),colno:Number(t.col),abs_path:Kt(t.file,1e3)}))}function Kt(t,e){return t.length>e?t.substring(0,e):t}function Jt(t){let e;if("string"==typeof t)e=t;else if(null!==t&&"object"==typeof t){try{e=JSON.stringify(t)}catch(n){e=Object.prototype.toString.call(t)}e||(e=Object.prototype.toString.call(t))}else e=String(t);return Kt(e,qt)}function Zt(t){const{frames:e,headerType:n}=function(t){const e=[];let n="";if(!t||"string"!=typeof t)return{frames:e,headerType:n};const i=t.split(/\r?\n/);for(let s=0;s<i.length;s++){const t=i[s];if(!t||t.length>1024)continue;const r=t.match(Wt),o=r?null:t.match(Gt),a=r||o;if(a)e.push({fn:a[1]||"?",file:a[2],line:a[3],col:a[4]});else if(0===s){const e=t.indexOf(":");e>0&&(n=t.substring(0,e).trim())}if(e.length>=30)break}return{frames:e,headerType:n}}(t&&t.stack);let i=t&&t.name||n||"Error";return i=Kt(String(i),200),{$exception_level:"error",$exception_type:i,$exception_message:Kt(String(t&&t.message||""),qt),$exception_frames:Yt(e)}}function Qt(t,e,n,i){let s=[];return e&&(s=[{platform:"web:javascript",filename:zt(e),function:"?",lineno:n||0,colno:i||0,abs_path:Kt(e,1e3)}]),{$exception_level:"error",$exception_type:"Error",$exception_message:Kt(String(t||""),qt),$exception_frames:s}}class Vt{constructor(t=10,e=1,n=1e4){this.buckets=new Map,this.bucketSize=t,this.refillRate=e,this.refillInterval=n}allow(t){const e=Date.now();let n=this.buckets.get(t);if(n){if(e>n.lastRefill){const t=Math.floor((e-n.lastRefill)/this.refillInterval)*this.refillRate;t>0&&(n.tokens=Math.min(this.bucketSize,n.tokens+t),n.lastRefill+=t/this.refillRate*this.refillInterval)}}else n={tokens:this.bucketSize,lastRefill:e},this.buckets.set(t,n);return n.tokens>=1&&(n.tokens-=1,!0)}reset(){this.buckets.clear()}}const te=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleError=null,this.boundHandleRejection=null,this.rateLimiter=new Vt,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleError=this.handleError.bind(this),this.boundHandleRejection=this.handleRejection.bind(this),window.addEventListener("error",this.boundHandleError,!0),window.addEventListener("unhandledrejection",this.boundHandleRejection),this.isInitialized=!0)}handleError(t){try{const e=t.target;let n;if(e&&e!==window&&e.tagName)n=function(t){const e=t,n=(e.tagName||"").toLowerCase(),i=Kt(String(e.src||e.href||""),qt);return{$exception_level:"error",$exception_type:"ResourceLoadError",$exception_message:`Failed to load <${n}>${i?` from ${i}`:""}`,$exception_frames:[]}}(e);else{const e=t;n=e.error instanceof Error?Zt(e.error):Qt(String(e.message||""),e.filename,e.lineno,e.colno)}this.send(n)}catch(e){}}handleRejection(t){try{const e=t.reason;this.send(function(t){return t instanceof Error?Zt(t):{$exception_level:"error",$exception_type:"UnhandledRejection",$exception_message:Jt(t),$exception_frames:[]}}(e))}catch(e){}}send(t){t.$exception_message&&this.rateLimiter.allow(t.$exception_type)&&mt({event:T,properties:t},this.config)}destroy(){this.boundHandleError&&(window.removeEventListener("error",this.boundHandleError,!0),this.boundHandleError=null),this.boundHandleRejection&&(window.removeEventListener("unhandledrejection",this.boundHandleRejection),this.boundHandleRejection=null),this.rateLimiter.reset(),this.isInitialized=!1}};te.NAME="exception";let ee=te;const ne=[],ie={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1,enableErrorTrack:!1,enableCrashTrack:!1,optOutCapturing:!1,persistOptOut:!1},se=new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new t,this.pluginCore={},this.commonProps={},this.spaCleanup=null,this._optOutCapturing=!1,this.consentStorage=new vt(!1),this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance=this}init(t,e={}){return this.inited?this:(O.instance=this,e.sourceToken=t,this.mergeConfig(e),this.consentStorage=new vt(!0===this.config.persistOptOut),this._optOutCapturing?this.consentStorage.write(!0):!0===this.config.optOutCapturing?(this._optOutCapturing=!0,this.consentStorage.write(!0)):!0===this.consentStorage.read()&&(this._optOutCapturing=!0),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0,this._optOutCapturing?(jt.captureAndStore(this.config.debug),this.eventEmitter.emit(b),this.inited=!0,this):(this.__setupAfterConsent(),this.eventEmitter.emit(b),this.inited=!0,this))}__setupAfterConsent(){if(this._setupAfterConsentDone)return;this._setupAfterConsentDone=!0;const t=this.config;ne.length=0,N.init(t.crossSubdomainCookie),t.anonId&&N.setAnonId(t.anonId),function(){if(window._swFailedRequestsInitialized)return;window._swFailedRequestsInitialized=!0;const t=O.instance;t&&"function"==typeof t.hasOptedOutCapturing&&t.hasOptedOutCapturing()||t&&!0===t._postConsentInit||function(){const t=et.getAll();if(0!==t.length)for(let e=0,n=t.length;e<n;e+=10){const n=t.slice(e,e+10),i=[],s=[];n.forEach(t=>{Array.isArray(t.data)?i.push(...t.data):i.push(t.data),s.push(t.id)});const r=n[n.length-1],o=r.url,a=r.headers;$({url:o,method:"POST",data:i,headers:a,callback:t=>{200!==t.statusCode?(console.error("Failed to send batch stored requests:",t),P(t.statusCode)||s.forEach(t=>{et.dequeue(t)})):s.forEach(t=>{et.dequeue(t)})}})}}()}(),ne.push(jt),t.autoCapture&&this.autoTrack(),t.enableAB&&ne.push(Dt),t.enableClickTrack&&ne.push(xt),t.enableCrashTrack&&t.debug&&console.warn("[SensorsWave] enableCrashTrack 仅在 app 宿主环境生效,当前 Web 环境不采集 crash"),t.enableErrorTrack&&ne.push(ee),this.pluginCore=new bt({plugins:ne,emitter:this.eventEmitter,config:t,sdk:this}),this.spaCleanup=function(t){let e=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){t(e),e=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),t(e),e=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),t(e),e=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(t=>{this.eventEmitter.emit(y,t)})}mergeConfig(t){this.config={...ie,...t}}__canCapture(){return this.inited&&!this._optOutCapturing}track(t){this.__canCapture()&&function(t,e){if(!st())return;if(!rt())return;const n={...t};n.time||(n.time=Date.now()),n.login_id||(n.login_id=N.getLoginId()),n.anon_id||(n.anon_id=N.getAnonId()),n.trace_id||(n.trace_id=N.getTraceId()),n.properties={...tt(),...gt(N.getCommonProps()),...n.properties};const i=ut(e),s=ht(e),r=!1!==e.batchSend&&at();if(!r)return dt(i,{data:[n],headers:s});et.enqueue(i,[n],s),r.add()}(t,this.config)}trackEvent(t,e){this.__canCapture()&&mt({event:t,properties:e},this.config)}trackException(t,e){if(!this.__canCapture())return;const n={...e||{},...t instanceof Error?Zt(t):Qt(String(t))};mt({event:T,properties:n},this.config)}autoTrack(){ne.push(At,Nt,Tt)}profileSet(t){this.__canCapture()&&Et({userProps:{$set:t},opts:this.config})}profileSetOnce(t){this.__canCapture()&&Et({userProps:{$set_once:t},opts:this.config})}profileIncrement(t){this.__canCapture()&&Et({userProps:{$increment:t},opts:this.config})}profileAppend(t){this.__canCapture()&&Et({userProps:{$append:t},opts:this.config})}profileUnion(t){this.__canCapture()&&Et({userProps:{$union:t},opts:this.config})}profileUnset(t){if(!this.__canCapture())return;const e={};r(t)?t.forEach(function(t){e[t]=null}):e[t]=null,Et({userProps:{$unset:e},opts:this.config})}profileDelete(){this.__canCapture()&&Et({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(t){if(!i(t))return console.warn("Commmon Properties must be an object!");this.commonProps=t,N.setCommonProps(this.commonProps)}clearCommonProperties(t){if(!r(t))return console.warn("Commmon Properties to be cleared must be an array!");t.forEach(t=>{delete this.commonProps[t]}),N.setCommonProps(this.commonProps)}identify(t){this.__canCapture()&&(N.setLoginId(t),function(t){if(!st())return;if(!rt())return;const e=N.getLoginId(),n=N.getAnonId();if(!e||!n)return;const i={time:Date.now(),trace_id:N.getTraceId(),event:"$Identify",login_id:e,anon_id:n,properties:ft()},s=ut(t),r=ht(t),o=at();if(!o)return dt(s,{data:[i],headers:r});et.enqueue(s,[i],r),o.add()}(this.config))}setLoginId(t){this.__canCapture()&&N.setLoginId(t)}getAnonId(){return this.__canCapture()?N.getAnonId():""}setAnonId(t){this.__canCapture()&&N.setAnonId(t)}getLoginId(){return this.__canCapture()?N.getLoginId():""}reset(t=!1){this.__canCapture()&&(N.clearLoginId(),t&&N.resetAnonId())}checkFeatureGate(t){if(!this.__canCapture())return Promise.resolve(!1);const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.checkFeatureGate(t):Promise.reject("AB is disabled")}getExperiment(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getExperiment(t):Promise.reject("AB is disabled")}getFeatureConfig(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getFeatureConfig(t):Promise.reject("AB is disabled")}optOutCapturing(){this._optOutCapturing=!0,this.consentStorage.write(!0),ot&&ot.pause()}optInCapturing(){if(this._optOutCapturing=!1,this.consentStorage.write(!1),ot&&ot.resume(),this.inited&&!this._setupAfterConsentDone){this._postConsentInit=!0;try{this.__setupAfterConsent(),this.eventEmitter.emit(b)}finally{this._postConsentInit=!1}}}hasOptedOutCapturing(){return this._optOutCapturing}destroy(){ot&&(ot.destroy(),ot=null),"undefined"!=typeof window&&(window._swFailedRequestsInitialized=!1),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.pluginCore={},this.eventEmitter&&this.eventEmitter.removeAllListeners(),this.consentStorage=new vt(!0===this.config?.persistOptOut),this._optOutCapturing=!1,this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance===this&&(O.instance=null)}};module.exports=se;
|
package/dist/index.es.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class t{constructor(){this.listeners={}}on(t,e,n=!1){if(t&&e){if(!s(e))throw new Error("listener must be a function");this.listeners[t]=this.listeners[t]||[],this.listeners[t].push({listener:e,once:n})}}off(t,e){const n=this.listeners[t];if(!n?.length)return;"number"==typeof e&&n.splice(e,1);const i=n.findIndex(t=>t.listener===e);-1!==i&&n.splice(i,1)}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((n,i)=>{n.listener.call(this,...e),n.listener.once&&this.off(t,i)})}once(t,e){this.on(t,e,!0)}removeAllListeners(t){t?this.listeners[t]=[]:this.listeners={}}}const e={get:function(t){const e=t+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let t=n[i];for(;" "==t.charAt(0);)t=t.substring(1,t.length);if(0==t.indexOf(e))return l(t.substring(e.length,t.length))}return null},set:function({name:t,value:e,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",u="",c="";if(0!==(n=null==n||void 0===n?365:n)){const t=/* @__PURE__ */new Date;"s"===String(n).slice(-1)?t.setTime(t.getTime()+1e3*Number(String(n).slice(0,-1))):t.setTime(t.getTime()+24*n*60*60*1e3),o="; expires="+t.toUTCString()}function h(t){return t?t.replace(/\r\n/g,""):""}i&&(u="; SameSite="+i),s&&(a="; secure");const l=h(t),d=h(e),p=h(r);p&&(c="; domain="+p),l&&d&&(document.cookie=l+"="+encodeURIComponent(d)+o+"; path=/"+c+u+a)},remove:function(t){this.set({name:t,value:"",expires:-1})},isSupport:function({samesite:t,secure:e}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:t,secure:e}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(t){return"[object Object]"===n.call(t)}function s(t){const e=n.call(t);return"[object Function]"==e||"[object AsyncFunction]"==e}function r(t){return"[object Array]"==n.call(t)}function o(t){return"[object String]"==n.call(t)}function a(t){return void 0===t}const u=Object.prototype.hasOwnProperty;function c(t){if(i(t)){for(let e in t)if(u.call(t,e))return!1;return!0}return!1}function h(t){return!(!t||1!==t.nodeType)}function l(t){let e=t;try{e=decodeURIComponent(t)}catch(n){e=t}return e}function d(t){try{return JSON.parse(t)}catch(e){return""}}const p=function(){let t=Date.now();return function(e){return Math.ceil((t=(9301*t+49297)%233280,t/233280*e))}}();function g(){if("function"==typeof Uint32Array){let t;if("undefined"!=typeof crypto&&(t=crypto),t&&i(t)&&t.getRandomValues)return t.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return p(1e19)/1e19}const f=/* @__PURE__ */function(){function t(t){return("0".repeat(t)+Date.now().toString(16)).slice(-t)}return function(){let e=String(screen.height*screen.width);e=e&&/\d{4,}/.test(e)?e.slice(-4):String(31242*g()).replace(".","").slice(0,4);return t(8)+"-"+g().toString(16).replace(".","").slice(-4)+"-"+function(){const t=navigator.userAgent;let e,n=[],i=0;function s(t,e){let i=0;for(let s=0;s<e.length;s++)i|=n[s]<<8*s;return(t^i)>>>0}for(let r=0;r<t.length;r++)e=t.charCodeAt(r),n.unshift(255&e),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+e+"-"+t(12)||(String(g())+String(g())+String(g())).slice(2,15)}}();function m(t,e){e&&"string"==typeof e||(e="");let n=null;try{n=new URL(t).hostname}catch(i){}return n||e}function E(t){let e=[];try{e=atob(t).split("").map(function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})}catch(n){e=[]}try{return decodeURIComponent(e.join(""))}catch(n){return e.join("")}}function _(t){let e="";try{e=btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}))}catch(n){e=t}return e}const I={get:function(t){return window.localStorage.getItem(t)},parse:function(t){let e;try{e=JSON.parse(I.get(t))||null}catch(n){console.warn(n)}return e},set:function(t,e){try{window.localStorage.setItem(t,e)}catch(n){console.warn(n)}},remove:function(t){window.localStorage.removeItem(t)},isSupport:function(){let t=!0;try{const e="__local_store_support__",n="testIsSupportStorage";I.set(e,n),I.get(e)!==n&&(t=!1),I.remove(e)}catch(e){t=!1}return t}};function S(t){return t.trim()}function w(t){if(!t||"string"!=typeof t)return"";try{return new URL(t,window.location.origin).pathname}catch(e){return""}}const O={},v="1.2.0",A="init-ready",y="spa-switch",R="ff-ready",T="$PageLeave";var b=/* @__PURE__ */(t=>(t[t.FEATURE_GATE=1]="FEATURE_GATE",t[t.FEATURE_CONFIG=2]="FEATURE_CONFIG",t[t.EXPERIMENT=3]="EXPERIMENT",t))(b||{});const C={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(t){this.commonProps=t},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(t,e){this._state[t]=e,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let t=JSON.parse(JSON.stringify(this._state));t.identities&&(t.identities=_(JSON.stringify(t.identities)));const n=JSON.stringify(t);e.set({name:this.getCookieName(),value:n,expires:365})},init:function(t){let n,s;this.crossSubdomain=t,e.isSupport()&&(n=e.get(this.getCookieName()),s=d(n)),C._state={...s||{}},C._state.identities&&(C._state.identities=d(E(C._state.identities))),C._state.identities&&i(C._state.identities)&&!c(C._state.identities)||(C._state.identities={$identity_cookie_id:f()}),C.save()},setLoginId(t){"number"==typeof t&&(t=String(t)),void 0!==t&&t&&(C.set("login_id",t),C.save())},setAnonId(t){"number"==typeof t&&(t=String(t)),"string"==typeof t&&t?(C.set("anon_id",t),C.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",t)},saveABData(t){if(!t||c(t))return;this._abData=t;let e=JSON.parse(JSON.stringify(this._abData));e=_(JSON.stringify(e));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:e,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(t=6e5){try{let e=localStorage.getItem(this.getABLSName());if(e){const{time:n,data:i,login_id:s,anon_id:r}=d(e)||{};if(n&&i&&Date.now()-n<t&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const t=d(E(i));return this._abData=Array.isArray(t)?t:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(e){console.warn("Failed to load abdata from localStorage",e),this._abData=[]}return this._abData||[]}};function N(t){var e;if(t.data)return{contentType:"application/json",body:(e=t.data,JSON.stringify(e,(t,e)=>"bigint"==typeof e?e.toString():e,undefined))}}const P=[];function k(t){const e={...t};e.timeout=e.timeout||6e4;const n=e.transport??"fetch",i=P.find(t=>t.transport===n)?.method??P[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(e)}function L(t){return o(t=t||document.referrer)&&(t=l(t=t.trim()))||""}function F(t){const e=m(t=t||L());if(!e)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let t=n[i];for(let n=0,s=t.length;n<s;n++)if(t[n].test(e))return i}return""}function B(t,e){return-1!==t.indexOf(e)}"function"==typeof fetch&&P.push({transport:"fetch",method:function(t){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const e=N(t),n=new Headers;t.headers&&Object.keys(t.headers).forEach(e=>{n.append(e,t.headers[e])}),e?.contentType&&n.append("Content-Type",e.contentType),fetch(t.url,{method:t.method||"GET",headers:n,body:e?.body}).then(e=>e.text().then(n=>{const i={statusCode:e.status,text:n};if(200===e.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}t.callback?.(i)})).catch(e=>{console.error("Request failed:",e),t.callback?.({statusCode:0,text:String(e)})})}}),"undefined"!=typeof XMLHttpRequest&&P.push({transport:"XHR",method:function(t){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const e=new XMLHttpRequest;e.open(t.method||"GET",t.url,!0);const n=N(t);t.headers&&Object.keys(t.headers).forEach(n=>{e.setRequestHeader(n,t.headers[n])}),n?.contentType&&e.setRequestHeader("Content-Type",n.contentType),e.timeout=t.timeout||6e4,e.withCredentials=!0,e.onreadystatechange=()=>{if(4===e.readyState){const i={statusCode:e.status,text:e.responseText};if(200===e.status)try{i.json=JSON.parse(e.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}t.callback?.(i)}},e.send(n?.body)}});const M={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},D="(\\d+(\\.\\d+)?)",$=new RegExp("Version/"+D),x=new RegExp(M.XBOX,"i"),U=new RegExp(M.PLAYSTATION+" \\w+","i"),H=new RegExp(M.NINTENDO+" \\w+","i"),X=new RegExp(M.BLACKBERRY+"|PlayBook|BB10","i"),q=new RegExp("(HUAWEI|honor|HONOR)","i"),W=new RegExp("(Xiaomi|Redmi)","i"),G=new RegExp("(OPPO|realme)","i"),j=new RegExp("(vivo|IQOO)","i"),z={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function Y(t,e){return e=e||"",B(t," OPR/")&&B(t,"Mini")?M.OPERA_MINI:B(t," OPR/")?M.OPERA:X.test(t)?M.BLACKBERRY:B(t,"IE"+M.MOBILE)||B(t,"WPDesktop")?M.INTERNET_EXPLORER_MOBILE:B(t,M.SAMSUNG_BROWSER)?M.SAMSUNG_INTERNET:B(t,M.EDGE)||B(t,"Edg/")?M.MICROSOFT_EDGE:B(t,"FBIOS")?M.FACEBOOK+" "+M.MOBILE:B(t,"UCWEB")||B(t,"UCBrowser")?M.UC_BROWSER:B(t,"CriOS")?M.CHROME_IOS:B(t,"CrMo")||B(t,M.CHROME)?M.CHROME:B(t,M.ANDROID)&&B(t,M.SAFARI)?M.ANDROID_MOBILE:B(t,"FxiOS")?M.FIREFOX_IOS:B(t.toLowerCase(),M.KONQUEROR.toLowerCase())?M.KONQUEROR:function(t,e){return e&&B(e,M.APPLE)||B(n=t,M.SAFARI)&&!B(n,M.CHROME)&&!B(n,M.ANDROID);var n}(t,e)?B(t,M.MOBILE)?M.MOBILE_SAFARI:M.SAFARI:B(t,M.FIREFOX)?M.FIREFOX:B(t,"MSIE")||B(t,"Trident/")?M.INTERNET_EXPLORER:B(t,"Gecko")?M.FIREFOX:""}const K={[M.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+D)],[M.MICROSOFT_EDGE]:[new RegExp(M.EDGE+"?\\/"+D)],[M.CHROME]:[new RegExp("("+M.CHROME+"|CrMo)\\/"+D)],[M.CHROME_IOS]:[new RegExp("CriOS\\/"+D)],[M.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+D)],[M.SAFARI]:[$],[M.MOBILE_SAFARI]:[$],[M.OPERA]:[new RegExp("("+M.OPERA+"|OPR)\\/"+D)],[M.FIREFOX]:[new RegExp(M.FIREFOX+"\\/"+D)],[M.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+D)],[M.KONQUEROR]:[new RegExp("Konqueror[:/]?"+D,"i")],[M.BLACKBERRY]:[new RegExp(M.BLACKBERRY+" "+D),$],[M.ANDROID_MOBILE]:[new RegExp("android\\s"+D,"i")],[M.SAMSUNG_INTERNET]:[new RegExp(M.SAMSUNG_BROWSER+"\\/"+D)],[M.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+D)],Mozilla:[new RegExp("rv:"+D)]};function J(t,e){const n=Y(t,e),i=K[n];if(a(i))return null;for(let s=0;s<i.length;s++){const e=i[s],n=t.match(e);if(n)return parseFloat(n[n.length-2])}return null}const Z=[[new RegExp(M.XBOX+"; "+M.XBOX+" (.*?)[);]","i"),t=>[M.XBOX,t&&t[1]||""]],[new RegExp(M.NINTENDO,"i"),[M.NINTENDO,""]],[new RegExp(M.PLAYSTATION,"i"),[M.PLAYSTATION,""]],[X,[M.BLACKBERRY,""]],[new RegExp(M.WINDOWS,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[M.WINDOWS_PHONE,""];if(new RegExp(M.MOBILE).test(e)&&!/IEMobile\b/.test(e))return[M.WINDOWS+" "+M.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){const t=n[1];let i=z[t]||"";return/arm/i.test(e)&&(i="RT"),[M.WINDOWS,i]}return[M.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){const e=[t[3],t[4],t[5]||"0"];return[M.IOS,e.join(".")]}return[M.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=a(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+M.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+M.ANDROID+")","i"),t=>{if(t&&t[2]){const e=[t[2],t[3],t[4]||"0"];return[M.ANDROID,e.join(".")]}return[M.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{const e=["Mac OS X",""];if(t&&t[1]){const n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[M.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function Q(){const t=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,e=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(t){for(let e=0;e<Z.length;e++){const[n,i]=Z[e],s=n.exec(t),r=s&&("function"==typeof i?i(s,t):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:Y(n),$browser_version:J(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:t,$viewport_width:e,$lib:"webjs",$lib_version:v,$search_engine:F(),$referrer:L(),$referrer_host:m(r=r||L()),$title:document.title,$language:navigator.language,$model:(s=n,(H.test(s)?M.NINTENDO:U.test(s)?M.PLAYSTATION:x.test(s)?M.XBOX:new RegExp(M.OUYA,"i").test(s)?M.OUYA:new RegExp("("+M.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?M.WINDOWS_PHONE:/iPad/.test(s)?M.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?M.APPLE_WATCH:X.test(s)?M.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp(M.NOKIA,"i").test(s)?M.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":q.test(s)?M.HUAWEI:W.test(s)?M.XIAOMI:G.test(s)?M.OPPO:j.test(s)?M.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp(M.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?M.ANDROID:M.ANDROID_TABLET:M.ANDROID:new RegExp("(pda|"+M.MOBILE+")","i").test(s)?M.GENERIC_MOBILE:new RegExp(M.TABLET,"i").test(s)&&!new RegExp(M.TABLET+" pc","i").test(s)?M.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-/* @__PURE__ */(new Date).getTimezoneOffset()};var s,r}const V=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const t=localStorage.getItem(this.STORAGE_KEY);t&&(this.queue=d(t)||[])}catch(t){console.warn("Failed to load queue from localStorage:",t),this.queue=[]}}cleanupExpiredItems(){const t=Date.now(),e=this.queue.filter(e=>t-e.timestamp<this.MAX_AGE_MS);e.length!==this.queue.length&&(this.queue=e,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(t){console.warn("Failed to save queue to localStorage:",t)}}enqueue(t,e,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:t,data:e,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(t){try{this.queue=this.queue.filter(e=>e.id!==t),this.saveToStorage()}catch(e){console.warn("Failed to dequeue request:",e)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(t){return console.warn("Failed to get queue items:",t),[]}}incrementRetryCount(t){const e=this.queue.find(e=>e.id===t);return!(!e||e.retryCount>=e.maxRetries||(e.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(t){console.warn("Failed to clear queue from localStorage:",t)}}getItemById(t){return this.queue.find(e=>e.id===t)}};class tt{constructor(t={}){this.flushTimer=null,this.isFlushing=!1,this.paused=!1,this.destroyed=!1,this.config={maxBatchSize:t.maxBatchSize||20,flushInterval:t.flushInterval||5e3},this.startFlushTimer()}pause(){this.paused=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}resume(){this.paused&&(this.paused=!1,this.startFlushTimer())}isPaused(){return this.paused}add(){V.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.paused||this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const t=V.getAll();if(0===t.length)return this.isFlushing=!1,void this.startFlushTimer();const e=[],n=[];t.forEach(t=>{Array.isArray(t.data)?e.push(...t.data):e.push(t.data),n.push(t.id)});const i=e.slice(0,this.config.maxBatchSize),s=t[t.length-1],r=s.url,o=s.headers;O.instance&&O.instance.config.debug&&console.log(JSON.stringify(i,null,2)),k({url:r,method:"POST",data:i,headers:o,callback:t=>{200===t.statusCode?n.forEach(t=>{V.dequeue(t)}):console.error("Failed to send batch events:",t),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.destroyed||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{V.getAll().length>0&&this.triggerFlush()},this.config.flushInterval))}destroy(){this.destroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush()}}let et=null;function nt(){const t=O.instance;return!(!t||!t.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}function it(){const t=O.instance;return!t||"function"!=typeof t.hasOptedOutCapturing||!t.hasOptedOutCapturing()}let st=null;function rt(){return I.isSupport()?(st||(et||(et=new tt({maxBatchSize:20,flushInterval:5e3})),st=et),st):null}function ot(t,e,n){return k({url:t,method:"POST",data:e.data,headers:e.headers,callback:t=>{if(200!==t.statusCode){if(n)if(V.incrementRetryCount(n)){const t=V.getItemById(n);if(t){const e=Math.min(1e3*Math.pow(2,t.retryCount),3e4);setTimeout(()=>{ot(t.url,{data:t.data,headers:t.headers},t.id)},e)}}else console.warn("Max retries reached for request:",n)}else n&&V.dequeue(n),e.callback&&e.callback(t.json)}})}function at(t){return`${t.apiHost}/in/track`}function ut(t){return`${t.apiHost}/ab/evalall`}function ct(t){return{"Content-Type":"application/json",SourceToken:t.sourceToken}}function ht(t,e,n){O.instance&&O.instance.config.debug&&console.log(JSON.stringify(e.data,null,2));const i=V.enqueue(t,e.data,e.headers);return ot(t,{...e,callback:void 0},i)}function lt(){try{const t=sessionStorage.getItem("sensorswave_utm");if(!t)return{};const e=JSON.parse(t),n={};return Object.entries(e).forEach(([t,e])=>{null!=e&&""!==e&&(n[`$${t}`]=e)}),n}catch(t){return{}}}function dt(t){const e={};return Object.entries(t).forEach(([t,n])=>{if("function"==typeof n)try{const i=n();e[t]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",t,i)}else e[t]=n}),e}function pt(t={},e=!0){const n={...e?Q():{},...dt(C.getCommonProps()),...t},i=lt();return Object.keys(i).length>0&&Object.assign(n,i),n}function gt(t,e,n=!0){if(!nt())return;if(!it())return;const i={time:Date.now(),trace_id:C.getTraceId(),event:t.event,properties:pt(t.properties,n)},s=lt();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),t.user_properties&&(t.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...t.user_properties.$set},delete t.user_properties.$set),i.user_properties={...i.user_properties,...t.user_properties});const r=C.getLoginId(),o=C.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=at(e),u=ct(e),c=!1!==e.batchSend&&rt();c?(V.enqueue(a,[i],u),c.add()):ht(a,{data:[i],headers:u})}function ft({userProps:t,opts:e}){if(!nt())return;if(!it())return;const n=C.getLoginId(),i=C.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:C.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:t,properties:pt()},r=at(e),o=ct(e),a=rt();if(!a)return ht(r,{data:[s],headers:o});V.enqueue(r,[s],o),a.add()}function mt(t){return t.typ===b.FEATURE_GATE||t.typ===b.FEATURE_CONFIG?`$feature_${t.id}`:t.typ===b.EXPERIMENT?`$exp_${t.id}`:""}function Et(t){const e=t.typ;return[b.FEATURE_GATE,b.EXPERIMENT,b.FEATURE_CONFIG].includes(e)?{[mt(t)]:t.vid}:{}}function _t(t){const e=t.typ;return e===b.FEATURE_GATE||e===b.FEATURE_CONFIG?{$feature_key:t.key,$feature_variant:t.vid}:e===b.EXPERIMENT?{$exp_key:t.key,$exp_variant:t.vid}:{}}function It({isUnset:t=!1,data:e,opts:n}){if(!nt())return;if(!it())return;if(!e||c(e)||e.disable_impress)return;const i=C.getLoginId(),s=C.getAnonId();if(!i&&!s)return;const r=e.typ===b.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=t?{$unset:{[mt(e)]:null}}:{$set:{...Et(e)}},gt({event:r,properties:_t(e),user_properties:o},n)}const St="sensorswave_opt_out";class wt{constructor(t){this.persist=t}read(){if(this.persist)try{const t=I.get(St);return"0"===t||"1"!==t&&void 0}catch{return}}write(t){if(this.persist)try{I.set(St,t?"0":"1")}catch{}}}class Ot{constructor({plugins:t,emitter:e,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=e,this.config=n,this.sdk=i,this.registerBuiltInPlugins(t),this.created(),this.emitter.on(A,()=>{this.init()})}registerBuiltInPlugins(t){for(let e=0,n=t.length;e<n;e++)this.registerPlugin(t[e])}registerPlugin(t){this.plugins.push(t)}getPlugins(){return this.plugins}getPlugin(t){return this.pluginInsMap[t]}created(){for(let t=0,e=this.plugins.length;t<e;t++){const e=this.plugins[t];if(!e.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new e({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[e.NAME]=n}}init(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.init&&e.init()}}destroy(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.destroy&&"function"==typeof e.destroy&&e.destroy()}this.pluginInsMap={},this.plugins=[]}}const vt=class{constructor({emitter:t,config:e,sdk:n}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;this.boundSend=()=>{gt({event:"$PageView",properties:{}},t)},this.sdk&&!0===this.sdk._postConsentInit||setTimeout(()=>{this.boundSend()},0),t.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=t=>{t!==location.href&&this.boundSend()},this.emitter.on(y,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(y,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};vt.NAME="pageview";let At=vt;const yt=class{constructor({emitter:t,config:e,sdk:n}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this._skipFirstPageEnd=!1,this.emitter=t,this.config=e,this.sdk=n}__canCapture(){return!this.sdk||"function"!=typeof this.sdk.hasOptedOutCapturing||!this.sdk.hasOptedOutCapturing()}init(){this.pageId=Number(String(g()).slice(2,5)+String(g()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),this.sdk&&!0===this.sdk._postConsentInit&&(this._skipFirstPageEnd=!0),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(t){console.log(t)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title,this._skipFirstPageEnd=!1}pageEndHandler(){if(!0===this.pageHiddenStatus)return;if(!this.__canCapture())return;const t=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete t.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,gt({event:T,properties:t},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const t=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",t),this.eventListeners.push({target:window,event:"pageshow",handler:t})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(y,t=>{t!==location.href&&(this.url=t,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(t=>{if(`on${t}`in window){const e=()=>{if(this._skipFirstPageEnd)return this._skipFirstPageEnd=!1,void this.stopHeartBeatInterval();this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(t,e),this.eventListeners.push({target:window,event:t,handler:e})}})}addPageSwitchListener(){const t=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",t),this.eventListeners.push({target:document,event:"visibilitychange",handler:t})}addHeartBeatInterval(){I.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.sdk&&!0===this.sdk._postConsentInit&&!0===this._skipFirstPageEnd||(this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData())}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(t){if(!this.__canCapture())return;const e=this.getPageLeaveProperties();e.$time=Date.now(),"is_first_heartbeat"===t&&(e.$event_duration=3);const n={type:"track",event:T,properties:e,time:e.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,I.isSupport()&&I.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(t){I.isSupport()&&I.remove(t||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){if(this.__canCapture())for(let t=window.localStorage.length-1;t>=0;t--){const e=window.localStorage.key(t);if(e&&e!==`${this.storageName}-${this.pageId}`&&0===e.indexOf(`${this.storageName}-`)){const t=I.parse(e);i(t)&&Date.now()-t.time>t.heartbeat_interval_time+5e3&&(delete t.heartbeat_interval_time,t._flush_time=/* @__PURE__ */(new Date).getTime(),gt({event:T,properties:t?.properties},this.config),this.delHeartBeatData(e))}}}getPageLeaveProperties(){let t=(Date.now()-this.startTime)/1e3;(isNaN(t)||t<0||t>this.maxDuration)&&(t=0),t=Number(t.toFixed(3));const e={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:w(this.url)};return 0!==t&&(e.$event_duration=t),e}destroy(){this.eventListeners.forEach(({target:t,event:e,handler:n})=>{t.removeEventListener(e,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};yt.NAME="pageleave";let Rt=yt;const Tt=class{constructor({emitter:t,config:e,sdk:n}){this.eventSended=!1,this.emitter=t,this.config=e,this.sdk=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit)return;const t=()=>{let e=0;const n={};if(window.performance){e=function(){let t=0;if("function"==typeof performance.getEntriesByType){const e=performance.getEntriesByType("navigation");e.length>0&&(t=e[0].domContentLoadedEventEnd||0)}return t}();const t=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const t=performance.getEntries();let e=0;for(const n of t)"transferSize"in n&&(e+=n.transferSize);if("number"==typeof e&&e>=0&&e<10737418240)return Number((e/1024).toFixed(3))}}();t&&(n.$page_resource_size=t)}else console.warn("Performance API is not supported.");e>0&&!Number.isFinite(e)&&(n.$event_duration=Number((e/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,gt({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",t)};"complete"===document.readyState?t():window.addEventListener&&window.addEventListener("load",t)}};Tt.NAME="pageload";let bt=Tt;function Ct(t,e){if(!h(t))return!1;const n=o(t.tagName)?t.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=t.getAttribute("name")||"",i.$element_id=t.getAttribute("id")||"",i.$element_class_name=o(t.className)?t.className:"",i.$element_target_url=t.getAttribute("href")||"",i.$element_content=function(t,e){return o(e)&&"input"===e.toLowerCase()?("button"===(n=t).type||"submit"===n.type)&&n.value||"":function(t,e){let n="",i="";return t.textContent?n=S(t.textContent):t.innerText&&(n=S(t.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==e&&"INPUT"!==e||(i=t.value||""),i}(t,e);var n}(t,n)||"",i.$element_selector=Nt(t)||"",i.$element_path=function(t){let e=[];for(;t.parentNode&&h(t);){if(!o(t.tagName))return"";if(t.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.id)){e.unshift(t.tagName.toLowerCase()+"#"+t.id);break}if(t===document.body){e.unshift("body");break}e.unshift(t.tagName.toLowerCase()),t=t.parentNode}return e.join(" > ")}(t)||"";const s=function(t,e){const n=e.pageX||e.clientX+Pt().scrollLeft||e.offsetX+kt(t).targetEleX,i=e.pageY||e.clientY+Pt().scrollTop||e.offsetY+kt(t).targetEleY;return{$page_x:Lt(n),$page_y:Lt(i)}}(t,e);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function Nt(t,e=[]){if(!(t&&t.parentNode&&t.parentNode.children&&o(t.tagName)))return"";e=Array.isArray(e)?e:[];const n=t.nodeName.toLowerCase();return t&&"body"!==n&&1==t.nodeType?(e.unshift(function(t){if(!t||!h(t)||!o(t.tagName))return"";let e=t.parentNode&&9==t.parentNode.nodeType?-1:function(t){if(!t.parentNode)return-1;let e=0;const n=t.tagName,i=t.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(t===i[s])return e;e++}return-1}(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~e?":nth-of-type("+(e+1)+")":"")}(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?e.join(" > "):Nt(t.parentNode,e)):(e.unshift("body"),e.join(" > "))}function Pt(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function kt(t){if(document.documentElement.getBoundingClientRect){const e=t.getBoundingClientRect();return{targetEleX:e.left+Pt().scrollLeft||0,targetEleY:e.top+Pt().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Lt(t){return Number(Number(t).toFixed(3))}const Ft=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(t){const e=t.target;if(!e)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(e.tagName))return;if("true"===e.getAttribute("sensorswave-disable"))return;gt({event:"$WebClick",properties:Ct(e,t)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};Ft.NAME="webclick";let Bt=Ft;const Mt=class{constructor({emitter:t,config:e,sdk:n}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;if(t.enableAB){if(this.sdk&&"function"==typeof this.sdk.hasOptedOutCapturing&&this.sdk.hasOptedOutCapturing())return;this.fastFetch().then(()=>{this.emitter.emit(R)}),t.abRefreshInterval<3e4&&(t.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},t.abRefreshInterval)}}async fastFetch(){const t=C.getABData(this.config.abRefreshInterval);return t&&t.length?(this.emitter.emit(R),Promise.resolve(t)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(t=>{!function({opts:t,cb:e}){if(!nt())return void(e&&e({}));if(!it())return void(e&&e({}));const n=C.getLoginId(),i=C.getAnonId();if(!n&&!i)return void(e&&e({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...Q(),...dt(C.getCommonProps())}},sdk:"webjs",sdk_version:v};k({url:ut(t),method:"POST",data:s,headers:ct(t),callback:t=>{200!==t.statusCode?(console.error("Failed to fetch feature flags"),e&&e({})):e&&e(t.json)}})}({opts:this.config,cb:e=>{C.saveABData(e?.data?.results||[]),t(e),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(t){return await this.fastFetch().catch(console.warn),C.getABData(this.config.abRefreshInterval).find(e=>e.typ===b.FEATURE_GATE&&e.key==t)}async checkFeatureGate(t){const e=await this.getFeatureGate(t);return!!e&&(!e.hasOwnProperty("vid")&&e.key?(It({isUnset:!0,data:e,opts:this.config}),!1):(It({data:e,opts:this.config}),"fail"!==e.vid))}async getExperiment(t){await this.fastFetch().catch(console.warn);const e=C.getABData(this.config.abRefreshInterval).find(e=>e.typ===b.EXPERIMENT&&e.key===t);return e?!e.hasOwnProperty("vid")&&e.key?(It({isUnset:!0,data:e,opts:this.config}),{}):(It({data:e,opts:this.config}),e?.value||{}):{}}async getFeatureConfig(t){await this.fastFetch().catch(console.warn);const e=C.getABData(this.config.abRefreshInterval).find(e=>e.typ===b.FEATURE_CONFIG&&e.key===t);if(!e)return{};if(!e.hasOwnProperty("vid")&&e.key)return It({isUnset:!0,data:e,opts:this.config}),{};It({data:e,opts:this.config});const n=e?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Mt.NAME="abtest";let Dt=Mt;const $t=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],xt="sensorswave_utm",Ut=class t{constructor({sdk:t,emitter:e,config:n}){this.sdk=t,this.emitter=e,this.config=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit){let e=t.readFromSessionStorage();return e&&0!==Object.keys(e).length||(e=t.captureAndStore(this.config?.debug)),void this.scheduleInitialUTM(e)}const e=t.getUTMFromURL();t.saveToSessionStorage(e,this.config?.debug),this.scheduleInitialUTM(e)}scheduleInitialUTM(t){setTimeout(()=>{this.sendInitialUTM(t)},0)}static getUTMFromURL(){try{const t=new URLSearchParams(window.location.search),e={};return $t.forEach(n=>{const i=t.get(n);i&&(e[n]=i)}),e}catch(e){return t.getUTMFromURLFallback()}}static getUTMFromURLFallback(){const t={};return window.location.search.substring(1).split("&").forEach(e=>{const[n,i]=e.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";$t.includes(s)&&(t[s]=r)}),t}static readFromSessionStorage(){try{const t=sessionStorage.getItem(xt);if(!t)return{};const e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch(t){return{}}}static saveToSessionStorage(t,e=!1){try{sessionStorage.setItem(xt,JSON.stringify(t))}catch(n){e&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",n)}}static captureAndStore(e=!1){const n=t.getUTMFromURL();return t.saveToSessionStorage(n,e),n}sendInitialUTM(t){const e={};$t.forEach(n=>{e[`$initial_${n}`]=null!=t[n]?t[n]:""});try{this.sdk.profileSetOnce(e)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};Ut.NAME="UTM";let Ht=Ut;const Xt=[],qt={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1,optOutCapturing:!1,persistOptOut:!1},Wt=new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new t,this.pluginCore={},this.commonProps={},this.spaCleanup=null,this._optOutCapturing=!1,this.consentStorage=new wt(!1),this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance=this}init(t,e={}){return this.inited?this:(O.instance=this,e.sourceToken=t,this.mergeConfig(e),this.consentStorage=new wt(!0===this.config.persistOptOut),this._optOutCapturing?this.consentStorage.write(!0):!0===this.config.optOutCapturing?(this._optOutCapturing=!0,this.consentStorage.write(!0)):!0===this.consentStorage.read()&&(this._optOutCapturing=!0),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0,this._optOutCapturing?(Ht.captureAndStore(this.config.debug),this.eventEmitter.emit(A),this.inited=!0,this):(this.__setupAfterConsent(),this.eventEmitter.emit(A),this.inited=!0,this))}__setupAfterConsent(){if(this._setupAfterConsentDone)return;this._setupAfterConsentDone=!0;const t=this.config;Xt.length=0,C.init(t.crossSubdomainCookie),t.anonId&&C.setAnonId(t.anonId),function(){if(window._swFailedRequestsInitialized)return;window._swFailedRequestsInitialized=!0;const t=O.instance;t&&"function"==typeof t.hasOptedOutCapturing&&t.hasOptedOutCapturing()||t&&!0===t._postConsentInit||function(){const t=V.getAll();if(0!==t.length)for(let e=0,n=t.length;e<n;e+=10){const n=t.slice(e,e+10),i=[],s=[];n.forEach(t=>{Array.isArray(t.data)?i.push(...t.data):i.push(t.data),s.push(t.id)});const r=n[n.length-1],o=r.url,a=r.headers;k({url:o,method:"POST",data:i,headers:a,callback:t=>{200!==t.statusCode?console.error("Failed to send batch stored requests:",t):s.forEach(t=>{V.dequeue(t)})}})}}()}(),Xt.push(Ht),t.autoCapture&&this.autoTrack(),t.enableAB&&Xt.push(Dt),t.enableClickTrack&&Xt.push(Bt),this.pluginCore=new Ot({plugins:Xt,emitter:this.eventEmitter,config:t,sdk:this}),this.spaCleanup=function(t){let e=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){t(e),e=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),t(e),e=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),t(e),e=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(t=>{this.eventEmitter.emit(y,t)})}mergeConfig(t){this.config={...qt,...t}}__canCapture(){return this.inited&&!this._optOutCapturing}track(t){this.__canCapture()&&function(t,e){if(!nt())return;if(!it())return;const n={...t};n.time||(n.time=Date.now()),n.login_id||(n.login_id=C.getLoginId()),n.anon_id||(n.anon_id=C.getAnonId()),n.trace_id||(n.trace_id=C.getTraceId()),n.properties={...Q(),...dt(C.getCommonProps()),...n.properties};const i=at(e),s=ct(e),r=!1!==e.batchSend&&rt();if(!r)return ht(i,{data:[n],headers:s});V.enqueue(i,[n],s),r.add()}(t,this.config)}trackEvent(t,e){this.__canCapture()&>({event:t,properties:e},this.config)}autoTrack(){Xt.push(At,bt,Rt)}profileSet(t){this.__canCapture()&&ft({userProps:{$set:t},opts:this.config})}profileSetOnce(t){this.__canCapture()&&ft({userProps:{$set_once:t},opts:this.config})}profileIncrement(t){this.__canCapture()&&ft({userProps:{$increment:t},opts:this.config})}profileAppend(t){this.__canCapture()&&ft({userProps:{$append:t},opts:this.config})}profileUnion(t){this.__canCapture()&&ft({userProps:{$union:t},opts:this.config})}profileUnset(t){if(!this.__canCapture())return;const e={};r(t)?t.forEach(function(t){e[t]=null}):e[t]=null,ft({userProps:{$unset:e},opts:this.config})}profileDelete(){this.__canCapture()&&ft({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(t){if(!i(t))return console.warn("Commmon Properties must be an object!");this.commonProps=t,C.setCommonProps(this.commonProps)}clearCommonProperties(t){if(!r(t))return console.warn("Commmon Properties to be cleared must be an array!");t.forEach(t=>{delete this.commonProps[t]}),C.setCommonProps(this.commonProps)}identify(t){this.__canCapture()&&(C.setLoginId(t),function(t){if(!nt())return;if(!it())return;const e=C.getLoginId(),n=C.getAnonId();if(!e||!n)return;const i={time:Date.now(),trace_id:C.getTraceId(),event:"$Identify",login_id:e,anon_id:n,properties:pt()},s=at(t),r=ct(t),o=rt();if(!o)return ht(s,{data:[i],headers:r});V.enqueue(s,[i],r),o.add()}(this.config))}setLoginId(t){this.__canCapture()&&C.setLoginId(t)}getAnonId(){return this.__canCapture()?C.getAnonId():""}setAnonId(t){this.__canCapture()&&C.setAnonId(t)}getLoginId(){return this.__canCapture()?C.getLoginId():""}checkFeatureGate(t){if(!this.__canCapture())return Promise.resolve(!1);const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.checkFeatureGate(t):Promise.reject("AB is disabled")}getExperiment(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getExperiment(t):Promise.reject("AB is disabled")}getFeatureConfig(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getFeatureConfig(t):Promise.reject("AB is disabled")}optOutCapturing(){this._optOutCapturing=!0,this.consentStorage.write(!0),st&&st.pause()}optInCapturing(){if(this._optOutCapturing=!1,this.consentStorage.write(!1),st&&st.resume(),this.inited&&!this._setupAfterConsentDone){this._postConsentInit=!0;try{this.__setupAfterConsent(),this.eventEmitter.emit(A)}finally{this._postConsentInit=!1}}}hasOptedOutCapturing(){return this._optOutCapturing}destroy(){st&&(st.destroy(),st=null),"undefined"!=typeof window&&(window._swFailedRequestsInitialized=!1),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.pluginCore={},this.eventEmitter&&this.eventEmitter.removeAllListeners(),this.consentStorage=new wt(!0===this.config?.persistOptOut),this._optOutCapturing=!1,this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance===this&&(O.instance=null)}};export{Wt as default};
|
|
1
|
+
class t{constructor(){this.listeners={}}on(t,e,n=!1){if(t&&e){if(!s(e))throw new Error("listener must be a function");this.listeners[t]=this.listeners[t]||[],this.listeners[t].push({listener:e,once:n})}}off(t,e){const n=this.listeners[t];if(!n?.length)return;"number"==typeof e&&n.splice(e,1);const i=n.findIndex(t=>t.listener===e);-1!==i&&n.splice(i,1)}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((n,i)=>{n.listener.call(this,...e),n.listener.once&&this.off(t,i)})}once(t,e){this.on(t,e,!0)}removeAllListeners(t){t?this.listeners[t]=[]:this.listeners={}}}const e={get:function(t){const e=t+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let t=n[i];for(;" "==t.charAt(0);)t=t.substring(1,t.length);if(0==t.indexOf(e))return h(t.substring(e.length,t.length))}return null},set:function({name:t,value:e,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",c="",u="";if(0!==(n=null==n||void 0===n?365:n)){const t=/* @__PURE__ */new Date;"s"===String(n).slice(-1)?t.setTime(t.getTime()+1e3*Number(String(n).slice(0,-1))):t.setTime(t.getTime()+24*n*60*60*1e3),o="; expires="+t.toUTCString()}function l(t){return t?t.replace(/\r\n/g,""):""}i&&(c="; SameSite="+i),s&&(a="; secure");const h=l(t),d=l(e),p=l(r);p&&(u="; domain="+p),h&&d&&(document.cookie=h+"="+encodeURIComponent(d)+o+"; path=/"+u+c+a)},remove:function(t){this.set({name:t,value:"",expires:-1})},isSupport:function({samesite:t,secure:e}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:t,secure:e}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(t){return"[object Object]"===n.call(t)}function s(t){const e=n.call(t);return"[object Function]"==e||"[object AsyncFunction]"==e}function r(t){return"[object Array]"==n.call(t)}function o(t){return"[object String]"==n.call(t)}function a(t){return void 0===t}const c=Object.prototype.hasOwnProperty;function u(t){if(i(t)){for(let e in t)if(c.call(t,e))return!1;return!0}return!1}function l(t){return!(!t||1!==t.nodeType)}function h(t){let e=t;try{e=decodeURIComponent(t)}catch(n){e=t}return e}function d(t){try{return JSON.parse(t)}catch(e){return""}}const p=function(){let t=Date.now();return function(e){return Math.ceil((t=(9301*t+49297)%233280,t/233280*e))}}();function g(){if("function"==typeof Uint32Array){let t;if("undefined"!=typeof crypto&&(t=crypto),t&&i(t)&&t.getRandomValues)return t.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return p(1e19)/1e19}const f=/* @__PURE__ */function(){function t(t){return("0".repeat(t)+Date.now().toString(16)).slice(-t)}return function(){let e=String(screen.height*screen.width);e=e&&/\d{4,}/.test(e)?e.slice(-4):String(31242*g()).replace(".","").slice(0,4);return t(8)+"-"+g().toString(16).replace(".","").slice(-4)+"-"+function(){const t=navigator.userAgent;let e,n=[],i=0;function s(t,e){let i=0;for(let s=0;s<e.length;s++)i|=n[s]<<8*s;return(t^i)>>>0}for(let r=0;r<t.length;r++)e=t.charCodeAt(r),n.unshift(255&e),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+e+"-"+t(12)||(String(g())+String(g())+String(g())).slice(2,15)}}();function m(t,e){e&&"string"==typeof e||(e="");let n=null;try{n=new URL(t).hostname}catch(i){}return n||e}function E(t){let e=[];try{e=atob(t).split("").map(function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})}catch(n){e=[]}try{return decodeURIComponent(e.join(""))}catch(n){return e.join("")}}function _(t){let e="";try{e=btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}))}catch(n){e=t}return e}const I={get:function(t){return window.localStorage.getItem(t)},parse:function(t){let e;try{e=JSON.parse(I.get(t))||null}catch(n){console.warn(n)}return e},set:function(t,e){try{window.localStorage.setItem(t,e)}catch(n){console.warn(n)}},remove:function(t){window.localStorage.removeItem(t)},isSupport:function(){let t=!0;try{const e="__local_store_support__",n="testIsSupportStorage";I.set(e,n),I.get(e)!==n&&(t=!1),I.remove(e)}catch(e){t=!1}return t}};function S(t){return t.trim()}function w(t){if(!t||"string"!=typeof t)return"";try{return new URL(t,window.location.origin).pathname}catch(e){return""}}const O={},v="1.4.0",b="init-ready",y="spa-switch",A="ff-ready",R="$PageLeave",T="$Exception";var C=/* @__PURE__ */(t=>(t[t.FEATURE_GATE=1]="FEATURE_GATE",t[t.FEATURE_CONFIG=2]="FEATURE_CONFIG",t[t.EXPERIMENT=3]="EXPERIMENT",t))(C||{});const N={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(t){this.commonProps=t},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(t,e){this._state[t]=e,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let t=JSON.parse(JSON.stringify(this._state));t.identities&&(t.identities=_(JSON.stringify(t.identities)));const n=JSON.stringify(t);e.set({name:this.getCookieName(),value:n,expires:365})},init:function(t){let n,s;this.crossSubdomain=t,e.isSupport()&&(n=e.get(this.getCookieName()),s=d(n)),N._state={...s||{}},N._state.identities&&(N._state.identities=d(E(N._state.identities))),N._state.identities&&i(N._state.identities)&&!u(N._state.identities)||(N._state.identities={$identity_cookie_id:f()}),N.save()},setLoginId(t){"number"==typeof t&&(t=String(t)),void 0!==t&&t&&(N.set("login_id",t),N.save())},clearLoginId(){this._state.login_id="",this.save()},resetAnonId(){this._state.anon_id="",this._state.identities={$identity_cookie_id:f()},this.save()},setAnonId(t){"number"==typeof t&&(t=String(t)),"string"==typeof t&&t?(N.set("anon_id",t),N.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",t)},saveABData(t){if(!t||u(t))return;this._abData=t;let e=JSON.parse(JSON.stringify(this._abData));e=_(JSON.stringify(e));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:e,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(t=6e5){try{let e=localStorage.getItem(this.getABLSName());if(e){const{time:n,data:i,login_id:s,anon_id:r}=d(e)||{};if(n&&i&&Date.now()-n<t&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const t=d(E(i));return this._abData=Array.isArray(t)?t:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(e){this._abData=[]}return this._abData||[]}};function P(t){return!(t>=400&&t<500)||408===t||429===t}function k(t){var e;if(t.data)return{contentType:"application/json",body:(e=t.data,JSON.stringify(e,(t,e)=>"bigint"==typeof e?e.toString():e,undefined))}}const L=[];function $(t){const e={...t};e.timeout=e.timeout||6e4;const n=e.transport??"fetch",i=L.find(t=>t.transport===n)?.method??L[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(e)}function F(t){return o(t=t||document.referrer)&&(t=h(t=t.trim()))||""}function B(t){const e=m(t=t||F());if(!e)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let t=n[i];for(let n=0,s=t.length;n<s;n++)if(t[n].test(e))return i}return""}function x(t,e){return-1!==t.indexOf(e)}"function"==typeof fetch&&L.push({transport:"fetch",method:function(t){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const e=k(t),n=new Headers;t.headers&&Object.keys(t.headers).forEach(e=>{n.append(e,t.headers[e])}),e?.contentType&&n.append("Content-Type",e.contentType),fetch(t.url,{method:t.method||"GET",headers:n,body:e?.body}).then(e=>e.text().then(n=>{const i={statusCode:e.status,text:n};if(200===e.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}t.callback?.(i)})).catch(e=>{console.error("Request failed:",e),t.callback?.({statusCode:0,text:String(e)})})}}),"undefined"!=typeof XMLHttpRequest&&L.push({transport:"XHR",method:function(t){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const e=new XMLHttpRequest;e.open(t.method||"GET",t.url,!0);const n=k(t);t.headers&&Object.keys(t.headers).forEach(n=>{e.setRequestHeader(n,t.headers[n])}),n?.contentType&&e.setRequestHeader("Content-Type",n.contentType),e.timeout=t.timeout||6e4,e.withCredentials=!0,e.onreadystatechange=()=>{if(4===e.readyState){const i={statusCode:e.status,text:e.responseText};if(200===e.status)try{i.json=JSON.parse(e.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}t.callback?.(i)}},e.send(n?.body)}});const M={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},D="(\\d+(\\.\\d+)?)",H=new RegExp("Version/"+D),U=new RegExp(M.XBOX,"i"),X=new RegExp(M.PLAYSTATION+" \\w+","i"),j=new RegExp(M.NINTENDO+" \\w+","i"),q=new RegExp(M.BLACKBERRY+"|PlayBook|BB10","i"),W=new RegExp("(HUAWEI|honor|HONOR)","i"),G=new RegExp("(Xiaomi|Redmi)","i"),z=new RegExp("(OPPO|realme)","i"),Y=new RegExp("(vivo|IQOO)","i"),K={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function J(t,e){return e=e||"",x(t," OPR/")&&x(t,"Mini")?M.OPERA_MINI:x(t," OPR/")?M.OPERA:q.test(t)?M.BLACKBERRY:x(t,"IE"+M.MOBILE)||x(t,"WPDesktop")?M.INTERNET_EXPLORER_MOBILE:x(t,M.SAMSUNG_BROWSER)?M.SAMSUNG_INTERNET:x(t,M.EDGE)||x(t,"Edg/")?M.MICROSOFT_EDGE:x(t,"FBIOS")?M.FACEBOOK+" "+M.MOBILE:x(t,"UCWEB")||x(t,"UCBrowser")?M.UC_BROWSER:x(t,"CriOS")?M.CHROME_IOS:x(t,"CrMo")||x(t,M.CHROME)?M.CHROME:x(t,M.ANDROID)&&x(t,M.SAFARI)?M.ANDROID_MOBILE:x(t,"FxiOS")?M.FIREFOX_IOS:x(t.toLowerCase(),M.KONQUEROR.toLowerCase())?M.KONQUEROR:function(t,e){return e&&x(e,M.APPLE)||x(n=t,M.SAFARI)&&!x(n,M.CHROME)&&!x(n,M.ANDROID);var n}(t,e)?x(t,M.MOBILE)?M.MOBILE_SAFARI:M.SAFARI:x(t,M.FIREFOX)?M.FIREFOX:x(t,"MSIE")||x(t,"Trident/")?M.INTERNET_EXPLORER:x(t,"Gecko")?M.FIREFOX:""}const Z={[M.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+D)],[M.MICROSOFT_EDGE]:[new RegExp(M.EDGE+"?\\/"+D)],[M.CHROME]:[new RegExp("("+M.CHROME+"|CrMo)\\/"+D)],[M.CHROME_IOS]:[new RegExp("CriOS\\/"+D)],[M.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+D)],[M.SAFARI]:[H],[M.MOBILE_SAFARI]:[H],[M.OPERA]:[new RegExp("("+M.OPERA+"|OPR)\\/"+D)],[M.FIREFOX]:[new RegExp(M.FIREFOX+"\\/"+D)],[M.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+D)],[M.KONQUEROR]:[new RegExp("Konqueror[:/]?"+D,"i")],[M.BLACKBERRY]:[new RegExp(M.BLACKBERRY+" "+D),H],[M.ANDROID_MOBILE]:[new RegExp("android\\s"+D,"i")],[M.SAMSUNG_INTERNET]:[new RegExp(M.SAMSUNG_BROWSER+"\\/"+D)],[M.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+D)],Mozilla:[new RegExp("rv:"+D)]};function Q(t,e){const n=J(t,e),i=Z[n];if(a(i))return null;for(let s=0;s<i.length;s++){const e=i[s],n=t.match(e);if(n)return parseFloat(n[n.length-2])}return null}const V=[[new RegExp(M.XBOX+"; "+M.XBOX+" (.*?)[);]","i"),t=>[M.XBOX,t&&t[1]||""]],[new RegExp(M.NINTENDO,"i"),[M.NINTENDO,""]],[new RegExp(M.PLAYSTATION,"i"),[M.PLAYSTATION,""]],[q,[M.BLACKBERRY,""]],[new RegExp(M.WINDOWS,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[M.WINDOWS_PHONE,""];if(new RegExp(M.MOBILE).test(e)&&!/IEMobile\b/.test(e))return[M.WINDOWS+" "+M.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){const t=n[1];let i=K[t]||"";return/arm/i.test(e)&&(i="RT"),[M.WINDOWS,i]}return[M.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){const e=[t[3],t[4],t[5]||"0"];return[M.IOS,e.join(".")]}return[M.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=a(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+M.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+M.ANDROID+")","i"),t=>{if(t&&t[2]){const e=[t[2],t[3],t[4]||"0"];return[M.ANDROID,e.join(".")]}return[M.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{const e=["Mac OS X",""];if(t&&t[1]){const n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[M.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function tt(){const t=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,e=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(t){for(let e=0;e<V.length;e++){const[n,i]=V[e],s=n.exec(t),r=s&&("function"==typeof i?i(s,t):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:J(n),$browser_version:Q(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:t,$viewport_width:e,$lib:"webjs",$lib_version:v,$search_engine:B(),$referrer:F(),$referrer_host:m(r=r||F()),$title:document.title,$language:navigator.language,$model:(s=n,(j.test(s)?M.NINTENDO:X.test(s)?M.PLAYSTATION:U.test(s)?M.XBOX:new RegExp(M.OUYA,"i").test(s)?M.OUYA:new RegExp("("+M.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?M.WINDOWS_PHONE:/iPad/.test(s)?M.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?M.APPLE_WATCH:q.test(s)?M.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp(M.NOKIA,"i").test(s)?M.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":W.test(s)?M.HUAWEI:G.test(s)?M.XIAOMI:z.test(s)?M.OPPO:Y.test(s)?M.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp(M.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?M.ANDROID:M.ANDROID_TABLET:M.ANDROID:new RegExp("(pda|"+M.MOBILE+")","i").test(s)?M.GENERIC_MOBILE:new RegExp(M.TABLET,"i").test(s)&&!new RegExp(M.TABLET+" pc","i").test(s)?M.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-/* @__PURE__ */(new Date).getTimezoneOffset()};var s,r}const et=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const t=localStorage.getItem(this.STORAGE_KEY);t&&(this.queue=d(t)||[])}catch(t){console.warn("Failed to load queue from localStorage:",t),this.queue=[]}}cleanupExpiredItems(){const t=Date.now(),e=this.queue.filter(e=>t-e.timestamp<this.MAX_AGE_MS);e.length!==this.queue.length&&(this.queue=e,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(t){console.warn("Failed to save queue to localStorage:",t)}}enqueue(t,e,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:t,data:e,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(t){try{this.queue=this.queue.filter(e=>e.id!==t),this.saveToStorage()}catch(e){console.warn("Failed to dequeue request:",e)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(t){return console.warn("Failed to get queue items:",t),[]}}incrementRetryCount(t){const e=this.queue.find(e=>e.id===t);return!(!e||e.retryCount>=e.maxRetries||(e.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(t){console.warn("Failed to clear queue from localStorage:",t)}}getItemById(t){return this.queue.find(e=>e.id===t)}};class nt{constructor(t={}){this.flushTimer=null,this.isFlushing=!1,this.paused=!1,this.destroyed=!1,this.config={maxBatchSize:t.maxBatchSize||20,flushInterval:t.flushInterval||5e3},this.startFlushTimer()}pause(){this.paused=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}resume(){this.paused&&(this.paused=!1,this.startFlushTimer())}isPaused(){return this.paused}add(){et.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.paused||this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const t=et.getAll();if(0===t.length)return this.isFlushing=!1,void this.startFlushTimer();const e=t.slice(0,this.config.maxBatchSize),n=[],i=[];e.forEach(t=>{Array.isArray(t.data)?n.push(...t.data):n.push(t.data),i.push(t.id)});const s=e[e.length-1],r=s.url,o=s.headers;O.instance&&O.instance.config.debug&&console.log(JSON.stringify(n,null,2)),$({url:r,method:"POST",data:n,headers:o,callback:t=>{200===t.statusCode?i.forEach(t=>{et.dequeue(t)}):P(t.statusCode)?console.error("Failed to send batch events:",t):i.forEach(t=>{et.dequeue(t)}),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.destroyed||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{et.getAll().length>0&&this.triggerFlush()},this.config.flushInterval))}destroy(){this.destroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.paused||this.flush()}}let it=null;function st(){const t=O.instance;return!(!t||!t.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}function rt(){const t=O.instance;return!t||"function"!=typeof t.hasOptedOutCapturing||!t.hasOptedOutCapturing()}let ot=null;function at(){return I.isSupport()?(ot||(it||(it=new nt({maxBatchSize:20,flushInterval:5e3})),ot=it),ot):null}function ct(t,e,n){if(rt())return $({url:t,method:"POST",data:e.data,headers:e.headers,callback:t=>{if(200!==t.statusCode){if(!P(t.statusCode))return void(n&&et.dequeue(n));if(n&&et.incrementRetryCount(n)){const t=et.getItemById(n);if(t){const e=Math.min(1e3*Math.pow(2,t.retryCount),3e4);setTimeout(()=>{ct(t.url,{data:t.data,headers:t.headers},t.id)},e)}}}else n&&et.dequeue(n),e.callback&&e.callback(t.json)}})}function ut(t){return`${t.apiHost}/in/track`}function lt(t){return`${t.apiHost}/ab/evalall`}function ht(t){return{"Content-Type":"application/json",SourceToken:t.sourceToken}}function dt(t,e,n){O.instance&&O.instance.config.debug&&console.log(JSON.stringify(e.data,null,2));const i=et.enqueue(t,e.data,e.headers);return ct(t,{...e,callback:void 0},i)}function pt(){try{const t=sessionStorage.getItem("sensorswave_utm");if(!t)return{};const e=JSON.parse(t),n={};return Object.entries(e).forEach(([t,e])=>{null!=e&&""!==e&&(n[`$${t}`]=e)}),n}catch(t){return{}}}function gt(t){const e={};return Object.entries(t).forEach(([t,n])=>{if("function"==typeof n)try{const i=n();e[t]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",t,i)}else e[t]=n}),e}function ft(t={},e=!0){const n={...e?tt():{},...gt(N.getCommonProps()),...t},i=pt();return Object.keys(i).length>0&&Object.assign(n,i),n}function mt(t,e,n=!0){if(!st())return;if(!rt())return;const i={time:Date.now(),trace_id:N.getTraceId(),event:t.event,properties:ft(t.properties,n)},s=pt();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),t.user_properties&&(t.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...t.user_properties.$set},delete t.user_properties.$set),i.user_properties={...i.user_properties,...t.user_properties});const r=N.getLoginId(),o=N.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=ut(e),c=ht(e),u=!1!==e.batchSend&&at();u?(et.enqueue(a,[i],c),u.add()):dt(a,{data:[i],headers:c})}function Et({userProps:t,opts:e}){if(!st())return;if(!rt())return;const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:N.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:t,properties:ft()},r=ut(e),o=ht(e),a=at();if(!a)return dt(r,{data:[s],headers:o});et.enqueue(r,[s],o),a.add()}function _t(t){return t.typ===C.FEATURE_GATE||t.typ===C.FEATURE_CONFIG?`$feature_${t.id}`:t.typ===C.EXPERIMENT?`$exp_${t.id}`:""}function It(t){const e=t.typ;return[C.FEATURE_GATE,C.EXPERIMENT,C.FEATURE_CONFIG].includes(e)?{[_t(t)]:t.vid}:{}}function St(t){const e=t.typ;return e===C.FEATURE_GATE||e===C.FEATURE_CONFIG?{$feature_key:t.key,$feature_variant:t.vid}:e===C.EXPERIMENT?{$exp_key:t.key,$exp_variant:t.vid}:{}}function wt({isUnset:t=!1,data:e,opts:n}){if(!st())return;if(!rt())return;if(!e||u(e)||e.disable_impress)return;const i=N.getLoginId(),s=N.getAnonId();if(!i&&!s)return;const r=e.typ===C.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=t?{$unset:{[_t(e)]:null}}:{$set:{...It(e)}},mt({event:r,properties:St(e),user_properties:o},n)}const Ot="sensorswave_opt_out";class vt{constructor(t){this.persist=t}read(){if(this.persist)try{const t=I.get(Ot);return"0"===t||"1"!==t&&void 0}catch{return}}write(t){if(this.persist)try{I.set(Ot,t?"0":"1")}catch{}}}class bt{constructor({plugins:t,emitter:e,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=e,this.config=n,this.sdk=i,this.registerBuiltInPlugins(t),this.created(),this.emitter.on(b,()=>{this.init()})}registerBuiltInPlugins(t){for(let e=0,n=t.length;e<n;e++)this.registerPlugin(t[e])}registerPlugin(t){this.plugins.push(t)}getPlugins(){return this.plugins}getPlugin(t){return this.pluginInsMap[t]}created(){for(let t=0,e=this.plugins.length;t<e;t++){const e=this.plugins[t];if(!e.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new e({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[e.NAME]=n}}init(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.init&&e.init()}}destroy(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.destroy&&"function"==typeof e.destroy&&e.destroy()}this.pluginInsMap={},this.plugins=[]}}const yt=class{constructor({emitter:t,config:e,sdk:n}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;this.boundSend=()=>{mt({event:"$PageView",properties:{}},t)},this.sdk&&!0===this.sdk._postConsentInit||setTimeout(()=>{this.boundSend()},0),t.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=t=>{t!==location.href&&this.boundSend()},this.emitter.on(y,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(y,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};yt.NAME="pageview";let At=yt;const Rt=class{constructor({emitter:t,config:e,sdk:n}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this._skipFirstPageEnd=!1,this.emitter=t,this.config=e,this.sdk=n}__canCapture(){return!this.sdk||"function"!=typeof this.sdk.hasOptedOutCapturing||!this.sdk.hasOptedOutCapturing()}init(){this.pageId=Number(String(g()).slice(2,5)+String(g()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),this.sdk&&!0===this.sdk._postConsentInit&&(this._skipFirstPageEnd=!0),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(t){console.log(t)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title,this._skipFirstPageEnd=!1}pageEndHandler(){if(!0===this.pageHiddenStatus)return;if(!this.__canCapture())return;const t=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete t.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,mt({event:R,properties:t},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const t=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",t),this.eventListeners.push({target:window,event:"pageshow",handler:t})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(y,t=>{t!==location.href&&(this.url=t,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(t=>{if(`on${t}`in window){const e=()=>{if(this._skipFirstPageEnd)return this._skipFirstPageEnd=!1,void this.stopHeartBeatInterval();this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(t,e),this.eventListeners.push({target:window,event:t,handler:e})}})}addPageSwitchListener(){const t=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",t),this.eventListeners.push({target:document,event:"visibilitychange",handler:t})}addHeartBeatInterval(){I.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.sdk&&!0===this.sdk._postConsentInit&&!0===this._skipFirstPageEnd||(this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData())}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(t){if(!this.__canCapture())return;const e=this.getPageLeaveProperties();e.$time=Date.now(),"is_first_heartbeat"===t&&(e.$event_duration=3);const n={type:"track",event:R,properties:e,time:e.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,I.isSupport()&&I.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(t){I.isSupport()&&I.remove(t||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){if(this.__canCapture())for(let t=window.localStorage.length-1;t>=0;t--){const e=window.localStorage.key(t);if(e&&e!==`${this.storageName}-${this.pageId}`&&0===e.indexOf(`${this.storageName}-`)){const t=I.parse(e);i(t)&&Date.now()-t.time>t.heartbeat_interval_time+5e3&&(delete t.heartbeat_interval_time,t._flush_time=/* @__PURE__ */(new Date).getTime(),mt({event:R,properties:t?.properties},this.config),this.delHeartBeatData(e))}}}getPageLeaveProperties(){let t=(Date.now()-this.startTime)/1e3;(isNaN(t)||t<0||t>this.maxDuration)&&(t=0),t=Number(t.toFixed(3));const e={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:w(this.url)};return 0!==t&&(e.$event_duration=t),e}destroy(){this.eventListeners.forEach(({target:t,event:e,handler:n})=>{t.removeEventListener(e,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};Rt.NAME="pageleave";let Tt=Rt;const Ct=class{constructor({emitter:t,config:e,sdk:n}){this.eventSended=!1,this.emitter=t,this.config=e,this.sdk=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit)return;const t=()=>{let e=0;const n={};if(window.performance){e=function(){let t=0;if("function"==typeof performance.getEntriesByType){const e=performance.getEntriesByType("navigation");e.length>0&&(t=e[0].domContentLoadedEventEnd||0)}return t}();const t=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const t=performance.getEntries();let e=0;for(const n of t)"transferSize"in n&&(e+=n.transferSize);if("number"==typeof e&&e>=0&&e<10737418240)return Number((e/1024).toFixed(3))}}();t&&(n.$page_resource_size=t)}else console.warn("Performance API is not supported.");e>0&&!Number.isFinite(e)&&(n.$event_duration=Number((e/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,mt({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",t)};"complete"===document.readyState?t():window.addEventListener&&window.addEventListener("load",t)}};Ct.NAME="pageload";let Nt=Ct;function Pt(t,e){if(!l(t))return!1;const n=o(t.tagName)?t.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=t.getAttribute("name")||"",i.$element_id=t.getAttribute("id")||"",i.$element_class_name=o(t.className)?t.className:"",i.$element_target_url=t.getAttribute("href")||"",i.$element_content=function(t,e){return o(e)&&"input"===e.toLowerCase()?("button"===(n=t).type||"submit"===n.type)&&n.value||"":function(t,e){let n="",i="";return t.textContent?n=S(t.textContent):t.innerText&&(n=S(t.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==e&&"INPUT"!==e||(i=t.value||""),i}(t,e);var n}(t,n)||"",i.$element_selector=kt(t)||"",i.$element_path=function(t){let e=[];for(;t.parentNode&&l(t);){if(!o(t.tagName))return"";if(t.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.id)){e.unshift(t.tagName.toLowerCase()+"#"+t.id);break}if(t===document.body){e.unshift("body");break}e.unshift(t.tagName.toLowerCase()),t=t.parentNode}return e.join(" > ")}(t)||"";const s=function(t,e){const n=e.pageX||e.clientX+Lt().scrollLeft||e.offsetX+$t(t).targetEleX,i=e.pageY||e.clientY+Lt().scrollTop||e.offsetY+$t(t).targetEleY;return{$page_x:Ft(n),$page_y:Ft(i)}}(t,e);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function kt(t,e=[]){if(!(t&&t.parentNode&&t.parentNode.children&&o(t.tagName)))return"";e=Array.isArray(e)?e:[];const n=t.nodeName.toLowerCase();return t&&"body"!==n&&1==t.nodeType?(e.unshift(function(t){if(!t||!l(t)||!o(t.tagName))return"";let e=t.parentNode&&9==t.parentNode.nodeType?-1:function(t){if(!t.parentNode)return-1;let e=0;const n=t.tagName,i=t.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(t===i[s])return e;e++}return-1}(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~e?":nth-of-type("+(e+1)+")":"")}(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?e.join(" > "):kt(t.parentNode,e)):(e.unshift("body"),e.join(" > "))}function Lt(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function $t(t){if(document.documentElement.getBoundingClientRect){const e=t.getBoundingClientRect();return{targetEleX:e.left+Lt().scrollLeft||0,targetEleY:e.top+Lt().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Ft(t){return Number(Number(t).toFixed(3))}const Bt=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(t){const e=t.target;if(!e)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(e.tagName))return;if("true"===e.getAttribute("sensorswave-disable"))return;mt({event:"$WebClick",properties:Pt(e,t)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};Bt.NAME="webclick";let xt=Bt;const Mt=class{constructor({emitter:t,config:e,sdk:n}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;if(t.enableAB){if(this.sdk&&"function"==typeof this.sdk.hasOptedOutCapturing&&this.sdk.hasOptedOutCapturing())return;this.fastFetch().then(()=>{this.emitter.emit(A)}),t.abRefreshInterval<3e4&&(t.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},t.abRefreshInterval)}}async fastFetch(){const t=N.getABData(this.config.abRefreshInterval);return t&&t.length?(this.emitter.emit(A),Promise.resolve(t)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(t=>{!function({opts:t,cb:e}){if(!st())return void(e&&e({}));if(!rt())return void(e&&e({}));const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return void(e&&e({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...tt(),...gt(N.getCommonProps())}},sdk:"webjs",sdk_version:v};$({url:lt(t),method:"POST",data:s,headers:ht(t),callback:t=>{200!==t.statusCode?(console.error("Failed to fetch feature flags"),e&&e({})):e&&e(t.json)}})}({opts:this.config,cb:e=>{N.saveABData(e?.data?.results||[]),t(e),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(t){return await this.fastFetch().catch(console.warn),N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_GATE&&e.key==t)}async checkFeatureGate(t){const e=await this.getFeatureGate(t);return!!e&&(!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),!1):(wt({data:e,opts:this.config}),"fail"!==e.vid))}async getExperiment(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.EXPERIMENT&&e.key===t);return e?!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),{}):(wt({data:e,opts:this.config}),e?.value||{}):{}}async getFeatureConfig(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_CONFIG&&e.key===t);if(!e)return{};if(!e.hasOwnProperty("vid")&&e.key)return wt({isUnset:!0,data:e,opts:this.config}),{};wt({data:e,opts:this.config});const n=e?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Mt.NAME="abtest";let Dt=Mt;const Ht=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],Ut="sensorswave_utm",Xt=class t{constructor({sdk:t,emitter:e,config:n}){this.sdk=t,this.emitter=e,this.config=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit){let e=t.readFromSessionStorage();return e&&0!==Object.keys(e).length||(e=t.captureAndStore(this.config?.debug)),void this.scheduleInitialUTM(e)}const e=t.getUTMFromURL();t.saveToSessionStorage(e,this.config?.debug),this.scheduleInitialUTM(e)}scheduleInitialUTM(t){setTimeout(()=>{this.sendInitialUTM(t)},0)}static getUTMFromURL(){try{const t=new URLSearchParams(window.location.search),e={};return Ht.forEach(n=>{const i=t.get(n);i&&(e[n]=i)}),e}catch(e){return t.getUTMFromURLFallback()}}static getUTMFromURLFallback(){const t={};return window.location.search.substring(1).split("&").forEach(e=>{const[n,i]=e.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";Ht.includes(s)&&(t[s]=r)}),t}static readFromSessionStorage(){try{const t=sessionStorage.getItem(Ut);if(!t)return{};const e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch(t){return{}}}static saveToSessionStorage(t,e=!1){try{sessionStorage.setItem(Ut,JSON.stringify(t))}catch(n){e&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",n)}}static captureAndStore(e=!1){const n=t.getUTMFromURL();return t.saveToSessionStorage(n,e),n}sendInitialUTM(t){const e={};Ht.forEach(n=>{e[`$initial_${n}`]=null!=t[n]?t[n]:""});try{this.sdk.profileSetOnce(e)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};Xt.NAME="UTM";let jt=Xt;const qt=1e3,Wt=/^\s*(?:async\s+)?at\s+(?:(.+)\s+\()?(.+?):(\d+):(\d+)\)?$/,Gt=/^(?:(.*)@)?(.+?):(\d+):(\d+)$/;function zt(t){let e=t;try{const t=location.origin;t&&0===e.indexOf(t)&&(e=e.substring(t.length))}catch(s){}const n=e.indexOf("?");n>-1&&(e=e.substring(0,n));const i=e.indexOf("#");return i>-1&&(e=e.substring(0,i)),e}function Yt(t){return t.map(t=>({platform:"web:javascript",filename:zt(t.file),function:t.fn||"?",lineno:Number(t.line),colno:Number(t.col),abs_path:Kt(t.file,1e3)}))}function Kt(t,e){return t.length>e?t.substring(0,e):t}function Jt(t){let e;if("string"==typeof t)e=t;else if(null!==t&&"object"==typeof t){try{e=JSON.stringify(t)}catch(n){e=Object.prototype.toString.call(t)}e||(e=Object.prototype.toString.call(t))}else e=String(t);return Kt(e,qt)}function Zt(t){const{frames:e,headerType:n}=function(t){const e=[];let n="";if(!t||"string"!=typeof t)return{frames:e,headerType:n};const i=t.split(/\r?\n/);for(let s=0;s<i.length;s++){const t=i[s];if(!t||t.length>1024)continue;const r=t.match(Wt),o=r?null:t.match(Gt),a=r||o;if(a)e.push({fn:a[1]||"?",file:a[2],line:a[3],col:a[4]});else if(0===s){const e=t.indexOf(":");e>0&&(n=t.substring(0,e).trim())}if(e.length>=30)break}return{frames:e,headerType:n}}(t&&t.stack);let i=t&&t.name||n||"Error";return i=Kt(String(i),200),{$exception_level:"error",$exception_type:i,$exception_message:Kt(String(t&&t.message||""),qt),$exception_frames:Yt(e)}}function Qt(t,e,n,i){let s=[];return e&&(s=[{platform:"web:javascript",filename:zt(e),function:"?",lineno:n||0,colno:i||0,abs_path:Kt(e,1e3)}]),{$exception_level:"error",$exception_type:"Error",$exception_message:Kt(String(t||""),qt),$exception_frames:s}}class Vt{constructor(t=10,e=1,n=1e4){this.buckets=/* @__PURE__ */new Map,this.bucketSize=t,this.refillRate=e,this.refillInterval=n}allow(t){const e=Date.now();let n=this.buckets.get(t);if(n){if(e>n.lastRefill){const t=Math.floor((e-n.lastRefill)/this.refillInterval)*this.refillRate;t>0&&(n.tokens=Math.min(this.bucketSize,n.tokens+t),n.lastRefill+=t/this.refillRate*this.refillInterval)}}else n={tokens:this.bucketSize,lastRefill:e},this.buckets.set(t,n);return n.tokens>=1&&(n.tokens-=1,!0)}reset(){this.buckets.clear()}}const te=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleError=null,this.boundHandleRejection=null,this.rateLimiter=new Vt,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleError=this.handleError.bind(this),this.boundHandleRejection=this.handleRejection.bind(this),window.addEventListener("error",this.boundHandleError,!0),window.addEventListener("unhandledrejection",this.boundHandleRejection),this.isInitialized=!0)}handleError(t){try{const e=t.target;let n;if(e&&e!==window&&e.tagName)n=function(t){const e=t,n=(e.tagName||"").toLowerCase(),i=Kt(String(e.src||e.href||""),qt);return{$exception_level:"error",$exception_type:"ResourceLoadError",$exception_message:`Failed to load <${n}>${i?` from ${i}`:""}`,$exception_frames:[]}}(e);else{const e=t;n=e.error instanceof Error?Zt(e.error):Qt(String(e.message||""),e.filename,e.lineno,e.colno)}this.send(n)}catch(e){}}handleRejection(t){try{const e=t.reason;this.send(function(t){return t instanceof Error?Zt(t):{$exception_level:"error",$exception_type:"UnhandledRejection",$exception_message:Jt(t),$exception_frames:[]}}(e))}catch(e){}}send(t){t.$exception_message&&this.rateLimiter.allow(t.$exception_type)&&mt({event:T,properties:t},this.config)}destroy(){this.boundHandleError&&(window.removeEventListener("error",this.boundHandleError,!0),this.boundHandleError=null),this.boundHandleRejection&&(window.removeEventListener("unhandledrejection",this.boundHandleRejection),this.boundHandleRejection=null),this.rateLimiter.reset(),this.isInitialized=!1}};te.NAME="exception";let ee=te;const ne=[],ie={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1,enableErrorTrack:!1,enableCrashTrack:!1,optOutCapturing:!1,persistOptOut:!1},se=new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new t,this.pluginCore={},this.commonProps={},this.spaCleanup=null,this._optOutCapturing=!1,this.consentStorage=new vt(!1),this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance=this}init(t,e={}){return this.inited?this:(O.instance=this,e.sourceToken=t,this.mergeConfig(e),this.consentStorage=new vt(!0===this.config.persistOptOut),this._optOutCapturing?this.consentStorage.write(!0):!0===this.config.optOutCapturing?(this._optOutCapturing=!0,this.consentStorage.write(!0)):!0===this.consentStorage.read()&&(this._optOutCapturing=!0),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0,this._optOutCapturing?(jt.captureAndStore(this.config.debug),this.eventEmitter.emit(b),this.inited=!0,this):(this.__setupAfterConsent(),this.eventEmitter.emit(b),this.inited=!0,this))}__setupAfterConsent(){if(this._setupAfterConsentDone)return;this._setupAfterConsentDone=!0;const t=this.config;ne.length=0,N.init(t.crossSubdomainCookie),t.anonId&&N.setAnonId(t.anonId),function(){if(window._swFailedRequestsInitialized)return;window._swFailedRequestsInitialized=!0;const t=O.instance;t&&"function"==typeof t.hasOptedOutCapturing&&t.hasOptedOutCapturing()||t&&!0===t._postConsentInit||function(){const t=et.getAll();if(0!==t.length)for(let e=0,n=t.length;e<n;e+=10){const n=t.slice(e,e+10),i=[],s=[];n.forEach(t=>{Array.isArray(t.data)?i.push(...t.data):i.push(t.data),s.push(t.id)});const r=n[n.length-1],o=r.url,a=r.headers;$({url:o,method:"POST",data:i,headers:a,callback:t=>{200!==t.statusCode?(console.error("Failed to send batch stored requests:",t),P(t.statusCode)||s.forEach(t=>{et.dequeue(t)})):s.forEach(t=>{et.dequeue(t)})}})}}()}(),ne.push(jt),t.autoCapture&&this.autoTrack(),t.enableAB&&ne.push(Dt),t.enableClickTrack&&ne.push(xt),t.enableCrashTrack&&t.debug&&console.warn("[SensorsWave] enableCrashTrack 仅在 app 宿主环境生效,当前 Web 环境不采集 crash"),t.enableErrorTrack&&ne.push(ee),this.pluginCore=new bt({plugins:ne,emitter:this.eventEmitter,config:t,sdk:this}),this.spaCleanup=function(t){let e=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){t(e),e=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),t(e),e=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),t(e),e=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(t=>{this.eventEmitter.emit(y,t)})}mergeConfig(t){this.config={...ie,...t}}__canCapture(){return this.inited&&!this._optOutCapturing}track(t){this.__canCapture()&&function(t,e){if(!st())return;if(!rt())return;const n={...t};n.time||(n.time=Date.now()),n.login_id||(n.login_id=N.getLoginId()),n.anon_id||(n.anon_id=N.getAnonId()),n.trace_id||(n.trace_id=N.getTraceId()),n.properties={...tt(),...gt(N.getCommonProps()),...n.properties};const i=ut(e),s=ht(e),r=!1!==e.batchSend&&at();if(!r)return dt(i,{data:[n],headers:s});et.enqueue(i,[n],s),r.add()}(t,this.config)}trackEvent(t,e){this.__canCapture()&&mt({event:t,properties:e},this.config)}trackException(t,e){if(!this.__canCapture())return;const n={...e||{},...t instanceof Error?Zt(t):Qt(String(t))};mt({event:T,properties:n},this.config)}autoTrack(){ne.push(At,Nt,Tt)}profileSet(t){this.__canCapture()&&Et({userProps:{$set:t},opts:this.config})}profileSetOnce(t){this.__canCapture()&&Et({userProps:{$set_once:t},opts:this.config})}profileIncrement(t){this.__canCapture()&&Et({userProps:{$increment:t},opts:this.config})}profileAppend(t){this.__canCapture()&&Et({userProps:{$append:t},opts:this.config})}profileUnion(t){this.__canCapture()&&Et({userProps:{$union:t},opts:this.config})}profileUnset(t){if(!this.__canCapture())return;const e={};r(t)?t.forEach(function(t){e[t]=null}):e[t]=null,Et({userProps:{$unset:e},opts:this.config})}profileDelete(){this.__canCapture()&&Et({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(t){if(!i(t))return console.warn("Commmon Properties must be an object!");this.commonProps=t,N.setCommonProps(this.commonProps)}clearCommonProperties(t){if(!r(t))return console.warn("Commmon Properties to be cleared must be an array!");t.forEach(t=>{delete this.commonProps[t]}),N.setCommonProps(this.commonProps)}identify(t){this.__canCapture()&&(N.setLoginId(t),function(t){if(!st())return;if(!rt())return;const e=N.getLoginId(),n=N.getAnonId();if(!e||!n)return;const i={time:Date.now(),trace_id:N.getTraceId(),event:"$Identify",login_id:e,anon_id:n,properties:ft()},s=ut(t),r=ht(t),o=at();if(!o)return dt(s,{data:[i],headers:r});et.enqueue(s,[i],r),o.add()}(this.config))}setLoginId(t){this.__canCapture()&&N.setLoginId(t)}getAnonId(){return this.__canCapture()?N.getAnonId():""}setAnonId(t){this.__canCapture()&&N.setAnonId(t)}getLoginId(){return this.__canCapture()?N.getLoginId():""}reset(t=!1){this.__canCapture()&&(N.clearLoginId(),t&&N.resetAnonId())}checkFeatureGate(t){if(!this.__canCapture())return Promise.resolve(!1);const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.checkFeatureGate(t):Promise.reject("AB is disabled")}getExperiment(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getExperiment(t):Promise.reject("AB is disabled")}getFeatureConfig(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getFeatureConfig(t):Promise.reject("AB is disabled")}optOutCapturing(){this._optOutCapturing=!0,this.consentStorage.write(!0),ot&&ot.pause()}optInCapturing(){if(this._optOutCapturing=!1,this.consentStorage.write(!1),ot&&ot.resume(),this.inited&&!this._setupAfterConsentDone){this._postConsentInit=!0;try{this.__setupAfterConsent(),this.eventEmitter.emit(b)}finally{this._postConsentInit=!1}}}hasOptedOutCapturing(){return this._optOutCapturing}destroy(){ot&&(ot.destroy(),ot=null),"undefined"!=typeof window&&(window._swFailedRequestsInitialized=!1),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.pluginCore={},this.eventEmitter&&this.eventEmitter.removeAllListeners(),this.consentStorage=new vt(!0===this.config?.persistOptOut),this._optOutCapturing=!1,this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance===this&&(O.instance=null)}};export{se as default};
|
package/dist/index.umd.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).SensorsWave=e()}(this,function(){"use strict";class t{constructor(){this.listeners={}}on(t,e,n=!1){if(t&&e){if(!s(e))throw new Error("listener must be a function");this.listeners[t]=this.listeners[t]||[],this.listeners[t].push({listener:e,once:n})}}off(t,e){const n=this.listeners[t];if(!n?.length)return;"number"==typeof e&&n.splice(e,1);const i=n.findIndex(t=>t.listener===e);-1!==i&&n.splice(i,1)}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((n,i)=>{n.listener.call(this,...e),n.listener.once&&this.off(t,i)})}once(t,e){this.on(t,e,!0)}removeAllListeners(t){t?this.listeners[t]=[]:this.listeners={}}}const e={get:function(t){const e=t+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let t=n[i];for(;" "==t.charAt(0);)t=t.substring(1,t.length);if(0==t.indexOf(e))return l(t.substring(e.length,t.length))}return null},set:function({name:t,value:e,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",u="",c="";if(0!==(n=null==n||void 0===n?365:n)){const t=new Date;"s"===String(n).slice(-1)?t.setTime(t.getTime()+1e3*Number(String(n).slice(0,-1))):t.setTime(t.getTime()+24*n*60*60*1e3),o="; expires="+t.toUTCString()}function h(t){return t?t.replace(/\r\n/g,""):""}i&&(u="; SameSite="+i),s&&(a="; secure");const l=h(t),d=h(e),p=h(r);p&&(c="; domain="+p),l&&d&&(document.cookie=l+"="+encodeURIComponent(d)+o+"; path=/"+c+u+a)},remove:function(t){this.set({name:t,value:"",expires:-1})},isSupport:function({samesite:t,secure:e}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:t,secure:e}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(t){return"[object Object]"===n.call(t)}function s(t){const e=n.call(t);return"[object Function]"==e||"[object AsyncFunction]"==e}function r(t){return"[object Array]"==n.call(t)}function o(t){return"[object String]"==n.call(t)}function a(t){return void 0===t}const u=Object.prototype.hasOwnProperty;function c(t){if(i(t)){for(let e in t)if(u.call(t,e))return!1;return!0}return!1}function h(t){return!(!t||1!==t.nodeType)}function l(t){let e=t;try{e=decodeURIComponent(t)}catch(n){e=t}return e}function d(t){try{return JSON.parse(t)}catch(e){return""}}const p=function(){let t=Date.now();return function(e){return Math.ceil((t=(9301*t+49297)%233280,t/233280*e))}}();function g(){if("function"==typeof Uint32Array){let t;if("undefined"!=typeof crypto&&(t=crypto),t&&i(t)&&t.getRandomValues)return t.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return p(1e19)/1e19}const f=function(){function t(t){return("0".repeat(t)+Date.now().toString(16)).slice(-t)}return function(){let e=String(screen.height*screen.width);e=e&&/\d{4,}/.test(e)?e.slice(-4):String(31242*g()).replace(".","").slice(0,4);return t(8)+"-"+g().toString(16).replace(".","").slice(-4)+"-"+function(){const t=navigator.userAgent;let e,n=[],i=0;function s(t,e){let i=0;for(let s=0;s<e.length;s++)i|=n[s]<<8*s;return(t^i)>>>0}for(let r=0;r<t.length;r++)e=t.charCodeAt(r),n.unshift(255&e),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+e+"-"+t(12)||(String(g())+String(g())+String(g())).slice(2,15)}}();function m(t,e){e&&"string"==typeof e||(e="");let n=null;try{n=new URL(t).hostname}catch(i){}return n||e}function E(t){let e=[];try{e=atob(t).split("").map(function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})}catch(n){e=[]}try{return decodeURIComponent(e.join(""))}catch(n){return e.join("")}}function _(t){let e="";try{e=btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}))}catch(n){e=t}return e}const I={get:function(t){return window.localStorage.getItem(t)},parse:function(t){let e;try{e=JSON.parse(I.get(t))||null}catch(n){console.warn(n)}return e},set:function(t,e){try{window.localStorage.setItem(t,e)}catch(n){console.warn(n)}},remove:function(t){window.localStorage.removeItem(t)},isSupport:function(){let t=!0;try{const e="__local_store_support__",n="testIsSupportStorage";I.set(e,n),I.get(e)!==n&&(t=!1),I.remove(e)}catch(e){t=!1}return t}};function S(t){return t.trim()}function w(t){if(!t||"string"!=typeof t)return"";try{return new URL(t,window.location.origin).pathname}catch(e){return""}}const O={},v="1.2.0",A="init-ready",y="spa-switch",T="ff-ready",R="$PageLeave";var b=(t=>(t[t.FEATURE_GATE=1]="FEATURE_GATE",t[t.FEATURE_CONFIG=2]="FEATURE_CONFIG",t[t.EXPERIMENT=3]="EXPERIMENT",t))(b||{});const C={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(t){this.commonProps=t},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(t,e){this._state[t]=e,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let t=JSON.parse(JSON.stringify(this._state));t.identities&&(t.identities=_(JSON.stringify(t.identities)));const n=JSON.stringify(t);e.set({name:this.getCookieName(),value:n,expires:365})},init:function(t){let n,s;this.crossSubdomain=t,e.isSupport()&&(n=e.get(this.getCookieName()),s=d(n)),C._state={...s||{}},C._state.identities&&(C._state.identities=d(E(C._state.identities))),C._state.identities&&i(C._state.identities)&&!c(C._state.identities)||(C._state.identities={$identity_cookie_id:f()}),C.save()},setLoginId(t){"number"==typeof t&&(t=String(t)),void 0!==t&&t&&(C.set("login_id",t),C.save())},setAnonId(t){"number"==typeof t&&(t=String(t)),"string"==typeof t&&t?(C.set("anon_id",t),C.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",t)},saveABData(t){if(!t||c(t))return;this._abData=t;let e=JSON.parse(JSON.stringify(this._abData));e=_(JSON.stringify(e));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:e,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(t=6e5){try{let e=localStorage.getItem(this.getABLSName());if(e){const{time:n,data:i,login_id:s,anon_id:r}=d(e)||{};if(n&&i&&Date.now()-n<t&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const t=d(E(i));return this._abData=Array.isArray(t)?t:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(e){console.warn("Failed to load abdata from localStorage",e),this._abData=[]}return this._abData||[]}};function N(t){var e;if(t.data)return{contentType:"application/json",body:(e=t.data,JSON.stringify(e,(t,e)=>"bigint"==typeof e?e.toString():e,undefined))}}const P=[];function k(t){const e={...t};e.timeout=e.timeout||6e4;const n=e.transport??"fetch",i=P.find(t=>t.transport===n)?.method??P[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(e)}function L(t){return o(t=t||document.referrer)&&(t=l(t=t.trim()))||""}function F(t){const e=m(t=t||L());if(!e)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let t=n[i];for(let n=0,s=t.length;n<s;n++)if(t[n].test(e))return i}return""}function B(t,e){return-1!==t.indexOf(e)}"function"==typeof fetch&&P.push({transport:"fetch",method:function(t){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const e=N(t),n=new Headers;t.headers&&Object.keys(t.headers).forEach(e=>{n.append(e,t.headers[e])}),e?.contentType&&n.append("Content-Type",e.contentType),fetch(t.url,{method:t.method||"GET",headers:n,body:e?.body}).then(e=>e.text().then(n=>{const i={statusCode:e.status,text:n};if(200===e.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}t.callback?.(i)})).catch(e=>{console.error("Request failed:",e),t.callback?.({statusCode:0,text:String(e)})})}}),"undefined"!=typeof XMLHttpRequest&&P.push({transport:"XHR",method:function(t){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const e=new XMLHttpRequest;e.open(t.method||"GET",t.url,!0);const n=N(t);t.headers&&Object.keys(t.headers).forEach(n=>{e.setRequestHeader(n,t.headers[n])}),n?.contentType&&e.setRequestHeader("Content-Type",n.contentType),e.timeout=t.timeout||6e4,e.withCredentials=!0,e.onreadystatechange=()=>{if(4===e.readyState){const i={statusCode:e.status,text:e.responseText};if(200===e.status)try{i.json=JSON.parse(e.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}t.callback?.(i)}},e.send(n?.body)}});const M={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},D="(\\d+(\\.\\d+)?)",$=new RegExp("Version/"+D),x=new RegExp(M.XBOX,"i"),U=new RegExp(M.PLAYSTATION+" \\w+","i"),H=new RegExp(M.NINTENDO+" \\w+","i"),X=new RegExp(M.BLACKBERRY+"|PlayBook|BB10","i"),q=new RegExp("(HUAWEI|honor|HONOR)","i"),W=new RegExp("(Xiaomi|Redmi)","i"),j=new RegExp("(OPPO|realme)","i"),G=new RegExp("(vivo|IQOO)","i"),z={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function Y(t,e){return e=e||"",B(t," OPR/")&&B(t,"Mini")?M.OPERA_MINI:B(t," OPR/")?M.OPERA:X.test(t)?M.BLACKBERRY:B(t,"IE"+M.MOBILE)||B(t,"WPDesktop")?M.INTERNET_EXPLORER_MOBILE:B(t,M.SAMSUNG_BROWSER)?M.SAMSUNG_INTERNET:B(t,M.EDGE)||B(t,"Edg/")?M.MICROSOFT_EDGE:B(t,"FBIOS")?M.FACEBOOK+" "+M.MOBILE:B(t,"UCWEB")||B(t,"UCBrowser")?M.UC_BROWSER:B(t,"CriOS")?M.CHROME_IOS:B(t,"CrMo")||B(t,M.CHROME)?M.CHROME:B(t,M.ANDROID)&&B(t,M.SAFARI)?M.ANDROID_MOBILE:B(t,"FxiOS")?M.FIREFOX_IOS:B(t.toLowerCase(),M.KONQUEROR.toLowerCase())?M.KONQUEROR:function(t,e){return e&&B(e,M.APPLE)||B(n=t,M.SAFARI)&&!B(n,M.CHROME)&&!B(n,M.ANDROID);var n}(t,e)?B(t,M.MOBILE)?M.MOBILE_SAFARI:M.SAFARI:B(t,M.FIREFOX)?M.FIREFOX:B(t,"MSIE")||B(t,"Trident/")?M.INTERNET_EXPLORER:B(t,"Gecko")?M.FIREFOX:""}const K={[M.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+D)],[M.MICROSOFT_EDGE]:[new RegExp(M.EDGE+"?\\/"+D)],[M.CHROME]:[new RegExp("("+M.CHROME+"|CrMo)\\/"+D)],[M.CHROME_IOS]:[new RegExp("CriOS\\/"+D)],[M.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+D)],[M.SAFARI]:[$],[M.MOBILE_SAFARI]:[$],[M.OPERA]:[new RegExp("("+M.OPERA+"|OPR)\\/"+D)],[M.FIREFOX]:[new RegExp(M.FIREFOX+"\\/"+D)],[M.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+D)],[M.KONQUEROR]:[new RegExp("Konqueror[:/]?"+D,"i")],[M.BLACKBERRY]:[new RegExp(M.BLACKBERRY+" "+D),$],[M.ANDROID_MOBILE]:[new RegExp("android\\s"+D,"i")],[M.SAMSUNG_INTERNET]:[new RegExp(M.SAMSUNG_BROWSER+"\\/"+D)],[M.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+D)],Mozilla:[new RegExp("rv:"+D)]};function J(t,e){const n=Y(t,e),i=K[n];if(a(i))return null;for(let s=0;s<i.length;s++){const e=i[s],n=t.match(e);if(n)return parseFloat(n[n.length-2])}return null}const Z=[[new RegExp(M.XBOX+"; "+M.XBOX+" (.*?)[);]","i"),t=>[M.XBOX,t&&t[1]||""]],[new RegExp(M.NINTENDO,"i"),[M.NINTENDO,""]],[new RegExp(M.PLAYSTATION,"i"),[M.PLAYSTATION,""]],[X,[M.BLACKBERRY,""]],[new RegExp(M.WINDOWS,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[M.WINDOWS_PHONE,""];if(new RegExp(M.MOBILE).test(e)&&!/IEMobile\b/.test(e))return[M.WINDOWS+" "+M.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){const t=n[1];let i=z[t]||"";return/arm/i.test(e)&&(i="RT"),[M.WINDOWS,i]}return[M.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){const e=[t[3],t[4],t[5]||"0"];return[M.IOS,e.join(".")]}return[M.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=a(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+M.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+M.ANDROID+")","i"),t=>{if(t&&t[2]){const e=[t[2],t[3],t[4]||"0"];return[M.ANDROID,e.join(".")]}return[M.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{const e=["Mac OS X",""];if(t&&t[1]){const n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[M.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function Q(){const t=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,e=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(t){for(let e=0;e<Z.length;e++){const[n,i]=Z[e],s=n.exec(t),r=s&&("function"==typeof i?i(s,t):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:Y(n),$browser_version:J(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:t,$viewport_width:e,$lib:"webjs",$lib_version:v,$search_engine:F(),$referrer:L(),$referrer_host:m(r=r||L()),$title:document.title,$language:navigator.language,$model:(s=n,(H.test(s)?M.NINTENDO:U.test(s)?M.PLAYSTATION:x.test(s)?M.XBOX:new RegExp(M.OUYA,"i").test(s)?M.OUYA:new RegExp("("+M.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?M.WINDOWS_PHONE:/iPad/.test(s)?M.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?M.APPLE_WATCH:X.test(s)?M.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp(M.NOKIA,"i").test(s)?M.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":q.test(s)?M.HUAWEI:W.test(s)?M.XIAOMI:j.test(s)?M.OPPO:G.test(s)?M.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp(M.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?M.ANDROID:M.ANDROID_TABLET:M.ANDROID:new RegExp("(pda|"+M.MOBILE+")","i").test(s)?M.GENERIC_MOBILE:new RegExp(M.TABLET,"i").test(s)&&!new RegExp(M.TABLET+" pc","i").test(s)?M.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-(new Date).getTimezoneOffset()};var s,r}const V=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const t=localStorage.getItem(this.STORAGE_KEY);t&&(this.queue=d(t)||[])}catch(t){console.warn("Failed to load queue from localStorage:",t),this.queue=[]}}cleanupExpiredItems(){const t=Date.now(),e=this.queue.filter(e=>t-e.timestamp<this.MAX_AGE_MS);e.length!==this.queue.length&&(this.queue=e,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(t){console.warn("Failed to save queue to localStorage:",t)}}enqueue(t,e,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:t,data:e,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(t){try{this.queue=this.queue.filter(e=>e.id!==t),this.saveToStorage()}catch(e){console.warn("Failed to dequeue request:",e)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(t){return console.warn("Failed to get queue items:",t),[]}}incrementRetryCount(t){const e=this.queue.find(e=>e.id===t);return!(!e||e.retryCount>=e.maxRetries||(e.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(t){console.warn("Failed to clear queue from localStorage:",t)}}getItemById(t){return this.queue.find(e=>e.id===t)}};class tt{constructor(t={}){this.flushTimer=null,this.isFlushing=!1,this.paused=!1,this.destroyed=!1,this.config={maxBatchSize:t.maxBatchSize||20,flushInterval:t.flushInterval||5e3},this.startFlushTimer()}pause(){this.paused=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}resume(){this.paused&&(this.paused=!1,this.startFlushTimer())}isPaused(){return this.paused}add(){V.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.paused||this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const t=V.getAll();if(0===t.length)return this.isFlushing=!1,void this.startFlushTimer();const e=[],n=[];t.forEach(t=>{Array.isArray(t.data)?e.push(...t.data):e.push(t.data),n.push(t.id)});const i=e.slice(0,this.config.maxBatchSize),s=t[t.length-1],r=s.url,o=s.headers;O.instance&&O.instance.config.debug&&console.log(JSON.stringify(i,null,2)),k({url:r,method:"POST",data:i,headers:o,callback:t=>{200===t.statusCode?n.forEach(t=>{V.dequeue(t)}):console.error("Failed to send batch events:",t),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.destroyed||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{V.getAll().length>0&&this.triggerFlush()},this.config.flushInterval))}destroy(){this.destroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush()}}let et=null;function nt(){const t=O.instance;return!(!t||!t.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}function it(){const t=O.instance;return!t||"function"!=typeof t.hasOptedOutCapturing||!t.hasOptedOutCapturing()}let st=null;function rt(){return I.isSupport()?(st||(et||(et=new tt({maxBatchSize:20,flushInterval:5e3})),st=et),st):null}function ot(t,e,n){return k({url:t,method:"POST",data:e.data,headers:e.headers,callback:t=>{if(200!==t.statusCode){if(n)if(V.incrementRetryCount(n)){const t=V.getItemById(n);if(t){const e=Math.min(1e3*Math.pow(2,t.retryCount),3e4);setTimeout(()=>{ot(t.url,{data:t.data,headers:t.headers},t.id)},e)}}else console.warn("Max retries reached for request:",n)}else n&&V.dequeue(n),e.callback&&e.callback(t.json)}})}function at(t){return`${t.apiHost}/in/track`}function ut(t){return`${t.apiHost}/ab/evalall`}function ct(t){return{"Content-Type":"application/json",SourceToken:t.sourceToken}}function ht(t,e,n){O.instance&&O.instance.config.debug&&console.log(JSON.stringify(e.data,null,2));const i=V.enqueue(t,e.data,e.headers);return ot(t,{...e,callback:void 0},i)}function lt(){try{const t=sessionStorage.getItem("sensorswave_utm");if(!t)return{};const e=JSON.parse(t),n={};return Object.entries(e).forEach(([t,e])=>{null!=e&&""!==e&&(n[`$${t}`]=e)}),n}catch(t){return{}}}function dt(t){const e={};return Object.entries(t).forEach(([t,n])=>{if("function"==typeof n)try{const i=n();e[t]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",t,i)}else e[t]=n}),e}function pt(t={},e=!0){const n={...e?Q():{},...dt(C.getCommonProps()),...t},i=lt();return Object.keys(i).length>0&&Object.assign(n,i),n}function gt(t,e,n=!0){if(!nt())return;if(!it())return;const i={time:Date.now(),trace_id:C.getTraceId(),event:t.event,properties:pt(t.properties,n)},s=lt();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),t.user_properties&&(t.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...t.user_properties.$set},delete t.user_properties.$set),i.user_properties={...i.user_properties,...t.user_properties});const r=C.getLoginId(),o=C.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=at(e),u=ct(e),c=!1!==e.batchSend&&rt();c?(V.enqueue(a,[i],u),c.add()):ht(a,{data:[i],headers:u})}function ft({userProps:t,opts:e}){if(!nt())return;if(!it())return;const n=C.getLoginId(),i=C.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:C.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:t,properties:pt()},r=at(e),o=ct(e),a=rt();if(!a)return ht(r,{data:[s],headers:o});V.enqueue(r,[s],o),a.add()}function mt(t){return t.typ===b.FEATURE_GATE||t.typ===b.FEATURE_CONFIG?`$feature_${t.id}`:t.typ===b.EXPERIMENT?`$exp_${t.id}`:""}function Et(t){const e=t.typ;return[b.FEATURE_GATE,b.EXPERIMENT,b.FEATURE_CONFIG].includes(e)?{[mt(t)]:t.vid}:{}}function _t(t){const e=t.typ;return e===b.FEATURE_GATE||e===b.FEATURE_CONFIG?{$feature_key:t.key,$feature_variant:t.vid}:e===b.EXPERIMENT?{$exp_key:t.key,$exp_variant:t.vid}:{}}function It({isUnset:t=!1,data:e,opts:n}){if(!nt())return;if(!it())return;if(!e||c(e)||e.disable_impress)return;const i=C.getLoginId(),s=C.getAnonId();if(!i&&!s)return;const r=e.typ===b.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=t?{$unset:{[mt(e)]:null}}:{$set:{...Et(e)}},gt({event:r,properties:_t(e),user_properties:o},n)}const St="sensorswave_opt_out";class wt{constructor(t){this.persist=t}read(){if(this.persist)try{const t=I.get(St);return"0"===t||"1"!==t&&void 0}catch{return}}write(t){if(this.persist)try{I.set(St,t?"0":"1")}catch{}}}class Ot{constructor({plugins:t,emitter:e,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=e,this.config=n,this.sdk=i,this.registerBuiltInPlugins(t),this.created(),this.emitter.on(A,()=>{this.init()})}registerBuiltInPlugins(t){for(let e=0,n=t.length;e<n;e++)this.registerPlugin(t[e])}registerPlugin(t){this.plugins.push(t)}getPlugins(){return this.plugins}getPlugin(t){return this.pluginInsMap[t]}created(){for(let t=0,e=this.plugins.length;t<e;t++){const e=this.plugins[t];if(!e.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new e({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[e.NAME]=n}}init(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.init&&e.init()}}destroy(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.destroy&&"function"==typeof e.destroy&&e.destroy()}this.pluginInsMap={},this.plugins=[]}}const vt=class{constructor({emitter:t,config:e,sdk:n}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;this.boundSend=()=>{gt({event:"$PageView",properties:{}},t)},this.sdk&&!0===this.sdk._postConsentInit||setTimeout(()=>{this.boundSend()},0),t.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=t=>{t!==location.href&&this.boundSend()},this.emitter.on(y,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(y,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};vt.NAME="pageview";let At=vt;const yt=class{constructor({emitter:t,config:e,sdk:n}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this._skipFirstPageEnd=!1,this.emitter=t,this.config=e,this.sdk=n}__canCapture(){return!this.sdk||"function"!=typeof this.sdk.hasOptedOutCapturing||!this.sdk.hasOptedOutCapturing()}init(){this.pageId=Number(String(g()).slice(2,5)+String(g()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),this.sdk&&!0===this.sdk._postConsentInit&&(this._skipFirstPageEnd=!0),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(t){console.log(t)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title,this._skipFirstPageEnd=!1}pageEndHandler(){if(!0===this.pageHiddenStatus)return;if(!this.__canCapture())return;const t=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete t.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,gt({event:R,properties:t},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const t=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",t),this.eventListeners.push({target:window,event:"pageshow",handler:t})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(y,t=>{t!==location.href&&(this.url=t,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(t=>{if(`on${t}`in window){const e=()=>{if(this._skipFirstPageEnd)return this._skipFirstPageEnd=!1,void this.stopHeartBeatInterval();this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(t,e),this.eventListeners.push({target:window,event:t,handler:e})}})}addPageSwitchListener(){const t=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",t),this.eventListeners.push({target:document,event:"visibilitychange",handler:t})}addHeartBeatInterval(){I.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.sdk&&!0===this.sdk._postConsentInit&&!0===this._skipFirstPageEnd||(this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData())}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(t){if(!this.__canCapture())return;const e=this.getPageLeaveProperties();e.$time=Date.now(),"is_first_heartbeat"===t&&(e.$event_duration=3);const n={type:"track",event:R,properties:e,time:e.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,I.isSupport()&&I.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(t){I.isSupport()&&I.remove(t||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){if(this.__canCapture())for(let t=window.localStorage.length-1;t>=0;t--){const e=window.localStorage.key(t);if(e&&e!==`${this.storageName}-${this.pageId}`&&0===e.indexOf(`${this.storageName}-`)){const t=I.parse(e);i(t)&&Date.now()-t.time>t.heartbeat_interval_time+5e3&&(delete t.heartbeat_interval_time,t._flush_time=(new Date).getTime(),gt({event:R,properties:t?.properties},this.config),this.delHeartBeatData(e))}}}getPageLeaveProperties(){let t=(Date.now()-this.startTime)/1e3;(isNaN(t)||t<0||t>this.maxDuration)&&(t=0),t=Number(t.toFixed(3));const e={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:w(this.url)};return 0!==t&&(e.$event_duration=t),e}destroy(){this.eventListeners.forEach(({target:t,event:e,handler:n})=>{t.removeEventListener(e,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};yt.NAME="pageleave";let Tt=yt;const Rt=class{constructor({emitter:t,config:e,sdk:n}){this.eventSended=!1,this.emitter=t,this.config=e,this.sdk=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit)return;const t=()=>{let e=0;const n={};if(window.performance){e=function(){let t=0;if("function"==typeof performance.getEntriesByType){const e=performance.getEntriesByType("navigation");e.length>0&&(t=e[0].domContentLoadedEventEnd||0)}return t}();const t=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const t=performance.getEntries();let e=0;for(const n of t)"transferSize"in n&&(e+=n.transferSize);if("number"==typeof e&&e>=0&&e<10737418240)return Number((e/1024).toFixed(3))}}();t&&(n.$page_resource_size=t)}else console.warn("Performance API is not supported.");e>0&&!Number.isFinite(e)&&(n.$event_duration=Number((e/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,gt({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",t)};"complete"===document.readyState?t():window.addEventListener&&window.addEventListener("load",t)}};Rt.NAME="pageload";let bt=Rt;function Ct(t,e){if(!h(t))return!1;const n=o(t.tagName)?t.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=t.getAttribute("name")||"",i.$element_id=t.getAttribute("id")||"",i.$element_class_name=o(t.className)?t.className:"",i.$element_target_url=t.getAttribute("href")||"",i.$element_content=function(t,e){return o(e)&&"input"===e.toLowerCase()?("button"===(n=t).type||"submit"===n.type)&&n.value||"":function(t,e){let n="",i="";return t.textContent?n=S(t.textContent):t.innerText&&(n=S(t.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==e&&"INPUT"!==e||(i=t.value||""),i}(t,e);var n}(t,n)||"",i.$element_selector=Nt(t)||"",i.$element_path=function(t){let e=[];for(;t.parentNode&&h(t);){if(!o(t.tagName))return"";if(t.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.id)){e.unshift(t.tagName.toLowerCase()+"#"+t.id);break}if(t===document.body){e.unshift("body");break}e.unshift(t.tagName.toLowerCase()),t=t.parentNode}return e.join(" > ")}(t)||"";const s=function(t,e){const n=e.pageX||e.clientX+Pt().scrollLeft||e.offsetX+kt(t).targetEleX,i=e.pageY||e.clientY+Pt().scrollTop||e.offsetY+kt(t).targetEleY;return{$page_x:Lt(n),$page_y:Lt(i)}}(t,e);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function Nt(t,e=[]){if(!(t&&t.parentNode&&t.parentNode.children&&o(t.tagName)))return"";e=Array.isArray(e)?e:[];const n=t.nodeName.toLowerCase();return t&&"body"!==n&&1==t.nodeType?(e.unshift(function(t){if(!t||!h(t)||!o(t.tagName))return"";let e=t.parentNode&&9==t.parentNode.nodeType?-1:function(t){if(!t.parentNode)return-1;let e=0;const n=t.tagName,i=t.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(t===i[s])return e;e++}return-1}(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~e?":nth-of-type("+(e+1)+")":"")}(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?e.join(" > "):Nt(t.parentNode,e)):(e.unshift("body"),e.join(" > "))}function Pt(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function kt(t){if(document.documentElement.getBoundingClientRect){const e=t.getBoundingClientRect();return{targetEleX:e.left+Pt().scrollLeft||0,targetEleY:e.top+Pt().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Lt(t){return Number(Number(t).toFixed(3))}const Ft=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(t){const e=t.target;if(!e)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(e.tagName))return;if("true"===e.getAttribute("sensorswave-disable"))return;gt({event:"$WebClick",properties:Ct(e,t)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};Ft.NAME="webclick";let Bt=Ft;const Mt=class{constructor({emitter:t,config:e,sdk:n}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;if(t.enableAB){if(this.sdk&&"function"==typeof this.sdk.hasOptedOutCapturing&&this.sdk.hasOptedOutCapturing())return;this.fastFetch().then(()=>{this.emitter.emit(T)}),t.abRefreshInterval<3e4&&(t.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},t.abRefreshInterval)}}async fastFetch(){const t=C.getABData(this.config.abRefreshInterval);return t&&t.length?(this.emitter.emit(T),Promise.resolve(t)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(t=>{!function({opts:t,cb:e}){if(!nt())return void(e&&e({}));if(!it())return void(e&&e({}));const n=C.getLoginId(),i=C.getAnonId();if(!n&&!i)return void(e&&e({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...Q(),...dt(C.getCommonProps())}},sdk:"webjs",sdk_version:v};k({url:ut(t),method:"POST",data:s,headers:ct(t),callback:t=>{200!==t.statusCode?(console.error("Failed to fetch feature flags"),e&&e({})):e&&e(t.json)}})}({opts:this.config,cb:e=>{C.saveABData(e?.data?.results||[]),t(e),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(t){return await this.fastFetch().catch(console.warn),C.getABData(this.config.abRefreshInterval).find(e=>e.typ===b.FEATURE_GATE&&e.key==t)}async checkFeatureGate(t){const e=await this.getFeatureGate(t);return!!e&&(!e.hasOwnProperty("vid")&&e.key?(It({isUnset:!0,data:e,opts:this.config}),!1):(It({data:e,opts:this.config}),"fail"!==e.vid))}async getExperiment(t){await this.fastFetch().catch(console.warn);const e=C.getABData(this.config.abRefreshInterval).find(e=>e.typ===b.EXPERIMENT&&e.key===t);return e?!e.hasOwnProperty("vid")&&e.key?(It({isUnset:!0,data:e,opts:this.config}),{}):(It({data:e,opts:this.config}),e?.value||{}):{}}async getFeatureConfig(t){await this.fastFetch().catch(console.warn);const e=C.getABData(this.config.abRefreshInterval).find(e=>e.typ===b.FEATURE_CONFIG&&e.key===t);if(!e)return{};if(!e.hasOwnProperty("vid")&&e.key)return It({isUnset:!0,data:e,opts:this.config}),{};It({data:e,opts:this.config});const n=e?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Mt.NAME="abtest";let Dt=Mt;const $t=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],xt="sensorswave_utm",Ut=class t{constructor({sdk:t,emitter:e,config:n}){this.sdk=t,this.emitter=e,this.config=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit){let e=t.readFromSessionStorage();return e&&0!==Object.keys(e).length||(e=t.captureAndStore(this.config?.debug)),void this.scheduleInitialUTM(e)}const e=t.getUTMFromURL();t.saveToSessionStorage(e,this.config?.debug),this.scheduleInitialUTM(e)}scheduleInitialUTM(t){setTimeout(()=>{this.sendInitialUTM(t)},0)}static getUTMFromURL(){try{const t=new URLSearchParams(window.location.search),e={};return $t.forEach(n=>{const i=t.get(n);i&&(e[n]=i)}),e}catch(e){return t.getUTMFromURLFallback()}}static getUTMFromURLFallback(){const t={};return window.location.search.substring(1).split("&").forEach(e=>{const[n,i]=e.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";$t.includes(s)&&(t[s]=r)}),t}static readFromSessionStorage(){try{const t=sessionStorage.getItem(xt);if(!t)return{};const e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch(t){return{}}}static saveToSessionStorage(t,e=!1){try{sessionStorage.setItem(xt,JSON.stringify(t))}catch(n){e&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",n)}}static captureAndStore(e=!1){const n=t.getUTMFromURL();return t.saveToSessionStorage(n,e),n}sendInitialUTM(t){const e={};$t.forEach(n=>{e[`$initial_${n}`]=null!=t[n]?t[n]:""});try{this.sdk.profileSetOnce(e)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};Ut.NAME="UTM";let Ht=Ut;const Xt=[],qt={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1,optOutCapturing:!1,persistOptOut:!1};return new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new t,this.pluginCore={},this.commonProps={},this.spaCleanup=null,this._optOutCapturing=!1,this.consentStorage=new wt(!1),this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance=this}init(t,e={}){return this.inited?this:(O.instance=this,e.sourceToken=t,this.mergeConfig(e),this.consentStorage=new wt(!0===this.config.persistOptOut),this._optOutCapturing?this.consentStorage.write(!0):!0===this.config.optOutCapturing?(this._optOutCapturing=!0,this.consentStorage.write(!0)):!0===this.consentStorage.read()&&(this._optOutCapturing=!0),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0,this._optOutCapturing?(Ht.captureAndStore(this.config.debug),this.eventEmitter.emit(A),this.inited=!0,this):(this.__setupAfterConsent(),this.eventEmitter.emit(A),this.inited=!0,this))}__setupAfterConsent(){if(this._setupAfterConsentDone)return;this._setupAfterConsentDone=!0;const t=this.config;Xt.length=0,C.init(t.crossSubdomainCookie),t.anonId&&C.setAnonId(t.anonId),function(){if(window._swFailedRequestsInitialized)return;window._swFailedRequestsInitialized=!0;const t=O.instance;t&&"function"==typeof t.hasOptedOutCapturing&&t.hasOptedOutCapturing()||t&&!0===t._postConsentInit||function(){const t=V.getAll();if(0!==t.length)for(let e=0,n=t.length;e<n;e+=10){const n=t.slice(e,e+10),i=[],s=[];n.forEach(t=>{Array.isArray(t.data)?i.push(...t.data):i.push(t.data),s.push(t.id)});const r=n[n.length-1],o=r.url,a=r.headers;k({url:o,method:"POST",data:i,headers:a,callback:t=>{200!==t.statusCode?console.error("Failed to send batch stored requests:",t):s.forEach(t=>{V.dequeue(t)})}})}}()}(),Xt.push(Ht),t.autoCapture&&this.autoTrack(),t.enableAB&&Xt.push(Dt),t.enableClickTrack&&Xt.push(Bt),this.pluginCore=new Ot({plugins:Xt,emitter:this.eventEmitter,config:t,sdk:this}),this.spaCleanup=function(t){let e=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){t(e),e=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),t(e),e=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),t(e),e=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(t=>{this.eventEmitter.emit(y,t)})}mergeConfig(t){this.config={...qt,...t}}__canCapture(){return this.inited&&!this._optOutCapturing}track(t){this.__canCapture()&&function(t,e){if(!nt())return;if(!it())return;const n={...t};n.time||(n.time=Date.now()),n.login_id||(n.login_id=C.getLoginId()),n.anon_id||(n.anon_id=C.getAnonId()),n.trace_id||(n.trace_id=C.getTraceId()),n.properties={...Q(),...dt(C.getCommonProps()),...n.properties};const i=at(e),s=ct(e),r=!1!==e.batchSend&&rt();if(!r)return ht(i,{data:[n],headers:s});V.enqueue(i,[n],s),r.add()}(t,this.config)}trackEvent(t,e){this.__canCapture()&>({event:t,properties:e},this.config)}autoTrack(){Xt.push(At,bt,Tt)}profileSet(t){this.__canCapture()&&ft({userProps:{$set:t},opts:this.config})}profileSetOnce(t){this.__canCapture()&&ft({userProps:{$set_once:t},opts:this.config})}profileIncrement(t){this.__canCapture()&&ft({userProps:{$increment:t},opts:this.config})}profileAppend(t){this.__canCapture()&&ft({userProps:{$append:t},opts:this.config})}profileUnion(t){this.__canCapture()&&ft({userProps:{$union:t},opts:this.config})}profileUnset(t){if(!this.__canCapture())return;const e={};r(t)?t.forEach(function(t){e[t]=null}):e[t]=null,ft({userProps:{$unset:e},opts:this.config})}profileDelete(){this.__canCapture()&&ft({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(t){if(!i(t))return console.warn("Commmon Properties must be an object!");this.commonProps=t,C.setCommonProps(this.commonProps)}clearCommonProperties(t){if(!r(t))return console.warn("Commmon Properties to be cleared must be an array!");t.forEach(t=>{delete this.commonProps[t]}),C.setCommonProps(this.commonProps)}identify(t){this.__canCapture()&&(C.setLoginId(t),function(t){if(!nt())return;if(!it())return;const e=C.getLoginId(),n=C.getAnonId();if(!e||!n)return;const i={time:Date.now(),trace_id:C.getTraceId(),event:"$Identify",login_id:e,anon_id:n,properties:pt()},s=at(t),r=ct(t),o=rt();if(!o)return ht(s,{data:[i],headers:r});V.enqueue(s,[i],r),o.add()}(this.config))}setLoginId(t){this.__canCapture()&&C.setLoginId(t)}getAnonId(){return this.__canCapture()?C.getAnonId():""}setAnonId(t){this.__canCapture()&&C.setAnonId(t)}getLoginId(){return this.__canCapture()?C.getLoginId():""}checkFeatureGate(t){if(!this.__canCapture())return Promise.resolve(!1);const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.checkFeatureGate(t):Promise.reject("AB is disabled")}getExperiment(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getExperiment(t):Promise.reject("AB is disabled")}getFeatureConfig(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getFeatureConfig(t):Promise.reject("AB is disabled")}optOutCapturing(){this._optOutCapturing=!0,this.consentStorage.write(!0),st&&st.pause()}optInCapturing(){if(this._optOutCapturing=!1,this.consentStorage.write(!1),st&&st.resume(),this.inited&&!this._setupAfterConsentDone){this._postConsentInit=!0;try{this.__setupAfterConsent(),this.eventEmitter.emit(A)}finally{this._postConsentInit=!1}}}hasOptedOutCapturing(){return this._optOutCapturing}destroy(){st&&(st.destroy(),st=null),"undefined"!=typeof window&&(window._swFailedRequestsInitialized=!1),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.pluginCore={},this.eventEmitter&&this.eventEmitter.removeAllListeners(),this.consentStorage=new wt(!0===this.config?.persistOptOut),this._optOutCapturing=!1,this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance===this&&(O.instance=null)}}});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).SensorsWave=e()}(this,function(){"use strict";class t{constructor(){this.listeners={}}on(t,e,n=!1){if(t&&e){if(!s(e))throw new Error("listener must be a function");this.listeners[t]=this.listeners[t]||[],this.listeners[t].push({listener:e,once:n})}}off(t,e){const n=this.listeners[t];if(!n?.length)return;"number"==typeof e&&n.splice(e,1);const i=n.findIndex(t=>t.listener===e);-1!==i&&n.splice(i,1)}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((n,i)=>{n.listener.call(this,...e),n.listener.once&&this.off(t,i)})}once(t,e){this.on(t,e,!0)}removeAllListeners(t){t?this.listeners[t]=[]:this.listeners={}}}const e={get:function(t){const e=t+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let t=n[i];for(;" "==t.charAt(0);)t=t.substring(1,t.length);if(0==t.indexOf(e))return h(t.substring(e.length,t.length))}return null},set:function({name:t,value:e,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",c="",u="";if(0!==(n=null==n||void 0===n?365:n)){const t=new Date;"s"===String(n).slice(-1)?t.setTime(t.getTime()+1e3*Number(String(n).slice(0,-1))):t.setTime(t.getTime()+24*n*60*60*1e3),o="; expires="+t.toUTCString()}function l(t){return t?t.replace(/\r\n/g,""):""}i&&(c="; SameSite="+i),s&&(a="; secure");const h=l(t),d=l(e),p=l(r);p&&(u="; domain="+p),h&&d&&(document.cookie=h+"="+encodeURIComponent(d)+o+"; path=/"+u+c+a)},remove:function(t){this.set({name:t,value:"",expires:-1})},isSupport:function({samesite:t,secure:e}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:t,secure:e}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(t){return"[object Object]"===n.call(t)}function s(t){const e=n.call(t);return"[object Function]"==e||"[object AsyncFunction]"==e}function r(t){return"[object Array]"==n.call(t)}function o(t){return"[object String]"==n.call(t)}function a(t){return void 0===t}const c=Object.prototype.hasOwnProperty;function u(t){if(i(t)){for(let e in t)if(c.call(t,e))return!1;return!0}return!1}function l(t){return!(!t||1!==t.nodeType)}function h(t){let e=t;try{e=decodeURIComponent(t)}catch(n){e=t}return e}function d(t){try{return JSON.parse(t)}catch(e){return""}}const p=function(){let t=Date.now();return function(e){return Math.ceil((t=(9301*t+49297)%233280,t/233280*e))}}();function g(){if("function"==typeof Uint32Array){let t;if("undefined"!=typeof crypto&&(t=crypto),t&&i(t)&&t.getRandomValues)return t.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return p(1e19)/1e19}const f=function(){function t(t){return("0".repeat(t)+Date.now().toString(16)).slice(-t)}return function(){let e=String(screen.height*screen.width);e=e&&/\d{4,}/.test(e)?e.slice(-4):String(31242*g()).replace(".","").slice(0,4);return t(8)+"-"+g().toString(16).replace(".","").slice(-4)+"-"+function(){const t=navigator.userAgent;let e,n=[],i=0;function s(t,e){let i=0;for(let s=0;s<e.length;s++)i|=n[s]<<8*s;return(t^i)>>>0}for(let r=0;r<t.length;r++)e=t.charCodeAt(r),n.unshift(255&e),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+e+"-"+t(12)||(String(g())+String(g())+String(g())).slice(2,15)}}();function m(t,e){e&&"string"==typeof e||(e="");let n=null;try{n=new URL(t).hostname}catch(i){}return n||e}function E(t){let e=[];try{e=atob(t).split("").map(function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})}catch(n){e=[]}try{return decodeURIComponent(e.join(""))}catch(n){return e.join("")}}function _(t){let e="";try{e=btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}))}catch(n){e=t}return e}const I={get:function(t){return window.localStorage.getItem(t)},parse:function(t){let e;try{e=JSON.parse(I.get(t))||null}catch(n){console.warn(n)}return e},set:function(t,e){try{window.localStorage.setItem(t,e)}catch(n){console.warn(n)}},remove:function(t){window.localStorage.removeItem(t)},isSupport:function(){let t=!0;try{const e="__local_store_support__",n="testIsSupportStorage";I.set(e,n),I.get(e)!==n&&(t=!1),I.remove(e)}catch(e){t=!1}return t}};function S(t){return t.trim()}function w(t){if(!t||"string"!=typeof t)return"";try{return new URL(t,window.location.origin).pathname}catch(e){return""}}const O={},v="1.4.0",b="init-ready",y="spa-switch",A="ff-ready",R="$PageLeave",T="$Exception";var C=(t=>(t[t.FEATURE_GATE=1]="FEATURE_GATE",t[t.FEATURE_CONFIG=2]="FEATURE_CONFIG",t[t.EXPERIMENT=3]="EXPERIMENT",t))(C||{});const N={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(t){this.commonProps=t},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(t,e){this._state[t]=e,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let t=JSON.parse(JSON.stringify(this._state));t.identities&&(t.identities=_(JSON.stringify(t.identities)));const n=JSON.stringify(t);e.set({name:this.getCookieName(),value:n,expires:365})},init:function(t){let n,s;this.crossSubdomain=t,e.isSupport()&&(n=e.get(this.getCookieName()),s=d(n)),N._state={...s||{}},N._state.identities&&(N._state.identities=d(E(N._state.identities))),N._state.identities&&i(N._state.identities)&&!u(N._state.identities)||(N._state.identities={$identity_cookie_id:f()}),N.save()},setLoginId(t){"number"==typeof t&&(t=String(t)),void 0!==t&&t&&(N.set("login_id",t),N.save())},clearLoginId(){this._state.login_id="",this.save()},resetAnonId(){this._state.anon_id="",this._state.identities={$identity_cookie_id:f()},this.save()},setAnonId(t){"number"==typeof t&&(t=String(t)),"string"==typeof t&&t?(N.set("anon_id",t),N.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",t)},saveABData(t){if(!t||u(t))return;this._abData=t;let e=JSON.parse(JSON.stringify(this._abData));e=_(JSON.stringify(e));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:e,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(t=6e5){try{let e=localStorage.getItem(this.getABLSName());if(e){const{time:n,data:i,login_id:s,anon_id:r}=d(e)||{};if(n&&i&&Date.now()-n<t&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const t=d(E(i));return this._abData=Array.isArray(t)?t:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(e){this._abData=[]}return this._abData||[]}};function P(t){return!(t>=400&&t<500)||408===t||429===t}function k(t){var e;if(t.data)return{contentType:"application/json",body:(e=t.data,JSON.stringify(e,(t,e)=>"bigint"==typeof e?e.toString():e,undefined))}}const L=[];function $(t){const e={...t};e.timeout=e.timeout||6e4;const n=e.transport??"fetch",i=L.find(t=>t.transport===n)?.method??L[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(e)}function F(t){return o(t=t||document.referrer)&&(t=h(t=t.trim()))||""}function x(t){const e=m(t=t||F());if(!e)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let t=n[i];for(let n=0,s=t.length;n<s;n++)if(t[n].test(e))return i}return""}function B(t,e){return-1!==t.indexOf(e)}"function"==typeof fetch&&L.push({transport:"fetch",method:function(t){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const e=k(t),n=new Headers;t.headers&&Object.keys(t.headers).forEach(e=>{n.append(e,t.headers[e])}),e?.contentType&&n.append("Content-Type",e.contentType),fetch(t.url,{method:t.method||"GET",headers:n,body:e?.body}).then(e=>e.text().then(n=>{const i={statusCode:e.status,text:n};if(200===e.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}t.callback?.(i)})).catch(e=>{console.error("Request failed:",e),t.callback?.({statusCode:0,text:String(e)})})}}),"undefined"!=typeof XMLHttpRequest&&L.push({transport:"XHR",method:function(t){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const e=new XMLHttpRequest;e.open(t.method||"GET",t.url,!0);const n=k(t);t.headers&&Object.keys(t.headers).forEach(n=>{e.setRequestHeader(n,t.headers[n])}),n?.contentType&&e.setRequestHeader("Content-Type",n.contentType),e.timeout=t.timeout||6e4,e.withCredentials=!0,e.onreadystatechange=()=>{if(4===e.readyState){const i={statusCode:e.status,text:e.responseText};if(200===e.status)try{i.json=JSON.parse(e.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}t.callback?.(i)}},e.send(n?.body)}});const M={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},D="(\\d+(\\.\\d+)?)",H=new RegExp("Version/"+D),U=new RegExp(M.XBOX,"i"),X=new RegExp(M.PLAYSTATION+" \\w+","i"),j=new RegExp(M.NINTENDO+" \\w+","i"),q=new RegExp(M.BLACKBERRY+"|PlayBook|BB10","i"),W=new RegExp("(HUAWEI|honor|HONOR)","i"),G=new RegExp("(Xiaomi|Redmi)","i"),z=new RegExp("(OPPO|realme)","i"),Y=new RegExp("(vivo|IQOO)","i"),K={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function J(t,e){return e=e||"",B(t," OPR/")&&B(t,"Mini")?M.OPERA_MINI:B(t," OPR/")?M.OPERA:q.test(t)?M.BLACKBERRY:B(t,"IE"+M.MOBILE)||B(t,"WPDesktop")?M.INTERNET_EXPLORER_MOBILE:B(t,M.SAMSUNG_BROWSER)?M.SAMSUNG_INTERNET:B(t,M.EDGE)||B(t,"Edg/")?M.MICROSOFT_EDGE:B(t,"FBIOS")?M.FACEBOOK+" "+M.MOBILE:B(t,"UCWEB")||B(t,"UCBrowser")?M.UC_BROWSER:B(t,"CriOS")?M.CHROME_IOS:B(t,"CrMo")||B(t,M.CHROME)?M.CHROME:B(t,M.ANDROID)&&B(t,M.SAFARI)?M.ANDROID_MOBILE:B(t,"FxiOS")?M.FIREFOX_IOS:B(t.toLowerCase(),M.KONQUEROR.toLowerCase())?M.KONQUEROR:function(t,e){return e&&B(e,M.APPLE)||B(n=t,M.SAFARI)&&!B(n,M.CHROME)&&!B(n,M.ANDROID);var n}(t,e)?B(t,M.MOBILE)?M.MOBILE_SAFARI:M.SAFARI:B(t,M.FIREFOX)?M.FIREFOX:B(t,"MSIE")||B(t,"Trident/")?M.INTERNET_EXPLORER:B(t,"Gecko")?M.FIREFOX:""}const Z={[M.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+D)],[M.MICROSOFT_EDGE]:[new RegExp(M.EDGE+"?\\/"+D)],[M.CHROME]:[new RegExp("("+M.CHROME+"|CrMo)\\/"+D)],[M.CHROME_IOS]:[new RegExp("CriOS\\/"+D)],[M.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+D)],[M.SAFARI]:[H],[M.MOBILE_SAFARI]:[H],[M.OPERA]:[new RegExp("("+M.OPERA+"|OPR)\\/"+D)],[M.FIREFOX]:[new RegExp(M.FIREFOX+"\\/"+D)],[M.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+D)],[M.KONQUEROR]:[new RegExp("Konqueror[:/]?"+D,"i")],[M.BLACKBERRY]:[new RegExp(M.BLACKBERRY+" "+D),H],[M.ANDROID_MOBILE]:[new RegExp("android\\s"+D,"i")],[M.SAMSUNG_INTERNET]:[new RegExp(M.SAMSUNG_BROWSER+"\\/"+D)],[M.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+D)],Mozilla:[new RegExp("rv:"+D)]};function Q(t,e){const n=J(t,e),i=Z[n];if(a(i))return null;for(let s=0;s<i.length;s++){const e=i[s],n=t.match(e);if(n)return parseFloat(n[n.length-2])}return null}const V=[[new RegExp(M.XBOX+"; "+M.XBOX+" (.*?)[);]","i"),t=>[M.XBOX,t&&t[1]||""]],[new RegExp(M.NINTENDO,"i"),[M.NINTENDO,""]],[new RegExp(M.PLAYSTATION,"i"),[M.PLAYSTATION,""]],[q,[M.BLACKBERRY,""]],[new RegExp(M.WINDOWS,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[M.WINDOWS_PHONE,""];if(new RegExp(M.MOBILE).test(e)&&!/IEMobile\b/.test(e))return[M.WINDOWS+" "+M.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){const t=n[1];let i=K[t]||"";return/arm/i.test(e)&&(i="RT"),[M.WINDOWS,i]}return[M.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){const e=[t[3],t[4],t[5]||"0"];return[M.IOS,e.join(".")]}return[M.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=a(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+M.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+M.ANDROID+")","i"),t=>{if(t&&t[2]){const e=[t[2],t[3],t[4]||"0"];return[M.ANDROID,e.join(".")]}return[M.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{const e=["Mac OS X",""];if(t&&t[1]){const n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[M.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function tt(){const t=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,e=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(t){for(let e=0;e<V.length;e++){const[n,i]=V[e],s=n.exec(t),r=s&&("function"==typeof i?i(s,t):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:J(n),$browser_version:Q(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:t,$viewport_width:e,$lib:"webjs",$lib_version:v,$search_engine:x(),$referrer:F(),$referrer_host:m(r=r||F()),$title:document.title,$language:navigator.language,$model:(s=n,(j.test(s)?M.NINTENDO:X.test(s)?M.PLAYSTATION:U.test(s)?M.XBOX:new RegExp(M.OUYA,"i").test(s)?M.OUYA:new RegExp("("+M.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?M.WINDOWS_PHONE:/iPad/.test(s)?M.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?M.APPLE_WATCH:q.test(s)?M.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp(M.NOKIA,"i").test(s)?M.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":W.test(s)?M.HUAWEI:G.test(s)?M.XIAOMI:z.test(s)?M.OPPO:Y.test(s)?M.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp(M.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?M.ANDROID:M.ANDROID_TABLET:M.ANDROID:new RegExp("(pda|"+M.MOBILE+")","i").test(s)?M.GENERIC_MOBILE:new RegExp(M.TABLET,"i").test(s)&&!new RegExp(M.TABLET+" pc","i").test(s)?M.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-(new Date).getTimezoneOffset()};var s,r}const et=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const t=localStorage.getItem(this.STORAGE_KEY);t&&(this.queue=d(t)||[])}catch(t){console.warn("Failed to load queue from localStorage:",t),this.queue=[]}}cleanupExpiredItems(){const t=Date.now(),e=this.queue.filter(e=>t-e.timestamp<this.MAX_AGE_MS);e.length!==this.queue.length&&(this.queue=e,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(t){console.warn("Failed to save queue to localStorage:",t)}}enqueue(t,e,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:t,data:e,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(t){try{this.queue=this.queue.filter(e=>e.id!==t),this.saveToStorage()}catch(e){console.warn("Failed to dequeue request:",e)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(t){return console.warn("Failed to get queue items:",t),[]}}incrementRetryCount(t){const e=this.queue.find(e=>e.id===t);return!(!e||e.retryCount>=e.maxRetries||(e.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(t){console.warn("Failed to clear queue from localStorage:",t)}}getItemById(t){return this.queue.find(e=>e.id===t)}};class nt{constructor(t={}){this.flushTimer=null,this.isFlushing=!1,this.paused=!1,this.destroyed=!1,this.config={maxBatchSize:t.maxBatchSize||20,flushInterval:t.flushInterval||5e3},this.startFlushTimer()}pause(){this.paused=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}resume(){this.paused&&(this.paused=!1,this.startFlushTimer())}isPaused(){return this.paused}add(){et.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.paused||this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const t=et.getAll();if(0===t.length)return this.isFlushing=!1,void this.startFlushTimer();const e=t.slice(0,this.config.maxBatchSize),n=[],i=[];e.forEach(t=>{Array.isArray(t.data)?n.push(...t.data):n.push(t.data),i.push(t.id)});const s=e[e.length-1],r=s.url,o=s.headers;O.instance&&O.instance.config.debug&&console.log(JSON.stringify(n,null,2)),$({url:r,method:"POST",data:n,headers:o,callback:t=>{200===t.statusCode?i.forEach(t=>{et.dequeue(t)}):P(t.statusCode)?console.error("Failed to send batch events:",t):i.forEach(t=>{et.dequeue(t)}),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.destroyed||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{et.getAll().length>0&&this.triggerFlush()},this.config.flushInterval))}destroy(){this.destroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.paused||this.flush()}}let it=null;function st(){const t=O.instance;return!(!t||!t.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}function rt(){const t=O.instance;return!t||"function"!=typeof t.hasOptedOutCapturing||!t.hasOptedOutCapturing()}let ot=null;function at(){return I.isSupport()?(ot||(it||(it=new nt({maxBatchSize:20,flushInterval:5e3})),ot=it),ot):null}function ct(t,e,n){if(rt())return $({url:t,method:"POST",data:e.data,headers:e.headers,callback:t=>{if(200!==t.statusCode){if(!P(t.statusCode))return void(n&&et.dequeue(n));if(n&&et.incrementRetryCount(n)){const t=et.getItemById(n);if(t){const e=Math.min(1e3*Math.pow(2,t.retryCount),3e4);setTimeout(()=>{ct(t.url,{data:t.data,headers:t.headers},t.id)},e)}}}else n&&et.dequeue(n),e.callback&&e.callback(t.json)}})}function ut(t){return`${t.apiHost}/in/track`}function lt(t){return`${t.apiHost}/ab/evalall`}function ht(t){return{"Content-Type":"application/json",SourceToken:t.sourceToken}}function dt(t,e,n){O.instance&&O.instance.config.debug&&console.log(JSON.stringify(e.data,null,2));const i=et.enqueue(t,e.data,e.headers);return ct(t,{...e,callback:void 0},i)}function pt(){try{const t=sessionStorage.getItem("sensorswave_utm");if(!t)return{};const e=JSON.parse(t),n={};return Object.entries(e).forEach(([t,e])=>{null!=e&&""!==e&&(n[`$${t}`]=e)}),n}catch(t){return{}}}function gt(t){const e={};return Object.entries(t).forEach(([t,n])=>{if("function"==typeof n)try{const i=n();e[t]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",t,i)}else e[t]=n}),e}function ft(t={},e=!0){const n={...e?tt():{},...gt(N.getCommonProps()),...t},i=pt();return Object.keys(i).length>0&&Object.assign(n,i),n}function mt(t,e,n=!0){if(!st())return;if(!rt())return;const i={time:Date.now(),trace_id:N.getTraceId(),event:t.event,properties:ft(t.properties,n)},s=pt();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),t.user_properties&&(t.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...t.user_properties.$set},delete t.user_properties.$set),i.user_properties={...i.user_properties,...t.user_properties});const r=N.getLoginId(),o=N.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=ut(e),c=ht(e),u=!1!==e.batchSend&&at();u?(et.enqueue(a,[i],c),u.add()):dt(a,{data:[i],headers:c})}function Et({userProps:t,opts:e}){if(!st())return;if(!rt())return;const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:N.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:t,properties:ft()},r=ut(e),o=ht(e),a=at();if(!a)return dt(r,{data:[s],headers:o});et.enqueue(r,[s],o),a.add()}function _t(t){return t.typ===C.FEATURE_GATE||t.typ===C.FEATURE_CONFIG?`$feature_${t.id}`:t.typ===C.EXPERIMENT?`$exp_${t.id}`:""}function It(t){const e=t.typ;return[C.FEATURE_GATE,C.EXPERIMENT,C.FEATURE_CONFIG].includes(e)?{[_t(t)]:t.vid}:{}}function St(t){const e=t.typ;return e===C.FEATURE_GATE||e===C.FEATURE_CONFIG?{$feature_key:t.key,$feature_variant:t.vid}:e===C.EXPERIMENT?{$exp_key:t.key,$exp_variant:t.vid}:{}}function wt({isUnset:t=!1,data:e,opts:n}){if(!st())return;if(!rt())return;if(!e||u(e)||e.disable_impress)return;const i=N.getLoginId(),s=N.getAnonId();if(!i&&!s)return;const r=e.typ===C.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=t?{$unset:{[_t(e)]:null}}:{$set:{...It(e)}},mt({event:r,properties:St(e),user_properties:o},n)}const Ot="sensorswave_opt_out";class vt{constructor(t){this.persist=t}read(){if(this.persist)try{const t=I.get(Ot);return"0"===t||"1"!==t&&void 0}catch{return}}write(t){if(this.persist)try{I.set(Ot,t?"0":"1")}catch{}}}class bt{constructor({plugins:t,emitter:e,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=e,this.config=n,this.sdk=i,this.registerBuiltInPlugins(t),this.created(),this.emitter.on(b,()=>{this.init()})}registerBuiltInPlugins(t){for(let e=0,n=t.length;e<n;e++)this.registerPlugin(t[e])}registerPlugin(t){this.plugins.push(t)}getPlugins(){return this.plugins}getPlugin(t){return this.pluginInsMap[t]}created(){for(let t=0,e=this.plugins.length;t<e;t++){const e=this.plugins[t];if(!e.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new e({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[e.NAME]=n}}init(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.init&&e.init()}}destroy(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.destroy&&"function"==typeof e.destroy&&e.destroy()}this.pluginInsMap={},this.plugins=[]}}const yt=class{constructor({emitter:t,config:e,sdk:n}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;this.boundSend=()=>{mt({event:"$PageView",properties:{}},t)},this.sdk&&!0===this.sdk._postConsentInit||setTimeout(()=>{this.boundSend()},0),t.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=t=>{t!==location.href&&this.boundSend()},this.emitter.on(y,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(y,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};yt.NAME="pageview";let At=yt;const Rt=class{constructor({emitter:t,config:e,sdk:n}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this._skipFirstPageEnd=!1,this.emitter=t,this.config=e,this.sdk=n}__canCapture(){return!this.sdk||"function"!=typeof this.sdk.hasOptedOutCapturing||!this.sdk.hasOptedOutCapturing()}init(){this.pageId=Number(String(g()).slice(2,5)+String(g()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),this.sdk&&!0===this.sdk._postConsentInit&&(this._skipFirstPageEnd=!0),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(t){console.log(t)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title,this._skipFirstPageEnd=!1}pageEndHandler(){if(!0===this.pageHiddenStatus)return;if(!this.__canCapture())return;const t=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete t.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,mt({event:R,properties:t},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const t=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",t),this.eventListeners.push({target:window,event:"pageshow",handler:t})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(y,t=>{t!==location.href&&(this.url=t,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(t=>{if(`on${t}`in window){const e=()=>{if(this._skipFirstPageEnd)return this._skipFirstPageEnd=!1,void this.stopHeartBeatInterval();this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(t,e),this.eventListeners.push({target:window,event:t,handler:e})}})}addPageSwitchListener(){const t=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",t),this.eventListeners.push({target:document,event:"visibilitychange",handler:t})}addHeartBeatInterval(){I.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.sdk&&!0===this.sdk._postConsentInit&&!0===this._skipFirstPageEnd||(this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData())}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(t){if(!this.__canCapture())return;const e=this.getPageLeaveProperties();e.$time=Date.now(),"is_first_heartbeat"===t&&(e.$event_duration=3);const n={type:"track",event:R,properties:e,time:e.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,I.isSupport()&&I.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(t){I.isSupport()&&I.remove(t||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){if(this.__canCapture())for(let t=window.localStorage.length-1;t>=0;t--){const e=window.localStorage.key(t);if(e&&e!==`${this.storageName}-${this.pageId}`&&0===e.indexOf(`${this.storageName}-`)){const t=I.parse(e);i(t)&&Date.now()-t.time>t.heartbeat_interval_time+5e3&&(delete t.heartbeat_interval_time,t._flush_time=(new Date).getTime(),mt({event:R,properties:t?.properties},this.config),this.delHeartBeatData(e))}}}getPageLeaveProperties(){let t=(Date.now()-this.startTime)/1e3;(isNaN(t)||t<0||t>this.maxDuration)&&(t=0),t=Number(t.toFixed(3));const e={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:w(this.url)};return 0!==t&&(e.$event_duration=t),e}destroy(){this.eventListeners.forEach(({target:t,event:e,handler:n})=>{t.removeEventListener(e,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};Rt.NAME="pageleave";let Tt=Rt;const Ct=class{constructor({emitter:t,config:e,sdk:n}){this.eventSended=!1,this.emitter=t,this.config=e,this.sdk=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit)return;const t=()=>{let e=0;const n={};if(window.performance){e=function(){let t=0;if("function"==typeof performance.getEntriesByType){const e=performance.getEntriesByType("navigation");e.length>0&&(t=e[0].domContentLoadedEventEnd||0)}return t}();const t=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const t=performance.getEntries();let e=0;for(const n of t)"transferSize"in n&&(e+=n.transferSize);if("number"==typeof e&&e>=0&&e<10737418240)return Number((e/1024).toFixed(3))}}();t&&(n.$page_resource_size=t)}else console.warn("Performance API is not supported.");e>0&&!Number.isFinite(e)&&(n.$event_duration=Number((e/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,mt({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",t)};"complete"===document.readyState?t():window.addEventListener&&window.addEventListener("load",t)}};Ct.NAME="pageload";let Nt=Ct;function Pt(t,e){if(!l(t))return!1;const n=o(t.tagName)?t.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=t.getAttribute("name")||"",i.$element_id=t.getAttribute("id")||"",i.$element_class_name=o(t.className)?t.className:"",i.$element_target_url=t.getAttribute("href")||"",i.$element_content=function(t,e){return o(e)&&"input"===e.toLowerCase()?("button"===(n=t).type||"submit"===n.type)&&n.value||"":function(t,e){let n="",i="";return t.textContent?n=S(t.textContent):t.innerText&&(n=S(t.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==e&&"INPUT"!==e||(i=t.value||""),i}(t,e);var n}(t,n)||"",i.$element_selector=kt(t)||"",i.$element_path=function(t){let e=[];for(;t.parentNode&&l(t);){if(!o(t.tagName))return"";if(t.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.id)){e.unshift(t.tagName.toLowerCase()+"#"+t.id);break}if(t===document.body){e.unshift("body");break}e.unshift(t.tagName.toLowerCase()),t=t.parentNode}return e.join(" > ")}(t)||"";const s=function(t,e){const n=e.pageX||e.clientX+Lt().scrollLeft||e.offsetX+$t(t).targetEleX,i=e.pageY||e.clientY+Lt().scrollTop||e.offsetY+$t(t).targetEleY;return{$page_x:Ft(n),$page_y:Ft(i)}}(t,e);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function kt(t,e=[]){if(!(t&&t.parentNode&&t.parentNode.children&&o(t.tagName)))return"";e=Array.isArray(e)?e:[];const n=t.nodeName.toLowerCase();return t&&"body"!==n&&1==t.nodeType?(e.unshift(function(t){if(!t||!l(t)||!o(t.tagName))return"";let e=t.parentNode&&9==t.parentNode.nodeType?-1:function(t){if(!t.parentNode)return-1;let e=0;const n=t.tagName,i=t.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(t===i[s])return e;e++}return-1}(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~e?":nth-of-type("+(e+1)+")":"")}(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?e.join(" > "):kt(t.parentNode,e)):(e.unshift("body"),e.join(" > "))}function Lt(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function $t(t){if(document.documentElement.getBoundingClientRect){const e=t.getBoundingClientRect();return{targetEleX:e.left+Lt().scrollLeft||0,targetEleY:e.top+Lt().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Ft(t){return Number(Number(t).toFixed(3))}const xt=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(t){const e=t.target;if(!e)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(e.tagName))return;if("true"===e.getAttribute("sensorswave-disable"))return;mt({event:"$WebClick",properties:Pt(e,t)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};xt.NAME="webclick";let Bt=xt;const Mt=class{constructor({emitter:t,config:e,sdk:n}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;if(t.enableAB){if(this.sdk&&"function"==typeof this.sdk.hasOptedOutCapturing&&this.sdk.hasOptedOutCapturing())return;this.fastFetch().then(()=>{this.emitter.emit(A)}),t.abRefreshInterval<3e4&&(t.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},t.abRefreshInterval)}}async fastFetch(){const t=N.getABData(this.config.abRefreshInterval);return t&&t.length?(this.emitter.emit(A),Promise.resolve(t)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(t=>{!function({opts:t,cb:e}){if(!st())return void(e&&e({}));if(!rt())return void(e&&e({}));const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return void(e&&e({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...tt(),...gt(N.getCommonProps())}},sdk:"webjs",sdk_version:v};$({url:lt(t),method:"POST",data:s,headers:ht(t),callback:t=>{200!==t.statusCode?(console.error("Failed to fetch feature flags"),e&&e({})):e&&e(t.json)}})}({opts:this.config,cb:e=>{N.saveABData(e?.data?.results||[]),t(e),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(t){return await this.fastFetch().catch(console.warn),N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_GATE&&e.key==t)}async checkFeatureGate(t){const e=await this.getFeatureGate(t);return!!e&&(!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),!1):(wt({data:e,opts:this.config}),"fail"!==e.vid))}async getExperiment(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.EXPERIMENT&&e.key===t);return e?!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),{}):(wt({data:e,opts:this.config}),e?.value||{}):{}}async getFeatureConfig(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_CONFIG&&e.key===t);if(!e)return{};if(!e.hasOwnProperty("vid")&&e.key)return wt({isUnset:!0,data:e,opts:this.config}),{};wt({data:e,opts:this.config});const n=e?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Mt.NAME="abtest";let Dt=Mt;const Ht=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],Ut="sensorswave_utm",Xt=class t{constructor({sdk:t,emitter:e,config:n}){this.sdk=t,this.emitter=e,this.config=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit){let e=t.readFromSessionStorage();return e&&0!==Object.keys(e).length||(e=t.captureAndStore(this.config?.debug)),void this.scheduleInitialUTM(e)}const e=t.getUTMFromURL();t.saveToSessionStorage(e,this.config?.debug),this.scheduleInitialUTM(e)}scheduleInitialUTM(t){setTimeout(()=>{this.sendInitialUTM(t)},0)}static getUTMFromURL(){try{const t=new URLSearchParams(window.location.search),e={};return Ht.forEach(n=>{const i=t.get(n);i&&(e[n]=i)}),e}catch(e){return t.getUTMFromURLFallback()}}static getUTMFromURLFallback(){const t={};return window.location.search.substring(1).split("&").forEach(e=>{const[n,i]=e.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";Ht.includes(s)&&(t[s]=r)}),t}static readFromSessionStorage(){try{const t=sessionStorage.getItem(Ut);if(!t)return{};const e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch(t){return{}}}static saveToSessionStorage(t,e=!1){try{sessionStorage.setItem(Ut,JSON.stringify(t))}catch(n){e&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",n)}}static captureAndStore(e=!1){const n=t.getUTMFromURL();return t.saveToSessionStorage(n,e),n}sendInitialUTM(t){const e={};Ht.forEach(n=>{e[`$initial_${n}`]=null!=t[n]?t[n]:""});try{this.sdk.profileSetOnce(e)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};Xt.NAME="UTM";let jt=Xt;const qt=1e3,Wt=/^\s*(?:async\s+)?at\s+(?:(.+)\s+\()?(.+?):(\d+):(\d+)\)?$/,Gt=/^(?:(.*)@)?(.+?):(\d+):(\d+)$/;function zt(t){let e=t;try{const t=location.origin;t&&0===e.indexOf(t)&&(e=e.substring(t.length))}catch(s){}const n=e.indexOf("?");n>-1&&(e=e.substring(0,n));const i=e.indexOf("#");return i>-1&&(e=e.substring(0,i)),e}function Yt(t){return t.map(t=>({platform:"web:javascript",filename:zt(t.file),function:t.fn||"?",lineno:Number(t.line),colno:Number(t.col),abs_path:Kt(t.file,1e3)}))}function Kt(t,e){return t.length>e?t.substring(0,e):t}function Jt(t){let e;if("string"==typeof t)e=t;else if(null!==t&&"object"==typeof t){try{e=JSON.stringify(t)}catch(n){e=Object.prototype.toString.call(t)}e||(e=Object.prototype.toString.call(t))}else e=String(t);return Kt(e,qt)}function Zt(t){const{frames:e,headerType:n}=function(t){const e=[];let n="";if(!t||"string"!=typeof t)return{frames:e,headerType:n};const i=t.split(/\r?\n/);for(let s=0;s<i.length;s++){const t=i[s];if(!t||t.length>1024)continue;const r=t.match(Wt),o=r?null:t.match(Gt),a=r||o;if(a)e.push({fn:a[1]||"?",file:a[2],line:a[3],col:a[4]});else if(0===s){const e=t.indexOf(":");e>0&&(n=t.substring(0,e).trim())}if(e.length>=30)break}return{frames:e,headerType:n}}(t&&t.stack);let i=t&&t.name||n||"Error";return i=Kt(String(i),200),{$exception_level:"error",$exception_type:i,$exception_message:Kt(String(t&&t.message||""),qt),$exception_frames:Yt(e)}}function Qt(t,e,n,i){let s=[];return e&&(s=[{platform:"web:javascript",filename:zt(e),function:"?",lineno:n||0,colno:i||0,abs_path:Kt(e,1e3)}]),{$exception_level:"error",$exception_type:"Error",$exception_message:Kt(String(t||""),qt),$exception_frames:s}}class Vt{constructor(t=10,e=1,n=1e4){this.buckets=new Map,this.bucketSize=t,this.refillRate=e,this.refillInterval=n}allow(t){const e=Date.now();let n=this.buckets.get(t);if(n){if(e>n.lastRefill){const t=Math.floor((e-n.lastRefill)/this.refillInterval)*this.refillRate;t>0&&(n.tokens=Math.min(this.bucketSize,n.tokens+t),n.lastRefill+=t/this.refillRate*this.refillInterval)}}else n={tokens:this.bucketSize,lastRefill:e},this.buckets.set(t,n);return n.tokens>=1&&(n.tokens-=1,!0)}reset(){this.buckets.clear()}}const te=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleError=null,this.boundHandleRejection=null,this.rateLimiter=new Vt,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleError=this.handleError.bind(this),this.boundHandleRejection=this.handleRejection.bind(this),window.addEventListener("error",this.boundHandleError,!0),window.addEventListener("unhandledrejection",this.boundHandleRejection),this.isInitialized=!0)}handleError(t){try{const e=t.target;let n;if(e&&e!==window&&e.tagName)n=function(t){const e=t,n=(e.tagName||"").toLowerCase(),i=Kt(String(e.src||e.href||""),qt);return{$exception_level:"error",$exception_type:"ResourceLoadError",$exception_message:`Failed to load <${n}>${i?` from ${i}`:""}`,$exception_frames:[]}}(e);else{const e=t;n=e.error instanceof Error?Zt(e.error):Qt(String(e.message||""),e.filename,e.lineno,e.colno)}this.send(n)}catch(e){}}handleRejection(t){try{const e=t.reason;this.send(function(t){return t instanceof Error?Zt(t):{$exception_level:"error",$exception_type:"UnhandledRejection",$exception_message:Jt(t),$exception_frames:[]}}(e))}catch(e){}}send(t){t.$exception_message&&this.rateLimiter.allow(t.$exception_type)&&mt({event:T,properties:t},this.config)}destroy(){this.boundHandleError&&(window.removeEventListener("error",this.boundHandleError,!0),this.boundHandleError=null),this.boundHandleRejection&&(window.removeEventListener("unhandledrejection",this.boundHandleRejection),this.boundHandleRejection=null),this.rateLimiter.reset(),this.isInitialized=!1}};te.NAME="exception";let ee=te;const ne=[],ie={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1,enableErrorTrack:!1,enableCrashTrack:!1,optOutCapturing:!1,persistOptOut:!1};return new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new t,this.pluginCore={},this.commonProps={},this.spaCleanup=null,this._optOutCapturing=!1,this.consentStorage=new vt(!1),this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance=this}init(t,e={}){return this.inited?this:(O.instance=this,e.sourceToken=t,this.mergeConfig(e),this.consentStorage=new vt(!0===this.config.persistOptOut),this._optOutCapturing?this.consentStorage.write(!0):!0===this.config.optOutCapturing?(this._optOutCapturing=!0,this.consentStorage.write(!0)):!0===this.consentStorage.read()&&(this._optOutCapturing=!0),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0,this._optOutCapturing?(jt.captureAndStore(this.config.debug),this.eventEmitter.emit(b),this.inited=!0,this):(this.__setupAfterConsent(),this.eventEmitter.emit(b),this.inited=!0,this))}__setupAfterConsent(){if(this._setupAfterConsentDone)return;this._setupAfterConsentDone=!0;const t=this.config;ne.length=0,N.init(t.crossSubdomainCookie),t.anonId&&N.setAnonId(t.anonId),function(){if(window._swFailedRequestsInitialized)return;window._swFailedRequestsInitialized=!0;const t=O.instance;t&&"function"==typeof t.hasOptedOutCapturing&&t.hasOptedOutCapturing()||t&&!0===t._postConsentInit||function(){const t=et.getAll();if(0!==t.length)for(let e=0,n=t.length;e<n;e+=10){const n=t.slice(e,e+10),i=[],s=[];n.forEach(t=>{Array.isArray(t.data)?i.push(...t.data):i.push(t.data),s.push(t.id)});const r=n[n.length-1],o=r.url,a=r.headers;$({url:o,method:"POST",data:i,headers:a,callback:t=>{200!==t.statusCode?(console.error("Failed to send batch stored requests:",t),P(t.statusCode)||s.forEach(t=>{et.dequeue(t)})):s.forEach(t=>{et.dequeue(t)})}})}}()}(),ne.push(jt),t.autoCapture&&this.autoTrack(),t.enableAB&&ne.push(Dt),t.enableClickTrack&&ne.push(Bt),t.enableCrashTrack&&t.debug&&console.warn("[SensorsWave] enableCrashTrack 仅在 app 宿主环境生效,当前 Web 环境不采集 crash"),t.enableErrorTrack&&ne.push(ee),this.pluginCore=new bt({plugins:ne,emitter:this.eventEmitter,config:t,sdk:this}),this.spaCleanup=function(t){let e=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){t(e),e=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),t(e),e=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),t(e),e=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(t=>{this.eventEmitter.emit(y,t)})}mergeConfig(t){this.config={...ie,...t}}__canCapture(){return this.inited&&!this._optOutCapturing}track(t){this.__canCapture()&&function(t,e){if(!st())return;if(!rt())return;const n={...t};n.time||(n.time=Date.now()),n.login_id||(n.login_id=N.getLoginId()),n.anon_id||(n.anon_id=N.getAnonId()),n.trace_id||(n.trace_id=N.getTraceId()),n.properties={...tt(),...gt(N.getCommonProps()),...n.properties};const i=ut(e),s=ht(e),r=!1!==e.batchSend&&at();if(!r)return dt(i,{data:[n],headers:s});et.enqueue(i,[n],s),r.add()}(t,this.config)}trackEvent(t,e){this.__canCapture()&&mt({event:t,properties:e},this.config)}trackException(t,e){if(!this.__canCapture())return;const n={...e||{},...t instanceof Error?Zt(t):Qt(String(t))};mt({event:T,properties:n},this.config)}autoTrack(){ne.push(At,Nt,Tt)}profileSet(t){this.__canCapture()&&Et({userProps:{$set:t},opts:this.config})}profileSetOnce(t){this.__canCapture()&&Et({userProps:{$set_once:t},opts:this.config})}profileIncrement(t){this.__canCapture()&&Et({userProps:{$increment:t},opts:this.config})}profileAppend(t){this.__canCapture()&&Et({userProps:{$append:t},opts:this.config})}profileUnion(t){this.__canCapture()&&Et({userProps:{$union:t},opts:this.config})}profileUnset(t){if(!this.__canCapture())return;const e={};r(t)?t.forEach(function(t){e[t]=null}):e[t]=null,Et({userProps:{$unset:e},opts:this.config})}profileDelete(){this.__canCapture()&&Et({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(t){if(!i(t))return console.warn("Commmon Properties must be an object!");this.commonProps=t,N.setCommonProps(this.commonProps)}clearCommonProperties(t){if(!r(t))return console.warn("Commmon Properties to be cleared must be an array!");t.forEach(t=>{delete this.commonProps[t]}),N.setCommonProps(this.commonProps)}identify(t){this.__canCapture()&&(N.setLoginId(t),function(t){if(!st())return;if(!rt())return;const e=N.getLoginId(),n=N.getAnonId();if(!e||!n)return;const i={time:Date.now(),trace_id:N.getTraceId(),event:"$Identify",login_id:e,anon_id:n,properties:ft()},s=ut(t),r=ht(t),o=at();if(!o)return dt(s,{data:[i],headers:r});et.enqueue(s,[i],r),o.add()}(this.config))}setLoginId(t){this.__canCapture()&&N.setLoginId(t)}getAnonId(){return this.__canCapture()?N.getAnonId():""}setAnonId(t){this.__canCapture()&&N.setAnonId(t)}getLoginId(){return this.__canCapture()?N.getLoginId():""}reset(t=!1){this.__canCapture()&&(N.clearLoginId(),t&&N.resetAnonId())}checkFeatureGate(t){if(!this.__canCapture())return Promise.resolve(!1);const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.checkFeatureGate(t):Promise.reject("AB is disabled")}getExperiment(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getExperiment(t):Promise.reject("AB is disabled")}getFeatureConfig(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getFeatureConfig(t):Promise.reject("AB is disabled")}optOutCapturing(){this._optOutCapturing=!0,this.consentStorage.write(!0),ot&&ot.pause()}optInCapturing(){if(this._optOutCapturing=!1,this.consentStorage.write(!1),ot&&ot.resume(),this.inited&&!this._setupAfterConsentDone){this._postConsentInit=!0;try{this.__setupAfterConsent(),this.eventEmitter.emit(b)}finally{this._postConsentInit=!1}}}hasOptedOutCapturing(){return this._optOutCapturing}destroy(){ot&&(ot.destroy(),ot=null),"undefined"!=typeof window&&(window._swFailedRequestsInitialized=!1),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.pluginCore={},this.eventEmitter&&this.eventEmitter.removeAllListeners(),this.consentStorage=new vt(!0===this.config?.persistOptOut),this._optOutCapturing=!1,this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance===this&&(O.instance=null)}}});
|
package/dist/types/Api.d.ts
CHANGED
|
@@ -46,6 +46,8 @@ export interface SensorsWaveConfig {
|
|
|
46
46
|
abRefreshInterval?: number;
|
|
47
47
|
enableClickTrack?: boolean;
|
|
48
48
|
batchSend?: boolean;
|
|
49
|
+
enableErrorTrack?: boolean;
|
|
50
|
+
enableCrashTrack?: boolean;
|
|
49
51
|
anonId?: string;
|
|
50
52
|
optOutCapturing?: boolean;
|
|
51
53
|
persistOptOut?: boolean;
|
|
@@ -54,6 +56,7 @@ export interface SensorsWaveConfig {
|
|
|
54
56
|
interface SensorsWaveInterface {
|
|
55
57
|
trackEvent(e: string, p?: Object): void;
|
|
56
58
|
track(e: AdvanceEvent): void;
|
|
59
|
+
trackException(error: Error | string, properties?: Record<string, any>): void;
|
|
57
60
|
profileSet(p: Object): void;
|
|
58
61
|
profileSetOnce(p: Object): void;
|
|
59
62
|
profileIncrement(p: Object): void;
|
|
@@ -66,6 +69,7 @@ interface SensorsWaveInterface {
|
|
|
66
69
|
identify(u: string | number): void;
|
|
67
70
|
setLoginId(u: string | number): void;
|
|
68
71
|
setAnonId(u: string | number): void;
|
|
72
|
+
reset(resetAnonymousId?: boolean): void;
|
|
69
73
|
checkFeatureGate(key: string): Promise<boolean>;
|
|
70
74
|
getExperiment(key: string): Promise<Object>;
|
|
71
75
|
getFeatureConfig(key: string): Promise<Object>;
|
|
@@ -23,6 +23,8 @@ declare const store: {
|
|
|
23
23
|
save: () => void;
|
|
24
24
|
init: (crossSubdomain: boolean | undefined) => void;
|
|
25
25
|
setLoginId(id: string): void;
|
|
26
|
+
clearLoginId(): void;
|
|
27
|
+
resetAnonId(): void;
|
|
26
28
|
setAnonId(id: string): void;
|
|
27
29
|
saveABData(data: any): void;
|
|
28
30
|
getABData(expireTime?: number): ABData[];
|
|
@@ -21,6 +21,7 @@ declare class SensorsWave {
|
|
|
21
21
|
private __canCapture;
|
|
22
22
|
track(e: SensorsWaveSendEvent): void;
|
|
23
23
|
trackEvent(event: string, properties: Record<string, any>): void;
|
|
24
|
+
trackException(error: Error | string, properties?: Record<string, any>): void;
|
|
24
25
|
private autoTrack;
|
|
25
26
|
profileSet(p: Object): void;
|
|
26
27
|
profileSetOnce(p: Object): void;
|
|
@@ -36,6 +37,7 @@ declare class SensorsWave {
|
|
|
36
37
|
getAnonId(): string;
|
|
37
38
|
setAnonId(anonId: string): void;
|
|
38
39
|
getLoginId(): string;
|
|
40
|
+
reset(resetAnonymousId?: boolean): void;
|
|
39
41
|
checkFeatureGate(key: string): any;
|
|
40
42
|
getExperiment(key: string): any;
|
|
41
43
|
getFeatureConfig(key: string): any;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { EventEmitter } from '../../../core';
|
|
2
|
+
import { SensorsWaveConfig } from '../../types/Api';
|
|
3
|
+
export declare class Exception {
|
|
4
|
+
static NAME: string;
|
|
5
|
+
private emitter;
|
|
6
|
+
private config;
|
|
7
|
+
private isInitialized;
|
|
8
|
+
private boundHandleError;
|
|
9
|
+
private boundHandleRejection;
|
|
10
|
+
private rateLimiter;
|
|
11
|
+
constructor({ emitter, config }: {
|
|
12
|
+
emitter: EventEmitter;
|
|
13
|
+
config: SensorsWaveConfig;
|
|
14
|
+
});
|
|
15
|
+
init(): void;
|
|
16
|
+
private handleError;
|
|
17
|
+
private handleRejection;
|
|
18
|
+
private send;
|
|
19
|
+
destroy(): void;
|
|
20
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
type StackFrame = {
|
|
2
|
+
fn: string;
|
|
3
|
+
file: string;
|
|
4
|
+
line: string;
|
|
5
|
+
col: string;
|
|
6
|
+
};
|
|
7
|
+
export type ExceptionPlatform = 'web:javascript' | 'java' | 'dart' | 'hermes' | 'ios';
|
|
8
|
+
export type ExceptionFrame = {
|
|
9
|
+
platform: ExceptionPlatform;
|
|
10
|
+
filename?: string;
|
|
11
|
+
function?: string;
|
|
12
|
+
lineno?: number;
|
|
13
|
+
colno?: number;
|
|
14
|
+
abs_path?: string;
|
|
15
|
+
module?: string;
|
|
16
|
+
};
|
|
17
|
+
export type ExceptionProps = {
|
|
18
|
+
$exception_level: string;
|
|
19
|
+
$exception_type: string;
|
|
20
|
+
$exception_message: string;
|
|
21
|
+
$exception_frames: ExceptionFrame[];
|
|
22
|
+
};
|
|
23
|
+
export declare function parseStack(stack?: string): {
|
|
24
|
+
frames: StackFrame[];
|
|
25
|
+
headerType: string;
|
|
26
|
+
};
|
|
27
|
+
export declare function toExceptionFrames(frames: StackFrame[]): ExceptionFrame[];
|
|
28
|
+
export declare function buildErrorProps(err: Error): ExceptionProps;
|
|
29
|
+
export declare function buildStringProps(message: string, filename?: string, lineno?: number, colno?: number): ExceptionProps;
|
|
30
|
+
export declare function buildRejectionProps(reason: unknown): ExceptionProps;
|
|
31
|
+
export declare function buildResourceProps(target: Element): ExceptionProps;
|
|
32
|
+
export declare class ExceptionRateLimiter {
|
|
33
|
+
private bucketSize;
|
|
34
|
+
private refillRate;
|
|
35
|
+
private refillInterval;
|
|
36
|
+
private buckets;
|
|
37
|
+
constructor(bucketSize?: number, refillRate?: number, refillInterval?: number);
|
|
38
|
+
allow(key: string): boolean;
|
|
39
|
+
reset(): void;
|
|
40
|
+
}
|
|
41
|
+
export {};
|
|
@@ -20,6 +20,7 @@ interface RequestContent {
|
|
|
20
20
|
body: string | BlobPart;
|
|
21
21
|
}
|
|
22
22
|
export declare function appendUrlParameters(url: string, params: Record<string, any>): string;
|
|
23
|
+
export declare function isRetryableStatusCode(statusCode: number): boolean;
|
|
23
24
|
export declare function serializeJson(data: any, space?: string | number): string;
|
|
24
25
|
export declare function prepareRequestBody(options: HttpRequestOptions): RequestContent | undefined;
|
|
25
26
|
export declare function request(_options: HttpRequestOptions): void;
|