@cloudcare/browser-core 3.2.28 → 3.2.30

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.
Files changed (52) hide show
  1. package/cjs/dataMap.js +1 -0
  2. package/cjs/dataMap.js.map +1 -1
  3. package/cjs/helper/encoder.js +1 -1
  4. package/cjs/helper/encoder.js.map +1 -1
  5. package/cjs/index.js +7 -0
  6. package/cjs/index.js.map +1 -1
  7. package/cjs/session/sessionConstants.js +5 -1
  8. package/cjs/session/sessionConstants.js.map +1 -1
  9. package/cjs/session/sessionInCookie.js +1 -1
  10. package/cjs/session/sessionInCookie.js.map +1 -1
  11. package/cjs/session/sessionInLocalStorage.js +1 -1
  12. package/cjs/session/sessionInLocalStorage.js.map +1 -1
  13. package/cjs/session/sessionStore.js +18 -5
  14. package/cjs/session/sessionStore.js.map +1 -1
  15. package/cjs/session/sessionStoreOperations.js +34 -8
  16. package/cjs/session/sessionStoreOperations.js.map +1 -1
  17. package/cjs/transport/batch.js +7 -2
  18. package/cjs/transport/batch.js.map +1 -1
  19. package/cjs/transport/httpRequest.js +37 -6
  20. package/cjs/transport/httpRequest.js.map +1 -1
  21. package/esm/dataMap.js +1 -0
  22. package/esm/dataMap.js.map +1 -1
  23. package/esm/helper/encoder.js +1 -1
  24. package/esm/helper/encoder.js.map +1 -1
  25. package/esm/index.js +1 -1
  26. package/esm/index.js.map +1 -1
  27. package/esm/session/sessionConstants.js +4 -0
  28. package/esm/session/sessionConstants.js.map +1 -1
  29. package/esm/session/sessionInCookie.js +2 -2
  30. package/esm/session/sessionInCookie.js.map +1 -1
  31. package/esm/session/sessionInLocalStorage.js +2 -2
  32. package/esm/session/sessionInLocalStorage.js.map +1 -1
  33. package/esm/session/sessionStore.js +18 -5
  34. package/esm/session/sessionStore.js.map +1 -1
  35. package/esm/session/sessionStoreOperations.js +34 -9
  36. package/esm/session/sessionStoreOperations.js.map +1 -1
  37. package/esm/transport/batch.js +7 -2
  38. package/esm/transport/batch.js.map +1 -1
  39. package/esm/transport/httpRequest.js +37 -6
  40. package/esm/transport/httpRequest.js.map +1 -1
  41. package/package.json +2 -2
  42. package/src/dataMap.js +1 -0
  43. package/src/helper/encoder.js +1 -1
  44. package/src/index.js +2 -1
  45. package/src/session/sessionConstants.js +4 -0
  46. package/src/session/sessionInCookie.js +3 -2
  47. package/src/session/sessionInLocalStorage.js +4 -2
  48. package/src/session/sessionStore.js +27 -8
  49. package/src/session/sessionStoreOperations.js +31 -13
  50. package/src/transport/batch.js +1 -2
  51. package/src/transport/httpRequest.js +52 -15
  52. package/types/index.d.ts +16 -2
@@ -1,10 +1,12 @@
1
1
  import { clearInterval, setInterval } from '../helper/timer';
2
2
  import { Observable } from '../helper/observable';
3
+ import { display } from '../helper/display';
3
4
  import { ONE_SECOND, dateNow, throttle, UUID, assign } from '../helper/tools';
4
5
  import { selectCookieStrategy, initCookieStrategy } from './sessionInCookie';
5
6
  import { getExpiredSessionState, isSessionInExpiredState, isSessionInNotStartedState, isSessionStarted } from './sessionState';
6
7
  import { initLocalStorageStrategy, selectLocalStorageStrategy } from './sessionInLocalStorage';
7
8
  import { processSessionStoreOperations } from './sessionStoreOperations';
9
+ import { SessionPersistence } from './sessionConstants';
8
10
 
9
11
  /**
10
12
  * Every second, the storage will be polled to check for any change that can occur
@@ -18,11 +20,22 @@ export var STORAGE_POLL_DELAY = ONE_SECOND;
18
20
  * Else, checks if LocalStorage is allowed and available
19
21
  */
