@amplitude/analytics-core 2.24.1 → 2.26.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.
Files changed (29) hide show
  1. package/lib/cjs/diagnostics/diagnostics-client.d.ts +156 -0
  2. package/lib/cjs/diagnostics/diagnostics-client.d.ts.map +1 -0
  3. package/lib/cjs/diagnostics/diagnostics-client.js +305 -0
  4. package/lib/cjs/diagnostics/diagnostics-client.js.map +1 -0
  5. package/lib/cjs/diagnostics/diagnostics-storage.d.ts +123 -0
  6. package/lib/cjs/diagnostics/diagnostics-storage.d.ts.map +1 -0
  7. package/lib/cjs/diagnostics/diagnostics-storage.js +492 -0
  8. package/lib/cjs/diagnostics/diagnostics-storage.js.map +1 -0
  9. package/lib/cjs/index.d.ts.map +1 -1
  10. package/lib/cjs/index.js +1 -0
  11. package/lib/cjs/index.js.map +1 -1
  12. package/lib/cjs/types/config/core-config.d.ts +5 -0
  13. package/lib/cjs/types/config/core-config.d.ts.map +1 -1
  14. package/lib/cjs/types/config/core-config.js.map +1 -1
  15. package/lib/esm/diagnostics/diagnostics-client.d.ts +156 -0
  16. package/lib/esm/diagnostics/diagnostics-client.d.ts.map +1 -0
  17. package/lib/esm/diagnostics/diagnostics-client.js +302 -0
  18. package/lib/esm/diagnostics/diagnostics-client.js.map +1 -0
  19. package/lib/esm/diagnostics/diagnostics-storage.d.ts +123 -0
  20. package/lib/esm/diagnostics/diagnostics-storage.d.ts.map +1 -0
  21. package/lib/esm/diagnostics/diagnostics-storage.js +489 -0
  22. package/lib/esm/diagnostics/diagnostics-storage.js.map +1 -0
  23. package/lib/esm/index.d.ts.map +1 -1
  24. package/lib/esm/index.js +1 -0
  25. package/lib/esm/index.js.map +1 -1
  26. package/lib/esm/types/config/core-config.d.ts +5 -0
  27. package/lib/esm/types/config/core-config.d.ts.map +1 -1
  28. package/lib/esm/types/config/core-config.js.map +1 -1
  29. package/package.json +2 -2
