@bluenath/engage 1.0.1 → 1.0.3

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.
@@ -7,7 +7,10 @@ export declare class EventQueue {
7
7
  private transport;
8
8
  private readonly STORAGE_KEY;
9
9
  private isFlushing;
10
+ private flushInterval;
11
+ private retryCount;
10
12
  constructor(transport: Transport);
13
+ private startTimer;
11
14
  enqueue(event: AnalyticsEvent): void;
12
15
  private save;
13
16
  private load;
@@ -0,0 +1,9 @@
1
+ import { EngagePro } from './Analytics';
2
+
3
+ export declare class PerformanceMonitor {
4
+ private analytics;
5
+ private metrics;
6
+ constructor(analytics: EngagePro);
7
+ private observe;
8
+ private logMetric;
9
+ }
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=Object.defineProperty,t=(t,n,r)=>((t,n,r)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r)(t,"symbol"!=typeof n?n+"":n,r);Object.defineProperties(exports,{t:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const n=require("react");let r;const i=new Uint8Array(16);function o(){if(!r&&(r="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!r))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return r(i)}const s=[];for(let E=0;E<256;++E)s.push((E+256).toString(16).slice(1));const a={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function c(e,t,n){if(a.randomUUID&&!e)return a.randomUUID();const r=(e=e||{}).random||(e.rng||o)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return s[e[t+0]]+s[e[t+1]]+s[e[t+2]]+s[e[t+3]]+"-"+s[e[t+4]]+s[e[t+5]]+"-"+s[e[t+6]]+s[e[t+7]]+"-"+s[e[t+8]]+s[e[t+9]]+"-"+s[e[t+10]]+s[e[t+11]]+s[e[t+12]]+s[e[t+13]]+s[e[t+14]]+s[e[t+15]]}(r)}const u=e=>{let t=2166136261;const n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return("0000000"+(t>>>0).toString(16)).substr(-8)};class l{constructor(e="local"){t(this,"memoryStore",{}),t(this,"keyPrefix","engage_"),t(this,"domain"),this.type=e,this.domain=this.getCookieDomain()}getItem(e){const t=this.keyPrefix+e;if(this.memoryStore.hasOwnProperty(t))return this.memoryStore[t];try{if("local"===this.type&&this.isBrowser())return window.localStorage.getItem(t);if("cookie"===this.type&&this.isBrowser())return this.getCookie(t)}catch(n){return null}return null}setItem(e,t){const n=this.keyPrefix+e;this.memoryStore[n]=t;try{"local"===this.type&&this.isBrowser()?window.localStorage.setItem(n,t):"cookie"===this.type&&this.isBrowser()&&this.setCookie(n,t,365)}catch(r){this.isQuotaError(r)&&(this.type="memory")}}removeItem(e){const t=this.keyPrefix+e;delete this.memoryStore[t];try{"local"===this.type&&this.isBrowser()?window.localStorage.removeItem(t):"cookie"===this.type&&this.isBrowser()&&this.setCookie(t,"",-1)}catch(n){}}getCookie(e){const t=e+"=",n=document.cookie.split(";");for(let r=0;r<n.length;r++){let e=n[r];for(;" "===e.charAt(0);)e=e.substring(1,e.length);if(0===e.indexOf(t))return decodeURIComponent(e.substring(t.length,e.length))}return null}setCookie(e,t,n){let r="";if(n){const e=new Date;e.setTime(e.getTime()+24*n*60*60*1e3),r="; expires="+e.toUTCString()}document.cookie=`${e}=${encodeURIComponent(t)}${r}; path=/; domain=${this.domain}; SameSite=Lax; Secure`}getCookieDomain(){if(!this.isBrowser())return"";const e=window.location.hostname,t=e.split(".");return 1===t.length||"localhost"===e?"":t.length>2?"."+t.slice(-2).join("."):"."+e}isBrowser(){try{return"undefined"!=typeof window&&void 0!==window.document}catch(e){return!1}}isQuotaError(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)}}class f{constructor(e){t(this,"storage"),t(this,"SESSION_TIMEOUT",18e5),t(this,"deviceId"),t(this,"sessionId"),t(this,"userId",null),t(this,"currentUrl"),t(this,"referrer"),this.storage=new l(e.persistence),this.deviceId=this.getOrSetDeviceId(),this.sessionId="",this.manageSession(),"undefined"!=typeof window?(this.currentUrl=window.location.href,this.referrer=document.referrer,this.listenToHistory()):(this.currentUrl="",this.referrer="")}getOrSetDeviceId(){const e=this.storage.getItem("device_id");if(e)return e;const t=(()=>{if("undefined"==typeof window)return"server-side-id";const e=navigator,t=window.screen,n={userAgent:e.userAgent||"",screenRes:`${t.width}x${t.height}`,colorDepth:t.colorDepth||0,timezone:(new Date).getTimezoneOffset(),language:e.language||"en-US",platform:e.platform||"unknown",hardwareConcurrency:e.hardwareConcurrency||1,deviceMemory:e.deviceMemory||0},r=[n.platform,n.language,n.screenRes,n.colorDepth,n.timezone,n.hardwareConcurrency,n.deviceMemory].join("|");return`${u(r)}-${u(n.userAgent)}`})();return this.storage.setItem("device_id",t),t}manageSession(){const e=Date.now(),t=this.storage.getItem("session_id"),n=parseInt(this.storage.getItem("last_activity")||"0");if(!t||e-n>this.SESSION_TIMEOUT?(this.sessionId=`sess_${e}_${Math.random().toString(36).substr(2,9)}`,this.storage.setItem("session_id",this.sessionId)):this.sessionId=t,this.storage.setItem("last_activity",e.toString()),"undefined"!=typeof window){const e=()=>this.storage.setItem("last_activity",Date.now().toString());window.addEventListener("click",e),window.addEventListener("scroll",e)}}listenToHistory(){const e=history.pushState;history.pushState=(...t)=>{e.apply(history,t),this.handleUrlChange()},window.addEventListener("popstate",()=>this.handleUrlChange())}handleUrlChange(){const e=window.location.href;e!==this.currentUrl&&(this.referrer=this.currentUrl,this.currentUrl=e)}getPayload(){var e;return{library:{name:"@engagepro/analytics",version:"2.0.0"},user:{anonymousId:this.deviceId,id:this.userId},session:{id:this.sessionId,startTime:parseInt(this.sessionId.split("_")[1]||Date.now().toString())},page:{path:"undefined"!=typeof window?window.location.pathname:"",referrer:this.referrer,title:"undefined"!=typeof document?document.title:"",search:"undefined"!=typeof window?window.location.search:"",url:this.currentUrl},network:{online:"undefined"==typeof navigator||navigator.onLine,downlink:null==(e=navigator.connection)?void 0:e.downlink},screen:{width:"undefined"!=typeof screen?screen.width:0,height:"undefined"!=typeof screen?screen.height:0,density:"undefined"!=typeof window?window.devicePixelRatio:1},device:{fingerprint:this.deviceId,type:this.getDeviceType(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"server"},locale:"undefined"!=typeof navigator?navigator.language:"en-US",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}getDeviceType(){if("undefined"==typeof navigator)return"desktop";const e=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(e)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated/.test(e)?"mobile":"desktop"}}class d{constructor(e){t(this,"queue",[]),t(this,"storage"),t(this,"transport"),t(this,"STORAGE_KEY","engage_queue_v1"),t(this,"isFlushing",!1),this.transport=e,this.storage=new l("local"),this.load(),"undefined"!=typeof window&&(window.addEventListener("online",()=>this.flush()),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.flush()})),setInterval(()=>this.flush(),3e3)}enqueue(e){this.queue.push(e),this.save(),this.queue.length>=10&&this.flush()}save(){this.storage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}load(){const e=this.storage.getItem(this.STORAGE_KEY);if(e)try{this.queue=JSON.parse(e)}catch(t){this.queue=[]}}async flush(){if(0===this.queue.length||this.isFlushing)return;if("undefined"!=typeof navigator&&!navigator.onLine)return;this.isFlushing=!0;const e=[...this.queue];this.queue=[],this.save();try{await this.transport.send(e)||(this.queue=[...e,...this.queue],this.save())}catch(t){this.queue=[...e,...this.queue],this.save()}finally{this.isFlushing=!1}}}class p{constructor(e){this.apiEndpoint=e}async send(e){const t=JSON.stringify({batch:e,sentAt:(new Date).toISOString()});if("undefined"!=typeof navigator&&navigator.sendBeacon&&t.length<6e4){const e=new Blob([t],{type:"application/json"});if(navigator.sendBeacon(this.apiEndpoint,e))return!0}try{return(await fetch(this.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0})).ok}catch(n){return!1}}}class h{constructor(e){t(this,"config"),t(this,"context"),t(this,"queue"),t(this,"transport"),t(this,"identify",(e,t)=>{this.context.userId=e,this.processEvent({event:"Identify",properties:{traits:t},standardEvent:"LOGIN",intent:"identity",confidence:1})}),t(this,"page",(e,t)=>{const n=this.context.getPayload().page;this.processEvent({event:e||n.title||"Unknown Page",properties:{path:n.path,referrer:n.referrer,title:n.title,...t},standardEvent:"PAGE_VIEW",intent:"navigation",confidence:1})}),t(this,"track",(e,t,n)=>{this.processEvent({event:e,properties:t||{},...n})}),this.config=e,this.transport=new p(e.apiHost||"http://localhost:3000/v1/ingest"),this.context=new f({persistence:e.tracking.useCookies?"cookie":"local"}),this.queue=new d(this.transport)}processEvent(e){const t=this.context.getPayload(),n={event:e.event,properties:e.properties,standardEvent:e.standardEvent,intent:e.intent,confidence:e.confidence,rawLabel:e.rawLabel,timestamp:(new Date).toISOString(),messageId:c(),writeKey:this.config.writeKey,userId:t.user.id||void 0,anonymousId:t.user.anonymousId,context:t};this.config.debug,this.queue.enqueue(n)}}var y,v,m={exports:{}},w={},b={};"production"===process.env.NODE_ENV?m.exports=function(){if(y)return w;y=1;var e=n,t=Symbol.for("react.element"),r=Symbol.for("react.fragment"),i=Object.prototype.hasOwnProperty,o=e.i.ReactCurrentOwner,s={key:!0,ref:!0,o:!0,u:!0};function a(e,n,r){var a,c={},u=null,l=null;for(a in void 0!==r&&(u=""+r),void 0!==n.key&&(u=""+n.key),void 0!==n.ref&&(l=n.ref),n)i.call(n,a)&&!s.hasOwnProperty(a)&&(c[a]=n[a]);if(e&&e.defaultProps)for(a in n=e.defaultProps)void 0===c[a]&&(c[a]=n[a]);return{$$typeof:t,type:e,key:u,ref:l,props:c,l:o.current}}return w.Fragment=r,w.jsx=a,w.jsxs=a,w}():m.exports=(v||(v=1,"production"!==process.env.NODE_ENV&&function(){var e,t=n,r=Symbol.for("react.element"),i=Symbol.for("react.portal"),o=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),c=Symbol.for("react.provider"),u=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),y=Symbol.for("react.offscreen"),v=Symbol.iterator,m=t.i;function w(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];!function(e,t,n){var r=m.ReactDebugCurrentFrame.getStackAddendum();""!==r&&(t+="%s",n=n.concat([r]));var i=n.map(function(e){return String(e)});i.unshift("Warning: "+t),Function.prototype.apply.call(console.error,console,i)}(0,e,n)}function g(e){return e.displayName||"Context"}function k(e){if(null==e)return null;if("number"==typeof e.tag&&w("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),"function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case o:return"Fragment";case i:return"Portal";case a:return"Profiler";case s:return"StrictMode";case f:return"Suspense";case d:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case u:return g(e)+".Consumer";case c:return g(e.p)+".Provider";case l:return function(e,t,n){var r=e.displayName;if(r)return r;var i=t.displayName||t.name||"";return""!==i?n+"("+i+")":n}(e,e.render,"ForwardRef");case p:var t=e.displayName||null;return null!==t?t:k(e.type)||"Memo";case h:var n=e,r=n.h,y=n.v;try{return k(y(r))}catch(v){return null}}return null}e=Symbol.for("react.module.reference");var S,E,_,O,R,j,I,T=Object.assign,C=0;function A(){}A.m=!0;var D,x=m.ReactCurrentDispatcher;function P(e,t,n){if(void 0===D)try{throw Error()}catch(i){var r=i.stack.trim().match(/\n( *(at )?)/);D=r&&r[1]||""}return"\n"+D+e}var U,F=!1,M="function"==typeof WeakMap?WeakMap:Map;function $(e,t){if(!e||F)return"";var n,r=U.get(e);if(void 0!==r)return r;F=!0;var i,o=Error.prepareStackTrace;Error.prepareStackTrace=void 0,i=x.current,x.current=null,function(){if(0===C){S=console.log,E=console.info,_=console.warn,O=console.error,R=console.group,j=console.groupCollapsed,I=console.groupEnd;var e={configurable:!0,enumerable:!0,value:A,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}C++}();try{if(t){var s=function(){throw Error()};if(Object.defineProperty(s.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(s,[])}catch(h){n=h}Reflect.construct(e,[],s)}else{try{s.call()}catch(h){n=h}e.call(s.prototype)}}else{try{throw Error()}catch(h){n=h}e()}}catch(y){if(y&&n&&"string"==typeof y.stack){for(var a=y.stack.split("\n"),c=n.stack.split("\n"),u=a.length-1,l=c.length-1;u>=1&&l>=0&&a[u]!==c[l];)l--;for(;u>=1&&l>=0;u--,l--)if(a[u]!==c[l]){if(1!==u||1!==l)do{if(u--,--l<0||a[u]!==c[l]){var f="\n"+a[u].replace(" at new "," at ");return e.displayName&&f.includes("<anonymous>")&&(f=f.replace("<anonymous>",e.displayName)),"function"==typeof e&&U.set(e,f),f}}while(u>=1&&l>=0);break}}}finally{F=!1,x.current=i,function(){if(0===--C){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:T({},e,{value:S}),info:T({},e,{value:E}),warn:T({},e,{value:_}),error:T({},e,{value:O}),group:T({},e,{value:R}),groupCollapsed:T({},e,{value:j}),groupEnd:T({},e,{value:I})})}C<0&&w("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}(),Error.prepareStackTrace=o}var d=e?e.displayName||e.name:"",p=d?P(d):"";return"function"==typeof e&&U.set(e,p),p}function N(e,t,n){if(null==e)return"";if("function"==typeof e)return $(e,!(!(r=e.prototype)||!r.isReactComponent));var r;if("string"==typeof e)return P(e);switch(e){case f:return P("Suspense");case d:return P("SuspenseList")}if("object"==typeof e)switch(e.$$typeof){case l:return $(e.render,!1);case p:return N(e.type,t,n);case h:var i=e,o=i.h,s=i.v;try{return N(s(o),t,n)}catch(a){}}return""}U=new M;var q=Object.prototype.hasOwnProperty,L={},K=m.ReactDebugCurrentFrame;function H(e){if(e){var t=e.l,n=N(e.type,e.k,t?t.type:null);K.setExtraStackFrame(n)}else K.setExtraStackFrame(null)}var B=Array.isArray;function G(e){return B(e)}function J(e){return""+e}function W(e){if(function(e){try{return J(e),!1}catch(t){return!0}}(e))return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",function(e){return"function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object"}(e)),J(e)}var Y,z,Q=m.ReactCurrentOwner,V={key:!0,ref:!0,o:!0,u:!0};var X,Z=m.ReactCurrentOwner,ee=m.ReactDebugCurrentFrame;function te(e){if(e){var t=e.l,n=N(e.type,e.k,t?t.type:null);ee.setExtraStackFrame(n)}else ee.setExtraStackFrame(null)}function ne(e){return"object"==typeof e&&null!==e&&e.$$typeof===r}function re(){if(Z.current){var e=k(Z.current.type);if(e)return"\n\nCheck the render method of `"+e+"`."}return""}X=!1;var ie={};function oe(e,t){if(e.S&&!e.S.validated&&null==e.key){e.S.validated=!0;var n=function(e){var t=re();if(!t){var n="string"==typeof e?e:e.displayName||e.name;n&&(t="\n\nCheck the top-level render call using <"+n+">.")}return t}(t);if(!ie[n]){ie[n]=!0;var r="";e&&e.l&&e.l!==Z.current&&(r=" It was passed a child from "+k(e.l.type)+"."),te(e),w('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',n,r),te(null)}}}function se(e,t){if("object"==typeof e)if(G(e))for(var n=0;n<e.length;n++){var r=e[n];ne(r)&&oe(r,t)}else if(ne(e))e.S&&(e.S.validated=!0);else if(e){var i=function(e){if(null===e||"object"!=typeof e)return null;var t=v&&e[v]||e["@@iterator"];return"function"==typeof t?t:null}(e);if("function"==typeof i&&i!==e.entries)for(var o,s=i.call(e);!(o=s.next()).done;)ne(o.value)&&oe(o.value,t)}}var ae={};function ce(t,n,i,v,m,b){var g=function(t){return"string"==typeof t||"function"==typeof t||t===o||t===a||t===s||t===f||t===d||t===y||"object"==typeof t&&null!==t&&(t.$$typeof===h||t.$$typeof===p||t.$$typeof===c||t.$$typeof===u||t.$$typeof===l||t.$$typeof===e||void 0!==t.getModuleId)}(t);if(!g){var S,E="";(void 0===t||"object"==typeof t&&null!==t&&0===Object.keys(t).length)&&(E+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."),E+=re(),null===t?S="null":G(t)?S="array":void 0!==t&&t.$$typeof===r?(S="<"+(k(t.type)||"Unknown")+" />",E=" Did you accidentally export a JSX literal instead of a component?"):S=typeof t,w("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",S,E)}var _=function(e,t,n,i,o){var s,a={},c=null,u=null;for(s in void 0!==n&&(W(n),c=""+n),function(e){if(q.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(t)&&(W(t.key),c=""+t.key),function(e){if(q.call(e,"ref")){var t=Object.getOwnPropertyDescriptor(e,"ref").get;if(t&&t.isReactWarning)return!1}return void 0!==e.ref}(t)&&(u=t.ref,function(e){"string"==typeof e.ref&&Q.current}(t)),t)q.call(t,s)&&!V.hasOwnProperty(s)&&(a[s]=t[s]);if(e&&e.defaultProps){var l=e.defaultProps;for(s in l)void 0===a[s]&&(a[s]=l[s])}if(c||u){var f="function"==typeof e?e.displayName||e.name||"Unknown":e;c&&function(e,t){var n=function(){Y||(Y=!0,w("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}(a,f),u&&function(e,t){var n=function(){z||(z=!0,w("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"ref",{get:n,configurable:!0})}(a,f)}return function(e,t,n,i,o,s,a){var c={$$typeof:r,type:e,key:t,ref:n,props:a,l:s,S:{}};return Object.defineProperty(c.S,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(c,"_",{configurable:!1,enumerable:!1,writable:!1,value:i}),Object.defineProperty(c,"k",{configurable:!1,enumerable:!1,writable:!1,value:o}),Object.freeze&&(Object.freeze(c.props),Object.freeze(c)),c}(e,c,u,o,i,Q.current,a)}(t,n,i,m,b);if(null==_)return _;if(g){var O=n.children;if(void 0!==O)if(v)if(G(O)){for(var R=0;R<O.length;R++)se(O[R],t);Object.freeze&&Object.freeze(O)}else w("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else se(O,t)}if(q.call(n,"key")){var j=k(t),I=Object.keys(n).filter(function(e){return"key"!==e}),T=I.length>0?"{key: someKey, "+I.join(": ..., ")+": ...}":"{key: someKey}";ae[j+T]||(w('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',T,j,I.length>0?"{"+I.join(": ..., ")+": ...}":"{}",j),ae[j+T]=!0)}return t===o?function(e){for(var t=Object.keys(e.props),n=0;n<t.length;n++){var r=t[n];if("children"!==r&&"key"!==r){te(e),w("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",r),te(null);break}}null!==e.ref&&(te(e),w("Invalid attribute `ref` supplied to `React.Fragment`."),te(null))}(_):function(e){var t,n=e.type;if(null!=n&&"string"!=typeof n){if("function"==typeof n)t=n.propTypes;else{if("object"!=typeof n||n.$$typeof!==l&&n.$$typeof!==p)return;t=n.propTypes}if(t){var r=k(n);!function(e,t,n,r,i){var o=Function.call.bind(q);for(var s in e)if(o(e,s)){var a=void 0;try{if("function"!=typeof e[s]){var c=Error((r||"React class")+": "+n+" type `"+s+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[s]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw c.name="Invariant Violation",c}a=e[s](t,s,r,n,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(u){a=u}!a||a instanceof Error||(H(i),w("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",r||"React class",n,s,typeof a),H(null)),a instanceof Error&&!(a.message in L)&&(L[a.message]=!0,H(i),w("Failed %s type: %s",n,a.message),H(null))}}(t,e.props,"prop",r,e)}else void 0===n.PropTypes||X||(X=!0,w("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",k(n)||"Unknown"));"function"!=typeof n.getDefaultProps||n.getDefaultProps.isReactClassApproved||w("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}(_),_}b.Fragment=o,b.jsx=function(e,t,n){return ce(e,t,n,!1)},b.jsxs=function(e,t,n){return ce(e,t,n,!0)}}()),b);var g=m.exports;const k=n.createContext(null);let S=null;exports.EngageProProvider=({children:e,...t})=>{const r=n.useRef(null),i=n.useRef(null);r.current||(r.current=new h(t));const o=r.current;return n.useEffect(()=>{if(!t.tracking.autoTrack)return;const e=e=>{const t=e.target.closest('button, a, input[type="submit"], [data-track], .clickable');if(t){const e=Date.now(),n=i.current;n&&n.el===t&&e-n.ts<500?(n.count++,n.ts=e,3===n.count&&(o.track("Rage Click detected",{element:t.tagName},{standardEvent:"RAGE_CLICK",intent:"frustration",confidence:1}),i.current=null)):i.current={el:t,count:1,ts:e};const r=(e=>{let t=(e.innerText||e.value||e.getAttribute("aria-label")||"").trim();if(!t){const n=e.querySelector("img");n&&n.alt&&(t=n.alt);const r=e.querySelector("title");r&&(t=r.textContent||"")}const n=t.slice(0,100),r=n.toLowerCase(),i=(e.id||"").toLowerCase(),o=e.href||"";return/add to (cart|bag)|buy now/.test(r)||i.includes("add-to-cart")?{standard:"ADD_TO_CART",intent:"commerce",label:n,confidence:.9}:/checkout|proceed/.test(r)||o.includes("/checkout")?{standard:"INITIATE_CHECKOUT",intent:"commerce",label:n,confidence:.9}:/place order|pay now/.test(r)||i.includes("place-order")?{standard:"PURCHASE",intent:"commerce",label:n,confidence:.95}:/cancel order/.test(r)||i.includes("cancel")?{standard:"ORDER_CANCEL",intent:"lifecycle",label:n,confidence:.85}:/refund|return/.test(r)||i.includes("refund")?{standard:"ORDER_REFUND",intent:"lifecycle",label:n,confidence:.85}:/track package|shipping/.test(r)?{standard:"TRACK_PACKAGE",intent:"lifecycle",label:n,confidence:.8}:/write review/.test(r)||r.includes("star")&&/^[1-5]/.test(r)?{standard:"RATE_PRODUCT",intent:"engagement",label:n,confidence:.8}:r.includes("search")||i.includes("search")?{standard:"SEARCH",intent:"search",label:n,confidence:.7}:{standard:"GENERIC",intent:"interaction",label:n,confidence:.5}})(t),s="A"===t.tagName;o.track("Interaction",{element:t.tagName.toLowerCase(),id:t.id,destination:s?t.href:void 0},{standardEvent:r.standard,intent:r.intent,rawLabel:r.label,confidence:r.confidence})}},n=e=>{const t=e.target;(e=>"password"===e.getAttribute("type")||"hidden"===e.getAttribute("type")||/password|cvc|card|cc-num|ssn|credit|hidden/i.test(e.getAttribute("name")||e.id||""))(t)||"focusin"!==e.type||t.dataset.tracked||(t.dataset.tracked="true",o.track("Form Start",{field:t.name||t.id},{standardEvent:"FORM_START",intent:"identity"}))},r=()=>{const e=new URLSearchParams(window.location.search);e.has("q")&&o.track("Search Query",{query:e.get("q")},{standardEvent:"SEARCH",intent:"search"}),requestAnimationFrame(()=>o.page())},s=history.pushState;return history.pushState=(...e)=>{s.apply(history,e),r()},window.addEventListener("popstate",r),window.addEventListener("click",e,!0),window.addEventListener("focusin",n,!0),r(),()=>{window.removeEventListener("popstate",r),window.removeEventListener("click",e,!0),window.removeEventListener("focusin",n,!0)}},[t.tracking.autoTrack]),g.jsx(k.Provider,{value:o,children:e})},exports.default=h,exports.init=e=>(S||(S=new h(e)),S),exports.useAnalytics=()=>{const e=n.useContext(k);if(!e)throw new Error("useAnalytics must be used within EngageProProvider");return e};
1
+ "use strict";var t=Object.defineProperty,e=(e,n,i)=>((e,n,i)=>n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[n]=i)(e,"symbol"!=typeof n?n+"":n,i);Object.defineProperties(exports,{t:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const n=require("react/jsx-runtime"),i=require("react");let s;const r=new Uint8Array(16);function o(){if(!s&&(s="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!s))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return s(r)}const a=[];for(let g=0;g<256;++g)a.push((g+256).toString(16).slice(1));const c={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function d(t,e,n){if(c.randomUUID&&!t)return c.randomUUID();const i=(t=t||{}).random||(t.rng||o)();return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(t,e=0){return a[t[e+0]]+a[t[e+1]]+a[t[e+2]]+a[t[e+3]]+"-"+a[t[e+4]]+a[t[e+5]]+"-"+a[t[e+6]]+a[t[e+7]]+"-"+a[t[e+8]]+a[t[e+9]]+"-"+a[t[e+10]]+a[t[e+11]]+a[t[e+12]]+a[t[e+13]]+a[t[e+14]]+a[t[e+15]]}(i)}const h=t=>{let e=2166136261;const n=t.length;for(let i=0;i<n;i++)e^=t.charCodeAt(i),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24);return("0000000"+(e>>>0).toString(16)).substr(-8)};class l{constructor(t="local"){e(this,"memoryStore",{}),e(this,"keyPrefix","engage_"),e(this,"domain"),this.type=t,this.domain=this.getCookieDomain()}getItem(t){const e=this.keyPrefix+t;if(this.memoryStore.hasOwnProperty(e))return this.memoryStore[e];try{if("local"===this.type&&this.isBrowser())return window.localStorage.getItem(e);if("cookie"===this.type&&this.isBrowser())return this.getCookie(e)}catch(n){return null}return null}setItem(t,e){const n=this.keyPrefix+t;this.memoryStore[n]=e;try{"local"===this.type&&this.isBrowser()?window.localStorage.setItem(n,e):"cookie"===this.type&&this.isBrowser()&&this.setCookie(n,e,365)}catch(i){this.isQuotaError(i)&&(this.type="memory")}}removeItem(t){const e=this.keyPrefix+t;delete this.memoryStore[e];try{"local"===this.type&&this.isBrowser()?window.localStorage.removeItem(e):"cookie"===this.type&&this.isBrowser()&&this.setCookie(e,"",-1)}catch(n){}}getCookie(t){const e=t+"=",n=document.cookie.split(";");for(let i=0;i<n.length;i++){let t=n[i];for(;" "===t.charAt(0);)t=t.substring(1,t.length);if(0===t.indexOf(e))return decodeURIComponent(t.substring(e.length,t.length))}return null}setCookie(t,e,n){let i="";if(n){const t=new Date;t.setTime(t.getTime()+24*n*60*60*1e3),i="; expires="+t.toUTCString()}document.cookie=`${t}=${encodeURIComponent(e)}${i}; path=/; domain=${this.domain}; SameSite=Lax; Secure`}getCookieDomain(){if(!this.isBrowser())return"";const t=window.location.hostname,e=t.split(".");return 1===e.length||"localhost"===t?"":e.length>2?"."+e.slice(-2).join("."):"."+t}isBrowser(){try{return"undefined"!=typeof window&&void 0!==window.document}catch(t){return!1}}isQuotaError(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)}}class u{constructor(t){e(this,"storage"),e(this,"SESSION_TIMEOUT",18e5),e(this,"deviceId"),e(this,"sessionId"),e(this,"userId",null),e(this,"currentUrl"),e(this,"referrer"),this.storage=new l(t.persistence),this.deviceId=this.getOrSetDeviceId(),this.sessionId="",this.manageSession(),"undefined"!=typeof window?(this.currentUrl=window.location.href,this.referrer=document.referrer,this.listenToHistory()):(this.currentUrl="",this.referrer="")}getOrSetDeviceId(){const t=this.storage.getItem("device_id");if(t)return t;const e=(()=>{if("undefined"==typeof window)return"server-side-id";const t=navigator,e=window.screen,n={userAgent:t.userAgent||"",screenRes:`${e.width}x${e.height}`,colorDepth:e.colorDepth||0,timezone:(new Date).getTimezoneOffset(),language:t.language||"en-US",platform:t.platform||"unknown",hardwareConcurrency:t.hardwareConcurrency||1,deviceMemory:t.deviceMemory||0},i=[n.platform,n.language,n.screenRes,n.colorDepth,n.timezone,n.hardwareConcurrency,n.deviceMemory].join("|");return`${h(i)}-${h(n.userAgent)}`})();return this.storage.setItem("device_id",e),e}manageSession(){const t=Date.now(),e=this.storage.getItem("session_id"),n=parseInt(this.storage.getItem("last_activity")||"0");if(!e||t-n>this.SESSION_TIMEOUT?(this.sessionId=`sess_${t}_${Math.random().toString(36).substr(2,9)}`,this.storage.setItem("session_id",this.sessionId)):this.sessionId=e,this.storage.setItem("last_activity",t.toString()),"undefined"!=typeof window){const t=()=>this.storage.setItem("last_activity",Date.now().toString());window.addEventListener("click",t),window.addEventListener("scroll",t)}}listenToHistory(){const t=history.pushState;history.pushState=(...e)=>{t.apply(history,e),this.handleUrlChange()},window.addEventListener("popstate",()=>this.handleUrlChange())}handleUrlChange(){const t=window.location.href;t!==this.currentUrl&&(this.referrer=this.currentUrl,this.currentUrl=t)}getPayload(){var t;return{library:{name:"@engagepro/analytics",version:"2.0.0"},user:{anonymousId:this.deviceId,id:this.userId},session:{id:this.sessionId,startTime:parseInt(this.sessionId.split("_")[1]||Date.now().toString())},page:{path:"undefined"!=typeof window?window.location.pathname:"",referrer:this.referrer,title:"undefined"!=typeof document?document.title:"",search:"undefined"!=typeof window?window.location.search:"",url:this.currentUrl},network:{online:"undefined"==typeof navigator||navigator.onLine,downlink:null==(t=navigator.connection)?void 0:t.downlink},screen:{width:"undefined"!=typeof screen?screen.width:0,height:"undefined"!=typeof screen?screen.height:0,density:"undefined"!=typeof window?window.devicePixelRatio:1},device:{fingerprint:this.deviceId,type:this.getDeviceType(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"server"},locale:"undefined"!=typeof navigator?navigator.language:"en-US",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}getDeviceType(){if("undefined"==typeof navigator)return"desktop";const t=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(t)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated/.test(t)?"mobile":"desktop"}}class f{constructor(t){e(this,"queue",[]),e(this,"storage"),e(this,"transport"),e(this,"STORAGE_KEY","engage_queue_v1"),e(this,"isFlushing",!1),e(this,"flushInterval"),e(this,"retryCount",0),this.transport=t,this.storage=new l("local"),this.load(),"undefined"!=typeof window&&(window.addEventListener("online",()=>{this.retryCount=0,this.flush()}),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.flush()})),this.startTimer()}startTimer(){this.flushInterval&&clearInterval(this.flushInterval);const t=3e3*Math.pow(2,this.retryCount);this.flushInterval=setInterval(()=>{this.flush()},Math.min(t,3e4))}enqueue(t){this.queue.push(t),this.save(),(this.queue.length>=10||"PURCHASE"===t.standardEvent)&&this.flush()}save(){this.storage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}load(){const t=this.storage.getItem(this.STORAGE_KEY);if(t)try{this.queue=JSON.parse(t)}catch(e){this.queue=[]}}async flush(){if(0===this.queue.length||this.isFlushing)return;if("undefined"!=typeof navigator&&!navigator.onLine)return;this.isFlushing=!0;const t=[...this.queue];this.queue=[],this.save();try{if(!(await this.transport.send(t)))throw new Error("Server rejected batch");this.retryCount=0,this.startTimer()}catch(e){this.queue=[...t,...this.queue],this.save(),this.retryCount++,this.startTimer()}finally{this.isFlushing=!1}}}class w{constructor(t){this.apiEndpoint=t}async send(t){const e=JSON.stringify({batch:t,sentAt:(new Date).toISOString()});if("undefined"!=typeof navigator&&navigator.sendBeacon&&e.length<6e4){const t=new Blob([e],{type:"application/json"});if(navigator.sendBeacon(this.apiEndpoint,t))return!0}try{return(await fetch(this.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0})).ok}catch(n){return!1}}}class p{constructor(t){e(this,"config"),e(this,"context"),e(this,"queue"),e(this,"transport"),e(this,"identify",(t,e)=>{this.context.userId=t,this.processEvent({event:"Identify",properties:{traits:e},standardEvent:"LOGIN",intent:"identity",confidence:1})}),e(this,"page",(t,e)=>{const n=this.context.getPayload().page;this.processEvent({event:t||n.title||"Unknown Page",properties:{path:n.path,referrer:n.referrer,title:n.title,...e},standardEvent:"PAGE_VIEW",intent:"navigation",confidence:1})}),e(this,"track",(t,e,n)=>{this.processEvent({event:t,properties:e||{},...n})}),this.config=t,this.transport=new w(t.apiHost||"http://localhost:3000/v1/ingest"),this.context=new u({persistence:t.tracking.useCookies?"cookie":"local"}),this.queue=new f(this.transport)}processEvent(t){const e=this.context.getPayload(),n={event:t.event,properties:t.properties,standardEvent:t.standardEvent,intent:t.intent,confidence:t.confidence,rawLabel:t.rawLabel,timestamp:(new Date).toISOString(),messageId:d(),writeKey:this.config.writeKey,userId:e.user.id||void 0,anonymousId:e.user.anonymousId,context:e};this.config.debug,this.queue.enqueue(n)}}class y{constructor(t){e(this,"analytics"),e(this,"metrics",{}),this.analytics=t,"undefined"!=typeof window&&"PerformanceObserver"in window&&this.observe()}observe(){try{new PerformanceObserver(t=>{for(const e of t.getEntries()){const t=e;t.hadRecentInput||(this.metrics.cls=(this.metrics.cls||0)+t.value)}}).observe({type:"layout-shift",buffered:!0}),new PerformanceObserver(t=>{const e=t.getEntries(),n=e[e.length-1];this.metrics.lcp=n.renderTime||n.loadTime,this.logMetric("LCP",this.metrics.lcp)}).observe({type:"largest-contentful-paint",buffered:!0}),new PerformanceObserver(t=>{const e=t.getEntries()[0];e&&(this.metrics.fid=e.processingStart-e.startTime,this.logMetric("FID",this.metrics.fid))}).observe({type:"first-input",buffered:!0}),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.metrics.cls&&this.logMetric("CLS",this.metrics.cls)})}catch(t){}}logMetric(t,e){e<0||this.analytics.track(`Core Web Vital: ${t}`,{metric:t,value:Math.round(e)},{standardEvent:"PERFORMANCE",intent:"performance",confidence:1,rawLabel:`${t}: ${Math.round(e)}ms`})}}const v=i.createContext(null);let m=null;exports.EngageProProvider=({children:t,...e})=>{const s=i.useRef(null),r=i.useRef(null);s.current||(s.current=new p(e),"undefined"!=typeof window&&new y(s.current));const o=s.current;return i.useEffect(()=>{if(!e.tracking.autoTrack)return;const t=t=>{const e=t.target.closest('button, a, input[type="submit"], [data-track], .clickable');if(e){const t=Date.now(),n=r.current;n&&n.el===e&&t-n.ts<500?(n.count++,n.ts=t,3===n.count&&(o.track("Rage Click detected",{element:e.tagName},{standardEvent:"RAGE_CLICK",intent:"frustration",confidence:1}),r.current=null)):r.current={el:e,count:1,ts:t};const i=(t=>{let e=(t.innerText||t.value||t.getAttribute("aria-label")||"").trim();if(!e){const n=t.querySelector("img");n&&n.alt&&(e=n.alt);const i=t.querySelector("title");i&&(e=i.textContent||"")}const n=e.slice(0,100),i=n.toLowerCase(),s=(t.id||"").toLowerCase(),r=t.href||"";return/add to (cart|bag)|buy now/.test(i)||s.includes("add-to-cart")?{standard:"ADD_TO_CART",intent:"commerce",label:n,confidence:.9}:/checkout|proceed/.test(i)||r.includes("/checkout")?{standard:"INITIATE_CHECKOUT",intent:"commerce",label:n,confidence:.9}:/place order|pay now/.test(i)||s.includes("place-order")?{standard:"PURCHASE",intent:"commerce",label:n,confidence:.95}:/cancel order/.test(i)||s.includes("cancel")?{standard:"ORDER_CANCEL",intent:"lifecycle",label:n,confidence:.85}:/refund|return/.test(i)||s.includes("refund")?{standard:"ORDER_REFUND",intent:"lifecycle",label:n,confidence:.85}:/track package|shipping/.test(i)?{standard:"TRACK_PACKAGE",intent:"lifecycle",label:n,confidence:.8}:/write review/.test(i)||i.includes("star")&&/^[1-5]/.test(i)?{standard:"RATE_PRODUCT",intent:"engagement",label:n,confidence:.8}:i.includes("search")||s.includes("search")?{standard:"SEARCH",intent:"search",label:n,confidence:.7}:{standard:"GENERIC",intent:"interaction",label:n,confidence:.5}})(e),s="A"===e.tagName;o.track("Interaction",{element:e.tagName.toLowerCase(),id:e.id,destination:s?e.href:void 0},{standardEvent:i.standard,intent:i.intent,rawLabel:i.label,confidence:i.confidence})}},n=t=>{const e=t.target;(t=>"password"===t.getAttribute("type")||"hidden"===t.getAttribute("type")||/password|cvc|card|cc-num|ssn|credit|hidden/i.test(t.getAttribute("name")||t.id||""))(e)||"focusin"!==t.type||e.dataset.tracked||(e.dataset.tracked="true",o.track("Form Start",{field:e.name||e.id},{standardEvent:"FORM_START",intent:"identity"}))},i=()=>{const t=new URLSearchParams(window.location.search);t.has("q")&&o.track("Search Query",{query:t.get("q")},{standardEvent:"SEARCH",intent:"search"}),requestAnimationFrame(()=>o.page())},s=history.pushState;return history.pushState=(...t)=>{s.apply(history,t),i()},window.addEventListener("popstate",i),window.addEventListener("click",t,!0),window.addEventListener("focusin",n,!0),i(),()=>{window.removeEventListener("popstate",i),window.removeEventListener("click",t,!0),window.removeEventListener("focusin",n,!0)}},[e.tracking.autoTrack]),n.jsx(v.Provider,{value:o,children:t})},exports.default=p,exports.init=t=>(m||(m=new p(t)),m),exports.useAnalytics=()=>{const t=i.useContext(v);if(!t)throw new Error("useAnalytics must be used within EngageProProvider");return t};
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- import require$$0, { createContext, useRef, useEffect, useContext } from "react";
4
+ import { jsx } from "react/jsx-runtime";
5
+ import { createContext, useRef, useEffect, useContext } from "react";
5
6
  let getRandomValues;
6
7
  const rnds8 = new Uint8Array(16);
7
8
  function rng() {
@@ -304,21 +305,36 @@ class EventQueue {
304
305
  __publicField(this, "transport");
305
306
  __publicField(this, "STORAGE_KEY", "engage_queue_v1");
306
307
  __publicField(this, "isFlushing", false);
308
+ __publicField(this, "flushInterval");
309
+ __publicField(this, "retryCount", 0);
307
310
  this.transport = transport;
308
311
  this.storage = new StorageEngine("local");
309
312
  this.load();
310
313
  if (typeof window !== "undefined") {
311
- window.addEventListener("online", () => this.flush());
314
+ window.addEventListener("online", () => {
315
+ this.retryCount = 0;
316
+ this.flush();
317
+ });
312
318
  window.addEventListener("visibilitychange", () => {
313
319
  if (document.visibilityState === "hidden") this.flush();
314
320
  });
315
321
  }
316
- setInterval(() => this.flush(), 3e3);
322
+ this.startTimer();
323
+ }
324
+ startTimer() {
325
+ if (this.flushInterval) clearInterval(this.flushInterval);
326
+ const delay = 3e3 * Math.pow(2, this.retryCount);
327
+ this.flushInterval = setInterval(
328
+ () => {
329
+ this.flush();
330
+ },
331
+ Math.min(delay, 3e4)
332
+ );
317
333
  }
318
334
  enqueue(event) {
319
335
  this.queue.push(event);
320
336
  this.save();
321
- if (this.queue.length >= 10) {
337
+ if (this.queue.length >= 10 || event.standardEvent === "PURCHASE") {
322
338
  this.flush();
323
339
  }
324
340
  }
@@ -344,13 +360,17 @@ class EventQueue {
344
360
  this.save();
345
361
  try {
346
362
  const success = await this.transport.send(batch);
347
- if (!success) {
348
- this.queue = [...batch, ...this.queue];
349
- this.save();
363
+ if (success) {
364
+ this.retryCount = 0;
365
+ this.startTimer();
366
+ } else {
367
+ throw new Error("Server rejected batch");
350
368
  }
351
369
  } catch (e) {
352
370
  this.queue = [...batch, ...this.queue];
353
371
  this.save();
372
+ this.retryCount++;
373
+ this.startTimer();
354
374
  } finally {
355
375
  this.isFlushing = false;
356
376
  }
@@ -462,928 +482,63 @@ class EngagePro {
462
482
  this.queue.enqueue(payload);
463
483
  }
464
484
  }
465
- var jsxRuntime = { exports: {} };
466
- var reactJsxRuntime_production_min = {};
467
- /**
468
- * @license React
469
- * react-jsx-runtime.production.min.js
470
- *
471
- * Copyright (c) Facebook, Inc. and its affiliates.
472
- *
473
- * This source code is licensed under the MIT license found in the
474
- * LICENSE file in the root directory of this source tree.
475
- */
476
- var hasRequiredReactJsxRuntime_production_min;
477
- function requireReactJsxRuntime_production_min() {
478
- if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
479
- hasRequiredReactJsxRuntime_production_min = 1;
480
- var f = require$$0, k = Symbol.for("react.element"), l = Symbol.for("react.fragment"), m = Object.prototype.hasOwnProperty, n = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p = { key: true, ref: true, __self: true, __source: true };
481
- function q(c, a, g) {
482
- var b, d = {}, e = null, h = null;
483
- void 0 !== g && (e = "" + g);
484
- void 0 !== a.key && (e = "" + a.key);
485
- void 0 !== a.ref && (h = a.ref);
486
- for (b in a) m.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]);
487
- if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d[b] && (d[b] = a[b]);
488
- return { $$typeof: k, type: c, key: e, ref: h, props: d, _owner: n.current };
485
+ class PerformanceMonitor {
486
+ constructor(analytics) {
487
+ __publicField(this, "analytics");
488
+ __publicField(this, "metrics", {});
489
+ this.analytics = analytics;
490
+ if (typeof window !== "undefined" && "PerformanceObserver" in window) {
491
+ this.observe();
492
+ }
489
493
  }
490
- reactJsxRuntime_production_min.Fragment = l;
491
- reactJsxRuntime_production_min.jsx = q;
492
- reactJsxRuntime_production_min.jsxs = q;
493
- return reactJsxRuntime_production_min;
494
- }
495
- var reactJsxRuntime_development = {};
496
- /**
497
- * @license React
498
- * react-jsx-runtime.development.js
499
- *
500
- * Copyright (c) Facebook, Inc. and its affiliates.
501
- *
502
- * This source code is licensed under the MIT license found in the
503
- * LICENSE file in the root directory of this source tree.
504
- */
505
- var hasRequiredReactJsxRuntime_development;
506
- function requireReactJsxRuntime_development() {
507
- if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
508
- hasRequiredReactJsxRuntime_development = 1;
509
- if (process.env.NODE_ENV !== "production") {
510
- (function() {
511
- var React = require$$0;
512
- var REACT_ELEMENT_TYPE = Symbol.for("react.element");
513
- var REACT_PORTAL_TYPE = Symbol.for("react.portal");
514
- var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
515
- var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
516
- var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
517
- var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
518
- var REACT_CONTEXT_TYPE = Symbol.for("react.context");
519
- var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
520
- var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
521
- var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
522
- var REACT_MEMO_TYPE = Symbol.for("react.memo");
523
- var REACT_LAZY_TYPE = Symbol.for("react.lazy");
524
- var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
525
- var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
526
- var FAUX_ITERATOR_SYMBOL = "@@iterator";
527
- function getIteratorFn(maybeIterable) {
528
- if (maybeIterable === null || typeof maybeIterable !== "object") {
529
- return null;
530
- }
531
- var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
532
- if (typeof maybeIterator === "function") {
533
- return maybeIterator;
534
- }
535
- return null;
536
- }
537
- var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
538
- function error(format) {
539
- {
540
- {
541
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
542
- args[_key2 - 1] = arguments[_key2];
543
- }
544
- printWarning("error", format, args);
545
- }
546
- }
547
- }
548
- function printWarning(level, format, args) {
549
- {
550
- var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
551
- var stack = ReactDebugCurrentFrame2.getStackAddendum();
552
- if (stack !== "") {
553
- format += "%s";
554
- args = args.concat([stack]);
555
- }
556
- var argsWithFormat = args.map(function(item) {
557
- return String(item);
558
- });
559
- argsWithFormat.unshift("Warning: " + format);
560
- Function.prototype.apply.call(console[level], console, argsWithFormat);
561
- }
562
- }
563
- var enableScopeAPI = false;
564
- var enableCacheElement = false;
565
- var enableTransitionTracing = false;
566
- var enableLegacyHidden = false;
567
- var enableDebugTracing = false;
568
- var REACT_MODULE_REFERENCE;
569
- {
570
- REACT_MODULE_REFERENCE = Symbol.for("react.module.reference");
571
- }
572
- function isValidElementType(type) {
573
- if (typeof type === "string" || typeof type === "function") {
574
- return true;
575
- }
576
- if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
577
- return true;
578
- }
579
- if (typeof type === "object" && type !== null) {
580
- if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
581
- // types supported by any Flight configuration anywhere since
582
- // we don't know which Flight build this will end up being used
583
- // with.
584
- type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) {
585
- return true;
586
- }
587
- }
588
- return false;
589
- }
590
- function getWrappedName(outerType, innerType, wrapperName) {
591
- var displayName = outerType.displayName;
592
- if (displayName) {
593
- return displayName;
594
- }
595
- var functionName = innerType.displayName || innerType.name || "";
596
- return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
597
- }
598
- function getContextName(type) {
599
- return type.displayName || "Context";
600
- }
601
- function getComponentNameFromType(type) {
602
- if (type == null) {
603
- return null;
604
- }
605
- {
606
- if (typeof type.tag === "number") {
607
- error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.");
608
- }
609
- }
610
- if (typeof type === "function") {
611
- return type.displayName || type.name || null;
612
- }
613
- if (typeof type === "string") {
614
- return type;
615
- }
616
- switch (type) {
617
- case REACT_FRAGMENT_TYPE:
618
- return "Fragment";
619
- case REACT_PORTAL_TYPE:
620
- return "Portal";
621
- case REACT_PROFILER_TYPE:
622
- return "Profiler";
623
- case REACT_STRICT_MODE_TYPE:
624
- return "StrictMode";
625
- case REACT_SUSPENSE_TYPE:
626
- return "Suspense";
627
- case REACT_SUSPENSE_LIST_TYPE:
628
- return "SuspenseList";
629
- }
630
- if (typeof type === "object") {
631
- switch (type.$$typeof) {
632
- case REACT_CONTEXT_TYPE:
633
- var context = type;
634
- return getContextName(context) + ".Consumer";
635
- case REACT_PROVIDER_TYPE:
636
- var provider = type;
637
- return getContextName(provider._context) + ".Provider";
638
- case REACT_FORWARD_REF_TYPE:
639
- return getWrappedName(type, type.render, "ForwardRef");
640
- case REACT_MEMO_TYPE:
641
- var outerName = type.displayName || null;
642
- if (outerName !== null) {
643
- return outerName;
644
- }
645
- return getComponentNameFromType(type.type) || "Memo";
646
- case REACT_LAZY_TYPE: {
647
- var lazyComponent = type;
648
- var payload = lazyComponent._payload;
649
- var init2 = lazyComponent._init;
650
- try {
651
- return getComponentNameFromType(init2(payload));
652
- } catch (x) {
653
- return null;
654
- }
655
- }
656
- }
657
- }
658
- return null;
659
- }
660
- var assign = Object.assign;
661
- var disabledDepth = 0;
662
- var prevLog;
663
- var prevInfo;
664
- var prevWarn;
665
- var prevError;
666
- var prevGroup;
667
- var prevGroupCollapsed;
668
- var prevGroupEnd;
669
- function disabledLog() {
670
- }
671
- disabledLog.__reactDisabledLog = true;
672
- function disableLogs() {
673
- {
674
- if (disabledDepth === 0) {
675
- prevLog = console.log;
676
- prevInfo = console.info;
677
- prevWarn = console.warn;
678
- prevError = console.error;
679
- prevGroup = console.group;
680
- prevGroupCollapsed = console.groupCollapsed;
681
- prevGroupEnd = console.groupEnd;
682
- var props = {
683
- configurable: true,
684
- enumerable: true,
685
- value: disabledLog,
686
- writable: true
687
- };
688
- Object.defineProperties(console, {
689
- info: props,
690
- log: props,
691
- warn: props,
692
- error: props,
693
- group: props,
694
- groupCollapsed: props,
695
- groupEnd: props
696
- });
697
- }
698
- disabledDepth++;
699
- }
700
- }
701
- function reenableLogs() {
702
- {
703
- disabledDepth--;
704
- if (disabledDepth === 0) {
705
- var props = {
706
- configurable: true,
707
- enumerable: true,
708
- writable: true
709
- };
710
- Object.defineProperties(console, {
711
- log: assign({}, props, {
712
- value: prevLog
713
- }),
714
- info: assign({}, props, {
715
- value: prevInfo
716
- }),
717
- warn: assign({}, props, {
718
- value: prevWarn
719
- }),
720
- error: assign({}, props, {
721
- value: prevError
722
- }),
723
- group: assign({}, props, {
724
- value: prevGroup
725
- }),
726
- groupCollapsed: assign({}, props, {
727
- value: prevGroupCollapsed
728
- }),
729
- groupEnd: assign({}, props, {
730
- value: prevGroupEnd
731
- })
732
- });
733
- }
734
- if (disabledDepth < 0) {
735
- error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
736
- }
737
- }
738
- }
739
- var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
740
- var prefix;
741
- function describeBuiltInComponentFrame(name, source, ownerFn) {
742
- {
743
- if (prefix === void 0) {
744
- try {
745
- throw Error();
746
- } catch (x) {
747
- var match = x.stack.trim().match(/\n( *(at )?)/);
748
- prefix = match && match[1] || "";
749
- }
750
- }
751
- return "\n" + prefix + name;
752
- }
753
- }
754
- var reentry = false;
755
- var componentFrameCache;
756
- {
757
- var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
758
- componentFrameCache = new PossiblyWeakMap();
759
- }
760
- function describeNativeComponentFrame(fn, construct) {
761
- if (!fn || reentry) {
762
- return "";
763
- }
764
- {
765
- var frame = componentFrameCache.get(fn);
766
- if (frame !== void 0) {
767
- return frame;
768
- }
769
- }
770
- var control;
771
- reentry = true;
772
- var previousPrepareStackTrace = Error.prepareStackTrace;
773
- Error.prepareStackTrace = void 0;
774
- var previousDispatcher;
775
- {
776
- previousDispatcher = ReactCurrentDispatcher.current;
777
- ReactCurrentDispatcher.current = null;
778
- disableLogs();
779
- }
780
- try {
781
- if (construct) {
782
- var Fake = function() {
783
- throw Error();
784
- };
785
- Object.defineProperty(Fake.prototype, "props", {
786
- set: function() {
787
- throw Error();
788
- }
789
- });
790
- if (typeof Reflect === "object" && Reflect.construct) {
791
- try {
792
- Reflect.construct(Fake, []);
793
- } catch (x) {
794
- control = x;
795
- }
796
- Reflect.construct(fn, [], Fake);
797
- } else {
798
- try {
799
- Fake.call();
800
- } catch (x) {
801
- control = x;
802
- }
803
- fn.call(Fake.prototype);
804
- }
805
- } else {
806
- try {
807
- throw Error();
808
- } catch (x) {
809
- control = x;
810
- }
811
- fn();
812
- }
813
- } catch (sample) {
814
- if (sample && control && typeof sample.stack === "string") {
815
- var sampleLines = sample.stack.split("\n");
816
- var controlLines = control.stack.split("\n");
817
- var s = sampleLines.length - 1;
818
- var c = controlLines.length - 1;
819
- while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
820
- c--;
821
- }
822
- for (; s >= 1 && c >= 0; s--, c--) {
823
- if (sampleLines[s] !== controlLines[c]) {
824
- if (s !== 1 || c !== 1) {
825
- do {
826
- s--;
827
- c--;
828
- if (c < 0 || sampleLines[s] !== controlLines[c]) {
829
- var _frame = "\n" + sampleLines[s].replace(" at new ", " at ");
830
- if (fn.displayName && _frame.includes("<anonymous>")) {
831
- _frame = _frame.replace("<anonymous>", fn.displayName);
832
- }
833
- {
834
- if (typeof fn === "function") {
835
- componentFrameCache.set(fn, _frame);
836
- }
837
- }
838
- return _frame;
839
- }
840
- } while (s >= 1 && c >= 0);
841
- }
842
- break;
843
- }
844
- }
845
- }
846
- } finally {
847
- reentry = false;
848
- {
849
- ReactCurrentDispatcher.current = previousDispatcher;
850
- reenableLogs();
851
- }
852
- Error.prepareStackTrace = previousPrepareStackTrace;
853
- }
854
- var name = fn ? fn.displayName || fn.name : "";
855
- var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
856
- {
857
- if (typeof fn === "function") {
858
- componentFrameCache.set(fn, syntheticFrame);
859
- }
860
- }
861
- return syntheticFrame;
862
- }
863
- function describeFunctionComponentFrame(fn, source, ownerFn) {
864
- {
865
- return describeNativeComponentFrame(fn, false);
866
- }
867
- }
868
- function shouldConstruct(Component) {
869
- var prototype = Component.prototype;
870
- return !!(prototype && prototype.isReactComponent);
871
- }
872
- function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
873
- if (type == null) {
874
- return "";
875
- }
876
- if (typeof type === "function") {
877
- {
878
- return describeNativeComponentFrame(type, shouldConstruct(type));
879
- }
880
- }
881
- if (typeof type === "string") {
882
- return describeBuiltInComponentFrame(type);
883
- }
884
- switch (type) {
885
- case REACT_SUSPENSE_TYPE:
886
- return describeBuiltInComponentFrame("Suspense");
887
- case REACT_SUSPENSE_LIST_TYPE:
888
- return describeBuiltInComponentFrame("SuspenseList");
889
- }
890
- if (typeof type === "object") {
891
- switch (type.$$typeof) {
892
- case REACT_FORWARD_REF_TYPE:
893
- return describeFunctionComponentFrame(type.render);
894
- case REACT_MEMO_TYPE:
895
- return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
896
- case REACT_LAZY_TYPE: {
897
- var lazyComponent = type;
898
- var payload = lazyComponent._payload;
899
- var init2 = lazyComponent._init;
900
- try {
901
- return describeUnknownElementTypeFrameInDEV(init2(payload), source, ownerFn);
902
- } catch (x) {
903
- }
904
- }
905
- }
906
- }
907
- return "";
908
- }
909
- var hasOwnProperty = Object.prototype.hasOwnProperty;
910
- var loggedTypeFailures = {};
911
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
912
- function setCurrentlyValidatingElement(element) {
913
- {
914
- if (element) {
915
- var owner = element._owner;
916
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
917
- ReactDebugCurrentFrame.setExtraStackFrame(stack);
918
- } else {
919
- ReactDebugCurrentFrame.setExtraStackFrame(null);
920
- }
921
- }
922
- }
923
- function checkPropTypes(typeSpecs, values, location, componentName, element) {
924
- {
925
- var has = Function.call.bind(hasOwnProperty);
926
- for (var typeSpecName in typeSpecs) {
927
- if (has(typeSpecs, typeSpecName)) {
928
- var error$1 = void 0;
929
- try {
930
- if (typeof typeSpecs[typeSpecName] !== "function") {
931
- var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
932
- err.name = "Invariant Violation";
933
- throw err;
934
- }
935
- error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
936
- } catch (ex) {
937
- error$1 = ex;
938
- }
939
- if (error$1 && !(error$1 instanceof Error)) {
940
- setCurrentlyValidatingElement(element);
941
- error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
942
- setCurrentlyValidatingElement(null);
943
- }
944
- if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
945
- loggedTypeFailures[error$1.message] = true;
946
- setCurrentlyValidatingElement(element);
947
- error("Failed %s type: %s", location, error$1.message);
948
- setCurrentlyValidatingElement(null);
949
- }
950
- }
951
- }
952
- }
953
- }
954
- var isArrayImpl = Array.isArray;
955
- function isArray(a) {
956
- return isArrayImpl(a);
957
- }
958
- function typeName(value) {
959
- {
960
- var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
961
- var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
962
- return type;
963
- }
964
- }
965
- function willCoercionThrow(value) {
966
- {
967
- try {
968
- testStringCoercion(value);
969
- return false;
970
- } catch (e) {
971
- return true;
972
- }
973
- }
974
- }
975
- function testStringCoercion(value) {
976
- return "" + value;
977
- }
978
- function checkKeyStringCoercion(value) {
979
- {
980
- if (willCoercionThrow(value)) {
981
- error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
982
- return testStringCoercion(value);
983
- }
984
- }
985
- }
986
- var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
987
- var RESERVED_PROPS = {
988
- key: true,
989
- ref: true,
990
- __self: true,
991
- __source: true
992
- };
993
- var specialPropKeyWarningShown;
994
- var specialPropRefWarningShown;
995
- function hasValidRef(config) {
996
- {
997
- if (hasOwnProperty.call(config, "ref")) {
998
- var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
999
- if (getter && getter.isReactWarning) {
1000
- return false;
1001
- }
1002
- }
1003
- }
1004
- return config.ref !== void 0;
1005
- }
1006
- function hasValidKey(config) {
1007
- {
1008
- if (hasOwnProperty.call(config, "key")) {
1009
- var getter = Object.getOwnPropertyDescriptor(config, "key").get;
1010
- if (getter && getter.isReactWarning) {
1011
- return false;
1012
- }
1013
- }
1014
- }
1015
- return config.key !== void 0;
1016
- }
1017
- function warnIfStringRefCannotBeAutoConverted(config, self) {
1018
- {
1019
- if (typeof config.ref === "string" && ReactCurrentOwner.current && self) ;
1020
- }
1021
- }
1022
- function defineKeyPropWarningGetter(props, displayName) {
1023
- {
1024
- var warnAboutAccessingKey = function() {
1025
- if (!specialPropKeyWarningShown) {
1026
- specialPropKeyWarningShown = true;
1027
- error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
1028
- }
1029
- };
1030
- warnAboutAccessingKey.isReactWarning = true;
1031
- Object.defineProperty(props, "key", {
1032
- get: warnAboutAccessingKey,
1033
- configurable: true
1034
- });
1035
- }
1036
- }
1037
- function defineRefPropWarningGetter(props, displayName) {
1038
- {
1039
- var warnAboutAccessingRef = function() {
1040
- if (!specialPropRefWarningShown) {
1041
- specialPropRefWarningShown = true;
1042
- error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
1043
- }
1044
- };
1045
- warnAboutAccessingRef.isReactWarning = true;
1046
- Object.defineProperty(props, "ref", {
1047
- get: warnAboutAccessingRef,
1048
- configurable: true
1049
- });
1050
- }
1051
- }
1052
- var ReactElement = function(type, key, ref, self, source, owner, props) {
1053
- var element = {
1054
- // This tag allows us to uniquely identify this as a React Element
1055
- $$typeof: REACT_ELEMENT_TYPE,
1056
- // Built-in properties that belong on the element
1057
- type,
1058
- key,
1059
- ref,
1060
- props,
1061
- // Record the component responsible for creating this element.
1062
- _owner: owner
1063
- };
1064
- {
1065
- element._store = {};
1066
- Object.defineProperty(element._store, "validated", {
1067
- configurable: false,
1068
- enumerable: false,
1069
- writable: true,
1070
- value: false
1071
- });
1072
- Object.defineProperty(element, "_self", {
1073
- configurable: false,
1074
- enumerable: false,
1075
- writable: false,
1076
- value: self
1077
- });
1078
- Object.defineProperty(element, "_source", {
1079
- configurable: false,
1080
- enumerable: false,
1081
- writable: false,
1082
- value: source
1083
- });
1084
- if (Object.freeze) {
1085
- Object.freeze(element.props);
1086
- Object.freeze(element);
1087
- }
1088
- }
1089
- return element;
1090
- };
1091
- function jsxDEV(type, config, maybeKey, source, self) {
1092
- {
1093
- var propName;
1094
- var props = {};
1095
- var key = null;
1096
- var ref = null;
1097
- if (maybeKey !== void 0) {
1098
- {
1099
- checkKeyStringCoercion(maybeKey);
1100
- }
1101
- key = "" + maybeKey;
1102
- }
1103
- if (hasValidKey(config)) {
1104
- {
1105
- checkKeyStringCoercion(config.key);
1106
- }
1107
- key = "" + config.key;
1108
- }
1109
- if (hasValidRef(config)) {
1110
- ref = config.ref;
1111
- warnIfStringRefCannotBeAutoConverted(config, self);
1112
- }
1113
- for (propName in config) {
1114
- if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
1115
- props[propName] = config[propName];
1116
- }
1117
- }
1118
- if (type && type.defaultProps) {
1119
- var defaultProps = type.defaultProps;
1120
- for (propName in defaultProps) {
1121
- if (props[propName] === void 0) {
1122
- props[propName] = defaultProps[propName];
1123
- }
1124
- }
1125
- }
1126
- if (key || ref) {
1127
- var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type;
1128
- if (key) {
1129
- defineKeyPropWarningGetter(props, displayName);
1130
- }
1131
- if (ref) {
1132
- defineRefPropWarningGetter(props, displayName);
1133
- }
1134
- }
1135
- return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
1136
- }
1137
- }
1138
- var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
1139
- var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
1140
- function setCurrentlyValidatingElement$1(element) {
1141
- {
1142
- if (element) {
1143
- var owner = element._owner;
1144
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
1145
- ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
1146
- } else {
1147
- ReactDebugCurrentFrame$1.setExtraStackFrame(null);
1148
- }
494
+ observe() {
495
+ try {
496
+ new PerformanceObserver((entryList) => {
497
+ for (const entry of entryList.getEntries()) {
498
+ const layoutShift = entry;
499
+ if (!layoutShift.hadRecentInput) {
500
+ this.metrics.cls = (this.metrics.cls || 0) + layoutShift.value;
501
+ }
502
+ }
503
+ }).observe({ type: "layout-shift", buffered: true });
504
+ new PerformanceObserver((entryList) => {
505
+ const entries = entryList.getEntries();
506
+ const lastEntry = entries[entries.length - 1];
507
+ this.metrics.lcp = lastEntry.renderTime || lastEntry.loadTime;
508
+ this.logMetric("LCP", this.metrics.lcp);
509
+ }).observe({ type: "largest-contentful-paint", buffered: true });
510
+ new PerformanceObserver((entryList) => {
511
+ const firstInput = entryList.getEntries()[0];
512
+ if (firstInput) {
513
+ this.metrics.fid = firstInput.processingStart - firstInput.startTime;
514
+ this.logMetric("FID", this.metrics.fid);
515
+ }
516
+ }).observe({ type: "first-input", buffered: true });
517
+ window.addEventListener("visibilitychange", () => {
518
+ if (document.visibilityState === "hidden" && this.metrics.cls) {
519
+ this.logMetric("CLS", this.metrics.cls);
1149
520
  }
1150
- }
1151
- var propTypesMisspellWarningShown;
521
+ });
522
+ } catch (e) {
523
+ console.warn(
524
+ "[EngagePro] Performance API not supported in this environment."
525
+ );
526
+ }
527
+ }
528
+ logMetric(name, value) {
529
+ if (value < 0) return;
530
+ this.analytics.track(
531
+ `Core Web Vital: ${name}`,
532
+ { metric: name, value: Math.round(value) },
1152
533
  {
1153
- propTypesMisspellWarningShown = false;
1154
- }
1155
- function isValidElement(object) {
1156
- {
1157
- return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
1158
- }
1159
- }
1160
- function getDeclarationErrorAddendum() {
1161
- {
1162
- if (ReactCurrentOwner$1.current) {
1163
- var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
1164
- if (name) {
1165
- return "\n\nCheck the render method of `" + name + "`.";
1166
- }
1167
- }
1168
- return "";
1169
- }
534
+ standardEvent: "PERFORMANCE",
535
+ intent: "performance",
536
+ confidence: 1,
537
+ rawLabel: `${name}: ${Math.round(value)}ms`
1170
538
  }
1171
- function getSourceInfoErrorAddendum(source) {
1172
- {
1173
- return "";
1174
- }
1175
- }
1176
- var ownerHasKeyUseWarning = {};
1177
- function getCurrentComponentErrorInfo(parentType) {
1178
- {
1179
- var info = getDeclarationErrorAddendum();
1180
- if (!info) {
1181
- var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
1182
- if (parentName) {
1183
- info = "\n\nCheck the top-level render call using <" + parentName + ">.";
1184
- }
1185
- }
1186
- return info;
1187
- }
1188
- }
1189
- function validateExplicitKey(element, parentType) {
1190
- {
1191
- if (!element._store || element._store.validated || element.key != null) {
1192
- return;
1193
- }
1194
- element._store.validated = true;
1195
- var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
1196
- if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
1197
- return;
1198
- }
1199
- ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
1200
- var childOwner = "";
1201
- if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
1202
- childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
1203
- }
1204
- setCurrentlyValidatingElement$1(element);
1205
- error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
1206
- setCurrentlyValidatingElement$1(null);
1207
- }
1208
- }
1209
- function validateChildKeys(node, parentType) {
1210
- {
1211
- if (typeof node !== "object") {
1212
- return;
1213
- }
1214
- if (isArray(node)) {
1215
- for (var i = 0; i < node.length; i++) {
1216
- var child = node[i];
1217
- if (isValidElement(child)) {
1218
- validateExplicitKey(child, parentType);
1219
- }
1220
- }
1221
- } else if (isValidElement(node)) {
1222
- if (node._store) {
1223
- node._store.validated = true;
1224
- }
1225
- } else if (node) {
1226
- var iteratorFn = getIteratorFn(node);
1227
- if (typeof iteratorFn === "function") {
1228
- if (iteratorFn !== node.entries) {
1229
- var iterator = iteratorFn.call(node);
1230
- var step;
1231
- while (!(step = iterator.next()).done) {
1232
- if (isValidElement(step.value)) {
1233
- validateExplicitKey(step.value, parentType);
1234
- }
1235
- }
1236
- }
1237
- }
1238
- }
1239
- }
1240
- }
1241
- function validatePropTypes(element) {
1242
- {
1243
- var type = element.type;
1244
- if (type === null || type === void 0 || typeof type === "string") {
1245
- return;
1246
- }
1247
- var propTypes;
1248
- if (typeof type === "function") {
1249
- propTypes = type.propTypes;
1250
- } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
1251
- // Inner props are checked in the reconciler.
1252
- type.$$typeof === REACT_MEMO_TYPE)) {
1253
- propTypes = type.propTypes;
1254
- } else {
1255
- return;
1256
- }
1257
- if (propTypes) {
1258
- var name = getComponentNameFromType(type);
1259
- checkPropTypes(propTypes, element.props, "prop", name, element);
1260
- } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) {
1261
- propTypesMisspellWarningShown = true;
1262
- var _name = getComponentNameFromType(type);
1263
- error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
1264
- }
1265
- if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) {
1266
- error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
1267
- }
1268
- }
1269
- }
1270
- function validateFragmentProps(fragment) {
1271
- {
1272
- var keys = Object.keys(fragment.props);
1273
- for (var i = 0; i < keys.length; i++) {
1274
- var key = keys[i];
1275
- if (key !== "children" && key !== "key") {
1276
- setCurrentlyValidatingElement$1(fragment);
1277
- error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key);
1278
- setCurrentlyValidatingElement$1(null);
1279
- break;
1280
- }
1281
- }
1282
- if (fragment.ref !== null) {
1283
- setCurrentlyValidatingElement$1(fragment);
1284
- error("Invalid attribute `ref` supplied to `React.Fragment`.");
1285
- setCurrentlyValidatingElement$1(null);
1286
- }
1287
- }
1288
- }
1289
- var didWarnAboutKeySpread = {};
1290
- function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
1291
- {
1292
- var validType = isValidElementType(type);
1293
- if (!validType) {
1294
- var info = "";
1295
- if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) {
1296
- info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
1297
- }
1298
- var sourceInfo = getSourceInfoErrorAddendum();
1299
- if (sourceInfo) {
1300
- info += sourceInfo;
1301
- } else {
1302
- info += getDeclarationErrorAddendum();
1303
- }
1304
- var typeString;
1305
- if (type === null) {
1306
- typeString = "null";
1307
- } else if (isArray(type)) {
1308
- typeString = "array";
1309
- } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) {
1310
- typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />";
1311
- info = " Did you accidentally export a JSX literal instead of a component?";
1312
- } else {
1313
- typeString = typeof type;
1314
- }
1315
- error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
1316
- }
1317
- var element = jsxDEV(type, props, key, source, self);
1318
- if (element == null) {
1319
- return element;
1320
- }
1321
- if (validType) {
1322
- var children = props.children;
1323
- if (children !== void 0) {
1324
- if (isStaticChildren) {
1325
- if (isArray(children)) {
1326
- for (var i = 0; i < children.length; i++) {
1327
- validateChildKeys(children[i], type);
1328
- }
1329
- if (Object.freeze) {
1330
- Object.freeze(children);
1331
- }
1332
- } else {
1333
- error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
1334
- }
1335
- } else {
1336
- validateChildKeys(children, type);
1337
- }
1338
- }
1339
- }
1340
- {
1341
- if (hasOwnProperty.call(props, "key")) {
1342
- var componentName = getComponentNameFromType(type);
1343
- var keys = Object.keys(props).filter(function(k) {
1344
- return k !== "key";
1345
- });
1346
- var beforeExample = keys.length > 0 ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}";
1347
- if (!didWarnAboutKeySpread[componentName + beforeExample]) {
1348
- var afterExample = keys.length > 0 ? "{" + keys.join(": ..., ") + ": ...}" : "{}";
1349
- error('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);
1350
- didWarnAboutKeySpread[componentName + beforeExample] = true;
1351
- }
1352
- }
1353
- }
1354
- if (type === REACT_FRAGMENT_TYPE) {
1355
- validateFragmentProps(element);
1356
- } else {
1357
- validatePropTypes(element);
1358
- }
1359
- return element;
1360
- }
1361
- }
1362
- function jsxWithValidationStatic(type, props, key) {
1363
- {
1364
- return jsxWithValidation(type, props, key, true);
1365
- }
1366
- }
1367
- function jsxWithValidationDynamic(type, props, key) {
1368
- {
1369
- return jsxWithValidation(type, props, key, false);
1370
- }
1371
- }
1372
- var jsx = jsxWithValidationDynamic;
1373
- var jsxs = jsxWithValidationStatic;
1374
- reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
1375
- reactJsxRuntime_development.jsx = jsx;
1376
- reactJsxRuntime_development.jsxs = jsxs;
1377
- })();
539
+ );
1378
540
  }
