@aicore/core-analytics-client-lib 1.0.11 → 2.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.
@@ -1,4 +1,4 @@
1
- function initAnalyticsSession(e,t,n,o,a){let i,r,s,l,u,c,d,f,y={};const v="aicore.analytics.userID",g="aicore.analytics.sessionID",p=1e4;let m=null;var w,h,b,C="undefined"==typeof window;let I="https://analytics.core.ai",S,D,E=0,T=!1;function U(...e){window.analytics.debugMode&&console.log("analytics client: ",...e)}function A(...e){window.analytics.debugMode&&console.error("analytics client: ",...e)}if(C)throw new Error("Node environment is not currently supported");function N(){return{schemaVersion:1,accountID:i,appName:r,uuid:s,sessionID:l,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(()=>{R(e)},3e4*e.backoffCount)}function B(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
2
- typically means that you may be sending too many value events? .`),U("Sending Analytics data of length: ",n.length,"B"),e=["Sending data:",t],window.analytics.debugMode&&console.info("analytics client: ",...e),window.navigator.onLine?window.fetch(f,{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 R(e){T||(e||(e=m,E=0,L(),m=N()),0!==e.numEventsTotal&&B(e))}function L(e){S&&(clearInterval(S),S=null),e||(S=setInterval(()=>{E+=c},1e3*c))}function M(e){L(e),D&&(clearInterval(D),D=null),e||(D=setInterval(R,1e3*u))}function _(n,o,a,i=1,r=0){if(!T){var s=n,l=o,u=a,c=i,d=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 d)throw new Error("invalid value, value should be a number");{s=n;l=o;u=a;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][o][a].time;if((0<c.length?c[c.length-1]:null)===E){d=t[n][o][a].valueCount.length-1;{var s=d,l=n,u=o,c=a,d=i,f=r;let t=m.events;var e="number"==typeof t[l][u][c].valueCount[s];if(e&&0===f)t[l][u][c].valueCount[s]+=d;else if(e&&0!==f){let e={};e[f]=d,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[f]=(e[f]||0)+d}m.numEventsTotal+=1}}else{if(t[n][o][a].time.push(E),0===r)t[n][o][a].valueCount.push(i);else{let e={};e[r]=i,t[n][o][a].valueCount.push(e)}m.numEventsTotal+=1}}}if(!e||!t)throw new Error("accountID and appName must exist for init");d=n?n.toString().replace(/\/$/,""):I,i=e,r=t,u=o||60,c=a||3,f=d+"/ingest",s=function(){let e=localStorage.getItem(v);return e||(e=crypto.randomUUID(),localStorage.setItem(v,e)),e}(),l=function(){let e=sessionStorage.getItem(g);return e||(e=Math.random().toString(36).substr(2,10),sessionStorage.setItem(g,e)),e}(),m=N(),M(),w=o,h=a,new Promise(t=>{var e;window.navigator.onLine?(e=d+(`/getAppConfig?accountID=${i}&appName=`+r),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=>{y!=={}&&(y=e,u=w||y.postIntervalSecondsInit||60,c=h||y.granularitySecInit||3,d=y.analyticsURLInit||d||I,M(T=!0===y.disabled),U(`Init analytics Config from remote. disabled: ${T}
3
- postIntervalSeconds:${u}, granularitySec: ${c} ,URL: `+d),T&&console.warn(`Core Analytics is disabled from the server for app: ${i}:`+r))});for(b of analytics._initData)_(...b);analytics._initData=[],analytics._getCurrentAnalyticsEvent=function(){return $(),JSON.parse(JSON.stringify(m))},analytics._getAppConfig=function(){return{accountID:i,appName:r,disabled:T,uuid:s,sessionID:l,postIntervalSeconds:u,granularitySec:c,analyticsURL:d,serverConfig:y}},analytics.event=_}window.analytics||(window.analytics={_initData:[],debugMode:!1}),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))});
1
+ function initAnalyticsSession(n,t,e,o,a){let i,r,s,l,u,c,d,f,y={};const v="aicore.analytics.userID",g="aicore.analytics.sessionID",p=1e4;let m=null;var w,h,b,C="undefined"==typeof window;let I="https://analytics.core.ai",S,D,E=0,U=!1;function T(...n){window.analytics.debugMode&&console.log("analytics client: ",...n)}function A(...n){window.analytics.debugMode&&console.error("analytics client: ",...n)}if(C)throw new Error("Node environment is not currently supported");function N(){return{schemaVersion:1,accountID:i,appName:r,uuid:s,sessionID:l,unixTimestampUTC:+new Date,numEventsTotal:0,events:{}}}function $(){if(!m)throw new Error("Please call initSession before using any analytics event")}function k(n){n.backoffCount=(n.backoffCount||0)+1,T(`Failed to call core analytics server. Will retry in ${30*n.backoffCount}s: `),setTimeout(()=>{R(n)},3e4*n.backoffCount)}function B(t){var n,e=JSON.stringify(t);e.length>p&&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? .`),T("Sending Analytics data of length: ",e.length,"B"),n=["Sending data:",t],window.analytics.debugMode&&console.info("analytics client: ",...n),window.navigator.onLine?window.fetch(f,{method:"POST",headers:{"Content-Type":"application/json"},body:e}).then(n=>{200!==n.status&&(400!==n.status?k(t):console.error("Bad Request, this is most likely a problem with the library, update to latest version."))}).catch(n=>{A(n),k(t)}):k(t)}function R(n){U||(n||(n=m,E=0,L(),m=N()),0!==n.numEventsTotal&&B(n))}function L(n){S&&(clearInterval(S),S=null),n||(S=setInterval(()=>{E+=c},1e3*c))}function M(n){L(n),D&&(clearInterval(D),D=null),n||(D=setInterval(R,1e3*u))}function _(n,t,e,o=1,a=0){if(!U){var i=n,r=t,s=e,l=o,u=a;if($(),!i||!r||!s)throw new Error("missing eventType or category or subCategory");if("number"!=typeof l||l<0)throw new Error("invalid count, count should be a positive number");if("number"!=typeof u)throw new Error("invalid value, value should be a number");i=n,r=t,s=e,(l=m.events)[i]=l[i]||{},l[i][r]=l[i][r]||{},l[i][r][s]=l[i][r][s]||{time:[],valueCount:[]};var u=m.events,l=u[n][t][e],i=l.time;(0<i.length?i[i.length-1]:null)!==E?(i.push(E),0===a?l.valueCount.push(o):((r={})[a]=o,l.valueCount.push(r))):(s=l.valueCount.length-1,u=s,i=n,r=t,l=e,s=o,n=a,i=m.events[i][r][l],(r="number"==typeof i.valueCount[u])&&0===n?i.valueCount[u]+=s:r&&0!==n?((l={})[n]=s,l[0]=i.valueCount[u],i.valueCount[u]=l):r||((l=i.valueCount[u])[n]=(l[n]||0)+s)),m.numEventsTotal+=1}}if(!n||!t)throw new Error("accountID and appName must exist for init");d=e?e.toString().replace(/\/$/,""):I,i=n,r=t,u=o||60,c=a||3,f=d+"/ingest",s=function(){let n=localStorage.getItem(v);return n||(n=crypto.randomUUID(),localStorage.setItem(v,n)),n}(),l=function(){let n=sessionStorage.getItem(g);return n||(n=Math.random().toString(36).substr(2,10),sessionStorage.setItem(g,n)),n}(),m=N(),M(),w=o,h=a,new Promise(t=>{var n;window.navigator.onLine?(n=d+(`/getAppConfig?accountID=${i}&appName=`+r),window.fetch(n).then(n=>{switch(n.status){case 200:return void n.json().then(n=>{t(n)}).catch(n=>{A("remote response invalid. Continuing with defaults.",n),t({})});case 400:A("Bad Request, check library version compatible?",n),t({});break;default:A("Could not update from remote config. Continuing with defaults.",n),t({})}}).catch(n=>{A("Could not update from remote config. Continuing with defaults.",n),t({})})):t({})}).then(n=>{y!=={}&&(y=n,u=w||y.postIntervalSecondsInit||60,c=h||y.granularitySecInit||3,d=y.analyticsURLInit||d||I,M(U=!0===y.disabled),T(`Init analytics Config from remote. disabled: ${U}
3
+ postIntervalSeconds:${u}, granularitySec: ${c} ,URL: `+d),U)&&console.warn(`Core Analytics is disabled from the server for app: ${i}:`+r)});for(b of analytics._initData)_(...b);analytics._initData=[],analytics._getCurrentAnalyticsEvent=function(){return $(),JSON.parse(JSON.stringify(m))},analytics._getAppConfig=function(){return{accountID:i,appName:r,disabled:U,uuid:s,sessionID:l,postIntervalSeconds:u,granularitySec:c,analyticsURL:d,serverConfig:y}},analytics.countEvent=function(n,t,e,o=1){return _(n,t,e,o,0)},analytics.valueEvent=function(n,t,e,o=0,a=1){return _(n,t,e,a,o)}}window.analytics||(window.analytics={_initData:[],debugMode:!1}),void 0===window.crypto&&(window.crypto={}),"randomUUID"in crypto||(crypto.randomUUID=function(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,n=>(n^crypto.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16))});
4
4
  //# sourceMappingURL=analytics.min.js.map
