@aicore/core-analytics-client-lib 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,20 +19,15 @@ events for [Core-Analytics-Server](https://github.com/aicore/Core-Analytics-Serv
19
19
 
20
20
  # Usage
21
21
 
22
- ## Initialize the session
22
+ ## Load the Library
23
23
  Embed the script in your HTML file :
24
24
  ```html
25
- <html lang="en">
26
- <script type="module">
27
- // For production use cases, use url: https://unpkg.com/@aicore/core-analytics-client-lib/dist/analytics.min.js
28
- // The below url is for development purposes only.
29
- import {initSession} from "https://unpkg.com/@aicore/core-analytics-client-lib/src/analytics.js";
30
- initSession("accountID", "appName");
31
- </script>
32
- </html>
25
+ <script src="https://unpkg.com/@aicore/core-analytics-client-lib/src/analytics.js"></script>
33
26
  ```
27
+ This will create a global `analytics` variable which can be used to access the analytics APIs.
34
28
 
35
- initSession(): Initialize the analytics session. It takes the following parameters:
29
+ ## Initialize the analytics session.
30
+ Call `analytics.initSession()` after loading the library. It takes the following parameters:
36
31
 
37
32
  * `accountID`: Your analytics account id as configured in the server or core.ai analytics
38
33
  * `appName`: The app name to log the events against. Eg: "phoenixCode"
@@ -43,38 +38,41 @@ that any events that happen within 3 seconds cannot be distinguished in ordering
43
38
  * `analyticsURL` (_Optional_): Provide your own analytics server address if you self-hosted the server
44
39
  * `debug` (_Optional_): set to true if you want to see detailed debug logs.
45
40
 
41
+ ### usageExample
46
42
  ```javascript
43
+ // Init with default values.
44
+ analytics.initSession("accountID", "appName");
45
+
47
46
  // Example for custom initSession where the analytics aggregated data
48
47
  // is posted to custom server https://localhost:3000 every 600 secs
49
48
  // with a granularity(resolution) of 5 seconds.
50
-
51
- initSession("accountID", "appName", "https://localhost:3000", 600, 5);
49
+ analytics.initSession("accountID", "appName", "https://localhost:3000", 600, 5);
52
50
 
53
51
  // To initSession in debug mode set debug arg in init to true:
54
- initSession("accountID", "appName", "https://localhost:3000", 600, 5, true);
52
+ analytics.initSession("accountID", "appName", "https://localhost:3000", 600, 5, true);
55
53
  ```
56
54
 
57
55
  ## Raising analytics events
58
- Once `initSession` is called, we can now start logging analytics events by calling `analyticsEvent` API.
56
+ Once `initSession` is called, we can now start logging analytics events by calling `analytics.event` API.
59
57
  The API registers an analytics event. The events will be aggregated and send to the analytics server periodically.
60
58
 
61
59
  ```javascript
62
60
  // analyticsEvent(eventType, eventCategory, subCategory, eventCount, eventValue);
63
61
 
64
62
  // Eg: event without counts and values
65
- analyticsEvent("platform", "os", "linux");
63
+ analytics.event("platform", "os", "linux");
66
64
 
67
65
  // Eg: event with count, here it logs that html file is opened 100 times
68
- analyticsEvent("file", "opened", "html", 100);
66
+ analytics.event("file", "opened", "html", 100);
69
67
 
70
68
  // Eg: event with count and value, here it logs that the startup time is 250 milliseconds.
71
69
  // Note that the value is unitless from analytics perspective. unit is deduced from subCategory name
72
- analyticsEvent("platform", "performance", "startupTimeMs", 1, 250);
70
+ analytics.event("platform", "performance", "startupTimeMs", 1, 250);
73
71
 
74
72
  // Eg: event with fractional value.
75
- analyticsEvent("platform", "CPU", "utilization", 1, .45);
73
+ analytics.event("platform", "CPU", "utilization", 1, .45);
76
74
  // Eg. Here we register that the system has 8 cores with each core having 2300MHz frequency.
77
- analyticsEvent("platform", "CPU", "coreCountsAndFrequencyMhz", 8, 2300);
75
+ analytics.event("platform", "CPU", "coreCountsAndFrequencyMhz", 8, 2300);
78
76
  ```
79
77
  ### API parameters
80
78
  * `eventType` - A string, required
@@ -1,4 +1,4 @@
1
- let accountID,appName,userID,sessionID,postIntervalSeconds,granularitySec,analyticsURL,postURL,serverConfig;const DEFAULT_GRANULARITY_IN_SECONDS=3,DEFAULT_RETRY_TIME_IN_SECONDS=30,DEFAULT_POST_INTERVAL_SECONDS=600,USERID_LOCAL_STORAGE_KEY="aicore.analytics.userID",POST_LARGE_DATA_THRESHOLD_BYTES=1e4;let currentAnalyticsEvent=null;const IS_NODE_ENV="undefined"==typeof window;let DEFAULT_BASE_URL="https://analytics.core.ai",granularityTimer,postTimer,currentQuantisedTime=0,disabled=!1,debugMode=!1;function debugLog(...e){debugMode&&console.log(...e)}function debugError(...e){debugMode&&console.error(...e)}if(IS_NODE_ENV)throw new Error("Node environment is not currently supported");function _createAnalyticsEvent(){return{schemaVersion:1,accountID:accountID,appName:appName,uuid:userID,sessionID:sessionID,unixTimestampUTC:+new Date,numEventsTotal:0,events:{}}}function _validateCurrentState(){if(!currentAnalyticsEvent)throw new Error("Please call initSession before using any analytics event")}function getCurrentAnalyticsEvent(){return _validateCurrentState(),JSON.parse(JSON.stringify(currentAnalyticsEvent))}function _getOrCreateUserID(){let e=localStorage.getItem(USERID_LOCAL_STORAGE_KEY);return e||(e=crypto.randomUUID(),localStorage.setItem(USERID_LOCAL_STORAGE_KEY,e)),e}function _getOrCreateSessionID(){let e=sessionStorage.getItem(USERID_LOCAL_STORAGE_KEY);return e||(e=Math.random().toString(36).substr(2,10),sessionStorage.setItem(USERID_LOCAL_STORAGE_KEY,e)),e}function _setupIDs(){userID=_getOrCreateUserID(),sessionID=_getOrCreateSessionID()}function _retryPost(e){e.backoffCount=(e.backoffCount||0)+1,debugLog(`Failed to call core analytics server. Will retry in ${DEFAULT_RETRY_TIME_IN_SECONDS*e.backoffCount}s: `),setTimeout(()=>{_postCurrentAnalyticsEvent(e)},1e3*DEFAULT_RETRY_TIME_IN_SECONDS*e.backoffCount)}function _postCurrentAnalyticsEvent(t){var e;disabled||(t||(t=currentAnalyticsEvent,currentQuantisedTime=0,_resetGranularityTimer(),currentAnalyticsEvent=_createAnalyticsEvent()),0!==t.numEventsTotal&&((e=JSON.stringify(t)).length>POST_LARGE_DATA_THRESHOLD_BYTES&&console.warn(`Analytics event generated is very large at greater than ${e.length}B. This
2
- typically means that you may be sending too many value events? .`),debugLog("Sending Analytics data of length: ",e.length,"B"),window.fetch(postURL,{method:"POST",headers:{"Content-Type":"application/json"},body:e}).then(e=>{200!==e.status&&(400!==e.status?_retryPost(t):console.error("Analytics client: Bad Request, this is most likely a problem with the library, update to latest version."))}).catch(e=>{debugError(e),_retryPost(t)})))}function _resetGranularityTimer(e){granularityTimer&&(clearInterval(granularityTimer),granularityTimer=null),e||(granularityTimer=setInterval(()=>{currentQuantisedTime+=granularitySec},1e3*granularitySec))}function _setupTimers(e){_resetGranularityTimer(e),postTimer&&(clearInterval(postTimer),postTimer=null),e||(postTimer=setInterval(_postCurrentAnalyticsEvent,1e3*postIntervalSeconds))}async function _getServerConfig(){return new Promise((n,r)=>{var e=analyticsURL+(`/getAppConfig?accountID=${accountID}&appName=`+appName);window.fetch(e).then(async e=>{switch(e.status){case 200:var t=await e.json();return void n(t);case 400:r("Bad Request, check library version compatible?",e);break;default:r("analytics client: Could not update from remote config. Continuing with defaults.",e)}}).catch(e=>{r("analytics client: Could not update from remote config. Continuing with defaults.",e)})})}function getAppConfig(){return{accountID:accountID,appName:appName,disabled:disabled,uuid:userID,sessionID:sessionID,postIntervalSeconds:postIntervalSeconds,granularitySec:granularitySec,analyticsURL:analyticsURL,serverConfig:serverConfig}}async function _initFromRemoteConfig(e,t){(serverConfig=await _getServerConfig())!=={}&&(postIntervalSeconds=e||serverConfig.postIntervalSecondsInit||DEFAULT_POST_INTERVAL_SECONDS,granularitySec=t||serverConfig.granularitySecInit||DEFAULT_GRANULARITY_IN_SECONDS,analyticsURL=serverConfig.analyticsURLInit||analyticsURL||DEFAULT_BASE_URL,_setupTimers(disabled=!0===serverConfig.disabled),debugLog(`Init analytics Config from remote. disabled: ${disabled}
3
- postIntervalSeconds:${postIntervalSeconds}, granularitySec: ${granularitySec} ,URL: `+analyticsURL),disabled&&console.warn(`Core Analytics is disabled from the server for app: ${accountID}:`+appName))}function _stripTrailingSlash(e){return e.replace(/\/$/,"")}function initSession(e,t,n,r,a,i){if(!e||!t)throw new Error("accountID and appName must exist for init");analyticsURL=n?_stripTrailingSlash(n):DEFAULT_BASE_URL,accountID=e,appName=t,debugMode=i||!1,postIntervalSeconds=r||DEFAULT_POST_INTERVAL_SECONDS,granularitySec=a||DEFAULT_GRANULARITY_IN_SECONDS,postURL=analyticsURL+"/ingest",_setupIDs(),currentAnalyticsEvent=_createAnalyticsEvent(),_setupTimers(),_initFromRemoteConfig(r,a)}function _ensureAnalyticsEventExists(e,t,n){let r=currentAnalyticsEvent.events;r[e]=r[e]||{},r[e][t]=r[e][t]||{},r[e][t][n]=r[e][t][n]||{time:[],valueCount:[]}}function _validateEvent(e,t,n,r,a){if(_validateCurrentState(),!e||!t||!n)throw new Error("missing eventType or category or subCategory");if("number"!=typeof r||r<0)throw new Error("invalid count");if("number"!=typeof a)throw new Error("invalid value")}function _updateExistingAnalyticsEvent(t,n,r,a,i,s){let o=currentAnalyticsEvent.events;var e="number"==typeof o[n][r][a].valueCount[t];if(e&&0===s)o[n][r][a].valueCount[t]+=i;else if(e&&0!==s){let e={};e[s]=i,e[0]=o[n][r][a].valueCount[t],o[n][r][a].valueCount[t]=e}else if(!e){let e=o[n][r][a].valueCount[t];e[s]=(e[s]||0)+i}currentAnalyticsEvent.numEventsTotal+=1}function analyticsEvent(n,r,a,i=1,s=0){if(!disabled){_validateEvent(n,r,a,i,s),_ensureAnalyticsEventExists(n,r,a);let t=currentAnalyticsEvent.events;var e=t[n][r][a].time;if((0<e.length?e[e.length-1]:null)!==currentQuantisedTime){if(t[n][r][a].time.push(currentQuantisedTime),0===s)t[n][r][a].valueCount.push(i);else{let e={};e[s]=i,t[n][r][a].valueCount.push(e)}currentAnalyticsEvent.numEventsTotal+=1}else _updateExistingAnalyticsEvent(t[n][r][a].valueCount.length-1,n,r,a,i,s)}}export{initSession,getCurrentAnalyticsEvent,analyticsEvent,getAppConfig};
1
+ var analytics={};function init(){let r,s,e,t,l,u,c,f,n;const v=3,a=30,y=600,o="aicore.analytics.userID",i=1e4;let d=null;var m="undefined"==typeof window;let g="https://analytics.core.ai",p,h,w=0,C=!1,I=!1;function b(...e){I&&console.log(...e)}if(m)throw new Error("Node environment is not currently supported");function S(){return{schemaVersion:1,accountID:r,appName:s,uuid:e,sessionID:t,unixTimestampUTC:+new Date,numEventsTotal:0,events:{}}}function E(){if(!d)throw new Error("Please call initSession before using any analytics event")}function T(){e=function(){let e=localStorage.getItem(o);return e||(e=crypto.randomUUID(),localStorage.setItem(o,e)),e}(),t=function(){let e=sessionStorage.getItem(o);return e||(e=Math.random().toString(36).substr(2,10),sessionStorage.setItem(o,e)),e}()}function D(e){e.backoffCount=(e.backoffCount||0)+1,b(`Failed to call core analytics server. Will retry in ${a*e.backoffCount}s: `),setTimeout(()=>{N(e)},1e3*a*e.backoffCount)}function N(t){var e;C||(t||(t=d,w=0,$(),d=S()),0!==t.numEventsTotal&&((e=JSON.stringify(t)).length>i&&console.warn(`Analytics event generated is very large at greater than ${e.length}B. This
2
+ typically means that you may be sending too many value events? .`),b("Sending Analytics data of length: ",e.length,"B"),window.fetch(f,{method:"POST",headers:{"Content-Type":"application/json"},body:e}).then(e=>{200!==e.status&&(400!==e.status?D(t):console.error("Analytics client: Bad Request, this is most likely a problem with the library, update to latest version."))}).catch(e=>{e=[e],I&&console.error(...e),D(t)})))}function $(e){p&&(clearInterval(p),p=null),e||(p=setInterval(()=>{w+=u},1e3*u))}function k(e){$(e),h&&(clearInterval(h),h=null),e||(h=setInterval(N,1e3*l))}async function A(e,t){(n=await new Promise((n,a)=>{var e=c+(`/getAppConfig?accountID=${r}&appName=`+s);window.fetch(e).then(async e=>{switch(e.status){case 200:var t=await e.json();return void n(t);case 400:a("Bad Request, check library version compatible?",e);break;default:a("analytics client: Could not update from remote config. Continuing with defaults.",e)}}).catch(e=>{a("analytics client: Could not update from remote config. Continuing with defaults.",e)})}))!=={}&&(l=e||n.postIntervalSecondsInit||y,u=t||n.granularitySecInit||v,c=n.analyticsURLInit||c||g,k(C=!0===n.disabled),b(`Init analytics Config from remote. disabled: ${C}
3
+ postIntervalSeconds:${l}, granularitySec: ${u} ,URL: `+c),C&&console.warn(`Core Analytics is disabled from the server for app: ${r}:`+s))}analytics.initSession=function(e,t,n,a,o,i){if(!e||!t)throw new Error("accountID and appName must exist for init");c=n?n.replace(/\/$/,""):g,r=e,s=t,I=i||!1,l=a||y,u=o||v,f=c+"/ingest",T(),d=S(),k(),A(a,o)},analytics.getCurrentAnalyticsEvent=function(){return E(),JSON.parse(JSON.stringify(d))},analytics.event=function(n,a,o,i=1,r=0){if(!C){var s=n,l=a,u=o,c=i,f=r;if(E(),!s||!l||!u)throw new Error("missing eventType or category or subCategory");if("number"!=typeof c||c<0)throw new Error("invalid count");if("number"!=typeof f)throw new Error("invalid value");{s=n;l=a;u=o;let e=d.events;e[s]=e[s]||{},e[s][l]=e[s][l]||{},e[s][l][u]=e[s][l][u]||{time:[],valueCount:[]}}let t=d.events;c=t[n][a][o].time;if((0<c.length?c[c.length-1]:null)===w){f=t[n][a][o].valueCount.length-1;{var s=f,l=n,u=a,c=o,f=i,v=r;let t=d.events;var e="number"==typeof t[l][u][c].valueCount[s];if(e&&0===v)t[l][u][c].valueCount[s]+=f;else if(e&&0!==v){let e={};e[v]=f,e[0]=t[l][u][c].valueCount[s],t[l][u][c].valueCount[s]=e}else if(!e){let e=t[l][u][c].valueCount[s];e[v]=(e[v]||0)+f}d.numEventsTotal+=1}}else{if(t[n][a][o].time.push(w),0===r)t[n][a][o].valueCount.push(i);else{let e={};e[r]=i,t[n][a][o].valueCount.push(e)}d.numEventsTotal+=1}}},analytics.getAppConfig=function(){return{accountID:r,appName:s,disabled:C,uuid:e,sessionID:t,postIntervalSeconds:l,granularitySec:u,analyticsURL:c,serverConfig:n}}}init();
4
4
  //# sourceMappingURL=analytics.min.js.map
@@ -1 +1 @@
1
- {"version":3,"sourceRoot":"src/analytics.js","sources":["src/analytics.js"],"names":["let","accountID","appName","userID","sessionID","postIntervalSeconds","granularitySec","analyticsURL","postURL","serverConfig","DEFAULT_GRANULARITY_IN_SECONDS","DEFAULT_RETRY_TIME_IN_SECONDS","DEFAULT_POST_INTERVAL_SECONDS","USERID_LOCAL_STORAGE_KEY","POST_LARGE_DATA_THRESHOLD_BYTES","currentAnalyticsEvent","IS_NODE_ENV","window","DEFAULT_BASE_URL","granularityTimer","postTimer","currentQuantisedTime","disabled","debugMode","debugLog","args","console","log","debugError","error","Error","_createAnalyticsEvent","schemaVersion","uuid","unixTimestampUTC","Date","numEventsTotal","events","_validateCurrentState","getCurrentAnalyticsEvent","JSON","parse","stringify","_getOrCreateUserID","localUserID","localStorage","getItem","crypto","randomUUID","setItem","_getOrCreateSessionID","localSessionID","sessionStorage","Math","random","toString","substr","_setupIDs","_retryPost","eventToSend","backoffCount","setTimeout","_postCurrentAnalyticsEvent","textToSend","_resetGranularityTimer","length","warn","fetch","method","headers","Content-Type","body","then","res","status","catch","disable","clearInterval","setInterval","_setupTimers","async","_getServerConfig","Promise","resolve","reject","configURL","serverResponse","json","err","getAppConfig","_initFromRemoteConfig","postIntervalSecondsInit","granularitySecInit","_stripTrailingSlash","url","replace","initSession","accountIDInit","appNameInit","analyticsURLInit","debug","_ensureAnalyticsEventExists","eventType","category","subCategory","time","valueCount","_validateEvent","count","value","_updateExistingAnalyticsEvent","index","newValue","storedValueIsCount","newValueCount","storedValueObject","analyticsEvent","eventCategory","eventCount","eventValue","timeArray","push"],"mappings":"AAKAA,IAAIC,UAAWC,QAASC,OAAQC,UAAWC,oBAAqBC,eAAgBC,aAAcC,QAASC,aACvG,MAAMC,+BAAiC,EACjCC,8BAAgC,GAChCC,8BAAgC,IAChCC,yBAA2B,0BAC3BC,gCAAkC,IACxCd,IAAIe,sBAAwB,KAC5B,MAAMC,YAAiC,oBAAXC,OAC5BjB,IAAIkB,iBAAmB,4BAEnBC,iBACAC,UACAC,qBAAuB,EACvBC,UAAW,EACXC,WAAY,EAEhB,SAASC,YAAYC,GACbF,WAGJG,QAAQC,OAAOF,GAGnB,SAASG,cAAcH,GACfF,WAGJG,QAAQG,SAASJ,GAIrB,GAAGT,YACC,MAAM,IAAIc,MAAM,+CAGpB,SAASC,wBACL,MAA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OiE,GAAWC,GAAUC,GAAyB,WAAEO,GAC/EI,EAAkBH,IAAaG,EAAkBH,IAAa,GAAKJ,EAEvE7F,sBAAsBqB,gBAAkB,EAY5C,SAASgF,eAAed,EAAWe,EAAeb,EAAac,EAAW,EAAGC,EAAW,GACpF,IAAGjG,SAAH,CAGAqF,eAAeL,EAAWe,EAAeb,EAAac,EAAYC,GAClElB,4BAA4BC,EAAWe,EAAeb,GACtDxG,IAAIqC,EAAStB,sBAAsBsB,OACnCrC,IAAIwH,EAAYnF,EAAOiE,GAAWe,GAAeb,GAAmB,KAEpE,IADgC,EAAjBgB,EAAUvD,OAAUuD,EAAUA,EAAUvD,OAAO,GAAK,QACnD5C,qBAAhB,CAEI,GADAgB,EAAOiE,GAAWe,GAAeb,GAAmB,KAAEiB,KAAKpG,sBAC3C,IAAbkG,EACClF,EAAOiE,GAAWe,GAAeb,GAAyB,WAAEiB,KAAKH,OAC9D,CACHtH,IAAI0G,EAAa,GACjBA,EAAWa,GAAcD,EACzBjF,EAAOiE,GAAWe,GAAeb,GAAyB,WAAEiB,KAAKf,GAErE3F,sBAAsBqB,gBAAkB,OAI5C0E,8BADwBzE,EAAOiE,GAAWe,GAAeb,GAAyB,WAAEvC,OAAQ,EAC3CqC,EAAWe,EAAeb,EAAac,EAAYC,WAIpGvB,YACAzD,yBACA6E,eACA3B"}
1
+ {"version":3,"sourceRoot":"src/analytics.js","sources":["src/analytics.js"],"names":["analytics","init","let","accountID","appName","userID","sessionID","postIntervalSeconds","granularitySec","analyticsURL","postURL","serverConfig","DEFAULT_GRANULARITY_IN_SECONDS","DEFAULT_RETRY_TIME_IN_SECONDS","DEFAULT_POST_INTERVAL_SECONDS","USERID_LOCAL_STORAGE_KEY","POST_LARGE_DATA_THRESHOLD_BYTES","currentAnalyticsEvent","IS_NODE_ENV","window","DEFAULT_BASE_URL","granularityTimer","postTimer","currentQuantisedTime","disabled","debugMode","debugLog","args","console","log","Error","_createAnalyticsEvent","schemaVersion","uuid","unixTimestampUTC","Date","numEventsTotal","events","_validateCurrentState","_setupIDs","localUserID","localStorage","getItem","crypto","randomUUID","setItem","_getOrCreateUserID","localSessionID","sessionStorage","Math","random","toString","substr","_getOrCreateSessionID","_retryPost","eventToSend","backoffCount","setTimeout","_postCurrentAnalyticsEvent","textToSend","_resetGranularityTimer","JSON","stringify","length","warn","fetch","method","headers","Content-Type","body","then","res","status","error","catch","debugError","disable","clearInterval","setInterval","_setupTimers","async","_initFromRemoteConfig","postIntervalSecondsInit","granularitySecInit","Promise","resolve","reject","configURL","serverResponse","json","err","initSession","accountIDInit","appNameInit","analyticsURLInit","debug","replace","getCurrentAnalyticsEvent","parse","event","eventType","eventCategory","subCategory","eventCount","eventValue","_validateEvent","category","count","value","_ensureAnalyticsEventExists","time","valueCount","timeArray","modificationIndex","_updateExistingAnalyticsEvent","index","newValue","storedValueIsCount","newValueCount","storedValueObject","push","getAppConfig"],"mappings":"AAKA,IAAIA,UAAY,GAEhB,SAASC,OACLC,IAAIC,EAAWC,EAASC,EAAQC,EAAWC,EAAqBC,EAAgBC,EAAcC,EAASC,EACvG,MAAMC,EAAiC,EACjCC,EAAgC,GAChCC,EAAgC,IAChCC,EAA2B,0BAC3BC,EAAkC,IACxCd,IAAIe,EAAwB,KAC5B,IAAMC,EAAiC,oBAAXC,OAC5BjB,IAAIkB,EAAmB,4BAEnBC,EACAC,EACAC,EAAuB,EACvBC,GAAW,EACXC,GAAY,EAEhB,SAASC,KAAYC,GACbF,GAGJG,QAAQC,OAAOF,GAWnB,GAAGT,EACC,MAAM,IAAIY,MAAM,+CAGpB,SAASC,IACL,MAAO,CACHC,cAAe,EACf7B,UAAWA,EACXC,QAASA,EACT6B,KAAM5B,EACNC,UAAWA,EACX4B,kBAAmB,IAAIC,KACvBC,eAAgB,EAChBC,OAAQ,IAIhB,SAASC,IACL,IAAIrB,EACA,MAAM,IAAIa,MAAM,4DA4BxB,SAASS,IACLlC,EAnBJ,WACIH,IAAIsC,EAAcC,aAAaC,QAA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CAC1BnH,IAAIqH,EAAoBlF,EAAO+D,GAAWM,GAAUJ,GAAyB,WAAEa,GAC/EI,EAAkBH,IAAaG,EAAkBH,IAAa,GAAKT,EAEvE1F,EAAsBmB,gBAAkB,OAqBxC,CAEI,GADAC,EAAO+D,GAAWC,GAAeC,GAAmB,KAAEkB,KAAKjG,GAC3C,IAAbiF,EACCnE,EAAO+D,GAAWC,GAAeC,GAAyB,WAAEkB,KAAKjB,OAC9D,CACHrG,IAAI6G,EAAa,GACjBA,EAAWP,GAAcD,EACzBlE,EAAO+D,GAAWC,GAAeC,GAAyB,WAAEkB,KAAKT,GAErE9F,EAAsBmB,gBAAkB,KAUhDpC,UAAUyH,aAzIV,WACI,MAAO,CACHtH,UAAAA,EAAWC,QAAAA,EAASoB,SAAAA,EACpBS,KAAM5B,EAAQC,UAAAA,EACdC,oBAAAA,EAAqBC,eAAAA,EAAgBC,aAAAA,EAAcE,aAAAA,IAwI/DV"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aicore/core-analytics-client-lib",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "Analytics client library for https://github.com/aicore/Core-Analytics-Server",
5
5
  "main": "dist/analytics.min.js",
6
6
  "type": "module",
@@ -19,17 +19,18 @@
19
19
  "lint": "eslint --quiet src test",
20
20
  "lint:fix": "eslint --quiet --fix src test",
21
21
  "prepare": "husky install",
22
- "test": "echo please open test/index.html in browser to run tests",
23
- "test:unit": "echo please open test/index.html in browser to run tests",
22
+ "test": "echo please run - npm run serve - and then open test/unit-test.html in browser to run tests",
23
+ "test:unit": "npm run test",
24
24
  "test:integ": "echo integration tests are disabled in this repo",
25
- "cover": "echo please open test/index.html in browser to run tests",
26
- "cover:unit": "echo please open test/index.html in browser to run tests",
27
- "cover:integ": "echo please open test/index.html in browser to run tests",
28
- "build": "",
25
+ "cover": "echo no coverage for now",
26
+ "cover:unit": "echo no coverage for now",
27
+ "cover:integ": "echo no coverage for now",
28
+ "build": "npm run minify",
29
29
  "minify": "echo creating minified package dist/analytics.min.js && mkdir -p dist && uglifyjs src/analytics.js --compress --mangle -o dist/analytics.min.js -c -m --source-map \"root='src/analytics.js',url='analytics.min.js.map'\"",
30
30
  "bumpPatchVersion": "npm --no-git-tag-version version patch",
31
31
  "bumpPatchVersionWithGitTag": "npm version patch",
32
- "release": "npm run minify && npm run bumpPatchVersionWithGitTag"
32
+ "release": "npm run minify && npm run bumpPatchVersionWithGitTag",
33
+ "serve": "http-server . -p 8000 -c-1"
33
34
  },
34
35
  "files": [
35
36
  "src",
@@ -53,6 +54,7 @@
53
54
  "eslint": "8.15.0",
54
55
  "husky": "7.0.4",
55
56
  "mocha": "9.2.2",
56
- "uglify-js": "3.15.5"
57
+ "uglify-js": "3.15.5",
58
+ "http-server": "14.1.0"
57
59
  }
58
60
  }
