@amplitude/analytics-core 2.41.7 → 2.43.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/index.d.ts +2 -1
- package/lib/cjs/index.d.ts.map +1 -1
- package/lib/cjs/index.js +2 -1
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/network-request-event.js +4 -4
- package/lib/cjs/network-request-event.js.map +1 -1
- package/lib/cjs/remote-config/remote-config.d.ts.map +1 -1
- package/lib/cjs/remote-config/remote-config.js +3 -2
- package/lib/cjs/remote-config/remote-config.js.map +1 -1
- package/lib/cjs/revenue.d.ts.map +1 -1
- package/lib/cjs/revenue.js +10 -2
- package/lib/cjs/revenue.js.map +1 -1
- package/lib/cjs/types/config/browser-config.d.ts +6 -0
- package/lib/cjs/types/config/browser-config.d.ts.map +1 -1
- package/lib/cjs/types/config/browser-config.js.map +1 -1
- package/lib/cjs/types/custom-enrichment.d.ts +8 -0
- package/lib/cjs/types/custom-enrichment.d.ts.map +1 -0
- package/lib/cjs/types/custom-enrichment.js +6 -0
- package/lib/cjs/types/custom-enrichment.js.map +1 -0
- package/lib/cjs/types/element-interactions.d.ts +21 -1
- package/lib/cjs/types/element-interactions.d.ts.map +1 -1
- package/lib/cjs/types/element-interactions.js +2 -1
- package/lib/cjs/types/element-interactions.js.map +1 -1
- package/lib/cjs/types/frustration-interactions.d.ts +1 -1
- package/lib/cjs/types/frustration-interactions.js.map +1 -1
- package/lib/esm/index.d.ts +2 -1
- package/lib/esm/index.d.ts.map +1 -1
- package/lib/esm/index.js +1 -1
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/network-request-event.js +1 -1
- package/lib/esm/network-request-event.js.map +1 -1
- package/lib/esm/remote-config/remote-config.d.ts.map +1 -1
- package/lib/esm/remote-config/remote-config.js +3 -2
- package/lib/esm/remote-config/remote-config.js.map +1 -1
- package/lib/esm/revenue.d.ts.map +1 -1
- package/lib/esm/revenue.js +10 -2
- package/lib/esm/revenue.js.map +1 -1
- package/lib/esm/types/config/browser-config.d.ts +6 -0
- package/lib/esm/types/config/browser-config.d.ts.map +1 -1
- package/lib/esm/types/config/browser-config.js.map +1 -1
- package/lib/esm/types/custom-enrichment.d.ts +8 -0
- package/lib/esm/types/custom-enrichment.d.ts.map +1 -0
- package/lib/esm/types/custom-enrichment.js +5 -0
- package/lib/esm/types/custom-enrichment.js.map +1 -0
- package/lib/esm/types/element-interactions.d.ts +21 -1
- package/lib/esm/types/element-interactions.d.ts.map +1 -1
- package/lib/esm/types/element-interactions.js +1 -0
- package/lib/esm/types/element-interactions.js.map +1 -1
- package/lib/esm/types/frustration-interactions.d.ts +1 -1
- package/lib/esm/types/frustration-interactions.js.map +1 -1
- package/package.json +1 -1
package/lib/cjs/index.d.ts
CHANGED
|
@@ -47,7 +47,7 @@ export { Response } from './types/response';
|
|
|
47
47
|
export { UserSession } from './types/user-session';
|
|
48
48
|
export { Plugin, BeforePlugin, DestinationPlugin, EnrichmentPlugin, PluginType, AnalyticsIdentity, } from './types/plugin';
|
|
49
49
|
export { Result } from './types/result';
|
|
50
|
-
export { ElementInteractionsOptions, Messenger, ActionType, DEFAULT_CSS_SELECTOR_ALLOWLIST, DEFAULT_DATA_ATTRIBUTE_PREFIX, DEFAULT_ACTION_CLICK_ALLOWLIST, LabeledEvent, Trigger, DataSource, } from './types/element-interactions';
|
|
50
|
+
export { ElementInteractionsOptions, Messenger, ActionType, DEFAULT_CSS_SELECTOR_ALLOWLIST, DEFAULT_DATA_ATTRIBUTE_PREFIX, DEFAULT_ACTION_CLICK_ALLOWLIST, DEFAULT_EXPOSURE_DURATION, LabeledEvent, Trigger, DataSource, } from './types/element-interactions';
|
|
51
51
|
export { FrustrationInteractionsOptions, DEFAULT_DEAD_CLICK_ALLOWLIST, DEFAULT_RAGE_CLICK_ALLOWLIST, DEFAULT_ERROR_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';
|
|
52
52
|
export { PageTrackingOptions, PageTrackingTrackOn, PageTrackingHistoryChanges } from './types/page-view-tracking';
|
|
53
53
|
export { FormInteractionsOptions } from './types/form-interactions';
|
|
@@ -57,6 +57,7 @@ export { NetworkRequestEvent, IRequestWrapper, JsonObject, JsonValue, JsonArray
|
|
|
57
57
|
export { NetworkTrackingOptions, NetworkCaptureRule } from './types/network-tracking';
|
|
58
58
|
export { SAFE_HEADERS, FORBIDDEN_HEADERS } from './types/constants';
|
|
59
59
|
export { PageUrlEnrichmentOptions } from './types/page-url-enrichment';
|
|
60
|
+
export { CustomEnrichmentOptions } from './types/custom-enrichment';
|
|
60
61
|
export { Campaign, UTMParameters, ReferrerParameters, ClickIdParameters, ICampaignParser } from './types/campaign';
|
|
61
62
|
export { EMPTY_VALUE, BASE_CAMPAIGN, MKTG } from './types/constants';
|
|
62
63
|
export { CampaignParser } from './campaign/campaign-parser';
|
package/lib/cjs/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,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACpE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,mBAAmB,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O,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAC;AAC/E,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,wBAAwB,EACxB,qBAAqB,EACrB,uCAAuC,GACxC,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,+BAA+B,EAAE,qCAAqC,EAAE,MAAM,+BAA+B,CAAC"}
|
package/lib/cjs/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.OfflineDisabled = exports.ServerZone = exports.SpecialEventType = exports.IdentifyOperation = exports.consoleObserver = exports.STORAGE_PREFIX = exports.AMPLITUDE_PREFIX = exports.LogLevel = exports.RemoteConfigClient = exports.MIN_GZIP_UPLOAD_BODY_SIZE_BYTES = exports.isCompressionStreamAvailable = exports.compressToGzipArrayBuffer = exports.FetchTransport = exports.BaseTransport = exports.registerSdkLoaderMetadata = exports.DiagnosticsClient = exports.BrowserStorage = exports.getStorageKey = exports.decodeCookieValue = exports.isDomainEqual = 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.EXCLUDE_INTERNAL_REFERRERS_CONDITIONS = exports.AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL = exports.AMPLITUDE_ORIGINS_MAP = exports.AMPLITUDE_ORIGIN_STAGING = exports.AMPLITUDE_ORIGIN_EU = exports.AMPLITUDE_ORIGIN = exports.enableBackgroundCapture = exports.getOrCreateWindowMessenger = exports.safeJsonStringify = exports.multicast = exports.merge = exports.asyncMap = exports.Observable = exports.EMAIL_REGEX = exports.SSN_REGEX = exports.CC_REGEX = exports.replaceSensitiveString = exports.MASKED_TEXT_VALUE = exports.TEXT_MASK_ATTRIBUTE = exports.getPageTitle = 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 = exports.DEFAULT_RAGE_CLICK_WINDOW_MS = exports.DEFAULT_RAGE_CLICK_THRESHOLD = exports.DEFAULT_ERROR_CLICK_ALLOWLIST = 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 = void 0;
|
|
4
|
+
exports.EXCLUDE_INTERNAL_REFERRERS_CONDITIONS = exports.AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL = exports.AMPLITUDE_ORIGINS_MAP = exports.AMPLITUDE_ORIGIN_STAGING = exports.AMPLITUDE_ORIGIN_EU = exports.AMPLITUDE_ORIGIN = exports.enableBackgroundCapture = exports.getOrCreateWindowMessenger = exports.safeJsonStringify = exports.multicast = exports.merge = exports.asyncMap = exports.Observable = exports.EMAIL_REGEX = exports.SSN_REGEX = exports.CC_REGEX = exports.replaceSensitiveString = exports.MASKED_TEXT_VALUE = exports.TEXT_MASK_ATTRIBUTE = exports.getPageTitle = 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 = exports.DEFAULT_RAGE_CLICK_WINDOW_MS = exports.DEFAULT_RAGE_CLICK_THRESHOLD = exports.DEFAULT_ERROR_CLICK_ALLOWLIST = exports.DEFAULT_RAGE_CLICK_ALLOWLIST = exports.DEFAULT_DEAD_CLICK_ALLOWLIST = exports.DEFAULT_EXPOSURE_DURATION = exports.DEFAULT_ACTION_CLICK_ALLOWLIST = exports.DEFAULT_DATA_ATTRIBUTE_PREFIX = exports.DEFAULT_CSS_SELECTOR_ALLOWLIST = 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
7
|
var identify_1 = require("./identify");
|
|
@@ -91,6 +91,7 @@ var element_interactions_1 = require("./types/element-interactions");
|
|
|
91
91
|
Object.defineProperty(exports, "DEFAULT_CSS_SELECTOR_ALLOWLIST", { enumerable: true, get: function () { return element_interactions_1.DEFAULT_CSS_SELECTOR_ALLOWLIST; } });
|
|
92
92
|
Object.defineProperty(exports, "DEFAULT_DATA_ATTRIBUTE_PREFIX", { enumerable: true, get: function () { return element_interactions_1.DEFAULT_DATA_ATTRIBUTE_PREFIX; } });
|
|
93
93
|
Object.defineProperty(exports, "DEFAULT_ACTION_CLICK_ALLOWLIST", { enumerable: true, get: function () { return element_interactions_1.DEFAULT_ACTION_CLICK_ALLOWLIST; } });
|
|
94
|
+
Object.defineProperty(exports, "DEFAULT_EXPOSURE_DURATION", { enumerable: true, get: function () { return element_interactions_1.DEFAULT_EXPOSURE_DURATION; } });
|
|
94
95
|
var frustration_interactions_1 = require("./types/frustration-interactions");
|
|
95
96
|
Object.defineProperty(exports, "DEFAULT_DEAD_CLICK_ALLOWLIST", { enumerable: true, get: function () { return frustration_interactions_1.DEFAULT_DEAD_CLICK_ALLOWLIST; } });
|
|
96
97
|
Object.defineProperty(exports, "DEFAULT_RAGE_CLICK_ALLOWLIST", { enumerable: true, get: function () { return frustration_interactions_1.DEFAULT_RAGE_CLICK_ALLOWLIST; } });
|
package/lib/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,6CAA8C;AAArC,4GAAA,aAAa,OAAA;AAItB,uCAAoE;AAA3D,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;AAEhC,mCAAsD;AAA7C,gGAAA,MAAM,OAAA;AACf,+CAAgD;AAAvC,8GAAA,cAAc,OAAA;AACvB,6DAAwG;AAA/F,4HAAA,qBAAqB,OAAA;AAAE,2HAAA,oBAAoB,OAAA;AAAE,yHAAA,kBAAkB,OAAA;AACxE,qCAAyC;AAAhC,uGAAA,YAAY,OAAA;AACrB,6CAAgE;AAAvD,4GAAA,aAAa,OAAA;AAAE,+GAAA,gBAAgB,OAAA;AACxC,uCAAyC;AAAhC,uGAAA,WAAW,OAAA;AACpB,+CAAgD;AAAvC,8GAAA,cAAc,OAAA;AAEvB,yDAAwE;AAA/D,+GAAA,aAAa,OAAA;AACtB,uCAAkF;AAAzE,qGAAA,YAAY,OAAA;AAAE,2GAAA,kBAAkB,OAAA;AAAE,wGAAA,eAAe,OAAA;AAC1D,qCAAoC;AAA3B,4FAAA,IAAI,OAAA;AACb,uDAA4D;AAAnD,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AAY,OAAA;AACZ,8GAAA,mBAAmB,OAAA;AACnB,4GAAA,iBAAiB,OAAA;AACjB,iHAAA,sBAAsB,OAAA;AACtB,mGAAA,QAAQ,OAAA;AACR,oGAAA,SAAS,OAAA;AACT,sGAAA,WAAW,OAAA;AA6Bb,iDAA4F;AAAnF,wGAAA,UAAU,OAAA;AAAE,sGAAA,QAAQ,OAAA;AAAE,mGAAA,KAAK,OAAA;AAAE,uGAAA,SAAS,OAAA;AAG/C,yDAA2D;AAAlD,mHAAA,iBAAiB,OAAA;AAI1B,2EAA+E;AAAtE,mIAAA,0BAA0B,OAAA;AACnC,qEAAyE;AAAhE,6HAAA,uBAAuB,OAAA;AAChC,mDAM+B;AAL7B,6GAAA,gBAAgB,OAAA;AAChB,gHAAA,mBAAmB,OAAA;AACnB,qHAAA,wBAAwB,OAAA;AACxB,kHAAA,qBAAqB,OAAA;AACrB,oIAAA,uCAAuC,OAAA;AAGzC,gEAAuH;AAA7E,uIAAA,qCAAqC,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, ValidPropertyType } 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, isDomainEqual, decodeCookieValue } from './storage/cookie';\nexport { getStorageKey } from './storage/helpers';\n\nexport { BrowserStorage } from './storage/browser-storage';\n\nexport { DiagnosticsClient, IDiagnosticsClient } from './diagnostics/diagnostics-client';\nexport { registerSdkLoaderMetadata } from './diagnostics/uncaught-sdk-errors';\n\nexport { BaseTransport } from './transports/base';\nexport { FetchTransport } from './transports/fetch';\nexport {\n compressToGzipArrayBuffer,\n isCompressionStreamAvailable,\n MIN_GZIP_UPLOAD_BODY_SIZE_BYTES,\n} from './transports/gzip';\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, CookieStorageConfig } from './types/storage';\nexport { consoleObserver } from './observers/console';\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, TransportOptions, TransportTypeOrOptions } 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 DEFAULT_EXPOSURE_DURATION,\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_ERROR_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 { FormInteractionsOptions } from './types/form-interactions';\nexport { Status } from './types/status';\n\nexport { NetworkEventCallback, networkObserver } from './observers/network';\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';\nexport { CustomEnrichmentOptions } from './types/custom-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\nexport { Observable, asyncMap, merge, multicast, Unsubscribable } from './utils/observable';\n\nexport { InstanceProxy } from './types/proxy';\nexport { safeJsonStringify } from './utils/safe-stringify';\n\n// Messenger (cross-window communication)\nexport type { BaseWindowMessenger, ActionHandler } from './messenger/base-window-messenger';\nexport { getOrCreateWindowMessenger } from './messenger/base-window-messenger';\nexport { enableBackgroundCapture } from './messenger/background-capture';\nexport {\n AMPLITUDE_ORIGIN,\n AMPLITUDE_ORIGIN_EU,\n AMPLITUDE_ORIGIN_STAGING,\n AMPLITUDE_ORIGINS_MAP,\n AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL,\n} from './messenger/constants';\n\nexport { ExcludeInternalReferrersOptions, EXCLUDE_INTERNAL_REFERRERS_CONDITIONS } from './types/config/browser-config';\n"]}
|
|
@@ -4,7 +4,7 @@ exports.NetworkRequestEvent = exports.pruneHeaders = exports.PRUNE_STRATEGY = ex
|
|
|
4
4
|
var tslib_1 = require("tslib");
|
|
5
5
|
var global_scope_1 = require("./global-scope");
|
|
6
6
|
var json_query_1 = require("./utils/json-query");
|
|
7
|
-
var
|
|
7
|
+
var constants_1 = require("./types/constants");
|
|
8
8
|
var TEXT_READ_TIMEOUT = 500;
|
|
9
9
|
exports.MAXIMUM_ENTRIES = 100;
|
|
10
10
|
/**
|
|
@@ -442,7 +442,7 @@ var REDACTED_VALUE = '[REDACTED]';
|
|
|
442
442
|
var pruneHeaders = function (headers, options) {
|
|
443
443
|
var e_4, _a;
|
|
444
444
|
var _b = options.allow, allow = _b === void 0 ? [] : _b, _c = options.strategy, strategy = _c === void 0 ? PRUNE_STRATEGY.REMOVE : _c;
|
|
445
|
-
var exclude = tslib_1.__spreadArray([], tslib_1.__read(
|
|
445
|
+
var exclude = tslib_1.__spreadArray([], tslib_1.__read(constants_1.FORBIDDEN_HEADERS), false);
|
|
446
446
|
var headersPruned = {};
|
|
447
447
|
var _loop_1 = function (key) {
|
|
448
448
|
var lowerKey = key.toLowerCase();
|
|
@@ -503,9 +503,9 @@ var NetworkRequestEvent = /** @class */ (function () {
|
|
|
503
503
|
error: this.error,
|
|
504
504
|
startTime: this.startTime,
|
|
505
505
|
endTime: this.endTime,
|
|
506
|
-
requestHeaders: (_a = this.requestWrapper) === null || _a === void 0 ? void 0 : _a.headers(tslib_1.__spreadArray([], tslib_1.__read(
|
|
506
|
+
requestHeaders: (_a = this.requestWrapper) === null || _a === void 0 ? void 0 : _a.headers(tslib_1.__spreadArray([], tslib_1.__read(constants_1.SAFE_HEADERS), false)),
|
|
507
507
|
requestBodySize: (_b = this.requestWrapper) === null || _b === void 0 ? void 0 : _b.bodySize,
|
|
508
|
-
responseHeaders: (_c = this.responseWrapper) === null || _c === void 0 ? void 0 : _c.headers(tslib_1.__spreadArray([], tslib_1.__read(
|
|
508
|
+
responseHeaders: (_c = this.responseWrapper) === null || _c === void 0 ? void 0 : _c.headers(tslib_1.__spreadArray([], tslib_1.__read(constants_1.SAFE_HEADERS), false)),
|
|
509
509
|
responseBodySize: (_d = this.responseWrapper) === null || _d === void 0 ? void 0 : _d.bodySize,
|
|
510
510
|
};
|
|
511
511
|
return Object.fromEntries(Object.entries(serialized).filter(function (_a) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-request-event.js","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":";;;;AAAA,+CAAgD;AAChD,iDAA+C;AAC/C,uBAAqD;AA2DrD,IAAM,iBAAiB,GAAG,GAAG,CAAC;AAmCjB,QAAA,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;;;;;;;;;;;;;GAiBG;AACH;IAEE,6BAAoB,OAAwB;QAA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,IAAI,CAAC,QAAQ;YACvB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,cAAc,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,OAAO,0CAAK,eAAY,UAAE;YAC/D,eAAe,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,QAAQ;YAC9C,eAAe,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,OAAO,0CAAK,eAAY,UAAE;YACjE,gBAAgB,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,QAAQ;SACjD,CAAC;QAEF,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,UAAC,EAAM;gBAAN,KAAA,qBAAM,EAAL,CAAC,QAAA,EAAE,CAAC,QAAA;YAAM,OAAA,CAAC,KAAK,SAAS;QAAf,CAAe,CAAC,CAAC,CAAC;IAC5F,CAAC;IACH,0BAAC;AAAD,CAAC,AAzCD,IAyCC;AAzCY,kDAAmB","sourcesContent":["import { getGlobalScope } from './global-scope';\nimport { pruneJson } from './utils/json-query';\nimport { SAFE_HEADERS, FORBIDDEN_HEADERS } from './';\n\n/* SAFE TYPE DEFINITIONS\n These type definitions expose limited properties of the original types\n to prevent the consumer from mutating them or consuming them.\n*/\ntype BlobSafe = {\n size: number;\n};\n\ntype ArrayBufferSafe = {\n byteLength: number;\n};\n\ntype ArrayBufferViewSafe = {\n byteLength: number;\n};\n\ntype URLSearchParamsSafe = {\n toString(): string;\n};\n\n// no method on readablestream is safe to call\ntype ReadableStreamSafe = Record<string, never>;\n\ntype FormDataEntryValueSafe = string | BlobSafe | null;\n\ntype BodyInitSafe =\n | string\n | Blob\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\ntype HeadersRequestSafe = {\n entries(): IterableIterator<[string, string]>;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersResponseSafe = {\n get(name: string): string | null;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersInitSafe = HeadersRequestSafe | Record<string, string> | string[][];\n\ntype ResponseSafe = {\n status: number;\n headers: HeadersResponseSafe | undefined;\n clone(): ResponseCloneSafe;\n};\n\ntype ResponseCloneSafe = {\n text(): Promise<string>;\n};\n\nconst TEXT_READ_TIMEOUT = 500;\n\nexport type RequestInitSafe = {\n method?: string;\n headers?: HeadersInitSafe;\n body?: BodyInitSafe;\n};\nexport interface FormDataSafe {\n entries(): IterableIterator<[string, FormDataEntryValueSafe]>;\n}\nexport type XMLHttpRequestBodyInitSafe = BlobSafe | FormDataSafe | URLSearchParamsSafe | string;\n\nexport type FetchRequestBody =\n | string\n | BlobSafe\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\nexport interface IRequestWrapper {\n /**\n * Get the headers of the request.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\nexport const MAXIMUM_ENTRIES = 100;\n\n/**\n * This class encapsulates the RequestInit (https://developer.mozilla.org/en-US/docs/Web/API/RequestInit)\n * object so that the consumer can only get access to the headers, method and body size.\n *\n * This is to prevent consumers from directly accessing the Request object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * request.\n * * NEVER .clone() the RequestInit object. This will 2x's the memory overhead of the request\n * * NEVER: call .arrayBuffer(), text(), json() or any other method on the body that\n * consumes the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class RequestWrapperFetch implements IRequestWrapper {\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n const headersUnsafe = this.request.headers;\n\n // copy the headers into a new object\n const headersSafeCopy: Record<string, string> = {};\n if (Array.isArray(headersUnsafe)) {\n headersUnsafe.forEach(([headerName, headerValue]) => {\n headersSafeCopy[headerName] = headerValue;\n });\n } else if (headersUnsafe instanceof Headers) {\n headersUnsafe.forEach((value: string, key: string) => {\n headersSafeCopy[key] = value;\n });\n } else if (typeof headersUnsafe === 'object' && headersUnsafe !== null) {\n for (const [key, value] of Object.entries(headersUnsafe as Record<string, string>)) {\n headersSafeCopy[key] = value;\n }\n }\n\n return pruneHeaders(headersSafeCopy, { allow });\n }\n\n get bodySize(): number | undefined {\n if (typeof this._bodySize === 'number') return this._bodySize;\n const global = getGlobalScope();\n\n /* istanbul ignore if */\n if (!global?.TextEncoder) {\n return;\n }\n const body = this.request.body as FetchRequestBody;\n this._bodySize = getBodySize(body, MAXIMUM_ENTRIES);\n return this._bodySize;\n }\n\n get method(): string | undefined {\n return this.request.method;\n }\n\n get body(): string | null {\n if (typeof this.request.body === 'string') {\n return this.request.body;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly bodyRaw: XMLHttpRequestBodyInitSafe | null, readonly requestHeaders: Record<string, string>) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n return pruneHeaders(this.requestHeaders, { allow });\n }\n\n get bodySize(): number | undefined {\n return getBodySize(this.bodyRaw as FetchRequestBody, MAXIMUM_ENTRIES);\n }\n\n get body(): string | null {\n if (typeof this.bodyRaw === 'string') {\n return this.bodyRaw;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nfunction getBodySize(bodyUnsafe: FetchRequestBody, maxEntries: number): number | undefined {\n let bodySize: number | undefined;\n const global = getGlobalScope();\n /* istanbul ignore next */\n const TextEncoder = global?.TextEncoder;\n /* istanbul ignore next */\n if (!TextEncoder) {\n return;\n }\n let bodySafe;\n if (typeof bodyUnsafe === 'string') {\n bodySafe = bodyUnsafe;\n bodySize = new TextEncoder().encode(bodySafe).length;\n } else if (bodyUnsafe instanceof Blob) {\n bodySafe = bodyUnsafe as BlobSafe;\n bodySize = bodySafe.size;\n } else if (bodyUnsafe instanceof URLSearchParams) {\n bodySafe = bodyUnsafe as URLSearchParamsSafe;\n bodySize = new TextEncoder().encode(bodySafe.toString()).length;\n } else if (ArrayBuffer.isView(bodyUnsafe)) {\n bodySafe = bodyUnsafe as ArrayBufferViewSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof ArrayBuffer) {\n bodySafe = bodyUnsafe as ArrayBufferSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof FormData) {\n // Estimating only for text parts; not accurate for files\n const formData = bodyUnsafe as unknown as FormDataSafe;\n\n let total = 0;\n let count = 0;\n for (const [key, value] of formData.entries()) {\n total += key.length;\n if (typeof value === 'string') {\n total += new TextEncoder().encode(value).length;\n } else if (value instanceof Blob) {\n total += value.size;\n } else {\n // encountered an unknown type\n // we can't estimate the size of this entry\n return;\n }\n // terminate if we reach the maximum number of entries\n // to avoid performance issues in case of very large FormData\n if (++count >= maxEntries) {\n return;\n }\n }\n bodySize = total;\n } else if (bodyUnsafe instanceof ReadableStream) {\n // If bodyUnsafe is an instanceof ReadableStream, we can't determine the size,\n // without consuming it, so we return undefined.\n // Never ever consume ReadableStream! DO NOT DO IT!!!\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bodySafe = bodyUnsafe as unknown as ReadableStreamSafe;\n return;\n }\n return bodySize;\n}\n\nexport type JsonObject = {\n [key: string]: JsonValue;\n};\n\nexport type JsonValue = string | number | boolean | null | JsonObject | JsonArray;\n\nexport type JsonArray = Array<JsonValue>;\n\nexport interface IResponseWrapper {\n /**\n * Get the headers of the response.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\n/**\n * This class encapsulates the Fetch API Response object\n * (https://developer.mozilla.org/en-US/docs/Web/API/Response) so that the consumer can\n * only get access to the headers and body size.\n *\n * This is to prevent consumers from directly accessing the Response object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * response.\n * * Do not .clone() the Response object unless you need to access the body.\n * Cloning will 2x the memory overhead of the response.\n * * NEVER consume the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class ResponseWrapperFetch implements IResponseWrapper {\n private _bodySize: number | undefined;\n private clonedResponse?: ResponseCloneSafe;\n constructor(private response: ResponseSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (this.response.headers instanceof Headers) {\n const headersSafe = this.response.headers as HeadersResponseSafe;\n const headersOut: Record<string, string> = {};\n /* istanbul ignore next */\n headersSafe?.forEach?.((value, key) => {\n headersOut[key] = value;\n });\n return pruneHeaders(headersOut, { allow });\n }\n\n return;\n }\n\n get bodySize(): number | undefined {\n if (this._bodySize !== undefined) return this._bodySize;\n /* istanbul ignore next */\n const contentLength = this.response.headers?.get?.('content-length');\n const bodySize = contentLength ? parseInt(contentLength, 10) : undefined;\n this._bodySize = bodySize;\n return bodySize;\n }\n\n get status(): number {\n return this.response.status;\n }\n\n async text(): Promise<string | null> {\n // !!!IMPORTANT: we clone the response to avoid mutating the original response\n // never call .text(), .json(), etc.. on the original response always clone it first\n if (!this.clonedResponse) {\n this.clonedResponse = this.response.clone();\n }\n try {\n const textPromise = this.clonedResponse.text();\n const timer = new Promise<null>((resolve) =>\n setTimeout(\n /* istanbul ignore next */\n () => resolve(null),\n TEXT_READ_TIMEOUT,\n ),\n );\n const text = await Promise.race<string | null>([textPromise, timer]);\n return text;\n } catch (error) {\n return null;\n }\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = await this.text();\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(\n readonly statusCode: number,\n readonly headersString: string,\n readonly size: number | undefined,\n readonly getJson: () => any | null,\n ) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (!this.headersString) {\n return {};\n }\n const headers: Record<string, string> = {};\n const headerLines = this.headersString.split('\\r\\n');\n for (const line of headerLines) {\n const [key, value] = line.split(': ');\n if (key && value) {\n headers[key] = value;\n }\n }\n return pruneHeaders(headers, { allow });\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const jsonBody = this.getJson() as JsonObject | null;\n if (jsonBody) {\n pruneJson(jsonBody, allow, exclude);\n return jsonBody;\n }\n return null;\n }\n}\n\nfunction safeParseAndPruneBody(text: string | null, allow: string[], exclude: string[]): JsonObject | null {\n if (!text) return null;\n try {\n const json = JSON.parse(text) as JsonObject;\n pruneJson(json, allow, exclude);\n return json;\n } catch (error) {\n return null;\n }\n}\n\nexport enum PRUNE_STRATEGY {\n REDACT = 'redact',\n REMOVE = 'remove',\n}\n\nconst REDACTED_VALUE = '[REDACTED]';\n\n/**\n * Prune headers from a headers record object.\n * @param headers - The headers to prune.\n * @param options - The options to prune the headers.\n * @param options.exclude - List of headers to delete from headers\n * @param options.include - List of headers to keep in headers, if not provided, all headers are kept by default\n * @returns The pruned headers.\n */\nexport const pruneHeaders = (\n headers: Record<string, string>,\n options: {\n allow?: string[];\n strategy?: PRUNE_STRATEGY;\n },\n): Record<string, string> => {\n const { allow = [], strategy = PRUNE_STRATEGY.REMOVE } = options;\n const exclude = [...FORBIDDEN_HEADERS];\n const headersPruned: Record<string, string> = {};\n\n for (const key of Object.keys(headers)) {\n const lowerKey = key.toLowerCase();\n\n if (exclude.find((e) => e.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else if (!allow.find((i) => i.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else {\n headersPruned[key] = headers[key];\n }\n }\n return headersPruned;\n};\nexport class NetworkRequestEvent {\n public requestHeaders?: Record<string, string>;\n public responseHeaders?: Record<string, string>;\n public requestBodyJson?: Promise<JsonObject | null>;\n public responseBodyJson?: Promise<JsonObject | null>;\n constructor(\n public readonly type: 'xhr' | 'fetch',\n public readonly method: string,\n public readonly timestamp: number,\n public readonly startTime: number,\n public readonly url?: string,\n public readonly requestWrapper?: IRequestWrapper,\n public readonly status: number = 0,\n public readonly duration?: number,\n public readonly responseWrapper?: IResponseWrapper,\n public readonly error?: {\n name: string;\n message: string;\n },\n public readonly endTime?: number,\n ) {}\n\n toSerializable(): Record<string, any> {\n const serialized: Record<string, any> = {\n type: this.type,\n method: this.method,\n url: this.url,\n timestamp: this.timestamp,\n status: this.status,\n duration: this.duration,\n error: this.error,\n startTime: this.startTime,\n endTime: this.endTime,\n requestHeaders: this.requestWrapper?.headers([...SAFE_HEADERS]),\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.headers([...SAFE_HEADERS]),\n responseBodySize: this.responseWrapper?.bodySize,\n };\n\n return Object.fromEntries(Object.entries(serialized).filter(([_, v]) => v !== undefined));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"network-request-event.js","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":";;;;AAAA,+CAAgD;AAChD,iDAA+C;AAC/C,+CAAoE;AA2DpE,IAAM,iBAAiB,GAAG,GAAG,CAAC;AAmCjB,QAAA,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;;;;;;;;;;;;;GAiBG;AACH;IAEE,6BAAoB,OAAwB;QAAxB,YAAO,GAAP,OAAO,CAAiB;IAAG,CAAC;IAEhD,qCAAO,GAAP,UAAQ,KAAoB;;QAApB,sBAAA,EAAA,UAAoB;QAC1B,IAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;QAE3C,qCAAqC;QACrC,IAAM,eAAe,GAA2B,EAAE,CAAC;QACnD,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;YAChC,aAAa,CAAC,OAAO,CAAC,UAAC,EAAyB;oBAAzB,KAAA,qBAAyB,EAAxB,UAAU,QAAA,EAAE,WAAW,QAAA;gBAC7C,eAAe,CAAC,UAAU,CAAC,GAAG,WAAW,CAAC;YAC5C,CAAC,CAAC,CAAC;SACJ;aAAM,IAAI,aAAa,YAAY,OAAO,EAAE;YAC3C,aAAa,CAAC,OAAO,CAAC,UAAC,KAAa,EAAE,GAAW;gBAC/C,eAAe,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;YAC/B,CAAC,CAAC,CAAC;SACJ;aAAM,IAAI,OAAO,aAAa,KAAK,QAAQ,IAAI,aAAa,KAAK,IAAI,EAAE;;gBACtE,KAA2B,IAAA,KAAA,iBAAA,MAAM,CAAC,OAAO,CAAC,aAAuC,CAAC,CAAA,gBAAA,4BAAE;oBAAzE,IAAA,KAAA,2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c,CAAkB;QAChC,WAAM,GAAN,MAAM,CAAY;QAClB,aAAQ,GAAR,QAAQ,CAAS;QACjB,oBAAe,GAAf,eAAe,CAAmB;QAClC,UAAK,GAAL,KAAK,CAGpB;QACe,YAAO,GAAP,OAAO,CAAS;IAC/B,CAAC;IAEJ,4CAAc,GAAd;;QACE,IAAM,UAAU,GAAwB;YACtC,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,GAAG,EAAE,IAAI,CAAC,GAAG;YACb,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,cAAc,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,OAAO,0CAAK,wBAAY,UAAE;YAC/D,eAAe,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,QAAQ;YAC9C,eAAe,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,OAAO,0CAAK,wBAAY,UAAE;YACjE,gBAAgB,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,QAAQ;SACjD,CAAC;QAEF,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,UAAC,EAAM;gBAAN,KAAA,qBAAM,EAAL,CAAC,QAAA,EAAE,CAAC,QAAA;YAAM,OAAA,CAAC,KAAK,SAAS;QAAf,CAAe,CAAC,CAAC,CAAC;IAC5F,CAAC;IACH,0BAAC;AAAD,CAAC,AAzCD,IAyCC;AAzCY,kDAAmB","sourcesContent":["import { getGlobalScope } from './global-scope';\nimport { pruneJson } from './utils/json-query';\nimport { SAFE_HEADERS, FORBIDDEN_HEADERS } from './types/constants';\n\n/* SAFE TYPE DEFINITIONS\n These type definitions expose limited properties of the original types\n to prevent the consumer from mutating them or consuming them.\n*/\ntype BlobSafe = {\n size: number;\n};\n\ntype ArrayBufferSafe = {\n byteLength: number;\n};\n\ntype ArrayBufferViewSafe = {\n byteLength: number;\n};\n\ntype URLSearchParamsSafe = {\n toString(): string;\n};\n\n// no method on readablestream is safe to call\ntype ReadableStreamSafe = Record<string, never>;\n\ntype FormDataEntryValueSafe = string | BlobSafe | null;\n\ntype BodyInitSafe =\n | string\n | Blob\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\ntype HeadersRequestSafe = {\n entries(): IterableIterator<[string, string]>;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersResponseSafe = {\n get(name: string): string | null;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersInitSafe = HeadersRequestSafe | Record<string, string> | string[][];\n\ntype ResponseSafe = {\n status: number;\n headers: HeadersResponseSafe | undefined;\n clone(): ResponseCloneSafe;\n};\n\ntype ResponseCloneSafe = {\n text(): Promise<string>;\n};\n\nconst TEXT_READ_TIMEOUT = 500;\n\nexport type RequestInitSafe = {\n method?: string;\n headers?: HeadersInitSafe;\n body?: BodyInitSafe;\n};\nexport interface FormDataSafe {\n entries(): IterableIterator<[string, FormDataEntryValueSafe]>;\n}\nexport type XMLHttpRequestBodyInitSafe = BlobSafe | FormDataSafe | URLSearchParamsSafe | string;\n\nexport type FetchRequestBody =\n | string\n | BlobSafe\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\nexport interface IRequestWrapper {\n /**\n * Get the headers of the request.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\nexport const MAXIMUM_ENTRIES = 100;\n\n/**\n * This class encapsulates the RequestInit (https://developer.mozilla.org/en-US/docs/Web/API/RequestInit)\n * object so that the consumer can only get access to the headers, method and body size.\n *\n * This is to prevent consumers from directly accessing the Request object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * request.\n * * NEVER .clone() the RequestInit object. This will 2x's the memory overhead of the request\n * * NEVER: call .arrayBuffer(), text(), json() or any other method on the body that\n * consumes the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class RequestWrapperFetch implements IRequestWrapper {\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n const headersUnsafe = this.request.headers;\n\n // copy the headers into a new object\n const headersSafeCopy: Record<string, string> = {};\n if (Array.isArray(headersUnsafe)) {\n headersUnsafe.forEach(([headerName, headerValue]) => {\n headersSafeCopy[headerName] = headerValue;\n });\n } else if (headersUnsafe instanceof Headers) {\n headersUnsafe.forEach((value: string, key: string) => {\n headersSafeCopy[key] = value;\n });\n } else if (typeof headersUnsafe === 'object' && headersUnsafe !== null) {\n for (const [key, value] of Object.entries(headersUnsafe as Record<string, string>)) {\n headersSafeCopy[key] = value;\n }\n }\n\n return pruneHeaders(headersSafeCopy, { allow });\n }\n\n get bodySize(): number | undefined {\n if (typeof this._bodySize === 'number') return this._bodySize;\n const global = getGlobalScope();\n\n /* istanbul ignore if */\n if (!global?.TextEncoder) {\n return;\n }\n const body = this.request.body as FetchRequestBody;\n this._bodySize = getBodySize(body, MAXIMUM_ENTRIES);\n return this._bodySize;\n }\n\n get method(): string | undefined {\n return this.request.method;\n }\n\n get body(): string | null {\n if (typeof this.request.body === 'string') {\n return this.request.body;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly bodyRaw: XMLHttpRequestBodyInitSafe | null, readonly requestHeaders: Record<string, string>) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n return pruneHeaders(this.requestHeaders, { allow });\n }\n\n get bodySize(): number | undefined {\n return getBodySize(this.bodyRaw as FetchRequestBody, MAXIMUM_ENTRIES);\n }\n\n get body(): string | null {\n if (typeof this.bodyRaw === 'string') {\n return this.bodyRaw;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nfunction getBodySize(bodyUnsafe: FetchRequestBody, maxEntries: number): number | undefined {\n let bodySize: number | undefined;\n const global = getGlobalScope();\n /* istanbul ignore next */\n const TextEncoder = global?.TextEncoder;\n /* istanbul ignore next */\n if (!TextEncoder) {\n return;\n }\n let bodySafe;\n if (typeof bodyUnsafe === 'string') {\n bodySafe = bodyUnsafe;\n bodySize = new TextEncoder().encode(bodySafe).length;\n } else if (bodyUnsafe instanceof Blob) {\n bodySafe = bodyUnsafe as BlobSafe;\n bodySize = bodySafe.size;\n } else if (bodyUnsafe instanceof URLSearchParams) {\n bodySafe = bodyUnsafe as URLSearchParamsSafe;\n bodySize = new TextEncoder().encode(bodySafe.toString()).length;\n } else if (ArrayBuffer.isView(bodyUnsafe)) {\n bodySafe = bodyUnsafe as ArrayBufferViewSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof ArrayBuffer) {\n bodySafe = bodyUnsafe as ArrayBufferSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof FormData) {\n // Estimating only for text parts; not accurate for files\n const formData = bodyUnsafe as unknown as FormDataSafe;\n\n let total = 0;\n let count = 0;\n for (const [key, value] of formData.entries()) {\n total += key.length;\n if (typeof value === 'string') {\n total += new TextEncoder().encode(value).length;\n } else if (value instanceof Blob) {\n total += value.size;\n } else {\n // encountered an unknown type\n // we can't estimate the size of this entry\n return;\n }\n // terminate if we reach the maximum number of entries\n // to avoid performance issues in case of very large FormData\n if (++count >= maxEntries) {\n return;\n }\n }\n bodySize = total;\n } else if (bodyUnsafe instanceof ReadableStream) {\n // If bodyUnsafe is an instanceof ReadableStream, we can't determine the size,\n // without consuming it, so we return undefined.\n // Never ever consume ReadableStream! DO NOT DO IT!!!\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bodySafe = bodyUnsafe as unknown as ReadableStreamSafe;\n return;\n }\n return bodySize;\n}\n\nexport type JsonObject = {\n [key: string]: JsonValue;\n};\n\nexport type JsonValue = string | number | boolean | null | JsonObject | JsonArray;\n\nexport type JsonArray = Array<JsonValue>;\n\nexport interface IResponseWrapper {\n /**\n * Get the headers of the response.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\n/**\n * This class encapsulates the Fetch API Response object\n * (https://developer.mozilla.org/en-US/docs/Web/API/Response) so that the consumer can\n * only get access to the headers and body size.\n *\n * This is to prevent consumers from directly accessing the Response object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * response.\n * * Do not .clone() the Response object unless you need to access the body.\n * Cloning will 2x the memory overhead of the response.\n * * NEVER consume the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class ResponseWrapperFetch implements IResponseWrapper {\n private _bodySize: number | undefined;\n private clonedResponse?: ResponseCloneSafe;\n constructor(private response: ResponseSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (this.response.headers instanceof Headers) {\n const headersSafe = this.response.headers as HeadersResponseSafe;\n const headersOut: Record<string, string> = {};\n /* istanbul ignore next */\n headersSafe?.forEach?.((value, key) => {\n headersOut[key] = value;\n });\n return pruneHeaders(headersOut, { allow });\n }\n\n return;\n }\n\n get bodySize(): number | undefined {\n if (this._bodySize !== undefined) return this._bodySize;\n /* istanbul ignore next */\n const contentLength = this.response.headers?.get?.('content-length');\n const bodySize = contentLength ? parseInt(contentLength, 10) : undefined;\n this._bodySize = bodySize;\n return bodySize;\n }\n\n get status(): number {\n return this.response.status;\n }\n\n async text(): Promise<string | null> {\n // !!!IMPORTANT: we clone the response to avoid mutating the original response\n // never call .text(), .json(), etc.. on the original response always clone it first\n if (!this.clonedResponse) {\n this.clonedResponse = this.response.clone();\n }\n try {\n const textPromise = this.clonedResponse.text();\n const timer = new Promise<null>((resolve) =>\n setTimeout(\n /* istanbul ignore next */\n () => resolve(null),\n TEXT_READ_TIMEOUT,\n ),\n );\n const text = await Promise.race<string | null>([textPromise, timer]);\n return text;\n } catch (error) {\n return null;\n }\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = await this.text();\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(\n readonly statusCode: number,\n readonly headersString: string,\n readonly size: number | undefined,\n readonly getJson: () => any | null,\n ) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (!this.headersString) {\n return {};\n }\n const headers: Record<string, string> = {};\n const headerLines = this.headersString.split('\\r\\n');\n for (const line of headerLines) {\n const [key, value] = line.split(': ');\n if (key && value) {\n headers[key] = value;\n }\n }\n return pruneHeaders(headers, { allow });\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const jsonBody = this.getJson() as JsonObject | null;\n if (jsonBody) {\n pruneJson(jsonBody, allow, exclude);\n return jsonBody;\n }\n return null;\n }\n}\n\nfunction safeParseAndPruneBody(text: string | null, allow: string[], exclude: string[]): JsonObject | null {\n if (!text) return null;\n try {\n const json = JSON.parse(text) as JsonObject;\n pruneJson(json, allow, exclude);\n return json;\n } catch (error) {\n return null;\n }\n}\n\nexport enum PRUNE_STRATEGY {\n REDACT = 'redact',\n REMOVE = 'remove',\n}\n\nconst REDACTED_VALUE = '[REDACTED]';\n\n/**\n * Prune headers from a headers record object.\n * @param headers - The headers to prune.\n * @param options - The options to prune the headers.\n * @param options.exclude - List of headers to delete from headers\n * @param options.include - List of headers to keep in headers, if not provided, all headers are kept by default\n * @returns The pruned headers.\n */\nexport const pruneHeaders = (\n headers: Record<string, string>,\n options: {\n allow?: string[];\n strategy?: PRUNE_STRATEGY;\n },\n): Record<string, string> => {\n const { allow = [], strategy = PRUNE_STRATEGY.REMOVE } = options;\n const exclude = [...FORBIDDEN_HEADERS];\n const headersPruned: Record<string, string> = {};\n\n for (const key of Object.keys(headers)) {\n const lowerKey = key.toLowerCase();\n\n if (exclude.find((e) => e.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else if (!allow.find((i) => i.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else {\n headersPruned[key] = headers[key];\n }\n }\n return headersPruned;\n};\nexport class NetworkRequestEvent {\n public requestHeaders?: Record<string, string>;\n public responseHeaders?: Record<string, string>;\n public requestBodyJson?: Promise<JsonObject | null>;\n public responseBodyJson?: Promise<JsonObject | null>;\n constructor(\n public readonly type: 'xhr' | 'fetch',\n public readonly method: string,\n public readonly timestamp: number,\n public readonly startTime: number,\n public readonly url?: string,\n public readonly requestWrapper?: IRequestWrapper,\n public readonly status: number = 0,\n public readonly duration?: number,\n public readonly responseWrapper?: IResponseWrapper,\n public readonly error?: {\n name: string;\n message: string;\n },\n public readonly endTime?: number,\n ) {}\n\n toSerializable(): Record<string, any> {\n const serialized: Record<string, any> = {\n type: this.type,\n method: this.method,\n url: this.url,\n timestamp: this.timestamp,\n status: this.status,\n duration: this.duration,\n error: this.error,\n startTime: this.startTime,\n endTime: this.endTime,\n requestHeaders: this.requestWrapper?.headers([...SAFE_HEADERS]),\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.headers([...SAFE_HEADERS]),\n responseBodySize: this.responseWrapper?.bodySize,\n };\n\n return Object.fromEntries(Object.entries(serialized).filter(([_, v]) => v !== undefined));\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-config.d.ts","sourceRoot":"","sources":["../../../src/remote-config/remote-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAIpC;;;;;;;;;GASG;AACH,MAAM,MAAM,YAAY,GAAG,KAAK,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEvD;;;;GAIG;AACH,MAAM,MAAM,MAAM,GAAG,OAAO,GAAG,QAAQ,CAAC;AAExC,eAAO,MAAM,aAAa,+CAA+C,CAAC;AAC1E,eAAO,MAAM,aAAa,kDAAkD,CAAC;AAC7E,eAAO,MAAM,mBAAmB,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"remote-config.d.ts","sourceRoot":"","sources":["../../../src/remote-config/remote-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EA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CAAC;IAuEhH;;OAEG;IACH,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM;IAIzC,YAAY,IAAI,MAAM;CASvB"}
|
|
@@ -9,6 +9,7 @@ exports.EU_SERVER_URL = 'https://sr-client-cfg.eu.amplitude.com/config';
|
|
|
9
9
|
exports.DEFAULT_MAX_RETRIES = 3;
|
|
10
10
|
var CODE_STATUS = {
|
|
11
11
|
INVALID_API_KEY: 401,
|
|
12
|
+
FORBIDDEN: 403,
|
|
12
13
|
RATE_LIMIT: 429,
|
|
13
14
|
};
|
|
14
15
|
/**
|
|
@@ -293,8 +294,8 @@ var RemoteConfigClient = /** @class */ (function () {
|
|
|
293
294
|
case 3:
|
|
294
295
|
body = _b.sent();
|
|
295
296
|
this_1.logger.debug("Remote config client fetch with retry time ".concat(retries, " failed with ").concat(res.status, ": ").concat(body));
|
|
296
|
-
if (res.status === CODE_STATUS.INVALID_API_KEY) {
|
|
297
|
-
this_1.logger.error("Remote config client fetch failed with ".concat(
|
|
297
|
+
if (res.status === CODE_STATUS.INVALID_API_KEY || res.status === CODE_STATUS.FORBIDDEN) {
|
|
298
|
+
this_1.logger.error("Remote config client fetch failed with ".concat(res.status, ". Invalid API key; future fetches will be skipped."));
|
|
298
299
|
this_1.isLastFetchInvalidApiKey = true;
|
|
299
300
|
shouldRetry = false;
|
|
300
301
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-config.js","sourceRoot":"","sources":["../../../src/remote-config/remote-config.ts"],"names":[],"mappings":";;;;AAEA,2EAAwE;AACxE,sCAAqC;AAqBxB,QAAA,aAAa,GAAG,4CAA4C,CAAC;AAC7D,QAAA,aAAa,GAAG,+CAA+C,CAAC;AAChE,QAAA,mBAAmB,GAAG,CAAC,CAAC;AACrC,IAAM,WAAW,GAAG;IAClB,eAAe,EAAE,GAAG;IACpB,UAAU,EAAE,GAAG;CACP,CAAC;AAEX;;;GAGG;AACH,IAAM,eAAe,GAAG,IAAI,CAAC;A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;QACtD,IAAM,aAAa,GAAG,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAEtD,IAAM,SAAS,GAAG,IAAI,eAAe,EAAE,CAAC;QACxC,SAAS,CAAC,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAAC,YAAY,CAAC,CAAC;QAElE,OAAO,UAAG,IAAI,CAAC,SAAS,cAAI,aAAa,cAAI,SAAS,CAAC,QAAQ,EAAE,CAAE,CAAC;IACtE,CAAC;IA9Se,+BAAY,GAAG,SAAS,CAAC;IA+S3C,yBAAC;CAAA,AAhTD,IAgTC;AAhTY,gDAAkB","sourcesContent":["import { ServerZoneType } from '../types/server-zone';\nimport { ILogger } from '../logger';\nimport { RemoteConfigLocalStorage } from './remote-config-localstorage';\nimport { UUID } from '../utils/uuid';\n\n/**\n * Modes for receiving remote config updates:\n * - `'all'` – Optimized for both speed and freshness. Returns the fastest response first\n * (cache or remote), then always waits for and returns the remote response to ensure\n * the most up-to-date config. Callback may be called once (if remote wins) or twice\n * (cache first, then remote).\n * - `{ timeout: number }` – Prefers remote data but with a fallback strategy. Waits for\n * a remote response until the specified timeout (in milliseconds), then falls back to\n * cached data if available. Callback is called exactly once.\n */\nexport type DeliveryMode = 'all' | { timeout: number };\n\n/**\n * Sources of returned remote config:\n * - `cache` - Fetched from local storage.\n * - `remote` - Fetched from remote.\n */\nexport type Source = 'cache' | 'remote';\n\nexport const US_SERVER_URL = 'https://sr-client-cfg.amplitude.com/config';\nexport const EU_SERVER_URL = 'https://sr-client-cfg.eu.amplitude.com/config';\nexport const DEFAULT_MAX_RETRIES = 3;\nconst CODE_STATUS = {\n INVALID_API_KEY: 401,\n RATE_LIMIT: 429,\n} as const;\n\n/**\n * The default timeout for fetch in milliseconds.\n * Linear backoff policy: timeout / retry times is the interval between fetch retry.\n */\nconst DEFAULT_TIMEOUT = 1000;\n\n/**\n * The minimum time between fetches in milliseconds.\n * This prevents too many requests from being sent in a short period of time.\n */\nconst DEFAULT_MIN_TIME_BETWEEN_FETCHES = 5 * 60 * 1000; // 5 minutes\n\nexport interface RemoteConfig {\n [key: string]: any;\n}\n\nexport interface RemoteConfigInfo {\n remoteConfig: RemoteConfig | null;\n // Timestamp of when the remote config was fetched.\n lastFetch: Date;\n}\n\nexport interface RemoteConfigStorage {\n /**\n * Fetch remote config from storage asynchronously.\n */\n fetchConfig(): Promise<RemoteConfigInfo>;\n\n /**\n * Set remote config to storage asynchronously.\n */\n setConfig(config: RemoteConfigInfo): Promise<boolean>;\n}\n\n/**\n * Information about each callback registered by `RemoteConfigClient.subscribe()`,\n * managed internally by `RemoteConfigClient`.\n */\nexport interface CallbackInfo {\n id: string;\n key?: string;\n deliveryMode: DeliveryMode;\n callback: RemoteConfigCallback;\n lastCallback?: Date;\n}\n\n/**\n * Callback used in `RemoteConfigClient.subscribe()`.\n * This function is called when the remote config is fetched.\n */\ntype RemoteConfigCallback = (remoteConfig: RemoteConfig | null, source: Source, lastFetch: Date) => void;\n\nexport interface IRemoteConfigClient {\n /**\n * Subscribe for updates to remote config.\n * Callback is guaranteed to be called at least once,\n * Whether we are able to fetch a config or not.\n *\n * @param key - a string containing a series of period delimited keys to filter the returned config.\n * Ie, {a: {b: {c: ...}}} would return {b: {c: ...}} for \"a\" or {c: ...} for \"a.b\".\n * Set to `undefined` to subscribe all keys.\n * @param deliveryMode - how the initial callback is sent.\n * @param callback - a block that will be called when remote config is fetched.\n * @return id - identification of the subscribe and can be used to unsubscribe from updates.\n */\n subscribe(key: string | undefined, deliveryMode: DeliveryMode, callback: RemoteConfigCallback): string;\n\n /**\n * Unsubscribe a callback from receiving future updates.\n *\n * @param id - identification of the callback that you want to unsubscribe.\n * It's the return value of subscribe().\n * @return boolean - whether the callback is removed.\n */\n unsubscribe(id: string): boolean;\n\n /**\n * Request the remote config client to fetch from remote, update cache, and callback.\n */\n updateConfigs(): void;\n}\n\nexport class RemoteConfigClient implements IRemoteConfigClient {\n static readonly CONFIG_GROUP = 'browser';\n\n readonly apiKey: string;\n readonly serverUrl: string;\n readonly logger: ILogger;\n readonly storage: RemoteConfigStorage;\n // Registered callbackInfos by subscribe().\n callbackInfos: CallbackInfo[] = [];\n // Track the last successful fetch time for throttling (timestamp in milliseconds).\n lastSuccessfulFetch: number | null = null;\n // Store the in-flight fetch promise for deduplication.\n fetchPromise: Promise<RemoteConfigInfo> | null = null;\n // Used to skip periodic updateConfigs calls when API key is invalid.\n isLastFetchInvalidApiKey = false;\n\n constructor(apiKey: string, logger: ILogger, serverZone: ServerZoneType = 'US', serverUrl?: string) {\n this.apiKey = apiKey;\n this.serverUrl = serverUrl || (serverZone === 'US' ? US_SERVER_URL : EU_SERVER_URL);\n this.logger = logger;\n this.storage = new RemoteConfigLocalStorage(apiKey, logger);\n }\n\n subscribe(key: string | undefined, deliveryMode: DeliveryMode, callback: RemoteConfigCallback): string {\n const id = UUID();\n const callbackInfo = {\n id: id,\n key: key,\n deliveryMode: deliveryMode,\n callback: callback,\n };\n this.callbackInfos.push(callbackInfo);\n\n if (deliveryMode === 'all') {\n void this.subscribeAll(callbackInfo);\n } else {\n void this.subscribeWaitForRemote(callbackInfo, deliveryMode.timeout);\n }\n\n return id;\n }\n\n unsubscribe(id: string): boolean {\n const index = this.callbackInfos.findIndex((callbackInfo) => callbackInfo.id === id);\n if (index === -1) {\n this.logger.debug(`Remote config client unsubscribe failed because callback with id ${id} doesn't exist.`);\n return false;\n }\n\n this.callbackInfos.splice(index, 1);\n this.logger.debug(`Remote config client unsubscribe succeeded removing callback with id ${id}.`);\n return true;\n }\n\n async updateConfigs() {\n // Check if we need to throttle based on last successful fetch time\n if (this.lastSuccessfulFetch) {\n const timeSinceLastFetch = Date.now() - this.lastSuccessfulFetch;\n if (timeSinceLastFetch < DEFAULT_MIN_TIME_BETWEEN_FETCHES) {\n this.logger.debug('Remote config client skipping updateConfigs: Too recent');\n return;\n }\n }\n\n const result = await this.getOrCreateFetchPromise();\n void this.storage.setConfig(result);\n this.callbackInfos.forEach((callbackInfo) => {\n this.sendCallback(callbackInfo, result, 'remote');\n });\n }\n\n /**\n * Get the in-flight fetch promise or create a new one.\n * This ensures multiple subscribe calls share the same network request.\n */\n getOrCreateFetchPromise(): Promise<RemoteConfigInfo> {\n if (this.fetchPromise) {\n return this.fetchPromise;\n }\n\n if (this.isLastFetchInvalidApiKey) {\n this.logger.debug('Remote config client skipping fetch: Invalid API key');\n this.fetchPromise = Promise.resolve({\n remoteConfig: null,\n lastFetch: new Date(),\n }).finally(() => {\n this.fetchPromise = null;\n });\n return this.fetchPromise;\n }\n\n this.fetchPromise = this.fetch()\n .then((result) => {\n // Update last successful fetch time if we got a valid config\n if (result.remoteConfig !== null) {\n this.lastSuccessfulFetch = Date.now();\n }\n return result;\n })\n .finally(() => {\n // Clear the promise after it settles (success or failure)\n this.fetchPromise = null;\n });\n\n return this.fetchPromise;\n }\n\n /**\n * Send remote first. If it's already complete, we can skip the cached response.\n * - if remote is fetched first, no cache fetch.\n * - if cache is fetched first, still fetching remote.\n */\n async subscribeAll(callbackInfo: CallbackInfo) {\n const remotePromise = this.getOrCreateFetchPromise().then((result) => {\n this.logger.debug(`Remote config client subscription all mode fetched from remote: ${JSON.stringify(result)}`);\n this.sendCallback(callbackInfo, result, 'remote');\n void this.storage.setConfig(result);\n });\n\n const cachePromise = this.storage.fetchConfig().then((result) => {\n return result;\n });\n\n // Wait for the first result to resolve\n const result = await Promise.race([remotePromise, cachePromise]);\n\n // If cache is fetched first, wait for remote.\n if (result !== undefined) {\n this.logger.debug(`Remote config client subscription all mode fetched from cache: ${JSON.stringify(result)}`);\n // Skip sending callback if cache is empty (first time user).\n if (result.remoteConfig !== null) {\n this.sendCallback(callbackInfo, result, 'cache');\n } else {\n this.logger.debug('Remote config client skips sending callback because cache is empty (first time user).');\n }\n }\n await remotePromise;\n }\n\n /**\n * Waits for a remote response until the given timeout, then return a cached copy, if available.\n */\n async subscribeWaitForRemote(callbackInfo: CallbackInfo, timeout: number) {\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject('Timeout exceeded');\n }, timeout);\n });\n\n try {\n const result: RemoteConfigInfo = (await Promise.race([\n this.getOrCreateFetchPromise(),\n timeoutPromise,\n ])) as RemoteConfigInfo;\n\n this.logger.debug('Remote config client subscription wait for remote mode returns from remote.');\n this.sendCallback(callbackInfo, result, 'remote');\n void this.storage.setConfig(result);\n } catch (error) {\n this.logger.debug(\n 'Remote config client subscription wait for remote mode exceeded timeout. Try to fetch from cache.',\n );\n const result = await this.storage.fetchConfig();\n if (result.remoteConfig !== null) {\n this.logger.debug('Remote config client subscription wait for remote mode returns a cached copy.');\n this.sendCallback(callbackInfo, result, 'cache');\n } else {\n this.logger.debug('Remote config client subscription wait for remote mode failed to fetch cache.');\n this.sendCallback(callbackInfo, result, 'remote');\n }\n }\n }\n\n /**\n * Call the callback with filtered remote config based on key.\n * @param remoteConfigInfo - the whole remote config object without filtering by key.\n */\n sendCallback(callbackInfo: CallbackInfo, remoteConfigInfo: RemoteConfigInfo, source: Source) {\n callbackInfo.lastCallback = new Date();\n\n let filteredConfig: RemoteConfig | null;\n if (callbackInfo.key) {\n // Filter remote config by key.\n // For example, if remote config is {a: {b: {c: 1}}},\n // if key = 'a', filter result is {b: {c: 1}};\n // if key = 'a.b', filter result is {c: 1}\n filteredConfig = callbackInfo.key.split('.').reduce((config, key) => {\n if (config === null) {\n return config;\n }\n\n return key in config ? (config[key] as RemoteConfig) : null;\n }, remoteConfigInfo.remoteConfig);\n } else {\n filteredConfig = remoteConfigInfo.remoteConfig;\n }\n\n callbackInfo.callback(filteredConfig, source, remoteConfigInfo.lastFetch);\n }\n\n /**\n * Fetch remote config from remote.\n * @param retries - the number of retries. default is 3.\n * @param timeout - the timeout in milliseconds. Default is 1000.\n * This timeout serves two purposes:\n * 1. It determines how long to wait for each remote config fetch request before aborting it.\n * If the fetch does not complete within the specified timeout, the request is cancelled using AbortController,\n * and the attempt is considered failed (and may be retried if retries remain).\n * 2. It is also used to calculate the interval between retries. The total timeout is divided by the number of retries,\n * so each retry waits for (timeout / retries) milliseconds before the next attempt (linear backoff).\n * Retry behavior by status code:\n * - 401: invalid API key (stop retries and disable future updateConfigs calls).\n * - 429: retry up to max retries.\n * - other 4xx: no retry.\n * - 5xx and network failures: retry up to max retries.\n * @returns the remote config info. null if failed to fetch or the response is not valid JSON.\n */\n async fetch(retries: number = DEFAULT_MAX_RETRIES, timeout: number = DEFAULT_TIMEOUT): Promise<RemoteConfigInfo> {\n const interval = timeout / retries;\n const failedRemoteConfigInfo: RemoteConfigInfo = {\n remoteConfig: null,\n lastFetch: new Date(),\n };\n\n for (let attempt = 0; attempt < retries; attempt++) {\n let shouldRetry = true;\n // Create AbortController for request timeout\n const abortController = new AbortController();\n const timeoutId = setTimeout(() => abortController.abort(), timeout);\n\n try {\n const res = await fetch(this.getUrlParams(), {\n method: 'GET',\n headers: {\n Accept: '*/*',\n },\n signal: abortController.signal,\n });\n\n // Handle unsuccessful fetch\n if (!res.ok) {\n const body = await res.text();\n this.logger.debug(`Remote config client fetch with retry time ${retries} failed with ${res.status}: ${body}`);\n\n if (res.status === CODE_STATUS.INVALID_API_KEY) {\n this.logger.error(\n `Remote config client fetch failed with ${CODE_STATUS.INVALID_API_KEY}. Invalid API key; future fetches will be skipped.`,\n );\n this.isLastFetchInvalidApiKey = true;\n shouldRetry = false;\n } else if (res.status >= 400 && res.status < 500 && res.status !== CODE_STATUS.RATE_LIMIT) {\n shouldRetry = false;\n }\n } else {\n // Handle successful fetch\n const remoteConfig: RemoteConfig = (await res.json()) as RemoteConfig;\n return {\n remoteConfig: remoteConfig,\n lastFetch: new Date(),\n };\n }\n } catch (error) {\n // Handle rejects when the request fails, for example, a network error or timeout\n if (error instanceof Error && error.name === 'AbortError') {\n this.logger.debug(`Remote config client fetch with retry time ${retries} timed out after ${timeout}ms`);\n } else {\n this.logger.debug(`Remote config client fetch with retry time ${retries} is rejected because: `, error);\n }\n } finally {\n // Clear the timeout since request completed or failed\n clearTimeout(timeoutId);\n }\n\n if (!shouldRetry) {\n break;\n }\n\n // Linear backoff:\n // wait for the specified interval before the next attempt\n // except after the last attempt.\n if (attempt < retries - 1) {\n await new Promise((resolve) => setTimeout(resolve, this.getJitterDelay(interval)));\n }\n }\n\n return failedRemoteConfigInfo;\n }\n\n /**\n * Return jitter in the bound of [0,baseDelay) and then floor round.\n */\n getJitterDelay(baseDelay: number): number {\n return Math.floor(Math.random() * baseDelay);\n }\n\n getUrlParams(): string {\n // URL encode the API key to handle special characters\n const encodedApiKey = encodeURIComponent(this.apiKey);\n\n const urlParams = new URLSearchParams();\n urlParams.append('config_group', RemoteConfigClient.CONFIG_GROUP);\n\n return `${this.serverUrl}/${encodedApiKey}?${urlParams.toString()}`;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"remote-config.js","sourceRoot":"","sources":["../../../src/remote-config/remote-config.ts"],"names":[],"mappings":";;;;AAEA,2EAAwE;AACxE,sCAAqC;AAqBxB,QAAA,aAAa,GAAG,4CAA4C,CAAC;AAC7D,QAAA,aAAa,GAAG,+CAA+C,CAAC;AAChE,QAAA,mBAAmB,GAAG,CAAC,CAAC;AACrC,IAAM,WAAW,GAAG;IAClB,eAAe,EAAE,GAAG;IACpB,SAAS,EAAE,GAAG;IACd,UAAU,EAAE,GAAG;CACP,CAAC;AAEX;;;GAGG;AACH,IAAM,eAAe,GAAG,IAAI,CAAC;AAE7B;;;GAGG;AACH,IAAM,gCAAgC,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,YAAY;AAwEpE;IAgBE,4BAAY,MAAc,EAAE,MAAe,EAAE,UAAiC,EAAE,SAAkB;QAArD,2BAAA,EAAA,iBAAiC;QAT9E,2CAA2C;QAC3C,kBAAa,GAAmB,EAAE,CAAC;QACnC,mFAAmF;QACnF,wBAAmB,GAAkB,IAAI,CAAC;QAC1C,uDAAuD;QACvD,iBAAY,GAAqC,IAAI,CAAC;QACtD,qEAAqE;QACrE,6BAAwB,GAAG,KAAK,CAAC;QAG/B,IAAI,CA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CAAA,AAhTD,IAgTC;AAhTY,gDAAkB","sourcesContent":["import { ServerZoneType } from '../types/server-zone';\nimport { ILogger } from '../logger';\nimport { RemoteConfigLocalStorage } from './remote-config-localstorage';\nimport { UUID } from '../utils/uuid';\n\n/**\n * Modes for receiving remote config updates:\n * - `'all'` – Optimized for both speed and freshness. Returns the fastest response first\n * (cache or remote), then always waits for and returns the remote response to ensure\n * the most up-to-date config. Callback may be called once (if remote wins) or twice\n * (cache first, then remote).\n * - `{ timeout: number }` – Prefers remote data but with a fallback strategy. Waits for\n * a remote response until the specified timeout (in milliseconds), then falls back to\n * cached data if available. Callback is called exactly once.\n */\nexport type DeliveryMode = 'all' | { timeout: number };\n\n/**\n * Sources of returned remote config:\n * - `cache` - Fetched from local storage.\n * - `remote` - Fetched from remote.\n */\nexport type Source = 'cache' | 'remote';\n\nexport const US_SERVER_URL = 'https://sr-client-cfg.amplitude.com/config';\nexport const EU_SERVER_URL = 'https://sr-client-cfg.eu.amplitude.com/config';\nexport const DEFAULT_MAX_RETRIES = 3;\nconst CODE_STATUS = {\n INVALID_API_KEY: 401,\n FORBIDDEN: 403,\n RATE_LIMIT: 429,\n} as const;\n\n/**\n * The default timeout for fetch in milliseconds.\n * Linear backoff policy: timeout / retry times is the interval between fetch retry.\n */\nconst DEFAULT_TIMEOUT = 1000;\n\n/**\n * The minimum time between fetches in milliseconds.\n * This prevents too many requests from being sent in a short period of time.\n */\nconst DEFAULT_MIN_TIME_BETWEEN_FETCHES = 5 * 60 * 1000; // 5 minutes\n\nexport interface RemoteConfig {\n [key: string]: any;\n}\n\nexport interface RemoteConfigInfo {\n remoteConfig: RemoteConfig | null;\n // Timestamp of when the remote config was fetched.\n lastFetch: Date;\n}\n\nexport interface RemoteConfigStorage {\n /**\n * Fetch remote config from storage asynchronously.\n */\n fetchConfig(): Promise<RemoteConfigInfo>;\n\n /**\n * Set remote config to storage asynchronously.\n */\n setConfig(config: RemoteConfigInfo): Promise<boolean>;\n}\n\n/**\n * Information about each callback registered by `RemoteConfigClient.subscribe()`,\n * managed internally by `RemoteConfigClient`.\n */\nexport interface CallbackInfo {\n id: string;\n key?: string;\n deliveryMode: DeliveryMode;\n callback: RemoteConfigCallback;\n lastCallback?: Date;\n}\n\n/**\n * Callback used in `RemoteConfigClient.subscribe()`.\n * This function is called when the remote config is fetched.\n */\ntype RemoteConfigCallback = (remoteConfig: RemoteConfig | null, source: Source, lastFetch: Date) => void;\n\nexport interface IRemoteConfigClient {\n /**\n * Subscribe for updates to remote config.\n * Callback is guaranteed to be called at least once,\n * Whether we are able to fetch a config or not.\n *\n * @param key - a string containing a series of period delimited keys to filter the returned config.\n * Ie, {a: {b: {c: ...}}} would return {b: {c: ...}} for \"a\" or {c: ...} for \"a.b\".\n * Set to `undefined` to subscribe all keys.\n * @param deliveryMode - how the initial callback is sent.\n * @param callback - a block that will be called when remote config is fetched.\n * @return id - identification of the subscribe and can be used to unsubscribe from updates.\n */\n subscribe(key: string | undefined, deliveryMode: DeliveryMode, callback: RemoteConfigCallback): string;\n\n /**\n * Unsubscribe a callback from receiving future updates.\n *\n * @param id - identification of the callback that you want to unsubscribe.\n * It's the return value of subscribe().\n * @return boolean - whether the callback is removed.\n */\n unsubscribe(id: string): boolean;\n\n /**\n * Request the remote config client to fetch from remote, update cache, and callback.\n */\n updateConfigs(): void;\n}\n\nexport class RemoteConfigClient implements IRemoteConfigClient {\n static readonly CONFIG_GROUP = 'browser';\n\n readonly apiKey: string;\n readonly serverUrl: string;\n readonly logger: ILogger;\n readonly storage: RemoteConfigStorage;\n // Registered callbackInfos by subscribe().\n callbackInfos: CallbackInfo[] = [];\n // Track the last successful fetch time for throttling (timestamp in milliseconds).\n lastSuccessfulFetch: number | null = null;\n // Store the in-flight fetch promise for deduplication.\n fetchPromise: Promise<RemoteConfigInfo> | null = null;\n // Used to skip periodic updateConfigs calls when API key is invalid.\n isLastFetchInvalidApiKey = false;\n\n constructor(apiKey: string, logger: ILogger, serverZone: ServerZoneType = 'US', serverUrl?: string) {\n this.apiKey = apiKey;\n this.serverUrl = serverUrl || (serverZone === 'US' ? US_SERVER_URL : EU_SERVER_URL);\n this.logger = logger;\n this.storage = new RemoteConfigLocalStorage(apiKey, logger);\n }\n\n subscribe(key: string | undefined, deliveryMode: DeliveryMode, callback: RemoteConfigCallback): string {\n const id = UUID();\n const callbackInfo = {\n id: id,\n key: key,\n deliveryMode: deliveryMode,\n callback: callback,\n };\n this.callbackInfos.push(callbackInfo);\n\n if (deliveryMode === 'all') {\n void this.subscribeAll(callbackInfo);\n } else {\n void this.subscribeWaitForRemote(callbackInfo, deliveryMode.timeout);\n }\n\n return id;\n }\n\n unsubscribe(id: string): boolean {\n const index = this.callbackInfos.findIndex((callbackInfo) => callbackInfo.id === id);\n if (index === -1) {\n this.logger.debug(`Remote config client unsubscribe failed because callback with id ${id} doesn't exist.`);\n return false;\n }\n\n this.callbackInfos.splice(index, 1);\n this.logger.debug(`Remote config client unsubscribe succeeded removing callback with id ${id}.`);\n return true;\n }\n\n async updateConfigs() {\n // Check if we need to throttle based on last successful fetch time\n if (this.lastSuccessfulFetch) {\n const timeSinceLastFetch = Date.now() - this.lastSuccessfulFetch;\n if (timeSinceLastFetch < DEFAULT_MIN_TIME_BETWEEN_FETCHES) {\n this.logger.debug('Remote config client skipping updateConfigs: Too recent');\n return;\n }\n }\n\n const result = await this.getOrCreateFetchPromise();\n void this.storage.setConfig(result);\n this.callbackInfos.forEach((callbackInfo) => {\n this.sendCallback(callbackInfo, result, 'remote');\n });\n }\n\n /**\n * Get the in-flight fetch promise or create a new one.\n * This ensures multiple subscribe calls share the same network request.\n */\n getOrCreateFetchPromise(): Promise<RemoteConfigInfo> {\n if (this.fetchPromise) {\n return this.fetchPromise;\n }\n\n if (this.isLastFetchInvalidApiKey) {\n this.logger.debug('Remote config client skipping fetch: Invalid API key');\n this.fetchPromise = Promise.resolve({\n remoteConfig: null,\n lastFetch: new Date(),\n }).finally(() => {\n this.fetchPromise = null;\n });\n return this.fetchPromise;\n }\n\n this.fetchPromise = this.fetch()\n .then((result) => {\n // Update last successful fetch time if we got a valid config\n if (result.remoteConfig !== null) {\n this.lastSuccessfulFetch = Date.now();\n }\n return result;\n })\n .finally(() => {\n // Clear the promise after it settles (success or failure)\n this.fetchPromise = null;\n });\n\n return this.fetchPromise;\n }\n\n /**\n * Send remote first. If it's already complete, we can skip the cached response.\n * - if remote is fetched first, no cache fetch.\n * - if cache is fetched first, still fetching remote.\n */\n async subscribeAll(callbackInfo: CallbackInfo) {\n const remotePromise = this.getOrCreateFetchPromise().then((result) => {\n this.logger.debug(`Remote config client subscription all mode fetched from remote: ${JSON.stringify(result)}`);\n this.sendCallback(callbackInfo, result, 'remote');\n void this.storage.setConfig(result);\n });\n\n const cachePromise = this.storage.fetchConfig().then((result) => {\n return result;\n });\n\n // Wait for the first result to resolve\n const result = await Promise.race([remotePromise, cachePromise]);\n\n // If cache is fetched first, wait for remote.\n if (result !== undefined) {\n this.logger.debug(`Remote config client subscription all mode fetched from cache: ${JSON.stringify(result)}`);\n // Skip sending callback if cache is empty (first time user).\n if (result.remoteConfig !== null) {\n this.sendCallback(callbackInfo, result, 'cache');\n } else {\n this.logger.debug('Remote config client skips sending callback because cache is empty (first time user).');\n }\n }\n await remotePromise;\n }\n\n /**\n * Waits for a remote response until the given timeout, then return a cached copy, if available.\n */\n async subscribeWaitForRemote(callbackInfo: CallbackInfo, timeout: number) {\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject('Timeout exceeded');\n }, timeout);\n });\n\n try {\n const result: RemoteConfigInfo = (await Promise.race([\n this.getOrCreateFetchPromise(),\n timeoutPromise,\n ])) as RemoteConfigInfo;\n\n this.logger.debug('Remote config client subscription wait for remote mode returns from remote.');\n this.sendCallback(callbackInfo, result, 'remote');\n void this.storage.setConfig(result);\n } catch (error) {\n this.logger.debug(\n 'Remote config client subscription wait for remote mode exceeded timeout. Try to fetch from cache.',\n );\n const result = await this.storage.fetchConfig();\n if (result.remoteConfig !== null) {\n this.logger.debug('Remote config client subscription wait for remote mode returns a cached copy.');\n this.sendCallback(callbackInfo, result, 'cache');\n } else {\n this.logger.debug('Remote config client subscription wait for remote mode failed to fetch cache.');\n this.sendCallback(callbackInfo, result, 'remote');\n }\n }\n }\n\n /**\n * Call the callback with filtered remote config based on key.\n * @param remoteConfigInfo - the whole remote config object without filtering by key.\n */\n sendCallback(callbackInfo: CallbackInfo, remoteConfigInfo: RemoteConfigInfo, source: Source) {\n callbackInfo.lastCallback = new Date();\n\n let filteredConfig: RemoteConfig | null;\n if (callbackInfo.key) {\n // Filter remote config by key.\n // For example, if remote config is {a: {b: {c: 1}}},\n // if key = 'a', filter result is {b: {c: 1}};\n // if key = 'a.b', filter result is {c: 1}\n filteredConfig = callbackInfo.key.split('.').reduce((config, key) => {\n if (config === null) {\n return config;\n }\n\n return key in config ? (config[key] as RemoteConfig) : null;\n }, remoteConfigInfo.remoteConfig);\n } else {\n filteredConfig = remoteConfigInfo.remoteConfig;\n }\n\n callbackInfo.callback(filteredConfig, source, remoteConfigInfo.lastFetch);\n }\n\n /**\n * Fetch remote config from remote.\n * @param retries - the number of retries. default is 3.\n * @param timeout - the timeout in milliseconds. Default is 1000.\n * This timeout serves two purposes:\n * 1. It determines how long to wait for each remote config fetch request before aborting it.\n * If the fetch does not complete within the specified timeout, the request is cancelled using AbortController,\n * and the attempt is considered failed (and may be retried if retries remain).\n * 2. It is also used to calculate the interval between retries. The total timeout is divided by the number of retries,\n * so each retry waits for (timeout / retries) milliseconds before the next attempt (linear backoff).\n * Retry behavior by status code:\n * - 401: invalid API key (stop retries and disable future updateConfigs calls).\n * - 429: retry up to max retries.\n * - other 4xx: no retry.\n * - 5xx and network failures: retry up to max retries.\n * @returns the remote config info. null if failed to fetch or the response is not valid JSON.\n */\n async fetch(retries: number = DEFAULT_MAX_RETRIES, timeout: number = DEFAULT_TIMEOUT): Promise<RemoteConfigInfo> {\n const interval = timeout / retries;\n const failedRemoteConfigInfo: RemoteConfigInfo = {\n remoteConfig: null,\n lastFetch: new Date(),\n };\n\n for (let attempt = 0; attempt < retries; attempt++) {\n let shouldRetry = true;\n // Create AbortController for request timeout\n const abortController = new AbortController();\n const timeoutId = setTimeout(() => abortController.abort(), timeout);\n\n try {\n const res = await fetch(this.getUrlParams(), {\n method: 'GET',\n headers: {\n Accept: '*/*',\n },\n signal: abortController.signal,\n });\n\n // Handle unsuccessful fetch\n if (!res.ok) {\n const body = await res.text();\n this.logger.debug(`Remote config client fetch with retry time ${retries} failed with ${res.status}: ${body}`);\n\n if (res.status === CODE_STATUS.INVALID_API_KEY || res.status === CODE_STATUS.FORBIDDEN) {\n this.logger.error(\n `Remote config client fetch failed with ${res.status}. Invalid API key; future fetches will be skipped.`,\n );\n this.isLastFetchInvalidApiKey = true;\n shouldRetry = false;\n } else if (res.status >= 400 && res.status < 500 && res.status !== CODE_STATUS.RATE_LIMIT) {\n shouldRetry = false;\n }\n } else {\n // Handle successful fetch\n const remoteConfig: RemoteConfig = (await res.json()) as RemoteConfig;\n return {\n remoteConfig: remoteConfig,\n lastFetch: new Date(),\n };\n }\n } catch (error) {\n // Handle rejects when the request fails, for example, a network error or timeout\n if (error instanceof Error && error.name === 'AbortError') {\n this.logger.debug(`Remote config client fetch with retry time ${retries} timed out after ${timeout}ms`);\n } else {\n this.logger.debug(`Remote config client fetch with retry time ${retries} is rejected because: `, error);\n }\n } finally {\n // Clear the timeout since request completed or failed\n clearTimeout(timeoutId);\n }\n\n if (!shouldRetry) {\n break;\n }\n\n // Linear backoff:\n // wait for the specified interval before the next attempt\n // except after the last attempt.\n if (attempt < retries - 1) {\n await new Promise((resolve) => setTimeout(resolve, this.getJitterDelay(interval)));\n }\n }\n\n return failedRemoteConfigInfo;\n }\n\n /**\n * Return jitter in the bound of [0,baseDelay) and then floor round.\n */\n getJitterDelay(baseDelay: number): number {\n return Math.floor(Math.random() * baseDelay);\n }\n\n getUrlParams(): string {\n // URL encode the API key to handle special characters\n const encodedApiKey = encodeURIComponent(this.apiKey);\n\n const urlParams = new URLSearchParams();\n urlParams.append('config_group', RemoteConfigClient.CONFIG_GROUP);\n\n return `${this.serverUrl}/${encodedApiKey}?${urlParams.toString()}`;\n }\n}\n"]}
|
package/lib/cjs/revenue.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"revenue.d.ts","sourceRoot":"","sources":["../../src/revenue.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,QAAQ;IACvB,kBAAkB,IAAI,sBAAsB,CAAC;IAC7C,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC1C,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,CAAC;IACxC,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,QAAQ,CAAC;IAClC,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC9C,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,CAAC;IACxC,kBAAkB,CAAC,UAAU,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,GAAG,QAAQ,CAAC;IACjE,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ,CAAC;IACtC,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ,CAAC;IACtC,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,QAAQ,CAAC;CAC7C;AAED,qBAAa,OAAQ,YAAW,QAAQ;IACtC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,WAAW,CAAC,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAC,CAAS;IAC1B,OAAO,CAAC,UAAU,CAAC,CAAyB;IAC5C,OAAO,CAAC,OAAO,CAAC,CAAS;IACzB,OAAO,CAAC,OAAO,CAAC,CAAS;IACzB,OAAO,CAAC,UAAU,CAAC,CAAS;;I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aAAa,WAAW;IACxB,YAAY,iBAAiB;IAC7B,gBAAgB,cAAc;IAC9B,OAAO,aAAa;IACpB,OAAO,aAAa;IACpB,WAAW,gBAAgB;CAC5B;AAED,MAAM,MAAM,iBAAiB,GACzB,MAAM,GACN,MAAM,GACN,OAAO,GACP,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,GACtB;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,iBAAiB,CAAA;CAAE,GACpC,KAAK,CAAC;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,iBAAiB,CAAA;CAAE,CAAC,CAAC"}
|
package/lib/cjs/revenue.js
CHANGED
|
@@ -44,8 +44,16 @@ var Revenue = /** @class */ (function () {
|
|
|
44
44
|
return this;
|
|
45
45
|
};
|
|
46
46
|
Revenue.prototype.setEventProperties = function (properties) {
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
try {
|
|
48
|
+
// JSON.stringify drops undefined/function/symbol values before validation,
|
|
49
|
+
// so a single undefined property no longer causes the whole object to be rejected.
|
|
50
|
+
var filtered = JSON.parse(JSON.stringify(properties));
|
|
51
|
+
if ((0, valid_properties_1.isValidObject)(filtered)) {
|
|
52
|
+
this.properties = filtered;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
catch (_a) {
|
|
56
|
+
// no-op: invalid properties are ignored
|
|
49
57
|
}
|
|
50
58
|
return this;
|
|
51
59
|
};
|
package/lib/cjs/revenue.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"revenue.js","sourceRoot":"","sources":["../../src/revenue.ts"],"names":[],"mappings":";;;;AAAA,6DAAyD;AAezD;IAWE;QACE,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;QACpB,IAAI,CAAC,QAAQ,GAAG,CAAC,CAAC;QAClB,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC;IACnB,CAAC;IAED,8BAAY,GAAZ,UAAa,SAAiB;QAC5B,IAAI,CAAC,SAAS,GAAG,SAA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,eAAe,GAA2B,IAAI,CAAC,UAAU,CAAC,CAAC,sBAAM,IAAI,CAAC,UAAU,EAAG,CAAC,CAAC,EAAE,CAAC;QAC9F,eAAe,CAAC,eAAe,CAAC,kBAAkB,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC;QACrE,eAAe,CAAC,eAAe,CAAC,gBAAgB,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC;QAClE,eAAe,CAAC,eAAe,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC;QAC5D,eAAe,CAAC,eAAe,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC;QACjE,eAAe,CAAC,eAAe,CAAC,gBAAgB,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC;QAClE,eAAe,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC;QACxD,eAAe,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC;QACxD,eAAe,CAAC,eAAe,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC;QAC/D,OAAO,eAAe,CAAC;IACzB,CAAC;IACH,cAAC;AAAD,CAAC,AArFD,IAqFC;AArFY,0BAAO;AAkGpB,IAAY,eASX;AATD,WAAY,eAAe;IACzB,oDAAiC,CAAA;IACjC,iDAA8B,CAAA;IAC9B,2CAAwB,CAAA;IACxB,gDAA6B,CAAA;IAC7B,iDAA8B,CAAA;IAC9B,uCAAoB,CAAA;IACpB,uCAAoB,CAAA;IACpB,8CAA2B,CAAA;AAC7B,CAAC,EATW,eAAe,GAAf,uBAAe,KAAf,uBAAe,QAS1B","sourcesContent":["import { isValidObject } from './utils/valid-properties';\n\nexport interface IRevenue {\n getEventProperties(): RevenueEventProperties;\n setProductId(productId: string): IRevenue;\n setQuantity(quantity: number): IRevenue;\n setPrice(price: number): IRevenue;\n setRevenueType(revenueType: string): IRevenue;\n setCurrency(currency: string): IRevenue;\n setEventProperties(properties: { [key: string]: any }): IRevenue;\n setRevenue(revenue: number): IRevenue;\n setReceipt(receipt: string): IRevenue;\n setReceiptSig(receiptSig: string): IRevenue;\n}\n\nexport class Revenue implements IRevenue {\n private productId: string;\n private quantity: number;\n private price: number;\n private revenueType?: string;\n private currency?: string;\n private properties?: { [key: string]: any };\n private revenue?: number;\n private receipt?: string;\n private receiptSig?: string;\n\n constructor() {\n this.productId = '';\n this.quantity = 1;\n this.price = 0.0;\n }\n\n setProductId(productId: string) {\n this.productId = productId;\n return this;\n }\n\n setQuantity(quantity: number) {\n if (quantity > 0) {\n this.quantity = quantity;\n }\n return this;\n }\n\n setPrice(price: number) {\n this.price = price;\n return this;\n }\n\n setRevenueType(revenueType: string) {\n this.revenueType = revenueType;\n return this;\n }\n\n setCurrency(currency: string) {\n this.currency = currency;\n return this;\n }\n\n setRevenue(revenue: number) {\n this.revenue = revenue;\n return this;\n }\n\n setReceipt(receipt: string) {\n this.receipt = receipt;\n return this;\n }\n\n setReceiptSig(receiptSig: string) {\n this.receiptSig = receiptSig;\n return this;\n }\n\n setEventProperties(properties: { [key: string]: ValidPropertyType }) {\n try {\n // JSON.stringify drops undefined/function/symbol values before validation,\n // so a single undefined property no longer causes the whole object to be rejected.\n const filtered = JSON.parse(JSON.stringify(properties)) as { [key: string]: ValidPropertyType };\n if (isValidObject(filtered)) {\n this.properties = filtered;\n }\n } catch {\n // no-op: invalid properties are ignored\n }\n return this;\n }\n\n getEventProperties(): RevenueEventProperties {\n const eventProperties: RevenueEventProperties = this.properties ? { ...this.properties } : {};\n eventProperties[RevenueProperty.REVENUE_PRODUCT_ID] = this.productId;\n eventProperties[RevenueProperty.REVENUE_QUANTITY] = this.quantity;\n eventProperties[RevenueProperty.REVENUE_PRICE] = this.price;\n eventProperties[RevenueProperty.REVENUE_TYPE] = this.revenueType;\n eventProperties[RevenueProperty.REVENUE_CURRENCY] = this.currency;\n eventProperties[RevenueProperty.REVENUE] = this.revenue;\n eventProperties[RevenueProperty.RECEIPT] = this.receipt;\n eventProperties[RevenueProperty.RECEIPT_SIG] = this.receiptSig;\n return eventProperties;\n }\n}\n\nexport interface RevenueEventProperties {\n [RevenueProperty.REVENUE_PRODUCT_ID]?: string;\n [RevenueProperty.REVENUE_QUANTITY]?: number;\n [RevenueProperty.REVENUE_PRICE]?: number;\n [RevenueProperty.REVENUE_TYPE]?: string;\n [RevenueProperty.REVENUE_CURRENCY]?: string;\n [RevenueProperty.REVENUE]?: number;\n [RevenueProperty.RECEIPT]?: string;\n [RevenueProperty.RECEIPT_SIG]?: string;\n}\n\nexport enum RevenueProperty {\n REVENUE_PRODUCT_ID = '$productId',\n REVENUE_QUANTITY = '$quantity',\n REVENUE_PRICE = '$price',\n REVENUE_TYPE = '$revenueType',\n REVENUE_CURRENCY = '$currency',\n REVENUE = '$revenue',\n RECEIPT = '$receipt',\n RECEIPT_SIG = '$receiptSig',\n}\n\nexport type ValidPropertyType =\n | number\n | string\n | boolean\n | Array<string | number>\n | { [key: string]: ValidPropertyType }\n | Array<{ [key: string]: ValidPropertyType }>;\n"]}
|
|
@@ -9,6 +9,7 @@ import { NetworkTrackingOptions } from '../network-tracking';
|
|
|
9
9
|
import { FrustrationInteractionsOptions } from '../frustration-interactions';
|
|
10
10
|
import { IDiagnosticsClient } from '../../diagnostics/diagnostics-client';
|
|
11
11
|
import { IRemoteConfigClient } from '../../remote-config/remote-config';
|
|
12
|
+
import { CustomEnrichmentOptions } from '../custom-enrichment';
|
|
12
13
|
export interface BrowserConfig extends ExternalBrowserConfig, InternalBrowserConfig {
|
|
13
14
|
}
|
|
14
15
|
export interface ExternalBrowserConfig extends IConfig {
|
|
@@ -29,6 +30,11 @@ export interface ExternalBrowserConfig extends IConfig {
|
|
|
29
30
|
* See {@link https://www.docs.developers.amplitude.com/data/sdks/browser-2/autocapture/}.
|
|
30
31
|
*/
|
|
31
32
|
autocapture?: boolean | AutocaptureOptions;
|
|
33
|
+
/**
|
|
34
|
+
* The configurations for custom enrichment.
|
|
35
|
+
* @defaultValue `false`
|
|
36
|
+
*/
|
|
37
|
+
customEnrichment?: boolean | CustomEnrichmentOptions;
|
|
32
38
|
/**
|
|
33
39
|
* The identifier for the device running your application.
|
|
34
40
|
* @defaultValue `UUID()`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-config.d.ts","sourceRoot":"","sources":["../../../../src/types/config/browser-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"browser-config.d.ts","sourceRoot":"","sources":["../../../../src/types/config/browser-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAA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