20
22
  export function selectSessionStoreStrategyType(initConfiguration) {
21
- var sessionStoreStrategyType = selectCookieStrategy(initConfiguration);
22
- if (!sessionStoreStrategyType && initConfiguration.allowFallbackToLocalStorage) {
23
- sessionStoreStrategyType = selectLocalStorageStrategy();
23
+ switch (initConfiguration.sessionPersistence) {
24
+ case SessionPersistence.COOKIE:
25
+ return selectCookieStrategy(initConfiguration);
26
+ case SessionPersistence.LOCAL_STORAGE:
27
+ return selectLocalStorageStrategy();
28
+ case undefined:
29
+ {
30
+ var sessionStoreStrategyType = selectCookieStrategy(initConfiguration);
31
+ if (!sessionStoreStrategyType && initConfiguration.allowFallbackToLocalStorage) {
32
+ sessionStoreStrategyType = selectLocalStorageStrategy();
33
+ }
34
+ return sessionStoreStrategyType;
35
+ }
36
+ default:
37
+ display.error("Invalid session persistence '".concat(String(initConfiguration.sessionPersistence), "'"));
24
38
  }
25
- return sessionStoreStrategyType;
26
39
  }
27
40
 
28
41
  /**
@@ -35,7 +48,7 @@ export function startSessionStore(sessionStoreStrategyType, productKey, computeS
35
48
  var renewObservable = new Observable();
36
49
  var expireObservable = new Observable();
37
50
  var sessionStateUpdateObservable = new Observable();
38
- var sessionStoreStrategy = sessionStoreStrategyType.type === 'Cookie' ? initCookieStrategy(sessionStoreStrategyType.cookieOptions) : initLocalStorageStrategy();
51
+ var sessionStoreStrategy = sessionStoreStrategyType.type === SessionPersistence.COOKIE ? initCookieStrategy(sessionStoreStrategyType.cookieOptions) : initLocalStorageStrategy();
39
52
  var expireSession = sessionStoreStrategy.expireSession;
40
53
  var watchSessionTimeoutId = setInterval(watchSession, STORAGE_POLL_DELAY);
41
54
  var sessionCache;
@@ -1 +1 @@
1
- {"version":3,"file":"sessionStore.js","names":["clearInterval","setInterval","Observable","ONE_SECOND","dateNow","throttle","UUID","assign","selectCookieStrategy","initCookieStrategy","getExpiredSessionState","isSessionInExpiredState","isSessionInNotStartedState","isSessionStarted","initLocalStorageStrategy","selectLocalStorageStrategy","processSessionStoreOperations","STORAGE_POLL_DELAY","selectSessionStoreStrategyType","initConfiguration","sessionStoreStrategyType","allowFallbackToLocalStorage","startSessionStore","productKey","computeSessionState","renewObservable","expireObservable","sessionStateUpdateObservable","sessionStoreStrategy","type","cookieOptions","expireSession","watchSessionTimeoutId","watchSession","sessionCache","startSession","_throttle","process","sessionState","synchronizedSession","synchronizeSession","expandOrRenewSessionState","after","hasSessionInCache","renewSessionInCache","throttledExpandOrRenewSession","throttled","cancelExpandOrRenewSession","cancel","expandSession","undefined","isSessionInCacheOutdated","expireSessionInCache","notify","previousState","newState","_computeSessionState","trackingType","isTracked","isExpired","id","created","String","updateSessionState","partialSessionState","expandOrRenewSession","getSession","restartSession","expire","stop"],"sources":["../../src/session/sessionStore.js"],"sourcesContent":["import { clearInterval, setInterval } from '../helper/timer'\nimport { Observable } from '../helper/observable'\nimport { ONE_SECOND, dateNow, throttle, UUID, assign } from '../helper/tools'\nimport { selectCookieStrategy, initCookieStrategy } from './sessionInCookie'\nimport {\n getExpiredSessionState,\n isSessionInExpiredState,\n isSessionInNotStartedState,\n isSessionStarted\n} from './sessionState'\nimport {\n initLocalStorageStrategy,\n selectLocalStorageStrategy\n} from './sessionInLocalStorage'\nimport { processSessionStoreOperations } from './sessionStoreOperations'\n\n/**\n * Every second, the storage will be polled to check for any change that can occur\n * to the session state in another browser tab, or another window.\n * This value has been determined from our previous cookie-only implementation.\n */\nexport const STORAGE_POLL_DELAY = ONE_SECOND\n\n/**\n * Checks if cookies are available as the preferred storage\n * Else, checks if LocalStorage is allowed and available\n */\nexport function selectSessionStoreStrategyType(initConfiguration) {\n let sessionStoreStrategyType = selectCookieStrategy(initConfiguration)\n if (\n !sessionStoreStrategyType &&\n initConfiguration.allowFallbackToLocalStorage\n ) {\n sessionStoreStrategyType = selectLocalStorageStrategy()\n }\n return sessionStoreStrategyType\n}\n\n/**\n * Different session concepts:\n * - tracked, the session has an id and is updated along the user navigation\n * - not tracked, the session does not have an id but it is updated along the user navigation\n * - inactive, no session in store or session expired, waiting for a renew session\n */\nexport function startSessionStore(\n sessionStoreStrategyType,\n productKey,\n computeSessionState\n) {\n const renewObservable = new Observable()\n const expireObservable = new Observable()\n const sessionStateUpdateObservable = new Observable()\n const sessionStoreStrategy =\n sessionStoreStrategyType.type === 'Cookie'\n ? initCookieStrategy(sessionStoreStrategyType.cookieOptions)\n : initLocalStorageStrategy()\n const { expireSession } = sessionStoreStrategy\n\n const watchSessionTimeoutId = setInterval(watchSession, STORAGE_POLL_DELAY)\n let sessionCache\n\n startSession()\n\n const {\n throttled: throttledExpandOrRenewSession,\n cancel: cancelExpandOrRenewSession\n } = throttle(function () {\n processSessionStoreOperations(\n {\n process: function (sessionState) {\n if (isSessionInNotStartedState(sessionState)) {\n return\n }\n\n const synchronizedSession = synchronizeSession(sessionState)\n expandOrRenewSessionState(synchronizedSession)\n return synchronizedSession\n },\n after: function (sessionState) {\n if (isSessionStarted(sessionState) && !hasSessionInCache()) {\n renewSessionInCache(sessionState)\n }\n sessionCache = sessionState\n }\n },\n sessionStoreStrategy\n )\n }, STORAGE_POLL_DELAY)\n\n function expandSession() {\n processSessionStoreOperations(\n {\n process: function (sessionState) {\n return hasSessionInCache()\n ? synchronizeSession(sessionState)\n : undefined\n }\n },\n sessionStoreStrategy\n )\n }\n\n /**\n * allows two behaviors:\n * - if the session is active, synchronize the session cache without updating the session store\n * - if the session is not active, clear the session store and expire the session cache\n */\n function watchSession() {\n processSessionStoreOperations(\n {\n process: function (sessionState) {\n return isSessionInExpiredState(sessionState)\n ? getExpiredSessionState()\n : undefined\n },\n after: synchronizeSession\n },\n sessionStoreStrategy\n )\n }\n\n function synchronizeSession(sessionState) {\n if (isSessionInExpiredState(sessionState)) {\n sessionState = getExpiredSessionState()\n }\n if (hasSessionInCache()) {\n if (isSessionInCacheOutdated(sessionState)) {\n expireSessionInCache()\n } else {\n sessionStateUpdateObservable.notify({\n previousState: sessionCache,\n newState: sessionState\n })\n sessionCache = sessionState\n }\n }\n return sessionState\n }\n\n function startSession() {\n processSessionStoreOperations(\n {\n process: function (sessionState) {\n if (isSessionInNotStartedState(sessionState)) {\n return getExpiredSessionState()\n }\n },\n after: function (sessionState) {\n sessionCache = sessionState\n }\n },\n sessionStoreStrategy\n )\n }\n\n function expandOrRenewSessionState(sessionState) {\n if (isSessionInNotStartedState(sessionState)) {\n return false\n }\n\n const { trackingType, isTracked } = computeSessionState(\n sessionState[productKey]\n )\n sessionState[productKey] = trackingType\n delete sessionState.isExpired\n if (isTracked && !sessionState.id) {\n sessionState.id = UUID()\n sessionState.created = String(dateNow())\n }\n }\n\n function hasSessionInCache() {\n return sessionCache[productKey] !== undefined\n }\n\n function isSessionInCacheOutdated(sessionState) {\n return (\n sessionCache.id !== sessionState.id ||\n sessionCache[productKey] !== sessionState[productKey]\n )\n }\n\n function expireSessionInCache() {\n sessionCache = getExpiredSessionState()\n expireObservable.notify()\n }\n\n function renewSessionInCache(sessionState) {\n sessionCache = sessionState\n renewObservable.notify()\n }\n\n function updateSessionState(partialSessionState) {\n processSessionStoreOperations(\n {\n process: function (sessionState) {\n return assign({}, sessionState, partialSessionState)\n },\n after: synchronizeSession\n },\n sessionStoreStrategy\n )\n }\n\n return {\n expandOrRenewSession: throttledExpandOrRenewSession,\n expandSession,\n getSession: function () {\n return sessionCache || {}\n },\n renewObservable,\n expireObservable,\n sessionStateUpdateObservable,\n restartSession: startSession,\n expire: function () {\n cancelExpandOrRenewSession()\n expireSession()\n synchronizeSession(getExpiredSessionState())\n },\n stop: function () {\n clearInterval(watchSessionTimeoutId)\n },\n updateSessionState\n }\n}\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,WAAW,QAAQ,iBAAiB;AAC5D,SAASC,UAAU,QAAQ,sBAAsB;AACjD,SAASC,UAAU,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,MAAM,QAAQ,iBAAiB;AAC7E,SAASC,oBAAoB,EAAEC,kBAAkB,QAAQ,mBAAmB;AAC5E,SACEC,sBAAsB,EACtBC,uBAAuB,EACvBC,0BAA0B,EAC1BC,gBAAgB,QACX,gBAAgB;AACvB,SACEC,wBAAwB,EACxBC,0BAA0B,QACrB,yBAAyB;AAChC,SAASC,6BAA6B,QAAQ,0BAA0B;;AAExE;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMC,kBAAkB,GAAGd,UAAU;;AAE5C;AACA;AACA;AACA;AACA,OAAO,SAASe,8BAA8BA,CAACC,iBAAiB,EAAE;EAChE,IAAIC,wBAAwB,GAAGZ,oBAAoB,CAACW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,YAAY,GAAGI,YAAY;IAC3Bb,eAAe,CAAC4B,MAAM,CAAC,CAAC;EAC1B;EAEA,SAASU,kBAAkBA,CAACC,mBAAmB,EAAE;IAC/ChD,6BAA6B,CAC3B;MACEqB,OAAO,EAAE,SAATA,OAAOA,CAAYC,YAAY,EAAE;QAC/B,OAAO/B,MAAM,CAAC,CAAC,CAAC,EAAE+B,YAAY,EAAE0B,mBAAmB,CAAC;MACtD,CAAC;MACDtB,KAAK,EAAEF;IACT,CAAC,EACDZ,oBACF,CAAC;EACH;EAEA,OAAO;IACLqC,oBAAoB,EAAEpB,6BAA6B;IACnDI,aAAa,EAAbA,aAAa;IACbiB,UAAU,EAAE,SAAZA,UAAUA,CAAA,EAAc;MACtB,OAAOhC,YAAY,IAAI,CAAC,CAAC;IAC3B,CAAC;IACDT,eAAe,EAAfA,eAAe;IACfC,gBAAgB,EAAhBA,gBAAgB;IAChBC,4BAA4B,EAA5BA,4BAA4B;IAC5BwC,cAAc,EAAEhC,YAAY;IAC5BiC,MAAM,EAAE,SAARA,MAAMA,CAAA,EAAc;MAClBrB,0BAA0B,CAAC,CAAC;MAC5BhB,aAAa,CAAC,CAAC;MACfS,kBAAkB,CAAC9B,sBAAsB,CAAC,CAAC,CAAC;IAC9C,CAAC;IACD2D,IAAI,EAAE,SAANA,IAAIA,CAAA,EAAc;MAChBrE,aAAa,CAACgC,qBAAqB,CAAC;IACtC,CAAC;IACD+B,kBAAkB,EAAlBA;EACF,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"sessionStore.js","names":["clearInterval","setInterval","Observable","display","ONE_SECOND","dateNow","throttle","UUID","assign","selectCookieStrategy","initCookieStrategy","getExpiredSessionState","isSessionInExpiredState","isSessionInNotStartedState","isSessionStarted","initLocalStorageStrategy","selectLocalStorageStrategy","processSessionStoreOperations","SessionPersistence","STORAGE_POLL_DELAY","selectSessionStoreStrategyType","initConfiguration","sessionPersistence","COOKIE","LOCAL_STORAGE","undefined","sessionStoreStrategyType","allowFallbackToLocalStorage","error","concat","String","startSessionStore","productKey","computeSessionState","renewObservable","expireObservable","sessionStateUpdateObservable","sessionStoreStrategy","type","cookieOptions","expireSession","watchSessionTimeoutId","watchSession","sessionCache","startSession","_throttle","process","sessionState","synchronizedSession","synchronizeSession","expandOrRenewSessionState","after","hasSessionInCache","renewSessionInCache","throttledExpandOrRenewSession","throttled","cancelExpandOrRenewSession","cancel","expandSession","isSessionInCacheOutdated","expireSessionInCache","notify","previousState","newState","_computeSessionState","trackingType","isTracked","isExpired","id","created","updateSessionState","partialSessionState","expandOrRenewSession","getSession","restartSession","expire","stop"],"sources":["../../src/session/sessionStore.js"],"sourcesContent":["import { clearInterval, setInterval } from '../helper/timer'\nimport { Observable } from '../helper/observable'\nimport { display } from '../helper/display'\nimport { ONE_SECOND, dateNow, throttle, UUID, assign } from '../helper/tools'\nimport { selectCookieStrategy, initCookieStrategy } from './sessionInCookie'\nimport {\n getExpiredSessionState,\n isSessionInExpiredState,\n isSessionInNotStartedState,\n isSessionStarted\n} from './sessionState'\nimport {\n initLocalStorageStrategy,\n selectLocalStorageStrategy\n} from './sessionInLocalStorage'\nimport { processSessionStoreOperations } from './sessionStoreOperations'\nimport { SessionPersistence } from './sessionConstants'\n\n/**\n * Every second, the storage will be polled to check for any change that can occur\n * to the session state in another browser tab, or another window.\n * This value has been determined from our previous cookie-only implementation.\n */\nexport const STORAGE_POLL_DELAY = ONE_SECOND\n\n/**\n * Checks if cookies are available as the preferred storage\n * Else, checks if LocalStorage is allowed and available\n */\nexport function selectSessionStoreStrategyType(initConfiguration) {\n switch (initConfiguration.sessionPersistence) {\n case SessionPersistence.COOKIE:\n return selectCookieStrategy(initConfiguration)\n\n case SessionPersistence.LOCAL_STORAGE:\n return selectLocalStorageStrategy()\n\n case undefined: {\n let sessionStoreStrategyType = selectCookieStrategy(initConfiguration)\n if (\n !sessionStoreStrategyType &&\n initConfiguration.allowFallbackToLocalStorage\n ) {\n sessionStoreStrategyType = selectLocalStorageStrategy()\n }\n return sessionStoreStrategyType\n }\n\n default:\n display.error(\n `Invalid session persistence '${String(\n initConfiguration.sessionPersistence\n )}'`\n )\n }\n}\n\n/**\n * Different session concepts:\n * - tracked, the session has an id and is updated along the user navigation\n * - not tracked, the session does not have an id but it is updated along the user navigation\n * - inactive, no session in store or session expired, waiting for a renew session\n */\nexport function startSessionStore(\n sessionStoreStrategyType,\n productKey,\n computeSessionState\n) {\n const renewObservable = new Observable()\n const expireObservable = new Observable()\n const sessionStateUpdateObservable = new Observable()\n const sessionStoreStrategy =\n sessionStoreStrategyType.type === SessionPersistence.COOKIE\n ? initCookieStrategy(sessionStoreStrategyType.cookieOptions)\n : initLocalStorageStrategy()\n const { expireSession } = sessionStoreStrategy\n\n const watchSessionTimeoutId = setInterval(watchSession, STORAGE_POLL_DELAY)\n let sessionCache\n\n startSession()\n\n const {\n throttled: throttledExpandOrRenewSession,\n cancel: cancelExpandOrRenewSession\n } = throttle(function () {\n processSessionStoreOperations(\n {\n process: function (sessionState) {\n if (isSessionInNotStartedState(sessionState)) {\n return\n }\n\n const synchronizedSession = synchronizeSession(sessionState)\n expandOrRenewSessionState(synchronizedSession)\n return synchronizedSession\n },\n after: function (sessionState) {\n if (isSessionStarted(sessionState) && !hasSessionInCache()) {\n renewSessionInCache(sessionState)\n }\n sessionCache = sessionState\n }\n },\n sessionStoreStrategy\n )\n }, STORAGE_POLL_DELAY)\n\n function expandSession() {\n processSessionStoreOperations(\n {\n process: function (sessionState) {\n return hasSessionInCache()\n ? synchronizeSession(sessionState)\n : undefined\n }\n },\n sessionStoreStrategy\n )\n }\n\n /**\n * allows two behaviors:\n * - if the session is active, synchronize the session cache without updating the session store\n * - if the session is not active, clear the session store and expire the session cache\n */\n function watchSession() {\n processSessionStoreOperations(\n {\n process: function (sessionState) {\n return isSessionInExpiredState(sessionState)\n ? getExpiredSessionState()\n : undefined\n },\n after: synchronizeSession\n },\n sessionStoreStrategy\n )\n }\n\n function synchronizeSession(sessionState) {\n if (isSessionInExpiredState(sessionState)) {\n sessionState = getExpiredSessionState()\n }\n if (hasSessionInCache()) {\n if (isSessionInCacheOutdated(sessionState)) {\n expireSessionInCache()\n } else {\n sessionStateUpdateObservable.notify({\n previousState: sessionCache,\n newState: sessionState\n })\n sessionCache = sessionState\n }\n }\n return sessionState\n }\n\n function startSession() {\n processSessionStoreOperations(\n {\n process: function (sessionState) {\n if (isSessionInNotStartedState(sessionState)) {\n return getExpiredSessionState()\n }\n },\n after: function (sessionState) {\n sessionCache = sessionState\n }\n },\n sessionStoreStrategy\n )\n }\n\n function expandOrRenewSessionState(sessionState) {\n if (isSessionInNotStartedState(sessionState)) {\n return false\n }\n\n const { trackingType, isTracked } = computeSessionState(\n sessionState[productKey]\n )\n sessionState[productKey] = trackingType\n delete sessionState.isExpired\n if (isTracked && !sessionState.id) {\n sessionState.id = UUID()\n sessionState.created = String(dateNow())\n }\n }\n\n function hasSessionInCache() {\n return sessionCache[productKey] !== undefined\n }\n\n function isSessionInCacheOutdated(sessionState) {\n return (\n sessionCache.id !== sessionState.id ||\n sessionCache[productKey] !== sessionState[productKey]\n )\n }\n\n function expireSessionInCache() {\n sessionCache = getExpiredSessionState()\n expireObservable.notify()\n }\n\n function renewSessionInCache(sessionState) {\n sessionCache = sessionState\n renewObservable.notify()\n }\n\n function updateSessionState(partialSessionState) {\n processSessionStoreOperations(\n {\n process: function (sessionState) {\n return assign({}, sessionState, partialSessionState)\n },\n after: synchronizeSession\n },\n sessionStoreStrategy\n )\n }\n\n return {\n expandOrRenewSession: throttledExpandOrRenewSession,\n expandSession,\n getSession: function () {\n return sessionCache || {}\n },\n renewObservable,\n expireObservable,\n sessionStateUpdateObservable,\n restartSession: startSession,\n expire: function () {\n cancelExpandOrRenewSession()\n expireSession()\n synchronizeSession(getExpiredSessionState())\n },\n stop: function () {\n clearInterval(watchSessionTimeoutId)\n },\n updateSessionState\n }\n}\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,WAAW,QAAQ,iBAAiB;AAC5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AC,EACDZ,oBACF,CAAC;EACH;EAEA,OAAO;IACLmC,oBAAoB,EAAElB,6BAA6B;IACnDI,aAAa,EAAbA,aAAa;IACbe,UAAU,EAAE,SAAZA,UAAUA,CAAA,EAAc;MACtB,OAAO9B,YAAY,IAAI,CAAC,CAAC;IAC3B,CAAC;IACDT,eAAe,EAAfA,eAAe;IACfC,gBAAgB,EAAhBA,gBAAgB;IAChBC,4BAA4B,EAA5BA,4BAA4B;IAC5BsC,cAAc,EAAE9B,YAAY;IAC5B+B,MAAM,EAAE,SAARA,MAAMA,CAAA,EAAc;MAClBnB,0BAA0B,CAAC,CAAC;MAC5BhB,aAAa,CAAC,CAAC;MACfS,kBAAkB,CAACtC,sBAAsB,CAAC,CAAC,CAAC;IAC9C,CAAC;IACDiE,IAAI,EAAE,SAANA,IAAIA,CAAA,EAAc;MAChB5E,aAAa,CAACyC,qBAAqB,CAAC;IACtC,CAAC;IACD6B,kBAAkB,EAAlBA;EACF,CAAC;AACH","ignoreList":[]}
@@ -1,8 +1,23 @@
1
+ var _excluded = ["lock"];
2
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
3
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
5
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
6
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
7
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
8
+ function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
9
+ function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
1
10
  import { setTimeout } from '../helper/timer';
2
- import { UUID, assign } from '../helper/tools';
3
- import { expandSessionState, isSessionInExpiredState, isSessionInNotStartedState } from './sessionState';
11
+ import { UUID, assign, ONE_SECOND, timeStampNow, elapsed } from '../helper/tools';
12
+ import { expandSessionState, isSessionInExpiredState } from './sessionState';
13
+ import { addTelemetryDebug } from '../telemetry/telemetry';
4
14
  export var LOCK_RETRY_DELAY = 10;
5
15
  export var LOCK_MAX_TRIES = 100;
16
+
17
+ // Locks should be hold for a few milliseconds top, just the time it takes to read and write a
18
+ // cookie. Using one second should be enough in most situations.
19
+ export var LOCK_EXPIRATION_DELAY = ONE_SECOND;
20
+ var LOCK_SEPARATOR = '--';
6
21
  var bufferedOperations = [];
7
22
  var ongoingOperations;
8
23
  export function processSessionStoreOperations(operations, sessionStoreStrategy) {
@@ -16,14 +31,12 @@ export function processSessionStoreOperations(operations, sessionStoreStrategy)
16
31
  }));
