@aicore/core-analytics-client-lib
Advanced tools
Comparing version 1.0.8 to 1.0.9
@@ -1,4 +0,4 @@ | ||
function initAnalyticsSession(e,t,n,a,o,i){let s,r,l,u,c,f,d,v,y={};const g="aicore.analytics.userID",m="aicore.analytics.sessionID",p=1e4;let h=null;var w,b="undefined"==typeof window;let C="https://analytics.core.ai",I,S,D=0,E=!1,T=!1;function N(...e){T&&console.log("analytics client: ",...e)}function $(...e){T&&console.error("analytics client: ",...e)}if(b)throw new Error("Node environment is not currently supported");function k(){return{schemaVersion:1,accountID:s,appName:r,uuid:l,sessionID:u,unixTimestampUTC:+new Date,numEventsTotal:0,events:{}}}function A(){if(!h)throw new Error("Please call initSession before using any analytics event")}function L(e){e.backoffCount=(e.backoffCount||0)+1,N(`Failed to call core analytics server. Will retry in ${30*e.backoffCount}s: `),setTimeout(()=>{U(e)},3e4*e.backoffCount)}function O(t){var e,n=JSON.stringify(t);n.length>p&&console.warn(`Analytics event generated is very large at greater than ${n.length}B. This | ||
typically means that you may be sending too many value events? .`),N("Sending Analytics data of length: ",n.length,"B"),e=["Sending data:",n],T&&window.analytics.debugInfoLogsEnable&&console.info("analytics client: ",...e),window.navigator.onLine?window.fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:n}).then(e=>{200!==e.status&&(400!==e.status?L(t):console.error("Bad Request, this is most likely a problem with the library, update to latest version."))}).catch(e=>{$(e),L(t)}):L(t)}function U(e){E||(e||(e=h,D=0,R(),h=k()),0!==e.numEventsTotal&&O(e))}function R(e){I&&(clearInterval(I),I=null),e||(I=setInterval(()=>{D+=f},1e3*f))}function _(e){R(e),S&&(clearInterval(S),S=null),e||(S=setInterval(U,1e3*c))}function B(n,a,o,i=1,s=0){if(!E){var r=n,l=a,u=o,c=i,f=s;if(A(),!r||!l||!u)throw new Error("missing eventType or category or subCategory");if("number"!=typeof c||c<0)throw new Error("invalid count, count should be a positive number");if("number"!=typeof f)throw new Error("invalid value, value should be a number");{r=n;l=a;u=o;let e=h.events;e[r]=e[r]||{},e[r][l]=e[r][l]||{},e[r][l][u]=e[r][l][u]||{time:[],valueCount:[]}}let t=h.events;c=t[n][a][o].time;if((0<c.length?c[c.length-1]:null)===D){f=t[n][a][o].valueCount.length-1;{var r=f,l=n,u=a,c=o,f=i,d=s;let t=h.events;var e="number"==typeof t[l][u][c].valueCount[r];if(e&&0===d)t[l][u][c].valueCount[r]+=f;else if(e&&0!==d){let e={};e[d]=f,e[0]=t[l][u][c].valueCount[r],t[l][u][c].valueCount[r]=e}else if(!e){let e=t[l][u][c].valueCount[r];e[d]=(e[d]||0)+f}h.numEventsTotal+=1}}else{if(t[n][a][o].time.push(D),0===s)t[n][a][o].valueCount.push(i);else{let e={};e[s]=i,t[n][a][o].valueCount.push(e)}h.numEventsTotal+=1}}}if(!e||!t)throw new Error("accountID and appName must exist for init");d=n?n.replace(/\/$/,""):C,s=e,r=t,T=i||!1,c=a||60,f=o||3,v=d+"/ingest",l=function(){let e=localStorage.getItem(g);return e||(e=crypto.randomUUID(),localStorage.setItem(g,e)),e}(),u=function(){let e=sessionStorage.getItem(m);return e||(e=Math.random().toString(36).substr(2,10),sessionStorage.setItem(m,e)),e}(),h=k(),_(),async function(e,t){(y=await new Promise(n=>{var e;window.navigator.onLine?(e=d+(`/getAppConfig?accountID=${s}&appName=`+r),window.fetch(e).then(async e=>{switch(e.status){case 200:var t=await e.json();return void n(t);case 400:$("Bad Request, check library version compatible?",e),n({});break;default:$("Could not update from remote config. Continuing with defaults.",e),n({})}}).catch(e=>{$("Could not update from remote config. Continuing with defaults.",e),n({})})):n({})}))!=={}&&(c=e||y.postIntervalSecondsInit||60,f=t||y.granularitySecInit||3,d=y.analyticsURLInit||d||C,_(E=!0===y.disabled),N(`Init analytics Config from remote. disabled: ${E} | ||
postIntervalSeconds:${c}, granularitySec: ${f} ,URL: `+d),E&&console.warn(`Core Analytics is disabled from the server for app: ${s}:`+r))}(a,o);for(w of analytics._initData)B(...w);analytics._initData=[],analytics._getCurrentAnalyticsEvent=function(){return A(),JSON.parse(JSON.stringify(h))},analytics._getAppConfig=function(){return{accountID:s,appName:r,disabled:E,uuid:l,sessionID:u,postIntervalSeconds:c,granularitySec:f,analyticsURL:d,serverConfig:y}},analytics.event=B}window.analytics||(window.analytics={_initData:[]}); | ||
function initAnalyticsSession(e,t,n,a,o,i){let r,s,l,u,c,f,d,y,v={};const g="aicore.analytics.userID",p="aicore.analytics.sessionID",O=1e4;let m=null;var h,w,b,J="undefined"==typeof window;let C="https://analytics.core.ai",I,S,D=0,E=!1,T=!1;function U(...e){T&&console.log("analytics client: ",...e)}function A(...e){T&&console.error("analytics client: ",...e)}if(J)throw new Error("Node environment is not currently supported");function N(){return{schemaVersion:1,accountID:r,appName:s,uuid:l,sessionID:u,unixTimestampUTC:+new Date,numEventsTotal:0,events:{}}}function $(){if(!m)throw new Error("Please call initSession before using any analytics event")}function k(e){e.backoffCount=(e.backoffCount||0)+1,U(`Failed to call core analytics server. Will retry in ${30*e.backoffCount}s: `),setTimeout(()=>{L(e)},3e4*e.backoffCount)}function P(t){var e,n=JSON.stringify(t);n.length>O&&console.warn(`Analytics event generated is very large at greater than ${n.length}B. This | ||
typically means that you may be sending too many value events? .`),U("Sending Analytics data of length: ",n.length,"B"),e=["Sending data:",n],T&&window.analytics.debugInfoLogsEnable&&console.info("analytics client: ",...e),window.navigator.onLine?window.fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:n}).then(e=>{200!==e.status&&(400!==e.status?k(t):console.error("Bad Request, this is most likely a problem with the library, update to latest version."))}).catch(e=>{A(e),k(t)}):k(t)}function L(e){E||(e||(e=m,D=0,R(),m=N()),0!==e.numEventsTotal&&P(e))}function R(e){I&&(clearInterval(I),I=null),e||(I=setInterval(()=>{D+=f},1e3*f))}function _(e){R(e),S&&(clearInterval(S),S=null),e||(S=setInterval(L,1e3*c))}function B(n,a,o,i=1,r=0){if(!E){var s=n,l=a,u=o,c=i,f=r;if($(),!s||!l||!u)throw new Error("missing eventType or category or subCategory");if("number"!=typeof c||c<0)throw new Error("invalid count, count should be a positive number");if("number"!=typeof f)throw new Error("invalid value, value should be a number");{s=n;l=a;u=o;let e=m.events;e[s]=e[s]||{},e[s][l]=e[s][l]||{},e[s][l][u]=e[s][l][u]||{time:[],valueCount:[]}}let t=m.events;c=t[n][a][o].time;if((0<c.length?c[c.length-1]:null)===D){f=t[n][a][o].valueCount.length-1;{var s=f,l=n,u=a,c=o,f=i,d=r;let t=m.events;var e="number"==typeof t[l][u][c].valueCount[s];if(e&&0===d)t[l][u][c].valueCount[s]+=f;else if(e&&0!==d){let e={};e[d]=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[d]=(e[d]||0)+f}m.numEventsTotal+=1}}else{if(t[n][a][o].time.push(D),0===r)t[n][a][o].valueCount.push(i);else{let e={};e[r]=i,t[n][a][o].valueCount.push(e)}m.numEventsTotal+=1}}}if(!e||!t)throw new Error("accountID and appName must exist for init");d=n?n.toString().replace(/\/$/,""):C,r=e,s=t,T=i||!1,c=a||60,f=o||3,y=d+"/ingest",l=function(){let e=localStorage.getItem(g);return e||(e=crypto.randomUUID(),localStorage.setItem(g,e)),e}(),u=function(){let e=sessionStorage.getItem(p);return e||(e=Math.random().toString(36).substr(2,10),sessionStorage.setItem(p,e)),e}(),m=N(),_(),h=a,w=o,new Promise(t=>{var e;window.navigator.onLine?(e=d+(`/getAppConfig?accountID=${r}&appName=`+s),window.fetch(e).then(e=>{switch(e.status){case 200:return void e.json().then(e=>{t(e)}).catch(e=>{A("remote response invalid. Continuing with defaults.",e),t({})});case 400:A("Bad Request, check library version compatible?",e),t({});break;default:A("Could not update from remote config. Continuing with defaults.",e),t({})}}).catch(e=>{A("Could not update from remote config. Continuing with defaults.",e),t({})})):t({})}).then(e=>{v!=={}&&(v=e,c=h||v.postIntervalSecondsInit||60,f=w||v.granularitySecInit||3,d=v.analyticsURLInit||d||C,_(E=!0===v.disabled),U(`Init analytics Config from remote. disabled: ${E} | ||
postIntervalSeconds:${c}, granularitySec: ${f} ,URL: `+d),E&&console.warn(`Core Analytics is disabled from the server for app: ${r}:`+s))});for(b of analytics._initData)B(...b);analytics._initData=[],analytics._getCurrentAnalyticsEvent=function(){return $(),JSON.parse(JSON.stringify(m))},analytics._getAppConfig=function(){return{accountID:r,appName:s,disabled:E,uuid:l,sessionID:u,postIntervalSeconds:c,granularitySec:f,analyticsURL:d,serverConfig:v}},analytics.event=B}window.analytics||(window.analytics={_initData:[]}),void 0===window.crypto&&(window.crypto={}),"randomUUID"in crypto||(crypto.randomUUID=function(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))}); | ||
//# sourceMappingURL=analytics.min.js.map |
{ | ||
"name": "@aicore/core-analytics-client-lib", | ||
"version": "1.0.8", | ||
"version": "1.0.9", | ||
"description": "Analytics client library for https://github.com/aicore/Core-Analytics-Server", | ||
@@ -5,0 +5,0 @@ "main": "dist/analytics.min.js", |
@@ -13,2 +13,18 @@ // GNU AGPL-3.0 License Copyright (c) 2021 - present core.ai . All rights reserved. | ||
if (typeof window.crypto === 'undefined'){ | ||
window.crypto = {}; | ||
} | ||
if (!('randomUUID' in crypto)){ | ||
// https://stackoverflow.com/a/2117523/2800218 | ||
// LICENSE: https://creativecommons.org/licenses/by-sa/4.0/legalcode | ||
crypto.randomUUID = function randomUUID() { | ||
return ( | ||
[1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, | ||
// eslint-disable-next-line no-bitwise | ||
c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) | ||
); | ||
}; | ||
} | ||
/** | ||
@@ -202,3 +218,3 @@ * Initialize the analytics session | ||
async function _getServerConfig() { | ||
function _getServerConfig() { | ||
return new Promise((resolve)=>{ | ||
@@ -212,7 +228,11 @@ if(!window.navigator.onLine){ | ||
let configURL = analyticsURL + `/getAppConfig?accountID=${accountID}&appName=${appName}`; | ||
window.fetch(configURL).then(async res=>{ | ||
window.fetch(configURL).then(res=>{ | ||
switch (res.status) { | ||
case 200: | ||
let serverResponse = await res.json(); | ||
resolve(serverResponse); | ||
res.json().then(serverResponse =>{ | ||
resolve(serverResponse); | ||
}).catch(err => { | ||
debugError("remote response invalid. Continuing with defaults.", err); | ||
resolve({}); | ||
}); | ||
return; | ||
@@ -246,23 +266,25 @@ case 400: | ||
async function _initFromRemoteConfig(postIntervalSecondsInitial, granularitySecInitial) { | ||
serverConfig = await _getServerConfig(); | ||
if(serverConfig !== {}){ | ||
// User init overrides takes precedence over server overrides | ||
postIntervalSeconds = postIntervalSecondsInitial || | ||
serverConfig["postIntervalSecondsInit"] || DEFAULT_POST_INTERVAL_SECONDS; | ||
granularitySec = granularitySecInitial || serverConfig["granularitySecInit"] || DEFAULT_GRANULARITY_IN_SECONDS; | ||
// For URLs, the server suggested URL takes precedence over user init values | ||
analyticsURL = serverConfig["analyticsURLInit"] || analyticsURL || DEFAULT_BASE_URL; | ||
disabled = serverConfig["disabled"] === true; | ||
_setupTimers(disabled); | ||
debugLog(`Init analytics Config from remote. disabled: ${disabled} | ||
function _initFromRemoteConfig(postIntervalSecondsInitial, granularitySecInitial) { | ||
_getServerConfig().then(updatedServerConfig =>{ | ||
if(serverConfig !== {}){ | ||
serverConfig = updatedServerConfig; | ||
// User init overrides takes precedence over server overrides | ||
postIntervalSeconds = postIntervalSecondsInitial || | ||
serverConfig["postIntervalSecondsInit"] || DEFAULT_POST_INTERVAL_SECONDS; | ||
granularitySec = granularitySecInitial || serverConfig["granularitySecInit"] || DEFAULT_GRANULARITY_IN_SECONDS; | ||
// For URLs, the server suggested URL takes precedence over user init values | ||
analyticsURL = serverConfig["analyticsURLInit"] || analyticsURL || DEFAULT_BASE_URL; | ||
disabled = serverConfig["disabled"] === true; | ||
_setupTimers(disabled); | ||
debugLog(`Init analytics Config from remote. disabled: ${disabled} | ||
postIntervalSeconds:${postIntervalSeconds}, granularitySec: ${granularitySec} ,URL: ${analyticsURL}`); | ||
if(disabled){ | ||
console.warn(`Core Analytics is disabled from the server for app: ${accountID}:${appName}`); | ||
if(disabled){ | ||
console.warn(`Core Analytics is disabled from the server for app: ${accountID}:${appName}`); | ||
} | ||
} | ||
} | ||
}); | ||
} | ||
function _stripTrailingSlash(url) { | ||
return url.replace(/\/$/, ""); | ||
return url.toString().replace(/\/$/, ""); | ||
} | ||
@@ -275,4 +297,6 @@ | ||
events[eventType][category][subCategory] = events[eventType][category][subCategory] || { | ||
time: [], // quantised time | ||
valueCount: [] // value and count array, If a single value, then it is count, else object {"val1":count1, ...} | ||
// quantised time | ||
time: [], | ||
// value and count array, If a single value, then it is count, else object {"val1":count1, ...} | ||
valueCount: [] | ||
}; | ||
@@ -279,0 +303,0 @@ } |
Sorry, the diff of this file is not supported yet
77620
378