@cloudcare/browser-core 1.1.3 → 1.2.1

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 (134) hide show
  1. package/cjs/{cookie.js → browser/cookie.js} +6 -37
  2. package/cjs/browser/fetchObservable.js +91 -0
  3. package/cjs/browser/xhrObservable.js +118 -0
  4. package/cjs/configuration/configuration.js +70 -0
  5. package/cjs/configuration/transportConfiguration.js +64 -0
  6. package/cjs/console/consoleObservable.js +84 -0
  7. package/cjs/dataMap.js +26 -21
  8. package/cjs/error/trackRuntimeError.js +27 -0
  9. package/cjs/helper/catchUserErrors.js +20 -0
  10. package/cjs/helper/contextHistory.js +134 -0
  11. package/cjs/helper/createEventRateLimiter.js +47 -0
  12. package/cjs/helper/deviceInfo.js +8 -25
  13. package/cjs/helper/display.js +31 -0
  14. package/cjs/helper/enums.js +28 -2
  15. package/cjs/helper/errorTools.js +63 -2
  16. package/cjs/helper/instrumentMethod.js +93 -0
  17. package/cjs/helper/lifeCycle.js +5 -3
  18. package/cjs/helper/observable.js +40 -2
  19. package/cjs/helper/tools.js +185 -9
  20. package/cjs/index.js +153 -23
  21. package/cjs/init.js +17 -27
  22. package/cjs/report/reportObservable.js +112 -0
  23. package/cjs/session/sessionConstants.js +13 -0
  24. package/cjs/session/sessionCookieStore.js +188 -0
  25. package/cjs/session/sessionManagement.js +96 -0
  26. package/cjs/session/sessionStore.js +150 -0
  27. package/cjs/synthetics/syntheticsWorkerValues.js +32 -0
  28. package/cjs/synthetics/usr.js +32 -0
  29. package/cjs/tracekit/computeStackTrace.js +73 -563
  30. package/cjs/tracekit/index.js +3 -15
  31. package/cjs/tracekit/tracekit.js +113 -0
  32. package/cjs/transport/batch.js +332 -0
  33. package/cjs/transport/httpRequest.js +112 -0
  34. package/cjs/transport/index.js +29 -0
  35. package/cjs/transport/sendWithRetryStrategy.js +177 -0
  36. package/cjs/transport/startBatchWithReplica.js +24 -0
  37. package/esm/{cookie.js → browser/cookie.js} +4 -35
  38. package/esm/browser/fetchObservable.js +77 -0
  39. package/esm/browser/xhrObservable.js +106 -0
  40. package/esm/configuration/configuration.js +55 -0
  41. package/esm/configuration/transportConfiguration.js +54 -0
  42. package/esm/console/consoleObservable.js +70 -0
  43. package/esm/dataMap.js +26 -21
  44. package/esm/error/trackRuntimeError.js +16 -0
  45. package/esm/helper/catchUserErrors.js +12 -0
  46. package/esm/helper/contextHistory.js +106 -0
  47. package/esm/helper/createEventRateLimiter.js +38 -0
  48. package/esm/helper/deviceInfo.js +6 -25
  49. package/esm/helper/display.js +21 -0
  50. package/esm/helper/enums.js +25 -1
  51. package/esm/helper/errorTools.js +58 -3
  52. package/esm/helper/instrumentMethod.js +81 -0
  53. package/esm/helper/lifeCycle.js +5 -3
  54. package/esm/helper/observable.js +39 -3
  55. package/esm/helper/tools.js +147 -1
  56. package/esm/index.js +17 -7
  57. package/esm/init.js +17 -22
  58. package/esm/report/reportObservable.js +98 -0
  59. package/esm/session/sessionConstants.js +3 -0
  60. package/esm/session/sessionCookieStore.js +168 -0
  61. package/esm/session/sessionManagement.js +78 -0
  62. package/esm/session/sessionStore.js +139 -0
  63. package/esm/synthetics/syntheticsWorkerValues.js +15 -0
  64. package/esm/synthetics/usr.js +18 -0
  65. package/esm/tracekit/computeStackTrace.js +73 -557
  66. package/esm/tracekit/index.js +1 -1
  67. package/esm/tracekit/tracekit.js +103 -0
  68. package/esm/transport/batch.js +316 -0
  69. package/esm/transport/httpRequest.js +104 -0
  70. package/esm/transport/index.js +3 -0
  71. package/esm/transport/sendWithRetryStrategy.js +165 -0
  72. package/esm/transport/startBatchWithReplica.js +15 -0
  73. package/package.json +2 -2
  74. package/src/.DS_Store +0 -0
  75. package/src/{cookie.js → browser/cookie.js} +6 -34
  76. package/src/browser/fetchObservable.js +86 -0
  77. package/src/browser/xhrObservable.js +102 -0
  78. package/src/configuration/configuration.js +61 -0
  79. package/src/configuration/transportConfiguration.js +42 -0
  80. package/src/console/consoleObservable.js +65 -0
  81. package/src/dataMap.js +26 -21
  82. package/src/error/trackRuntimeError.js +19 -0
  83. package/src/helper/catchUserErrors.js +12 -0
  84. package/src/helper/contextHistory.js +85 -0
  85. package/src/helper/createEventRateLimiter.js +37 -0
  86. package/src/helper/deviceInfo.js +5 -51
  87. package/src/helper/display.js +21 -0
  88. package/src/helper/enums.js +38 -14
  89. package/src/helper/errorTools.js +76 -12
  90. package/src/helper/instrumentMethod.js +97 -0
  91. package/src/helper/lifeCycle.js +5 -3
  92. package/src/helper/observable.js +33 -2
  93. package/src/helper/tools.js +135 -4
  94. package/src/index.js +18 -7
  95. package/src/init.js +17 -18
  96. package/src/report/reportObservable.js +113 -0
  97. package/src/session/sessionConstants.js +3 -0
  98. package/src/session/sessionCookieStore.js +159 -0
  99. package/src/session/sessionManagement.js +89 -0
  100. package/src/session/sessionStore.js +139 -0
  101. package/src/synthetics/syntheticsWorkerValues.js +22 -0
  102. package/src/synthetics/usr.js +18 -0
  103. package/src/tracekit/computeStackTrace.js +75 -551
  104. package/src/tracekit/index.js +1 -1
  105. package/src/tracekit/tracekit.js +100 -0
  106. package/src/transport/batch.js +289 -0
  107. package/src/transport/httpRequest.js +109 -0
  108. package/src/transport/index.js +3 -0
  109. package/src/transport/sendWithRetryStrategy.js +186 -0
  110. package/src/transport/startBatchWithReplica.js +26 -0
  111. package/cjs/configuration.js +0 -193
  112. package/cjs/errorCollection.js +0 -167
  113. package/cjs/fetchProxy.js +0 -161
  114. package/cjs/helper/errorFilter.js +0 -47
  115. package/cjs/sessionManagement.js +0 -221
  116. package/cjs/tracekit/report.js +0 -289
  117. package/cjs/transport.js +0 -373
  118. package/cjs/xhrProxy.js +0 -122
  119. package/esm/configuration.js +0 -176
  120. package/esm/errorCollection.js +0 -141
  121. package/esm/fetchProxy.js +0 -115
  122. package/esm/helper/errorFilter.js +0 -38
  123. package/esm/sessionManagement.js +0 -195
  124. package/esm/tracekit/report.js +0 -273
  125. package/esm/transport.js +0 -357
  126. package/esm/xhrProxy.js +0 -110
  127. package/src/configuration.js +0 -161
  128. package/src/errorCollection.js +0 -170
  129. package/src/fetchProxy.js +0 -108
  130. package/src/helper/errorFilter.js +0 -38
  131. package/src/sessionManagement.js +0 -224
  132. package/src/tracekit/report.js +0 -284
  133. package/src/transport.js +0 -380
  134. package/src/xhrProxy.js +0 -106