@@ -1 +1 @@
1
- {"version":3,"sourceRoot":"src/analytics.js","sources":["src/analytics.js"],"names":["initAnalyticsSession","accountIDInit","appNameInit","analyticsURLInit","postIntervalSecondsInit","granularitySecInit","let","accountID","appName","userID","sessionID","postIntervalSeconds","granularitySec","analyticsURL","postURL","serverConfig","USERID_LOCAL_STORAGE_KEY","SESSION_ID_LOCAL_STORAGE_KEY","POST_LARGE_DATA_THRESHOLD_BYTES","currentAnalyticsEvent","postIntervalSecondsInitial","granularitySecInitial","eventData","IS_NODE_ENV","window","DEFAULT_BASE_URL","granularityTimer","postTimer","currentQuantisedTime","disabled","debugLog","args","analytics","debugMode","console","log","debugError","error","Error","_createAnalyticsEvent","schemaVersion","uuid","unixTimestampUTC","Date","numEventsTotal","events","_validateCurrentState","_retryPost","eventToSend","backoffCount","setTimeout","_postCurrentAnalyticsEvent","DEFAULT_RETRY_TIME_IN_SECONDS","_postEventWithRetry","textToSend","JSON","stringify","length","warn","debugInfo","info","navigator","onLine","fetch","method","headers","Content-Type","body","then","res","status","catch","_resetGranularityTimer","disable","clearInterval","setInterval","_setupTimers","event","eventType","eventCategory","subCategory","eventCount","eventValue","_validateEvent","category","count","value","_ensureAnalyticsEventExists","time","valueCount","timeArray","modificationIndex","_updateExistingAnalyticsEvent","index","newValue","storedValueIsCount","newValueCount","storedValueObject","push","toString","replace","localUserID","localStorage","getItem","crypto","randomUUID","setItem","_getOrCreateUserID","localSessionID","sessionStorage","Math","random","substr","_getOrCreateSessionID","Promise","configURL","json","serverResponse","resolve","err","updatedServerConfig","_initData","_getCurrentAnalyticsEvent","parse","_getAppConfig","c","getRandomValues","Uint8Array"],"mappings":"AAwCA,SAASA,qBAAqBC,EAAeC,EAAaC,EACtDC,EAAyBC,GACzBC,IAAIC,EAAWC,EAASC,EAAQC,EAAWC,EACvCC,EAAgBC,EAAcC,EAASC,EAAa,GACxD,MAGMC,EAA2B,0BAC3BC,EAA+B,6BAC/BC,EAAkC,IACxCZ,IAAIa,EAAwB,KAC5B,IAkN+BC,EAA4BC,EAwHnDC,EA1UFC,EAAiC,oBAAXC,OAC5BlB,IAAImB,EAAmB,4BAEnBC,EACAC,EACAC,EAAuB,EACvBC,GAAW,EAEf,SAASC,KAAYC,GACbP,OAAOQ,UAAUC,WAGrBC,QAAQC,IAAI,wBAAyBJ,GASzC,SAASK,KAAcL,GACfP,OAAOQ,UAAUC,WAGrBC,QAAQG,MAAM,wBAAyBN,GAI3C,GAAGR,EACC,MAAM,IAAIe,MAAM,+CAGpB,SAASC,IACL,MAAO,CACHC,cAAe,EACfjC,UAAWA,EACXC,QAASA,EACTiC,KAAMhC,EACNC,UAAWA,EACXgC,kBAAmB,IAAIC,KACvBC,eAAgB,EAChBC,OAAQ,IAIhB,SAASC,IACL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,"sourceRoot":"src/analytics.js","sources":["src/analytics.js"],"names":["initAnalyticsSession","accountIDInit","appNameInit","analyticsURLInit","postIntervalSecondsInit","granularitySecInit","let","accountID","appName","userID","sessionID","postIntervalSeconds","granularitySec","analyticsURL","postURL","serverConfig","USERID_LOCAL_STORAGE_KEY","SESSION_ID_LOCAL_STORAGE_KEY","POST_LARGE_DATA_THRESHOLD_BYTES","currentAnalyticsEvent","postIntervalSecondsInitial","granularitySecInitial","eventData","IS_NODE_ENV","window","DEFAULT_BASE_URL","granularityTimer","postTimer","currentQuantisedTime","disabled","debugLog","args","analytics","debugMode","console","log","debugError","error","Error","_createAnalyticsEvent","schemaVersion","uuid","unixTimestampUTC","Date","numEventsTotal","events","_validateCurrentState","_retryPost","eventToSend","backoffCount","setTimeout","_postCurrentAnalyticsEvent","DEFAULT_RETRY_TIME_IN_SECONDS","_postEventWithRetry","textToSend","JSON","stringify","length","warn","debugInfo","info","navigator","onLine","fetch","method","headers","Content-Type","body","then","res","status","catch","_resetGranularityTimer","disable","clearInterval","setInterval","_setupTimers","event","eventType","eventCategory","subCategory","eventCount","eventValue","_validateEvent","category","count","value","time","valueCount","eventItem","timeArray","push","modificationIndex","index","newValue","storedValueIsCount","newValueCount","storedValueObject","toString","replace","localUserID","localStorage","getItem","crypto","randomUUID","setItem","localSessionID","sessionStorage","Math","random","substr","Promise","configURL","json","serverResponse","resolve","err","updatedServerConfig","_initData","_getCurrentAnalyticsEvent","parse","_getAppConfig","countEvent","valueEvent","c","getRandomValues","Uint8Array"],"mappings":"AAwCA,SAASA,qBAAqBC,EAAeC,EAAaC,EACtDC,EAAyBC,GACzBC,IAAIC,EAAWC,EAASC,EAAQC,EAAWC,EACvCC,EAAgBC,EAAcC,EAASC,EAAa,GACxD,MAGMC,EAA2B,0BAC3BC,EAA+B,6BAC/BC,EAAkC,IACxCZ,IAAIa,EAAwB,KAC5B,IAkN+BC,EAA4BC,EAsKnDC,EAxXFC,EAAiC,aAAlB,OAAOC,OAC5B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4DAA4DnD,KAAaC,CAAS,CAGtG,CAAC,EAoJL,IAAQc,KAAaU,UAAUsF,UAC3BzC,EAAM,GAAGvD,CAAS,EAEtBU,UAAUsF,UAAY,GAGtBtF,UAAUuF,0BA1UV,WAGI,OAFAzE,EAAsB,EAEfS,KAAKiE,MAAMjE,KAAKC,UAAUrC,CAAqB,CAAC,CAC3D,EAuUAa,UAAUyF,cArLV,WACI,MAAO,CACHlH,UAAAA,EAAWC,QAAAA,EAASqB,SAAAA,EACpBY,KAAMhC,EAAQC,UAAAA,EACdC,oBAAAA,EAAqBC,eAAAA,EAAgBC,aAAAA,EAAcE,aAAAA,CACvD,CACJ,EAkLAiB,UAAU0F,WAzDV,SAAoB5C,EAAWC,EAAeC,EAAaC,EAAa,GACpE,OAAOJ,EAAMC,EAAWC,EAAeC,EAAaC,EAAY,CAAC,CACrE,EAwDAjD,UAAU2F,WAlCV,SAAoB7C,EAAWC,EAAeC,EAAaE,EAAa,EAAGG,EAAQ,GAC/E,OAAOR,EAAMC,EAAWC,EAAeC,EAAaK,EAAOH,CAAU,CACzE,CAiCJ,CAjbI1D,OAAOQ,YACPR,OAAOQ,UAAY,CACfsF,UAAW,GACXrF,UAAW,CAAA,CACf,GAGyB,KAAA,IAAlBT,OAAO+E,SACd/E,OAAO+E,OAAS,IAGd,eAAgBA,SAGlBA,OAAOC,WAAa,WAChB,OACI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAML,QAAQ,SAEpCyB,IAAMA,EAAIrB,OAAOsB,gBAAgB,IAAIC,WAAW,CAAC,CAAC,EAAE,GAAK,IAAMF,EAAI,GAAG1B,SAAS,EAAE,CACrF,CACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aicore/core-analytics-client-lib",
3
- "version": "1.0.11",
3
+ "version": "2.0.0",
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",
@@ -47,14 +47,14 @@
47
47
  },
