@statsig/client-core
Advanced tools
Comparing version 0.0.1-beta.41 to 0.0.1-beta.42
{ | ||
"name": "@statsig/client-core", | ||
"version": "0.0.1-beta.41", | ||
"version": "0.0.1-beta.42", | ||
"dependencies": {}, | ||
@@ -5,0 +5,0 @@ "type": "commonjs", |
@@ -7,8 +7,11 @@ "use strict"; | ||
const _getStatsigGlobal = () => { | ||
return __STATSIG__ !== null && __STATSIG__ !== void 0 ? __STATSIG__ : statsigGlobal; | ||
return __STATSIG__ ? __STATSIG__ : statsigGlobal; | ||
}; | ||
exports._getStatsigGlobal = _getStatsigGlobal; | ||
const _getInstance = (sdkKey) => { | ||
var _a; | ||
return sdkKey ? (_a = __STATSIG__ === null || __STATSIG__ === void 0 ? void 0 : __STATSIG__.instances) === null || _a === void 0 ? void 0 : _a[sdkKey] : __STATSIG__ === null || __STATSIG__ === void 0 ? void 0 : __STATSIG__.lastInstance; | ||
const gbl = (0, exports._getStatsigGlobal)(); | ||
if (!sdkKey) { | ||
return gbl.lastInstance; | ||
} | ||
return gbl.instances && gbl.instances[sdkKey]; | ||
}; | ||
@@ -15,0 +18,0 @@ exports._getInstance = _getInstance; |
@@ -18,3 +18,3 @@ "use strict"; | ||
]; | ||
return (0, Hashing_1.DJB2)(parts.join('|')); | ||
return (0, Hashing_1._DJB2)(parts.join('|')); | ||
} | ||
@@ -26,4 +26,4 @@ exports._getUserStorageKey = _getUserStorageKey; | ||
} | ||
return (0, Hashing_1.DJB2)(`k:${sdkKey}`); | ||
return (0, Hashing_1._DJB2)(`k:${sdkKey}`); | ||
} | ||
exports._getStorageKey = _getStorageKey; |
@@ -27,3 +27,2 @@ import { DataAdapterAsyncOptions, DataAdapterResult } from './StatsigDataAdapter'; | ||
protected _getSdkKey(): string; | ||
protected _addToInMemoryCache(cacheKey: string, result: DataAdapterResult): void; | ||
private _loadFromCache; | ||
@@ -30,0 +29,0 @@ private _writeToCache; |
@@ -14,2 +14,3 @@ "use strict"; | ||
const Log_1 = require("./Log"); | ||
const StableID_1 = require("./StableID"); | ||
const StatsigUser_1 = require("./StatsigUser"); | ||
@@ -25,4 +26,4 @@ const StorageProvider_1 = require("./StorageProvider"); | ||
this._sdkKey = null; | ||
this._inMemoryCache = {}; | ||
this._lastModifiedStoreKey = `statsig.last_modified_time.${_cacheSuffix}`; | ||
this._inMemoryCache = new InMemoryCache(); | ||
} | ||
@@ -35,10 +36,10 @@ attach(sdkKey, options) { | ||
const cacheKey = this._getCacheKey(user); | ||
const result = this._inMemoryCache[cacheKey]; | ||
if (result) { | ||
return result; | ||
const inMem = this._inMemoryCache.get(cacheKey, user); | ||
if (inMem) { | ||
return inMem; | ||
} | ||
const cache = this._loadFromCache(cacheKey); | ||
if (cache) { | ||
this._addToInMemoryCache(cacheKey, cache); | ||
return this._inMemoryCache[cacheKey]; | ||
this._inMemoryCache.add(cacheKey, cache); | ||
return this._inMemoryCache.get(cacheKey, user); | ||
} | ||
@@ -51,7 +52,3 @@ return null; | ||
const cacheKey = this._getCacheKey(normalized); | ||
this._addToInMemoryCache(cacheKey, { | ||
source: 'Bootstrap', | ||
data, | ||
receivedAt: Date.now(), | ||
}); | ||
this._inMemoryCache.add(cacheKey, _makeDataAdapterResult('Bootstrap', data, null)); | ||
} | ||
@@ -64,3 +61,3 @@ /** | ||
__primeInMemoryCache(cache) { | ||
this._inMemoryCache = Object.assign(Object.assign({}, this._inMemoryCache), cache); | ||
this._inMemoryCache.merge(cache); | ||
} | ||
@@ -88,3 +85,3 @@ _getDataAsyncImpl(current, user, options) { | ||
if (result) { | ||
this._addToInMemoryCache(cacheKey, Object.assign(Object.assign({}, result), { source: 'Prefetch' })); | ||
this._inMemoryCache.add(cacheKey, Object.assign(Object.assign({}, result), { source: 'Prefetch' })); | ||
} | ||
@@ -100,19 +97,17 @@ }); | ||
} | ||
const response = (0, TypedJsonParse_1.typedJsonParse)(latest, 'has_updates', 'Failure while attempting to persist latest value'); | ||
const response = (0, TypedJsonParse_1._typedJsonParse)(latest, 'has_updates', 'Initialize Response'); | ||
const sdkKey = this._getSdkKey(); | ||
const stableID = yield StableID_1.StableID.get(sdkKey); | ||
let result = null; | ||
if ((response === null || response === void 0 ? void 0 : response.has_updates) === true) { | ||
result = { source: 'Network', data: latest, receivedAt: Date.now() }; | ||
result = _makeDataAdapterResult('Network', latest, stableID); | ||
} | ||
else if (current && (response === null || response === void 0 ? void 0 : response.has_updates) === false) { | ||
result = { | ||
source: 'NetworkNotModified', | ||
data: current, | ||
receivedAt: Date.now(), | ||
}; | ||
result = _makeDataAdapterResult('NetworkNotModified', current, stableID); | ||
} | ||
if (!result) { | ||
else { | ||
return null; | ||
} | ||
const cacheKey = this._getCacheKey(user); | ||
this._addToInMemoryCache(cacheKey, result); | ||
this._inMemoryCache.add(cacheKey, result); | ||
yield this._writeToCache(cacheKey, result); | ||
@@ -129,14 +124,2 @@ return result; | ||
} | ||
_addToInMemoryCache(cacheKey, result) { | ||
const entries = Object.entries(this._inMemoryCache); | ||
if (entries.length < CACHE_LIMIT) { | ||
this._inMemoryCache[cacheKey] = result; | ||
return; | ||
} | ||
const [oldest] = entries.reduce((acc, curr) => { | ||
return curr[1] < acc[1] ? curr : acc; | ||
}); | ||
delete this._inMemoryCache[oldest]; | ||
this._inMemoryCache[cacheKey] = result; | ||
} | ||
_loadFromCache(cacheKey) { | ||
@@ -148,3 +131,3 @@ var _a; | ||
} | ||
const result = (0, TypedJsonParse_1.typedJsonParse)(cache, 'source', 'Failed to parse cached result'); | ||
const result = (0, TypedJsonParse_1._typedJsonParse)(cache, 'source', 'Cached Result'); | ||
return result ? Object.assign(Object.assign({}, result), { source: 'Cache' }) : null; | ||
@@ -178,1 +161,40 @@ } | ||
exports.DataAdapterCore = DataAdapterCore; | ||
function _makeDataAdapterResult(source, data, stableID) { | ||
return { | ||
source, | ||
data, | ||
receivedAt: Date.now(), | ||
stableID, | ||
}; | ||
} | ||
class InMemoryCache { | ||
constructor() { | ||
this._data = {}; | ||
} | ||
get(cacheKey, user) { | ||
var _a; | ||
const result = this._data[cacheKey]; | ||
const cached = result === null || result === void 0 ? void 0 : result.stableID; | ||
const provided = (_a = user === null || user === void 0 ? void 0 : user.customIDs) === null || _a === void 0 ? void 0 : _a.stableID; | ||
if (provided && cached && provided !== cached) { | ||
Log_1.Log.warn("'StatsigUser.customIDs.stableID' mismatch"); | ||
return null; | ||
} | ||
return result; | ||
} | ||
add(cacheKey, value) { | ||
const entries = Object.entries(this._data); | ||
if (entries.length < CACHE_LIMIT) { | ||
this._data[cacheKey] = value; | ||
return; | ||
} | ||
const [oldest] = entries.reduce((acc, curr) => { | ||
return curr[1] < acc[1] ? curr : acc; | ||
}); | ||
delete this._data[oldest]; | ||
this._data[cacheKey] = value; | ||
} | ||
merge(values) { | ||
this._data = Object.assign(Object.assign({}, this._data), values); | ||
} | ||
} |
@@ -11,5 +11,5 @@ import { StatsigClientEmitEventFunc } from './StatsigClientBase'; | ||
wrap(instance: unknown): void; | ||
capture(tag: string, task: () => unknown): unknown; | ||
logError(tag: string, error: unknown): void; | ||
private _capture; | ||
private _onError; | ||
} |
@@ -17,2 +17,3 @@ "use strict"; | ||
exports.EXCEPTION_ENDPOINT = 'https://statsigapi.net/v1/sdk_exception'; | ||
const UNKNOWN_ERROR = '[Statsig] UnknownError'; | ||
class ErrorBoundary { | ||
@@ -34,3 +35,3 @@ constructor(_sdkKey, _options, _emitter) { | ||
obj[name] = (...args) => { | ||
return this.capture(name, () => original.apply(instance, args)); | ||
return this._capture(name, () => original.apply(instance, args)); | ||
}; | ||
@@ -44,3 +45,6 @@ obj[name].$EB = true; | ||
} | ||
capture(tag, task) { | ||
logError(tag, error) { | ||
this._onError(tag, error); | ||
} | ||
_capture(tag, task) { | ||
try { | ||
@@ -58,5 +62,2 @@ const res = task(); | ||
} | ||
logError(tag, error) { | ||
this._onError(tag, error); | ||
} | ||
_onError(tag, error) { | ||
@@ -67,3 +68,3 @@ try { | ||
var _a, _b, _c, _d, _e, _f, _g; | ||
const unwrapped = (error !== null && error !== void 0 ? error : Error('[Statsig] Error was empty')); | ||
const unwrapped = (error ? error : Error(UNKNOWN_ERROR)); | ||
const isError = unwrapped instanceof Error; | ||
@@ -115,3 +116,3 @@ const name = isError ? unwrapped.name : 'No Name'; | ||
catch (_a) { | ||
return '[Statsig] Failed to get string for error.'; | ||
return UNKNOWN_ERROR; | ||
} | ||
@@ -118,0 +119,0 @@ } |
@@ -19,3 +19,2 @@ import { NetworkCore } from './NetworkCore'; | ||
private _logEventUrl; | ||
private _logEventBeaconUrl; | ||
constructor(_sdkKey: string, _emitter: StatsigClientEmitEventFunc, _network: NetworkCore, _options: StatsigOptionsCommon<NetworkConfigCommon> | null); | ||
@@ -37,2 +36,3 @@ setLoggingDisabled(isDisabled: boolean): void; | ||
private _sendEventsViaBeacon; | ||
private _getRequestData; | ||
private _saveFailedLogsToStorage; | ||
@@ -44,2 +44,3 @@ private _retryFailedLogs; | ||
private _getCurrentPageUrl; | ||
private _startBackgroundFlushInterval; | ||
} |
@@ -36,3 +36,3 @@ "use strict"; | ||
constructor(_sdkKey, _emitter, _network, _options) { | ||
var _a, _b; | ||
var _a; | ||
this._sdkKey = _sdkKey; | ||
@@ -50,16 +50,4 @@ this._emitter = _emitter; | ||
this._maxQueueSize = (_a = _options === null || _options === void 0 ? void 0 : _options.loggingBufferMaxSize) !== null && _a !== void 0 ? _a : DEFAULT_QUEUE_SIZE; | ||
const flushInterval = (_b = _options === null || _options === void 0 ? void 0 : _options.loggingIntervalMs) !== null && _b !== void 0 ? _b : DEFAULT_FLUSH_INTERVAL_MS; | ||
const intervalId = setInterval(() => { | ||
const logger = EVENT_LOGGER_MAP[_sdkKey]; | ||
if (logger._flushIntervalId !== intervalId) { | ||
clearInterval(intervalId); | ||
} | ||
else { | ||
_safeFlushAndForget(_sdkKey); | ||
} | ||
}, flushInterval); | ||
this._flushIntervalId = intervalId; | ||
const config = _options === null || _options === void 0 ? void 0 : _options.networkConfig; | ||
this._logEventUrl = (0, UrlOverrides_1._getOverridableUrl)(config === null || config === void 0 ? void 0 : config.logEventUrl, config === null || config === void 0 ? void 0 : config.api, '/rgstr', NetworkConfig_1.NetworkDefault.eventsApi); | ||
this._logEventBeaconUrl = (0, UrlOverrides_1._getOverridableUrl)(config === null || config === void 0 ? void 0 : config.logEventBeaconUrl, config === null || config === void 0 ? void 0 : config.api, '/log_event_beacon', NetworkConfig_1.NetworkDefault.eventsApi); | ||
(0, VisibilityObserving_1._subscribeToVisiblityChanged)((visibility) => { | ||
@@ -71,2 +59,3 @@ if (visibility === 'background') { | ||
this._retryFailedLogs(); | ||
this._startBackgroundFlushInterval(); | ||
} | ||
@@ -111,3 +100,3 @@ setLoggingDisabled(isDisabled) { | ||
this._queue = []; | ||
yield this._sendEvents(events); | ||
return this._sendEvents(events); | ||
}); | ||
@@ -130,12 +119,13 @@ } | ||
_shouldLogEvent(event) { | ||
var _a, _b, _c, _d; | ||
if (!(0, StatsigEvent_1._isExposureEvent)(event)) { | ||
return true; | ||
} | ||
const user = event.user ? event.user : {}; | ||
const metadata = event.metadata ? event.metadata : {}; | ||
const key = [ | ||
event.eventName, | ||
(_a = event.user) === null || _a === void 0 ? void 0 : _a.userID, | ||
(_b = event.metadata) === null || _b === void 0 ? void 0 : _b['gate'], | ||
(_c = event.metadata) === null || _c === void 0 ? void 0 : _c['config'], | ||
(_d = event.metadata) === null || _d === void 0 ? void 0 : _d['ruleID'], | ||
user.userID, | ||
metadata['gate'], | ||
metadata['config'], | ||
metadata['ruleID'], | ||
].join('|'); | ||
@@ -186,13 +176,3 @@ const previous = this._lastExposureTimeMap[key]; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const result = yield this._network.post({ | ||
sdkKey: this._sdkKey, | ||
data: { | ||
events, | ||
}, | ||
url: this._logEventUrl, | ||
retries: 3, | ||
params: { | ||
[NetworkConfig_1.NetworkParam.EventCount]: String(events.length), | ||
}, | ||
}); | ||
const result = yield this._network.post(this._getRequestData(events)); | ||
const code = (_a = result === null || result === void 0 ? void 0 : result.code) !== null && _a !== void 0 ? _a : -1; | ||
@@ -205,12 +185,20 @@ return { success: code >= 200 && code < 300 }; | ||
return { | ||
success: yield this._network.beacon({ | ||
sdkKey: this._sdkKey, | ||
data: { | ||
events, | ||
}, | ||
url: this._logEventBeaconUrl, | ||
}), | ||
success: yield this._network.beacon(this._getRequestData(events)), | ||
}; | ||
}); | ||
} | ||
_getRequestData(events) { | ||
return { | ||
sdkKey: this._sdkKey, | ||
data: { | ||
events, | ||
}, | ||
url: this._logEventUrl, | ||
retries: 3, | ||
isCompressable: true, | ||
params: { | ||
[NetworkConfig_1.NetworkParam.EventCount]: String(events.length), | ||
}, | ||
}; | ||
} | ||
_saveFailedLogsToStorage(events) { | ||
@@ -239,3 +227,3 @@ while (events.length > MAX_FAILED_LOGS) { | ||
_getStorageKey() { | ||
return `statsig.failed_logs.${(0, Hashing_1.DJB2)(this._sdkKey)}`; | ||
return `statsig.failed_logs.${(0, Hashing_1._DJB2)(this._sdkKey)}`; | ||
} | ||
@@ -252,3 +240,5 @@ _normalizeAndAppendEvent(event) { | ||
} | ||
this._queue.push(Object.assign(Object.assign({}, event), extras)); | ||
const final = Object.assign(Object.assign({}, event), extras); | ||
Log_1.Log.debug('Enqueued Event:', final); | ||
this._queue.push(final); | ||
} | ||
@@ -276,3 +266,20 @@ _appendAndResetNonExposedChecks() { | ||
} | ||
_startBackgroundFlushInterval() { | ||
var _a, _b; | ||
if (!(0, SafeJs_1._isBrowserEnv)()) { | ||
return; // do not run in server environments | ||
} | ||
const flushInterval = (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.loggingIntervalMs) !== null && _b !== void 0 ? _b : DEFAULT_FLUSH_INTERVAL_MS; | ||
const intervalId = setInterval(() => { | ||
const logger = EVENT_LOGGER_MAP[this._sdkKey]; | ||
if (logger._flushIntervalId !== intervalId) { | ||
clearInterval(intervalId); | ||
} | ||
else { | ||
_safeFlushAndForget(this._sdkKey); | ||
} | ||
}, flushInterval); | ||
this._flushIntervalId = intervalId; | ||
} | ||
} | ||
exports.EventLogger = EventLogger; |
@@ -1,2 +0,2 @@ | ||
export declare const DJB2: (value: string) => string; | ||
export declare const DJB2Object: (value: Record<string, unknown> | null) => string; | ||
export declare const _DJB2: (value: string) => string; | ||
export declare const _DJB2Object: (value: Record<string, unknown> | null) => string; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.DJB2Object = exports.DJB2 = void 0; | ||
const DJB2 = (value) => { | ||
exports._DJB2Object = exports._DJB2 = void 0; | ||
const _DJB2 = (value) => { | ||
let hash = 0; | ||
@@ -13,7 +13,7 @@ for (let i = 0; i < value.length; i++) { | ||
}; | ||
exports.DJB2 = DJB2; | ||
const DJB2Object = (value) => { | ||
return (0, exports.DJB2)(JSON.stringify(_getSortedObject(value))); | ||
exports._DJB2 = _DJB2; | ||
const _DJB2Object = (value) => { | ||
return (0, exports._DJB2)(JSON.stringify(_getSortedObject(value))); | ||
}; | ||
exports.DJB2Object = DJB2Object; | ||
exports._DJB2Object = _DJB2Object; | ||
const _getSortedObject = (object) => { | ||
@@ -20,0 +20,0 @@ if (object == null) { |
@@ -27,3 +27,2 @@ "use strict"; | ||
Object.defineProperty(exports, "Storage", { enumerable: true, get: function () { return StorageProvider_1.Storage; } }); | ||
const UUID_1 = require("./UUID"); | ||
__exportStar(require("./$_StatsigGlobal"), exports); | ||
@@ -62,6 +61,3 @@ __exportStar(require("./CacheKey"), exports); | ||
__exportStar(require("./VisibilityObserving"), exports); | ||
__STATSIG__ = Object.assign(Object.assign({}, (__STATSIG__ !== null && __STATSIG__ !== void 0 ? __STATSIG__ : {})), { EventLogger: EventLogger_1.EventLogger, | ||
Log: Log_1.Log, | ||
getUUID: UUID_1.getUUID, | ||
Storage: StorageProvider_1.Storage, | ||
__STATSIG__ = Object.assign(Object.assign({}, (__STATSIG__ !== null && __STATSIG__ !== void 0 ? __STATSIG__ : {})), { Log: Log_1.Log, | ||
SDK_VERSION: StatsigMetadata_1.SDK_VERSION }); |
@@ -17,3 +17,4 @@ export declare const NetworkDefault: { | ||
SessionID = "sid", | ||
StatsigEncoded = "se" | ||
StatsigEncoded = "se", | ||
IsGzipped = "gz" | ||
} |
@@ -18,2 +18,3 @@ "use strict"; | ||
NetworkParam["StatsigEncoded"] = "se"; | ||
NetworkParam["IsGzipped"] = "gz"; | ||
})(NetworkParam || (exports.NetworkParam = NetworkParam = {})); |
@@ -5,2 +5,3 @@ import './$_StatsigGlobal'; | ||
import { AnyStatsigOptions } from './StatsigOptionsCommon'; | ||
import { Flatten } from './UtitlityTypes'; | ||
type RequestArgs = { | ||
@@ -14,6 +15,8 @@ sdkKey: string; | ||
}; | ||
type RequestArgsWithData = RequestArgs & { | ||
export type RequestArgsWithData = Flatten<RequestArgs & { | ||
data: Record<string, unknown>; | ||
isStatsigEncodable?: boolean; | ||
}; | ||
isCompressable?: boolean; | ||
}>; | ||
type BeaconRequestArgs = Pick<RequestArgsWithData, 'data' | 'sdkKey' | 'url' | 'params' | 'isCompressable'>; | ||
type NetworkResponse = { | ||
@@ -27,2 +30,3 @@ body: string | null; | ||
private readonly _timeout; | ||
private readonly _netConfig; | ||
constructor(_options: AnyStatsigOptions | null, _emitter?: StatsigClientEmitEventFunc | undefined); | ||
@@ -32,3 +36,3 @@ post(args: RequestArgsWithData): Promise<NetworkResponse | null>; | ||
isBeaconSupported(): boolean; | ||
beacon(args: RequestArgsWithData): Promise<boolean>; | ||
beacon(args: BeaconRequestArgs): Promise<boolean>; | ||
private _sendRequest; | ||
@@ -35,0 +39,0 @@ private _getPopulatedURL; |
@@ -26,12 +26,18 @@ "use strict"; | ||
constructor(_options, _emitter) { | ||
var _a, _b; | ||
var _a, _b, _c; | ||
this._options = _options; | ||
this._emitter = _emitter; | ||
this._timeout = | ||
(_b = (_a = _options === null || _options === void 0 ? void 0 : _options.networkConfig) === null || _a === void 0 ? void 0 : _a.networkTimeoutMs) !== null && _b !== void 0 ? _b : DEFAULT_TIMEOUT_MS; | ||
this._netConfig = (_a = _options === null || _options === void 0 ? void 0 : _options.networkConfig) !== null && _a !== void 0 ? _a : null; | ||
this._timeout = (_c = (_b = this._netConfig) === null || _b === void 0 ? void 0 : _b.networkTimeoutMs) !== null && _c !== void 0 ? _c : DEFAULT_TIMEOUT_MS; | ||
} | ||
post(args) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const body = yield this._getPopulatedBody(args); | ||
return this._sendRequest(Object.assign({ method: 'POST', body: this._attemptToEncodeString(args, body) }, args)); | ||
let body = yield this._getPopulatedBody(args); | ||
if (args.isStatsigEncodable) { | ||
body = this._attemptToEncodeString(args, body); | ||
} | ||
else if (args.isCompressable) { | ||
body = yield _attemptToCompressBody(args, body); | ||
} | ||
return this._sendRequest(Object.assign({ method: 'POST', body }, args)); | ||
}); | ||
@@ -44,3 +50,3 @@ } | ||
return (typeof navigator !== 'undefined' && | ||
typeof (navigator === null || navigator === void 0 ? void 0 : navigator.sendBeacon) === 'function'); | ||
typeof navigator.sendBeacon === 'function'); | ||
} | ||
@@ -52,4 +58,5 @@ beacon(args) { | ||
} | ||
let body = yield this._getPopulatedBody(args); | ||
body = yield _attemptToCompressBody(args, body); | ||
const url = yield this._getPopulatedURL(args); | ||
const body = yield this._getPopulatedBody(args); | ||
return navigator.sendBeacon(url, body); | ||
@@ -59,3 +66,3 @@ }); | ||
_sendRequest(args) { | ||
var _a, _b, _c, _d, _e, _f; | ||
var _a, _b, _c, _d; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
@@ -65,8 +72,8 @@ if (!_ensureValidSdkKey(args)) { | ||
} | ||
if ((_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.networkConfig) === null || _b === void 0 ? void 0 : _b.preventAllNetworkTraffic) { | ||
if ((_a = this._netConfig) === null || _a === void 0 ? void 0 : _a.preventAllNetworkTraffic) { | ||
return null; | ||
} | ||
const { method, body, retries } = args; | ||
const controller = new AbortController(); | ||
const handle = setTimeout(() => controller.abort(`Timeout of ${this._timeout}ms expired.`), this._timeout); | ||
const controller = typeof AbortController !== 'undefined' ? new AbortController() : null; | ||
const handle = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(`Timeout of ${this._timeout}ms expired.`), this._timeout); | ||
const url = yield this._getPopulatedURL(args); | ||
@@ -80,7 +87,7 @@ let response = null; | ||
headers: Object.assign({}, args.headers), | ||
signal: controller.signal, | ||
signal: controller === null || controller === void 0 ? void 0 : controller.signal, | ||
priority: args.priority, | ||
keepalive, | ||
}; | ||
const func = (_e = (_d = (_c = this._options) === null || _c === void 0 ? void 0 : _c.networkConfig) === null || _d === void 0 ? void 0 : _d.networkOverrideFunc) !== null && _e !== void 0 ? _e : fetch; | ||
const func = (_c = (_b = this._netConfig) === null || _b === void 0 ? void 0 : _b.networkOverrideFunc) !== null && _c !== void 0 ? _c : fetch; | ||
response = yield func(url, config); | ||
@@ -105,3 +112,3 @@ clearTimeout(handle); | ||
if (!retries || retries <= 0) { | ||
(_f = this._emitter) === null || _f === void 0 ? void 0 : _f.call(this, { name: 'error', error }); | ||
(_d = this._emitter) === null || _d === void 0 ? void 0 : _d.call(this, { name: 'error', error }); | ||
Log_1.Log.error(`A networking error occured during ${method} request to ${url}.`, errorMessage, error); | ||
@@ -165,3 +172,3 @@ return null; | ||
function _getErrorMessage(controller, error) { | ||
if (controller.signal.aborted && | ||
if ((controller === null || controller === void 0 ? void 0 : controller.signal.aborted) && | ||
typeof controller.signal.reason === 'string') { | ||
@@ -178,1 +185,19 @@ return controller.signal.reason; | ||
} | ||
function _attemptToCompressBody(args, body) { | ||
var _a; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!args.isCompressable || | ||
typeof CompressionStream === 'undefined' || | ||
typeof TextEncoder === 'undefined' || | ||
(__STATSIG__ === null || __STATSIG__ === void 0 ? void 0 : __STATSIG__['no-compress']) != null) { | ||
return body; | ||
} | ||
const bytes = new TextEncoder().encode(body); | ||
const stream = new CompressionStream('gzip'); | ||
const writer = stream.writable.getWriter(); | ||
writer.write(bytes).catch(Log_1.Log.error); | ||
writer.close().catch(Log_1.Log.error); | ||
args.params = Object.assign(Object.assign({}, ((_a = args.params) !== null && _a !== void 0 ? _a : {})), { [NetworkConfig_1.NetworkParam.IsGzipped]: '1' }); | ||
return yield new Response(stream.readable).arrayBuffer(); | ||
}); | ||
} |
@@ -19,3 +19,2 @@ "use strict"; | ||
const SafeJs_1 = require("./SafeJs"); | ||
const StableID_1 = require("./StableID"); | ||
const StorageProvider_1 = require("./StorageProvider"); | ||
@@ -30,4 +29,6 @@ class StatsigClientBase { | ||
(options === null || options === void 0 ? void 0 : options.disableStorage) && StorageProvider_1.Storage._setDisabled(true); | ||
(options === null || options === void 0 ? void 0 : options.overrideStableID) && | ||
StableID_1.StableID.setOverride(options.overrideStableID, sdkKey); | ||
this._sdkKey = sdkKey; | ||
this._options = options !== null && options !== void 0 ? options : {}; | ||
this._overrideAdapter = (_a = options === null || options === void 0 ? void 0 : options.overrideAdapter) !== null && _a !== void 0 ? _a : null; | ||
this._logger = new EventLogger_1.EventLogger(sdkKey, emitter, network, options); | ||
this._errorBoundary = new ErrorBoundary_1.ErrorBoundary(sdkKey, options, emitter); | ||
@@ -37,6 +38,3 @@ this._errorBoundary.wrap(this); | ||
this._errorBoundary.wrap(adapter); | ||
this._sdkKey = sdkKey; | ||
this._options = options !== null && options !== void 0 ? options : {}; | ||
this._overrideAdapter = (_a = options === null || options === void 0 ? void 0 : options.overrideAdapter) !== null && _a !== void 0 ? _a : null; | ||
this._logger = new EventLogger_1.EventLogger(sdkKey, emitter, network, options); | ||
this._errorBoundary.wrap(this._logger); | ||
if ((0, SafeJs_1._isBrowserEnv)()) { | ||
@@ -43,0 +41,0 @@ const statsigGlobal = (0, __StatsigGlobal_1._getStatsigGlobal)(); |
@@ -9,2 +9,3 @@ import { NetworkPriority } from './NetworkConfig'; | ||
readonly receivedAt: number; | ||
readonly stableID: string | null; | ||
}; | ||
@@ -11,0 +12,0 @@ export type DataAdapterAsyncOptions = { |
@@ -1,2 +0,2 @@ | ||
export declare const SDK_VERSION = "0.0.1-beta.41"; | ||
export declare const SDK_VERSION = "0.0.1-beta.42"; | ||
export type StatsigMetadata = { | ||
@@ -3,0 +3,0 @@ readonly [key: string]: string | undefined; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.StatsigMetadataProvider = exports.SDK_VERSION = void 0; | ||
exports.SDK_VERSION = '0.0.1-beta.41'; | ||
exports.SDK_VERSION = '0.0.1-beta.42'; | ||
let metadata = { | ||
@@ -6,0 +6,0 @@ sdkVersion: exports.SDK_VERSION, |
@@ -30,8 +30,2 @@ import { LogLevel } from './Log'; | ||
/** | ||
* The URL used to flush queued events via {@link window.navigator.sendBeacon} (web only). Takes precedence over {@link StatsigOptionsCommon.api}. | ||
* | ||
* default: `https://featuregates.org/v1/initialize` | ||
*/ | ||
logEventBeaconUrl?: string; | ||
/** | ||
* The maximum amount of time (in milliseconds) that any network request can take | ||
@@ -74,6 +68,2 @@ * before timing out. | ||
/** | ||
* Overrides the auto-generated StableID that is set for the device. | ||
*/ | ||
overrideStableID?: string; | ||
/** | ||
* How much information is allowed to be printed to the console. | ||
@@ -80,0 +70,0 @@ * |
@@ -5,3 +5,6 @@ import type { StatsigEnvironment } from './StatsigOptionsCommon'; | ||
userID?: string; | ||
customIDs?: Record<string, string>; | ||
customIDs?: { | ||
[key: string]: string | undefined; | ||
stableID?: string; | ||
}; | ||
email?: string; | ||
@@ -8,0 +11,0 @@ ip?: string; |
@@ -11,3 +11,2 @@ "use strict"; | ||
}; | ||
var _a; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -21,21 +20,7 @@ exports._setObjectInStorage = exports._getObjectFromStorage = exports.Storage = void 0; | ||
_getProviderName: () => 'InMemory', | ||
_getItemSync(key) { | ||
var _a; | ||
return (_a = inMemoryStore[key]) !== null && _a !== void 0 ? _a : null; | ||
}, | ||
_getItem(key) { | ||
var _a; | ||
return _resolve((_a = inMemoryStore[key]) !== null && _a !== void 0 ? _a : null); | ||
}, | ||
_setItem(key, value) { | ||
inMemoryStore[key] = value; | ||
return _resolve(); | ||
}, | ||
_removeItem(key) { | ||
delete inMemoryStore[key]; | ||
return _resolve(); | ||
}, | ||
_getAllKeys() { | ||
return _resolve(Object.keys(inMemoryStore)); | ||
}, | ||
_getItemSync: (key) => inMemoryStore[key] ? inMemoryStore[key] : null, | ||
_getItem: (key) => _resolve(inMemoryStore[key] ? inMemoryStore[key] : null), | ||
_setItem: (key, value) => ((inMemoryStore[key] = value), _resolve()), | ||
_removeItem: (key) => (delete inMemoryStore[key], _resolve()), | ||
_getAllKeys: () => _resolve(Object.keys(inMemoryStore)), | ||
}; | ||
@@ -45,23 +30,12 @@ let _localStorageProvider = null; | ||
const win = (0, SafeJs_1._getWindowSafe)(); | ||
if (typeof ((_a = win === null || win === void 0 ? void 0 : win.localStorage) === null || _a === void 0 ? void 0 : _a.getItem) === 'function') { | ||
if (win && | ||
win.localStorage && | ||
typeof win.localStorage.getItem === 'function') { | ||
_localStorageProvider = { | ||
_getProviderName: () => 'LocalStorage', | ||
_getItemSync(key) { | ||
return win.localStorage.getItem(key); | ||
}, | ||
_getItem(key) { | ||
return _resolve(win.localStorage.getItem(key)); | ||
}, | ||
_setItem(key, value) { | ||
win.localStorage.setItem(key, value); | ||
return _resolve(); | ||
}, | ||
_removeItem(key) { | ||
win.localStorage.removeItem(key); | ||
return _resolve(); | ||
}, | ||
_getAllKeys() { | ||
const keys = Object.keys(win.localStorage); | ||
return _resolve(keys); | ||
}, | ||
_getItemSync: (key) => win.localStorage.getItem(key), | ||
_getItem: (key) => _resolve(win.localStorage.getItem(key)), | ||
_setItem: (key, value) => (win.localStorage.setItem(key, value), _resolve()), | ||
_removeItem: (key) => (win.localStorage.removeItem(key), _resolve()), | ||
_getAllKeys: () => _resolve(Object.keys(win.localStorage)), | ||
}; | ||
@@ -90,3 +64,3 @@ } | ||
_getItem: (key) => __awaiter(void 0, void 0, void 0, function* () { return _inMemoryBreaker(() => _current._getItem(key)); }), | ||
_getItemSync: (key) => _inMemoryBreaker(() => { var _a, _b; return (_b = (_a = _current._getItemSync) === null || _a === void 0 ? void 0 : _a.call(_current, key)) !== null && _b !== void 0 ? _b : null; }), | ||
_getItemSync: (key) => _inMemoryBreaker(() => _current._getItemSync ? _current._getItemSync(key) : null), | ||
_setItem: (key, value) => _current._setItem(key, value), | ||
@@ -93,0 +67,0 @@ _removeItem: (key) => _current._removeItem(key), |
@@ -8,2 +8,2 @@ /** | ||
*/ | ||
export declare function typedJsonParse<T>(data: string, guard: string, error: string): T | null; | ||
export declare function _typedJsonParse<T>(data: string, guard: string, typeName: string): T | null; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.typedJsonParse = void 0; | ||
exports._typedJsonParse = void 0; | ||
const Log_1 = require("./Log"); | ||
@@ -12,3 +12,3 @@ /** | ||
*/ | ||
function typedJsonParse(data, guard, error) { | ||
function _typedJsonParse(data, guard, typeName) { | ||
try { | ||
@@ -25,5 +25,5 @@ const result = JSON.parse(data); | ||
} | ||
Log_1.Log.error(error); | ||
Log_1.Log.error(`Failed to parse ${typeName}`); | ||
return null; | ||
} | ||
exports.typedJsonParse = typedJsonParse; | ||
exports._typedJsonParse = _typedJsonParse; |
114714
2679