1379
- return reactJsxRuntime_development;
1380
- }
1381
- if (process.env.NODE_ENV === "production") {
1382
- jsxRuntime.exports = requireReactJsxRuntime_production_min();
1383
- } else {
1384
- jsxRuntime.exports = requireReactJsxRuntime_development();
1385
541
  }
1386
- var jsxRuntimeExports = jsxRuntime.exports;
1387
542
  const AnalyticsContext = createContext(null);
1388
543
  const useAnalytics = () => {
1389
544
  const context = useContext(AnalyticsContext);
@@ -1476,6 +631,9 @@ const EngageProProvider = ({
1476
631
  const rageClickBuffer = useRef(null);
1477
632
  if (!analyticsRef.current) {
1478
633
  analyticsRef.current = new EngagePro(config);
634
+ if (typeof window !== "undefined") {
635
+ new PerformanceMonitor(analyticsRef.current);
636
+ }
1479
637
  }
1480
638
  const analytics = analyticsRef.current;
1481
639
  useEffect(() => {
@@ -1562,7 +720,7 @@ const EngageProProvider = ({
1562
720
  window.removeEventListener("focusin", handleInput, true);
1563
721
  };
1564
722
  }, [config.tracking.autoTrack]);
1565
- return /* @__PURE__ */ jsxRuntimeExports.jsx(AnalyticsContext.Provider, { value: analytics, children });
723
+ return /* @__PURE__ */ jsx(AnalyticsContext.Provider, { value: analytics, children });
1566
724
  };
1567
725
  let instance = null;
1568
726
  const init = (config) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bluenath/engage",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",