17
32
  };
18
33
  var retrieveStore = function retrieveStore() {
19
- var session = sessionStoreStrategy.retrieveSession();
20
- var lock = session.lock;
21
- if (session.lock) {
22
- delete session.lock;
23
- }
34
+ var _sessionStoreStrategy = sessionStoreStrategy.retrieveSession(),
35
+ lock = _sessionStoreStrategy.lock,
36
+ session = _objectWithoutProperties(_sessionStoreStrategy, _excluded);
24
37
  return {
25
38
  session: session,
26
- lock: lock
39
+ lock: lock && !isLockExpired(lock) ? lock : undefined
27
40
  };
28
41
  };
29
42
  if (!ongoingOperations) {
@@ -34,6 +47,9 @@ export function processSessionStoreOperations(operations, sessionStoreStrategy)
34
47
  return;
35
48
  }
36
49
  if (isLockEnabled && numberOfRetries >= LOCK_MAX_TRIES) {
50
+ addTelemetryDebug('Aborted session operation after max lock retries', {
51
+ currentStore: retrieveStore()
52
+ });
37
53
  next(sessionStoreStrategy);
38
54
  return;
39
55
  }
@@ -46,7 +62,7 @@ export function processSessionStoreOperations(operations, sessionStoreStrategy)
46
62
  return;
47
63
  }
48
64
  // acquire lock
49
- currentLock = UUID();
65
+ currentLock = createLock();
50
66
  persistWithLock(currentStore.session);
51
67
  // if lock is not acquired, retry later
52
68
  currentStore = retrieveStore();
@@ -105,4 +121,13 @@ function next(sessionStore) {
105
121
  processSessionStoreOperations(nextOperations, sessionStore);
106
122
  }
107
123
  }
124
+ export function createLock() {
125
+ return UUID() + LOCK_SEPARATOR + timeStampNow();
126
+ }
127
+ function isLockExpired(lock) {
128
+ var _lock$split = lock.split(LOCK_SEPARATOR),
129
+ _lock$split2 = _slicedToArray(_lock$split, 2),
130
+ timeStamp = _lock$split2[1];
131
+ return !timeStamp || elapsed(Number(timeStamp), timeStampNow()) > LOCK_EXPIRATION_DELAY;
132
+ }
108
133
  //# sourceMappingURL=sessionStoreOperations.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sessionStoreOperations.js","names":["setTimeout","UUID","assign","expandSessionState","isSessionInExpiredState","isSessionInNotStartedState","LOCK_RETRY_DELAY","LOCK_MAX_TRIES","bufferedOperations","ongoingOperations","processSessionStoreOperations","operations","sessionStoreStrategy","numberOfRetries","arguments","length","undefined","isLockEnabled","persistSession","expireSession","persistWithLock","session","lock","currentLock","retrieveStore","retrieveSession","push","next","currentStore","retryLater","processedSession","process","after","sessionStore","currentNumberOfRetries","nextOperations","shift"],"sources":["../../src/session/sessionStoreOperations.js"],"sourcesContent":["import { setTimeout } from '../helper/timer'\nimport { UUID, assign } from '../helper/tools'\nimport {\n expandSessionState,\n isSessionInExpiredState,\n isSessionInNotStartedState\n} from './sessionState'\n\nexport const LOCK_RETRY_DELAY = 10\nexport const LOCK_MAX_TRIES = 100\nconst bufferedOperations = []\nlet ongoingOperations\n\nexport function processSessionStoreOperations(\n operations,\n sessionStoreStrategy,\n numberOfRetries = 0\n) {\n const { isLockEnabled, persistSession, expireSession } = sessionStoreStrategy\n const persistWithLock = function (session) {\n return persistSession(assign({}, session, { lock: currentLock }))\n }\n const retrieveStore = function () {\n const session = sessionStoreStrategy.retrieveSession()\n const lock = session.lock\n if (session.lock) {\n delete session.lock\n }\n\n return {\n session,\n lock\n }\n }\n\n if (!ongoingOperations) {\n ongoingOperations = operations\n }\n if (operations !== ongoingOperations) {\n bufferedOperations.push(operations)\n return\n }\n if (isLockEnabled && numberOfRetries >= LOCK_MAX_TRIES) {\n next(sessionStoreStrategy)\n return\n }\n let currentLock\n let currentStore = retrieveStore()\n if (isLockEnabled) {\n // if someone has lock, retry later\n if (currentStore.lock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n // acquire lock\n currentLock = UUID()\n persistWithLock(currentStore.session)\n // if lock is not acquired, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n }\n let processedSession = operations.process(currentStore.session)\n if (isLockEnabled) {\n // if lock corrupted after process, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n }\n if (processedSession) {\n if (isSessionInExpiredState(processedSession)) {\n expireSession()\n } else {\n expandSessionState(processedSession)\n isLockEnabled\n ? persistWithLock(processedSession)\n : persistSession(processedSession)\n }\n }\n if (isLockEnabled) {\n // correctly handle lock around expiration would require to handle this case properly at several levels\n // since we don't have evidence of lock issues around expiration, let's just not do the corruption check for it\n if (!(processedSession && isSessionInExpiredState(processedSession))) {\n // if lock corrupted after persist, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n persistSession(currentStore.session)\n processedSession = currentStore.session\n }\n }\n // call after even if session is not persisted in order to perform operations on\n // up-to-date session state value => the value could have been modified by another tab\n if (operations.after) {\n operations.after(processedSession || currentStore.session)\n }\n next(sessionStoreStrategy)\n}\n\nfunction retryLater(operations, sessionStore, currentNumberOfRetries) {\n setTimeout(function () {\n processSessionStoreOperations(\n operations,\n sessionStore,\n currentNumberOfRetries + 1\n )\n }, LOCK_RETRY_DELAY)\n}\n\nfunction next(sessionStore) {\n ongoingOperations = undefined\n const nextOperations = bufferedOperations.shift()\n if (nextOperations) {\n processSessionStoreOperations(nextOperations, sessionStore)\n }\n}\n"],"mappings":"AAAA,SAASA,UAAU,QAAQ,iBAAiB;AAC5C,SAASC,IAAI,EAAEC,MAAM,QAAQ,iBAAiB;AAC9C,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,0BAA0B,QACrB,gBAAgB;AAEvB,OAAO,IAAMC,gBAAgB,GAAG,EAAE;AAClC,OAAO,IAAMC,cAAc,GAAG,GAAG;AACjC,IAAMC,kBAAkB,GAAG,EAAE;AAC7B,IAAIC,iBAAiB;AAErB,OAAO,SAASC,6BAA6BA,CAC3CC,UAAU,EACVC,oBAAoB,EAEpB;EAAA,IADAC,eAAe,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC;EAEnB,IAAQG,aAAa,GAAoCL,oB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AAsB,EAAE;EACpElC,UAAU,CAAC,YAAY;IACrBU,6BAA6B,CAC3BC,UAAU,EACVsB,YAAY,EACZC,sBAAsB,GAAG,CAC3B,CAAC;EACH,CAAC,EAAE5B,gBAAgB,CAAC;AACtB;AAEA,SAASqB,IAAIA,CAACM,YAAY,EAAE;EAC1BxB,iBAAiB,GAAGO,SAAS;EAC7B,IAAMmB,cAAc,GAAG3B,kBAAkB,CAAC4B,KAAK,CAAC,CAAC;EACjD,IAAID,cAAc,EAAE;IAClBzB,6BAA6B,CAACyB,cAAc,EAAEF,YAAY,CAAC;EAC7D;AACF","ignoreList":[]}
