@amplitude/analytics-core 2.26.0 → 2.26.2

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 (51) hide show
  1. package/lib/cjs/diagnostics/diagnostics-client.d.ts +32 -1
  2. package/lib/cjs/diagnostics/diagnostics-client.d.ts.map +1 -1
  3. package/lib/cjs/diagnostics/diagnostics-client.js +48 -23
  4. package/lib/cjs/diagnostics/diagnostics-client.js.map +1 -1
  5. package/lib/cjs/index.d.ts +2 -0
  6. package/lib/cjs/index.d.ts.map +1 -1
  7. package/lib/cjs/index.js +7 -5
  8. package/lib/cjs/index.js.map +1 -1
  9. package/lib/cjs/network-observer.d.ts.map +1 -1
  10. package/lib/cjs/network-observer.js +3 -5
  11. package/lib/cjs/network-observer.js.map +1 -1
  12. package/lib/cjs/types/amplitude-context.d.ts +7 -5
  13. package/lib/cjs/types/amplitude-context.d.ts.map +1 -1
  14. package/lib/cjs/types/amplitude-context.js +0 -30
  15. package/lib/cjs/types/amplitude-context.js.map +1 -1
  16. package/lib/cjs/types/client/browser-client.d.ts +9 -0
  17. package/lib/cjs/types/client/browser-client.d.ts.map +1 -1
  18. package/lib/cjs/types/client/browser-client.js.map +1 -1
  19. package/lib/cjs/types/config/browser-config.d.ts +10 -0
  20. package/lib/cjs/types/config/browser-config.d.ts.map +1 -1
  21. package/lib/cjs/types/config/browser-config.js.map +1 -1
  22. package/lib/cjs/utils/sampling.d.ts +3 -0
  23. package/lib/cjs/utils/sampling.d.ts.map +1 -0
  24. package/lib/cjs/utils/sampling.js +24 -0
  25. package/lib/cjs/utils/sampling.js.map +1 -0
  26. package/lib/esm/diagnostics/diagnostics-client.d.ts +32 -1
  27. package/lib/esm/diagnostics/diagnostics-client.d.ts.map +1 -1
  28. package/lib/esm/diagnostics/diagnostics-client.js +48 -23
  29. package/lib/esm/diagnostics/diagnostics-client.js.map +1 -1
  30. package/lib/esm/index.d.ts +2 -0
  31. package/lib/esm/index.d.ts.map +1 -1
  32. package/lib/esm/index.js +2 -2
  33. package/lib/esm/index.js.map +1 -1
  34. package/lib/esm/network-observer.d.ts.map +1 -1
  35. package/lib/esm/network-observer.js +3 -5
  36. package/lib/esm/network-observer.js.map +1 -1
  37. package/lib/esm/types/amplitude-context.d.ts +7 -5
  38. package/lib/esm/types/amplitude-context.d.ts.map +1 -1
  39. package/lib/esm/types/amplitude-context.js +1 -29
  40. package/lib/esm/types/amplitude-context.js.map +1 -1
  41. package/lib/esm/types/client/browser-client.d.ts +9 -0
  42. package/lib/esm/types/client/browser-client.d.ts.map +1 -1
  43. package/lib/esm/types/client/browser-client.js.map +1 -1
  44. package/lib/esm/types/config/browser-config.d.ts +10 -0
  45. package/lib/esm/types/config/browser-config.d.ts.map +1 -1
  46. package/lib/esm/types/config/browser-config.js.map +1 -1
  47. package/lib/esm/utils/sampling.d.ts +3 -0
  48. package/lib/esm/utils/sampling.d.ts.map +1 -0
  49. package/lib/esm/utils/sampling.js +19 -0
  50. package/lib/esm/utils/sampling.js.map +1 -0
  51. package/package.json +2 -2
@@ -121,19 +121,45 @@ export interface IDiagnosticsClient {
121
121
  */
122
122
  recordEvent(name: string, properties: EventProperties): void;
123
123
  _flush(): void;
124
+ /**
125
+ * Sets the sample rate for diagnostics.
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * diagnostics.setSampleRate(0.5);
130
+ * ```
131
+ */
132
+ _setSampleRate(sampleRate: number): void;
124
133
  }