48
48
  "homepage": "https://github.com/aicore/core-analytics-client-lib#readme",
49
49
  "devDependencies": {
50
- "@commitlint/cli": "17.0.2",
51
- "@commitlint/config-conventional": "17.0.2",
52
- "c8": "7.11.3",
53
- "chai": "4.3.6",
54
- "eslint": "8.16.0",
55
- "husky": "7.0.4",
56
- "mocha": "9.2.2",
57
- "uglify-js": "3.15.5",
50
+ "@commitlint/cli": "17.5.1",
51
+ "@commitlint/config-conventional": "17.4.4",
52
+ "c8": "7.13.0",
53
+ "chai": "4.3.7",
54
+ "eslint": "8.37.0",
55
+ "husky": "8.0.3",
56
+ "mocha": "10.2.0",
57
+ "uglify-js": "3.17.4",
58
58
  "http-server": "14.1.1"
59
59
  }
60
60
  }
package/src/analytics.js CHANGED
@@ -311,16 +311,17 @@ function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
311
311
 
312
312
  function _updateExistingAnalyticsEvent(index, eventType, category, subCategory, count, newValue) {
313
313
  let events = currentAnalyticsEvent.events;
314
- const storedValueIsCount = typeof(events[eventType][category][subCategory]["valueCount"][index]) === 'number';
314
+ const eventItem = events[eventType][category][subCategory];
315
+ const storedValueIsCount = typeof(eventItem.valueCount[index]) === 'number';
315
316
  if(storedValueIsCount && newValue === 0){
316
- events[eventType][category][subCategory]["valueCount"][index] += count;
317
+ eventItem.valueCount[index] += count;
317
318
  } else if(storedValueIsCount && newValue !== 0){
318
319
  let newValueCount = {};
319
320
  newValueCount[newValue] = count;
320
- newValueCount[0] = events[eventType][category][subCategory]["valueCount"][index];
321
- events[eventType][category][subCategory]["valueCount"][index] = newValueCount;
321
+ newValueCount[0] = eventItem.valueCount[index];
322
+ eventItem.valueCount[index] = newValueCount;
322
323
  } else if(!storedValueIsCount){
323
- let storedValueObject = events[eventType][category][subCategory]["valueCount"][index];
324
+ let storedValueObject = eventItem.valueCount[index];
324
325
  storedValueObject[newValue] = (storedValueObject[newValue] || 0) + count;
325
326
  }
326
327
  currentAnalyticsEvent.numEventsTotal += 1;
@@ -342,24 +343,69 @@ function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
342
343
  _validateEvent(eventType, eventCategory, subCategory, eventCount, eventValue);
343
344
  _ensureAnalyticsEventExists(eventType, eventCategory, subCategory);
344
345
  let events = currentAnalyticsEvent.events;
345
- let timeArray = events[eventType][eventCategory][subCategory]["time"];
346
+ const eventItem = events[eventType][eventCategory][subCategory];
347
+ let timeArray = eventItem.time;
346
348
  let lastTime = timeArray.length>0? timeArray[timeArray.length-1] : null;
347
349
  if(lastTime !== currentQuantisedTime){
348
- events[eventType][eventCategory][subCategory]["time"].push(currentQuantisedTime);
350
+ timeArray.push(currentQuantisedTime);
349
351
  if(eventValue===0){
350
- events[eventType][eventCategory][subCategory]["valueCount"].push(eventCount);
352
+ eventItem.valueCount.push(eventCount);
351
353
  } else {
352
354
  let valueCount = {};
353
355
  valueCount[eventValue] = eventCount;
354
- events[eventType][eventCategory][subCategory]["valueCount"].push(valueCount);
356
+ eventItem.valueCount.push(valueCount);
355
357
  }
356
358
  currentAnalyticsEvent.numEventsTotal += 1;
357
359
  return;
358
360
  }
359
- let modificationIndex = events[eventType][eventCategory][subCategory]["valueCount"].length -1;
361
+ let modificationIndex = eventItem.valueCount.length - 1;
360
362
  _updateExistingAnalyticsEvent(modificationIndex, eventType, eventCategory, subCategory, eventCount, eventValue);
361
363
  }