1
+ {"version":3,"file":"sessionStoreOperations.js","names":["setTimeout","UUID","assign","ONE_SECOND","timeStampNow","elapsed","expandSessionState","isSessionInExpiredState","addTelemetryDebug","LOCK_RETRY_DELAY","LOCK_MAX_TRIES","LOCK_EXPIRATION_DELAY","LOCK_SEPARATOR","bufferedOperations","ongoingOperations","processSessionStoreOperations","operations","sessionStoreStrategy","numberOfRetries","arguments","length","undefined","isLockEnabled","persistSession","expireSession","persistWithLock","session","lock","currentLock","retrieveStore","_sessionStoreStrategy","retrieveSession","_objectWithoutProperties","_excluded","isLockExpired","push","currentStore","next","retryLater","createLock","processedSession","process","after","sessionStore","currentNumberOfRetries","nextOperations","shift","_lock$split","split","_lock$split2","_slicedToArray","timeStamp","Number"],"sources":["../../src/session/sessionStoreOperations.js"],"sourcesContent":["import { setTimeout } from '../helper/timer'\nimport {\n UUID,\n assign,\n ONE_SECOND,\n timeStampNow,\n elapsed\n} from '../helper/tools'\nimport { expandSessionState, isSessionInExpiredState } from './sessionState'\nimport { addTelemetryDebug } from '../telemetry/telemetry'\nexport const LOCK_RETRY_DELAY = 10\nexport const LOCK_MAX_TRIES = 100\n\n// Locks should be hold for a few milliseconds top, just the time it takes to read and write a\n// cookie. Using one second should be enough in most situations.\nexport const LOCK_EXPIRATION_DELAY = ONE_SECOND\nconst LOCK_SEPARATOR = '--'\nconst bufferedOperations = []\nlet ongoingOperations\n\nexport function processSessionStoreOperations(\n operations,\n sessionStoreStrategy,\n numberOfRetries = 0\n) {\n const { isLockEnabled, persistSession, expireSession } = sessionStoreStrategy\n const persistWithLock = function (session) {\n return persistSession(assign({}, session, { lock: currentLock }))\n }\n const retrieveStore = function () {\n const { lock, ...session } = sessionStoreStrategy.retrieveSession()\n\n return {\n session,\n lock: lock && !isLockExpired(lock) ? lock : undefined\n }\n }\n\n if (!ongoingOperations) {\n ongoingOperations = operations\n }\n if (operations !== ongoingOperations) {\n bufferedOperations.push(operations)\n return\n }\n if (isLockEnabled && numberOfRetries >= LOCK_MAX_TRIES) {\n addTelemetryDebug('Aborted session operation after max lock retries', {\n currentStore: retrieveStore()\n })\n next(sessionStoreStrategy)\n return\n }\n let currentLock\n let currentStore = retrieveStore()\n if (isLockEnabled) {\n // if someone has lock, retry later\n if (currentStore.lock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n // acquire lock\n currentLock = createLock()\n persistWithLock(currentStore.session)\n // if lock is not acquired, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n }\n let processedSession = operations.process(currentStore.session)\n if (isLockEnabled) {\n // if lock corrupted after process, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n }\n if (processedSession) {\n if (isSessionInExpiredState(processedSession)) {\n expireSession()\n } else {\n expandSessionState(processedSession)\n isLockEnabled\n ? persistWithLock(processedSession)\n : persistSession(processedSession)\n }\n }\n if (isLockEnabled) {\n // correctly handle lock around expiration would require to handle this case properly at several levels\n // since we don't have evidence of lock issues around expiration, let's just not do the corruption check for it\n if (!(processedSession && isSessionInExpiredState(processedSession))) {\n // if lock corrupted after persist, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n persistSession(currentStore.session)\n processedSession = currentStore.session\n }\n }\n // call after even if session is not persisted in order to perform operations on\n // up-to-date session state value => the value could have been modified by another tab\n if (operations.after) {\n operations.after(processedSession || currentStore.session)\n }\n next(sessionStoreStrategy)\n}\n\nfunction retryLater(operations, sessionStore, currentNumberOfRetries) {\n setTimeout(function () {\n processSessionStoreOperations(\n operations,\n sessionStore,\n currentNumberOfRetries + 1\n )\n }, LOCK_RETRY_DELAY)\n}\n\nfunction next(sessionStore) {\n ongoingOperations = undefined\n const nextOperations = bufferedOperations.shift()\n if (nextOperations) {\n processSessionStoreOperations(nextOperations, sessionStore)\n }\n}\n\nexport function createLock() {\n return UUID() + LOCK_SEPARATOR + timeStampNow()\n}\n\nfunction isLockExpired(lock) {\n const [, timeStamp] = lock.split(LOCK_SEPARATOR)\n return (\n !timeStamp ||\n elapsed(Number(timeStamp), timeStampNow()) > LOCK_EXPIRATION_DELAY\n )\n}\n"],"mappings":";;;;;;;;;AAAA,SAASA,UAAU,QAAQ,iBAAiB;AAC5C,SACEC,IAAI,EACJC,MAAM,EACNC,UAAU,EACVC,YAAY,EACZC,OAAO,QACF,iBAAiB;AACxB,SAASC,kBAAkB,EAAEC,uBAAuB,QAAQ,gBAAgB;AAC5E,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,OAAO,IAAMC,gBAAgB,GAAG,EAAE;AAClC,OAAO,IAAMC,cAAc,GAAG,GAAG;;AAEjC;AACA;AACA,OAAO,IAAMC,qBAAqB,GAAGR,UAAU;AAC/C,IAAMS,cAAc,GAAG,IAAI;AAC3B,IAAMC,kBAAkB,GAAG,EAAE;AAC7B,IAAIC,iBAAiB;AAErB,OAAO,SAASC,6BAA6BA,CAC3CC,UAAU,EACVC,oBAAoB,EAEpB;EAAA,IADAC,eAAe,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC;EAEnB,IAAQG,aAAa,GAAoCL,oBAAoB,CAArEK,aAAa;I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Y,CAACV,OAAO,CAAC;EAC5D;EACAW,IAAI,CAACpB,oBAAoB,CAAC;AAC5B;AAEA,SAASqB,UAAUA,CAACtB,UAAU,EAAE2B,YAAY,EAAEC,sBAAsB,EAAE;EACpE5C,UAAU,CAAC,YAAY;IACrBe,6BAA6B,CAC3BC,UAAU,EACV2B,YAAY,EACZC,sBAAsB,GAAG,CAC3B,CAAC;EACH,CAAC,EAAEnC,gBAAgB,CAAC;AACtB;AAEA,SAAS4B,IAAIA,CAACM,YAAY,EAAE;EAC1B7B,iBAAiB,GAAGO,SAAS;EAC7B,IAAMwB,cAAc,GAAGhC,kBAAkB,CAACiC,KAAK,CAAC,CAAC;EACjD,IAAID,cAAc,EAAE;IAClB9B,6BAA6B,CAAC8B,cAAc,EAAEF,YAAY,CAAC;EAC7D;AACF;AAEA,OAAO,SAASJ,UAAUA,CAAA,EAAG;EAC3B,OAAOtC,IAAI,CAAC,CAAC,GAAGW,cAAc,GAAGR,YAAY,CAAC,CAAC;AACjD;AAEA,SAAS8B,aAAaA,CAACP,IAAI,EAAE;EAC3B,IAAAoB,WAAA,GAAsBpB,IAAI,CAACqB,KAAK,CAACpC,cAAc,CAAC;IAAAqC,YAAA,GAAAC,cAAA,CAAAH,WAAA;IAAvCI,SAAS,GAAAF,YAAA;EAClB,OACE,CAACE,SAAS,IACV9C,OAAO,CAAC+C,MAAM,CAACD,SAAS,CAAC,EAAE/C,YAAY,CAAC,CAAC,CAAC,GAAGO,qBAAqB;AAEtE","ignoreList":[]}
@@ -1,3 +1,9 @@
1
+ function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
2
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
4
+ function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
5
+ function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
6
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
1
7
  import { display } from '../helper/display';
2
8
  import { values, findByPath, each, isNumber, isArray, extend, isString, isEmptyObject, isObject } from '../helper/tools';
3
9
  import { escapeJsonValue, escapeRowField, escapeRowData } from '../helper/serialisation/rowData';