125
134
  export declare class DiagnosticsClient implements IDiagnosticsClient {
126
135
  storage?: IDiagnosticsStorage;
127
136
  logger: ILogger;
128
137
  serverUrl: string;
129
138
  apiKey: string;
139
+ shouldTrack: boolean;
140
+ config: {
141
+ enabled: boolean;
142
+ sampleRate: number;
143
+ };
144
+ /**
145
+ * The timestamp when the diagnostics client was initialized.
146
+ * Save in memory to keep lifecycle sample rate calculation consistency.
147
+ */
148
+ startTimestamp: number;
130
149
  inMemoryTags: DiagnosticsTags;
131
150
  inMemoryCounters: DiagnosticsCounters;
132
151
  inMemoryHistograms: DiagnosticsHistogramStats;
133
152
  inMemoryEvents: DiagnosticsEvent[];
134
153
  saveTimer: ReturnType<typeof setTimeout> | null;
135
154
  flushTimer: ReturnType<typeof setTimeout> | null;
136
- constructor(apiKey: string, logger: ILogger, serverZone?: ServerZoneType);
155
+ constructor(apiKey: string, logger: ILogger, serverZone?: ServerZoneType, options?: {
156
+ enabled?: boolean;
157
+ sampleRate?: number;
158
+ });
159
+ /**
160
+ * Check if storage is available and tracking is enabled
161
+ */
162
+ isStorageAndTrackEnabled(): boolean;
137
163
  setTag(name: string, value: string): void;
138
164
  increment(name: string, size?: number): void;
139
165
  recordHistogram(name: string, value: number): void;
@@ -151,6 +177,11 @@ export declare class DiagnosticsClient implements IDiagnosticsClient {
151
177
  * Otherwise set a timer to flush when the interval is reached.
152
178
  */
153
179
  initializeFlushInterval(): Promise<void>;
180
+ /**
181
+ * Helper method to set flush timer with consistent error handling
182
+ */
183
+ private _setFlushTimer;
184
+ _setSampleRate(sampleRate: number): void;
154
185
  }
155
186
  export {};
156
187
  //# sourceMappingURL=diagnostics-client.d.ts.map
@@ -1 +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,M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nostics-storage");
6
6
  var global_scope_1 = require("../global-scope");
7
+ var sampling_1 = require("../utils/sampling");
7
8
  exports.SAVE_INTERVAL_MS = 1000; // 1 second
8
9
  exports.FLUSH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
9
10
  exports.DIAGNOSTICS_US_SERVER_URL = 'https://diagnostics.prod.us-west-2.amplitude.com/v1/capture';
@@ -12,7 +13,7 @@ exports.DIAGNOSTICS_EU_SERVER_URL = 'https://diagnostics.prod.eu-central-1.ampli
12
13
  exports.MAX_MEMORY_STORAGE_COUNT = 10000; // for tags, counters, histograms separately
13
14
  exports.MAX_MEMORY_STORAGE_EVENTS_COUNT = 10;
14
15
  var DiagnosticsClient = /** @class */ (function () {
15
- function DiagnosticsClient(apiKey, logger, serverZone) {
16
+ function DiagnosticsClient(apiKey, logger, serverZone, options) {
16
17
  if (serverZone === void 0) { serverZone = 'US'; }
17
18
  // In-memory storages
18
19
  this.inMemoryTags = {};
@@ -26,6 +27,11 @@ var DiagnosticsClient = /** @class */ (function () {
26
27
  this.apiKey = apiKey;
27
28
  this.logger = logger;
28
29
  this.serverUrl = serverZone === 'US' ? exports.DIAGNOSTICS_US_SERVER_URL : exports.DIAGNOSTICS_EU_SERVER_URL;
30
+ this.logger.debug('DiagnosticsClient: Initializing with options', JSON.stringify(options, null, 2));
31
+ // Diagnostics is enabled by default with sample rate of 0 (no sampling)
32
+ this.config = tslib_1.__assign({ enabled: true, sampleRate: 0 }, options);
33
+ this.startTimestamp = Date.now();
34
+ this.shouldTrack = (0, sampling_1.isTimestampInSample)(this.startTimestamp, this.config.sampleRate) && this.config.enabled;
29
35
  if (diagnostics_storage_1.DiagnosticsStorage.isSupported()) {
30
36
  this.storage = new diagnostics_storage_1.DiagnosticsStorage(apiKey, logger);
31
37
  }
@@ -34,8 +40,14 @@ var DiagnosticsClient = /** @class */ (function () {
34
40
  }
35
41
  void this.initializeFlushInterval();
36
42
  }
43
+ /**
44
+ * Check if storage is available and tracking is enabled
45
+ */
46
+ DiagnosticsClient.prototype.isStorageAndTrackEnabled = function () {
47
+ return Boolean(this.storage) && Boolean(this.shouldTrack);
48
+ };
37
49
  DiagnosticsClient.prototype.setTag = function (name, value) {
38
- if (!this.storage) {
50
+ if (!this.isStorageAndTrackEnabled()) {
39
51
  return;
40
52
  }
41
53
  if (Object.keys(this.inMemoryTags).length >= exports.MAX_MEMORY_STORAGE_COUNT) {
@@ -47,7 +59,7 @@ var DiagnosticsClient = /** @class */ (function () {
47
59
  };
48
60
  DiagnosticsClient.prototype.increment = function (name, size) {
49
61
  if (size === void 0) { size = 1; }
50
- if (!this.storage) {
62
+ if (!this.isStorageAndTrackEnabled()) {
51
63
  return;
52
64
  }
53
65
  if (Object.keys(this.inMemoryCounters).length >= exports.MAX_MEMORY_STORAGE_COUNT) {
@@ -58,7 +70,7 @@ var DiagnosticsClient = /** @class */ (function () {
58
70
  this.startTimersIfNeeded();
59
71
  };
60
72
  DiagnosticsClient.prototype.recordHistogram = function (name, value) {
61
- if (!this.storage) {
73
+ if (!this.isStorageAndTrackEnabled()) {
62
74
  return;
63
75
  }
64
76
  if (Object.keys(this.inMemoryHistograms).length >= exports.MAX_MEMORY_STORAGE_COUNT) {
@@ -85,7 +97,7 @@ var DiagnosticsClient = /** @class */ (function () {
85
97
  this.startTimersIfNeeded();
86
98
  };
87
99
  DiagnosticsClient.prototype.recordEvent = function (name, properties) {
88
- if (!this.storage) {
100
+ if (!this.isStorageAndTrackEnabled()) {
89
101
  return;
90
102
  }
91
103
  if (this.inMemoryEvents.length >= exports.MAX_MEMORY_STORAGE_EVENTS_COUNT) {
@@ -196,10 +208,7 @@ var DiagnosticsClient = /** @class */ (function () {
196
208
  event_properties: record.event_properties,
197
209
  }); });
198
210
  // 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) {
211
+ if (Object.keys(counters).length === 0 && Object.keys(histogram).length === 0 && events.length === 0) {
203
212
  return [2 /*return*/];
204
213
  }
205
214
  payload = {
@@ -260,8 +269,7 @@ var DiagnosticsClient = /** @class */ (function () {
260
269
  */
261
270
  DiagnosticsClient.prototype.initializeFlushInterval = function () {
262
271
  return tslib_1.__awaiter(this, void 0, void 0, function () {
263
- var now, lastFlushTimestamp, timeSinceLastFlush, remainingTime;
264
- var _this = this;
272
+ var now, lastFlushTimestamp, timeSinceLastFlush;
265
273
  return tslib_1.__generator(this, function (_a) {
266
274
  switch (_a.label) {
267
275
  case 0:
@@ -272,33 +280,50 @@ var DiagnosticsClient = /** @class */ (function () {
272
280
  return [4 /*yield*/, this.storage.getLastFlushTimestamp()];
273
281
  case 1:
274
282
  lastFlushTimestamp = (_a.sent()) || -1;
275
- timeSinceLastFlush = now - lastFlushTimestamp;
276
283
  // If last flush timestamp is -1, it means this is a new client
284
+ // Save current timestamp as the initial "last flush timestamp"
285
+ // and schedule the flush timer
277
286
  if (lastFlushTimestamp === -1) {
287
+ void this.storage.setLastFlushTimestamp(now);
288
+ this._setFlushTimer(exports.FLUSH_INTERVAL_MS);
278
289
  return [2 /*return*/];
279
290
  }
280
- else if (timeSinceLastFlush >= exports.FLUSH_INTERVAL_MS) {
291
+ timeSinceLastFlush = now - lastFlushTimestamp;
292
+ if (timeSinceLastFlush >= exports.FLUSH_INTERVAL_MS) {
281
293
  // More than 5 minutes has passed, flush immediately
282
294
  void this._flush();
283
295
  return [2 /*return*/];
284
296
  }
285
297
  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);
298
+ // Set timer for remaining time
299
+ this._setFlushTimer(exports.FLUSH_INTERVAL_MS - timeSinceLastFlush);
296
300
  }
297
301
  return [2 /*return*/];
298
302
  }
299
303
  });
300
304
  });
301
305
  };
306
+ /**
307
+ * Helper method to set flush timer with consistent error handling
308
+ */
309
+ DiagnosticsClient.prototype._setFlushTimer = function (delay) {
310
+ var _this = this;
311
+ this.flushTimer = setTimeout(function () {
312
+ _this._flush()
313
+ .catch(function (error) {
314
+ _this.logger.debug('DiagnosticsClient: Failed to flush', error);
315
+ })
316
+ .finally(function () {
317
+ _this.flushTimer = null;
318
+ });
319
+ }, delay);
320
+ };
321
+ DiagnosticsClient.prototype._setSampleRate = function (sampleRate) {
322
+ this.logger.debug('DiagnosticsClient: Setting sample rate to', sampleRate);
323
+ this.config.sampleRate = sampleRate;
324
+ this.shouldTrack = (0, sampling_1.isTimestampInSample)(this.startTimestamp, this.config.sampleRate) && this.config.enabled;
325
+ this.logger.debug('DiagnosticsClient: Should track is', this.shouldTrack);
326
+ };
302
327
  return DiagnosticsClient;
303
328
  }());
304
329
  exports.DiagnosticsClient = DiagnosticsClient;
@@ -1 +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,qBAAgB,GAAwB,EAAE,CAAC;QAC3C,uBAAkB,GAA8B,EAAE,CAAC;QACnD,mBA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AG,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"]}
1
+ {"version":3,"file":"diagnostics-client.js","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-client.ts"],"names":[],"mappings":";;;;AACA,6DAAgF;AAEhF,gDAAiD;AACjD,8CAAwD;AAE3C,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;AAkJlD;IA4BE,2BACE,MAAc,EACd,MAAe,EACf,UA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;OAEG;IACK,0CAAc,GAAtB,UAAuB,KAAa;QAApC,iBAUC;QATC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;YAC3B,KAAI,CAAC,MAAM,EAAE;iBACV,KAAK,CAAC,UAAC,KAAK;gBACX,KAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;YACjE,CAAC,CAAC;iBACD,OAAO,CAAC;gBACP,KAAI,CAAC,UAAU,GAAG,IAAI,CAAC;YACzB,CAAC,CAAC,CAAC;QACP,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC;IAED,0CAAc,GAAd,UAAe,UAAkB;QAC/B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,2CAA2C,EAAE,UAAU,CAAC,CAAC;QAC3E,IAAI,CAAC,MAAM,CAAC,UAAU,GAAG,UAAU,CAAC;QACpC,IAAI,CAAC,WAAW,GAAG,IAAA,8BAAmB,EAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;QAC3G,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAC5E,CAAC;IACH,wBAAC;AAAD,CAAC,AA5UD,IA4UC;AA5UY,8CAAiB","sourcesContent":["import { ILogger } from '../logger';\nimport { DiagnosticsStorage, IDiagnosticsStorage } from './diagnostics-storage';\nimport { ServerZoneType } from '../types/server-zone';\nimport { getGlobalScope } from '../global-scope';\nimport { isTimestampInSample } from '../utils/sampling';\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 /**\n * Sets the sample rate for diagnostics.\n *\n * @example\n * ```typescript\n * diagnostics.setSampleRate(0.5);\n * ```\n */\n _setSampleRate(sampleRate: number): void;\n}\n\nexport class DiagnosticsClient implements IDiagnosticsClient {\n storage?: IDiagnosticsStorage;\n logger: ILogger;\n serverUrl: string;\n apiKey: string;\n // Whether to track diagnostics data based on sample rate and enabled flag\n shouldTrack: boolean;\n config: {\n enabled: boolean;\n sampleRate: number;\n };\n /**\n * The timestamp when the diagnostics client was initialized.\n * Save in memory to keep lifecycle sample rate calculation consistency.\n */\n startTimestamp: number;\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(\n apiKey: string,\n logger: ILogger,\n serverZone: ServerZoneType = 'US',\n options?: {\n enabled?: boolean;\n sampleRate?: number;\n },\n ) {\n this.apiKey = apiKey;\n this.logger = logger;\n this.serverUrl = serverZone === 'US' ? DIAGNOSTICS_US_SERVER_URL : DIAGNOSTICS_EU_SERVER_URL;\n\n this.logger.debug('DiagnosticsClient: Initializing with options', JSON.stringify(options, null, 2));\n // Diagnostics is enabled by default with sample rate of 0 (no sampling)\n this.config = { enabled: true, sampleRate: 0, ...options };\n this.startTimestamp = Date.now();\n this.shouldTrack = isTimestampInSample(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\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 /**\n * Check if storage is available and tracking is enabled\n */\n isStorageAndTrackEnabled(): boolean {\n return Boolean(this.storage) && Boolean(this.shouldTrack);\n }\n\n setTag(name: string, value: string) {\n if (!this.isStorageAndTrackEnabled()) {\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.isStorageAndTrackEnabled()) {\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.isStorageAndTrackEnabled()) {\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.isStorageAndTrackEnabled()) {\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 (Object.keys(counters).length === 0 && Object.keys(histogram).length === 0 && events.length === 0) {\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\n // If last flush timestamp is -1, it means this is a new client\n // Save current timestamp as the initial \"last flush timestamp\"\n // and schedule the flush timer\n if (lastFlushTimestamp === -1) {\n void this.storage.setLastFlushTimestamp(now);\n this._setFlushTimer(FLUSH_INTERVAL_MS);\n return;\n }\n\n const timeSinceLastFlush = now - lastFlushTimestamp;\n 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 this._setFlushTimer(FLUSH_INTERVAL_MS - timeSinceLastFlush);\n }\n }\n\n /**\n * Helper method to set flush timer with consistent error handling\n */\n private _setFlushTimer(delay: number) {\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 }, delay);\n }\n\n _setSampleRate(sampleRate: number): void {\n this.logger.debug('DiagnosticsClient: Setting sample rate to', sampleRate);\n this.config.sampleRate = sampleRate;\n this.shouldTrack = isTimestampInSample(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\n this.logger.debug('DiagnosticsClient: Should track is', this.shouldTrack);\n }\n}\n"]}
@@ -20,10 +20,12 @@ export { debugWrapper, getClientLogConfig, getClientStates } from './utils/debug
20
20
  export { UUID } from './utils/uuid';
21
21
  export { createIdentifyEvent } from './utils/event-builder';
22
22
  export { isUrlMatchAllowlist, getDecodeURI } from './utils/url-utils';
23
+ export { generateHashCode, isTimestampInSample } from './utils/sampling';
23
24
  export { MemoryStorage } from './storage/memory';
24
25
  export { CookieStorage } from './storage/cookie';
25
26
  export { getStorageKey } from './storage/helpers';
26
27
  export { BrowserStorage } from './storage/browser-storage';
28
+ export { DiagnosticsClient, IDiagnosticsClient } from './diagnostics/diagnostics-client';
27
29
  export { BaseTransport } from './transports/base';
28
30
  export { FetchTransport } from './transports/fetch';
29
31
  export { RemoteConfigClient, IRemoteConfigClient, RemoteConfig, Source } from './remote-config/remote-config';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot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AE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACjH,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACtF,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEpE,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAGvE,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnH,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAG5D,OAAO,EACL,aAAa,EACb,cAAc,EACd,sBAAsB,EACtB,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,kBAAkB,GACnB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAG9D,OAAO,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAGrE,OAAO,EACL,iBAAiB,EACjB,0BAA0B,EAC1B,kBAAkB,EAClB,6BAA6B,GAC9B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC"}
package/lib/cjs/index.js CHANGED
@@ -1,11 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DEFAULT_DEAD_CLICK_WINDOW_MS = exports.DEFAULT_RAGE_CLICK_OUT_OF_BOUNDS_THRESHOLD = exports.DEFAULT_RAGE_CLICK_WINDOW_MS = exports.DEFAULT_RAGE_CLICK_THRESHOLD = exports.DEFAULT_RAGE_CLICK_ALLOWLIST = exports.DEFAULT_DEAD_CLICK_ALLOWLIST = exports.DEFAULT_ACTION_CLICK_ALLOWLIST = exports.DEFAULT_DATA_ATTRIBUTE_PREFIX = exports.DEFAULT_CSS_SELECTOR_ALLOWLIST = exports.OfflineDisabled = exports.ServerZone = exports.SpecialEventType = exports.IdentifyOperation = exports.STORAGE_PREFIX = exports.AMPLITUDE_PREFIX = exports.LogLevel = exports.RemoteConfigClient = exports.FetchTransport = exports.BaseTransport = exports.BrowserStorage = exports.getStorageKey = exports.CookieStorage = exports.MemoryStorage = exports.getDecodeURI = exports.isUrlMatchAllowlist = exports.createIdentifyEvent = exports.UUID = exports.getClientStates = exports.getClientLogConfig = exports.debugWrapper = exports.returnWrapper = exports.getQueryParams = exports.getLanguage = exports.getOldCookieName = exports.getCookieName = exports.isNewSession = exports.setConnectorUserId = exports.setConnectorDeviceId = exports.getAnalyticsConnector = exports.getGlobalScope = exports.Logger = exports.RequestMetadata = exports.Config = exports.IdentityEventSender = exports.Destination = exports.RevenueProperty = exports.Revenue = exports.Identify = exports.AmplitudeContext = exports.AmplitudeCore = void 0;
4
- exports.CampaignParser = exports.MKTG = exports.BASE_CAMPAIGN = exports.EMPTY_VALUE = exports.FORBIDDEN_HEADERS = exports.SAFE_HEADERS = exports.NetworkRequestEvent = exports.networkObserver = exports.NetworkEventCallback = exports.Status = void 0;
3
+ exports.DEFAULT_RAGE_CLICK_WINDOW_MS = exports.DEFAULT_RAGE_CLICK_THRESHOLD = exports.DEFAULT_RAGE_CLICK_ALLOWLIST = exports.DEFAULT_DEAD_CLICK_ALLOWLIST = exports.DEFAULT_ACTION_CLICK_ALLOWLIST = exports.DEFAULT_DATA_ATTRIBUTE_PREFIX = exports.DEFAULT_CSS_SELECTOR_ALLOWLIST = exports.OfflineDisabled = exports.ServerZone = exports.SpecialEventType = exports.IdentifyOperation = exports.STORAGE_PREFIX = exports.AMPLITUDE_PREFIX = exports.LogLevel = exports.RemoteConfigClient = exports.FetchTransport = exports.BaseTransport = exports.DiagnosticsClient = exports.BrowserStorage = exports.getStorageKey = exports.CookieStorage = exports.MemoryStorage = exports.isTimestampInSample = exports.generateHashCode = exports.getDecodeURI = exports.isUrlMatchAllowlist = exports.createIdentifyEvent = exports.UUID = exports.getClientStates = exports.getClientLogConfig = exports.debugWrapper = exports.returnWrapper = exports.getQueryParams = exports.getLanguage = exports.getOldCookieName = exports.getCookieName = exports.isNewSession = exports.setConnectorUserId = exports.setConnectorDeviceId = exports.getAnalyticsConnector = exports.getGlobalScope = exports.Logger = exports.RequestMetadata = exports.Config = exports.IdentityEventSender = exports.Destination = exports.RevenueProperty = exports.Revenue = exports.Identify = exports.AmplitudeCore = void 0;
4
+ exports.CampaignParser = exports.MKTG = exports.BASE_CAMPAIGN = exports.EMPTY_VALUE = exports.FORBIDDEN_HEADERS = exports.SAFE_HEADERS = exports.NetworkRequestEvent = exports.networkObserver = exports.NetworkEventCallback = exports.Status = exports.DEFAULT_DEAD_CLICK_WINDOW_MS = exports.DEFAULT_RAGE_CLICK_OUT_OF_BOUNDS_THRESHOLD = void 0;
5
5
  var core_client_1 = require("./core-client");
6
6
  Object.defineProperty(exports, "AmplitudeCore", { enumerable: true, get: function () { return core_client_1.AmplitudeCore; } });
7
- var amplitude_context_1 = require("./types/amplitude-context");
8
- Object.defineProperty(exports, "AmplitudeContext", { enumerable: true, get: function () { return amplitude_context_1.AmplitudeContext; } });
9
7
  var identify_1 = require("./identify");
10
8
  Object.defineProperty(exports, "Identify", { enumerable: true, get: function () { return identify_1.Identify; } });
11
9
  var revenue_1 = require("./revenue");
@@ -48,6 +46,9 @@ Object.defineProperty(exports, "createIdentifyEvent", { enumerable: true, get: f
48
46
  var url_utils_1 = require("./utils/url-utils");
49
47
  Object.defineProperty(exports, "isUrlMatchAllowlist", { enumerable: true, get: function () { return url_utils_1.isUrlMatchAllowlist; } });
50
48
  Object.defineProperty(exports, "getDecodeURI", { enumerable: true, get: function () { return url_utils_1.getDecodeURI; } });
49
+ var sampling_1 = require("./utils/sampling");
50
+ Object.defineProperty(exports, "generateHashCode", { enumerable: true, get: function () { return sampling_1.generateHashCode; } });
51
+ Object.defineProperty(exports, "isTimestampInSample", { enumerable: true, get: function () { return sampling_1.isTimestampInSample; } });
51
52
  var memory_1 = require("./storage/memory");
52
53
  Object.defineProperty(exports, "MemoryStorage", { enumerable: true, get: function () { return memory_1.MemoryStorage; } });
53
54
  var cookie_1 = require("./storage/cookie");
@@ -56,7 +57,8 @@ var helpers_1 = require("./storage/helpers");
56
57
  Object.defineProperty(exports, "getStorageKey", { enumerable: true, get: function () { return helpers_1.getStorageKey; } });
57
58
  var browser_storage_1 = require("./storage/browser-storage");
58
59
  Object.defineProperty(exports, "BrowserStorage", { enumerable: true, get: function () { return browser_storage_1.BrowserStorage; } });
59
- // export { DiagnosticsClient, IDiagnosticsClient } from './diagnostics/diagnostics-client';
60
+ var diagnostics_client_1 = require("./diagnostics/diagnostics-client");
61
+ Object.defineProperty(exports, "DiagnosticsClient", { enumerable: true, get: function () { return diagnostics_client_1.DiagnosticsClient; } });
60
62
  var base_1 = require("./transports/base");
61
63
  Object.defineProperty(exports, "BaseTransport", { enumerable: true, get: function () { return base_1.BaseTransport; } });
62
64
  var fetch_1 = require("./transports/fetch");
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,6CAA8C;AAArC,4GAAA,aAAa,OAAA;AAGtB,+DAA6D;AAApD,qHAAA,gBAAgB,OAAA;AACzB,uCAAiD;AAAxC,oGAAA,QAAQ,OAAA;AACjB,qCAA+D;AAAtD,kGAAA,OAAO,OAAA;AAAY,0GAAA,eAAe,OAAA;AAC3C,qDAAoD;AAA3C,0GAAA,WAAW,OAAA;AACpB,+CAAyD;AAAhD,+GAAA,mBAAmB,OAAA;AAC5B,mCAAmD;AAA1C,gGAAA,MAAM,OAAA;AAAE,yGAAA,eAAe,OAAA;AAEh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AexB,qEAOsC;AAHpC,sIAAA,8BAA8B,OAAA;AAC9B,qIAAA,6BAA6B,OAAA;AAC7B,sIAAA,8BAA8B,OAAA;AAGhC,6EAQ0C;AANxC,wIAAA,4BAA4B,OAAA;AAC5B,wIAAA,4BAA4B,OAAA;AAC5B,wIAAA,4BAA4B,OAAA;AAC5B,wIAAA,4BAA4B,OAAA;AAC5B,sJAAA,0CAA0C,OAAA;AAC1C,wIAAA,4BAA4B,OAAA;AAG9B,yCAAwC;AAA/B,gGAAA,MAAM,OAAA;AAEf,uDAA2E;AAAlE,wHAAA,oBAAoB,OAAA;AAAE,mHAAA,eAAe,OAAA;AAC9C,iEAAiH;AAAxG,4HAAA,mBAAmB,OAAA;AAE5B,+CAAoE;AAA3D,yGAAA,YAAY,OAAA;AAAE,8GAAA,iBAAiB,OAAA;AAMxC,+CAAqE;AAA5D,wGAAA,WAAW,OAAA;AAAE,0GAAA,aAAa,OAAA;AAAE,iGAAA,IAAI,OAAA;AACzC,8DAA4D;AAAnD,iHAAA,cAAc,OAAA","sourcesContent":["export { AmplitudeCore } from './core-client';\nexport { CoreClient, PluginHost } from './types/client/core-client';\nexport { AnalyticsClient } from './types/client/analytics-client';\nexport { AmplitudeContext } from './types/amplitude-context';\nexport { Identify, IIdentify } from './identify';\nexport { Revenue, IRevenue, RevenueProperty } from './revenue';\nexport { Destination } from './plugins/destination';\nexport { IdentityEventSender } from './plugins/identity';\nexport { Config, RequestMetadata } from './config';\nexport { IConfig } from './types/config/core-config';\nexport { Logger, ILogger, LogConfig } from './logger';\nexport { getGlobalScope } from './global-scope';\nexport { getAnalyticsConnector, setConnectorDeviceId, setConnectorUserId } from './analytics-connector';\nexport { isNewSession } from './session';\nexport { getCookieName, getOldCookieName } from './cookie-name';\nexport { getLanguage } from './language';\nexport { getQueryParams } from './query-params';\n\nexport { returnWrapper, AmplitudeReturn } from './utils/return-wrapper';\nexport { debugWrapper, getClientLogConfig, getClientStates } from './utils/debug';\nexport { UUID } from './utils/uuid';\nexport { createIdentifyEvent } from './utils/event-builder';\nexport { isUrlMatchAllowlist, getDecodeURI } from './utils/url-utils';\n\nexport { MemoryStorage } from './storage/memory';\nexport { CookieStorage } from './storage/cookie';\nexport { getStorageKey } from './storage/helpers';\n\nexport { BrowserStorage } from './storage/browser-storage';\n\n// export { DiagnosticsClient, IDiagnosticsClient } from './diagnostics/diagnostics-client';\n\nexport { BaseTransport } from './transports/base';\nexport { FetchTransport } from './transports/fetch';\n\nexport { RemoteConfigClient, IRemoteConfigClient, RemoteConfig, Source } from './remote-config/remote-config';\n\nexport { LogLevel } from './types/loglevel';\nexport { AMPLITUDE_PREFIX, STORAGE_PREFIX } from './types/constants';\nexport { Storage, IdentityStorageType } from './types/storage';\nexport { Event, IdentifyOperation, SpecialEventType, IdentifyEvent, GroupIdentifyEvent } from './types/event/event';\nexport { EventOptions, BaseEvent } from './types/event/base-event';\nexport { IngestionMetadata } from './types/event/ingestion-metadata';\nexport { ServerZoneType, ServerZone } from './types/server-zone';\nexport { OfflineDisabled } from './types/offline';\nexport { Plan } from './types/event/plan';\nexport { TransportType, Transport } from './types/transport';\nexport { Payload } from './types/payload';\nexport { Response } from './types/response';\nexport { UserSession } from './types/user-session';\nexport {\n Plugin,\n BeforePlugin,\n DestinationPlugin,\n EnrichmentPlugin,\n PluginType,\n AnalyticsIdentity,\n} from './types/plugin';\nexport { Result } from './types/result';\nexport {\n ElementInteractionsOptions,\n Messenger,\n ActionType,\n DEFAULT_CSS_SELECTOR_ALLOWLIST,\n DEFAULT_DATA_ATTRIBUTE_PREFIX,\n DEFAULT_ACTION_CLICK_ALLOWLIST,\n} from './types/element-interactions';\n\nexport {\n FrustrationInteractionsOptions,\n DEFAULT_DEAD_CLICK_ALLOWLIST,\n DEFAULT_RAGE_CLICK_ALLOWLIST,\n DEFAULT_RAGE_CLICK_THRESHOLD,\n DEFAULT_RAGE_CLICK_WINDOW_MS,\n DEFAULT_RAGE_CLICK_OUT_OF_BOUNDS_THRESHOLD,\n DEFAULT_DEAD_CLICK_WINDOW_MS,\n} from './types/frustration-interactions';\nexport { PageTrackingOptions, PageTrackingTrackOn, PageTrackingHistoryChanges } from './types/page-view-tracking';\nexport { Status } from './types/status';\n\nexport { NetworkEventCallback, networkObserver } from './network-observer';\nexport { NetworkRequestEvent, IRequestWrapper, JsonObject, JsonValue, JsonArray } from './network-request-event';\nexport { NetworkTrackingOptions, NetworkCaptureRule } from './types/network-tracking';\nexport { SAFE_HEADERS, FORBIDDEN_HEADERS } from './types/constants';\n\nexport { PageUrlEnrichmentOptions } from './types/page-url-enrichment';\n\n// Campaign\nexport { Campaign, UTMParameters, ReferrerParameters, ClickIdParameters, ICampaignParser } from './types/campaign';\nexport { EMPTY_VALUE, BASE_CAMPAIGN, MKTG } from './types/constants';\nexport { CampaignParser } from './campaign/campaign-parser';\n\n// Browser\nexport {\n BrowserConfig,\n BrowserOptions,\n DefaultTrackingOptions,\n TrackingOptions,\n AutocaptureOptions,\n CookieOptions,\n AttributionOptions,\n} from './types/config/browser-config';\nexport { BrowserClient } from './types/client/browser-client';\n\n// Node\nexport { NodeClient } from './types/client/node-client';\nexport { NodeConfig, NodeOptions } from './types/config/node-config';\n\n// React Native\nexport {\n ReactNativeConfig,\n ReactNativeTrackingOptions,\n ReactNativeOptions,\n ReactNativeAttributionOptions,\n} from './types/config/react-native-config';\nexport { ReactNativeClient } from './types/client/react-native-client';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,6CAA8C;AAArC,4GAAA,aAAa,OAAA;AAItB,uCAAiD;AAAxC,oGAAA,QAAQ,OAAA;AACjB,qCAA+D;AAAtD,kGAAA,OAAO,OAAA;AAAY,0GAAA,eAAe,OAAA;AAC3C,qDAAoD;AAA3C,0GAAA,WAAW,OAAA;AACpB,+CAAyD;AAAhD,+GAAA,mBAAmB,OAAA;AAC5B,mCAAmD;AAA1C,gGAAA,MAAM,OAAA;AAAE,yGAAA,eAAe,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AAAE,yGAAA,gBAAgB,OAAA;AAGnD,mDAAiE;AAAxC,yGAAA,UAAU,OAAA;AACnC,2CAAkD;AAAzC,0GAAA,eAAe,OAAA;AAexB,qEAOsC;AAHpC,sIAAA,8BAA8B,OAAA;AAC9B,qIAAA,6BAA6B,OAAA;AAC7B,sIAAA,8BAA8B,OAAA;AAGhC,6EAQ0C;AANxC,wIAAA,4BAA4B,OAAA;AAC5B,wIAAA,4BAA4B,OAAA;AAC5B,wIAAA,4BAA4B,OAAA;AAC5B,wIAAA,4BAA4B,OAAA;AAC5B,sJAAA,0CAA0C,OAAA;AAC1C,wIAAA,4BAA4B,OAAA;AAG9B,yCAAwC;AAA/B,gGAAA,MAAM,OAAA;AAEf,uDAA2E;AAAlE,wHAAA,oBAAoB,OAAA;AAAE,mHAAA,eAAe,OAAA;AAC9C,iEAAiH;AAAxG,4HAAA,mBAAmB,OAAA;AAE5B,+CAAoE;AAA3D,yGAAA,YAAY,OAAA;AAAE,8GAAA,iBAAiB,OAAA;AAMxC,+CAAqE;AAA5D,wGAAA,WAAW,OAAA;AAAE,0GAAA,aAAa,OAAA;AAAE,iGAAA,IAAI,OAAA;AACzC,8DAA4D;AAAnD,iHAAA,cAAc,OAAA","sourcesContent":["export { AmplitudeCore } from './core-client';\nexport { CoreClient, PluginHost } from './types/client/core-client';\nexport { AnalyticsClient } from './types/client/analytics-client';\nexport { AmplitudeContext } from './types/amplitude-context';\nexport { Identify, IIdentify } from './identify';\nexport { Revenue, IRevenue, RevenueProperty } from './revenue';\nexport { Destination } from './plugins/destination';\nexport { IdentityEventSender } from './plugins/identity';\nexport { Config, RequestMetadata } from './config';\nexport { IConfig } from './types/config/core-config';\nexport { Logger, ILogger, LogConfig } from './logger';\nexport { getGlobalScope } from './global-scope';\nexport { getAnalyticsConnector, setConnectorDeviceId, setConnectorUserId } from './analytics-connector';\nexport { isNewSession } from './session';\nexport { getCookieName, getOldCookieName } from './cookie-name';\nexport { getLanguage } from './language';\nexport { getQueryParams } from './query-params';\n\nexport { returnWrapper, AmplitudeReturn } from './utils/return-wrapper';\nexport { debugWrapper, getClientLogConfig, getClientStates } from './utils/debug';\nexport { UUID } from './utils/uuid';\nexport { createIdentifyEvent } from './utils/event-builder';\nexport { isUrlMatchAllowlist, getDecodeURI } from './utils/url-utils';\nexport { generateHashCode, isTimestampInSample } from './utils/sampling';\n\nexport { MemoryStorage } from './storage/memory';\nexport { CookieStorage } from './storage/cookie';\nexport { getStorageKey } from './storage/helpers';\n\nexport { BrowserStorage } from './storage/browser-storage';\n\nexport { DiagnosticsClient, IDiagnosticsClient } from './diagnostics/diagnostics-client';\n\nexport { BaseTransport } from './transports/base';\nexport { FetchTransport } from './transports/fetch';\n\nexport { RemoteConfigClient, IRemoteConfigClient, RemoteConfig, Source } from './remote-config/remote-config';\n\nexport { LogLevel } from './types/loglevel';\nexport { AMPLITUDE_PREFIX, STORAGE_PREFIX } from './types/constants';\nexport { Storage, IdentityStorageType } from './types/storage';\nexport { Event, IdentifyOperation, SpecialEventType, IdentifyEvent, GroupIdentifyEvent } from './types/event/event';\nexport { EventOptions, BaseEvent } from './types/event/base-event';\nexport { IngestionMetadata } from './types/event/ingestion-metadata';\nexport { ServerZoneType, ServerZone } from './types/server-zone';\nexport { OfflineDisabled } from './types/offline';\nexport { Plan } from './types/event/plan';\nexport { TransportType, Transport } from './types/transport';\nexport { Payload } from './types/payload';\nexport { Response } from './types/response';\nexport { UserSession } from './types/user-session';\nexport {\n Plugin,\n BeforePlugin,\n DestinationPlugin,\n EnrichmentPlugin,\n PluginType,\n AnalyticsIdentity,\n} from './types/plugin';\nexport { Result } from './types/result';\nexport {\n ElementInteractionsOptions,\n Messenger,\n ActionType,\n DEFAULT_CSS_SELECTOR_ALLOWLIST,\n DEFAULT_DATA_ATTRIBUTE_PREFIX,\n DEFAULT_ACTION_CLICK_ALLOWLIST,\n} from './types/element-interactions';\n\nexport {\n FrustrationInteractionsOptions,\n DEFAULT_DEAD_CLICK_ALLOWLIST,\n DEFAULT_RAGE_CLICK_ALLOWLIST,\n DEFAULT_RAGE_CLICK_THRESHOLD,\n DEFAULT_RAGE_CLICK_WINDOW_MS,\n DEFAULT_RAGE_CLICK_OUT_OF_BOUNDS_THRESHOLD,\n DEFAULT_DEAD_CLICK_WINDOW_MS,\n} from './types/frustration-interactions';\nexport { PageTrackingOptions, PageTrackingTrackOn, PageTrackingHistoryChanges } from './types/page-view-tracking';\nexport { Status } from './types/status';\n\nexport { NetworkEventCallback, networkObserver } from './network-observer';\nexport { NetworkRequestEvent, IRequestWrapper, JsonObject, JsonValue, JsonArray } from './network-request-event';\nexport { NetworkTrackingOptions, NetworkCaptureRule } from './types/network-tracking';\nexport { SAFE_HEADERS, FORBIDDEN_HEADERS } from './types/constants';\n\nexport { PageUrlEnrichmentOptions } from './types/page-url-enrichment';\n\n// Campaign\nexport { Campaign, UTMParameters, ReferrerParameters, ClickIdParameters, ICampaignParser } from './types/campaign';\nexport { EMPTY_VALUE, BASE_CAMPAIGN, MKTG } from './types/constants';\nexport { CampaignParser } from './campaign/campaign-parser';\n\n// Browser\nexport {\n BrowserConfig,\n BrowserOptions,\n DefaultTrackingOptions,\n TrackingOptions,\n AutocaptureOptions,\n CookieOptions,\n AttributionOptions,\n} from './types/config/browser-config';\nexport { BrowserClient } from './types/client/browser-client';\n\n// Node\nexport { NodeClient } from './types/client/node-client';\nexport { NodeConfig, NodeOptions } from './types/config/node-config';\n\n// React Native\nexport {\n ReactNativeConfig,\n ReactNativeTrackingOptions,\n ReactNativeOptions,\n ReactNativeAttributionOptions,\n} from './types/config/react-native-config';\nexport { ReactNativeClient } from './types/client/react-native-client';\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"network-observer.d.ts","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EACL,eAAe,EACf,mBAAmB,EAKnB,gBAAgB,EAGjB,MAAM,yBAAyB,CAAC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,SAAS,EAC3C,eAAe,EAAE,gBAAgB,GAAG,SAAS,EAC7C,UAAU,EAAE,KAAK,GAAG,SAAS,EAC7B,SAAS,CAAC,EAAE,MAAM,EAClB,aAAa,CAAC,EAAE,MAAM;IA+DxB,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,YAAY;IA8DpB;;;;;;;;;OASG;IACH,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,cAAc,EAAE,OAAO,EAAE,eAAe;IA8B9E,OAAO,CAAC,UAAU;CAqHnB;AAGD,eAAO,MAAM,eAAe,iBAAwB,CAAC"}
@@ -84,7 +84,7 @@ var NetworkObserver = /** @class */ (function () {
84
84
  });
85
85
  };
86
86
  NetworkObserver.prototype.handleNetworkRequestEvent = function (requestType, requestInfo, requestWrapper, responseWrapper, typedError, startTime, durationStart) {
87
- var _a, _b;
87
+ var _a;
88
88
  /* istanbul ignore next */
89
89
  if (startTime === undefined || durationStart === undefined) {
90
90
  // if we reach this point, it means that the performance API is not supported
@@ -107,11 +107,9 @@ var NetworkObserver = /** @class */ (function () {
107
107
  var parsedUrl = new URL(url);
108
108
  // reconstruct the URL without the basic auth
109
109
  url = "".concat(parsedUrl.protocol, "//").concat(parsedUrl.host).concat(parsedUrl.pathname).concat(parsedUrl.search).concat(parsedUrl.hash);
110
+ // eslint-disable-next-line no-empty
110
111
  }
111
- catch (err) {
112
- /* istanbul ignore next */
113
- (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error('an unexpected error occurred while parsing the URL', err);
114
- }
112
+ catch (err) { }
115
113
  }
116
114
  method = (requestWrapper === null || requestWrapper === void 0 ? void 0 : requestWrapper.method) || method;
117
115
  var status, error;
@@ -1 +1 @@
1
- {"version":3,"file":"network-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";;;;AAAA,uBAAoC;AACpC,qCAAoC;AAEpC,iEAUiC;AAajC;;GAEG;AACH,SAAS,SAAS,CAAC,WAAgB;IACjC,OAAO,OAAO,WAAW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Y,CAAC,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,EACtD,cAAc,EACd,eAAe,EACf,SAAS,EACT,YAAY,CAAC,SAAS,EACtB,YAAY,CAAC,aAAa,CAC3B,CAAC;iBACH;gBAAC,OAAO,GAAG,EAAE;oBACZ,0BAA0B;oBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,sDAAsD,EAAE,GAAG,CAAC,CAAC;iBACnG;YACH,CAAC,CAAC,CAAC;YACH,oEAAoE;YACpE,OAAO,eAAe,CAAC,KAAK,CAAC,OAAO,EAAE,IAAW,CAAC,CAAC;QACrD,CAAC,CAAC;QAEF;;;;;WAKG;QACH,oEAAoE;QACpE,oEAAoE;QACpE,QAAQ,CAAC,gBAAgB,GAAG,UAAU,UAAe,EAAE,WAAgB;;YACrE,IAAM,OAAO,GAAG,IAA8C,CAAC;YAC/D,IAAI;gBACF,sEAAsE;gBACtE,OAAO,CAAC,yBAAyB,CAAC,OAAO,CAAC,UAAoB,CAAC,GAAG,WAAqB,CAAC;aACzF;YAAC,OAAO,GAAG,EAAE;gBACZ,0BAA0B;gBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,iEAAiE,EAAE,GAAG,CAAC,CAAC;aAC9G;YACD,oEAAoE;YACpE,2BAA2B,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC;QACxE,CAAC,CAAC;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AAhXD,IAgXC;AAhXY,0CAAe;AAkX5B,wCAAwC;AAC3B,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from './';\nimport { UUID } from './utils/uuid';\nimport { ILogger } from './logger';\nimport {\n IRequestWrapper,\n NetworkRequestEvent,\n RequestWrapperFetch,\n ResponseWrapperFetch,\n RequestWrapperXhr,\n ResponseWrapperXhr,\n IResponseWrapper,\n RequestInitSafe,\n XMLHttpRequestBodyInitSafe,\n} from './network-request-event';\n\n// object that is added to each XHR instance so\n// that info can be set in xhr.open and retrieved in xhr.send\ntype AmplitudeAnalyticsEvent = {\n method: string;\n url: string | URL;\n startTime: number;\n durationStart: number;\n status?: number;\n headers: Record<string, string>;\n};\n\n/**\n * Typeguard function checks if an input is a Request object.\n */\nfunction isRequest(requestInfo: any): requestInfo is Request {\n return typeof requestInfo === 'object' && requestInfo !== null && 'url' in requestInfo && 'method' in requestInfo;\n}\n\nexport type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;\n\nexport class NetworkEventCallback {\n constructor(public readonly callback: (event: NetworkRequestEvent) => void, public readonly id: string = UUID()) {}\n}\n\ntype RequestUrlAndMethod = {\n url: string | URL | undefined;\n method: string | undefined;\n};\n\n// A narrowed down [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) type\n// that only includes the properties we need to access and adds the $$AmplitudeAnalyticsEvent property\n// Use great care when modifying this type, make sure you only use read-only properties and only add\n// what you need to access, nothing more.\ntype AmplitudeXMLHttpRequestSafe = {\n $$AmplitudeAnalyticsEvent: AmplitudeAnalyticsEvent;\n status: number;\n responseText: string;\n responseType: XMLHttpRequestResponseType;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nexport class NetworkObserver {\n private eventCallbacks: Map<string, NetworkEventCallback> = new Map();\n // eslint-disable-next-line no-restricted-globals\n private globalScope?: typeof globalThis;\n private logger?: ILogger;\n private isObserving = false;\n constructor(logger?: ILogger) {\n this.logger = logger;\n const globalScope = getGlobalScope();\n if (!NetworkObserver.isSupported()) {\n /* istanbul ignore next */\n return;\n }\n this.globalScope = globalScope;\n }\n\n static isSupported(): boolean {\n const globalScope = getGlobalScope();\n return !!globalScope && !!globalScope.fetch;\n }\n\n subscribe(eventCallback: NetworkEventCallback, logger?: ILogger) {\n if (!this.logger) {\n this.logger = logger;\n }\n this.eventCallbacks.set(eventCallback.id, eventCallback);\n if (!this.isObserving) {\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrOpen = this.globalScope?.XMLHttpRequest?.prototype?.open;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSend = this.globalScope?.XMLHttpRequest?.prototype?.send;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\n }\n\n /* istanbul ignore next */\n const originalFetch = this.globalScope?.fetch;\n /* istanbul ignore next */\n if (originalFetch) {\n this.observeFetch(originalFetch);\n }\n\n /* istanbul ignore next */\n this.isObserving = true;\n }\n }\n\n unsubscribe(eventCallback: NetworkEventCallback) {\n this.eventCallbacks.delete(eventCallback.id);\n }\n\n protected triggerEventCallbacks(event: NetworkRequestEvent) {\n this.eventCallbacks.forEach((callback) => {\n try {\n callback.callback(event);\n } catch (err) {\n // if the callback throws an error, we should catch it\n // to avoid breaking the fetch promise chain\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n }\n });\n }\n\n handleNetworkRequestEvent(\n requestType: 'fetch' | 'xhr',\n requestInfo: RequestInfo | URL | RequestUrlAndMethod | undefined,\n requestWrapper: IRequestWrapper | undefined,\n responseWrapper: IResponseWrapper | undefined,\n typedError: Error | undefined,\n startTime?: number,\n durationStart?: number,\n ) {\n /* istanbul ignore next */\n if (startTime === undefined || durationStart === undefined) {\n // if we reach this point, it means that the performance API is not supported\n // so we can't construct a NetworkRequestEvent\n return;\n }\n\n // parse the URL and Method\n let url: string | undefined;\n let method = 'GET';\n if (isRequest(requestInfo)) {\n url = requestInfo['url'];\n method = requestInfo['method'];\n } else {\n url = requestInfo?.toString?.();\n }\n\n // strip basic auth from the URL\n if (url) {\n try {\n const parsedUrl = new URL(url);\n // reconstruct the URL without the basic auth\n url = `${parsedUrl.protocol}//${parsedUrl.host}${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;\n } catch (err) {\n /* istanbul ignore next */\n this.logger?.error('an unexpected error occurred while parsing the URL', err);\n }\n }\n method = requestWrapper?.method || method;\n\n let status, error;\n if (responseWrapper) {\n status = responseWrapper.status;\n }\n\n if (typedError) {\n error = {\n name: typedError.name || 'UnknownError',\n message: typedError.message || 'An unknown error occurred',\n };\n status = 0;\n }\n\n const duration = Math.floor(performance.now() - durationStart);\n const endTime = Math.floor(startTime + duration);\n\n const requestEvent = new NetworkRequestEvent(\n requestType,\n method,\n startTime, // timestamp and startTime are aliases\n startTime,\n url,\n requestWrapper,\n status,\n duration,\n responseWrapper,\n error,\n endTime,\n );\n\n this.triggerEventCallbacks(requestEvent);\n }\n\n private getTimestamps() {\n /* istanbul ignore next */\n return {\n startTime: Date.now?.(),\n durationStart: performance?.now?.(),\n };\n }\n\n private observeFetch(\n originalFetch: (requestInfo: RequestInfo | URL, requestInit?: RequestInit) => Promise<Response>,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalFetch) {\n return;\n }\n /**\n * IMPORTANT: This overrides window.fetch in browsers.\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of fetch\n * and make sure another developer who is an expert reviews this change throughly\n */\n this.globalScope.fetch = async (requestInfo?: RequestInfo | URL, requestInit?: RequestInit) => {\n // 1: capture the start time and duration start time before the fetch call\n let timestamps;\n try {\n timestamps = this.getTimestamps();\n } catch (error) {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while retrieving timestamps', error);\n }\n\n // 2. make the call to the original fetch and preserve the response or error\n let originalResponse, originalError;\n try {\n originalResponse = await originalFetch(requestInfo as RequestInfo | URL, requestInit);\n } catch (err) {\n // Capture error information\n originalError = err;\n }\n\n // 3. call the handler after the fetch call is done\n try {\n this.handleNetworkRequestEvent(\n 'fetch',\n requestInfo,\n requestInit ? new RequestWrapperFetch(requestInit as RequestInitSafe) : undefined,\n originalResponse ? new ResponseWrapperFetch(originalResponse) : undefined,\n originalError as Error,\n /* istanbul ignore next */\n timestamps?.startTime,\n /* istanbul ignore next */\n timestamps?.durationStart,\n );\n } catch (err) {\n // this catch shouldn't be reachable, but keep it here for safety\n // because we're overriding the fetch function and better to be safe than sorry\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while handling fetch', err);\n }\n\n // 4. return the original response or throw the original error\n if (originalResponse) {\n // if the response is not undefined, return it\n return originalResponse;\n } else {\n throw originalError;\n }\n };\n }\n\n /**\n * Creates a function that parses the response of an XMLHttpRequest as JSON.\n *\n * Returns function instead of JSON object to avoid unnecessary parsing if the\n * body is not being captured.\n *\n * @param xhrSafe - The XMLHttpRequest object.\n * @param context - The NetworkObserver instance.\n * @returns A function that parses the response of an XMLHttpRequest as JSON.\n */\n static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver) {\n return () => {\n try {\n if (xhrUnsafe.responseType === 'json') {\n // if response is a JS object, clone it so that subscribers can't mutate it\n if (context.globalScope?.structuredClone) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return context.globalScope.structuredClone(xhrUnsafe.response);\n }\n } else if (['text', ''].includes(xhrUnsafe.responseType)) {\n // if response is a string, parse it as JSON\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return JSON.parse(xhrUnsafe.responseText);\n }\n } catch (err) {\n /* istanbul ignore if */\n if (err instanceof Error && err.name === 'InvalidStateError') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions\n // if we reach here, it means we don't handle responseType correctly\n context.logger?.error(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\n );\n }\n // the other possible error is Json Parse error which we fail silently\n return null;\n }\n return null;\n };\n }\n\n private observeXhr(\n originalXhrOpen:\n | ((\n method: string,\n url: string | URL,\n async?: boolean,\n username?: string | null,\n password?: string | null,\n ) => void)\n | undefined,\n originalXhrSend: ((body?: Document | XMLHttpRequestBodyInit | null) => void) | undefined,\n originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {\n return;\n }\n\n const xhrProto = this.globalScope.XMLHttpRequest.prototype;\n\n const networkObserverContext = this as NetworkObserver;\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.open\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.open\n * and make sure another developer who is an expert reviews this change throughly\n */\n xhrProto.open = function (...args: any[]) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const [method, url] = args as [string, string | URL];\n try {\n /* istanbul ignore next */\n xhrSafe.$$AmplitudeAnalyticsEvent = {\n method,\n url: url?.toString?.(),\n headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr open', err);\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return originalXhrOpen.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.send\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.send\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.send = function (...args: any[]) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhrUnsafe = this;\n const xhrSafe = xhrUnsafe as unknown as AmplitudeXMLHttpRequestSafe;\n const getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n getJson,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\n requestEvent.status = xhrSafe.status;\n networkObserverContext.handleNetworkRequestEvent(\n 'xhr',\n { url: requestEvent.url, method: requestEvent.method },\n requestWrapper,\n responseWrapper,\n undefined,\n requestEvent.startTime,\n requestEvent.durationStart,\n );\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while handling xhr send', err);\n }\n });\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.setRequestHeader\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n xhrSafe.$$AmplitudeAnalyticsEvent.headers[headerName as string] = headerValue as string;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr setRequestHeader', err);\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
1
+ {"version":3,"file":"network-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";;;;AAAA,uBAAoC;AACpC,qCAAoC;AAEpC,iEAUiC;AAajC;;GAEG;AACH,SAAS,SAAS,CAAC,WAAgB;IACjC,OAAO,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,KAAK,IAAI,IAAI,KAAK,IAAI,WAAW,IAAI,QAAQ,IAAI,WAAW,CAAC;AACpH,CAAC;AAID;IACE,8BAA4B,QAA8C,EAAkB,EAAmB;QAAnB,mBAAA,EAAA,SAAa,WAAI,GAAE;QAAnF,aAAQ,GAAR,QAAQ,CAAsC;QAAkB,OAAE,GAAF,EAAE,CAAiB;IAAG,CAAC;IACrH,2BAAC;AAAD,CAAC,AAFD,IAEC;AAFY,oDAAoB;AAuBjC;IAME,yBAAY,MAAgB;QALpB,mBAAc,GAAsC,IAAI,GAAG,EAAE,CAAC;QAI9D,gBAAW,GAAG,KAAK,CAAC;QAE1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAM,WAAW,GAAG,IAAA,iBAAc,GAAE,CAAC;QACrC,IAAI,CAAC,eAAe,CAAC,WAAW,EAAE,EAAE;YAClC,0BAA0B;YAC1B,OAAO;SACR;QACD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAEM,2BAAW,GAAlB;QACE,IAAM,WAAW,GAAG,IAAA,iBAAc,GAAE,CAAC;QACrC,OAAO,CAAC,CAAC,WAAW,IAAI,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC;IAC9C,CAAC;IAED,mCAAS,GAAT,UAAU,aAAmC,EAAE,MAAgB;;QAC7D,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;YAChB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;SACtB;QACD,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,EAAE,aAAa,CAAC,CA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ILogger } from './logger';\nimport {\n IRequestWrapper,\n NetworkRequestEvent,\n RequestWrapperFetch,\n ResponseWrapperFetch,\n RequestWrapperXhr,\n ResponseWrapperXhr,\n IResponseWrapper,\n RequestInitSafe,\n XMLHttpRequestBodyInitSafe,\n} from './network-request-event';\n\n// object that is added to each XHR instance so\n// that info can be set in xhr.open and retrieved in xhr.send\ntype AmplitudeAnalyticsEvent = {\n method: string;\n url: string | URL;\n startTime: number;\n durationStart: number;\n status?: number;\n headers: Record<string, string>;\n};\n\n/**\n * Typeguard function checks if an input is a Request object.\n */\nfunction isRequest(requestInfo: any): requestInfo is Request {\n return typeof requestInfo === 'object' && requestInfo !== null && 'url' in requestInfo && 'method' in requestInfo;\n}\n\nexport type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;\n\nexport class NetworkEventCallback {\n constructor(public readonly callback: (event: NetworkRequestEvent) => void, public readonly id: string = UUID()) {}\n}\n\ntype RequestUrlAndMethod = {\n url: string | URL | undefined;\n method: string | undefined;\n};\n\n// A narrowed down [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) type\n// that only includes the properties we need to access and adds the $$AmplitudeAnalyticsEvent property\n// Use great care when modifying this type, make sure you only use read-only properties and only add\n// what you need to access, nothing more.\ntype AmplitudeXMLHttpRequestSafe = {\n $$AmplitudeAnalyticsEvent: AmplitudeAnalyticsEvent;\n status: number;\n responseText: string;\n responseType: XMLHttpRequestResponseType;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nexport class NetworkObserver {\n private eventCallbacks: Map<string, NetworkEventCallback> = new Map();\n // eslint-disable-next-line no-restricted-globals\n private globalScope?: typeof globalThis;\n private logger?: ILogger;\n private isObserving = false;\n constructor(logger?: ILogger) {\n this.logger = logger;\n const globalScope = getGlobalScope();\n if (!NetworkObserver.isSupported()) {\n /* istanbul ignore next */\n return;\n }\n this.globalScope = globalScope;\n }\n\n static isSupported(): boolean {\n const globalScope = getGlobalScope();\n return !!globalScope && !!globalScope.fetch;\n }\n\n subscribe(eventCallback: NetworkEventCallback, logger?: ILogger) {\n if (!this.logger) {\n this.logger = logger;\n }\n this.eventCallbacks.set(eventCallback.id, eventCallback);\n if (!this.isObserving) {\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrOpen = this.globalScope?.XMLHttpRequest?.prototype?.open;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSend = this.globalScope?.XMLHttpRequest?.prototype?.send;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\n }\n\n /* istanbul ignore next */\n const originalFetch = this.globalScope?.fetch;\n /* istanbul ignore next */\n if (originalFetch) {\n this.observeFetch(originalFetch);\n }\n\n /* istanbul ignore next */\n this.isObserving = true;\n }\n }\n\n unsubscribe(eventCallback: NetworkEventCallback) {\n this.eventCallbacks.delete(eventCallback.id);\n }\n\n protected triggerEventCallbacks(event: NetworkRequestEvent) {\n this.eventCallbacks.forEach((callback) => {\n try {\n callback.callback(event);\n } catch (err) {\n // if the callback throws an error, we should catch it\n // to avoid breaking the fetch promise chain\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n }\n });\n }\n\n handleNetworkRequestEvent(\n requestType: 'fetch' | 'xhr',\n requestInfo: RequestInfo | URL | RequestUrlAndMethod | undefined,\n requestWrapper: IRequestWrapper | undefined,\n responseWrapper: IResponseWrapper | undefined,\n typedError: Error | undefined,\n startTime?: number,\n durationStart?: number,\n ) {\n /* istanbul ignore next */\n if (startTime === undefined || durationStart === undefined) {\n // if we reach this point, it means that the performance API is not supported\n // so we can't construct a NetworkRequestEvent\n return;\n }\n\n // parse the URL and Method\n let url: string | undefined;\n let method = 'GET';\n if (isRequest(requestInfo)) {\n url = requestInfo['url'];\n method = requestInfo['method'];\n } else {\n url = requestInfo?.toString?.();\n }\n\n // strip basic auth from the URL\n if (url) {\n try {\n const parsedUrl = new URL(url);\n // reconstruct the URL without the basic auth\n url = `${parsedUrl.protocol}//${parsedUrl.host}${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;\n // eslint-disable-next-line no-empty\n } catch (err) {}\n }\n method = requestWrapper?.method || method;\n\n let status, error;\n if (responseWrapper) {\n status = responseWrapper.status;\n }\n\n if (typedError) {\n error = {\n name: typedError.name || 'UnknownError',\n message: typedError.message || 'An unknown error occurred',\n };\n status = 0;\n }\n\n const duration = Math.floor(performance.now() - durationStart);\n const endTime = Math.floor(startTime + duration);\n\n const requestEvent = new NetworkRequestEvent(\n requestType,\n method,\n startTime, // timestamp and startTime are aliases\n startTime,\n url,\n requestWrapper,\n status,\n duration,\n responseWrapper,\n error,\n endTime,\n );\n\n this.triggerEventCallbacks(requestEvent);\n }\n\n private getTimestamps() {\n /* istanbul ignore next */\n return {\n startTime: Date.now?.(),\n durationStart: performance?.now?.(),\n };\n }\n\n private observeFetch(\n originalFetch: (requestInfo: RequestInfo | URL, requestInit?: RequestInit) => Promise<Response>,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalFetch) {\n return;\n }\n /**\n * IMPORTANT: This overrides window.fetch in browsers.\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of fetch\n * and make sure another developer who is an expert reviews this change throughly\n */\n this.globalScope.fetch = async (requestInfo?: RequestInfo | URL, requestInit?: RequestInit) => {\n // 1: capture the start time and duration start time before the fetch call\n let timestamps;\n try {\n timestamps = this.getTimestamps();\n } catch (error) {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while retrieving timestamps', error);\n }\n\n // 2. make the call to the original fetch and preserve the response or error\n let originalResponse, originalError;\n try {\n originalResponse = await originalFetch(requestInfo as RequestInfo | URL, requestInit);\n } catch (err) {\n // Capture error information\n originalError = err;\n }\n\n // 3. call the handler after the fetch call is done\n try {\n this.handleNetworkRequestEvent(\n 'fetch',\n requestInfo,\n requestInit ? new RequestWrapperFetch(requestInit as RequestInitSafe) : undefined,\n originalResponse ? new ResponseWrapperFetch(originalResponse) : undefined,\n originalError as Error,\n /* istanbul ignore next */\n timestamps?.startTime,\n /* istanbul ignore next */\n timestamps?.durationStart,\n );\n } catch (err) {\n // this catch shouldn't be reachable, but keep it here for safety\n // because we're overriding the fetch function and better to be safe than sorry\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while handling fetch', err);\n }\n\n // 4. return the original response or throw the original error\n if (originalResponse) {\n // if the response is not undefined, return it\n return originalResponse;\n } else {\n throw originalError;\n }\n };\n }\n\n /**\n * Creates a function that parses the response of an XMLHttpRequest as JSON.\n *\n * Returns function instead of JSON object to avoid unnecessary parsing if the\n * body is not being captured.\n *\n * @param xhrSafe - The XMLHttpRequest object.\n * @param context - The NetworkObserver instance.\n * @returns A function that parses the response of an XMLHttpRequest as JSON.\n */\n static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver) {\n return () => {\n try {\n if (xhrUnsafe.responseType === 'json') {\n // if response is a JS object, clone it so that subscribers can't mutate it\n if (context.globalScope?.structuredClone) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return context.globalScope.structuredClone(xhrUnsafe.response);\n }\n } else if (['text', ''].includes(xhrUnsafe.responseType)) {\n // if response is a string, parse it as JSON\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return JSON.parse(xhrUnsafe.responseText);\n }\n } catch (err) {\n /* istanbul ignore if */\n if (err instanceof Error && err.name === 'InvalidStateError') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions\n // if we reach here, it means we don't handle responseType correctly\n context.logger?.error(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\n );\n }\n // the other possible error is Json Parse error which we fail silently\n return null;\n }\n return null;\n };\n }\n\n private observeXhr(\n originalXhrOpen:\n | ((\n method: string,\n url: string | URL,\n async?: boolean,\n username?: string | null,\n password?: string | null,\n ) => void)\n | undefined,\n originalXhrSend: ((body?: Document | XMLHttpRequestBodyInit | null) => void) | undefined,\n originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {\n return;\n }\n\n const xhrProto = this.globalScope.XMLHttpRequest.prototype;\n\n const networkObserverContext = this as NetworkObserver;\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.open\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.open\n * and make sure another developer who is an expert reviews this change throughly\n */\n xhrProto.open = function (...args: any[]) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const [method, url] = args as [string, string | URL];\n try {\n /* istanbul ignore next */\n xhrSafe.$$AmplitudeAnalyticsEvent = {\n method,\n url: url?.toString?.(),\n headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr open', err);\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return originalXhrOpen.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.send\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.send\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.send = function (...args: any[]) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhrUnsafe = this;\n const xhrSafe = xhrUnsafe as unknown as AmplitudeXMLHttpRequestSafe;\n const getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n getJson,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\n requestEvent.status = xhrSafe.status;\n networkObserverContext.handleNetworkRequestEvent(\n 'xhr',\n { url: requestEvent.url, method: requestEvent.method },\n requestWrapper,\n responseWrapper,\n undefined,\n requestEvent.startTime,\n requestEvent.durationStart,\n );\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while handling xhr send', err);\n }\n });\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.setRequestHeader\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n xhrSafe.$$AmplitudeAnalyticsEvent.headers[headerName as string] = headerValue as string;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr setRequestHeader', err);\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}