362
364
 
365
+ /**
366
+ * Counts the occurrence of a specific event. Use this to track how many times something happens.
367
+ * Events are aggregated and periodically sent to the analytics server.
368
+ *
369
+ * @example
370
+ * // Count a single occurrence of a button click
371
+ * analytics.countEvent("ui", "button", "save");
372
+ *
373
+ * // Count multiple occurrences at once (e.g., 5 items were deleted in a batch)
374
+ * analytics.countEvent("action", "delete", "files", 5);
375
+ *
376
+ * @param {string} eventType - The type of the event (e.g., "ui", "action", "lifecycle").
377
+ * @param {string} eventCategory - The category of the event (e.g., "button", "menu", "startup").
378
+ * @param {string} subCategory - The subcategory of the event (e.g., "save", "open", "click").
379
+ * @param {number} [eventCount=1] - The number of occurrences to count. Must be a non-negative number.
380
+ */
381
+ function countEvent(eventType, eventCategory, subCategory, eventCount = 1) {
382
+ return event(eventType, eventCategory, subCategory, eventCount, 0);
383
+ }
384
+
385
+ /**
386
+ * Tracks an event with an associated numeric value. Use this to measure quantities like latencies,
387
+ * durations, sizes, or anything where you need running averages and distributions.
388
+ *
389
+ * @example
390
+ * // Track an API response time of 250ms
391
+ * analytics.valueEvent("performance", "api", "getUserData", 250);
392
+ *
393
+ * // Track a file size of 1024 bytes
394
+ * analytics.valueEvent("resource", "file", "upload", 1024);
395
+ *
396
+ * // Track that a 300ms latency occurred 10 times (e.g., from a pre-aggregated batch)
397
+ * analytics.valueEvent("performance", "api", "listItems", 300, 10);
398
+ *
399
+ * @param {string} eventType - The type of the event (e.g., "performance", "resource", "usage").
400
+ * @param {string} eventCategory - The category of the event (e.g., "api", "file", "memory").
401
+ * @param {string} subCategory - The subcategory of the event (e.g., "upload", "render", "query").
402
+ * @param {number} [eventValue=0] - The numeric value to associate with the event.
403
+ * @param {number} [count=1] - The number of times this value occurred. Must be a non-negative number.
404
+ */
405
+ function valueEvent(eventType, eventCategory, subCategory, eventValue = 0, count = 1) {
406
+ return event(eventType, eventCategory, subCategory, count, eventValue);
407
+ }
408
+
363
409
  // Init Analytics
364
410
  if(!accountIDInit || !appNameInit){
365
411
  throw new Error("accountID and appName must exist for init");
@@ -389,5 +435,6 @@ function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
389
435
  analytics._getAppConfig = _getAppConfig;
390
436
 
391
437
  // Public API
392
- analytics.event = event;
438
+ analytics.countEvent = countEvent;
439
+ analytics.valueEvent = valueEvent;
393
440
  }