@@ -0,0 +1,156 @@
1
+ import { ILogger } from '../logger';
2
+ import { IDiagnosticsStorage } from './diagnostics-storage';
3
+ import { ServerZoneType } from '../types/server-zone';
4
+ export declare const SAVE_INTERVAL_MS = 1000;
5
+ export declare const FLUSH_INTERVAL_MS: number;
6
+ export declare const DIAGNOSTICS_US_SERVER_URL = "https://diagnostics.prod.us-west-2.amplitude.com/v1/capture";
7
+ export declare const DIAGNOSTICS_EU_SERVER_URL = "https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture";
8
+ export declare const MAX_MEMORY_STORAGE_COUNT = 10000;
9
+ export declare const MAX_MEMORY_STORAGE_EVENTS_COUNT = 10;
10
+ /**
11
+ * Key-value pairs for environment/context information
12
+ */
13
+ type DiagnosticsTags = Record<string, string>;
14
+ /**
15
+ * Numeric counters that can be incremented
16
+ */
17
+ type DiagnosticsCounters = Record<string, number>;
18
+ /**
19
+ * Properties for diagnostic events
20
+ */
21
+ type EventProperties = Record<string, any>;
22
+ /**
23
+ * Individual diagnostic event
24
+ */
25
+ interface DiagnosticsEvent {
26
+ readonly event_name: string;
27
+ readonly time: number;
28
+ readonly event_properties: EventProperties;
29
+ }
30
+ /**
31
+ * Computed histogram statistics for final payload
32
+ */
33
+ interface HistogramResult {
34
+ readonly count: number;
35
+ readonly min: number;
36
+ readonly max: number;
37
+ readonly avg: number;
38
+ }
39
+ /**
40
+ * Internal histogram statistics with sum for efficient incremental updates
41
+ */
42
+ export interface HistogramStats {
43
+ count: number;
44
+ min: number;
45
+ max: number;
46
+ sum: number;
47
+ }
48
+ /**
49
+ * Collection of histogram results keyed by histogram name
50
+ */
51
+ type DiagnosticsHistograms = Record<string, HistogramResult>;
52
+ /**
53
+ * Collection of histogram stats keyed by histogram name (internal use for memory + persistence storage)
54
+ */
55
+ type DiagnosticsHistogramStats = Record<string, HistogramStats>;
56
+ /**
57
+ * Complete diagnostics payload sent to backend
58
+ */
59
+ interface FlushPayload {
60
+ readonly tags: DiagnosticsTags;
61
+ readonly histogram: DiagnosticsHistograms;
62
+ readonly counters: DiagnosticsCounters;
63
+ readonly events: readonly DiagnosticsEvent[];
64
+ }
65
+ /**
66
+ * Amplitude Diagnostics Client
67
+ *
68
+ * A client for collecting and managing diagnostics data including tags, counters,
69
+ * histograms, and events. Data is stored persistently using IndexedDB to survive browser restarts and offline scenarios.
70
+ *
71
+ * Key Features:
72
+ * - IndexedDB storage
73
+ * - Time-based persistent storage flush interval (5 minutes since last flush)
74
+ * - 1 second time-based memory storage flush to persistent storage
75
+ * - Histogram statistics calculation (min, max, avg)
76
+ */
77
+ export interface IDiagnosticsClient {
78
+ /**
79
+ * Set or update a tag
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * // Set environment tags
84
+ * diagnostics.setTag('library', 'amplitude-typescript/2.0.0');
85
+ * diagnostics.setTag('user_agent', navigator.userAgent);
86
+ * ```
87
+ */
88
+ setTag(name: string, value: string): void;
89
+ /**
90
+ * Increment a counter. If doesn't exist, create a counter and set value to 1
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * // Track counters
95
+ * diagnostics.increment('analytics.fileNotFound');
96
+ * diagnostics.increment('network.retry', 3);
97
+ * ```
98
+ */
99
+ increment(name: string, size?: number): void;
100
+ /**
101
+ * Record a histogram value
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * // Record performance metrics
106
+ * diagnostics.recordHistogram('sr.time', 5.2);
107
+ * diagnostics.recordHistogram('network.latency', 150);
108
+ * ```
109
+ */
110
+ recordHistogram(name: string, value: number): void;
111
+ /**
112
+ * Record an event
113
+ *
114
+ * @example
115
+ * ```typescript
116
+ * // Record diagnostic events
117
+ * diagnostics.recordEvent('error', {
118
+ * stack_trace: '...',
119
+ * });
120
+ * ```
121
+ */
122
+ recordEvent(name: string, properties: EventProperties): void;
123
+ _flush(): void;
124
+ }
125
+ export declare class DiagnosticsClient implements IDiagnosticsClient {
126
+ storage?: IDiagnosticsStorage;
127
+ logger: ILogger;
128
+ serverUrl: string;
129
+ apiKey: string;
130
+ inMemoryTags: DiagnosticsTags;
131
+ inMemoryCounters: DiagnosticsCounters;
132
+ inMemoryHistograms: DiagnosticsHistogramStats;
133
+ inMemoryEvents: DiagnosticsEvent[];
134
+ saveTimer: ReturnType<typeof setTimeout> | null;
135
+ flushTimer: ReturnType<typeof setTimeout> | null;
136
+ constructor(apiKey: string, logger: ILogger, serverZone?: ServerZoneType);
137
+ setTag(name: string, value: string): void;
138
+ increment(name: string, size?: number): void;
139
+ recordHistogram(name: string, value: number): void;
140
+ recordEvent(name: string, properties: EventProperties): void;
141
+ startTimersIfNeeded(): void;
142
+ saveAllDataToStorage(): Promise<void>;
143
+ _flush(): Promise<void>;
144
+ /**
145
+ * Send diagnostics data to the server
146
+ */
147
+ fetch(payload: FlushPayload): Promise<void>;
148
+ /**
149
+ * Initialize flush interval logic.
150
+ * Check if 5 minutes has passed since last flush, if so flush immediately.
151
+ * Otherwise set a timer to flush when the interval is reached.
152
+ */
153
+ initializeFlushInterval(): Promise<void>;
154
+ }
155
+ export {};
156
+ //# sourceMappingURL=diagnostics-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics-client.d.ts","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAsB,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAChF,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtD,eAAO,MAAM,gBAAgB,OAAO,CAAC;AACrC,eAAO,MAAM,iBAAiB,QAAgB,CAAC;AAC/C,eAAO,MAAM,yBAAyB,gEAAgE,CAAC;AACvG,eAAO,MAAM,yBAAyB,mEAAmE,CAAC;AAG1G,eAAO,MAAM,wBAAwB,QAAQ,CAAC;AAC9C,eAAO,MAAM,+BAA+B,KAAK,CAAC;AAIlD;;GAEG;AACH,KAAK,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAE9C;;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CA6B9B"}
@@ -0,0 +1,305 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DiagnosticsClient = exports.MAX_MEMORY_STORAGE_EVENTS_COUNT = exports.MAX_MEMORY_STORAGE_COUNT = exports.DIAGNOSTICS_EU_SERVER_URL = exports.DIAGNOSTICS_US_SERVER_URL = exports.FLUSH_INTERVAL_MS = exports.SAVE_INTERVAL_MS = void 0;
4
+ var tslib_1 = require("tslib");
5
+ var diagnostics_storage_1 = require("./diagnostics-storage");
6
+ var global_scope_1 = require("../global-scope");
7
+ exports.SAVE_INTERVAL_MS = 1000; // 1 second
8
+ exports.FLUSH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
9
+ exports.DIAGNOSTICS_US_SERVER_URL = 'https://diagnostics.prod.us-west-2.amplitude.com/v1/capture';
10
+ exports.DIAGNOSTICS_EU_SERVER_URL = 'https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture';
11
+ // In-memory storage limits
12
+ exports.MAX_MEMORY_STORAGE_COUNT = 10000; // for tags, counters, histograms separately
13
+ exports.MAX_MEMORY_STORAGE_EVENTS_COUNT = 10;
14
+ var DiagnosticsClient = /** @class */ (function () {
15
+ function DiagnosticsClient(apiKey, logger, serverZone) {
16
+ if (serverZone === void 0) { serverZone = 'US'; }
17
+ // In-memory storages
18
+ this.inMemoryTags = {};
19
+ this.inMemoryCounters = {};
20
+ this.inMemoryHistograms = {};
21
+ this.inMemoryEvents = [];
22
+ // Timer for 1-second persistence
23
+ this.saveTimer = null;
24
+ // Timer for flush interval
25
+ this.flushTimer = null;
26
+ this.apiKey = apiKey;
27
+ this.logger = logger;
28
+ this.serverUrl = serverZone === 'US' ? exports.DIAGNOSTICS_US_SERVER_URL : exports.DIAGNOSTICS_EU_SERVER_URL;
29
+ if (diagnostics_storage_1.DiagnosticsStorage.isSupported()) {
30
+ this.storage = new diagnostics_storage_1.DiagnosticsStorage(apiKey, logger);
31
+ }
32
+ else {
33
+ this.logger.debug('DiagnosticsClient: IndexedDB is not supported');
34
+ }
35
+ void this.initializeFlushInterval();
36
+ }
37
+ DiagnosticsClient.prototype.setTag = function (name, value) {
38
+ if (!this.storage) {
39
+ return;
40
+ }
41
+ if (Object.keys(this.inMemoryTags).length >= exports.MAX_MEMORY_STORAGE_COUNT) {
42
+ this.logger.debug('DiagnosticsClient: Early return setTags as reaching memory limit');
43
+ return;
44
+ }
45
+ this.inMemoryTags[name] = value;
46
+ this.startTimersIfNeeded();
47
+ };
48
+ DiagnosticsClient.prototype.increment = function (name, size) {
49
+ if (size === void 0) { size = 1; }
50
+ if (!this.storage) {
51
+ return;
52
+ }
53
+ if (Object.keys(this.inMemoryCounters).length >= exports.MAX_MEMORY_STORAGE_COUNT) {
54
+ this.logger.debug('DiagnosticsClient: Early return increment as reaching memory limit');
55
+ return;
56
+ }
57
+ this.inMemoryCounters[name] = (this.inMemoryCounters[name] || 0) + size;
58
+ this.startTimersIfNeeded();
59
+ };
60
+ DiagnosticsClient.prototype.recordHistogram = function (name, value) {
61
+ if (!this.storage) {
62
+ return;
63
+ }
64
+ if (Object.keys(this.inMemoryHistograms).length >= exports.MAX_MEMORY_STORAGE_COUNT) {
65
+ this.logger.debug('DiagnosticsClient: Early return recordHistogram as reaching memory limit');
66
+ return;
67
+ }
68
+ var existing = this.inMemoryHistograms[name];
69
+ if (existing) {
70
+ // Update existing stats incrementally
71
+ existing.count += 1;
72
+ existing.min = Math.min(existing.min, value);
73
+ existing.max = Math.max(existing.max, value);
74
+ existing.sum += value;
75
+ }
76
+ else {
77
+ // Create new stats
78
+ this.inMemoryHistograms[name] = {
79
+ count: 1,
80
+ min: value,
81
+ max: value,
82
+ sum: value,
83
+ };
84
+ }
85
+ this.startTimersIfNeeded();
86
+ };
87
+ DiagnosticsClient.prototype.recordEvent = function (name, properties) {
88
+ if (!this.storage) {
89
+ return;
90
+ }
91
+ if (this.inMemoryEvents.length >= exports.MAX_MEMORY_STORAGE_EVENTS_COUNT) {
92
+ this.logger.debug('DiagnosticsClient: Early return recordEvent as reaching memory limit');
93
+ return;
94
+ }
95
+ this.inMemoryEvents.push({
96
+ event_name: name,
97
+ time: Date.now(),
98
+ event_properties: properties,
99
+ });
100
+ this.startTimersIfNeeded();
101
+ };
102
+ DiagnosticsClient.prototype.startTimersIfNeeded = function () {
103
+ var _this = this;
104
+ if (!this.saveTimer) {
105
+ this.saveTimer = setTimeout(function () {
106
+ _this.saveAllDataToStorage()
107
+ .catch(function (error) {
108
+ _this.logger.debug('DiagnosticsClient: Failed to save all data to storage', error);
109
+ })
110
+ .finally(function () {
111
+ _this.saveTimer = null;
112
+ });
113
+ }, exports.SAVE_INTERVAL_MS);
114
+ }
115
+ if (!this.flushTimer) {
116
+ this.flushTimer = setTimeout(function () {
117
+ _this._flush()
118
+ .catch(function (error) {
119
+ _this.logger.debug('DiagnosticsClient: Failed to flush', error);
120
+ })
121
+ .finally(function () {
122
+ _this.flushTimer = null;
123
+ });
124
+ }, exports.FLUSH_INTERVAL_MS);
125
+ }
126
+ };
127
+ DiagnosticsClient.prototype.saveAllDataToStorage = function () {
128
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
129
+ var tagsToSave, countersToSave, histogramsToSave, eventsToSave;
130
+ return tslib_1.__generator(this, function (_a) {
131
+ switch (_a.label) {
132
+ case 0:
133
+ if (!this.storage) {
134
+ return [2 /*return*/];
135
+ }
136
+ tagsToSave = tslib_1.__assign({}, this.inMemoryTags);
137
+ countersToSave = tslib_1.__assign({}, this.inMemoryCounters);
138
+ histogramsToSave = tslib_1.__assign({}, this.inMemoryHistograms);
139
+ eventsToSave = tslib_1.__spreadArray([], tslib_1.__read(this.inMemoryEvents), false);
140
+ this.inMemoryEvents = [];
141
+ this.inMemoryTags = {};
142
+ this.inMemoryCounters = {};
143
+ this.inMemoryHistograms = {};
144
+ return [4 /*yield*/, Promise.all([
145
+ this.storage.setTags(tagsToSave),
146
+ this.storage.incrementCounters(countersToSave),
147
+ this.storage.setHistogramStats(histogramsToSave),
148
+ this.storage.addEventRecords(eventsToSave),
149
+ ])];
150
+ case 1:
151
+ _a.sent();
152
+ return [2 /*return*/];
153
+ }
154
+ });
155
+ });
156
+ };
157
+ DiagnosticsClient.prototype._flush = function () {
158
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
159
+ var _a, tagRecords, counterRecords, histogramStatsRecords, eventRecords, tags, counters, histogram, events, payload;
160
+ return tslib_1.__generator(this, function (_b) {
161
+ switch (_b.label) {
162
+ case 0:
163
+ if (!this.storage) {
164
+ return [2 /*return*/];
165
+ }
166
+ return [4 /*yield*/, this.saveAllDataToStorage()];
167
+ case 1:
168
+ _b.sent();
169
+ this.saveTimer = null;
170
+ this.flushTimer = null;
171
+ return [4 /*yield*/, this.storage.getAllAndClear()];
172
+ case 2:
173
+ _a = _b.sent(), tagRecords = _a.tags, counterRecords = _a.counters, histogramStatsRecords = _a.histogramStats, eventRecords = _a.events;
174
+ // Update the last flush timestamp
175
+ void this.storage.setLastFlushTimestamp(Date.now());
176
+ tags = {};
177
+ tagRecords.forEach(function (record) {
178
+ tags[record.key] = record.value;
179
+ });
180
+ counters = {};
181
+ counterRecords.forEach(function (record) {
182
+ counters[record.key] = record.value;
183
+ });
184
+ histogram = {};
185
+ histogramStatsRecords.forEach(function (stats) {
186
+ histogram[stats.key] = {
187
+ count: stats.count,
188
+ min: stats.min,
189
+ max: stats.max,
190
+ avg: Math.round((stats.sum / stats.count) * 100) / 100, // round the average to 2 decimal places.
191
+ };
192
+ });
193
+ events = eventRecords.map(function (record) { return ({
194
+ event_name: record.event_name,
195
+ time: record.time,
196
+ event_properties: record.event_properties,
197
+ }); });
198
+ // Early return if all data collections are empty
199
+ if (Object.keys(tags).length === 0 &&
200
+ Object.keys(counters).length === 0 &&
201
+ Object.keys(histogram).length === 0 &&
202
+ events.length === 0) {
203
+ return [2 /*return*/];
204
+ }
205
+ payload = {
206
+ tags: tags,
207
+ histogram: histogram,
208
+ counters: counters,
209
+ events: events,
210
+ };
211
+ // Send payload to diagnostics server
212
+ void this.fetch(payload);
213
+ return [2 /*return*/];
214
+ }
215
+ });
216
+ });
217
+ };
218
+ /**
219
+ * Send diagnostics data to the server
220
+ */
221
+ DiagnosticsClient.prototype.fetch = function (payload) {
222
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
223
+ var response, error_1;
224
+ return tslib_1.__generator(this, function (_a) {
225
+ switch (_a.label) {
226
+ case 0:
227
+ _a.trys.push([0, 2, , 3]);
228
+ if (!(0, global_scope_1.getGlobalScope)()) {
229
+ throw new Error('DiagnosticsClient: Fetch is not supported');
230
+ }
231
+ return [4 /*yield*/, fetch(this.serverUrl, {
232
+ method: 'POST',
233
+ headers: {
234
+ 'X-ApiKey': this.apiKey,
235
+ 'Content-Type': 'application/json',
236
+ },
237
+ body: JSON.stringify(payload),
238
+ })];
239
+ case 1:
240
+ response = _a.sent();
241
+ if (!response.ok) {
242
+ this.logger.debug('DiagnosticsClient: Failed to send diagnostics data.');
243
+ return [2 /*return*/];
244
+ }
245
+ this.logger.debug('DiagnosticsClient: Successfully sent diagnostics data');
246
+ return [3 /*break*/, 3];
247
+ case 2:
248
+ error_1 = _a.sent();
249
+ this.logger.debug('DiagnosticsClient: Failed to send diagnostics data. ', error_1);
250
+ return [3 /*break*/, 3];
251
+ case 3: return [2 /*return*/];
252
+ }
253
+ });
254
+ });
255
+ };
256
+ /**
257
+ * Initialize flush interval logic.
258
+ * Check if 5 minutes has passed since last flush, if so flush immediately.
259
+ * Otherwise set a timer to flush when the interval is reached.
260
+ */
261
+ DiagnosticsClient.prototype.initializeFlushInterval = function () {
262
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
263
+ var now, lastFlushTimestamp, timeSinceLastFlush, remainingTime;
264
+ var _this = this;
265
+ return tslib_1.__generator(this, function (_a) {
266
+ switch (_a.label) {
267
+ case 0:
268
+ if (!this.storage) {
269
+ return [2 /*return*/];
270
+ }
271
+ now = Date.now();
272
+ return [4 /*yield*/, this.storage.getLastFlushTimestamp()];
273
+ case 1:
274
+ lastFlushTimestamp = (_a.sent()) || -1;
275
+ timeSinceLastFlush = now - lastFlushTimestamp;
276
+ // If last flush timestamp is -1, it means this is a new client
277
+ if (lastFlushTimestamp === -1) {
278
+ return [2 /*return*/];
279
+ }
280
+ else if (timeSinceLastFlush >= exports.FLUSH_INTERVAL_MS) {
281
+ // More than 5 minutes has passed, flush immediately
282
+ void this._flush();
283
+ return [2 /*return*/];
284
+ }
285
+ else {
286
+ remainingTime = exports.FLUSH_INTERVAL_MS - timeSinceLastFlush;
287
+ this.flushTimer = setTimeout(function () {
288
+ _this._flush()
289
+ .catch(function (error) {
290
+ _this.logger.debug('DiagnosticsClient: Failed to flush', error);
291
+ })
292
+ .finally(function () {
293
+ _this.flushTimer = null;
294
+ });
295
+ }, remainingTime);
296
+ }
297
+ return [2 /*return*/];
298
+ }
299
+ });
300
+ });
301
+ };
302
+ return DiagnosticsClient;
303
+ }());
304
+ exports.DiagnosticsClient = DiagnosticsClient;
305
+ //# sourceMappingURL=diagnostics-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics-client.js","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-client.ts"],"names":[],"mappings":";;;;AACA,6DAAgF;AAEhF,gDAAiD;AAEpC,QAAA,gBAAgB,GAAG,IAAI,CAAC,CAAC,WAAW;AACpC,QAAA,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,YAAY;AAC/C,QAAA,yBAAyB,GAAG,6DAA6D,CAAC;AAC1F,QAAA,yBAAyB,GAAG,gEAAgE,CAAC;AAE1G,2BAA2B;AACd,QAAA,wBAAwB,GAAG,KAAK,CAAC,CAAC,4CAA4C;AAC9E,QAAA,+BAA+B,GAAG,EAAE,CAAC;AAwIlD;IAiBE,2BAAY,MAAc,EAAE,MAAe,EAAE,UAAiC;QAAjC,2BAAA,EAAA,iBAAiC;QAX9E,qBAAqB;QACrB,iBAAY,GAAoB,EAAE,CAAC;QACnC,qB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B,GAAG,CAAC,SAA0C,CAAC,IAAI,CAAC,CAAC;wBACvE,kBAAkB,GAAG,GAAG,GAAG,kBAAkB,CAAC;wBAEpD,+DAA+D;wBAC/D,IAAI,kBAAkB,KAAK,CAAC,CAAC,EAAE;4BAC7B,sBAAO;yBACR;6BAAM,IAAI,kBAAkB,IAAI,yBAAiB,EAAE;4BAClD,oDAAoD;4BACpD,KAAK,IAAI,CAAC,MAAM,EAAE,CAAC;4BACnB,sBAAO;yBACR;6BAAM;4BAEC,aAAa,GAAG,yBAAiB,GAAG,kBAAkB,CAAC;4BAC7D,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;gCAC3B,KAAI,CAAC,MAAM,EAAE;qCACV,KAAK,CAAC,UAAC,KAAK;oCACX,KAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;gCACjE,CAAC,CAAC;qCACD,OAAO,CAAC;oCACP,KAAI,CAAC,UAAU,GAAG,IAAI,CAAC;gCACzB,CAAC,CAAC,CAAC;4BACP,CAAC,EAAE,aAAa,CAAC,CAAC;yBACnB;;;;;KACF;IACH,wBAAC;AAAD,CAAC,AA9RD,IA8RC;AA9RY,8CAAiB","sourcesContent":["import { ILogger } from '../logger';\nimport { DiagnosticsStorage, IDiagnosticsStorage } from './diagnostics-storage';\nimport { ServerZoneType } from '../types/server-zone';\nimport { getGlobalScope } from '../global-scope';\n\nexport const SAVE_INTERVAL_MS = 1000; // 1 second\nexport const FLUSH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\nexport const DIAGNOSTICS_US_SERVER_URL = 'https://diagnostics.prod.us-west-2.amplitude.com/v1/capture';\nexport const DIAGNOSTICS_EU_SERVER_URL = 'https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture';\n\n// In-memory storage limits\nexport const MAX_MEMORY_STORAGE_COUNT = 10000; // for tags, counters, histograms separately\nexport const MAX_MEMORY_STORAGE_EVENTS_COUNT = 10;\n\n// === Core Data Types ===\n\n/**\n * Key-value pairs for environment/context information\n */\ntype DiagnosticsTags = Record<string, string>;\n\n/**\n * Numeric counters that can be incremented\n */\ntype DiagnosticsCounters = Record<string, number>;\n\n/**\n * Properties for diagnostic events\n */\ntype EventProperties = Record<string, any>;\n\n/**\n * Individual diagnostic event\n */\ninterface DiagnosticsEvent {\n readonly event_name: string;\n readonly time: number;\n readonly event_properties: EventProperties;\n}\n\n/**\n * Computed histogram statistics for final payload\n */\ninterface HistogramResult {\n readonly count: number;\n readonly min: number;\n readonly max: number;\n readonly avg: number;\n}\n\n/**\n * Internal histogram statistics with sum for efficient incremental updates\n */\nexport interface HistogramStats {\n count: number;\n min: number;\n max: number;\n sum: number; // Used for avg calculation\n}\n\n/**\n * Collection of histogram results keyed by histogram name\n */\ntype DiagnosticsHistograms = Record<string, HistogramResult>;\n\n/**\n * Collection of histogram stats keyed by histogram name (internal use for memory + persistence storage)\n */\ntype DiagnosticsHistogramStats = Record<string, HistogramStats>;\n\n// === Payload Types ===\n\n/**\n * Complete diagnostics payload sent to backend\n */\ninterface FlushPayload {\n readonly tags: DiagnosticsTags;\n readonly histogram: DiagnosticsHistograms;\n readonly counters: DiagnosticsCounters;\n readonly events: readonly DiagnosticsEvent[];\n}\n\n/**\n * Amplitude Diagnostics Client\n *\n * A client for collecting and managing diagnostics data including tags, counters,\n * histograms, and events. Data is stored persistently using IndexedDB to survive browser restarts and offline scenarios.\n *\n * Key Features:\n * - IndexedDB storage\n * - Time-based persistent storage flush interval (5 minutes since last flush)\n * - 1 second time-based memory storage flush to persistent storage\n * - Histogram statistics calculation (min, max, avg)\n */\nexport interface IDiagnosticsClient {\n /**\n * Set or update a tag\n *\n * @example\n * ```typescript\n * // Set environment tags\n * diagnostics.setTag('library', 'amplitude-typescript/2.0.0');\n * diagnostics.setTag('user_agent', navigator.userAgent);\n * ```\n */\n setTag(name: string, value: string): void;\n\n /**\n * Increment a counter. If doesn't exist, create a counter and set value to 1\n *\n * @example\n * ```typescript\n * // Track counters\n * diagnostics.increment('analytics.fileNotFound');\n * diagnostics.increment('network.retry', 3);\n * ```\n */\n increment(name: string, size?: number): void;\n\n /**\n * Record a histogram value\n *\n * @example\n * ```typescript\n * // Record performance metrics\n * diagnostics.recordHistogram('sr.time', 5.2);\n * diagnostics.recordHistogram('network.latency', 150);\n * ```\n */\n recordHistogram(name: string, value: number): void;\n\n /**\n * Record an event\n *\n * @example\n * ```typescript\n * // Record diagnostic events\n * diagnostics.recordEvent('error', {\n * stack_trace: '...',\n * });\n * ```\n */\n recordEvent(name: string, properties: EventProperties): void;\n\n // Flush storage\n _flush(): void;\n}\n\nexport class DiagnosticsClient implements IDiagnosticsClient {\n storage?: IDiagnosticsStorage;\n logger: ILogger;\n serverUrl: string;\n apiKey: string;\n\n // In-memory storages\n inMemoryTags: DiagnosticsTags = {};\n inMemoryCounters: DiagnosticsCounters = {};\n inMemoryHistograms: DiagnosticsHistogramStats = {};\n inMemoryEvents: DiagnosticsEvent[] = [];\n\n // Timer for 1-second persistence\n saveTimer: ReturnType<typeof setTimeout> | null = null;\n // Timer for flush interval\n flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(apiKey: string, logger: ILogger, serverZone: ServerZoneType = 'US') {\n this.apiKey = apiKey;\n this.logger = logger;\n this.serverUrl = serverZone === 'US' ? DIAGNOSTICS_US_SERVER_URL : DIAGNOSTICS_EU_SERVER_URL;\n\n if (DiagnosticsStorage.isSupported()) {\n this.storage = new DiagnosticsStorage(apiKey, logger);\n } else {\n this.logger.debug('DiagnosticsClient: IndexedDB is not supported');\n }\n\n void this.initializeFlushInterval();\n }\n\n setTag(name: string, value: string) {\n if (!this.storage) {\n return;\n }\n\n if (Object.keys(this.inMemoryTags).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return setTags as reaching memory limit');\n return;\n }\n\n this.inMemoryTags[name] = value;\n this.startTimersIfNeeded();\n }\n\n increment(name: string, size = 1) {\n if (!this.storage) {\n return;\n }\n\n if (Object.keys(this.inMemoryCounters).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return increment as reaching memory limit');\n return;\n }\n\n this.inMemoryCounters[name] = (this.inMemoryCounters[name] || 0) + size;\n this.startTimersIfNeeded();\n }\n\n recordHistogram(name: string, value: number) {\n if (!this.storage) {\n return;\n }\n\n if (Object.keys(this.inMemoryHistograms).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordHistogram as reaching memory limit');\n return;\n }\n\n const existing = this.inMemoryHistograms[name];\n if (existing) {\n // Update existing stats incrementally\n existing.count += 1;\n existing.min = Math.min(existing.min, value);\n existing.max = Math.max(existing.max, value);\n existing.sum += value;\n } else {\n // Create new stats\n this.inMemoryHistograms[name] = {\n count: 1,\n min: value,\n max: value,\n sum: value,\n };\n }\n this.startTimersIfNeeded();\n }\n\n recordEvent(name: string, properties: EventProperties) {\n if (!this.storage) {\n return;\n }\n\n if (this.inMemoryEvents.length >= MAX_MEMORY_STORAGE_EVENTS_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordEvent as reaching memory limit');\n return;\n }\n\n this.inMemoryEvents.push({\n event_name: name,\n time: Date.now(),\n event_properties: properties,\n });\n this.startTimersIfNeeded();\n }\n\n startTimersIfNeeded() {\n if (!this.saveTimer) {\n this.saveTimer = setTimeout(() => {\n this.saveAllDataToStorage()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to save all data to storage', error);\n })\n .finally(() => {\n this.saveTimer = null;\n });\n }, SAVE_INTERVAL_MS);\n }\n\n if (!this.flushTimer) {\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, FLUSH_INTERVAL_MS);\n }\n }\n\n async saveAllDataToStorage() {\n if (!this.storage) {\n return;\n }\n const tagsToSave = { ...this.inMemoryTags };\n const countersToSave = { ...this.inMemoryCounters };\n const histogramsToSave = { ...this.inMemoryHistograms };\n const eventsToSave = [...this.inMemoryEvents];\n\n this.inMemoryEvents = [];\n this.inMemoryTags = {};\n this.inMemoryCounters = {};\n this.inMemoryHistograms = {};\n\n await Promise.all([\n this.storage.setTags(tagsToSave),\n this.storage.incrementCounters(countersToSave),\n this.storage.setHistogramStats(histogramsToSave),\n this.storage.addEventRecords(eventsToSave),\n ]);\n }\n\n async _flush() {\n if (!this.storage) {\n return;\n }\n\n await this.saveAllDataToStorage();\n this.saveTimer = null;\n this.flushTimer = null;\n\n // Get all data from storage and clear it\n const {\n tags: tagRecords,\n counters: counterRecords,\n histogramStats: histogramStatsRecords,\n events: eventRecords,\n } = await this.storage.getAllAndClear();\n\n // Update the last flush timestamp\n void this.storage.setLastFlushTimestamp(Date.now());\n\n // Convert metrics to the expected format\n const tags: DiagnosticsTags = {};\n tagRecords.forEach((record) => {\n tags[record.key] = record.value;\n });\n\n const counters: DiagnosticsCounters = {};\n counterRecords.forEach((record) => {\n counters[record.key] = record.value;\n });\n\n const histogram: DiagnosticsHistograms = {};\n histogramStatsRecords.forEach((stats) => {\n histogram[stats.key] = {\n count: stats.count,\n min: stats.min,\n max: stats.max,\n avg: Math.round((stats.sum / stats.count) * 100) / 100, // round the average to 2 decimal places.\n };\n });\n\n const events: DiagnosticsEvent[] = eventRecords.map((record) => ({\n event_name: record.event_name,\n time: record.time,\n event_properties: record.event_properties,\n }));\n\n // Early return if all data collections are empty\n if (\n Object.keys(tags).length === 0 &&\n Object.keys(counters).length === 0 &&\n Object.keys(histogram).length === 0 &&\n events.length === 0\n ) {\n return;\n }\n\n // Create flush payload\n const payload: FlushPayload = {\n tags,\n histogram,\n counters,\n events,\n };\n\n // Send payload to diagnostics server\n void this.fetch(payload);\n }\n\n /**\n * Send diagnostics data to the server\n */\n async fetch(payload: FlushPayload) {\n try {\n if (!getGlobalScope()) {\n throw new Error('DiagnosticsClient: Fetch is not supported');\n }\n\n const response = await fetch(this.serverUrl, {\n method: 'POST',\n headers: {\n 'X-ApiKey': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data.');\n return;\n }\n\n this.logger.debug('DiagnosticsClient: Successfully sent diagnostics data');\n } catch (error) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data. ', error);\n }\n }\n\n /**\n * Initialize flush interval logic.\n * Check if 5 minutes has passed since last flush, if so flush immediately.\n * Otherwise set a timer to flush when the interval is reached.\n */\n async initializeFlushInterval() {\n if (!this.storage) {\n return;\n }\n const now = Date.now();\n const lastFlushTimestamp = (await this.storage.getLastFlushTimestamp()) || -1;\n const timeSinceLastFlush = now - lastFlushTimestamp;\n\n // If last flush timestamp is -1, it means this is a new client\n if (lastFlushTimestamp === -1) {\n return;\n } else if (timeSinceLastFlush >= FLUSH_INTERVAL_MS) {\n // More than 5 minutes has passed, flush immediately\n void this._flush();\n return;\n } else {\n // Set timer for remaining time\n const remainingTime = FLUSH_INTERVAL_MS - timeSinceLastFlush;\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, remainingTime);\n }\n }\n}\n"]}
@@ -0,0 +1,123 @@
1
+ import { ILogger } from '../logger';
2
+ import { HistogramStats } from './diagnostics-client';
3
+ export declare const TABLE_NAMES: {
4
+ readonly TAGS: "tags";
5
+ readonly COUNTERS: "counters";
6
+ readonly HISTOGRAMS: "histograms";
7
+ readonly EVENTS: "events";
8
+ readonly INTERNAL: "internal";
9
+ };
10
+ export declare const INTERNAL_KEYS: {
11
+ readonly LAST_FLUSH_TIMESTAMP: "last_flush_timestamp";
12
+ };
13
+ export interface TagRecord {
14
+ key: string;
15
+ value: string;
16
+ }
17
+ export interface CounterRecord {
18
+ key: string;
19
+ value: number;
20
+ }
21
+ export interface HistogramRecord {
22
+ key: string;
23
+ count: number;
24
+ min: number;
25
+ max: number;
26
+ sum: number;
27
+ }
28
+ export interface EventRecord {
29
+ id?: number;
30
+ event_name: string;
31
+ time: number;
32
+ event_properties: Record<string, any>;
33
+ }
34
+ export interface InternalRecord {
35
+ key: string;
36
+ value: string;
37
+ }
38
+ export interface IDiagnosticsStorage {
39
+ /**
40
+ * Set multiple tags in a single transaction (batch operation)
41
+ * Promise never rejects - errors are logged and operation continues gracefully
42
+ */
43
+ setTags(tags: Record<string, string>): Promise<void>;
44
+ /**
45
+ * Increment multiple counters in a single transaction (batch operation)
46
+ * Uses read-modify-write pattern to accumulate with existing values
47
+ * Promise never rejects - errors are logged and operation continues gracefully
48
+ */
49
+ incrementCounters(counters: Record<string, number>): Promise<void>;
50
+ /**
51
+ * Set multiple histogram stats in a single transaction (batch operation)
52
+ * Uses read-modify-write pattern to accumulate count/sum and update min/max with existing values
53
+ * Promise never rejects - errors are logged and operation continues gracefully
54
+ */
55
+ setHistogramStats(histogramStats: Record<string, {
56
+ count: number;
57
+ min: number;
58
+ max: number;
59
+ sum: number;
60
+ }>): Promise<void>;
61
+ /**
62
+ * Add multiple event records in a single transaction (batch operation)
63
+ * Promise never rejects - errors are logged and operation continues gracefully
64
+ */
65
+ addEventRecords(events: Array<{
66
+ event_name: string;
67
+ time: number;
68
+ event_properties: Record<string, any>;
69
+ }>): Promise<void>;
70
+ setLastFlushTimestamp(timestamp: number): Promise<void>;
71
+ getLastFlushTimestamp(): Promise<number | undefined>;
72
+ /**
73
+ * Get all data except internal data from storage and clear it
74
+ */
75
+ getAllAndClear(): Promise<{
76
+ tags: TagRecord[];
77
+ counters: CounterRecord[];
78
+ histogramStats: HistogramRecord[];
79
+ events: EventRecord[];
80
+ }>;
81
+ }
82
+ /**
83
+ * Purpose-specific IndexedDB storage for diagnostics data
84
+ * Provides optimized methods for each type of diagnostics data
85
+ */
86
+ export declare class DiagnosticsStorage implements IDiagnosticsStorage {
87
+ dbPromise: Promise<IDBDatabase> | null;
88
+ dbName: string;
89
+ logger: ILogger;
90
+ constructor(apiKey: string, logger: ILogger);
91
+ /**
92
+ * Check if IndexedDB is supported in the current environment
93
+ * @returns true if IndexedDB is available, false otherwise
94
+ */
95
+ static isSupported(): boolean;
96
+ getDB(): Promise<IDBDatabase>;
97
+ openDB(): Promise<IDBDatabase>;
98
+ createTables(db: IDBDatabase): void;
99
+ setTags(tags: Record<string, string>): Promise<void>;
100
+ incrementCounters(counters: Record<string, number>): Promise<void>;
101
+ setHistogramStats(histogramStats: Record<string, HistogramStats>): Promise<void>;
102
+ addEventRecords(events: Array<{
103
+ event_name: string;
104
+ time: number;
105
+ event_properties: Record<string, any>;
106
+ }>): Promise<void>;
107
+ setInternal(key: string, value: string): Promise<void>;
108
+ getInternal(key: string): Promise<InternalRecord | undefined>;
109
+ getLastFlushTimestamp(): Promise<number | undefined>;
110
+ setLastFlushTimestamp(timestamp: number): Promise<void>;
111
+ clearTable(transaction: IDBTransaction, tableName: string): Promise<void>;
112
+ getAllAndClear(): Promise<{
113
+ tags: TagRecord[];
114
+ counters: CounterRecord[];
115
+ histogramStats: HistogramRecord[];
116
+ events: EventRecord[];
117
+ }>;
118
+ /**
119
+ * Helper method to get all records from a store within a transaction
120
+ */
121
+ private getAllFromStore;
122
+ }
123
+ //# sourceMappingURL=diagnostics-storage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics-storage.d.ts","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-storage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAQtD,eAAO,MAAM,WAAW;;;;;;CAMd,CAAC;AAGX,eAAO,MAAM,aAAa;;CAEhB,CAAC;AAGX,MAAM,WAAW,SAAS;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,aAAa;IAC5B,GAAG,EAA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