@amplitude/analytics-core 2.30.0 → 2.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/config.d.ts +1 -2
- package/lib/cjs/config.d.ts.map +1 -1
- package/lib/cjs/config.js.map +1 -1
- package/lib/cjs/diagnostics/diagnostics-client.d.ts.map +1 -1
- package/lib/cjs/diagnostics/diagnostics-client.js +4 -0
- package/lib/cjs/diagnostics/diagnostics-client.js.map +1 -1
- package/lib/cjs/index.d.ts +1 -1
- package/lib/cjs/index.d.ts.map +1 -1
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/plugins/destination.d.ts +5 -0
- package/lib/cjs/plugins/destination.d.ts.map +1 -1
- package/lib/cjs/plugins/destination.js +18 -1
- package/lib/cjs/plugins/destination.js.map +1 -1
- package/lib/cjs/transports/base.d.ts.map +1 -1
- package/lib/cjs/transports/base.js +2 -1
- package/lib/cjs/transports/base.js.map +1 -1
- package/lib/cjs/utils/status-code.d.ts +7 -0
- package/lib/cjs/utils/status-code.d.ts.map +1 -0
- package/lib/cjs/utils/status-code.js +13 -0
- package/lib/cjs/utils/status-code.js.map +1 -0
- package/lib/esm/config.d.ts +1 -2
- package/lib/esm/config.d.ts.map +1 -1
- package/lib/esm/config.js.map +1 -1
- package/lib/esm/diagnostics/diagnostics-client.d.ts.map +1 -1
- package/lib/esm/diagnostics/diagnostics-client.js +4 -0
- package/lib/esm/diagnostics/diagnostics-client.js.map +1 -1
- package/lib/esm/index.d.ts +1 -1
- package/lib/esm/index.d.ts.map +1 -1
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/plugins/destination.d.ts +5 -0
- package/lib/esm/plugins/destination.d.ts.map +1 -1
- package/lib/esm/plugins/destination.js +18 -1
- package/lib/esm/plugins/destination.js.map +1 -1
- package/lib/esm/transports/base.d.ts.map +1 -1
- package/lib/esm/transports/base.js +2 -1
- package/lib/esm/transports/base.js.map +1 -1
- package/lib/esm/utils/status-code.d.ts +7 -0
- package/lib/esm/utils/status-code.d.ts.map +1 -0
- package/lib/esm/utils/status-code.js +9 -0
- package/lib/esm/utils/status-code.js.map +1 -0
- package/package.json +2 -2
package/lib/esm/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAOA,OAAO,EACL,oBAAoB,EACpB,0BAA0B,EAC1B,uBAAuB,EACvB,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,MAAM,EAAW,MAAM,UAAU,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAOA,OAAO,EACL,oBAAoB,EACpB,0BAA0B,EAC1B,uBAAuB,EACvB,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,MAAM,EAAW,MAAM,UAAU,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAG5C,MAAM,CAAC,IAAM,gBAAgB,GAAG,cAAM,OAAA,CAAC;IACrC,eAAe,EAAE,EAAE;IACnB,cAAc,EAAE,GAAG;IACnB,mBAAmB,EAAE,KAAK;IAC1B,YAAY,EAAE,qBAAqB;IACnC,QAAQ,EAAE,QAAQ,CAAC,IAAI;IACvB,cAAc,EAAE,IAAI,MAAM,EAAE;IAC5B,OAAO,EAAE,KAAK;IACd,MAAM,EAAE,KAAK;IACb,SAAS,EAAE,oBAAoB;IAC/B,UAAU,EAAE,IAAsB;IAClC,QAAQ,EAAE,KAAK;CAChB,CAAC,EAZoC,CAYpC,CAAC;AACH;IA2BE,gBAAY,OAAsB;;QARxB,YAAO,GAAG,KAAK,CAAC;QASxB,IAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;QACz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CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,gBAAgB,EAAE,CAAC,UAAU,CAAC;IACnG,OAAO;QACL,UAAU,EAAE,WAAW;QACvB,SAAS,EAAE,YAAY,CAAC,WAAW,EAAE,QAAQ,CAAC;KAC/C,CAAC;AACJ,CAAC,CAAC;AAEF;IAOE;QACE,IAAI,CAAC,GAAG,GAAG;YACT,OAAO,EAAE;gBACP,SAAS,EAAE,EAAE;aACd;SACF,CAAC;IACJ,CAAC;IAED,yCAAe,GAAf,UAAwC,GAAM,EAAE,KAA0B;QACxE,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IAC1C,CAAC;IACH,sBAAC;AAAD,CAAC,AAlBD,IAkBC;;AAED;IAAA;IAIA,CAAC;IAAD,uBAAC;AAAD,CAAC,AAJD,IAIC","sourcesContent":["import { OfflineDisabled } from './types/offline';\nimport { ServerZoneType } from './types/server-zone';\nimport { Transport } from './types/transport';\nimport { Event } from './types/event/event';\nimport { Plan } from './types/event/plan';\nimport { IngestionMetadata } from './types/event/ingestion-metadata';\nimport { Storage } from './types/storage';\nimport {\n AMPLITUDE_SERVER_URL,\n AMPLITUDE_BATCH_SERVER_URL,\n EU_AMPLITUDE_SERVER_URL,\n EU_AMPLITUDE_BATCH_SERVER_URL,\n DEFAULT_INSTANCE_NAME,\n} from './types/constants';\n\nimport { Logger, ILogger } from './logger';\nimport { LogLevel } from './types/loglevel';\nimport { IConfig, ConfigOptions, IRequestMetadata, IHistogramOptions, HistogramKey } from './types/config/core-config';\n\nexport const getDefaultConfig = () => ({\n flushMaxRetries: 12,\n flushQueueSize: 200,\n flushIntervalMillis: 10000,\n instanceName: DEFAULT_INSTANCE_NAME,\n logLevel: LogLevel.Warn,\n loggerProvider: new Logger(),\n offline: false,\n optOut: false,\n serverUrl: AMPLITUDE_SERVER_URL,\n serverZone: 'US' as ServerZoneType,\n useBatch: false,\n});\nexport class Config implements IConfig {\n apiKey: string;\n flushIntervalMillis: number;\n flushMaxRetries: number;\n flushQueueSize: number;\n instanceName?: string;\n loggerProvider: ILogger;\n logLevel: LogLevel;\n minIdLength?: number;\n offline?: boolean | typeof OfflineDisabled;\n plan?: Plan;\n ingestionMetadata?: IngestionMetadata;\n serverUrl: string | undefined;\n serverZone?: ServerZoneType;\n transportProvider: Transport;\n storageProvider?: Storage<Event[]>;\n useBatch: boolean;\n requestMetadata?: RequestMetadata;\n\n protected _optOut = false;\n get optOut() {\n return this._optOut;\n }\n set optOut(optOut: boolean) {\n this._optOut = optOut;\n }\n\n constructor(options: ConfigOptions) {\n const defaultConfig = getDefaultConfig();\n this.apiKey = options.apiKey;\n this.flushIntervalMillis = options.flushIntervalMillis ?? defaultConfig.flushIntervalMillis;\n this.flushMaxRetries = options.flushMaxRetries || defaultConfig.flushMaxRetries;\n this.flushQueueSize = options.flushQueueSize || defaultConfig.flushQueueSize;\n this.instanceName = options.instanceName || defaultConfig.instanceName;\n this.loggerProvider = options.loggerProvider || defaultConfig.loggerProvider;\n this.logLevel = options.logLevel ?? defaultConfig.logLevel;\n this.minIdLength = options.minIdLength;\n this.plan = options.plan;\n this.ingestionMetadata = options.ingestionMetadata;\n this.offline = options.offline !== undefined ? options.offline : defaultConfig.offline;\n this.optOut = options.optOut ?? defaultConfig.optOut;\n this.serverUrl = options.serverUrl;\n this.serverZone = options.serverZone || defaultConfig.serverZone;\n this.storageProvider = options.storageProvider;\n this.transportProvider = options.transportProvider;\n this.useBatch = options.useBatch ?? defaultConfig.useBatch;\n this.loggerProvider.enable(this.logLevel);\n\n const serverConfig = createServerConfig(options.serverUrl, options.serverZone, options.useBatch);\n this.serverZone = serverConfig.serverZone;\n this.serverUrl = serverConfig.serverUrl;\n }\n}\n\nexport const getServerUrl = (serverZone: ServerZoneType, useBatch: boolean) => {\n if (serverZone === 'EU') {\n return useBatch ? EU_AMPLITUDE_BATCH_SERVER_URL : EU_AMPLITUDE_SERVER_URL;\n }\n return useBatch ? AMPLITUDE_BATCH_SERVER_URL : AMPLITUDE_SERVER_URL;\n};\n\nexport const createServerConfig = (\n serverUrl = '',\n serverZone: ServerZoneType = getDefaultConfig().serverZone,\n useBatch: boolean = getDefaultConfig().useBatch,\n) => {\n if (serverUrl) {\n return { serverUrl, serverZone: undefined };\n }\n const _serverZone = ['US', 'EU'].includes(serverZone) ? serverZone : getDefaultConfig().serverZone;\n return {\n serverZone: _serverZone,\n serverUrl: getServerUrl(_serverZone, useBatch),\n };\n};\n\nexport class RequestMetadata implements IRequestMetadata {\n sdk: {\n metrics: {\n histogram: HistogramOptions;\n };\n };\n\n constructor() {\n this.sdk = {\n metrics: {\n histogram: {},\n },\n };\n }\n\n recordHistogram<T extends HistogramKey>(key: T, value: HistogramOptions[T]) {\n this.sdk.metrics.histogram[key] = value;\n }\n}\n\nclass HistogramOptions implements IHistogramOptions {\n remote_config_fetch_time_IDB?: number;\n remote_config_fetch_time_API_success?: number;\n remote_config_fetch_time_API_fail?: number;\n}\n"]}
|
|
@@ -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;AAItD,eAAO,MAAM,gBAAgB,OAAO,CAAC;AACrC,eAAO,MAAM,iBAAiB,QAAgB,CAAC;AAC/C,eAAO,MAAM,yBAAyB,gEAAgE,CAAC;AACvG,eAAO,MAAM,yBAAyB,mEAAmE,CAAC;AAG1G,eAAO,MAAM,wBAAwB,QAAQ,CAAC;AAC9C,eAAO,MAAM,+BAA+B,KAAK,CAAC;AAIlD;;GAEG;AACH,KAAK,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAE9C;;GAEG;AACH,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,CAAC;IACF;;;OAGG;IACH,cAAc,EAAE,MAAM,CAAC;IAGvB,YAAY,EAAE,eAAe,CAAM;IACnC,gBAAgB,EAAE,mBAAmB,CAAM;IAC3C,kBAAkB,EAAE,yBAAyB,CAAM;IACnD,cAAc,EAAE,gBAAgB,EAAE,CAAM;IAGxC,SAAS,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG,IAAI,CAAQ;IAEvD,UAAU,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG,IAAI,CAAQ;gBAGtD,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,OAAO,EACf,UAAU,GAAE,cAAqB,EACjC,OAAO,CAAC,EAAE;QACR,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB,UAAU,CAAC,EAAE,MAAM,CAAC;KACrB;IA0BH;;OAEG;IACH,wBAAwB,IAAI,OAAO;IAInC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM;IAclC,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,SAAI;IAchC,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM;IA6B3C,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,eAAe;IAkBrD,mBAAmB;IA0Bb,oBAAoB;IAsBpB,MAAM;IAgEZ;;OAEG;IACG,KAAK,CAAC,OAAO,EAAE,YAAY;IA0BjC;;;;OAIG;IACG,uBAAuB;IA2B7B;;OAEG;IACH,OAAO,CAAC,cAAc;IAYtB,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;CAMzC"}
|
|
@@ -36,6 +36,10 @@ var DiagnosticsClient = /** @class */ (function () {
|
|
|
36
36
|
this.logger.debug('DiagnosticsClient: IndexedDB is not supported');
|
|
37
37
|
}
|
|
38
38
|
void this.initializeFlushInterval();
|
|
39
|
+
// Track internal diagnostics metrics for sampling
|
|
40
|
+
if (this.shouldTrack) {
|
|
41
|
+
this.increment('sdk.diagnostics.sampled.in.and.enabled');
|
|
42
|
+
}
|
|
39
43
|
}
|
|
40
44
|
/**
|
|
41
45
|
* Check if storage is available and tracking is enabled
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics-client.js","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-client.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,kBAAkB,EAAuB,MAAM,uBAAuB,CAAC;AAEhF,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,MAAM,CAAC,IAAM,gBAAgB,GAAG,IAAI,CAAC,CAAC,WAAW;AACjD,MAAM,CAAC,IAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,YAAY;AAC5D,MAAM,CAAC,IAAM,yBAAyB,GAAG,6DAA6D,CAAC;AACvG,MAAM,CAAC,IAAM,yBAAyB,GAAG,gEAAgE,CAAC;AAE1G,2BAA2B;AAC3B,MAAM,CAAC,IAAM,wBAAwB,GAAG,KAAK,CAAC,CAAC,4CAA4C;AAC3F,MAAM,CAAC,IAAM,+BAA+B,GAAG,EAAE,CAAC;AAkJlD;IA4BE,2BACE,MAAc,EACd,MAAe,EACf,UAAiC,EACjC,OAGC;QAJD,2BAAA,EAAA,iBAAiC;QAdnC,qBAAqB;QACrB,iBAAY,GAAoB,EAAE,CAAC;QACnC,qBAAgB,GAAwB,EAAE,CAAC;QAC3C,uBAAkB,GAA8B,EAAE,CAAC;QACnD,mBAAc,GAAuB,EAAE,CAAC;QAExC,iCAAiC;QACjC,cAAS,GAAyC,IAAI,CAAC;QACvD,2BAA2B;QAC3B,eAAU,GAAyC,IAAI,CAAC;QAWtD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,UAAU,KAAK,IAAI,C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CAAC,KAAK,CAAC,2CAA2C,EAAE,UAAU,CAAC,CAAC;QAC3E,IAAI,CAAC,MAAM,CAAC,UAAU,GAAG,UAAU,CAAC;QACpC,IAAI,CAAC,WAAW,GAAG,uBAAuB,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;QAC/G,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAC5E,CAAC;IACH,wBAAC;AAAD,CAAC,AA5UD,IA4UC","sourcesContent":["import { ILogger } from '../logger';\nimport { DiagnosticsStorage, IDiagnosticsStorage } from './diagnostics-storage';\nimport { ServerZoneType } from '../types/server-zone';\nimport { getGlobalScope } from '../global-scope';\nimport { isTimestampInSampleTemp } 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 = isTimestampInSampleTemp(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 = isTimestampInSampleTemp(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\n this.logger.debug('DiagnosticsClient: Should track is', this.shouldTrack);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"diagnostics-client.js","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-client.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,kBAAkB,EAAuB,MAAM,uBAAuB,CAAC;AAEhF,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,MAAM,CAAC,IAAM,gBAAgB,GAAG,IAAI,CAAC,CAAC,WAAW;AACjD,MAAM,CAAC,IAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,YAAY;AAC5D,MAAM,CAAC,IAAM,yBAAyB,GAAG,6DAA6D,CAAC;AACvG,MAAM,CAAC,IAAM,yBAAyB,GAAG,gEAAgE,CAAC;AAE1G,2BAA2B;AAC3B,MAAM,CAAC,IAAM,wBAAwB,GAAG,KAAK,CAAC,CAAC,4CAA4C;AAC3F,MAAM,CAAC,IAAM,+BAA+B,GAAG,EAAE,CAAC;AAkJlD;IA4BE,2BACE,MAAc,EACd,MAAe,EACf,UAAiC,EACjC,OAGC;QAJD,2BAAA,EAAA,iBAAiC;QAdnC,qBAAqB;QACrB,iBAAY,GAAoB,EAAE,CAAC;QACnC,qBAAgB,GAAwB,EAAE,CAAC;QAC3C,uBAAkB,GAA8B,EAAE,CAAC;QACnD,mBAAc,GAAuB,EAAE,CAAC;QAExC,iCAAiC;QACjC,cAAS,GAAyC,IAAI,CAAC;QACvD,2BAA2B;QAC3B,eAAU,GAAyC,IAAI,CAAC;QAWtD,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AAoC,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,uBAAuB,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;QAC/G,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAC5E,CAAC;IACH,wBAAC;AAAD,CAAC,AAjVD,IAiVC","sourcesContent":["import { ILogger } from '../logger';\nimport { DiagnosticsStorage, IDiagnosticsStorage } from './diagnostics-storage';\nimport { ServerZoneType } from '../types/server-zone';\nimport { getGlobalScope } from '../global-scope';\nimport { isTimestampInSampleTemp } 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 = isTimestampInSampleTemp(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 // Track internal diagnostics metrics for sampling\n if (this.shouldTrack) {\n this.increment('sdk.diagnostics.sampled.in.and.enabled');\n }\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 = isTimestampInSampleTemp(this.startTimestamp, this.config.sampleRate) && this.config.enabled;\n this.logger.debug('DiagnosticsClient: Should track is', this.shouldTrack);\n }\n}\n"]}
|
package/lib/esm/index.d.ts
CHANGED
|
@@ -44,7 +44,7 @@ export { Response } from './types/response';
|
|
|
44
44
|
export { UserSession } from './types/user-session';
|
|
45
45
|
export { Plugin, BeforePlugin, DestinationPlugin, EnrichmentPlugin, PluginType, AnalyticsIdentity, } from './types/plugin';
|
|
46
46
|
export { Result } from './types/result';
|
|
47
|
-
export { ElementInteractionsOptions, Messenger, ActionType, DEFAULT_CSS_SELECTOR_ALLOWLIST, DEFAULT_DATA_ATTRIBUTE_PREFIX, DEFAULT_ACTION_CLICK_ALLOWLIST, } from './types/element-interactions';
|
|
47
|
+
export { ElementInteractionsOptions, Messenger, ActionType, DEFAULT_CSS_SELECTOR_ALLOWLIST, DEFAULT_DATA_ATTRIBUTE_PREFIX, DEFAULT_ACTION_CLICK_ALLOWLIST, LabeledEvent, Trigger, DataSource, } from './types/element-interactions';
|
|
48
48
|
export { FrustrationInteractionsOptions, DEFAULT_DEAD_CLICK_ALLOWLIST, DEFAULT_RAGE_CLICK_ALLOWLIST, DEFAULT_RAGE_CLICK_THRESHOLD, DEFAULT_RAGE_CLICK_WINDOW_MS, DEFAULT_RAGE_CLICK_OUT_OF_BOUNDS_THRESHOLD, DEFAULT_DEAD_CLICK_WINDOW_MS, } from './types/frustration-interactions';
|
|
49
49
|
export { PageTrackingOptions, PageTrackingTrackOn, PageTrackingHistoryChanges } from './types/page-view-tracking';
|
|
50
50
|
export { Status } from './types/status';
|
package/lib/esm/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAClE,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AACrD,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACxG,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAChE,O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EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,kBAAkB,EAA6C,MAAM,+BAA+B,CAAC;AAE9G,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAErE,OAAO,EAEL,iBAAiB,EACjB,gBAAgB,GAIjB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EAAkB,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAelD,OAAO,EAIL,8BAA8B,EAC9B,6BAA6B,EAC7B,8BAA8B,GAI/B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAEL,4BAA4B,EAC5B,4BAA4B,EAC5B,4BAA4B,EAC5B,4BAA4B,EAC5B,0CAA0C,EAC1C,4BAA4B,GAC7B,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAExC,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAqD,MAAM,yBAAyB,CAAC;AAEjH,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAMpE,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EACL,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,sBAAsB,EACtB,QAAQ,EACR,SAAS,EACT,WAAW,GACZ,MAAM,mBAAmB,CAAC","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 {\n Event,\n IdentifyOperation,\n SpecialEventType,\n IdentifyEvent,\n GroupIdentifyEvent,\n IdentifyUserProperties,\n} 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 LabeledEvent,\n Trigger,\n DataSource,\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';\nexport {\n getPageTitle,\n TEXT_MASK_ATTRIBUTE,\n MASKED_TEXT_VALUE,\n replaceSensitiveString,\n CC_REGEX,\n SSN_REGEX,\n EMAIL_REGEX,\n} from './plugins/helpers';\n\n// Browser\nexport {\n BrowserConfig,\n BrowserOptions,\n DefaultTrackingOptions,\n TrackingOptions,\n AutocaptureOptions,\n CookieOptions,\n AttributionOptions,\n RemoteConfigOptions,\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"]}
|
|
@@ -4,6 +4,7 @@ import { Result } from '../types/result';
|
|
|
4
4
|
import { Response, InvalidResponse, PayloadTooLargeResponse, RateLimitResponse, SuccessResponse } from '../types/response';
|
|
5
5
|
import { IConfig } from '../types/config/core-config';
|
|
6
6
|
import { EventCallback } from '../types/event-callback';
|
|
7
|
+
import { IDiagnosticsClient } from '../diagnostics/diagnostics-client';
|
|
7
8
|
export interface Context {
|
|
8
9
|
event: Event;
|
|
9
10
|
attempts: number;
|
|
@@ -22,6 +23,10 @@ export declare class Destination implements DestinationPlugin {
|
|
|
22
23
|
scheduledTimeout: number;
|
|
23
24
|
flushId: ReturnType<typeof setTimeout> | null;
|
|
24
25
|
queue: Context[];
|
|
26
|
+
diagnosticsClient: IDiagnosticsClient | undefined;
|
|
27
|
+
constructor(context?: {
|
|
28
|
+
diagnosticsClient: IDiagnosticsClient;
|
|
29
|
+
});
|
|
25
30
|
setup(config: IConfig): Promise<undefined>;
|
|
26
31
|
execute(event: Event): Promise<Result>;
|
|
27
32
|
removeEventsExceedFlushMaxRetries(list: Context[]): Context[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"destination.d.ts","sourceRoot":"","sources":["../../../src/plugins/destination.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,s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buildResult } from '../utils/result-builder';
|
|
7
7
|
import { createServerConfig, RequestMetadata } from '../config';
|
|
8
8
|
import { UUID } from '../utils/uuid';
|
|
9
|
+
import { isSuccessStatusCode } from '../utils/status-code';
|
|
10
|
+
import { getStacktrace } from '../utils/debug';
|
|
9
11
|
function getErrorMessage(error) {
|
|
10
12
|
if (error instanceof Error)
|
|
11
13
|
return error.message;
|
|
@@ -24,7 +26,7 @@ export function getResponseBodyString(res) {
|
|
|
24
26
|
return responseBodyString;
|
|
25
27
|
}
|
|
26
28
|
var Destination = /** @class */ (function () {
|
|
27
|
-
function Destination() {
|
|
29
|
+
function Destination(context) {
|
|
28
30
|
this.name = 'amplitude';
|
|
29
31
|
this.type = 'destination';
|
|
30
32
|
this.retryTimeout = 1000;
|
|
@@ -41,6 +43,7 @@ var Destination = /** @class */ (function () {
|
|
|
41
43
|
// When flush resolves, set `flushId` to null
|
|
42
44
|
this.flushId = null;
|
|
43
45
|
this.queue = [];
|
|
46
|
+
this.diagnosticsClient = context === null || context === void 0 ? void 0 : context.diagnosticsClient;
|
|
44
47
|
}
|
|
45
48
|
Destination.prototype.setup = function (config) {
|
|
46
49
|
var _a;
|
|
@@ -334,6 +337,20 @@ var Destination = /** @class */ (function () {
|
|
|
334
337
|
this.scheduleEvents(tryable);
|
|
335
338
|
};
|
|
336
339
|
Destination.prototype.fulfillRequest = function (list, code, message) {
|
|
340
|
+
var _a, _b, _c;
|
|
341
|
+
// Record diagnostics for dropped events (non-success status codes)
|
|
342
|
+
if (!isSuccessStatusCode(code)) {
|
|
343
|
+
(_a = this.diagnosticsClient) === null || _a === void 0 ? void 0 : _a.increment('analytics.events.dropped', list.length);
|
|
344
|
+
(_b = this.diagnosticsClient) === null || _b === void 0 ? void 0 : _b.recordEvent('analytics.events.dropped', {
|
|
345
|
+
events: list.map(function (context) { return context.event.event_type; }),
|
|
346
|
+
code: code,
|
|
347
|
+
message: message,
|
|
348
|
+
stack_trace: getStacktrace(),
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
else {
|
|
352
|
+
(_c = this.diagnosticsClient) === null || _c === void 0 ? void 0 : _c.increment('analytics.events.sent', list.length);
|
|
353
|
+
}
|
|
337
354
|
this.removeEvents(list);
|
|
338
355
|
list.forEach(function (context) { return context.callback(buildResult(context.event, code, message)); });
|
|
339
356
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"destination.js","sourceRoot":"","sources":["../../../src/plugins/destination.ts"],"names":[],"mappings":";AAGA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAQzC,OAAO,EACL,eAAe,EACf,4BAA4B,EAC5B,uBAAuB,EACvB,eAAe,EACf,wBAAwB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAChE,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAWrC,SAAS,eAAe,CAAC,KAAc;IACrC,IAAI,KAAK,YAAY,KAAK;QAAE,OAAO,KAAK,CAAC,OAAO,CAAC;IACjD,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;AACvB,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,GAAa;IACjD,IAAI,kBAAkB,GAAG,EAAE,CAAC;IAC5B,IAAI;QACF,IAAI,MAAM,IAAI,GAAG,EAAE;YACjB,kBAAkB,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;SACxD;KACF;IAAC,WAAM;QACN,8FAA8F;KAC/F;IACD,OAAO,kBAAkB,CAAC;AAC5B,CAAC;AAED;IAAA;QACE,SAAI,GAAG,WAAW,CAAC;QACnB,SAAI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AY,CAAC,IAAI,CAAC,CAAC;QACxB,IAAI,CAAC,OAAO,CAAC,UAAC,OAAO,IAAK,OAAA,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,EAA3D,CAA2D,CAAC,CAAC;IACzF,CAAC;IAED;;;;;;OAMG;IACH,gCAAU,GAAV;QACE,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,EAAE;YAChC,OAAO;SACR;QAED,IAAM,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAC,OAAO,IAAK,OAAA,OAAO,CAAC,KAAK,EAAb,CAAa,CAAC,CAAC;QACjE,KAAK,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,EAAE,aAAa,CAAC,CAAC;IACvE,CAAC;IAED;;OAEG;IACH,kCAAY,GAAZ,UAAa,cAAyB;QACpC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAC5B,UAAC,aAAa,IAAK,OAAA,CAAC,cAAc,CAAC,IAAI,CAAC,UAAC,OAAO,IAAK,OAAA,OAAO,CAAC,KAAK,CAAC,SAAS,KAAK,aAAa,CAAC,KAAK,CAAC,SAAS,EAAzD,CAAyD,CAAC,EAA5F,CAA4F,CAChH,CAAC;QAEF,IAAI,CAAC,UAAU,EAAE,CAAC;IACpB,CAAC;IACH,kBAAC;AAAD,CAAC,AA7UD,IA6UC","sourcesContent":["import { DestinationPlugin } from '../types/plugin';\nimport { Event } from '../types/event/event';\nimport { Result } from '../types/result';\nimport { Status } from '../types/status';\nimport {\n Response,\n InvalidResponse,\n PayloadTooLargeResponse,\n RateLimitResponse,\n SuccessResponse,\n} from '../types/response';\nimport {\n INVALID_API_KEY,\n MAX_RETRIES_EXCEEDED_MESSAGE,\n MISSING_API_KEY_MESSAGE,\n SUCCESS_MESSAGE,\n UNEXPECTED_ERROR_MESSAGE,\n} from '../types/messages';\nimport { STORAGE_PREFIX } from '../types/constants';\nimport { chunk } from '../utils/chunk';\nimport { buildResult } from '../utils/result-builder';\nimport { createServerConfig, RequestMetadata } from '../config';\nimport { UUID } from '../utils/uuid';\nimport { IConfig } from '../types/config/core-config';\nimport { EventCallback } from '../types/event-callback';\n\nexport interface Context {\n event: Event;\n attempts: number;\n callback: EventCallback;\n timeout: number;\n}\n\nfunction getErrorMessage(error: unknown) {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nexport function getResponseBodyString(res: Response) {\n let responseBodyString = '';\n try {\n if ('body' in res) {\n responseBodyString = JSON.stringify(res.body, null, 2);\n }\n } catch {\n // to avoid crash, but don't care about the error, add comment to avoid empty block lint error\n }\n return responseBodyString;\n}\n\nexport class Destination implements DestinationPlugin {\n name = 'amplitude';\n type = 'destination' as const;\n\n retryTimeout = 1000;\n throttleTimeout = 30000;\n storageKey = '';\n // this.config is defined in setup() which will always be called first\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n config: IConfig;\n // Indicator of whether events that are scheduled (but not flushed yet).\n // When flush:\n // 1. assign `scheduleId` to `flushId`\n // 2. set `scheduleId` to null\n scheduleId: ReturnType<typeof setTimeout> | null = null;\n // Timeout in milliseconds of current schedule\n scheduledTimeout = 0;\n // Indicator of whether current flush resolves.\n // When flush resolves, set `flushId` to null\n flushId: ReturnType<typeof setTimeout> | null = null;\n queue: Context[] = [];\n\n async setup(config: IConfig): Promise<undefined> {\n this.config = config;\n\n this.storageKey = `${STORAGE_PREFIX}_${this.config.apiKey.substring(0, 10)}`;\n const unsent = await this.config.storageProvider?.get(this.storageKey);\n if (unsent && unsent.length > 0) {\n void Promise.all(unsent.map((event: Event) => this.execute(event))).catch();\n }\n\n return Promise.resolve(undefined);\n }\n\n execute(event: Event): Promise<Result> {\n // Assign insert_id for dropping invalid event later\n if (!event.insert_id) {\n event.insert_id = UUID();\n }\n\n return new Promise((resolve) => {\n const context = {\n event,\n attempts: 0,\n callback: (result: Result) => resolve(result),\n timeout: 0,\n };\n this.queue.push(context);\n this.schedule(this.config.flushIntervalMillis);\n this.saveEvents();\n });\n }\n\n removeEventsExceedFlushMaxRetries(list: Context[]) {\n return list.filter((context) => {\n context.attempts += 1;\n if (context.attempts < this.config.flushMaxRetries) {\n return true;\n }\n void this.fulfillRequest([context], 500, MAX_RETRIES_EXCEEDED_MESSAGE);\n return false;\n });\n }\n\n scheduleEvents(list: Context[]) {\n list.forEach((context) => {\n this.schedule(context.timeout === 0 ? this.config.flushIntervalMillis : context.timeout);\n });\n }\n\n // Schedule a flush in timeout when\n // 1. No schedule\n // 2. Timeout greater than existing timeout.\n // This makes sure that when throttled, no flush when throttle timeout expires.\n schedule(timeout: number) {\n if (this.config.offline) {\n return;\n }\n\n if (this.scheduleId === null || (this.scheduleId && timeout > this.scheduledTimeout)) {\n if (this.scheduleId) {\n clearTimeout(this.scheduleId);\n }\n this.scheduledTimeout = timeout;\n this.scheduleId = setTimeout(() => {\n this.queue = this.queue.map((context) => {\n context.timeout = 0;\n return context;\n });\n void this.flush(true);\n }, timeout);\n return;\n }\n }\n\n // Mark current schedule is flushed.\n resetSchedule() {\n this.scheduleId = null;\n this.scheduledTimeout = 0;\n }\n\n // Flush all events regardless of their timeout\n async flush(useRetry = false) {\n // Skip flush if offline\n if (this.config.offline) {\n this.resetSchedule();\n this.config.loggerProvider.debug('Skipping flush while offline.');\n return;\n }\n\n if (this.flushId) {\n this.resetSchedule();\n this.config.loggerProvider.debug('Skipping flush because previous flush has not resolved.');\n return;\n }\n\n this.flushId = this.scheduleId;\n this.resetSchedule();\n\n const list: Context[] = [];\n const later: Context[] = [];\n this.queue.forEach((context) => (context.timeout === 0 ? list.push(context) : later.push(context)));\n\n const batches = chunk(list, this.config.flushQueueSize);\n\n // Promise.all() doesn't guarantee resolve order.\n // Sequentially resolve to make sure backend receives events in order\n await batches.reduce(async (promise, batch) => {\n await promise;\n return await this.send(batch, useRetry);\n }, Promise.resolve());\n\n // Mark current flush is done\n this.flushId = null;\n\n this.scheduleEvents(this.queue);\n }\n\n async send(list: Context[], useRetry = true) {\n if (!this.config.apiKey) {\n return this.fulfillRequest(list, 400, MISSING_API_KEY_MESSAGE);\n }\n\n const payload = {\n api_key: this.config.apiKey,\n events: list.map((context) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { extra, ...eventWithoutExtra } = context.event;\n return eventWithoutExtra;\n }),\n options: {\n min_id_length: this.config.minIdLength,\n },\n client_upload_time: new Date().toISOString(),\n request_metadata: this.config.requestMetadata,\n };\n this.config.requestMetadata = new RequestMetadata();\n\n try {\n const { serverUrl } = createServerConfig(this.config.serverUrl, this.config.serverZone, this.config.useBatch);\n const res = await this.config.transportProvider.send(serverUrl, payload);\n if (res === null) {\n this.fulfillRequest(list, 0, UNEXPECTED_ERROR_MESSAGE);\n return;\n }\n if (!useRetry) {\n if ('body' in res) {\n this.fulfillRequest(list, res.statusCode, `${res.status}: ${getResponseBodyString(res)}`);\n } else {\n this.fulfillRequest(list, res.statusCode, res.status);\n }\n return;\n }\n this.handleResponse(res, list);\n } catch (e) {\n const errorMessage = getErrorMessage(e);\n this.config.loggerProvider.error(errorMessage);\n this.handleResponse({ status: Status.Failed, statusCode: 0 }, list);\n }\n }\n\n handleResponse(res: Response, list: Context[]) {\n const { status } = res;\n\n switch (status) {\n case Status.Success: {\n this.handleSuccessResponse(res, list);\n break;\n }\n case Status.Invalid: {\n this.handleInvalidResponse(res, list);\n break;\n }\n case Status.PayloadTooLarge: {\n this.handlePayloadTooLargeResponse(res, list);\n break;\n }\n case Status.RateLimit: {\n this.handleRateLimitResponse(res, list);\n break;\n }\n default: {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(`{code: 0, error: \"Status '${status}' provided for ${list.length} events\"}`);\n this.handleOtherResponse(list);\n break;\n }\n }\n }\n\n handleSuccessResponse(res: SuccessResponse, list: Context[]) {\n this.fulfillRequest(list, res.statusCode, SUCCESS_MESSAGE);\n }\n\n handleInvalidResponse(res: InvalidResponse, list: Context[]) {\n if (res.body.missingField || res.body.error.startsWith(INVALID_API_KEY)) {\n this.fulfillRequest(list, res.statusCode, res.body.error);\n return;\n }\n\n const dropIndex = [\n ...Object.values(res.body.eventsWithInvalidFields),\n ...Object.values(res.body.eventsWithMissingFields),\n ...Object.values(res.body.eventsWithInvalidIdLengths),\n ...res.body.silencedEvents,\n ].flat();\n const dropIndexSet = new Set(dropIndex);\n\n const retry = list.filter((context, index) => {\n if (dropIndexSet.has(index)) {\n this.fulfillRequest([context], res.statusCode, res.body.error);\n return;\n }\n return true;\n });\n\n if (retry.length > 0) {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n }\n\n const tryable = this.removeEventsExceedFlushMaxRetries(retry);\n this.scheduleEvents(tryable);\n }\n\n handlePayloadTooLargeResponse(res: PayloadTooLargeResponse, list: Context[]) {\n if (list.length === 1) {\n this.fulfillRequest(list, res.statusCode, res.body.error);\n return;\n }\n\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n\n this.config.flushQueueSize /= 2;\n\n const tryable = this.removeEventsExceedFlushMaxRetries(list);\n this.scheduleEvents(tryable);\n }\n\n handleRateLimitResponse(res: RateLimitResponse, list: Context[]) {\n const dropUserIds = Object.keys(res.body.exceededDailyQuotaUsers);\n const dropDeviceIds = Object.keys(res.body.exceededDailyQuotaDevices);\n const throttledIndex = res.body.throttledEvents;\n const dropUserIdsSet = new Set(dropUserIds);\n const dropDeviceIdsSet = new Set(dropDeviceIds);\n const throttledIndexSet = new Set(throttledIndex);\n\n const retry = list.filter((context, index) => {\n if (\n (context.event.user_id && dropUserIdsSet.has(context.event.user_id)) ||\n (context.event.device_id && dropDeviceIdsSet.has(context.event.device_id))\n ) {\n this.fulfillRequest([context], res.statusCode, res.body.error);\n return;\n }\n if (throttledIndexSet.has(index)) {\n context.timeout = this.throttleTimeout;\n }\n return true;\n });\n\n if (retry.length > 0) {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n }\n\n const tryable = this.removeEventsExceedFlushMaxRetries(retry);\n this.scheduleEvents(tryable);\n }\n\n handleOtherResponse(list: Context[]) {\n const later = list.map((context) => {\n context.timeout = context.attempts * this.retryTimeout;\n return context;\n });\n\n const tryable = this.removeEventsExceedFlushMaxRetries(later);\n this.scheduleEvents(tryable);\n }\n\n fulfillRequest(list: Context[], code: number, message: string) {\n this.removeEvents(list);\n list.forEach((context) => context.callback(buildResult(context.event, code, message)));\n }\n\n /**\n * This is called on\n * 1) new events are added to queue; or\n * 2) response comes back for a request\n *\n * Update the event storage based on the queue\n */\n saveEvents() {\n if (!this.config.storageProvider) {\n return;\n }\n\n const updatedEvents = this.queue.map((context) => context.event);\n void this.config.storageProvider.set(this.storageKey, updatedEvents);\n }\n\n /**\n * This is called on response comes back for a request\n */\n removeEvents(eventsToRemove: Context[]) {\n this.queue = this.queue.filter(\n (queuedContext) => !eventsToRemove.some((context) => context.event.insert_id === queuedContext.event.insert_id),\n );\n\n this.saveEvents();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"destination.js","sourceRoot":"","sources":["../../../src/plugins/destination.ts"],"names":[],"mappings":";AAGA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAQzC,OAAO,EACL,eAAe,EACf,4BAA4B,EAC5B,uBAAuB,EACvB,eAAe,EACf,wBAAwB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAChE,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAIrC,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO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AAC;QACxB,IAAI,CAAC,OAAO,CAAC,UAAC,OAAO,IAAK,OAAA,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,EAA3D,CAA2D,CAAC,CAAC;IACzF,CAAC;IAED;;;;;;OAMG;IACH,gCAAU,GAAV;QACE,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,EAAE;YAChC,OAAO;SACR;QAED,IAAM,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAC,OAAO,IAAK,OAAA,OAAO,CAAC,KAAK,EAAb,CAAa,CAAC,CAAC;QACjE,KAAK,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,EAAE,aAAa,CAAC,CAAC;IACvE,CAAC;IAED;;OAEG;IACH,kCAAY,GAAZ,UAAa,cAAyB;QACpC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAC5B,UAAC,aAAa,IAAK,OAAA,CAAC,cAAc,CAAC,IAAI,CAAC,UAAC,OAAO,IAAK,OAAA,OAAO,CAAC,KAAK,CAAC,SAAS,KAAK,aAAa,CAAC,KAAK,CAAC,SAAS,EAAzD,CAAyD,CAAC,EAA5F,CAA4F,CAChH,CAAC;QAEF,IAAI,CAAC,UAAU,EAAE,CAAC;IACpB,CAAC;IACH,kBAAC;AAAD,CAAC,AA/VD,IA+VC","sourcesContent":["import { DestinationPlugin } from '../types/plugin';\nimport { Event } from '../types/event/event';\nimport { Result } from '../types/result';\nimport { Status } from '../types/status';\nimport {\n Response,\n InvalidResponse,\n PayloadTooLargeResponse,\n RateLimitResponse,\n SuccessResponse,\n} from '../types/response';\nimport {\n INVALID_API_KEY,\n MAX_RETRIES_EXCEEDED_MESSAGE,\n MISSING_API_KEY_MESSAGE,\n SUCCESS_MESSAGE,\n UNEXPECTED_ERROR_MESSAGE,\n} from '../types/messages';\nimport { STORAGE_PREFIX } from '../types/constants';\nimport { chunk } from '../utils/chunk';\nimport { buildResult } from '../utils/result-builder';\nimport { createServerConfig, RequestMetadata } from '../config';\nimport { UUID } from '../utils/uuid';\nimport { IConfig } from '../types/config/core-config';\nimport { EventCallback } from '../types/event-callback';\nimport { IDiagnosticsClient } from '../diagnostics/diagnostics-client';\nimport { isSuccessStatusCode } from '../utils/status-code';\nimport { getStacktrace } from '../utils/debug';\n\nexport interface Context {\n event: Event;\n attempts: number;\n callback: EventCallback;\n timeout: number;\n}\n\nfunction getErrorMessage(error: unknown) {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nexport function getResponseBodyString(res: Response) {\n let responseBodyString = '';\n try {\n if ('body' in res) {\n responseBodyString = JSON.stringify(res.body, null, 2);\n }\n } catch {\n // to avoid crash, but don't care about the error, add comment to avoid empty block lint error\n }\n return responseBodyString;\n}\n\nexport class Destination implements DestinationPlugin {\n name = 'amplitude';\n type = 'destination' as const;\n\n retryTimeout = 1000;\n throttleTimeout = 30000;\n storageKey = '';\n // this.config is defined in setup() which will always be called first\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n config: IConfig;\n // Indicator of whether events that are scheduled (but not flushed yet).\n // When flush:\n // 1. assign `scheduleId` to `flushId`\n // 2. set `scheduleId` to null\n scheduleId: ReturnType<typeof setTimeout> | null = null;\n // Timeout in milliseconds of current schedule\n scheduledTimeout = 0;\n // Indicator of whether current flush resolves.\n // When flush resolves, set `flushId` to null\n flushId: ReturnType<typeof setTimeout> | null = null;\n queue: Context[] = [];\n diagnosticsClient: IDiagnosticsClient | undefined;\n\n constructor(context?: { diagnosticsClient: IDiagnosticsClient }) {\n this.diagnosticsClient = context?.diagnosticsClient;\n }\n\n async setup(config: IConfig): Promise<undefined> {\n this.config = config;\n\n this.storageKey = `${STORAGE_PREFIX}_${this.config.apiKey.substring(0, 10)}`;\n const unsent = await this.config.storageProvider?.get(this.storageKey);\n if (unsent && unsent.length > 0) {\n void Promise.all(unsent.map((event: Event) => this.execute(event))).catch();\n }\n\n return Promise.resolve(undefined);\n }\n\n execute(event: Event): Promise<Result> {\n // Assign insert_id for dropping invalid event later\n if (!event.insert_id) {\n event.insert_id = UUID();\n }\n\n return new Promise((resolve) => {\n const context = {\n event,\n attempts: 0,\n callback: (result: Result) => resolve(result),\n timeout: 0,\n };\n this.queue.push(context);\n this.schedule(this.config.flushIntervalMillis);\n this.saveEvents();\n });\n }\n\n removeEventsExceedFlushMaxRetries(list: Context[]) {\n return list.filter((context) => {\n context.attempts += 1;\n if (context.attempts < this.config.flushMaxRetries) {\n return true;\n }\n void this.fulfillRequest([context], 500, MAX_RETRIES_EXCEEDED_MESSAGE);\n return false;\n });\n }\n\n scheduleEvents(list: Context[]) {\n list.forEach((context) => {\n this.schedule(context.timeout === 0 ? this.config.flushIntervalMillis : context.timeout);\n });\n }\n\n // Schedule a flush in timeout when\n // 1. No schedule\n // 2. Timeout greater than existing timeout.\n // This makes sure that when throttled, no flush when throttle timeout expires.\n schedule(timeout: number) {\n if (this.config.offline) {\n return;\n }\n\n if (this.scheduleId === null || (this.scheduleId && timeout > this.scheduledTimeout)) {\n if (this.scheduleId) {\n clearTimeout(this.scheduleId);\n }\n this.scheduledTimeout = timeout;\n this.scheduleId = setTimeout(() => {\n this.queue = this.queue.map((context) => {\n context.timeout = 0;\n return context;\n });\n void this.flush(true);\n }, timeout);\n return;\n }\n }\n\n // Mark current schedule is flushed.\n resetSchedule() {\n this.scheduleId = null;\n this.scheduledTimeout = 0;\n }\n\n // Flush all events regardless of their timeout\n async flush(useRetry = false) {\n // Skip flush if offline\n if (this.config.offline) {\n this.resetSchedule();\n this.config.loggerProvider.debug('Skipping flush while offline.');\n return;\n }\n\n if (this.flushId) {\n this.resetSchedule();\n this.config.loggerProvider.debug('Skipping flush because previous flush has not resolved.');\n return;\n }\n\n this.flushId = this.scheduleId;\n this.resetSchedule();\n\n const list: Context[] = [];\n const later: Context[] = [];\n this.queue.forEach((context) => (context.timeout === 0 ? list.push(context) : later.push(context)));\n\n const batches = chunk(list, this.config.flushQueueSize);\n\n // Promise.all() doesn't guarantee resolve order.\n // Sequentially resolve to make sure backend receives events in order\n await batches.reduce(async (promise, batch) => {\n await promise;\n return await this.send(batch, useRetry);\n }, Promise.resolve());\n\n // Mark current flush is done\n this.flushId = null;\n\n this.scheduleEvents(this.queue);\n }\n\n async send(list: Context[], useRetry = true) {\n if (!this.config.apiKey) {\n return this.fulfillRequest(list, 400, MISSING_API_KEY_MESSAGE);\n }\n\n const payload = {\n api_key: this.config.apiKey,\n events: list.map((context) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { extra, ...eventWithoutExtra } = context.event;\n return eventWithoutExtra;\n }),\n options: {\n min_id_length: this.config.minIdLength,\n },\n client_upload_time: new Date().toISOString(),\n request_metadata: this.config.requestMetadata,\n };\n this.config.requestMetadata = new RequestMetadata();\n\n try {\n const { serverUrl } = createServerConfig(this.config.serverUrl, this.config.serverZone, this.config.useBatch);\n const res = await this.config.transportProvider.send(serverUrl, payload);\n if (res === null) {\n this.fulfillRequest(list, 0, UNEXPECTED_ERROR_MESSAGE);\n return;\n }\n if (!useRetry) {\n if ('body' in res) {\n this.fulfillRequest(list, res.statusCode, `${res.status}: ${getResponseBodyString(res)}`);\n } else {\n this.fulfillRequest(list, res.statusCode, res.status);\n }\n return;\n }\n this.handleResponse(res, list);\n } catch (e) {\n const errorMessage = getErrorMessage(e);\n this.config.loggerProvider.error(errorMessage);\n\n this.handleResponse({ status: Status.Failed, statusCode: 0 }, list);\n }\n }\n\n handleResponse(res: Response, list: Context[]) {\n const { status } = res;\n\n switch (status) {\n case Status.Success: {\n this.handleSuccessResponse(res, list);\n break;\n }\n case Status.Invalid: {\n this.handleInvalidResponse(res, list);\n break;\n }\n case Status.PayloadTooLarge: {\n this.handlePayloadTooLargeResponse(res, list);\n break;\n }\n case Status.RateLimit: {\n this.handleRateLimitResponse(res, list);\n break;\n }\n default: {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(`{code: 0, error: \"Status '${status}' provided for ${list.length} events\"}`);\n this.handleOtherResponse(list);\n break;\n }\n }\n }\n\n handleSuccessResponse(res: SuccessResponse, list: Context[]) {\n this.fulfillRequest(list, res.statusCode, SUCCESS_MESSAGE);\n }\n\n handleInvalidResponse(res: InvalidResponse, list: Context[]) {\n if (res.body.missingField || res.body.error.startsWith(INVALID_API_KEY)) {\n this.fulfillRequest(list, res.statusCode, res.body.error);\n return;\n }\n\n const dropIndex = [\n ...Object.values(res.body.eventsWithInvalidFields),\n ...Object.values(res.body.eventsWithMissingFields),\n ...Object.values(res.body.eventsWithInvalidIdLengths),\n ...res.body.silencedEvents,\n ].flat();\n const dropIndexSet = new Set(dropIndex);\n\n const retry = list.filter((context, index) => {\n if (dropIndexSet.has(index)) {\n this.fulfillRequest([context], res.statusCode, res.body.error);\n return;\n }\n return true;\n });\n\n if (retry.length > 0) {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n }\n\n const tryable = this.removeEventsExceedFlushMaxRetries(retry);\n this.scheduleEvents(tryable);\n }\n\n handlePayloadTooLargeResponse(res: PayloadTooLargeResponse, list: Context[]) {\n if (list.length === 1) {\n this.fulfillRequest(list, res.statusCode, res.body.error);\n return;\n }\n\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n\n this.config.flushQueueSize /= 2;\n\n const tryable = this.removeEventsExceedFlushMaxRetries(list);\n this.scheduleEvents(tryable);\n }\n\n handleRateLimitResponse(res: RateLimitResponse, list: Context[]) {\n const dropUserIds = Object.keys(res.body.exceededDailyQuotaUsers);\n const dropDeviceIds = Object.keys(res.body.exceededDailyQuotaDevices);\n const throttledIndex = res.body.throttledEvents;\n const dropUserIdsSet = new Set(dropUserIds);\n const dropDeviceIdsSet = new Set(dropDeviceIds);\n const throttledIndexSet = new Set(throttledIndex);\n\n const retry = list.filter((context, index) => {\n if (\n (context.event.user_id && dropUserIdsSet.has(context.event.user_id)) ||\n (context.event.device_id && dropDeviceIdsSet.has(context.event.device_id))\n ) {\n this.fulfillRequest([context], res.statusCode, res.body.error);\n return;\n }\n if (throttledIndexSet.has(index)) {\n context.timeout = this.throttleTimeout;\n }\n return true;\n });\n\n if (retry.length > 0) {\n // log intermediate event status before retry\n this.config.loggerProvider.warn(getResponseBodyString(res));\n }\n\n const tryable = this.removeEventsExceedFlushMaxRetries(retry);\n this.scheduleEvents(tryable);\n }\n\n handleOtherResponse(list: Context[]) {\n const later = list.map((context) => {\n context.timeout = context.attempts * this.retryTimeout;\n return context;\n });\n\n const tryable = this.removeEventsExceedFlushMaxRetries(later);\n this.scheduleEvents(tryable);\n }\n\n fulfillRequest(list: Context[], code: number, message: string) {\n // Record diagnostics for dropped events (non-success status codes)\n if (!isSuccessStatusCode(code)) {\n this.diagnosticsClient?.increment('analytics.events.dropped', list.length);\n this.diagnosticsClient?.recordEvent('analytics.events.dropped', {\n events: list.map((context) => context.event.event_type),\n code: code,\n message: message,\n stack_trace: getStacktrace(),\n });\n } else {\n this.diagnosticsClient?.increment('analytics.events.sent', list.length);\n }\n this.removeEvents(list);\n list.forEach((context) => context.callback(buildResult(context.event, code, message)));\n }\n\n /**\n * This is called on\n * 1) new events are added to queue; or\n * 2) response comes back for a request\n *\n * Update the event storage based on the queue\n */\n saveEvents() {\n if (!this.config.storageProvider) {\n return;\n }\n\n const updatedEvents = this.queue.map((context) => context.event);\n void this.config.storageProvider.set(this.storageKey, updatedEvents);\n }\n\n /**\n * This is called on response comes back for a request\n */\n removeEvents(eventsToRemove: Context[]) {\n this.queue = this.queue.filter(\n (queuedContext) => !eventsToRemove.some((context) => context.event.insert_id === queuedContext.event.insert_id),\n );\n\n this.saveEvents();\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../src/transports/base.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../src/transports/base.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAG7C,qBAAa,aAAc,YAAW,SAAS;IAC7C,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;IAIrE,aAAa,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,QAAQ,GAAG,IAAI;IAqEjE,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CA2BlC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Status } from '../types/status';
|
|
2
|
+
import { isSuccessStatusCode } from '../utils/status-code';
|
|
2
3
|
var BaseTransport = /** @class */ (function () {
|
|
3
4
|
function BaseTransport() {
|
|
4
5
|
}
|
|
@@ -72,7 +73,7 @@ var BaseTransport = /** @class */ (function () {
|
|
|
72
73
|
}
|
|
73
74
|
};
|
|
74
75
|
BaseTransport.prototype.buildStatus = function (code) {
|
|
75
|
-
if (code
|
|
76
|
+
if (isSuccessStatusCode(code)) {
|
|
76
77
|
return Status.Success;
|
|
77
78
|
}
|
|
78
79
|
if (code === 429) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/transports/base.ts"],"names":[],"mappings":"AAIA,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M,QAAA;oBACN,UAAU,YAAA;iBACX,CAAC;SACL;IACH,CAAC;IAED,mCAAW,GAAX,UAAY,IAAY;QACtB,IAAI,mBAAmB,CAAC,IAAI,CAAC,EAAE;YAC7B,OAAO,MAAM,CAAC,OAAO,CAAC;SACvB;QAED,IAAI,IAAI,KAAK,GAAG,EAAE;YAChB,OAAO,MAAM,CAAC,SAAS,CAAC;SACzB;QAED,IAAI,IAAI,KAAK,GAAG,EAAE;YAChB,OAAO,MAAM,CAAC,eAAe,CAAC;SAC/B;QAED,IAAI,IAAI,KAAK,GAAG,EAAE;YAChB,OAAO,MAAM,CAAC,OAAO,CAAC;SACvB;QAED,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,EAAE;YAC7B,OAAO,MAAM,CAAC,OAAO,CAAC;SACvB;QAED,IAAI,IAAI,IAAI,GAAG,EAAE;YACf,OAAO,MAAM,CAAC,MAAM,CAAC;SACtB;QAED,OAAO,MAAM,CAAC,OAAO,CAAC;IACxB,CAAC;IACH,oBAAC;AAAD,CAAC,AArGD,IAqGC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-argument */\n/* eslint-disable @typescript-eslint/no-unsafe-assignment */\n/* eslint-disable @typescript-eslint/no-unsafe-call */\nimport { Transport } from '../types/transport';\nimport { Status } from '../types/status';\nimport { Payload } from '../types/payload';\nimport { Response } from '../types/response';\nimport { isSuccessStatusCode } from '../utils/status-code';\n\nexport class BaseTransport implements Transport {\n send(_serverUrl: string, _payload: Payload): Promise<Response | null> {\n return Promise.resolve(null);\n }\n\n buildResponse(responseJSON: Record<string, any>): Response | null {\n if (typeof responseJSON !== 'object') {\n return null;\n }\n\n const statusCode = responseJSON.code || 0;\n const status = this.buildStatus(statusCode);\n\n switch (status) {\n case Status.Success:\n return {\n status,\n statusCode,\n body: {\n eventsIngested: responseJSON.events_ingested ?? 0,\n payloadSizeBytes: responseJSON.payload_size_bytes ?? 0,\n serverUploadTime: responseJSON.server_upload_time ?? 0,\n },\n };\n\n case Status.Invalid:\n return {\n status,\n statusCode,\n body: {\n error: responseJSON.error ?? '',\n missingField: responseJSON.missing_field ?? '',\n eventsWithInvalidFields: responseJSON.events_with_invalid_fields ?? {},\n eventsWithMissingFields: responseJSON.events_with_missing_fields ?? {},\n eventsWithInvalidIdLengths: responseJSON.events_with_invalid_id_lengths ?? {},\n epsThreshold: responseJSON.eps_threshold ?? 0,\n exceededDailyQuotaDevices: responseJSON.exceeded_daily_quota_devices ?? {},\n silencedDevices: responseJSON.silenced_devices ?? [],\n silencedEvents: responseJSON.silenced_events ?? [],\n throttledDevices: responseJSON.throttled_devices ?? {},\n throttledEvents: responseJSON.throttled_events ?? [],\n },\n };\n case Status.PayloadTooLarge:\n return {\n status,\n statusCode,\n body: {\n error: responseJSON.error ?? '',\n },\n };\n case Status.RateLimit:\n return {\n status,\n statusCode,\n body: {\n error: responseJSON.error ?? '',\n epsThreshold: responseJSON.eps_threshold ?? 0,\n throttledDevices: responseJSON.throttled_devices ?? {},\n throttledUsers: responseJSON.throttled_users ?? {},\n exceededDailyQuotaDevices: responseJSON.exceeded_daily_quota_devices ?? {},\n exceededDailyQuotaUsers: responseJSON.exceeded_daily_quota_users ?? {},\n throttledEvents: responseJSON.throttled_events ?? [],\n },\n };\n case Status.Timeout:\n default:\n return {\n status,\n statusCode,\n };\n }\n }\n\n buildStatus(code: number): Status {\n if (isSuccessStatusCode(code)) {\n return Status.Success;\n }\n\n if (code === 429) {\n return Status.RateLimit;\n }\n\n if (code === 413) {\n return Status.PayloadTooLarge;\n }\n\n if (code === 408) {\n return Status.Timeout;\n }\n\n if (code >= 400 && code < 500) {\n return Status.Invalid;\n }\n\n if (code >= 500) {\n return Status.Failed;\n }\n\n return Status.Unknown;\n }\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checks if an HTTP status code indicates success (2xx range)
|
|
3
|
+
* @param code - The HTTP status code to check
|
|
4
|
+
* @returns true if the status code is in the 2xx range, false otherwise
|
|
5
|
+
*/
|
|
6
|
+
export declare function isSuccessStatusCode(code: number): boolean;
|
|
7
|
+
//# sourceMappingURL=status-code.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"status-code.d.ts","sourceRoot":"","sources":["../../../src/utils/status-code.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEzD"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checks if an HTTP status code indicates success (2xx range)
|
|
3
|
+
* @param code - The HTTP status code to check
|
|
4
|
+
* @returns true if the status code is in the 2xx range, false otherwise
|
|
5
|
+
*/
|
|
6
|
+
export function isSuccessStatusCode(code) {
|
|
7
|
+
return code >= 200 && code < 300;
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=status-code.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"status-code.js","sourceRoot":"","sources":["../../../src/utils/status-code.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAAY;IAC9C,OAAO,IAAI,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Checks if an HTTP status code indicates success (2xx range)\n * @param code - The HTTP status code to check\n * @returns true if the status code is in the 2xx range, false otherwise\n */\nexport function isSuccessStatusCode(code: number): boolean {\n return code >= 200 && code < 300;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amplitude/analytics-core",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.31.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"author": "Amplitude Inc",
|
|
6
6
|
"homepage": "https://github.com/amplitude/Amplitude-TypeScript",
|
|
@@ -42,5 +42,5 @@
|
|
|
42
42
|
"files": [
|
|
43
43
|
"lib"
|
|
44
44
|
],
|
|
45
|
-
"gitHead": "
|
|
45
|
+
"gitHead": "c955088a4b93312d1347a6e91c35c430f2206781"
|
|
46
46
|
}
|