app-tracker 2.2.2 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,247 +1,363 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- const log_1 = require("./log");
13
- const cross_fetch_1 = require("cross-fetch");
14
- const safeFetch = typeof window !== 'undefined' ? cross_fetch_1.default.bind(window) : cross_fetch_1.default;
15
- class AppTrackerService {
16
- constructor() {
17
- this.sendLogsInDevelopment = false;
18
- this.logInConsole = false;
19
- this.endpointUrl = 'https://app-tracker-api.azurewebsites.net/';
20
- this.apiKey = '';
21
- this.logs = [];
22
- this.sendTries = 0;
23
- this.maxSendTries = 5;
24
- this.isSending = false;
25
- this.maxLogsCount = 10;
26
- this.userAgent = '';
27
- this.logLevel = [log_1.LogType.error];
28
- this.sendLogsByTypesImmediately = [log_1.LogType.error, log_1.LogType.critical];
29
- this.isNode = false;
30
- this.isRunningLocal = true;
31
- this.ident = '';
32
- this.eventListenerAdded = false;
33
- }
34
- init(apiKey, config) {
35
- this.apiKey = apiKey;
36
- if (config) {
37
- if (typeof config.endpointUrl !== 'undefined')
38
- this.endpointUrl = config.endpointUrl;
39
- if (typeof config.maxLogsCount !== 'undefined')
40
- this.maxLogsCount = config.maxLogsCount;
41
- if (typeof config.maxSendTries !== 'undefined')
42
- this.maxSendTries = config.maxSendTries;
43
- if (typeof config.sendLogsInDevelopment !== 'undefined')
44
- this.sendLogsInDevelopment = config.sendLogsInDevelopment;
45
- if (typeof config.logInConsole !== 'undefined')
46
- this.logInConsole = config.logInConsole;
47
- if (typeof config.logLevel !== 'undefined')
48
- this.logLevel = config.logLevel;
49
- if (typeof config.sendLogsByTypesImmediately !== 'undefined')
50
- this.sendLogsByTypesImmediately = config.sendLogsByTypesImmediately;
51
- }
52
- this.setRunningSystem(config);
53
- }
54
- addEventListener(apiKey) {
55
- if (apiKey != '' && !this.isNode && !this.isRunningLocal && !this.eventListenerAdded) {
56
- this._boundBeforeUnloadHandler = this._boundBeforeUnloadHandler || ((e) => this.beforeunloadHandler(e));
57
- window.addEventListener('beforeunload', this._boundBeforeUnloadHandler, true);
58
- this.eventListenerAdded = true;
59
- }
60
- }
61
- removeEventListener(apiKey) {
62
- if (apiKey != '' && !this.isNode && !this.isRunningLocal && this.eventListenerAdded) {
63
- if (this._boundBeforeUnloadHandler) {
64
- window.removeEventListener('beforeunload', this._boundBeforeUnloadHandler, true);
65
- }
66
- this.eventListenerAdded = false;
67
- }
68
- }
69
- beforeunloadHandler(event) {
70
- event.preventDefault();
71
- event.returnValue = '';
72
- if (!this.isSending) {
73
- const logsToSend = this.logs;
74
- this.isSending = true;
75
- this.logs = [];
76
- this.sendLogsToServerCore(logsToSend);
77
- }
78
- }
79
- setRunningSystem(config) {
80
- var _a, _b, _c;
81
- this.isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
82
- if (!this.isNode) {
83
- this.userAgent = (_a = config) === null || _a === void 0 ? void 0 : _a.userAgentOrOs;
84
- this.ident = this.getIdent();
85
- }
86
- else {
87
- this.os = (_b = config) === null || _b === void 0 ? void 0 : _b.userAgentOrOs;
88
- this.userAgent = this.setUserAgentFromOs();
89
- }
90
- this.isRunningLocal = this.isNode ? (_c = process.env.NODE_ENV, (_c !== null && _c !== void 0 ? _c : '')).indexOf("development") > -1 : window.location.href.indexOf('localhost') > -1;
91
- }
92
- getIdent() {
93
- var _a;
94
- let ident = (_a = localStorage) === null || _a === void 0 ? void 0 : _a.getItem('App-Tracker.device-ident');
95
- if (!ident) {
96
- ident = this.createUUID();
97
- localStorage.setItem('App-Tracker.device-ident', ident);
98
- }
99
- return ident;
100
- }
101
- debug(message, ...optionalParams) {
102
- this.addLog(log_1.LogType.debug, message, ...optionalParams);
103
- }
104
- info(message, ...optionalParams) {
105
- this.addLog(log_1.LogType.info, message, ...optionalParams);
106
- }
107
- log(message, ...optionalParams) {
108
- this.addLog(log_1.LogType.log, message, ...optionalParams);
109
- }
110
- warn(message, ...optionalParams) {
111
- this.addLog(log_1.LogType.warn, message, ...optionalParams);
112
- }
113
- error(message, ...optionalParams) {
114
- this.addLog(log_1.LogType.error, message, ...optionalParams);
115
- }
116
- critical(message, ...optionalParams) {
117
- this.addLog(log_1.LogType.critical, message, ...optionalParams);
118
- }
119
- addLog(type, message, ...optionalParams) {
120
- if (this.checkLogType(type)) {
121
- if (this.isRunningLocal && !this.sendLogsInDevelopment) {
122
- this.logToConsole(type, message, ...optionalParams);
123
- }
124
- else {
125
- this.sendLogsToServer(type, message, ...optionalParams);
126
- }
127
- }
128
- else {
129
- this.logToConsole(type, message, ...optionalParams);
130
- }
131
- }
132
- logToConsole(type, message, ...optionalParams) {
133
- if (this.logInConsole) {
134
- switch (type) {
135
- case log_1.LogType.debug:
136
- console.debug(message, ...optionalParams);
137
- break;
138
- case log_1.LogType.critical:
139
- case log_1.LogType.error:
140
- console.error(message, ...optionalParams);
141
- break;
142
- case log_1.LogType.info:
143
- console.info(message, ...optionalParams);
144
- break;
145
- case log_1.LogType.log:
146
- console.log(message, ...optionalParams);
147
- break;
148
- case log_1.LogType.warn:
149
- console.warn(message, ...optionalParams);
150
- break;
151
- default:
152
- console.warn("Unkown LogType: ", type);
153
- break;
154
- }
155
- }
156
- }
157
- sendLogsToServer(type, message, ...optionalParams) {
158
- var _a, _b;
159
- const log = { logType: type, message: message, optionalParams: [], createdAt: new Date(), ident: this.ident };
160
- optionalParams.forEach((op) => {
161
- if (Array.isArray(op))
162
- op.forEach(o => log.optionalParams.push(o));
163
- else
164
- log.optionalParams.push(op);
165
- });
166
- this.logs.push(log);
167
- if ((this.logs.length >= this.maxLogsCount && !this.isSending) ||
168
- ((((_a = this.sendLogsByTypesImmediately) === null || _a === void 0 ? void 0 : _a.find(l => l == type)) || type == log_1.LogType.critical) != null && !this.isSending)) {
169
- const logsToSend = this.logs;
170
- this.logs = [];
171
- this.isSending = true;
172
- this.sendLogsToServerCore(logsToSend);
173
- this.removeEventListener(this.apiKey);
174
- }
175
- if (((_b = this.logs) === null || _b === void 0 ? void 0 : _b.length) > 0 && !this.eventListenerAdded) {
176
- this.addEventListener(this.apiKey);
177
- }
178
- }
179
- checkLogType(type) {
180
- if (this.logLevel.find(l => l === type) != null || type === log_1.LogType.critical) {
181
- return true;
182
- }
183
- else {
184
- return false;
185
- }
186
- }
187
- sendLogsToServerCore(logsToSend) {
188
- return __awaiter(this, void 0, void 0, function* () {
189
- if (this.sendTries < this.maxSendTries) {
190
- try {
191
- const last = this.endpointUrl.charAt(this.endpointUrl.length - 1);
192
- const response = yield safeFetch(`${this.endpointUrl}${last === '/' ? 'logs/createLog' : '/logs/createLog'}`, {
193
- method: 'POST',
194
- headers: {
195
- 'Accept': 'application/json',
196
- 'Content-Type': 'application/json',
197
- 'X-Auth-Key': this.apiKey
198
- },
199
- body: JSON.stringify({ logs: logsToSend, userAgent: this.userAgent }, (key, value) => {
200
- if (value instanceof Error) {
201
- let error = {};
202
- Object.getOwnPropertyNames(value).forEach(function (key) {
203
- error[key] = value[key];
204
- });
205
- return error;
206
- }
207
- return value;
208
- })
209
- });
210
- logsToSend = [];
211
- this.isSending = false;
212
- this.sendTries = 0; // Reset sendTries after successful send
213
- }
214
- catch (error) {
215
- console.error(`AppLogger: Could not send Logs to Server try ${this.sendTries}`, error);
216
- this.sendTries++;
217
- // Warten, bevor der nächste asynchrone Versuch gestartet wird
218
- yield new Promise(resolve => setTimeout(resolve, 10000));
219
- yield this.sendLogsToServerCore(logsToSend);
220
- }
221
- }
222
- else {
223
- this.sendTries = 0;
224
- this.isSending = false;
225
- console.error('AppLogger: Could not send Logs to Server finally');
226
- }
227
- });
228
- }
229
- setUserAgentFromOs() {
230
- const osInfo = {
231
- arch: this.os.arch(),
232
- platform: this.os.platform(),
233
- release: this.os.release(),
234
- type: this.os.type(),
235
- version: this.os.version(),
236
- hostname: this.os.hostname()
237
- };
238
- return JSON.stringify(osInfo);
239
- }
240
- createUUID() {
241
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
242
- const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
243
- return v.toString(16);
244
- });
245
- }
246
- }
247
- exports.AppTrackerService = AppTrackerService;
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const log_1 = require("./log");
13
+ const cross_fetch_1 = require("cross-fetch");
14
+ const version_1 = require("./version");
15
+ const log_privacy_1 = require("./log-privacy");
16
+ const safeFetch = typeof window !== 'undefined' ? cross_fetch_1.default.bind(window) : cross_fetch_1.default;
17
+ class AppTrackerService {
18
+ constructor() {
19
+ this.sendLogsInDevelopment = false;
20
+ this.logInConsole = false;
21
+ this.endpointUrl = 'https://app-tracker-api.azurewebsites.net/';
22
+ this.apiKey = '';
23
+ this.logs = [];
24
+ this.maxSendTries = 5;
25
+ this.retryDelayMs = 10000;
26
+ this.requestTimeoutMs = 10000;
27
+ this.isSending = false;
28
+ this.maxLogsCount = 10;
29
+ this.clientInfo = null;
30
+ this.logLevel = [log_1.LogType.error];
31
+ this.sendLogsByTypesImmediately = [log_1.LogType.error, log_1.LogType.critical];
32
+ this.isNode = false;
33
+ this.isRunningLocal = true;
34
+ this.eventListenerAdded = false;
35
+ }
36
+ init(apiKey, config) {
37
+ this.apiKey = apiKey;
38
+ if (config) {
39
+ if (typeof config.endpointUrl !== 'undefined')
40
+ this.endpointUrl = config.endpointUrl;
41
+ if (typeof config.maxLogsCount !== 'undefined')
42
+ this.maxLogsCount = config.maxLogsCount;
43
+ if (typeof config.maxSendTries !== 'undefined')
44
+ this.maxSendTries = Math.max(1, config.maxSendTries);
45
+ if (typeof config.retryDelayMs !== 'undefined')
46
+ this.retryDelayMs = Math.max(0, config.retryDelayMs);
47
+ if (typeof config.requestTimeoutMs !== 'undefined')
48
+ this.requestTimeoutMs = Math.max(1, config.requestTimeoutMs);
49
+ if (typeof config.sendLogsInDevelopment !== 'undefined')
50
+ this.sendLogsInDevelopment = config.sendLogsInDevelopment;
51
+ if (typeof config.logInConsole !== 'undefined')
52
+ this.logInConsole = config.logInConsole;
53
+ if (typeof config.logLevel !== 'undefined')
54
+ this.logLevel = config.logLevel;
55
+ if (typeof config.sendLogsByTypesImmediately !== 'undefined')
56
+ this.sendLogsByTypesImmediately = config.sendLogsByTypesImmediately;
57
+ }
58
+ this.setRunningSystem(config);
59
+ if (!this.isNode && !this.correlationId) {
60
+ this.correlationId = this.createCorrelationId();
61
+ }
62
+ }
63
+ addEventListener(apiKey) {
64
+ if (apiKey != '' && !this.isNode && !this.isRunningLocal && !this.eventListenerAdded) {
65
+ this._boundBeforeUnloadHandler = this._boundBeforeUnloadHandler || ((e) => this.beforeunloadHandler(e));
66
+ window.addEventListener('beforeunload', this._boundBeforeUnloadHandler, true);
67
+ this.eventListenerAdded = true;
68
+ }
69
+ }
70
+ removeEventListener(apiKey) {
71
+ if (apiKey != '' && !this.isNode && !this.isRunningLocal && this.eventListenerAdded) {
72
+ if (this._boundBeforeUnloadHandler) {
73
+ window.removeEventListener('beforeunload', this._boundBeforeUnloadHandler, true);
74
+ }
75
+ this.eventListenerAdded = false;
76
+ }
77
+ }
78
+ beforeunloadHandler(_event) {
79
+ if (this.logs.length === 0)
80
+ return;
81
+ const logsToSend = this.logs.splice(0);
82
+ const body = this.serializePayload(logsToSend, true);
83
+ const url = this.getLogsEndpoint();
84
+ // sendBeacon is specifically designed to survive page termination. The API
85
+ // key is also accepted in the request body by the server's ApiKeyGuard.
86
+ // text/plain keeps a cross-origin beacon CORS-safelisted; the API explicitly
87
+ // enables JSON parsing for this content type.
88
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
89
+ const accepted = navigator.sendBeacon(url, new Blob([body], { type: 'text/plain;charset=UTF-8' }));
90
+ if (accepted)
91
+ return;
92
+ }
93
+ // Keep the logs queued if the browser could not schedule the beacon. A
94
+ // keepalive fetch is the best available fallback during page termination.
95
+ this.logs.unshift(...logsToSend);
96
+ void this.flush();
97
+ }
98
+ setRunningSystem(_config) {
99
+ var _a, _b, _c, _d, _e;
100
+ this.nodeProcess = typeof globalThis !== 'undefined' ? globalThis.process : undefined;
101
+ this.isNode = Object.prototype.toString.call(this.nodeProcess || 0) === '[object process]';
102
+ this.clientInfo = this.isNode
103
+ ? this.getNodeClientInfo((_a = _config) === null || _a === void 0 ? void 0 : _a.userAgentOrOs)
104
+ : this.getBrowserClientInfo((_b = _config) === null || _b === void 0 ? void 0 : _b.userAgentOrOs);
105
+ this.isRunningLocal = this.isNode
106
+ ? (_e = (_d = (_c = this.nodeProcess) === null || _c === void 0 ? void 0 : _c.env) === null || _d === void 0 ? void 0 : _d.NODE_ENV, (_e !== null && _e !== void 0 ? _e : '')).indexOf("development") > -1
107
+ : window.location.href.indexOf('localhost') > -1;
108
+ }
109
+ getIdent() {
110
+ // Kept for API compatibility. Stable device identifiers are deliberately
111
+ // no longer created or stored because they allow cross-session tracking.
112
+ return '';
113
+ }
114
+ getCorrelationId() {
115
+ return this.isNode ? '' : this.correlationId || '';
116
+ }
117
+ debug(message, ...optionalParams) {
118
+ this.addLog(log_1.LogType.debug, message, ...optionalParams);
119
+ }
120
+ info(message, ...optionalParams) {
121
+ this.addLog(log_1.LogType.info, message, ...optionalParams);
122
+ }
123
+ log(message, ...optionalParams) {
124
+ this.addLog(log_1.LogType.log, message, ...optionalParams);
125
+ }
126
+ warn(message, ...optionalParams) {
127
+ this.addLog(log_1.LogType.warn, message, ...optionalParams);
128
+ }
129
+ error(message, ...optionalParams) {
130
+ this.addLog(log_1.LogType.error, message, ...optionalParams);
131
+ }
132
+ critical(message, ...optionalParams) {
133
+ this.addLog(log_1.LogType.critical, message, ...optionalParams);
134
+ }
135
+ addLog(type, message, ...optionalParams) {
136
+ if (this.checkLogType(type)) {
137
+ if (this.isRunningLocal && !this.sendLogsInDevelopment) {
138
+ this.logToConsole(type, message, ...optionalParams);
139
+ }
140
+ else {
141
+ this.sendLogsToServer(type, message, ...optionalParams);
142
+ }
143
+ }
144
+ else {
145
+ this.logToConsole(type, message, ...optionalParams);
146
+ }
147
+ }
148
+ logToConsole(type, message, ...optionalParams) {
149
+ if (this.logInConsole) {
150
+ const safeMessage = typeof message === 'string' ? log_privacy_1.sanitizeLogText(message) : message;
151
+ const safeParams = optionalParams.map(param => log_privacy_1.sanitizeLogValue(param));
152
+ switch (type) {
153
+ case log_1.LogType.debug:
154
+ console.debug(safeMessage, ...safeParams);
155
+ break;
156
+ case log_1.LogType.critical:
157
+ case log_1.LogType.error:
158
+ console.error(safeMessage, ...safeParams);
159
+ break;
160
+ case log_1.LogType.info:
161
+ console.info(safeMessage, ...safeParams);
162
+ break;
163
+ case log_1.LogType.log:
164
+ console.log(safeMessage, ...safeParams);
165
+ break;
166
+ case log_1.LogType.warn:
167
+ console.warn(safeMessage, ...safeParams);
168
+ break;
169
+ default:
170
+ console.warn("Unkown LogType: ", type);
171
+ break;
172
+ }
173
+ }
174
+ }
175
+ sendLogsToServer(type, message, ...optionalParams) {
176
+ var _a, _b;
177
+ const log = { logType: type, message: typeof message === 'string' ? log_privacy_1.sanitizeLogText(message) : message, optionalParams: [], createdAt: new Date() };
178
+ optionalParams.forEach((op) => {
179
+ if (Array.isArray(op))
180
+ op.forEach(o => log.optionalParams.push(log_privacy_1.sanitizeLogValue(o)));
181
+ else
182
+ log.optionalParams.push(log_privacy_1.sanitizeLogValue(op));
183
+ });
184
+ this.logs.push(log);
185
+ const sendImmediately = type === log_1.LogType.critical || ((_a = this.sendLogsByTypesImmediately) === null || _a === void 0 ? void 0 : _a.includes(type)) === true;
186
+ if (this.logs.length >= this.maxLogsCount || sendImmediately)
187
+ void this.flush();
188
+ if (((_b = this.logs) === null || _b === void 0 ? void 0 : _b.length) > 0 && !this.eventListenerAdded) {
189
+ this.addEventListener(this.apiKey);
190
+ }
191
+ }
192
+ checkLogType(type) {
193
+ if (this.logLevel.find(l => l === type) != null || type === log_1.LogType.critical) {
194
+ return true;
195
+ }
196
+ else {
197
+ return false;
198
+ }
199
+ }
200
+ /** Sends all currently queued logs and any logs added while sending. */
201
+ flush() {
202
+ if (this.activeSend)
203
+ return this.activeSend;
204
+ if (this.logs.length === 0)
205
+ return Promise.resolve();
206
+ this.isSending = true;
207
+ this.removeEventListener(this.apiKey);
208
+ this.activeSend = this.runSendLoop();
209
+ return this.activeSend;
210
+ }
211
+ runSendLoop() {
212
+ return __awaiter(this, void 0, void 0, function* () {
213
+ try {
214
+ while (this.logs.length > 0) {
215
+ const logsToSend = this.logs.splice(0);
216
+ const sent = yield this.sendLogsToServerCore(logsToSend);
217
+ if (!sent) {
218
+ // Preserve the failed batch for a later explicit flush or log event.
219
+ this.logs.unshift(...logsToSend);
220
+ return;
221
+ }
222
+ }
223
+ }
224
+ finally {
225
+ this.isSending = false;
226
+ this.activeSend = undefined;
227
+ if (this.logs.length > 0)
228
+ this.addEventListener(this.apiKey);
229
+ }
230
+ });
231
+ }
232
+ sendLogsToServerCore(logsToSend) {
233
+ var _a;
234
+ return __awaiter(this, void 0, void 0, function* () {
235
+ for (let sendTry = 1; sendTry <= this.maxSendTries; sendTry++) {
236
+ const abortController = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
237
+ const timeout = abortController ? setTimeout(() => abortController.abort(), this.requestTimeoutMs) : undefined;
238
+ try {
239
+ const body = this.serializePayload(logsToSend);
240
+ const response = yield safeFetch(this.getLogsEndpoint(), {
241
+ method: 'POST',
242
+ headers: {
243
+ 'Accept': 'application/json',
244
+ 'Content-Type': 'application/json',
245
+ 'X-Auth-Key': this.apiKey
246
+ },
247
+ body,
248
+ signal: (_a = abortController) === null || _a === void 0 ? void 0 : _a.signal,
249
+ // Browsers impose a small quota on keepalive requests.
250
+ keepalive: body.length <= 60000
251
+ });
252
+ if (!response.ok)
253
+ throw new Error(`HTTP ${response.status} ${response.statusText}`);
254
+ return true;
255
+ }
256
+ catch (error) {
257
+ console.error(`AppLogger: Could not send logs to server (attempt ${sendTry}/${this.maxSendTries})`);
258
+ if (sendTry < this.maxSendTries)
259
+ yield new Promise(resolve => setTimeout(resolve, this.retryDelayMs));
260
+ }
261
+ finally {
262
+ if (timeout !== undefined)
263
+ clearTimeout(timeout);
264
+ }
265
+ }
266
+ console.error('AppLogger: Could not send logs to server finally; batch remains queued');
267
+ return false;
268
+ });
269
+ }
270
+ getLogsEndpoint() {
271
+ const last = this.endpointUrl.charAt(this.endpointUrl.length - 1);
272
+ return `${this.endpointUrl}${last === '/' ? 'logs/createLog' : '/logs/createLog'}`;
273
+ }
274
+ serializePayload(logsToSend, includeApiKey = false) {
275
+ const seen = new WeakSet();
276
+ const payload = {
277
+ logs: logsToSend,
278
+ osType: this.isNode ? 'node' : 'web',
279
+ packageVersion: version_1.APP_TRACKER_VERSION,
280
+ clientInfo: this.clientInfo
281
+ };
282
+ if (!this.isNode && this.correlationId)
283
+ payload.correlationId = this.correlationId;
284
+ if (includeApiKey)
285
+ payload.apiKey = this.apiKey;
286
+ return JSON.stringify(payload, (_key, value) => {
287
+ if (value instanceof Error) {
288
+ if (seen.has(value))
289
+ return '[Circular]';
290
+ seen.add(value);
291
+ const serializedError = {};
292
+ Object.getOwnPropertyNames(value).forEach(key => serializedError[key] = value[key]);
293
+ return serializedError;
294
+ }
295
+ if (typeof value === 'bigint')
296
+ return value.toString();
297
+ if (value && typeof value === 'object') {
298
+ if (seen.has(value))
299
+ return '[Circular]';
300
+ seen.add(value);
301
+ }
302
+ return value;
303
+ });
304
+ }
305
+ getBrowserClientInfo(userAgentOrOs) {
306
+ const userAgent = typeof userAgentOrOs === 'string' ? userAgentOrOs : '';
307
+ const browserPatterns = [
308
+ { name: 'Edge', expression: /Edg\/([0-9]+)/ },
309
+ { name: 'Firefox', expression: /Firefox\/([0-9]+)/ },
310
+ { name: 'Chrome', expression: /(?:Chrome|CriOS)\/([0-9]+)/ },
311
+ { name: 'Safari', expression: /Version\/([0-9]+).*Safari/ },
312
+ ];
313
+ const browser = browserPatterns
314
+ .map(item => ({ item, match: userAgent.match(item.expression) }))
315
+ .find(item => item.match !== null);
316
+ const android = userAgent.match(/Android\s+([0-9]+)/i);
317
+ const ios = userAgent.match(/(?:iPhone|iPad).*OS\s+([0-9]+)/i);
318
+ const windows = userAgent.match(/Windows NT\s+([0-9]+)/i);
319
+ const macOs = userAgent.match(/Mac OS X\s+([0-9]+)/i);
320
+ const os = android ? { name: 'Android', version: android[1], platform: '' }
321
+ : ios ? { name: 'iOS', version: ios[1], platform: '' }
322
+ : windows ? { name: 'Windows', version: windows[1], platform: '' }
323
+ : macOs ? { name: 'macOS', version: macOs[1], platform: '' }
324
+ : /Linux/i.test(userAgent) ? { name: 'Linux', version: '', platform: '' } : null;
325
+ return {
326
+ client: browser ? { type: 'browser', name: browser.item.name, version: browser.match[1] } : null,
327
+ os,
328
+ device: { type: /iPad|Tablet/i.test(userAgent) ? 'tablet' : /Mobile|Android|iPhone/i.test(userAgent) ? 'smartphone' : 'desktop' },
329
+ };
330
+ }
331
+ getNodeClientInfo(os) {
332
+ var _a, _b;
333
+ const call = (name) => os && typeof os[name] === 'function' ? String(os[name]()) : '';
334
+ return {
335
+ client: { type: 'library', name: 'Node.js', version: this.majorVersion((_a = this.nodeProcess) === null || _a === void 0 ? void 0 : _a.version) },
336
+ os: { name: call('platform') || ((_b = this.nodeProcess) === null || _b === void 0 ? void 0 : _b.platform) || '', version: this.majorVersion(call('release')), platform: call('arch') },
337
+ device: null,
338
+ };
339
+ }
340
+ majorVersion(value) {
341
+ const match = typeof value === 'string' ? value.match(/\d+/) : null;
342
+ return match ? match[0] : '';
343
+ }
344
+ createCorrelationId() {
345
+ var _a, _b;
346
+ const browserCrypto = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
347
+ if (typeof ((_a = browserCrypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === 'function')
348
+ return browserCrypto.randomUUID();
349
+ const bytes = new Uint8Array(16);
350
+ if (typeof ((_b = browserCrypto) === null || _b === void 0 ? void 0 : _b.getRandomValues) === 'function') {
351
+ browserCrypto.getRandomValues(bytes);
352
+ }
353
+ else {
354
+ for (let index = 0; index < bytes.length; index++)
355
+ bytes[index] = Math.floor(Math.random() * 256);
356
+ }
357
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
358
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
359
+ const hex = Array.from(bytes).map(value => (`0${value.toString(16)}`).slice(-2)).join('');
360
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
361
+ }
362
+ }
363
+ exports.AppTrackerService = AppTrackerService;
package/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
- export * from './main';
2
- export * from './app-tracker.service';
3
- export * from './log';
1
+ export * from './main';
2
+ export * from './app-tracker.service';
3
+ export * from './log';
4
+ export * from './version';