@@ -1,273 +0,0 @@
1
- import { computeStackTrace, augmentStackTraceWithInitialElement } from './computeStackTrace';
2
- import { each } from '../helper/tools'; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types
3
- // eslint-disable-next-line max-len
4
-
5
- var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;
6
- /**
7
- * Cross-browser processing of unhandled exceptions
8
- *
9
- * Syntax:
10
- * ```js
11
- * subscribe(function(stackInfo) { ... })
12
- * unsubscribe(function(stackInfo) { ... })
13
- * report(exception)
14
- * try { ...code... } catch(ex) { report(ex); }
15
- * ```
16
- *
17
- * Supports:
18
- * - Firefox: full stack trace with line numbers, plus column number
19
- * on top frame; column number is not guaranteed
20
- * - Opera: full stack trace with line and column numbers
21
- * - Chrome: full stack trace with line and column numbers
22
- * - Safari: line and column number for the top frame only; some frames
23
- * may be missing, and column number is not guaranteed
24
- * - IE: line and column number for the top frame only; some frames
25
- * may be missing, and column number is not guaranteed
26
- *
27
- * In theory, TraceKit should work on all of the following versions:
28
- * - IE5.5+ (only 8.0 tested)
29
- * - Firefox 0.9+ (only 3.5+ tested)
30
- * - Opera 7+ (only 10.50 tested; versions 9 and earlier may require
31
- * Exceptions Have Stacktrace to be enabled in opera:config)
32
- * - Safari 3+ (only 4+ tested)
33
- * - Chrome 1+ (only 5+ tested)
34
- * - Konqueror 3.5+ (untested)
35
- *
36
- * Requires computeStackTrace.
37
- *
38
- * Tries to catch all unhandled exceptions and report them to the
39
- * subscribed handlers. Please note that report will rethrow the
40
- * exception. This is REQUIRED in order to get a useful stack trace in IE.
41
- * If the exception does not reach the top of the browser, you will only
42
- * get a stack trace from the point where report was called.
43
- *
44
- * Handlers receive a StackTrace object as described in the
45
- * computeStackTrace docs.
46
- *
47
- * @memberof TraceKit
48
- * @namespace
49
- */
50
-
51
- /**
52
- * Reports an unhandled Error.
53
- * @param {Error} ex
54
- * @memberof report
55
- * @throws An exception if an incomplete stack trace is detected (old IE browsers).
56
- */
57
-
58
- export function report(ex) {
59
- if (lastExceptionStack) {
60
- if (lastException === ex) {
61
- return; // already caught by an inner catch block, ignore
62
- }
63
-
64
- processLastException();
65
- }
66
-
67
- var stack = computeStackTrace(ex);
68
- lastExceptionStack = stack;
69
- lastException = ex; // If the stack trace is incomplete, wait for 2 seconds for
70
- // slow slow IE to see if onerror occurs or not before reporting
71
- // this exception; otherwise, we will end up with an incomplete
72
- // stack trace
73
-
74
- setTimeout(function () {
75
- if (lastException === ex) {
76
- processLastException();
77
- }
78
- }, stack.incomplete ? 2000 : 0);
79
- throw ex; // re-throw to propagate to the top level (and cause window.onerror)
80
- }
81
- var handlers = [];
82
- var lastException;
83
- var lastExceptionStack;
84
- /**
85
- * Add a crash handler.
86
- * @param {Function} handler
87
- * @memberof report
88
- */
89
-
90
- export function subscribe(handler) {
91
- installGlobalHandler();
92
- installGlobalUnhandledRejectionHandler();
93
- handlers.push(handler);
94
- }
95
- /**
96
- * Remove a crash handler.
97
- * @param {Function} handler
98
- * @memberof report
99
- */
100
-
101
- export function unsubscribe(handler) {
102
- for (var i = handlers.length - 1; i >= 0; i -= 1) {
103
- if (handlers[i] === handler) {
104
- handlers.splice(i, 1);
105
- }
106
- }
107
-
108
- if (handlers.length === 0) {
109
- uninstallGlobalHandler();
110
- uninstallGlobalUnhandledRejectionHandler();
111
- }
112
- }
113
- /**
114
- * Dispatch stack information to all handlers.
115
- * @param {StackTrace} stack
116
- * @param {boolean} isWindowError Is this a top-level window error?
117
- * @param {Error=} error The error that's being handled (if available, null otherwise)
118
- * @memberof report
119
- * @throws An exception if an error occurs while calling an handler.
120
- */
121
-
122
- function notifyHandlers(stack, isWindowError, error) {
123
- var exception;
124
- each(handlers, function (handler) {
125
- try {
126
- handler(stack, isWindowError, error);
127
- } catch (inner) {
128
- exception = inner;
129
- }
130
- });
131
-
132
- if (exception) {
133
- throw exception;
134
- }
135
- }
136
-
137
- var oldOnerrorHandler;
138
- var onErrorHandlerInstalled;
139
- var oldOnunhandledrejectionHandler;
140
- var onUnhandledRejectionHandlerInstalled;
141
- /**
142
- * Ensures all global unhandled exceptions are recorded.
143
- * Supported by Gecko and IE.
144
- * @param {Event|string} message Error message.
145
- * @param {string=} url URL of script that generated the exception.
146
- * @param {(number|string)=} lineNo The line number at which the error occurred.
147
- * @param {(number|string)=} columnNo The column number at which the error occurred.
148
- * @param {Error=} errorObj The actual Error object.
149
- * @memberof report
150
- */
151
-
152
- export function traceKitWindowOnError(message, url, lineNo, columnNo, errorObj) {
153
- var stack;
154
-
155
- if (lastExceptionStack) {
156
- augmentStackTraceWithInitialElement(lastExceptionStack, url, lineNo);
157
- processLastException();
158
- } else if (errorObj) {
159
- stack = computeStackTrace(errorObj);
160
- notifyHandlers(stack, true, errorObj);
161
- } else {
162
- var location = {
163
- url: url,
164
- column: columnNo,
165
- line: lineNo
166
- };
167
- var name;
168
- var msg = message;
169
-
170
- if ({}.toString.call(message) === '[object String]') {
171
- var groups = ERROR_TYPES_RE.exec(msg);
172
-
173
- if (groups) {
174
- name = groups[1];
175
- msg = groups[2];
176
- }
177
- }
178
-
179
- stack = {
180
- name: name,
181
- message: typeof msg === 'string' ? msg : undefined,
182
- stack: [location]
183
- };
184
- notifyHandlers(stack, true, message);
185
- }
186
-
187
- if (oldOnerrorHandler) {
188
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
189
- return oldOnerrorHandler.apply(this, arguments);
190
- }
191
-
192
- return false;
193
- }
194
- /**
195
- * Ensures all unhandled rejections are recorded.
196
- * @param {PromiseRejectionEvent} e event.
197
- * @memberof report
198
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onunhandledrejection
199
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent
200
- */
201
-
202
- function traceKitWindowOnUnhandledRejection(e) {
203
- var reason = e.reason || 'Empty reason';
204
- var stack = computeStackTrace(reason);
205
- notifyHandlers(stack, true, reason);
206
- }
207
- /**
208
- * Install a global onerror handler
209
- * @memberof report
210
- */
211
-
212
-
213
- function installGlobalHandler() {
214
- if (onErrorHandlerInstalled) {
215
- return;
216
- }
217
-
218
- oldOnerrorHandler = window.onerror;
219
- window.onerror = traceKitWindowOnError;
220
- onErrorHandlerInstalled = true;
221
- }
222
- /**
223
- * Uninstall the global onerror handler
224
- * @memberof report
225
- */
226
-
227
-
228
- function uninstallGlobalHandler() {
229
- if (onErrorHandlerInstalled) {
230
- window.onerror = oldOnerrorHandler;
231
- onErrorHandlerInstalled = false;
232
- }
233
- }
234
- /**
235
- * Install a global onunhandledrejection handler
236
- * @memberof report
237
- */
238
-
239
-
240
- function installGlobalUnhandledRejectionHandler() {
241
- if (onUnhandledRejectionHandlerInstalled) {
242
- return;
243
- }
244
-
245
- oldOnunhandledrejectionHandler = window.onunhandledrejection !== null ? window.onunhandledrejection : undefined;
246
- window.onunhandledrejection = traceKitWindowOnUnhandledRejection;
247
- onUnhandledRejectionHandlerInstalled = true;
248
- }
249
- /**
250
- * Uninstall the global onunhandledrejection handler
251
- * @memberof report
252
- */
253
-
254
-
255
- function uninstallGlobalUnhandledRejectionHandler() {
256
- if (onUnhandledRejectionHandlerInstalled) {
257
- window.onunhandledrejection = oldOnunhandledrejectionHandler;
258
- onUnhandledRejectionHandlerInstalled = false;
259
- }
260
- }
261
- /**
262
- * Process the most recent exception
263
- * @memberof report
264
- */
265
-
266
-
267
- function processLastException() {
268
- var currentLastExceptionStack = lastExceptionStack;
269
- var currentLastException = lastException;
270
- lastExceptionStack = undefined;
271
- lastException = undefined;
272
- notifyHandlers(currentLastExceptionStack, false, currentLastException);
273
- }
package/esm/transport.js DELETED
@@ -1,357 +0,0 @@
1
- import { addEventListener, values, findByPath, escapeRowData, each, isNumber, isArray, extend, isString, toServerDuration, isBoolean, isEmptyObject, isObject, map, escapeJsonValue, escapeRowField } from './helper/tools';
2
- import { DOM_EVENT, RumEventType } from './helper/enums';
3
- import { commonTags, dataMap } from './dataMap';
4
- import { getGlobalObject } from './init'; // https://en.wikipedia.org/wiki/UTF-8
5
-
6
- var HAS_MULTI_BYTES_CHARACTERS = /[^\u0000-\u007F]/;
7
- var CUSTOM_KEYS = 'custom_keys';
8
-
9
- function addBatchPrecision(url) {
10
- if (!url) return url;
11
- return url + (url.indexOf('?') === -1 ? '?' : '&') + 'precision=ms';
12
- }
13
-
14
- var global = getGlobalObject();
15
-
16
- var httpRequest = function httpRequest(endpointUrl, bytesLimit, isLineProtocolToJson) {
17
- this.endpointUrl = endpointUrl;
18
- this.bytesLimit = bytesLimit;
19
- this.isLineProtocolToJson = isLineProtocolToJson;
20
- var isRealNavigator = Object.prototype.toString.call(global && global.navigator) === '[object Navigator]';
21
- var hasSendBeacon = isRealNavigator && typeof global.navigator.sendBeacon === 'function';
22
-
23
- if (hasSendBeacon) {
24
- this.sendBeacon = global.navigator.sendBeacon.bind(global.navigator);
25
- } else {
26
- this.sendBeacon = undefined;
27
- }
28
- };
29
-
30
- httpRequest.prototype = {
31
- send: function send(data, size) {
32
- var url = addBatchPrecision(this.endpointUrl);
33
-
34
- if (this.sendBeacon && size < this.bytesLimit && !this.isLineProtocolToJson) {
35
- var isQueued = this.sendBeacon(url, data);
36
-
37
- if (isQueued) {
38
- return;
39
- }
40
- } else if (this.sendBeacon && size < this.bytesLimit && this.isLineProtocolToJson) {
41
- var blob = new Blob([JSON.stringify(data)], {
42
- type: 'application/json'
43
- });
44
- var isQueued = this.sendBeacon(url, blob);
45
-
46
- if (isQueued) {
47
- return;
48
- }
49
- }
50
-
51
- var request = new XMLHttpRequest();
52
- request.open('POST', url, true);
53
- request.withCredentials = true;
54
-
55
- if (this.isLineProtocolToJson) {
56
- request.setRequestHeader('Content-type', 'application/json');
57
- request.send(JSON.stringify(data));
58
- } else {
59
- request.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
60
- request.send(data);
61
- }
62
- }
63
- };
64
- export var HttpRequest = httpRequest;
65
- export var processedMessageByDataMap = function processedMessageByDataMap(message) {
66
- if (!message || !message.type) return {
67
- rowStr: '',
68
- rowData: undefined
69
- };
70
- var rowData = {
71
- tags: {},
72
- fields: {}
73
- };
74
- var hasFileds = false;
75
- var rowStr = '';
76
- each(dataMap, function (value, key) {
77
- if (value.type === message.type) {
78
- rowStr += key + ',';
79
- rowData.measurement = key;
80
- var tagsStr = [];
81
- var tags = extend({}, commonTags, value.tags);
82
- var filterFileds = ['date', 'type', CUSTOM_KEYS]; // 已经在datamap中定义过的fields和tags
83
-
84
- each(tags, function (value_path, _key) {
85
- var _value = findByPath(message, value_path);
86
-
87
- filterFileds.push(_key);
88
-
89
- if (_value || isNumber(_value)) {
90
- rowData.tags[_key] = escapeJsonValue(_value);
91
- tagsStr.push(escapeRowData(_key) + '=' + escapeRowData(_value));
92
- }
93
- });
94
- var fieldsStr = [];
95
- each(value.fields, function (_value, _key) {
96
- if (isArray(_value) && _value.length === 2) {
97
- var type = _value[0],
98
- value_path = _value[1];
99
-
100
- var _valueData = findByPath(message, value_path);
101
-
102
- filterFileds.push(_key);
103
-
104
- if (_valueData || isNumber(_valueData)) {
105
- rowData.fields[_key] = _valueData; // 这里不需要转译
106
- // _valueData =
107
- // type === 'string'
108
- // ? '"' +
109
- // _valueData.replace(/[\\]*"/g, '"').replace(/"/g, '\\"') +
110
- // '"'
111
- // : escapeRowData(_valueData)
112
-
113
- fieldsStr.push(escapeRowData(_key) + '=' + escapeRowField(_valueData));
114
- }
115
- } else if (isString(_value)) {
116
- var _valueData = findByPath(message, _value);
117
-
118
- filterFileds.push(_key);
119
-
120
- if (_valueData || isNumber(_valueData)) {
121
- rowData.fields[_key] = _valueData; // 这里不需要转译
122
-
123
- fieldsStr.push(escapeRowData(_key) + '=' + escapeRowField(_valueData));
124
- }
125
- }
126
- });
127
-
128
- if (message.tags && isObject(message.tags) && !isEmptyObject(message.tags)) {
129
- // 自定义tag, 存储成field
130
- var _tagKeys = [];
131
- each(message.tags, function (_value, _key) {
132
- // 如果和之前tag重名,则舍弃
133
- if (filterFileds.indexOf(_key) > -1) return;
134
- filterFileds.push(_key);
135
-
136
- if (_value || isNumber(_value)) {
137
- _tagKeys.push(_key);
138
-
139
- rowData.fields[_key] = _value; // 这里不需要转译
140
-
141
- fieldsStr.push(escapeRowData(_key) + '=' + escapeRowField(_value));
142
- }
143
- });
144
-
145
- if (_tagKeys.length) {
146
- rowData.fields[CUSTOM_KEYS] = escapeRowField(_tagKeys);
147
- fieldsStr.push(escapeRowData(CUSTOM_KEYS) + '=' + escapeRowField(_tagKeys));
148
- }
149
- }
150
-
151
- if (message.type === RumEventType.LOGGER) {
152
- // 这里处理日志类型数据自定义字段
153
- each(message, function (value, key) {
154
- if (filterFileds.indexOf(key) === -1 && (isNumber(value) || isString(value) || isBoolean(value))) {
155
- rowData.fields[key] = value; // 这里不需要转译
156
-
157
- fieldsStr.push(escapeRowData(key) + '=' + escapeRowField(value));
158
- }
159
- });
160
- }
161
-
162
- if (tagsStr.length) {
163
- rowStr += tagsStr.join(',');
164
- }
165
-
166
- if (fieldsStr.length) {
167
- rowStr += ' ';
168
- rowStr += fieldsStr.join(',');
169
- hasFileds = true;
170
- }
171
-
172
- rowStr = rowStr + ' ' + message.date;
173
- rowData.time = toServerDuration(message.date); // 这里不需要转译
174
- }
175
- });
176
- return {
177
- rowStr: hasFileds ? rowStr : '',
178
- rowData: hasFileds ? rowData : undefined
179
- };
180
- };
181
-
182
- var batch = function batch(request, maxSize, bytesLimit, maxMessageSize, flushTimeout, isLineProtocolToJson, beforeUnloadCallback) {
183
- this.request = request;
184
- this.maxSize = maxSize;
185
- this.bytesLimit = bytesLimit;
186
- this.maxMessageSize = maxMessageSize;
187
- this.flushTimeout = flushTimeout;
188
- this.isLineProtocolToJson = isLineProtocolToJson;
189
- this.beforeUnloadCallback = beforeUnloadCallback;
190
- this.pushOnlyBuffer = [];
191
- this.upsertBuffer = {};
192
- this.bufferBytesSize = 0;
193
- this.bufferMessageCount = 0;
194
- this.flushOnVisibilityHidden();
195
- this.flushPeriodically();
196
- };
197
-
198
- batch.prototype = {
199
- add: function add(message) {
200
- this.addOrUpdate(message);
201
- },
202
- upsert: function upsert(message, key) {
203
- this.addOrUpdate(message, key);
204
- },
205
- flush: function flush() {
206
- if (this.bufferMessageCount !== 0) {
207
- var messages = this.pushOnlyBuffer.concat(values(this.upsertBuffer));
208
- if (messages.length === 0) return;
209
-
210
- if (this.isLineProtocolToJson) {
211
- this.request.send(map(messages, function (rowdataStr) {
212
- return JSON.parse(rowdataStr);
213
- }), this.bufferBytesSize);
214
- } else {
215
- this.request.send(messages.join('\n'), this.bufferBytesSize);
216
- }
217
-
218
- this.pushOnlyBuffer = [];
219
- this.upsertBuffer = {};
220
- this.bufferBytesSize = 0;
221
- this.bufferMessageCount = 0;
222
- }
223
- },
224
- processSendData: function processSendData(message) {
225
- if (this.isLineProtocolToJson) {
226
- return JSON.stringify(processedMessageByDataMap(message).rowData);
227
- }
228
-
229
- return processedMessageByDataMap(message).rowStr;
230
- },
231
- sizeInBytes: function sizeInBytes(candidate) {
232
- // Accurate byte size computations can degrade performances when there is a lot of events to process
233
- if (!HAS_MULTI_BYTES_CHARACTERS.test(candidate)) {
234
- return candidate.length;
235
- }
236
-
237
- if (window.TextEncoder !== undefined) {
238
- return new TextEncoder().encode(candidate).length;
239
- }
240
-
241
- return new Blob([candidate]).size;
242
- },
243
- addOrUpdate: function addOrUpdate(message, key) {
244
- var process = this.process(message);
245
- if (!process.processedMessage || process.processedMessage === '') return;
246
-
247
- if (process.messageBytesSize >= this.maxMessageSize) {
248
- console.warn('Discarded a message whose size was bigger than the maximum allowed size' + this.maxMessageSize + 'KB.');
249
- return;
250
- }
251
-
252
- if (this.hasMessageFor(key)) {
253
- this.remove(key);
254
- }
255
-
256
- if (this.willReachedBytesLimitWith(process.messageBytesSize)) {
257
- this.flush();
258
- }
259
-
260
- this.push(process.processedMessage, process.messageBytesSize, key);
261
-
262
- if (this.isFull()) {
263
- this.flush();
264
- }
265
- },
266
- process: function process(message) {
267
- var processedMessage = '';
268
- var processedMessage = this.processSendData(message);
269
- var messageBytesSize = this.sizeInBytes(processedMessage);
270
- return {
271
- processedMessage: processedMessage,
272
- messageBytesSize: messageBytesSize
273
- };
274
- },
275
- push: function push(processedMessage, messageBytesSize, key) {
276
- if (this.bufferMessageCount > 0) {
277
- // \n separator at serialization
278
- this.bufferBytesSize += 1;
279
- }
280
-
281
- if (key !== undefined) {
282
- this.upsertBuffer[key] = processedMessage;
283
- } else {
284
- this.pushOnlyBuffer.push(processedMessage);
285
- }
286
-
287
- this.bufferBytesSize += messageBytesSize;
288
- this.bufferMessageCount += 1;
289
- },
290
- remove: function remove(key) {
291
- var removedMessage = this.upsertBuffer[key];
292
- delete this.upsertBuffer[key];
293
- var messageBytesSize = this.sizeInBytes(removedMessage);
294
- this.bufferBytesSize -= messageBytesSize;
295
- this.bufferMessageCount -= 1;
296
-
297
- if (this.bufferMessageCount > 0) {
298
- this.bufferBytesSize -= 1;
299
- }
300
- },
301
- hasMessageFor: function hasMessageFor(key) {
302
- return key !== undefined && this.upsertBuffer[key] !== undefined;
303
- },
304
- willReachedBytesLimitWith: function willReachedBytesLimitWith(messageBytesSize) {
305
- // byte of the separator at the end of the message
306
- return this.bufferBytesSize + messageBytesSize + 1 >= this.bytesLimit;
307
- },
308
- isFull: function isFull() {
309
- return this.bufferMessageCount === this.maxSize || this.bufferBytesSize >= this.bytesLimit;
310
- },
311
- flushPeriodically: function flushPeriodically() {
312
- var _this = this;
313
-
314
- setTimeout(function () {
315
- _this.flush();
316
-
317
- _this.flushPeriodically();
318
- }, _this.flushTimeout);
319
- },
320
- flushOnVisibilityHidden: function flushOnVisibilityHidden() {
321
- var _this = this;
322
- /**
323
- * With sendBeacon, requests are guaranteed to be successfully sent during document unload
324
- */
325
- // @ts-ignore this function is not always defined
326
-
327
-
328
- if (global.navigator.sendBeacon) {
329
- /**
330
- * beforeunload is called before visibilitychange
331
- * register first to be sure to be called before flush on beforeunload
332
- * caveat: unload can still be canceled by another listener
333
- */
334
- addEventListener(window, DOM_EVENT.BEFORE_UNLOAD, _this.beforeUnloadCallback);
335
- /**
336
- * Only event that guarantee to fire on mobile devices when the page transitions to background state
337
- * (e.g. when user switches to a different application, goes to homescreen, etc), or is being unloaded.
338
- */
339
-
340
- addEventListener(document, DOM_EVENT.VISIBILITY_CHANGE, function () {
341
- if (document.visibilityState === 'hidden') {
342
- _this.flush();
343
- }
344
- });
345
- /**
346
- * Safari does not support yet to send a request during:
347
- * - a visibility change during doc unload (cf: https://bugs.webkit.org/show_bug.cgi?id=194897)
348
- * - a page hide transition (cf: https://bugs.webkit.org/show_bug.cgi?id=188329)
349
- */
350
-
351
- addEventListener(window, DOM_EVENT.BEFORE_UNLOAD, function () {
352
- _this.flush();
353
- });
354
- }
355
- }
356
- };
357
- export var Batch = batch;