@@ -180,9 +186,8 @@ export function createBatch(options) {
180
186
  if (encoderResult.outputBytesCount) {
181
187
  send(formatPayloadFromEncoder(encoderResult, sendContentTypeByJson));
182
188
  }
183
-
184
189
  // Send messages that are not yet encoded at this point
185
- var pendingMessages = [encoderResult.pendingData, upsertMessages].filter(Boolean).join('\n');
190
+ var pendingMessages = [].concat(_toConsumableArray(encoderResult.pendingData), [upsertMessages]).filter(Boolean).join('\n');
186
191
  if (pendingMessages) {
187
192
  send({
188
193
  data: pendingMessages,
@@ -1 +1 @@
1
- {"version":3,"file":"batch.js","names":["display","values","findByPath","each","isNumber","isArray","extend","isString","isEmptyObject","isObject","escapeJsonValue","escapeRowField","escapeRowData","commonTags","dataMap","commonFields","RumEventType","computeBytesCount","isPageExitReason","jsonStringify","CUSTOM_KEYS","processedMessageByDataMap","message","type","rowStr","rowData","undefined","tags","fields","hasFileds","value","key","measurement","tagsStr","filterFileds","value_path","_key","_value","push","fieldsStr","length","_valueData","context","_tagKeys","indexOf","LOGGER","join","date","time","createBatch","options","encoder","request","messageBytesLimit","sendContentTypeByJson","flushController","upsertBuffer","flushSubscription","flushObservable","subscribe","event","flush","getMessageText","messages","isEmpty","arguments","serializedMessage","estimatedMessageBytesCount","notifyBeforeAddMessage","notifyAfterAddMessage","write","realMessageBytesCount","hasMessageFor","remove","removedMessage","messageBytesCount","estimateEncodedBytesCount","notifyAfterRemoveMessage","process","processedMessage","addOrUpdate","warn","concat","upsertMessages","isPageExit","reason","send","sendOnExit","isAsync","encoderResult","finishSync","outputBytesCount","formatPayloadFromEncoder","pendingMessages","pendingData","filter","Boolean","data","bytesCount","text","finish","add","upsert","stop","unsubscribe","output","Blob","encoding"],"sources":["../../src/transport/batch.js"],"sourcesContent":["import { display } from '../helper/display'\nimport {\n values,\n findByPath,\n each,\n isNumber,\n isArray,\n extend,\n isString,\n isEmptyObject,\n isObject\n} from '../helper/tools'\nimport {\n escapeJsonValue,\n escapeRowField,\n escapeRowData\n} from '../helper/serialisation/rowData'\nimport { commonTags, dataMap, commonFields } from '../dataMap'\nimport { RumEventType } from '../helper/enums'\nimport { computeBytesCount } from '../helper/byteUtils'\nimport { isPageExitReason } from '../browser/pageExitObservable'\nimport { jsonStringify } from '../helper/serialisation/jsonStringify'\n// https://en.wikipedia.org/wiki/UTF-8\n// eslint-disable-next-line no-control-regex\nvar CUSTOM_KEYS = 'custom_keys'\nexport var processedMessageByDataMap = function (message) {\n if (!message || !message.type)\n return {\n rowStr: '',\n rowData: undefined\n }\n\n var rowData = { tags: {}, fields: {} }\n var hasFileds = false\n var rowStr = ''\n each(dataMap, function (value, key) {\n if (value.type === message.type) {\n rowStr += key + ','\n rowData.measurement = key\n var tagsStr = []\n var tags = extend({}, commonTags, value.tags)\n var filterFileds = ['date', 'type', CUSTOM_KEYS]\n each(tags, function (value_path, _key) {\n var _value = findByPath(message, value_path)\n filterFileds.push(_key)\n if (_value || isNumber(_value)) {\n rowData.tags[_key] = escapeJsonValue(_value, true)\n tagsStr.push(escapeRowData(_key) + '=' + escapeRowData(_value))\n }\n })\n\n var fieldsStr = []\n var fields = extend({}, commonFields, value.fields)\n each(fields, function (_value, _key) {\n if (isArray(_value) && _value.length === 2) {\n var value_path = _value[1]\n var _valueData = findByPath(message, value_path)\n filterFileds.push(_key)\n if (_valueData !== undefined && _valueData !== null) {\n rowData.fields[_key] = escapeJsonValue(_valueData)\n fieldsStr.push(\n escapeRowData(_key) + '=' + escapeRowField(_valueData)\n )\n }\n } else if (isString(_value)) {\n var _valueData = findByPath(message, _value)\n filterFileds.push(_key)\n if (_valueData !== undefined && _valueData !== null) {\n rowData.fields[_key] = escapeJsonValue(_valueData)\n fieldsStr.push(\n escapeRowData(_key) + '=' + escapeRowField(_valueData)\n )\n }\n }\n })\n if (\n message.context &&\n isObject(message.context) &&\n !isEmptyObject(message.context)\n ) {\n var _tagKeys = []\n each(message.context, function (_value, _key) {\n if (filterFileds.indexOf(_key) > -1) return\n filterFileds.push(_key)\n if (_value !== undefined && _value !== null) {\n _tagKeys.push(_key)\n rowData.fields[_key] = escapeJsonValue(_value)\n fieldsStr.push(escapeRowData(_key) + '=' + escapeRowField(_value))\n }\n })\n if (_tagKeys.length) {\n rowData.fields[CUSTOM_KEYS] = escapeJsonValue(_tagKeys)\n fieldsStr.push(\n escapeRowData(CUSTOM_KEYS) + '=' + escapeRowField(_tagKeys)\n )\n }\n }\n if (message.type === RumEventType.LOGGER) {\n each(message, function (value, key) {\n if (\n filterFileds.indexOf(key) === -1 &&\n value !== undefined &&\n value !== null\n ) {\n rowData.fields[key] = escapeJsonValue(value)\n fieldsStr.push(escapeRowData(key) + '=' + escapeRowField(value))\n }\n })\n }\n if (tagsStr.length) {\n rowStr += tagsStr.join(',')\n }\n if (fieldsStr.length) {\n rowStr += ' '\n rowStr += fieldsStr.join(',')\n hasFileds = true\n }\n rowStr = rowStr + ' ' + message.date\n rowData.time = message.date\n }\n })\n return {\n rowStr: hasFileds ? rowStr : '',\n rowData: hasFileds ? rowData : undefined\n }\n}\n\nexport function createBatch(options) {\n var encoder = options.encoder\n var request = options.request\n var messageBytesLimit = options.messageBytesLimit\n var sendContentTypeByJson = options.sendContentTypeByJson\n var flushController = options.flushController\n var upsertBuffer = {}\n var flushSubscription = flushController.flushObservable.subscribe(function (\n event\n ) {\n flush(event)\n })\n function getMessageText(messages, isEmpty = false) {\n if (sendContentTypeByJson) {\n if (isEmpty) {\n return '[' + messages.join(',')\n } else {\n return ',' + messages.join(',')\n }\n } else {\n if (isEmpty) {\n return messages.join('\\n')\n } else {\n return '\\n' + messages.join('\\n')\n }\n }\n }\n function push(serializedMessage, estimatedMessageBytesCount, key) {\n flushController.notifyBeforeAddMessage(estimatedMessageBytesCount)\n\n if (key !== undefined) {\n upsertBuffer[key] = serializedMessage\n flushController.notifyAfterAddMessage()\n } else {\n encoder.write(\n getMessageText([serializedMessage], encoder.isEmpty()),\n function (realMessageBytesCount) {\n flushController.notifyAfterAddMessage(\n realMessageBytesCount - estimatedMessageBytesCount\n )\n }\n )\n }\n }\n\n function hasMessageFor(key) {\n return key !== undefined && upsertBuffer[key] !== undefined\n }\n\n function remove(key) {\n var removedMessage = upsertBuffer[key]\n delete upsertBuffer[key]\n var messageBytesCount = encoder.estimateEncodedBytesCount(removedMessage)\n flushController.notifyAfterRemoveMessage(messageBytesCount)\n }\n function process(message) {\n var processedMessage = ''\n if (sendContentTypeByJson) {\n processedMessage = jsonStringify(\n processedMessageByDataMap(message).rowData\n )\n } else {\n processedMessage = processedMessageByDataMap(message).rowStr\n }\n return processedMessage\n }\n function addOrUpdate(message, key) {\n const serializedMessage = process(message)\n\n const estimatedMessageBytesCount =\n encoder.estimateEncodedBytesCount(serializedMessage)\n\n if (estimatedMessageBytesCount >= messageBytesLimit) {\n display.warn(\n `Discarded a message whose size was bigger than the maximum allowed size ${messageBytesLimit}KB.`\n )\n return\n }\n\n if (hasMessageFor(key)) {\n remove(key)\n }\n\n push(serializedMessage, estimatedMessageBytesCount, key)\n }\n\n function flush(event) {\n var upsertMessages = values(upsertBuffer).join(\n sendContentTypeByJson ? ',' : '\\n'\n )\n upsertBuffer = {}\n\n var isPageExit = isPageExitReason(event.reason)\n var send = isPageExit ? request.sendOnExit : request.send\n\n if (\n isPageExit &&\n // Note: checking that the encoder is async is not strictly needed, but it's an optimization:\n // if the encoder is async we need to send two requests in some cases (one for encoded data\n // and the other for non-encoded data). But if it's not async, we don't have to worry about\n // it and always send a single request.\n encoder.isAsync\n ) {\n var encoderResult = encoder.finishSync()\n\n // Send encoded messages\n if (encoderResult.outputBytesCount) {\n send(formatPayloadFromEncoder(encoderResult, sendContentTypeByJson))\n }\n\n // Send messages that are not yet encoded at this point\n var pendingMessages = [encoderResult.pendingData, upsertMessages]\n .filter(Boolean)\n .join('\\n')\n\n if (pendingMessages) {\n send({\n data: pendingMessages,\n bytesCount: computeBytesCount(pendingMessages)\n })\n }\n } else {\n if (upsertMessages) {\n var text = getMessageText([upsertMessages], encoder.isEmpty())\n if (sendContentTypeByJson) {\n text += ']'\n }\n encoder.write(text)\n } else {\n if (sendContentTypeByJson) {\n encoder.write(']')\n }\n }\n encoder.finish(function (encoderResult) {\n send(formatPayloadFromEncoder(encoderResult))\n })\n }\n }\n\n return {\n flushController: flushController,\n add: addOrUpdate,\n upsert: addOrUpdate,\n stop: flushSubscription.unsubscribe\n }\n}\n\nfunction formatPayloadFromEncoder(encoderResult, sendContentTypeByJson) {\n var data\n if (typeof encoderResult.output === 'string') {\n data = encoderResult.output\n } else {\n data = new Blob([encoderResult.output], {\n // This will set the 'Content-Type: text/plain' header. Reasoning:\n // * The intake rejects the request if there is no content type.\n // * The browser will issue CORS preflight requests if we set it to 'application/json', which\n // could induce higher intake load (and maybe has other impacts).\n // * Also it's not quite JSON, since we are concatenating multiple JSON objects separated by\n // new lines.\n type: 'text/plain'\n })\n }\n\n return {\n data: data,\n type: sendContentTypeByJson ? 'application/json;UTF-8' : undefined,\n bytesCount: encoderResult.outputBytesCount,\n encoding: encoderResult.encoding\n }\n}\n"],"mappings":"AAAA,SAASA,OAAO,QAAQ,mBAAmB;AAC3C,SACEC,MAAM,EACNC,UAAU,EACVC,IAAI,EACJC,QAAQ,EACRC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AAC;MAC/C,CAAC,CAAC;IACJ;EACF;EAEA,OAAO;IACLlC,eAAe,EAAEA,eAAe;IAChC8C,GAAG,EAAErB,WAAW;IAChBsB,MAAM,EAAEtB,WAAW;IACnBuB,IAAI,EAAE9C,iBAAiB,CAAC+C;EAC1B,CAAC;AACH;AAEA,SAASZ,wBAAwBA,CAACH,aAAa,EAAEnC,qBAAqB,EAAE;EACtE,IAAI2C,IAAI;EACR,IAAI,OAAOR,aAAa,CAACgB,MAAM,KAAK,QAAQ,EAAE;IAC5CR,IAAI,GAAGR,aAAa,CAACgB,MAAM;EAC7B,CAAC,MAAM;IACLR,IAAI,GAAG,IAAIS,IAAI,CAAC,CAACjB,aAAa,CAACgB,MAAM,CAAC,EAAE;MACtC;MACA;MACA;MACA;MACA;MACA;MACAlF,IAAI,EAAE;IACR,CAAC,CAAC;EACJ;EAEA,OAAO;IACL0E,IAAI,EAAEA,IAAI;IACV1E,IAAI,EAAE+B,qBAAqB,GAAG,wBAAwB,GAAG5B,SAAS;IAClEwE,UAAU,EAAET,aAAa,CAACE,gBAAgB;IAC1CgB,QAAQ,EAAElB,aAAa,CAACkB;EAC1B,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"batch.js","names":["display","values","findByPath","each","isNumber","isArray","extend","isString","isEmptyObject","isObject","escapeJsonValue","escapeRowField","escapeRowData","commonTags","dataMap","commonFields","RumEventType","computeBytesCount","isPageExitReason","jsonStringify","CUSTOM_KEYS","processedMessageByDataMap","message","type","rowStr","rowData","undefined","tags","fields","hasFileds","value","key","measurement","tagsStr","filterFileds","value_path","_key","_value","push","fieldsStr","length","_valueData","context","_tagKeys","indexOf","LOGGER","join","date","time","createBatch","options","encoder","request","messageBytesLimit","sendContentTypeByJson","flushController","upsertBuffer","flushSubscription","flushObservable","subscribe","event","flush","getMessageText","messages","isEmpty","arguments","serializedMessage","estimatedMessageBytesCount","notifyBeforeAddMessage","notifyAfterAddMessage","write","realMessageBytesCount","hasMessageFor","remove","removedMessage","messageBytesCount","estimateEncodedBytesCount","notifyAfterRemoveMessage","process","processedMessage","addOrUpdate","warn","concat","upsertMessages","isPageExit","reason","send","sendOnExit","isAsync","encoderResult","finishSync","outputBytesCount","formatPayloadFromEncoder","pendingMessages","_toConsumableArray","pendingData","filter","Boolean","data","bytesCount","text","finish","add","upsert","stop","unsubscribe","output","Blob","encoding"],"sources":["../../src/transport/batch.js"],"sourcesContent":["import { display } from '../helper/display'\nimport {\n values,\n findByPath,\n each,\n isNumber,\n isArray,\n extend,\n isString,\n isEmptyObject,\n isObject\n} from '../helper/tools'\nimport {\n escapeJsonValue,\n escapeRowField,\n escapeRowData\n} from '../helper/serialisation/rowData'\nimport { commonTags, dataMap, commonFields } from '../dataMap'\nimport { RumEventType } from '../helper/enums'\nimport { computeBytesCount } from '../helper/byteUtils'\nimport { isPageExitReason } from '../browser/pageExitObservable'\nimport { jsonStringify } from '../helper/serialisation/jsonStringify'\n// https://en.wikipedia.org/wiki/UTF-8\n// eslint-disable-next-line no-control-regex\nvar CUSTOM_KEYS = 'custom_keys'\nexport var processedMessageByDataMap = function (message) {\n if (!message || !message.type)\n return {\n rowStr: '',\n rowData: undefined\n }\n\n var rowData = { tags: {}, fields: {} }\n var hasFileds = false\n var rowStr = ''\n each(dataMap, function (value, key) {\n if (value.type === message.type) {\n rowStr += key + ','\n rowData.measurement = key\n var tagsStr = []\n var tags = extend({}, commonTags, value.tags)\n var filterFileds = ['date', 'type', CUSTOM_KEYS]\n each(tags, function (value_path, _key) {\n var _value = findByPath(message, value_path)\n filterFileds.push(_key)\n if (_value || isNumber(_value)) {\n rowData.tags[_key] = escapeJsonValue(_value, true)\n tagsStr.push(escapeRowData(_key) + '=' + escapeRowData(_value))\n }\n })\n\n var fieldsStr = []\n var fields = extend({}, commonFields, value.fields)\n each(fields, function (_value, _key) {\n if (isArray(_value) && _value.length === 2) {\n var value_path = _value[1]\n var _valueData = findByPath(message, value_path)\n filterFileds.push(_key)\n if (_valueData !== undefined && _valueData !== null) {\n rowData.fields[_key] = escapeJsonValue(_valueData)\n fieldsStr.push(\n escapeRowData(_key) + '=' + escapeRowField(_valueData)\n )\n }\n } else if (isString(_value)) {\n var _valueData = findByPath(message, _value)\n filterFileds.push(_key)\n if (_valueData !== undefined && _valueData !== null) {\n rowData.fields[_key] = escapeJsonValue(_valueData)\n fieldsStr.push(\n escapeRowData(_key) + '=' + escapeRowField(_valueData)\n )\n }\n }\n })\n if (\n message.context &&\n isObject(message.context) &&\n !isEmptyObject(message.context)\n ) {\n var _tagKeys = []\n each(message.context, function (_value, _key) {\n if (filterFileds.indexOf(_key) > -1) return\n filterFileds.push(_key)\n if (_value !== undefined && _value !== null) {\n _tagKeys.push(_key)\n rowData.fields[_key] = escapeJsonValue(_value)\n fieldsStr.push(escapeRowData(_key) + '=' + escapeRowField(_value))\n }\n })\n if (_tagKeys.length) {\n rowData.fields[CUSTOM_KEYS] = escapeJsonValue(_tagKeys)\n fieldsStr.push(\n escapeRowData(CUSTOM_KEYS) + '=' + escapeRowField(_tagKeys)\n )\n }\n }\n if (message.type === RumEventType.LOGGER) {\n each(message, function (value, key) {\n if (\n filterFileds.indexOf(key) === -1 &&\n value !== undefined &&\n value !== null\n ) {\n rowData.fields[key] = escapeJsonValue(value)\n fieldsStr.push(escapeRowData(key) + '=' + escapeRowField(value))\n }\n })\n }\n if (tagsStr.length) {\n rowStr += tagsStr.join(',')\n }\n if (fieldsStr.length) {\n rowStr += ' '\n rowStr += fieldsStr.join(',')\n hasFileds = true\n }\n rowStr = rowStr + ' ' + message.date\n rowData.time = message.date\n }\n })\n return {\n rowStr: hasFileds ? rowStr : '',\n rowData: hasFileds ? rowData : undefined\n }\n}\n\nexport function createBatch(options) {\n var encoder = options.encoder\n var request = options.request\n var messageBytesLimit = options.messageBytesLimit\n var sendContentTypeByJson = options.sendContentTypeByJson\n var flushController = options.flushController\n var upsertBuffer = {}\n var flushSubscription = flushController.flushObservable.subscribe(function (\n event\n ) {\n flush(event)\n })\n function getMessageText(messages, isEmpty = false) {\n if (sendContentTypeByJson) {\n if (isEmpty) {\n return '[' + messages.join(',')\n } else {\n return ',' + messages.join(',')\n }\n } else {\n if (isEmpty) {\n return messages.join('\\n')\n } else {\n return '\\n' + messages.join('\\n')\n }\n }\n }\n function push(serializedMessage, estimatedMessageBytesCount, key) {\n flushController.notifyBeforeAddMessage(estimatedMessageBytesCount)\n\n if (key !== undefined) {\n upsertBuffer[key] = serializedMessage\n flushController.notifyAfterAddMessage()\n } else {\n encoder.write(\n getMessageText([serializedMessage], encoder.isEmpty()),\n function (realMessageBytesCount) {\n flushController.notifyAfterAddMessage(\n realMessageBytesCount - estimatedMessageBytesCount\n )\n }\n )\n }\n }\n\n function hasMessageFor(key) {\n return key !== undefined && upsertBuffer[key] !== undefined\n }\n\n function remove(key) {\n var removedMessage = upsertBuffer[key]\n delete upsertBuffer[key]\n var messageBytesCount = encoder.estimateEncodedBytesCount(removedMessage)\n flushController.notifyAfterRemoveMessage(messageBytesCount)\n }\n function process(message) {\n var processedMessage = ''\n if (sendContentTypeByJson) {\n processedMessage = jsonStringify(\n processedMessageByDataMap(message).rowData\n )\n } else {\n processedMessage = processedMessageByDataMap(message).rowStr\n }\n return processedMessage\n }\n function addOrUpdate(message, key) {\n const serializedMessage = process(message)\n\n const estimatedMessageBytesCount =\n encoder.estimateEncodedBytesCount(serializedMessage)\n\n if (estimatedMessageBytesCount >= messageBytesLimit) {\n display.warn(\n `Discarded a message whose size was bigger than the maximum allowed size ${messageBytesLimit}KB.`\n )\n return\n }\n\n if (hasMessageFor(key)) {\n remove(key)\n }\n\n push(serializedMessage, estimatedMessageBytesCount, key)\n }\n\n function flush(event) {\n var upsertMessages = values(upsertBuffer).join(\n sendContentTypeByJson ? ',' : '\\n'\n )\n upsertBuffer = {}\n\n var isPageExit = isPageExitReason(event.reason)\n var send = isPageExit ? request.sendOnExit : request.send\n\n if (\n isPageExit &&\n // Note: checking that the encoder is async is not strictly needed, but it's an optimization:\n // if the encoder is async we need to send two requests in some cases (one for encoded data\n // and the other for non-encoded data). But if it's not async, we don't have to worry about\n // it and always send a single request.\n encoder.isAsync\n ) {\n var encoderResult = encoder.finishSync()\n\n // Send encoded messages\n if (encoderResult.outputBytesCount) {\n send(formatPayloadFromEncoder(encoderResult, sendContentTypeByJson))\n }\n // Send messages that are not yet encoded at this point\n var pendingMessages = [...encoderResult.pendingData, upsertMessages]\n .filter(Boolean)\n .join('\\n')\n\n if (pendingMessages) {\n send({\n data: pendingMessages,\n bytesCount: computeBytesCount(pendingMessages)\n })\n }\n } else {\n if (upsertMessages) {\n var text = getMessageText([upsertMessages], encoder.isEmpty())\n if (sendContentTypeByJson) {\n text += ']'\n }\n encoder.write(text)\n } else {\n if (sendContentTypeByJson) {\n encoder.write(']')\n }\n }\n encoder.finish(function (encoderResult) {\n send(formatPayloadFromEncoder(encoderResult))\n })\n }\n }\n\n return {\n flushController: flushController,\n add: addOrUpdate,\n upsert: addOrUpdate,\n stop: flushSubscription.unsubscribe\n }\n}\n\nfunction formatPayloadFromEncoder(encoderResult, sendContentTypeByJson) {\n var data\n if (typeof encoderResult.output === 'string') {\n data = encoderResult.output\n } else {\n data = new Blob([encoderResult.output], {\n // This will set the 'Content-Type: text/plain' header. Reasoning:\n // * The intake rejects the request if there is no content type.\n // * The browser will issue CORS preflight requests if we set it to 'application/json', which\n // could induce higher intake load (and maybe has other impacts).\n // * Also it's not quite JSON, since we are concatenating multiple JSON objects separated by\n // new lines.\n type: 'text/plain'\n })\n }\n\n return {\n data: data,\n type: sendContentTypeByJson ? 'application/json;UTF-8' : undefined,\n bytesCount: encoderResult.outputBytesCount,\n encoding: encoderResult.encoding\n }\n}\n"],"mappings":";;;;;;AAAA,SAASA,OAAO,QAAQ,mBAAmB;AAC3C,SACEC,MAAM,EACNC,UAAU,EACVC,IAAI,EACJC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,QAAQ,EACRC,aAAa,EACbC,QAAQ,QACH,iBAAiB;AACxB,SACEC,eAAe,EAC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;IAChC+C,GAAG,EAAEtB,WAAW;IAChBuB,MAAM,EAAEvB,WAAW;IACnBwB,IAAI,EAAE/C,iBAAiB,CAACgD;EAC1B,CAAC;AACH;AAEA,SAASb,wBAAwBA,CAACH,aAAa,EAAEnC,qBAAqB,EAAE;EACtE,IAAI4C,IAAI;EACR,IAAI,OAAOT,aAAa,CAACiB,MAAM,KAAK,QAAQ,EAAE;IAC5CR,IAAI,GAAGT,aAAa,CAACiB,MAAM;EAC7B,CAAC,MAAM;IACLR,IAAI,GAAG,IAAIS,IAAI,CAAC,CAAClB,aAAa,CAACiB,MAAM,CAAC,EAAE;MACtC;MACA;MACA;MACA;MACA;MACA;MACAnF,IAAI,EAAE;IACR,CAAC,CAAC;EACJ;EAEA,OAAO;IACL2E,IAAI,EAAEA,IAAI;IACV3E,IAAI,EAAE+B,qBAAqB,GAAG,wBAAwB,GAAG5B,SAAS;IAClEyE,UAAU,EAAEV,aAAa,CAACE,gBAAgB;IAC1CiB,QAAQ,EAAEnB,aAAa,CAACmB;EAC1B,CAAC;AACH","ignoreList":[]}
@@ -83,11 +83,13 @@ export function fetchKeepAliveStrategy(endpointUrl, bytesLimit, payload, onRespo
83
83
  keepalive: true,
84
84
  mode: 'cors'
85
85
  };
86
+ var headers = {
87
+ 'x-client-timestamp': Date.now().toString()
88
+ };
86
89
  if (payload.type) {
87
- fetchOption.headers = {
88
- 'Content-Type': payload.type
89
- };
90
+ headers['Content-Type'] = payload.type;
90
91
  }
92
+ fetchOption.headers = headers;
91
93
  fetch(url, fetchOption).then(monitor(function (response) {
92
94
  if (typeof onResponse === 'function') {
93
95
  onResponse({
@@ -95,9 +97,8 @@ export function fetchKeepAliveStrategy(endpointUrl, bytesLimit, payload, onRespo
95
97
  type: response.type
96
98
  });
97
99
  }
98
- }), monitor(function () {
99
- // failed to queue the request
100
- sendXHR(url, payload, onResponse);
100
+ }))["catch"](monitor(function () {
101
+ fetchStrategy(url, payload, onResponse);
101
102
  }));
102
103
  } else {
103
104
  sendXHR(url, payload, onResponse);
@@ -120,6 +121,7 @@ function sendXHR(url, payload, onResponse) {
120
121
  } else if (payload.type) {
121
122
  request.setRequestHeader('Content-Type', payload.type);
122
123
  }
124
+ request.setRequestHeader('x-client-timestamp', Date.now().toString());
123
125
  addEventListener(request, 'loadend', function () {
124
126
  if (typeof onResponse === 'function') {
125
127
  onResponse({
@@ -131,4 +133,33 @@ function sendXHR(url, payload, onResponse) {
131
133
  });
132
134
  request.send(data);
133
135
  }
136
+ function fetchStrategy(url, payload, onResponse) {
137
+ var fetchOption = {
138
+ method: 'POST',
139
+ body: payload.data,
140
+ keepalive: true,
141
+ mode: 'cors'
142
+ };
143
+ var headers = {
144
+ 'x-client-timestamp': Date.now().toString()
145
+ };
146
+ if (payload.type) {
147
+ headers['Content-Type'] = payload.type;
148
+ }
149
+ fetchOption.headers = headers;
150
+ fetch(url, fetchOption).then(monitor(function (response) {
151
+ if (typeof onResponse === 'function') {
152
+ onResponse({
153
+ status: response.status,
154
+ type: response.type
155
+ });
156
+ }
157
+ }))["catch"](monitor(function () {
158
+ if (typeof onResponse === 'function') {
159
+ onResponse({
160
+ status: 0
161
+ });
162
+ }
163
+ }));
164
+ }
134
165
  //# sourceMappingURL=httpRequest.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"httpRequest.js","names":["newRetryState","sendWithRetryStrategy","addEventListener","monitor","addTelemetryError","addBatchPrecision","url","encoding","indexOf","createHttpRequest","endpointUrl","bytesLimit","retryMaxSize","reportError","undefined","retryState","sendStrategyForRetry","payload","onResponse","fetchKeepAliveStrategy","send","sendOnExit","sendBeaconStrategy","data","bytesCount","canUseBeacon","navigator","sendBeacon","beaconData","type","Blob","isQueued","e","reportBeaconError","sendXHR","hasReportedBeaconError","canUseKeepAlive","isKeepAliveSupported","fetchOption","method","body","keepalive","mode","headers","fetch","then","response","status","window","Request","_unused","request","XMLHttpRequest","open","setRequestHeader","once"],"sources":["../../src/transport/httpRequest.js"],"sourcesContent":["import { newRetryState, sendWithRetryStrategy } from './sendWithRetryStrategy'\nimport { addEventListener } from '../browser/addEventListener'\nimport { monitor } from '../helper/monitor'\nimport { addTelemetryError } from '../telemetry/telemetry'\n/**\n * Use POST request without content type to:\n * - avoid CORS preflight requests\n * - allow usage of sendBeacon\n *\n * multiple elements are sent separated by \\n in order\n * to be parsed correctly without content type header\n */\nfunction addBatchPrecision(url, encoding) {\n if (!url) return url\n url = url + (url.indexOf('?') === -1 ? '?' : '&') + 'precision=ms'\n if (encoding) {\n url = url + '&encoding=' + encoding\n }\n return url\n}\nexport function createHttpRequest(\n endpointUrl,\n bytesLimit,\n retryMaxSize,\n reportError\n) {\n if (retryMaxSize === undefined) {\n retryMaxSize = -1\n }\n var retryState = newRetryState(retryMaxSize)\n var sendStrategyForRetry = function (payload, onResponse) {\n return fetchKeepAliveStrategy(endpointUrl, bytesLimit, payload, onResponse)\n }\n\n return {\n send: function (payload) {\n sendWithRetryStrategy(\n payload,\n retryState,\n sendStrategyForRetry,\n endpointUrl,\n reportError\n )\n },\n /**\n * Since fetch keepalive behaves like regular fetch on Firefox,\n * keep using sendBeaconStrategy on exit\n */\n sendOnExit: function (payload) {\n sendBeaconStrategy(endpointUrl, bytesLimit, payload)\n }\n }\n}\n\nfunction sendBeaconStrategy(endpointUrl, bytesLimit, payload) {\n var data = payload.data\n var bytesCount = payload.bytesCount\n var url = addBatchPrecision(endpointUrl, payload.encoding)\n var canUseBeacon = !!navigator.sendBeacon && bytesCount < bytesLimit\n if (canUseBeacon) {\n try {\n var beaconData\n if (payload.type) {\n beaconData = new Blob([data], {\n type: payload.type\n })\n } else {\n beaconData = data\n }\n\n var isQueued = navigator.sendBeacon(url, beaconData)\n\n if (isQueued) {\n return\n }\n } catch (e) {\n reportBeaconError(e)\n }\n }\n sendXHR(url, payload)\n}\nvar hasReportedBeaconError = false\n\nfunction reportBeaconError(e) {\n if (!hasReportedBeaconError) {\n hasReportedBeaconError = true\n addTelemetryError(e)\n }\n}\nexport function fetchKeepAliveStrategy(\n endpointUrl,\n bytesLimit,\n payload,\n onResponse\n) {\n var data = payload.data\n var bytesCount = payload.bytesCount\n var url = addBatchPrecision(endpointUrl, payload.encoding)\n var canUseKeepAlive = isKeepAliveSupported() && bytesCount < bytesLimit\n if (canUseKeepAlive) {\n var fetchOption = {\n method: 'POST',\n body: data,\n keepalive: true,\n mode: 'cors'\n }\n if (payload.type) {\n fetchOption.headers = {\n 'Content-Type': payload.type\n }\n }\n fetch(url, fetchOption).then(\n monitor(function (response) {\n if (typeof onResponse === 'function') {\n onResponse({ status: response.status, type: response.type })\n }\n }),\n monitor(function () {\n // failed to queue the request\n sendXHR(url, payload, onResponse)\n })\n )\n } else {\n sendXHR(url, payload, onResponse)\n }\n}\n\nfunction isKeepAliveSupported() {\n // Request can throw, cf https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#errors\n try {\n return window.Request && 'keepalive' in new Request('http://a')\n } catch {\n return false\n }\n}\n\nfunction sendXHR(url, payload, onResponse) {\n const data = payload.data\n const request = new XMLHttpRequest()\n request.open('POST', url, true)\n if (data instanceof Blob) {\n request.setRequestHeader('Content-Type', data.type)\n } else if (payload.type) {\n request.setRequestHeader('Content-Type', payload.type)\n }\n\n addEventListener(\n request,\n 'loadend',\n function () {\n if (typeof onResponse === 'function') {\n onResponse({ status: request.status })\n }\n },\n {\n once: true\n }\n )\n request.send(data)\n}\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,qBAAqB,QAAQ,yBAAyB;AAC9E,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,OAAO,QAAQ,mBAAmB;AAC3C,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,iBAAiBA,CAACC,GAAG,EAAEC,QAAQ,EAAE;EACxC,IAAI,CAACD,GAAG,EAAE,OAAOA,GAAG;EACpBA,GAAG,GAAGA,GAAG,IAAIA,GAAG,CAACE,OAAO,CAAC,GAAG,CAAC,KAAK,C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OjC,UAAU,KAAK,UAAU,EAAE;MACpCA,UAAU,CAAC;QAAE6B,MAAM,EAAEI,OAAO,CAACJ;MAAO,CAAC,CAAC;IACxC;EACF,CAAC,EACD;IACEQ,IAAI,EAAE;EACR,CACF,CAAC;EACDJ,OAAO,CAAC/B,IAAI,CAACG,IAAI,CAAC;AACpB","ignoreList":[]}
1
+ {"version":3,"file":"httpRequest.js","names":["newRetryState","sendWithRetryStrategy","addEventListener","monitor","addTelemetryError","addBatchPrecision","url","encoding","indexOf","createHttpRequest","endpointUrl","bytesLimit","retryMaxSize","reportError","undefined","retryState","sendStrategyForRetry","payload","onResponse","fetchKeepAliveStrategy","send","sendOnExit","sendBeaconStrategy","data","bytesCount","canUseBeacon","navigator","sendBeacon","beaconData","type","Blob","isQueued","e","reportBeaconError","sendXHR","hasReportedBeaconError","canUseKeepAlive","isKeepAliveSupported","fetchOption","method","body","keepalive","mode","headers","Date","now","toString","fetch","then","response","status","fetchStrategy","window","Request","_unused","request","XMLHttpRequest","open","setRequestHeader","once"],"sources":["../../src/transport/httpRequest.js"],"sourcesContent":["import { newRetryState, sendWithRetryStrategy } from './sendWithRetryStrategy'\nimport { addEventListener } from '../browser/addEventListener'\nimport { monitor } from '../helper/monitor'\nimport { addTelemetryError } from '../telemetry/telemetry'\n/**\n * Use POST request without content type to:\n * - avoid CORS preflight requests\n * - allow usage of sendBeacon\n *\n * multiple elements are sent separated by \\n in order\n * to be parsed correctly without content type header\n */\nfunction addBatchPrecision(url, encoding) {\n if (!url) return url\n url = url + (url.indexOf('?') === -1 ? '?' : '&') + 'precision=ms'\n if (encoding) {\n url = url + '&encoding=' + encoding\n }\n return url\n}\nexport function createHttpRequest(\n endpointUrl,\n bytesLimit,\n retryMaxSize,\n reportError\n) {\n if (retryMaxSize === undefined) {\n retryMaxSize = -1\n }\n var retryState = newRetryState(retryMaxSize)\n var sendStrategyForRetry = function (payload, onResponse) {\n return fetchKeepAliveStrategy(endpointUrl, bytesLimit, payload, onResponse)\n }\n\n return {\n send: function (payload) {\n sendWithRetryStrategy(\n payload,\n retryState,\n sendStrategyForRetry,\n endpointUrl,\n reportError\n )\n },\n /**\n * Since fetch keepalive behaves like regular fetch on Firefox,\n * keep using sendBeaconStrategy on exit\n */\n sendOnExit: function (payload) {\n sendBeaconStrategy(endpointUrl, bytesLimit, payload)\n }\n }\n}\n\nfunction sendBeaconStrategy(endpointUrl, bytesLimit, payload) {\n var data = payload.data\n var bytesCount = payload.bytesCount\n var url = addBatchPrecision(endpointUrl, payload.encoding)\n var canUseBeacon = !!navigator.sendBeacon && bytesCount < bytesLimit\n if (canUseBeacon) {\n try {\n var beaconData\n if (payload.type) {\n beaconData = new Blob([data], {\n type: payload.type\n })\n } else {\n beaconData = data\n }\n\n var isQueued = navigator.sendBeacon(url, beaconData)\n\n if (isQueued) {\n return\n }\n } catch (e) {\n reportBeaconError(e)\n }\n }\n sendXHR(url, payload)\n}\nvar hasReportedBeaconError = false\n\nfunction reportBeaconError(e) {\n if (!hasReportedBeaconError) {\n hasReportedBeaconError = true\n addTelemetryError(e)\n }\n}\nexport function fetchKeepAliveStrategy(\n endpointUrl,\n bytesLimit,\n payload,\n onResponse\n) {\n var data = payload.data\n var bytesCount = payload.bytesCount\n var url = addBatchPrecision(endpointUrl, payload.encoding)\n var canUseKeepAlive = isKeepAliveSupported() && bytesCount < bytesLimit\n if (canUseKeepAlive) {\n var fetchOption = {\n method: 'POST',\n body: data,\n keepalive: true,\n mode: 'cors'\n }\n const headers = {\n 'x-client-timestamp': Date.now().toString()\n }\n\n if (payload.type) {\n headers['Content-Type'] = payload.type\n }\n\n fetchOption.headers = headers\n fetch(url, fetchOption)\n .then(\n monitor(function (response) {\n if (typeof onResponse === 'function') {\n onResponse({ status: response.status, type: response.type })\n }\n })\n )\n .catch(\n monitor(function () {\n fetchStrategy(url, payload, onResponse)\n })\n )\n } else {\n sendXHR(url, payload, onResponse)\n }\n}\n\nfunction isKeepAliveSupported() {\n // Request can throw, cf https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#errors\n try {\n return window.Request && 'keepalive' in new Request('http://a')\n } catch {\n return false\n }\n}\n\nfunction sendXHR(url, payload, onResponse) {\n const data = payload.data\n const request = new XMLHttpRequest()\n request.open('POST', url, true)\n if (data instanceof Blob) {\n request.setRequestHeader('Content-Type', data.type)\n } else if (payload.type) {\n request.setRequestHeader('Content-Type', payload.type)\n }\n request.setRequestHeader('x-client-timestamp', Date.now().toString())\n addEventListener(\n request,\n 'loadend',\n function () {\n if (typeof onResponse === 'function') {\n onResponse({ status: request.status })\n }\n },\n {\n once: true\n }\n )\n request.send(data)\n}\nfunction fetchStrategy(url, payload, onResponse) {\n const fetchOption = {\n method: 'POST',\n body: payload.data,\n keepalive: true,\n mode: 'cors'\n }\n const headers = {\n 'x-client-timestamp': Date.now().toString()\n }\n if (payload.type) {\n headers['Content-Type'] = payload.type\n }\n fetchOption.headers = headers\n\n fetch(url, fetchOption)\n .then(\n monitor(function (response) {\n if (typeof onResponse === 'function') {\n onResponse({ status: response.status, type: response.type })\n }\n })\n )\n .catch(\n monitor(function () {\n if (typeof onResponse === 'function') {\n onResponse({ status: 0 })\n }\n })\n )\n}\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,qBAAqB,QAAQ,yBAAyB;AAC9E,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,OAAO,QAAQ,mBAAmB;AAC3C,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,iBAAiBA,CAACC,GAAG,EAAEC,QAAQ,EAAE;EACxC,IAAI,CAACD,GAAG,EAAE,OAAOA,GAAG;EACpBA,GAAG,GAAGA,GAAG,IAAIA,GAAG,CAACE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,cAAc;EAClE,IAAID,QAAQ,EAAE;IACZD,GAAG,GAAGA,GAAG,GAAG,YAAY,GAAGC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,CAAC;AACL","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudcare/browser-core",
3
- "version": "3.2.28",
3
+ "version": "3.2.30",
4
4
  "main": "cjs/index.js",
5
5
  "module": "esm/index.js",
6
6
  "types": "types/index.d.ts",
@@ -21,5 +21,5 @@
21
21
  },
22
22
  "author": "dataflux",
23
23
  "license": "MIT",
24
- "gitHead": "1d42bf528926c2c13947c3298a1d18ea2a4e91f6"
24
+ "gitHead": "64d182d1a5d825ee8eb708fa6cd5eb15ac0a5f52"
25
25
  }
package/src/dataMap.js CHANGED
@@ -58,6 +58,7 @@ export var dataMap = {
58
58
  view_privacy_replay_level: 'privacy.replay_level'
59
59
  },
60
60
  fields: {
61
+ view_update_time: '_gc.view_update_time',
61
62
  sampled_for_replay: 'session.sampled_for_replay',
62
63
  sampled_for_error_replay: 'session.sampled_for_error_replay',
63
64
  sampled_for_error_session: 'session.sampled_for_error_session',
@@ -29,7 +29,7 @@ export function createIdentityEncoder() {
29
29
  output: output,
30
30
  outputBytesCount: outputBytesCount,
31
31
  rawBytesCount: outputBytesCount,
32
- pendingData: ''
32
+ pendingData: []
33
33
  }
34
34
  output = ''
35
35
  outputBytesCount = 0
package/src/index.js CHANGED
@@ -45,7 +45,8 @@ export {
45
45
  } from './session/sessionManagement'
46
46
  export {
47
47
  SESSION_TIME_OUT_DELAY,
48
- SESSION_STORE_KEY
48
+ SESSION_STORE_KEY,
49
+ SessionPersistence
49
50
  } from './session/sessionConstants'
50
51
  export { STORAGE_POLL_DELAY } from './session/sessionStore'
51
52
  export * from './transport'
@@ -2,3 +2,7 @@ import { ONE_HOUR, ONE_MINUTE } from '../helper/tools'
2
2
  export var SESSION_TIME_OUT_DELAY = 4 * ONE_HOUR
3
3
  export var SESSION_EXPIRATION_DELAY = 15 * ONE_MINUTE
4
4
  export var SESSION_STORE_KEY = '_gc_s'
5
+ export const SessionPersistence = {
6
+ COOKIE: 'cookie',
7
+ LOCAL_STORAGE: 'local-storage'
8
+ }
@@ -8,7 +8,8 @@ import {
8
8
  import {
9
9
  SESSION_EXPIRATION_DELAY,
10
10
  SESSION_TIME_OUT_DELAY,
11
- SESSION_STORE_KEY
11
+ SESSION_STORE_KEY,
12
+ SessionPersistence
12
13
  } from './sessionConstants'
13
14
  import {
14
15
  toSessionString,
@@ -19,7 +20,7 @@ import {
19
20
  export function selectCookieStrategy(initConfiguration) {
20
21
  const cookieOptions = buildCookieOptions(initConfiguration)
21
22
  return areCookiesAuthorized(cookieOptions)
22
- ? { type: 'Cookie', cookieOptions }
23
+ ? { type: SessionPersistence.COOKIE, cookieOptions }
23
24
  : undefined
24
25
  }
25
26
 
@@ -5,7 +5,7 @@ import {
5
5
  getExpiredSessionState
6
6
  } from './sessionState'
7
7
 
8
- import { SESSION_STORE_KEY } from './sessionConstants'
8
+ import { SESSION_STORE_KEY, SessionPersistence } from './sessionConstants'
9
9
 
10
10
  const LOCAL_STORAGE_TEST_KEY = '_gc_test_'
11
11
 
@@ -16,7 +16,9 @@ export function selectLocalStorageStrategy() {
16
16
  localStorage.setItem(testKey, id)
17
17
  const retrievedId = localStorage.getItem(testKey)
18
18
  localStorage.removeItem(testKey)
19
- return id === retrievedId ? { type: 'LocalStorage' } : undefined
19
+ return id === retrievedId
20
+ ? { type: SessionPersistence.LOCAL_STORAGE }
21
+ : undefined
20
22
  } catch (e) {
21
23
  return undefined
22
24
  }