@bluenath/engage 1.0.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/dist/core/Analytics.d.ts +13 -0
- package/dist/core/Context.d.ts +22 -0
- package/dist/core/EventQueue.d.ts +15 -0
- package/dist/core/Queue.d.ts +15 -0
- package/dist/core/Transport.d.ts +7 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +1579 -0
- package/dist/lib/fingerprint.d.ts +11 -0
- package/dist/lib/hash.d.ts +6 -0
- package/dist/lib/storage.d.ts +24 -0
- package/dist/react/EngageProProvider.d.ts +10 -0
- package/dist/types/index.d.ts +63 -0
- package/package.json +40 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { EngageConfig, AnalyticsEvent } from '../types';
|
|
2
|
+
|
|
3
|
+
export declare class EngagePro {
|
|
4
|
+
private config;
|
|
5
|
+
private context;
|
|
6
|
+
private queue;
|
|
7
|
+
private transport;
|
|
8
|
+
constructor(config: EngageConfig);
|
|
9
|
+
identify: (userId: string, traits?: any) => void;
|
|
10
|
+
page: (name?: string, properties?: any) => void;
|
|
11
|
+
track: (eventName: string, properties?: any, intelligence?: Partial<AnalyticsEvent>) => void;
|
|
12
|
+
private processEvent;
|
|
13
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { AnalyticsContext } from '../types';
|
|
2
|
+
|
|
3
|
+
export interface ContextPayload extends AnalyticsContext {
|
|
4
|
+
}
|
|
5
|
+
export declare class Context {
|
|
6
|
+
private storage;
|
|
7
|
+
private readonly SESSION_TIMEOUT;
|
|
8
|
+
deviceId: string;
|
|
9
|
+
sessionId: string;
|
|
10
|
+
userId: string | null;
|
|
11
|
+
currentUrl: string;
|
|
12
|
+
referrer: string;
|
|
13
|
+
constructor(config: {
|
|
14
|
+
persistence: "local" | "cookie" | "memory";
|
|
15
|
+
});
|
|
16
|
+
private getOrSetDeviceId;
|
|
17
|
+
private manageSession;
|
|
18
|
+
private listenToHistory;
|
|
19
|
+
private handleUrlChange;
|
|
20
|
+
getPayload(): AnalyticsContext;
|
|
21
|
+
private getDeviceType;
|
|
22
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { AnalyticsEvent } from '../types';
|
|
2
|
+
import { Transport } from './Transport';
|
|
3
|
+
|
|
4
|
+
export declare class EventQueue {
|
|
5
|
+
private queue;
|
|
6
|
+
private storage;
|
|
7
|
+
private transport;
|
|
8
|
+
private readonly STORAGE_KEY;
|
|
9
|
+
private isFlushing;
|
|
10
|
+
constructor(transport: Transport);
|
|
11
|
+
enqueue(event: AnalyticsEvent): void;
|
|
12
|
+
private save;
|
|
13
|
+
private load;
|
|
14
|
+
flush(): Promise<void>;
|
|
15
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { AnalyticsEvent } from '../types';
|
|
2
|
+
|
|
3
|
+
export declare class EventQueue {
|
|
4
|
+
private queue;
|
|
5
|
+
private storage;
|
|
6
|
+
private readonly STORAGE_KEY;
|
|
7
|
+
constructor();
|
|
8
|
+
enqueue(event: AnalyticsEvent): void;
|
|
9
|
+
private save;
|
|
10
|
+
private load;
|
|
11
|
+
/**
|
|
12
|
+
* Process the queue by passing the sender function
|
|
13
|
+
*/
|
|
14
|
+
flush(sender?: (events: AnalyticsEvent[]) => Promise<boolean>): Promise<void>;
|
|
15
|
+
}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +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};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { EngagePro } from './core/Analytics';
|
|
2
|
+
import { EngageConfig } from './types';
|
|
3
|
+
|
|
4
|
+
export default EngagePro;
|
|
5
|
+
export { EngageProProvider, useAnalytics } from './react/EngageProProvider';
|
|
6
|
+
export * from './types';
|
|
7
|
+
export declare const init: (config: EngageConfig) => EngagePro;
|