package/src/analytics.js CHANGED
@@ -3,324 +3,328 @@
3
3
  // jshint ignore: start
4
4
  /*global localStorage, sessionStorage, crypto*/
5
5
 
6
- let accountID, appName, userID, sessionID, postIntervalSeconds, granularitySec, analyticsURL, postURL, serverConfig;
7
- const DEFAULT_GRANULARITY_IN_SECONDS = 3;
8
- const DEFAULT_RETRY_TIME_IN_SECONDS = 30;
9
- const DEFAULT_POST_INTERVAL_SECONDS = 600; // 10 minutes
10
- const USERID_LOCAL_STORAGE_KEY = 'aicore.analytics.userID';
11
- const POST_LARGE_DATA_THRESHOLD_BYTES = 10000;
12
- let currentAnalyticsEvent = null;
13
- const IS_NODE_ENV = (typeof window === 'undefined');
14
- let DEFAULT_BASE_URL = "https://analytics.core.ai";
6
+ var analytics = {};
15
7
 
16
- let granularityTimer;
17
- let postTimer;
18
- let currentQuantisedTime = 0;
19
- let disabled = false;
20
- let debugMode = false;
8
+ function init() {
9
+ let accountID, appName, userID, sessionID, postIntervalSeconds, granularitySec, analyticsURL, postURL, serverConfig;
10
+ const DEFAULT_GRANULARITY_IN_SECONDS = 3;
11
+ const DEFAULT_RETRY_TIME_IN_SECONDS = 30;
12
+ const DEFAULT_POST_INTERVAL_SECONDS = 600; // 10 minutes
13
+ const USERID_LOCAL_STORAGE_KEY = 'aicore.analytics.userID';
14
+ const POST_LARGE_DATA_THRESHOLD_BYTES = 10000;
15
+ let currentAnalyticsEvent = null;
16
+ const IS_NODE_ENV = (typeof window === 'undefined');
17
+ let DEFAULT_BASE_URL = "https://analytics.core.ai";
21
18
 
22
- function debugLog(...args) {
23
- if(!debugMode){
24
- return;
25
- }
26
- console.log(...args);
27
- }
19
+ let granularityTimer;
20
+ let postTimer;
21
+ let currentQuantisedTime = 0;
22
+ let disabled = false;
23
+ let debugMode = false;
28
24
 
29
- function debugError(...args) {
30
- if(!debugMode){
31
- return;
25
+ function debugLog(...args) {
26
+ if(!debugMode){
27
+ return;
28
+ }
29
+ console.log(...args);
32
30
  }
33
- console.error(...args);
34
- }
35
-
36
31
 
37
- if(IS_NODE_ENV){
38
- throw new Error("Node environment is not currently supported");
39
- }
40
-
41
- function _createAnalyticsEvent() {
42
- return {
43
- schemaVersion: 1,
44
- accountID: accountID,
45
- appName: appName,
46
- uuid: userID,
47
- sessionID: sessionID,
48
- unixTimestampUTC: +new Date(),
49
- numEventsTotal: 0,
50
- events: {}
51
- };
52
- }
53
-
54
- function _validateCurrentState() {
55
- if(!currentAnalyticsEvent){
56
- throw new Error("Please call initSession before using any analytics event");
32
+ function debugError(...args) {
33
+ if(!debugMode){
34
+ return;
35
+ }
36
+ console.error(...args);
57
37
  }
58
- }
59
38
 
60
- function getCurrentAnalyticsEvent() {
61
- _validateCurrentState();
62
- // return a clone
63
- return JSON.parse(JSON.stringify(currentAnalyticsEvent));
64
- }
65
39
 
66
- function _getOrCreateUserID() {
67
- let localUserID = localStorage.getItem(USERID_LOCAL_STORAGE_KEY);
68
- if(!localUserID){
69
- localUserID = crypto.randomUUID();
70
- localStorage.setItem(USERID_LOCAL_STORAGE_KEY, localUserID);
40
+ if(IS_NODE_ENV){
41
+ throw new Error("Node environment is not currently supported");
71
42
  }
72
- return localUserID;
73
- }
74
43
 
75
- function _getOrCreateSessionID() {
76
- let localSessionID = sessionStorage.getItem(USERID_LOCAL_STORAGE_KEY);
77
- if(!localSessionID){
78
- localSessionID = Math.random().toString(36).substr(2, 10);
79
- sessionStorage.setItem(USERID_LOCAL_STORAGE_KEY, localSessionID);
44
+ function _createAnalyticsEvent() {
45
+ return {
46
+ schemaVersion: 1,
47
+ accountID: accountID,
48
+ appName: appName,
49
+ uuid: userID,
50
+ sessionID: sessionID,
51
+ unixTimestampUTC: +new Date(),
52
+ numEventsTotal: 0,
53
+ events: {}
54
+ };
80
55
  }
81
- return localSessionID;
82
- }
83
56
 
84
- function _setupIDs() {
85
- userID = _getOrCreateUserID();
86
- sessionID = _getOrCreateSessionID();
87
- }
57
+ function _validateCurrentState() {
58
+ if(!currentAnalyticsEvent){
59
+ throw new Error("Please call initSession before using any analytics event");
60
+ }
61
+ }
88
62
 
89
- function _retryPost(eventToSend) {
90
- eventToSend.backoffCount = (eventToSend.backoffCount || 0) + 1;
91
- debugLog(`Failed to call core analytics server. Will retry in ${
92
- DEFAULT_RETRY_TIME_IN_SECONDS * eventToSend.backoffCount}s: `);
93
- setTimeout(()=>{
94
- _postCurrentAnalyticsEvent(eventToSend);
95
- }, DEFAULT_RETRY_TIME_IN_SECONDS * 1000 * eventToSend.backoffCount);
96
- }
63
+ function getCurrentAnalyticsEvent() {
64
+ _validateCurrentState();
65
+ // return a clone
66
+ return JSON.parse(JSON.stringify(currentAnalyticsEvent));
67
+ }
97
68
 
98
- function _postCurrentAnalyticsEvent(eventToSend) {
99
- if(disabled){
100
- return;
69
+ function _getOrCreateUserID() {
70
+ let localUserID = localStorage.getItem(USERID_LOCAL_STORAGE_KEY);
71
+ if(!localUserID){
72
+ localUserID = crypto.randomUUID();
73
+ localStorage.setItem(USERID_LOCAL_STORAGE_KEY, localUserID);
74
+ }
75
+ return localUserID;
101
76
  }
102
- if(!eventToSend){
103
- eventToSend = currentAnalyticsEvent;
104
- currentQuantisedTime = 0;
105
- _resetGranularityTimer();
106
- currentAnalyticsEvent = _createAnalyticsEvent();
77
+
78
+ function _getOrCreateSessionID() {
79
+ let localSessionID = sessionStorage.getItem(USERID_LOCAL_STORAGE_KEY);
80
+ if(!localSessionID){
81
+ localSessionID = Math.random().toString(36).substr(2, 10);
82
+ sessionStorage.setItem(USERID_LOCAL_STORAGE_KEY, localSessionID);
83
+ }
84
+ return localSessionID;
107
85
  }
108
- if(eventToSend.numEventsTotal === 0 ){
109
- return;
86
+
87
+ function _setupIDs() {
88
+ userID = _getOrCreateUserID();
89
+ sessionID = _getOrCreateSessionID();
110
90
  }
111
- let textToSend = JSON.stringify(eventToSend);
112
- if(textToSend.length > POST_LARGE_DATA_THRESHOLD_BYTES){
113
- console.warn(`Analytics event generated is very large at greater than ${textToSend.length}B. This
114
- typically means that you may be sending too many value events? .`);
91
+
92
+ function _retryPost(eventToSend) {
93
+ eventToSend.backoffCount = (eventToSend.backoffCount || 0) + 1;
94
+ debugLog(`Failed to call core analytics server. Will retry in ${
95
+ DEFAULT_RETRY_TIME_IN_SECONDS * eventToSend.backoffCount}s: `);
96
+ setTimeout(()=>{
97
+ _postCurrentAnalyticsEvent(eventToSend);
98
+ }, DEFAULT_RETRY_TIME_IN_SECONDS * 1000 * eventToSend.backoffCount);
115
99
  }
116
- debugLog("Sending Analytics data of length: ", textToSend.length, "B");
117
- window.fetch(postURL, {
118
- method: "POST",
119
- headers: {'Content-Type': 'application/json'},
120
- body: textToSend
121
- }).then(res=>{
122
- if(res.status === 200){
100
+
101
+ function _postCurrentAnalyticsEvent(eventToSend) {
102
+ if(disabled){
123
103
  return;
124
104
  }
125
- if(res.status !== 400){ // we don't retry bad requests
126
- _retryPost(eventToSend);
127
- } else {
128
- console.error("Analytics client: " +
129
- "Bad Request, this is most likely a problem with the library, update to latest version.");
105
+ if(!eventToSend){
106
+ eventToSend = currentAnalyticsEvent;
107
+ currentQuantisedTime = 0;
108
+ _resetGranularityTimer();
109
+ currentAnalyticsEvent = _createAnalyticsEvent();
130
110
  }
131
- }).catch(res => {
132
- debugError(res);
133
- _retryPost(eventToSend);
134
- });
135
- }
136
-
137
- function _resetGranularityTimer(disable) {
138
- if(granularityTimer){
139
- clearInterval(granularityTimer);
140
- granularityTimer = null;
141
- }
142
- if(disable){
143
- return;
111
+ if(eventToSend.numEventsTotal === 0 ){
112
+ return;
113
+ }
114
+ let textToSend = JSON.stringify(eventToSend);
115
+ if(textToSend.length > POST_LARGE_DATA_THRESHOLD_BYTES){
116
+ console.warn(`Analytics event generated is very large at greater than ${textToSend.length}B. This
117
+ typically means that you may be sending too many value events? .`);
118
+ }
119
+ debugLog("Sending Analytics data of length: ", textToSend.length, "B");
120
+ window.fetch(postURL, {
121
+ method: "POST",
122
+ headers: {'Content-Type': 'application/json'},
123
+ body: textToSend
124
+ }).then(res=>{
125
+ if(res.status === 200){
126
+ return;
127
+ }
128
+ if(res.status !== 400){ // we don't retry bad requests
129
+ _retryPost(eventToSend);
130
+ } else {
131
+ console.error("Analytics client: " +
132
+ "Bad Request, this is most likely a problem with the library, update to latest version.");
133
+ }
134
+ }).catch(res => {
135
+ debugError(res);
136
+ _retryPost(eventToSend);
137
+ });
144
138
  }
145
- granularityTimer = setInterval(()=>{
146
- currentQuantisedTime = currentQuantisedTime + granularitySec;
147
- }, granularitySec*1000);
148
- }
149
139
 
150
- function _setupTimers(disable) {
151
- _resetGranularityTimer(disable);
152
- if(postTimer){
153
- clearInterval(postTimer);
154
- postTimer = null;
140
+ function _resetGranularityTimer(disable) {
141
+ if(granularityTimer){
142
+ clearInterval(granularityTimer);
143
+ granularityTimer = null;
144
+ }
145
+ if(disable){
146
+ return;
147
+ }
148
+ granularityTimer = setInterval(()=>{
149
+ currentQuantisedTime = currentQuantisedTime + granularitySec;
150
+ }, granularitySec*1000);
155
151
  }
156
- if(disable){
157
- return;
152
+
153
+ function _setupTimers(disable) {
154
+ _resetGranularityTimer(disable);
155
+ if(postTimer){
156
+ clearInterval(postTimer);
157
+ postTimer = null;
158
+ }
159
+ if(disable){
160
+ return;
161
+ }
162
+ postTimer = setInterval(_postCurrentAnalyticsEvent, postIntervalSeconds*1000);
158
163
  }
159
- postTimer = setInterval(_postCurrentAnalyticsEvent, postIntervalSeconds*1000);
160
- }
161
164
 
162
- async function _getServerConfig() {
163
- return new Promise((resolve, reject)=>{
164
- let configURL = analyticsURL + `/getAppConfig?accountID=${accountID}&appName=${appName}`;
165
- window.fetch(configURL).then(async res=>{
166
- switch (res.status) {
167
- case 200:
168
- let serverResponse = await res.json();
169
- resolve(serverResponse);
170
- return;
171
- case 400:
172
- reject("Bad Request, check library version compatible?", res);
173
- break;
174
- default:
175
- reject("analytics client: Could not update from remote config. Continuing with defaults.", res);
176
- }
177
- }).catch(err => {
178
- reject("analytics client: Could not update from remote config. Continuing with defaults.", err);
165
+ async function _getServerConfig() {
166
+ return new Promise((resolve, reject)=>{
167
+ let configURL = analyticsURL + `/getAppConfig?accountID=${accountID}&appName=${appName}`;
168
+ window.fetch(configURL).then(async res=>{
169
+ switch (res.status) {
170
+ case 200:
171
+ let serverResponse = await res.json();
172
+ resolve(serverResponse);
173
+ return;
174
+ case 400:
175
+ reject("Bad Request, check library version compatible?", res);
176
+ break;
177
+ default:
178
+ reject("analytics client: Could not update from remote config. Continuing with defaults.", res);
179
+ }
180
+ }).catch(err => {
181
+ reject("analytics client: Could not update from remote config. Continuing with defaults.", err);
182
+ });
179
183
  });
180
- });
181
- }
184
+ }
182
185
 
183
- /**
184
- * Returns the analytics config for the app
185
- * @returns {Object}
186
- */
187
- function getAppConfig() {
188
- return {
189
- accountID, appName, disabled,
190
- uuid: userID, sessionID,
191
- postIntervalSeconds, granularitySec, analyticsURL, serverConfig
192
- };
193
- }
186
+ /**
187
+ * Returns the analytics config for the app
188
+ * @returns {Object}
189
+ */
190
+ function getAppConfig() {
191
+ return {
192
+ accountID, appName, disabled,
193
+ uuid: userID, sessionID,
194
+ postIntervalSeconds, granularitySec, analyticsURL, serverConfig
195
+ };
196
+ }
194
197
 
195
- async function _initFromRemoteConfig(postIntervalSecondsInit, granularitySecInit) {
196
- serverConfig = await _getServerConfig();
197
- if(serverConfig !== {}){
198
- // User init overrides takes precedence over server overrides
199
- postIntervalSeconds = postIntervalSecondsInit ||
200
- serverConfig["postIntervalSecondsInit"] || DEFAULT_POST_INTERVAL_SECONDS;
201
- granularitySec = granularitySecInit || serverConfig["granularitySecInit"] || DEFAULT_GRANULARITY_IN_SECONDS;
202
- // For URLs, the server suggested URL takes precedence over user init values
203
- analyticsURL = serverConfig["analyticsURLInit"] || analyticsURL || DEFAULT_BASE_URL;
204
- disabled = serverConfig["disabled"] === true;
205
- _setupTimers(disabled);
206
- debugLog(`Init analytics Config from remote. disabled: ${disabled}
198
+ async function _initFromRemoteConfig(postIntervalSecondsInit, granularitySecInit) {
199
+ serverConfig = await _getServerConfig();
200
+ if(serverConfig !== {}){
201
+ // User init overrides takes precedence over server overrides
202
+ postIntervalSeconds = postIntervalSecondsInit ||
203
+ serverConfig["postIntervalSecondsInit"] || DEFAULT_POST_INTERVAL_SECONDS;
204
+ granularitySec = granularitySecInit || serverConfig["granularitySecInit"] || DEFAULT_GRANULARITY_IN_SECONDS;
205
+ // For URLs, the server suggested URL takes precedence over user init values
206
+ analyticsURL = serverConfig["analyticsURLInit"] || analyticsURL || DEFAULT_BASE_URL;
207
+ disabled = serverConfig["disabled"] === true;
208
+ _setupTimers(disabled);
209
+ debugLog(`Init analytics Config from remote. disabled: ${disabled}
207
210
  postIntervalSeconds:${postIntervalSeconds}, granularitySec: ${granularitySec} ,URL: ${analyticsURL}`);
208
- if(disabled){
209
- console.warn(`Core Analytics is disabled from the server for app: ${accountID}:${appName}`);
211
+ if(disabled){
212
+ console.warn(`Core Analytics is disabled from the server for app: ${accountID}:${appName}`);
213
+ }
210
214
  }
211
215
  }
212
- }
213
216
 
214
- function _stripTrailingSlash(url) {
215
- return url.replace(/\/$/, "");
216
- }
217
-
218
- /**
219
- * Initialize the analytics session
220
- * @param accountIDInit Your analytics account id as configured in the server or core.ai analytics
221
- * @param appNameInit The app name to log the events against.
222
- * @param analyticsURLInit Optional: Provide your own analytics server address if you self-hosted the server
223
- * @param postIntervalSecondsInit Optional: This defines the interval between sending analytics events to the server.
224
- * Default is 10 minutes
225
- * @param granularitySecInit Optional: The smallest time period under which the events can be distinguished. Multiple
226
- * events happening during this time period is aggregated to a count. The default granularity is 3 Seconds, which means
227
- * that any events that happen within 3 seconds cannot be distinguished in ordering.
228
- * @param debug set to true if you want to see detailed debug logs.
229
- */
230
- function initSession(accountIDInit, appNameInit, analyticsURLInit, postIntervalSecondsInit, granularitySecInit, debug) {
231
- if(!accountIDInit || !appNameInit){
232
- throw new Error("accountID and appName must exist for init");
217
+ function _stripTrailingSlash(url) {
218
+ return url.replace(/\/$/, "");
233
219
  }
234
- analyticsURL = analyticsURLInit? _stripTrailingSlash(analyticsURLInit) : DEFAULT_BASE_URL;
235
- accountID = accountIDInit;
236
- appName = appNameInit;
237
- debugMode = debug || false;
238
- postIntervalSeconds = postIntervalSecondsInit || DEFAULT_POST_INTERVAL_SECONDS;
239
- granularitySec = granularitySecInit || DEFAULT_GRANULARITY_IN_SECONDS;
240
- postURL = analyticsURL + "/ingest";
241
- _setupIDs();
242
- currentAnalyticsEvent = _createAnalyticsEvent();
243
- _setupTimers();
244
- _initFromRemoteConfig(postIntervalSecondsInit, granularitySecInit);
245
- }
246
220
 
247
- function _ensureAnalyticsEventExists(eventType, category, subCategory) {
248
- let events = currentAnalyticsEvent.events;
249
- events[eventType] = events[eventType] || {};
250
- events[eventType][category] = events[eventType][category] || {};
251
- events[eventType][category][subCategory] = events[eventType][category][subCategory] || {
252
- time: [], // quantised time
253
- valueCount: [] // value and count array, If a single value, then it is count, else object {"val1":count1, ...}
254
- };
255
- }
256
-
257
- function _validateEvent(eventType, category, subCategory, count, value) {
258
- _validateCurrentState();
259
- if(!eventType || !category || !subCategory){
260
- throw new Error("missing eventType or category or subCategory");
261
- }
262
- if(typeof(count)!== 'number' || count <0){
263
- throw new Error("invalid count");
264
- }
265
- if(typeof(value)!== 'number'){
266
- throw new Error("invalid value");
221
+ /**
222
+ * Initialize the analytics session
223
+ * @param accountIDInit Your analytics account id as configured in the server or core.ai analytics
224
+ * @param appNameInit The app name to log the events against.
225
+ * @param analyticsURLInit Optional: Provide your own analytics server address if you self-hosted the server
226
+ * @param postIntervalSecondsInit Optional: This defines the interval between sending analytics events to the server.
227
+ * Default is 10 minutes
228
+ * @param granularitySecInit Optional: The smallest time period under which the events can be distinguished. Multiple
229
+ * events happening during this time period is aggregated to a count. The default granularity is 3 Seconds, which means
230
+ * that any events that happen within 3 seconds cannot be distinguished in ordering.
231
+ * @param debug set to true if you want to see detailed debug logs.
232
+ */
233
+ function initSession(accountIDInit, appNameInit, analyticsURLInit, postIntervalSecondsInit, granularitySecInit, debug) {
234
+ if(!accountIDInit || !appNameInit){
235
+ throw new Error("accountID and appName must exist for init");
236
+ }
237
+ analyticsURL = analyticsURLInit? _stripTrailingSlash(analyticsURLInit) : DEFAULT_BASE_URL;
238
+ accountID = accountIDInit;
239
+ appName = appNameInit;
240
+ debugMode = debug || false;
241
+ postIntervalSeconds = postIntervalSecondsInit || DEFAULT_POST_INTERVAL_SECONDS;
242
+ granularitySec = granularitySecInit || DEFAULT_GRANULARITY_IN_SECONDS;
243
+ postURL = analyticsURL + "/ingest";
244
+ _setupIDs();
245
+ currentAnalyticsEvent = _createAnalyticsEvent();
246
+ _setupTimers();
247
+ _initFromRemoteConfig(postIntervalSecondsInit, granularitySecInit);
267
248
  }
268
- }
269
249
 
270
- function _updateExistingAnalyticsEvent(index, eventType, category, subCategory, count, newValue) {
271
- let events = currentAnalyticsEvent.events;
272
- const storedValueIsCount = typeof(events[eventType][category][subCategory]["valueCount"][index]) === 'number';
273
- if(storedValueIsCount && newValue === 0){
274
- events[eventType][category][subCategory]["valueCount"][index] += count;
275
- } else if(storedValueIsCount && newValue !== 0){
276
- let newValueCount = {};
277
- newValueCount[newValue] = count;
278
- newValueCount[0] = events[eventType][category][subCategory]["valueCount"][index];
279
- events[eventType][category][subCategory]["valueCount"][index] = newValueCount;
280
- } else if(!storedValueIsCount){
281
- let storedValueObject = events[eventType][category][subCategory]["valueCount"][index];
282
- storedValueObject[newValue] = (storedValueObject[newValue] || 0) + count;
250
+ function _ensureAnalyticsEventExists(eventType, category, subCategory) {
251
+ let events = currentAnalyticsEvent.events;
252
+ events[eventType] = events[eventType] || {};
253
+ events[eventType][category] = events[eventType][category] || {};
254
+ events[eventType][category][subCategory] = events[eventType][category][subCategory] || {
255
+ time: [], // quantised time
256
+ valueCount: [] // value and count array, If a single value, then it is count, else object {"val1":count1, ...}
257
+ };
283
258
  }
284
- currentAnalyticsEvent.numEventsTotal += 1;
285
- }
286
259
 
287
- /**
288
- * Register an analytics event. The events will be aggregated and send to the analytics server periodically.
289
- * @param eventType - String, required
290
- * @param eventCategory - String, required
291
- * @param subCategory - String, required
292
- * @param eventCount (Optional) : A non-negative number indicating the number of times the event (or an event with a
293
- * particular value if a value is specified) happened. defaults to 1.
294
- * @param eventValue (Optional) : A number value associated with the event. defaults to 0
295
- */
296
- function analyticsEvent(eventType, eventCategory, subCategory, eventCount=1, eventValue=0) {
297
- if(disabled){
298
- return;
260
+ function _validateEvent(eventType, category, subCategory, count, value) {
261
+ _validateCurrentState();
262
+ if(!eventType || !category || !subCategory){
263
+ throw new Error("missing eventType or category or subCategory");
264
+ }
265
+ if(typeof(count)!== 'number' || count <0){
266
+ throw new Error("invalid count");
267
+ }
268
+ if(typeof(value)!== 'number'){
269
+ throw new Error("invalid value");
270
+ }
299
271
  }
300
- _validateEvent(eventType, eventCategory, subCategory, eventCount, eventValue);
301
- _ensureAnalyticsEventExists(eventType, eventCategory, subCategory);
302
- let events = currentAnalyticsEvent.events;
303
- let timeArray = events[eventType][eventCategory][subCategory]["time"];
304
- let lastTime = timeArray.length>0? timeArray[timeArray.length-1] : null;
305
- if(lastTime !== currentQuantisedTime){
306
- events[eventType][eventCategory][subCategory]["time"].push(currentQuantisedTime);
307
- if(eventValue===0){
308
- events[eventType][eventCategory][subCategory]["valueCount"].push(eventCount);
309
- } else {
310
- let valueCount = {};
311
- valueCount[eventValue] = eventCount;
312
- events[eventType][eventCategory][subCategory]["valueCount"].push(valueCount);
272
+
273
+ function _updateExistingAnalyticsEvent(index, eventType, category, subCategory, count, newValue) {
274
+ let events = currentAnalyticsEvent.events;
275
+ const storedValueIsCount = typeof(events[eventType][category][subCategory]["valueCount"][index]) === 'number';
276
+ if(storedValueIsCount && newValue === 0){
277
+ events[eventType][category][subCategory]["valueCount"][index] += count;
278
+ } else if(storedValueIsCount && newValue !== 0){
279
+ let newValueCount = {};
280
+ newValueCount[newValue] = count;
281
+ newValueCount[0] = events[eventType][category][subCategory]["valueCount"][index];
282
+ events[eventType][category][subCategory]["valueCount"][index] = newValueCount;
283
+ } else if(!storedValueIsCount){
284
+ let storedValueObject = events[eventType][category][subCategory]["valueCount"][index];
285
+ storedValueObject[newValue] = (storedValueObject[newValue] || 0) + count;
313
286
  }
314
287
  currentAnalyticsEvent.numEventsTotal += 1;
315
- return;
316
288
  }
317
- let modificationIndex = events[eventType][eventCategory][subCategory]["valueCount"].length -1;
318
- _updateExistingAnalyticsEvent(modificationIndex, eventType, eventCategory, subCategory, eventCount, eventValue);
289
+
290
+ /**
291
+ * Register an analytics event. The events will be aggregated and send to the analytics server periodically.
292
+ * @param eventType - String, required
293
+ * @param eventCategory - String, required
294
+ * @param subCategory - String, required
295
+ * @param eventCount (Optional) : A non-negative number indicating the number of times the event (or an event with a
296
+ * particular value if a value is specified) happened. defaults to 1.
297
+ * @param eventValue (Optional) : A number value associated with the event. defaults to 0
298
+ */
299
+ function event(eventType, eventCategory, subCategory, eventCount=1, eventValue=0) {
300
+ if(disabled){
301
+ return;
302
+ }
303
+ _validateEvent(eventType, eventCategory, subCategory, eventCount, eventValue);
304
+ _ensureAnalyticsEventExists(eventType, eventCategory, subCategory);
305
+ let events = currentAnalyticsEvent.events;
306
+ let timeArray = events[eventType][eventCategory][subCategory]["time"];
307
+ let lastTime = timeArray.length>0? timeArray[timeArray.length-1] : null;
308
+ if(lastTime !== currentQuantisedTime){
309
+ events[eventType][eventCategory][subCategory]["time"].push(currentQuantisedTime);
310
+ if(eventValue===0){
311
+ events[eventType][eventCategory][subCategory]["valueCount"].push(eventCount);
312
+ } else {
313
+ let valueCount = {};
314
+ valueCount[eventValue] = eventCount;
315
+ events[eventType][eventCategory][subCategory]["valueCount"].push(valueCount);
316
+ }
317
+ currentAnalyticsEvent.numEventsTotal += 1;
318
+ return;
319
+ }
320
+ let modificationIndex = events[eventType][eventCategory][subCategory]["valueCount"].length -1;
321
+ _updateExistingAnalyticsEvent(modificationIndex, eventType, eventCategory, subCategory, eventCount, eventValue);
322
+ }
323
+
324
+ analytics.initSession = initSession;
325
+ analytics.getCurrentAnalyticsEvent = getCurrentAnalyticsEvent;
326
+ analytics.event = event;
327
+ analytics.getAppConfig = getAppConfig;
319
328
  }
320
329
 
321
- export {
322
- initSession,
323
- getCurrentAnalyticsEvent,
324
- analyticsEvent,
325
- getAppConfig
326
- };
330
+ init();