@amplitude/analytics-core 2.15.0 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/lib/cjs/core-client.d.ts.map +1 -1
  2. package/lib/cjs/core-client.js +1 -0
  3. package/lib/cjs/core-client.js.map +1 -1
  4. package/lib/cjs/remote-config/remote-config.d.ts +1 -1
  5. package/lib/cjs/remote-config/remote-config.d.ts.map +1 -1
  6. package/lib/cjs/remote-config/remote-config.js +7 -18
  7. package/lib/cjs/remote-config/remote-config.js.map +1 -1
  8. package/lib/cjs/timeline.d.ts +2 -0
  9. package/lib/cjs/timeline.d.ts.map +1 -1
  10. package/lib/cjs/timeline.js +10 -2
  11. package/lib/cjs/timeline.js.map +1 -1
  12. package/lib/cjs/types/frustration-interactions.d.ts +4 -4
  13. package/lib/cjs/types/frustration-interactions.d.ts.map +1 -1
  14. package/lib/cjs/types/frustration-interactions.js +4 -4
  15. package/lib/cjs/types/frustration-interactions.js.map +1 -1
  16. package/lib/esm/core-client.d.ts.map +1 -1
  17. package/lib/esm/core-client.js +1 -0
  18. package/lib/esm/core-client.js.map +1 -1
  19. package/lib/esm/remote-config/remote-config.d.ts +1 -1
  20. package/lib/esm/remote-config/remote-config.d.ts.map +1 -1
  21. package/lib/esm/remote-config/remote-config.js +6 -17
  22. package/lib/esm/remote-config/remote-config.js.map +1 -1
  23. package/lib/esm/timeline.d.ts +2 -0
  24. package/lib/esm/timeline.d.ts.map +1 -1
  25. package/lib/esm/timeline.js +10 -2
  26. package/lib/esm/timeline.js.map +1 -1
  27. package/lib/esm/types/frustration-interactions.d.ts +4 -4
  28. package/lib/esm/types/frustration-interactions.d.ts.map +1 -1
  29. package/lib/esm/types/frustration-interactions.js +4 -4
  30. package/lib/esm/types/frustration-interactions.js.map +1 -1
  31. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"core-client.d.ts","sourceRoot":"","sources":["../../src/core-client.ts"],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a,CAAC,UAAU,EAAE,MAAM;IAIhC,oBAAoB,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI;IAOtE,QAAQ,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC;IAU7C;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,iCAAiC,CAAC,cAAc,EAAE,cAAc,GAAG,SAAS,GAAG;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE;IAsD/F,OAAO,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC;IA8B5C,SAAS,CAAC,MAAM,EAAE,OAAO;IAQzB,UAAU,CAAC,MAAM,EAAE,OAAO;IAO1B,KAAK;IAIL,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAUxC,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,WAAW,EAAE;QAAE,KAAK,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;KAAE,GAAG,CAAC,EAAE;CAGzE"}
@@ -27,6 +27,7 @@ var AmplitudeCore = /** @class */ (function () {
27
27
  case 0:
28
28
  this.config = config;
29
29
  this.timeline.reset(this);
30
+ this.timeline.loggerProvider = this.config.loggerProvider;
30
31
  return [4 /*yield*/, this.runQueuedFunctions('q')];
31
32
  case 1:
32
33
  _a.sent();
@@ -1 +1 @@
1
- {"version":3,"file":"core-client.js","sourceRoot":"","sources":["../../src/core-client.ts"],"names":[],"mappings":";;;;AAIA,6CAM6B;AAC7B,uCAAkE;AAElE,6CAA2E;AAC3E,uCAAsC;AACtC,uDAM+B;AAC/B,yDAAqD;AACrD,yDAAwE;AAmKxE;IAaE,uBAAY,IAAiB;QAAjB,qBAAA,EAAA,iBAAiB;QAZnB,iBAAY,GAAG,KAAK,CAAC;QAQ/B,YAAO,GAAG,KAAK,CAAC;QACN,MAA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M,CAAC,cAAc,CAAC,KAAK,CAAC,uCAAgC,IAAI,CAAE,CAAC,CAAC;YACzE,OAAO,SAAS,CAAC;SAClB;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,+BAAO,GAAP,UAA0B,WAAwC;QAChE,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,UAAC,MAAM,IAAK,OAAA,MAAM,YAAY,WAAW,EAA7B,CAA6B,CAAQ,CAAC;IACxF,CAAC;IACH,oBAAC;AAAD,CAAC,AA9PD,IA8PC;AA9PY,sCAAa","sourcesContent":["import { Plugin } from './types/plugin';\nimport { IConfig } from './config';\nimport { BaseEvent, EventOptions } from './types/event/base-event';\nimport { Result } from './types/result';\nimport {\n Event,\n IdentifyOperation,\n IdentifyUserProperties,\n SpecialEventType,\n UserProperties,\n} from './types/event/event';\nimport { IIdentify, OrderedIdentifyOperations } from './identify';\nimport { IRevenue } from './revenue';\nimport { CLIENT_NOT_INITIALIZED, OPT_OUT_MESSAGE } from './types/messages';\nimport { Timeline } from './timeline';\nimport {\n createGroupEvent,\n createGroupIdentifyEvent,\n createIdentifyEvent,\n createRevenueEvent,\n createTrackEvent,\n} from './utils/event-builder';\nimport { buildResult } from './utils/result-builder';\nimport { AmplitudeReturn, returnWrapper } from './utils/return-wrapper';\n\ninterface PluginHost {\n plugin(name: string): Plugin | undefined;\n plugins<T extends Plugin>(pluginClass: new (...args: any[]) => T): T[];\n}\n\nexport interface CoreClient {\n /**\n * Adds a new plugin.\n *\n * ```typescript\n * const plugin = {\n * name: 'myPlugin',\n * type: 'enrichment',\n * setup(config: Config) {\n * return;\n * },\n * execute(context: Event) {\n * return context;\n * },\n * };\n * amplitude.add(plugin);\n * ```\n */\n add(plugin: Plugin): AmplitudeReturn<void>;\n\n /**\n * Removes a plugin.\n *\n * ```typescript\n * amplitude.remove('myPlugin');\n * ```\n */\n remove(pluginName: string): AmplitudeReturn<void>;\n\n /**\n * Tracks user-defined event, with specified type, optional event properties and optional overwrites.\n *\n * ```typescript\n * // event tracking with event type only\n * track('Page Load');\n *\n * // event tracking with event type and additional event properties\n * track('Page Load', { loadTime: 1000 });\n *\n * // event tracking with event type, additional event properties, and overwritten event options\n * track('Page Load', { loadTime: 1000 }, { sessionId: -1 });\n *\n * // alternatively, this tracking method is awaitable\n * const result = await track('Page Load').promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n track(\n eventInput: BaseEvent | string,\n eventProperties?: Record<string, any>,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Alias for track()\n */\n logEvent(\n eventInput: BaseEvent | string,\n eventProperties?: Record<string, any>,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Sends an identify event containing user property operations\n *\n * ```typescript\n * const id = new Identify();\n * id.set('colors', ['rose', 'gold']);\n * identify(id);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await identify(id).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n identify(identify: IIdentify, eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sends a group identify event containing group property operations.\n *\n * ```typescript\n * const id = new Identify();\n * id.set('skills', ['js', 'ts']);\n * const groupType = 'org';\n * const groupName = 'engineering';\n * groupIdentify(groupType, groupName, id);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await groupIdentify(groupType, groupName, id).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n groupIdentify(\n groupType: string,\n groupName: string | string[],\n identify: IIdentify,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Assigns a user to group\n *\n * ```typescript\n * const groupType = 'orgId';\n * const groupName = '15';\n * setGroup(groupType, groupName, { user_id: '12345' })\n * ```\n */\n setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sends a revenue event containing revenue property operations.\n *\n * ```typescript\n * const rev = new Revenue();\n * rev.setRevenue(100);\n * revenue(rev);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await revenue(rev).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n revenue(revenue: IRevenue, eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sets a new optOut config value. This toggles event tracking on/off.\n *\n *```typescript\n * // Stops tracking\n * setOptOut(true);\n *\n * // Starts/resumes tracking\n * setOptOut(false);\n * ```\n */\n setOptOut(optOut: boolean): void;\n\n /**\n * Flush all unsent events.\n *\n *```typescript\n * flush();\n * ```\n */\n flush(): AmplitudeReturn<void>;\n}\n\nexport class AmplitudeCore implements CoreClient, PluginHost {\n protected initializing = false;\n protected name: string;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n config: IConfig;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n timeline: Timeline;\n isReady = false;\n protected q: Array<CallableFunction | typeof returnWrapper> = [];\n protected dispatchQ: Array<CallableFunction> = [];\n\n constructor(name = '$default') {\n this.timeline = new Timeline(this);\n this.name = name;\n }\n\n protected async _init(config: IConfig) {\n this.config = config;\n this.timeline.reset(this);\n await this.runQueuedFunctions('q');\n this.isReady = true;\n }\n\n async runQueuedFunctions(queueName: 'q' | 'dispatchQ') {\n const queuedFunctions = this[queueName];\n this[queueName] = [];\n for (const queuedFunction of queuedFunctions) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const val: ReturnType<typeof returnWrapper> | Promise<any> = queuedFunction();\n if (val && 'promise' in val) {\n await val.promise;\n } else {\n await val;\n }\n }\n // Rerun queued functions if the queue has accrued more while awaiting promises\n if (this[queueName].length) {\n await this.runQueuedFunctions(queueName);\n }\n }\n\n track(eventInput: BaseEvent | string, eventProperties?: Record<string, any>, eventOptions?: EventOptions) {\n const event = createTrackEvent(eventInput, eventProperties, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n logEvent = this.track.bind(this);\n\n identify(identify: IIdentify, eventOptions?: EventOptions) {\n const event = createIdentifyEvent(identify, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n groupIdentify(groupType: string, groupName: string | string[], identify: IIdentify, eventOptions?: EventOptions) {\n const event = createGroupIdentifyEvent(groupType, groupName, identify, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions) {\n const event = createGroupEvent(groupType, groupName, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n revenue(revenue: IRevenue, eventOptions?: EventOptions) {\n const event = createRevenueEvent(revenue, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n add(plugin: Plugin) {\n if (!this.isReady) {\n this.q.push(this._addPlugin.bind(this, plugin));\n return returnWrapper();\n }\n return this._addPlugin(plugin);\n }\n\n _addPlugin(plugin: Plugin) {\n return returnWrapper(this.timeline.register(plugin, this.config));\n }\n\n remove(pluginName: string) {\n if (!this.isReady) {\n this.q.push(this._removePlugin.bind(this, pluginName));\n return returnWrapper();\n }\n return this._removePlugin(pluginName);\n }\n\n _removePlugin(pluginName: string) {\n return returnWrapper(this.timeline.deregister(pluginName, this.config));\n }\n\n dispatchWithCallback(event: Event, callback: (result: Result) => void): void {\n if (!this.isReady) {\n return callback(buildResult(event, 0, CLIENT_NOT_INITIALIZED));\n }\n void this.process(event).then(callback);\n }\n\n async dispatch(event: Event): Promise<Result> {\n if (!this.isReady) {\n return new Promise<Result>((resolve) => {\n this.dispatchQ.push(this.dispatchWithCallback.bind(this, event, resolve));\n });\n }\n\n return this.process(event);\n }\n\n /**\n *\n * This method applies identify operations to user properties and\n * returns a single object representing the final user property state.\n *\n * This is a best-effort api that only supports $set, $clearAll, and $unset.\n * Other operations are not supported and are ignored.\n *\n *\n * @param userProperties The `event.userProperties` object from an Identify event.\n * @returns A key-value object user properties without operations.\n *\n * @example\n * Input:\n * {\n * $set: { plan: 'premium' },\n * custom_flag: true\n * }\n *\n * Output:\n * {\n * plan: 'premium',\n * custom_flag: true\n * }\n */\n getOperationAppliedUserProperties(userProperties: UserProperties | undefined): { [key: string]: any } {\n const updatedProperties: { [key: string]: any } = {};\n\n if (userProperties === undefined) {\n return updatedProperties;\n }\n\n // Keep non-operation keys for later merge\n const nonOpProperties: {\n [key in Exclude<string, IdentifyOperation>]: any;\n } = {};\n Object.keys(userProperties).forEach((key) => {\n if (!Object.values(IdentifyOperation).includes(key as IdentifyOperation)) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n nonOpProperties[key] = userProperties[key];\n }\n });\n\n OrderedIdentifyOperations.forEach((operation) => {\n // Skip when key is an operation.\n if (!Object.keys(userProperties).includes(operation)) return;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const opProperties: IdentifyUserProperties = userProperties[operation];\n\n switch (operation) {\n case IdentifyOperation.CLEAR_ALL:\n // Due to operation order, the following line will never execute.\n /* istanbul ignore next */\n Object.keys(updatedProperties).forEach((prop) => {\n delete updatedProperties[prop];\n });\n break;\n case IdentifyOperation.UNSET:\n Object.keys(opProperties).forEach((prop) => {\n delete updatedProperties[prop];\n });\n break;\n case IdentifyOperation.SET:\n Object.assign(updatedProperties, opProperties);\n break;\n }\n });\n\n // Merge non-operation properties.\n // Custom properties should not be affected by operations.\n // https://github.com/amplitude/nova/blob/343f678ded83c032e83b189796b3c2be161b48f5/src/main/java/com/amplitude/userproperty/model/ModifyUserPropertiesIdent.java#L79-L83\n Object.assign(updatedProperties, nonOpProperties);\n\n return updatedProperties;\n }\n\n async process(event: Event): Promise<Result> {\n try {\n // skip event processing if opt out\n if (this.config.optOut) {\n return buildResult(event, 0, OPT_OUT_MESSAGE);\n }\n\n if (event.event_type === SpecialEventType.IDENTIFY) {\n const userProperties = this.getOperationAppliedUserProperties(event.user_properties);\n this.timeline.onIdentityChanged({ userProperties: userProperties });\n }\n\n const result = await this.timeline.push(event);\n\n result.code === 200\n ? this.config.loggerProvider.log(result.message)\n : result.code === 100\n ? this.config.loggerProvider.warn(result.message)\n : this.config.loggerProvider.error(result.message);\n\n return result;\n } catch (e) {\n const message = String(e);\n this.config.loggerProvider.error(message);\n const result = buildResult(event, 0, message);\n\n return result;\n }\n }\n\n setOptOut(optOut: boolean) {\n if (!this.isReady) {\n this.q.push(this._setOptOut.bind(this, Boolean(optOut)));\n return;\n }\n this._setOptOut(optOut);\n }\n\n _setOptOut(optOut: boolean) {\n if (this.config.optOut !== optOut) {\n this.timeline.onOptOutChanged(optOut);\n this.config.optOut = Boolean(optOut);\n }\n }\n\n flush() {\n return returnWrapper(this.timeline.flush());\n }\n\n plugin(name: string): Plugin | undefined {\n const plugin = this.timeline.plugins.find((plugin) => plugin.name === name);\n if (plugin === undefined) {\n this.config.loggerProvider.debug(`Cannot find plugin with name ${name}`);\n return undefined;\n }\n\n return plugin;\n }\n\n plugins<T extends Plugin>(pluginClass: { new (...args: any[]): T }): T[] {\n return this.timeline.plugins.filter((plugin) => plugin instanceof pluginClass) as T[];\n }\n}\n"]}
1
+ {"version":3,"file":"core-client.js","sourceRoot":"","sources":["../../src/core-client.ts"],"names":[],"mappings":";;;;AAIA,6CAM6B;AAC7B,uCAAkE;AAElE,6CAA2E;AAC3E,uCAAsC;AACtC,uDAM+B;AAC/B,yDAAqD;AACrD,yDAAwE;AAmKxE;IAaE,uBAAY,IAAiB;QAAjB,qBAAA,EAAA,iBAAiB;QAZnB,iBAAY,GAAG,KAAK,CAAC;QAQ/B,YAAO,GAAG,KAAK,CAAC;QACN,MAAC,GAAmD,EAAE,CAAC;QACvD,cAAS,GAA4B,EAAE,CAAC;QAwClD,aAAQ,GAAG,IAAI,CAAC,KAAK,CA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c,CAAC,KAAK,CAAC,uCAAgC,IAAI,CAAE,CAAC,CAAC;YACzE,OAAO,SAAS,CAAC;SAClB;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,+BAAO,GAAP,UAA0B,WAAwC;QAChE,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,UAAC,MAAM,IAAK,OAAA,MAAM,YAAY,WAAW,EAA7B,CAA6B,CAAQ,CAAC;IACxF,CAAC;IACH,oBAAC;AAAD,CAAC,AA/PD,IA+PC;AA/PY,sCAAa","sourcesContent":["import { Plugin } from './types/plugin';\nimport { IConfig } from './config';\nimport { BaseEvent, EventOptions } from './types/event/base-event';\nimport { Result } from './types/result';\nimport {\n Event,\n IdentifyOperation,\n IdentifyUserProperties,\n SpecialEventType,\n UserProperties,\n} from './types/event/event';\nimport { IIdentify, OrderedIdentifyOperations } from './identify';\nimport { IRevenue } from './revenue';\nimport { CLIENT_NOT_INITIALIZED, OPT_OUT_MESSAGE } from './types/messages';\nimport { Timeline } from './timeline';\nimport {\n createGroupEvent,\n createGroupIdentifyEvent,\n createIdentifyEvent,\n createRevenueEvent,\n createTrackEvent,\n} from './utils/event-builder';\nimport { buildResult } from './utils/result-builder';\nimport { AmplitudeReturn, returnWrapper } from './utils/return-wrapper';\n\ninterface PluginHost {\n plugin(name: string): Plugin | undefined;\n plugins<T extends Plugin>(pluginClass: new (...args: any[]) => T): T[];\n}\n\nexport interface CoreClient {\n /**\n * Adds a new plugin.\n *\n * ```typescript\n * const plugin = {\n * name: 'myPlugin',\n * type: 'enrichment',\n * setup(config: Config) {\n * return;\n * },\n * execute(context: Event) {\n * return context;\n * },\n * };\n * amplitude.add(plugin);\n * ```\n */\n add(plugin: Plugin): AmplitudeReturn<void>;\n\n /**\n * Removes a plugin.\n *\n * ```typescript\n * amplitude.remove('myPlugin');\n * ```\n */\n remove(pluginName: string): AmplitudeReturn<void>;\n\n /**\n * Tracks user-defined event, with specified type, optional event properties and optional overwrites.\n *\n * ```typescript\n * // event tracking with event type only\n * track('Page Load');\n *\n * // event tracking with event type and additional event properties\n * track('Page Load', { loadTime: 1000 });\n *\n * // event tracking with event type, additional event properties, and overwritten event options\n * track('Page Load', { loadTime: 1000 }, { sessionId: -1 });\n *\n * // alternatively, this tracking method is awaitable\n * const result = await track('Page Load').promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n track(\n eventInput: BaseEvent | string,\n eventProperties?: Record<string, any>,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Alias for track()\n */\n logEvent(\n eventInput: BaseEvent | string,\n eventProperties?: Record<string, any>,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Sends an identify event containing user property operations\n *\n * ```typescript\n * const id = new Identify();\n * id.set('colors', ['rose', 'gold']);\n * identify(id);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await identify(id).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n identify(identify: IIdentify, eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sends a group identify event containing group property operations.\n *\n * ```typescript\n * const id = new Identify();\n * id.set('skills', ['js', 'ts']);\n * const groupType = 'org';\n * const groupName = 'engineering';\n * groupIdentify(groupType, groupName, id);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await groupIdentify(groupType, groupName, id).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n groupIdentify(\n groupType: string,\n groupName: string | string[],\n identify: IIdentify,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Assigns a user to group\n *\n * ```typescript\n * const groupType = 'orgId';\n * const groupName = '15';\n * setGroup(groupType, groupName, { user_id: '12345' })\n * ```\n */\n setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sends a revenue event containing revenue property operations.\n *\n * ```typescript\n * const rev = new Revenue();\n * rev.setRevenue(100);\n * revenue(rev);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await revenue(rev).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n revenue(revenue: IRevenue, eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sets a new optOut config value. This toggles event tracking on/off.\n *\n *```typescript\n * // Stops tracking\n * setOptOut(true);\n *\n * // Starts/resumes tracking\n * setOptOut(false);\n * ```\n */\n setOptOut(optOut: boolean): void;\n\n /**\n * Flush all unsent events.\n *\n *```typescript\n * flush();\n * ```\n */\n flush(): AmplitudeReturn<void>;\n}\n\nexport class AmplitudeCore implements CoreClient, PluginHost {\n protected initializing = false;\n protected name: string;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n config: IConfig;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n timeline: Timeline;\n isReady = false;\n protected q: Array<CallableFunction | typeof returnWrapper> = [];\n protected dispatchQ: Array<CallableFunction> = [];\n\n constructor(name = '$default') {\n this.timeline = new Timeline(this);\n this.name = name;\n }\n\n protected async _init(config: IConfig) {\n this.config = config;\n this.timeline.reset(this);\n this.timeline.loggerProvider = this.config.loggerProvider;\n await this.runQueuedFunctions('q');\n this.isReady = true;\n }\n\n async runQueuedFunctions(queueName: 'q' | 'dispatchQ') {\n const queuedFunctions = this[queueName];\n this[queueName] = [];\n for (const queuedFunction of queuedFunctions) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const val: ReturnType<typeof returnWrapper> | Promise<any> = queuedFunction();\n if (val && 'promise' in val) {\n await val.promise;\n } else {\n await val;\n }\n }\n // Rerun queued functions if the queue has accrued more while awaiting promises\n if (this[queueName].length) {\n await this.runQueuedFunctions(queueName);\n }\n }\n\n track(eventInput: BaseEvent | string, eventProperties?: Record<string, any>, eventOptions?: EventOptions) {\n const event = createTrackEvent(eventInput, eventProperties, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n logEvent = this.track.bind(this);\n\n identify(identify: IIdentify, eventOptions?: EventOptions) {\n const event = createIdentifyEvent(identify, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n groupIdentify(groupType: string, groupName: string | string[], identify: IIdentify, eventOptions?: EventOptions) {\n const event = createGroupIdentifyEvent(groupType, groupName, identify, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions) {\n const event = createGroupEvent(groupType, groupName, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n revenue(revenue: IRevenue, eventOptions?: EventOptions) {\n const event = createRevenueEvent(revenue, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n add(plugin: Plugin) {\n if (!this.isReady) {\n this.q.push(this._addPlugin.bind(this, plugin));\n return returnWrapper();\n }\n return this._addPlugin(plugin);\n }\n\n _addPlugin(plugin: Plugin) {\n return returnWrapper(this.timeline.register(plugin, this.config));\n }\n\n remove(pluginName: string) {\n if (!this.isReady) {\n this.q.push(this._removePlugin.bind(this, pluginName));\n return returnWrapper();\n }\n return this._removePlugin(pluginName);\n }\n\n _removePlugin(pluginName: string) {\n return returnWrapper(this.timeline.deregister(pluginName, this.config));\n }\n\n dispatchWithCallback(event: Event, callback: (result: Result) => void): void {\n if (!this.isReady) {\n return callback(buildResult(event, 0, CLIENT_NOT_INITIALIZED));\n }\n void this.process(event).then(callback);\n }\n\n async dispatch(event: Event): Promise<Result> {\n if (!this.isReady) {\n return new Promise<Result>((resolve) => {\n this.dispatchQ.push(this.dispatchWithCallback.bind(this, event, resolve));\n });\n }\n\n return this.process(event);\n }\n\n /**\n *\n * This method applies identify operations to user properties and\n * returns a single object representing the final user property state.\n *\n * This is a best-effort api that only supports $set, $clearAll, and $unset.\n * Other operations are not supported and are ignored.\n *\n *\n * @param userProperties The `event.userProperties` object from an Identify event.\n * @returns A key-value object user properties without operations.\n *\n * @example\n * Input:\n * {\n * $set: { plan: 'premium' },\n * custom_flag: true\n * }\n *\n * Output:\n * {\n * plan: 'premium',\n * custom_flag: true\n * }\n */\n getOperationAppliedUserProperties(userProperties: UserProperties | undefined): { [key: string]: any } {\n const updatedProperties: { [key: string]: any } = {};\n\n if (userProperties === undefined) {\n return updatedProperties;\n }\n\n // Keep non-operation keys for later merge\n const nonOpProperties: {\n [key in Exclude<string, IdentifyOperation>]: any;\n } = {};\n Object.keys(userProperties).forEach((key) => {\n if (!Object.values(IdentifyOperation).includes(key as IdentifyOperation)) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n nonOpProperties[key] = userProperties[key];\n }\n });\n\n OrderedIdentifyOperations.forEach((operation) => {\n // Skip when key is an operation.\n if (!Object.keys(userProperties).includes(operation)) return;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const opProperties: IdentifyUserProperties = userProperties[operation];\n\n switch (operation) {\n case IdentifyOperation.CLEAR_ALL:\n // Due to operation order, the following line will never execute.\n /* istanbul ignore next */\n Object.keys(updatedProperties).forEach((prop) => {\n delete updatedProperties[prop];\n });\n break;\n case IdentifyOperation.UNSET:\n Object.keys(opProperties).forEach((prop) => {\n delete updatedProperties[prop];\n });\n break;\n case IdentifyOperation.SET:\n Object.assign(updatedProperties, opProperties);\n break;\n }\n });\n\n // Merge non-operation properties.\n // Custom properties should not be affected by operations.\n // https://github.com/amplitude/nova/blob/343f678ded83c032e83b189796b3c2be161b48f5/src/main/java/com/amplitude/userproperty/model/ModifyUserPropertiesIdent.java#L79-L83\n Object.assign(updatedProperties, nonOpProperties);\n\n return updatedProperties;\n }\n\n async process(event: Event): Promise<Result> {\n try {\n // skip event processing if opt out\n if (this.config.optOut) {\n return buildResult(event, 0, OPT_OUT_MESSAGE);\n }\n\n if (event.event_type === SpecialEventType.IDENTIFY) {\n const userProperties = this.getOperationAppliedUserProperties(event.user_properties);\n this.timeline.onIdentityChanged({ userProperties: userProperties });\n }\n\n const result = await this.timeline.push(event);\n\n result.code === 200\n ? this.config.loggerProvider.log(result.message)\n : result.code === 100\n ? this.config.loggerProvider.warn(result.message)\n : this.config.loggerProvider.error(result.message);\n\n return result;\n } catch (e) {\n const message = String(e);\n this.config.loggerProvider.error(message);\n const result = buildResult(event, 0, message);\n\n return result;\n }\n }\n\n setOptOut(optOut: boolean) {\n if (!this.isReady) {\n this.q.push(this._setOptOut.bind(this, Boolean(optOut)));\n return;\n }\n this._setOptOut(optOut);\n }\n\n _setOptOut(optOut: boolean) {\n if (this.config.optOut !== optOut) {\n this.timeline.onOptOutChanged(optOut);\n this.config.optOut = Boolean(optOut);\n }\n }\n\n flush() {\n return returnWrapper(this.timeline.flush());\n }\n\n plugin(name: string): Plugin | undefined {\n const plugin = this.timeline.plugins.find((plugin) => plugin.name === name);\n if (plugin === undefined) {\n this.config.loggerProvider.debug(`Cannot find plugin with name ${name}`);\n return undefined;\n }\n\n return plugin;\n }\n\n plugins<T extends Plugin>(pluginClass: { new (...args: any[]): T }): T[] {\n return this.timeline.plugins.filter((plugin) => plugin instanceof pluginClass) as T[];\n }\n}\n"]}
@@ -18,7 +18,6 @@ export type Source = 'cache' | 'remote';
18
18
  export declare const US_SERVER_URL = "https://sr-client-cfg.amplitude.com/config";
19
19
  export declare const EU_SERVER_URL = "https://sr-client-cfg.eu.amplitude.com/config";
20
20
  export declare const DEFAULT_MAX_RETRIES = 3;
21
- export declare const FETCHED_KEYS: string[];
22
21
  export interface RemoteConfig {
23
22
  [key: string]: any;
24
23
  }
@@ -80,6 +79,7 @@ export interface IRemoteConfigClient {
80
79
  updateConfigs(): void;
81
80
  }
82
81
  export declare class RemoteConfigClient implements IRemoteConfigClient {
82
+ static readonly CONFIG_GROUP = "browser";
83
83
  readonly apiKey: string;
84
84
  readonly serverUrl: string;
85
85
  readonly logger: ILogger;
@@ -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;;;;;GAKG;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;AASrC,eAAO,MAAM,YAAY,UAOxB,CAAC;AAEF,MAAM,WAAW,YAAY;IAC3B,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,MAAM,WAAW,gBAAgB;IAC/B,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;IAElC,SAAS,EAAE,IAAI,CAAC;CACjB;AAED,MAAM,WAAW,mBAAmB;IAClC;;OAEG;IACH,WAAW,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAEzC;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACvD;AAED;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,YAAY,CAAC;IAC3B,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,YAAY,CAAC,EAAE,IAAI,CAAC;CACrB;AAED;;;GAGG;AACH,KAAK,oBAAoB,GAAG,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,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G,MAAM;IAIzC,YAAY,IAAI,MAAM;CASvB"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RemoteConfigClient = exports.FETCHED_KEYS = exports.DEFAULT_MAX_RETRIES = exports.EU_SERVER_URL = exports.US_SERVER_URL = void 0;
3
+ exports.RemoteConfigClient = exports.DEFAULT_MAX_RETRIES = exports.EU_SERVER_URL = exports.US_SERVER_URL = void 0;
4
4
  var tslib_1 = require("tslib");
5
5
  var remote_config_localstorage_1 = require("./remote-config-localstorage");
6
6
  var uuid_1 = require("../utils/uuid");
@@ -12,16 +12,6 @@ exports.DEFAULT_MAX_RETRIES = 3;
12
12
  * Linear backoff policy: timeout / retry times is the interval between fetch retry.
13
13
  */
14
14
  var DEFAULT_TIMEOUT = 1000;
15
- // TODO(xinyi)
16
- // const DEFAULT_MIN_TIME_BETWEEN_FETCHES = 5 * 60 * 1000; // 5 minutes
17
- exports.FETCHED_KEYS = [
18
- 'analyticsSDK.browserSDK',
19
- 'sessionReplay.sr_interaction_config',
20
- 'sessionReplay.sr_logging_config',
21
- 'sessionReplay.sr_privacy_config',
22
- 'sessionReplay.sr_sampling_config',
23
- 'sessionReplay.sr_targeting_config',
24
- ];
25
15
  var RemoteConfigClient = /** @class */ (function () {
26
16
  function RemoteConfigClient(apiKey, logger, serverZone) {
27
17
  if (serverZone === void 0) { serverZone = 'US'; }
@@ -250,14 +240,13 @@ var RemoteConfigClient = /** @class */ (function () {
250
240
  return Math.floor(Math.random() * baseDelay);
251
241
  };
252
242
  RemoteConfigClient.prototype.getUrlParams = function () {
253
- var urlParams = new URLSearchParams({
254
- api_key: this.apiKey,
255
- });
256
- exports.FETCHED_KEYS.forEach(function (key) {
257
- urlParams.append('config_keys', key);
258
- });
259
- return "".concat(this.serverUrl, "?").concat(urlParams.toString());
243
+ // URL encode the API key to handle special characters
244
+ var encodedApiKey = encodeURIComponent(this.apiKey);
245
+ var urlParams = new URLSearchParams();
246
+ urlParams.append('config_group', RemoteConfigClient.CONFIG_GROUP);
247
+ return "".concat(this.serverUrl, "/").concat(encodedApiKey, "?").concat(urlParams.toString());
260
248
  };
249
+ RemoteConfigClient.CONFIG_GROUP = 'browser';
261
250
  return RemoteConfigClient;
262
251
  }());
263
252
  exports.RemoteConfigClient = RemoteConfigClient;
@@ -1 +1 @@
1
- {"version":3,"file":"remote-config.js","sourceRoot":"","sources":["../../../src/remote-config/remote-config.ts"],"names":[],"mappings":";;;;AAEA,2EAAwE;AACxE,sCAAqC;AAiBxB,QAAA,aAAa,GAAG,4CAA4C,CAAC;AAC7D,QAAA,aAAa,GAAG,+CAA+C,CAAC;AAChE,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;GAGG;AACH,IAAM,eAAe,GAAG,IAAI,CAAC;AAC7B,cAAc;AACd,uEAAuE;AAC1D,QAAA,YAAY,GAAG;IAC1B,yBAAyB;IACzB,qCAAqC;IACrC,iCAAiC;IACjC,iCAAiC;IACjC,kCAAkC;IAClC,mCAAmC;CACpC,CAAC;AAwEF;IAQE,4BAAY,MAAc,EAAE,MAAe,EAAE,UAAiC;QAAjC,2BAAA,EAAA,iBAAiC;QAH9E,2CAA2C;QAC3C,kBAAa,GAAmB,EAAE,CAAC;QAGjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,qBAAa,CAAC,CAAC,CAAC,qBAAa,CAAC;QACrE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,IAAI,qDAAwB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9D,CAAC;IAED,sCAAS,GAAT,UAAU,GAAuB,EAAE,YAA0B,EAAE,QAA8B;QAC3F,IAAM,EAAE,GAAG,IAAA,WAAI,GAAE,CAAC;QAClB,IAAM,YAAY,GAAG;YACnB,EAAE,EAAE,EAAE;YACN,GAA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AE,OAAK,CAAC,CAAC;;;6BAMtG,CAAA,OAAO,GAAG,OAAO,GAAG,CAAC,CAAA,EAArB,yBAAqB;wBACvB,qBAAM,IAAI,OAAO,CAAC,UAAC,OAAO,IAAK,OAAA,UAAU,CAAC,OAAO,EAAE,KAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC,EAAlD,CAAkD,CAAC,EAAA;;wBAAlF,SAAkF,CAAC;;;wBA9B9C,OAAO,EAAE,CAAA;;6BAkClD,sBAAO,sBAAsB,EAAC;;;;KAC/B;IAED;;OAEG;IACH,2CAAc,GAAd,UAAe,SAAiB;QAC9B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IAC/C,CAAC;IAED,yCAAY,GAAZ;QACE,IAAM,SAAS,GAAG,IAAI,eAAe,CAAC;YACpC,OAAO,EAAE,IAAI,CAAC,MAAM;SACrB,CAAC,CAAC;QACH,oBAAY,CAAC,OAAO,CAAC,UAAC,GAAG;YACvB,SAAS,CAAC,MAAM,CAAC,aAAa,EAAE,GAAG,CAAC,CAAC;QACvC,CAAC,CAAC,CAAC;QAEH,OAAO,UAAG,IAAI,CAAC,SAAS,cAAI,SAAS,CAAC,QAAQ,EAAE,CAAE,CAAC;IACrD,CAAC;IACH,yBAAC;AAAD,CAAC,AAxMD,IAwMC;AAxMY,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'` – Receive all config updates as they occur.\n * - `{ timeout: number }` – Wait for a remote response until the specified timeout (in milliseconds),\n * then return a cached copy if available.\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;\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// TODO(xinyi)\n// const DEFAULT_MIN_TIME_BETWEEN_FETCHES = 5 * 60 * 1000; // 5 minutes\nexport const FETCHED_KEYS = [\n 'analyticsSDK.browserSDK',\n 'sessionReplay.sr_interaction_config',\n 'sessionReplay.sr_logging_config',\n 'sessionReplay.sr_privacy_config',\n 'sessionReplay.sr_sampling_config',\n 'sessionReplay.sr_targeting_config',\n];\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 readonly apiKey: string;\n readonly serverUrl: string;\n readonly logger: ILogger;\n readonly storage: RemoteConfigStorage;\n // Registered callbackInfos by subscribe().\n callbackInfos: CallbackInfo[] = [];\n\n constructor(apiKey: string, logger: ILogger, serverZone: ServerZoneType = 'US') {\n this.apiKey = apiKey;\n this.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 const result = await this.fetch();\n void this.storage.setConfig(result);\n this.callbackInfos.forEach((callbackInfo) => {\n this.sendCallback(callbackInfo, result, 'remote');\n });\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.fetch().then((result) => {\n this.logger.debug('Remote config client subscription all mode fetched from remote.');\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.');\n this.sendCallback(callbackInfo, result, 'cache');\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([this.fetch(), timeoutPromise])) 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 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 try {\n const res = await fetch(this.getUrlParams(), {\n method: 'GET',\n headers: {\n Accept: '*/*',\n },\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 } 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\n this.logger.debug(`Remote config client fetch with retry time ${retries} is rejected because: `, error);\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 const urlParams = new URLSearchParams({\n api_key: this.apiKey,\n });\n FETCHED_KEYS.forEach((key) => {\n urlParams.append('config_keys', key);\n });\n\n return `${this.serverUrl}?${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;AAiBxB,QAAA,aAAa,GAAG,4CAA4C,CAAC;AAC7D,QAAA,aAAa,GAAG,+CAA+C,CAAC;AAChE,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;GAGG;AACH,IAAM,eAAe,GAAG,IAAI,CAAC;AA0E7B;IAUE,4BAAY,MAAc,EAAE,MAAe,EAAE,UAAiC;QAAjC,2BAAA,EAAA,iBAAiC;QAH9E,2CAA2C;QAC3C,kBAAa,GAAmB,EAAE,CAAC;QAGjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,qBAAa,CAAC,CAAC,CAAC,qBAAa,CAAC;QACrE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,IAAI,qDAAwB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9D,CAAC;IAED,sCAAS,GAAT,UAAU,GAAuB,EAAE,YAA0B,EAAE,QAA8B;QAC3F,IAAM,EAAE,GAAG,IAAA,WAAI,GAAE,CAAC;QAClB,IAAM,YAAY,GAAG;YACnB,EAAE,EAAE,EAAE;YACN,GAAG,EAAE,GAAG;YACR,YAAY,EAAE,YAAY;YAC1B,QAAQ,EAAE,QAAQ;SACnB,CAAC;QACF,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QAEtC,IAAI,YAAY,KAAK,KAAK,EAAE;YAC1B,KAAK,IAAI,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;SACtC;aAAM;YACL,KAAK,IAAI,CAAC,sBAAsB,CAAC,YAAY,EAAE,YAAY,CAAC,OAAO,CAAC,CAAC;SACtE;QAED,OAAO,E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;;OAEG;IACH,2CAAc,GAAd,UAAe,SAAiB;QAC9B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IAC/C,CAAC;IAED,yCAAY,GAAZ;QACE,sDAAsD;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;IAvMe,+BAAY,GAAG,SAAS,CAAC;IAwM3C,yBAAC;CAAA,AAzMD,IAyMC;AAzMY,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'` – Receive all config updates as they occur.\n * - `{ timeout: number }` – Wait for a remote response until the specified timeout (in milliseconds),\n * then return a cached copy if available.\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;\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// TODO(xinyi)\n// const 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\n constructor(apiKey: string, logger: ILogger, serverZone: ServerZoneType = 'US') {\n this.apiKey = apiKey;\n this.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 const result = await this.fetch();\n void this.storage.setConfig(result);\n this.callbackInfos.forEach((callbackInfo) => {\n this.sendCallback(callbackInfo, result, 'remote');\n });\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.fetch().then((result) => {\n this.logger.debug('Remote config client subscription all mode fetched from remote.');\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.');\n this.sendCallback(callbackInfo, result, 'cache');\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([this.fetch(), timeoutPromise])) 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 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 try {\n const res = await fetch(this.getUrlParams(), {\n method: 'GET',\n headers: {\n Accept: '*/*',\n },\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 } 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\n this.logger.debug(`Remote config client fetch with retry time ${retries} is rejected because: `, error);\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,6 +1,7 @@
1
1
  import { AnalyticsIdentity, Plugin } from './types/plugin';
2
2
  import { CoreClient } from './core-client';
3
3
  import { IConfig } from './config';
4
+ import { ILogger } from './logger';
4
5
  import { EventCallback } from './types/event-callback';
5
6
  import { Event } from './types/event/event';
6
7
  import { Result } from './types/result';
@@ -9,6 +10,7 @@ export declare class Timeline {
9
10
  queue: [Event, EventCallback][];
10
11
  applying: boolean;
11
12
  plugins: Plugin[];
13
+ loggerProvider: ILogger;
12
14
  constructor(client: CoreClient);
13
15
  register(plugin: Plugin, config: IConfig): Promise<void>;
14
16
  deregister(pluginName: string, config: IConfig): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"timeline.d.ts","sourceRoot":"","sources":["../../src/timeline.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAqD,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC9G,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAIxC,qBAAa,QAAQ;IAQP,OAAO,CAAC,MAAM;IAP1B,KAAK,EAAE,CAAC,KAAK,EAAE,aAAa,CAAC,EAAE,CAAM;IAErC,QAAQ,UAAS;IAGjB,OAAO,EAAE,MAAM,EAAE,CAAM;gBAEH,MAAM,EAAE,UAAU;IAEhC,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IAmBxC,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IAWpD,KAAK,CAAC,MAAM,EAAE,UAAU;IAQxB,IAAI,CAAC,KAAK,EAAE,KAAK;IAOjB,aAAa,CAAC,OAAO,EAAE,MAAM;IAavB,KAAK,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,aAAa,CAAC,GAAG,SAAS;IAgE9C,KAAK;IAiBX,iBAAiB,CAAC,QAAQ,EAAE,iBAAiB;IAU7C,kBAAkB,CAAC,SAAS,EAAE,MAAM;IAUpC,eAAe,CAAC,MAAM,EAAE,OAAO;CAShC"}
1
+ {"version":3,"file":"timeline.d.ts","sourceRoot":"","sources":["../../src/timeline.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAqD,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC9G,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAIxC,qBAAa,QAAQ;IAYP,OAAO,CAAC,MAAM;IAX1B,KAAK,EAAE,CAAC,KAAK,EAAE,aAAa,CAAC,EAAE,CAAM;IAErC,QAAQ,UAAS;IAGjB,OAAO,EAAE,MAAM,EAAE,CAAM;IAIvB,cAAc,EAAE,OAAO,CAAC;gBAEJ,MAAM,EAAE,UAAU;IAEhC,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IAmBxC,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IAWpD,KAAK,CAAC,MAAM,EAAE,UAAU;IAQxB,IAAI,CAAC,KAAK,EAAE,KAAK;IAOjB,aAAa,CAAC,OAAO,EAAE,MAAM;IAavB,KAAK,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,aAAa,CAAC,GAAG,SAAS;IAsF9C,KAAK;IAiBX,iBAAiB,CAAC,QAAQ,EAAE,iBAAiB;IAU7C,kBAAkB,CAAC,SAAS,EAAE,MAAM;IAUpC,eAAe,CAAC,MAAM,EAAE,OAAO;CAShC"}
@@ -22,12 +22,12 @@ var Timeline = /** @class */ (function () {
22
22
  case 0:
23
23
  if (this.plugins.some(function (existingPlugin) { return existingPlugin.name === plugin.name; })) {
24
24
  // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
25
- config.loggerProvider.warn("Plugin with name ".concat(plugin.name, " already exists, skipping registration"));
25
+ this.loggerProvider.warn("Plugin with name ".concat(plugin.name, " already exists, skipping registration"));
26
26
  return [2 /*return*/];
27
27
  }
28
28
  if (plugin.name === undefined) {
29
29
  plugin.name = (0, uuid_1.UUID)();
30
- config.loggerProvider.warn("Plugin name is undefined. \n Generating a random UUID for plugin name: ".concat(plugin.name, ". \n Set a name for the plugin to prevent it from being added multiple times."));
30
+ this.loggerProvider.warn("Plugin name is undefined. \n Generating a random UUID for plugin name: ".concat(plugin.name, ". \n Set a name for the plugin to prevent it from being added multiple times."));
31
31
  }
32
32
  plugin.type = (_a = plugin.type) !== null && _a !== void 0 ? _a : 'enrichment';
33
33
  return [4 /*yield*/, ((_b = plugin.setup) === null || _b === void 0 ? void 0 : _b.call(plugin, config, this.client))];
@@ -101,6 +101,8 @@ var Timeline = /** @class */ (function () {
101
101
  }
102
102
  _a = tslib_1.__read(item, 1), event = _a[0];
103
103
  _b = tslib_1.__read(item, 2), resolve = _b[1];
104
+ // Log initial event
105
+ this.loggerProvider.log('Timeline.apply: Initial event', event);
104
106
  before = this.plugins.filter(function (plugin) { return plugin.type === 'before'; });
105
107
  _e.label = 1;
106
108
  case 1:
@@ -119,11 +121,13 @@ var Timeline = /** @class */ (function () {
119
121
  case 3:
120
122
  e = _e.sent();
121
123
  if (e === null) {
124
+ this.loggerProvider.log("Timeline.apply: Event filtered out by before plugin '".concat(String(plugin.name), "', event: ").concat(JSON.stringify(event)));
122
125
  resolve({ event: event, code: 0, message: '' });
123
126
  return [2 /*return*/];
124
127
  }
125
128
  else {
126
129
  event = e;
130
+ this.loggerProvider.log("Timeline.apply: Event after before plugin '".concat(String(plugin.name), "', event: ").concat(JSON.stringify(event)));
127
131
  }
128
132
  _e.label = 4;
129
133
  case 4:
@@ -159,11 +163,13 @@ var Timeline = /** @class */ (function () {
159
163
  case 11:
160
164
  e = _e.sent();
161
165
  if (e === null) {
166
+ this.loggerProvider.log("Timeline.apply: Event filtered out by enrichment plugin '".concat(String(plugin.name), "', event: ").concat(JSON.stringify(event)));
162
167
  resolve({ event: event, code: 0, message: '' });
163
168
  return [2 /*return*/];
164
169
  }
165
170
  else {
166
171
  event = e;
172
+ this.loggerProvider.log("Timeline.apply: Event after enrichment plugin '".concat(String(plugin.name), "', event: ").concat(JSON.stringify(event)));
167
173
  }
168
174
  _e.label = 12;
169
175
  case 12:
@@ -182,6 +188,8 @@ var Timeline = /** @class */ (function () {
182
188
  return [7 /*endfinally*/];
183
189
  case 16:
184
190
  destination = this.plugins.filter(function (plugin) { return plugin.type === 'destination'; });
191
+ // Log final event before sending to destinations
192
+ this.loggerProvider.log("Timeline.apply: Final event before destinations, event: ".concat(JSON.stringify(event)));
185
193
  executeDestinations = destination.map(function (plugin) {
186
194
  var eventClone = tslib_1.__assign({}, event);
187
195
  return plugin.execute(eventClone).catch(function (e) { return (0, result_builder_1.buildResult)(eventClone, 0, String(e)); });
@@ -1 +1 @@
1
- {"version":3,"file":"timeline.js","sourceRoot":"","sources":["../../src/timeline.ts"],"names":[],"mappings":";;;;AAMA,yDAAqD;AACrD,qCAAoC;AAEpC;IAQE,kBAAoB,MAAkB;QAAlB,WAAM,GAAN,MAAM,CAAY;QAPtC,UAAK,GAA6B,EAAE,CAAC;QACrC,kDAAkD;QAClD,aAAQ,GAAG,KAAK,CAAC;QACjB,4DAA4D;QAC5D,yFAAyF;QACzF,YAAO,GAAa,EAAE,CAAC;IAEkB,CAAC;IAEpC,2BAAQ,GAAd,UAAe,MAAc,EAAE,MAAe;;;;;;wBAC5C,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,UAAC,cAAc,IAAK,OAAA,cAAc,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,EAAnC,CAAmC,CAAC,EAAE;4BAC9E,4EAA4E;4BAC5E,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,2BAAoB,MAAM,CAAC,IAAI,2CAAwC,CAAC,CAAC;4BACpG,sBAAO;yBACR;wBAED,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,EAAE;4BAC7B,MAAM,CAAC,IAAI,GAAG,IAAA,WAAI,GAAE,CAAC;4BACrB,MAAM,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,UAAC,MAAM;;YAC1B,0EAA0E;YAC1E,wDAAwD;YACxD,0DAA0D;YAC1D,0BAA0B;YAC1B,KAAK,CAAA,MAAA,MAAM,CAAC,iBAAiB,uDAAG,QAAQ,CAAC,CAAA,CAAC;QAC5C,CAAC,CAAC,CAAC;IACL,CAAC;IAED,qCAAkB,GAAlB,UAAmB,SAAiB;QAClC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;;YAC1B,2EAA2E;YAC3E,wDAAwD;YACxD,0DAA0D;YAC1D,0BAA0B;YAC1B,KAAK,CAAA,MAAA,MAAM,CAAC,kBAAkB,uDAAG,SAAS,CAAC,CAAA,CAAC;QAC9C,CAAC,CAAC,CAAC;IACL,CAAC;IAED,kCAAe,GAAf,UAAgB,MAAe;QAC7B,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;;YAC1B,wEAAwE;YACxE,wDAAwD;YACxD,0DAA0D;YAC1D,0BAA0B;YAC1B,KAAK,CAAA,MAAA,MAAM,CAAC,eAAe,uDAAG,MAAM,CAAC,CAAA,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC;IACH,eAAC;AAAD,CAAC,AAlLD,IAkLC;AAlLY,4BAAQ","sourcesContent":["import { AnalyticsIdentity, BeforePlugin, DestinationPlugin, EnrichmentPlugin, Plugin } from './types/plugin';\nimport { CoreClient } from './core-client';\nimport { IConfig } from './config';\nimport { EventCallback } from './types/event-callback';\nimport { Event } from './types/event/event';\nimport { Result } from './types/result';\nimport { buildResult } from './utils/result-builder';\nimport { UUID } from './utils/uuid';\n\nexport class Timeline {\n queue: [Event, EventCallback][] = [];\n // Flag to guarantee one schedule apply is running\n applying = false;\n // Flag indicates whether timeline is ready to process event\n // Events collected before timeline is ready will stay in the queue to be processed later\n plugins: Plugin[] = [];\n\n constructor(private client: CoreClient) {}\n\n async register(plugin: Plugin, config: IConfig) {\n if (this.plugins.some((existingPlugin) => existingPlugin.name === plugin.name)) {\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n config.loggerProvider.warn(`Plugin with name ${plugin.name} already exists, skipping registration`);\n return;\n }\n\n if (plugin.name === undefined) {\n plugin.name = UUID();\n config.loggerProvider.warn(`Plugin name is undefined. \n Generating a random UUID for plugin name: ${plugin.name}. \n Set a name for the plugin to prevent it from being added multiple times.`);\n }\n\n plugin.type = plugin.type ?? 'enrichment';\n await plugin.setup?.(config, this.client);\n this.plugins.push(plugin);\n }\n\n async deregister(pluginName: string, config: IConfig) {\n const index = this.plugins.findIndex((plugin) => plugin.name === pluginName);\n if (index === -1) {\n config.loggerProvider.warn(`Plugin with name ${pluginName} does not exist, skipping deregistration`);\n return;\n }\n const plugin = this.plugins[index];\n this.plugins.splice(index, 1);\n await plugin.teardown?.();\n }\n\n reset(client: CoreClient) {\n this.applying = false;\n const plugins = this.plugins;\n plugins.map((plugin) => plugin.teardown?.());\n this.plugins = [];\n this.client = client;\n }\n\n push(event: Event) {\n return new Promise<Result>((resolve) => {\n this.queue.push([event, resolve]);\n this.scheduleApply(0);\n });\n }\n\n scheduleApply(timeout: number) {\n if (this.applying) return;\n this.applying = true;\n setTimeout(() => {\n void this.apply(this.queue.shift()).then(() => {\n this.applying = false;\n if (this.queue.length > 0) {\n this.scheduleApply(0);\n }\n });\n }, timeout);\n }\n\n async apply(item: [Event, EventCallback] | undefined) {\n if (!item) {\n return;\n }\n\n let [event] = item;\n const [, resolve] = item;\n\n const before = this.plugins.filter<BeforePlugin>(\n (plugin: Plugin): plugin is BeforePlugin => plugin.type === 'before',\n );\n\n for (const plugin of before) {\n /* istanbul ignore if */\n if (!plugin.execute) {\n // do nothing\n continue;\n }\n const e = await plugin.execute({ ...event });\n if (e === null) {\n resolve({ event, code: 0, message: '' });\n return;\n } else {\n event = e;\n }\n }\n\n const enrichment = this.plugins.filter<EnrichmentPlugin>(\n (plugin: Plugin): plugin is EnrichmentPlugin => plugin.type === 'enrichment' || plugin.type === undefined,\n );\n\n for (const plugin of enrichment) {\n /* istanbul ignore if */\n if (!plugin.execute) {\n // do nothing\n continue;\n }\n const e = await plugin.execute({ ...event });\n if (e === null) {\n resolve({ event, code: 0, message: '' });\n return;\n } else {\n event = e;\n }\n }\n\n const destination = this.plugins.filter<DestinationPlugin>(\n (plugin: Plugin): plugin is DestinationPlugin => plugin.type === 'destination',\n );\n\n const executeDestinations = destination.map((plugin) => {\n const eventClone = { ...event };\n return plugin.execute(eventClone).catch((e) => buildResult(eventClone, 0, String(e)));\n });\n\n void Promise.all(executeDestinations).then(([result]) => {\n const resolveResult =\n result || buildResult(event, 100, 'Event not tracked, no destination plugins on the instance');\n resolve(resolveResult);\n });\n\n return;\n }\n\n async flush() {\n const queue = this.queue;\n this.queue = [];\n\n await Promise.all(queue.map((item) => this.apply(item)));\n\n const destination = this.plugins.filter<DestinationPlugin>(\n (plugin: Plugin): plugin is DestinationPlugin => plugin.type === 'destination',\n );\n\n const executeDestinations = destination.map((plugin) => {\n return plugin.flush && plugin.flush();\n });\n\n await Promise.all(executeDestinations);\n }\n\n onIdentityChanged(identity: AnalyticsIdentity) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onIdentityChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onIdentityChanged?.(identity);\n });\n }\n\n onSessionIdChanged(sessionId: number) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onSessionIdChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onSessionIdChanged?.(sessionId);\n });\n }\n\n onOptOutChanged(optOut: boolean) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onOptOutChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onOptOutChanged?.(optOut);\n });\n }\n}\n"]}
1
+ {"version":3,"file":"timeline.js","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AAG,WAAW,CAAC,GAAG,CAAC,UAAC,MAAM;4BACjD,OAAO,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;wBACxC,CAAC,CAAC,CAAC;wBAEH,qBAAM,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,EAAA;;wBAAtC,SAAsC,CAAC;;;;;KACxC;IAED,oCAAiB,GAAjB,UAAkB,QAA2B;QAC3C,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;;YAC1B,0EAA0E;YAC1E,wDAAwD;YACxD,0DAA0D;YAC1D,0BAA0B;YAC1B,KAAK,CAAA,MAAA,MAAM,CAAC,iBAAiB,uDAAG,QAAQ,CAAC,CAAA,CAAC;QAC5C,CAAC,CAAC,CAAC;IACL,CAAC;IAED,qCAAkB,GAAlB,UAAmB,SAAiB;QAClC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;;YAC1B,2EAA2E;YAC3E,wDAAwD;YACxD,0DAA0D;YAC1D,0BAA0B;YAC1B,KAAK,CAAA,MAAA,MAAM,CAAC,kBAAkB,uDAAG,SAAS,CAAC,CAAA,CAAC;QAC9C,CAAC,CAAC,CAAC;IACL,CAAC;IAED,kCAAe,GAAf,UAAgB,MAAe;QAC7B,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;;YAC1B,wEAAwE;YACxE,wDAAwD;YACxD,0DAA0D;YAC1D,0BAA0B;YAC1B,KAAK,CAAA,MAAA,MAAM,CAAC,eAAe,uDAAG,MAAM,CAAC,CAAA,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC;IACH,eAAC;AAAD,CAAC,AA5MD,IA4MC;AA5MY,4BAAQ","sourcesContent":["import { AnalyticsIdentity, BeforePlugin, DestinationPlugin, EnrichmentPlugin, Plugin } from './types/plugin';\nimport { CoreClient } from './core-client';\nimport { IConfig } from './config';\nimport { ILogger } from './logger';\nimport { EventCallback } from './types/event-callback';\nimport { Event } from './types/event/event';\nimport { Result } from './types/result';\nimport { buildResult } from './utils/result-builder';\nimport { UUID } from './utils/uuid';\n\nexport class Timeline {\n queue: [Event, EventCallback][] = [];\n // Flag to guarantee one schedule apply is running\n applying = false;\n // Flag indicates whether timeline is ready to process event\n // Events collected before timeline is ready will stay in the queue to be processed later\n plugins: Plugin[] = [];\n // loggerProvider is set by the client at _init()\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n loggerProvider: ILogger;\n\n constructor(private client: CoreClient) {}\n\n async register(plugin: Plugin, config: IConfig) {\n if (this.plugins.some((existingPlugin) => existingPlugin.name === plugin.name)) {\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n this.loggerProvider.warn(`Plugin with name ${plugin.name} already exists, skipping registration`);\n return;\n }\n\n if (plugin.name === undefined) {\n plugin.name = UUID();\n this.loggerProvider.warn(`Plugin name is undefined. \n Generating a random UUID for plugin name: ${plugin.name}. \n Set a name for the plugin to prevent it from being added multiple times.`);\n }\n\n plugin.type = plugin.type ?? 'enrichment';\n await plugin.setup?.(config, this.client);\n this.plugins.push(plugin);\n }\n\n async deregister(pluginName: string, config: IConfig) {\n const index = this.plugins.findIndex((plugin) => plugin.name === pluginName);\n if (index === -1) {\n config.loggerProvider.warn(`Plugin with name ${pluginName} does not exist, skipping deregistration`);\n return;\n }\n const plugin = this.plugins[index];\n this.plugins.splice(index, 1);\n await plugin.teardown?.();\n }\n\n reset(client: CoreClient) {\n this.applying = false;\n const plugins = this.plugins;\n plugins.map((plugin) => plugin.teardown?.());\n this.plugins = [];\n this.client = client;\n }\n\n push(event: Event) {\n return new Promise<Result>((resolve) => {\n this.queue.push([event, resolve]);\n this.scheduleApply(0);\n });\n }\n\n scheduleApply(timeout: number) {\n if (this.applying) return;\n this.applying = true;\n setTimeout(() => {\n void this.apply(this.queue.shift()).then(() => {\n this.applying = false;\n if (this.queue.length > 0) {\n this.scheduleApply(0);\n }\n });\n }, timeout);\n }\n\n async apply(item: [Event, EventCallback] | undefined) {\n if (!item) {\n return;\n }\n\n let [event] = item;\n const [, resolve] = item;\n\n // Log initial event\n this.loggerProvider.log('Timeline.apply: Initial event', event);\n\n const before = this.plugins.filter<BeforePlugin>(\n (plugin: Plugin): plugin is BeforePlugin => plugin.type === 'before',\n );\n\n for (const plugin of before) {\n /* istanbul ignore if */\n if (!plugin.execute) {\n // do nothing\n continue;\n }\n const e = await plugin.execute({ ...event });\n if (e === null) {\n this.loggerProvider.log(\n `Timeline.apply: Event filtered out by before plugin '${String(plugin.name)}', event: ${JSON.stringify(\n event,\n )}`,\n );\n resolve({ event, code: 0, message: '' });\n return;\n } else {\n event = e;\n this.loggerProvider.log(\n `Timeline.apply: Event after before plugin '${String(plugin.name)}', event: ${JSON.stringify(event)}`,\n );\n }\n }\n\n const enrichment = this.plugins.filter<EnrichmentPlugin>(\n (plugin: Plugin): plugin is EnrichmentPlugin => plugin.type === 'enrichment' || plugin.type === undefined,\n );\n\n for (const plugin of enrichment) {\n /* istanbul ignore if */\n if (!plugin.execute) {\n // do nothing\n continue;\n }\n const e = await plugin.execute({ ...event });\n if (e === null) {\n this.loggerProvider.log(\n `Timeline.apply: Event filtered out by enrichment plugin '${String(plugin.name)}', event: ${JSON.stringify(\n event,\n )}`,\n );\n resolve({ event, code: 0, message: '' });\n return;\n } else {\n event = e;\n this.loggerProvider.log(\n `Timeline.apply: Event after enrichment plugin '${String(plugin.name)}', event: ${JSON.stringify(event)}`,\n );\n }\n }\n\n const destination = this.plugins.filter<DestinationPlugin>(\n (plugin: Plugin): plugin is DestinationPlugin => plugin.type === 'destination',\n );\n\n // Log final event before sending to destinations\n this.loggerProvider.log(`Timeline.apply: Final event before destinations, event: ${JSON.stringify(event)}`);\n\n const executeDestinations = destination.map((plugin) => {\n const eventClone = { ...event };\n return plugin.execute(eventClone).catch((e) => buildResult(eventClone, 0, String(e)));\n });\n\n void Promise.all(executeDestinations).then(([result]) => {\n const resolveResult =\n result || buildResult(event, 100, 'Event not tracked, no destination plugins on the instance');\n resolve(resolveResult);\n });\n\n return;\n }\n\n async flush() {\n const queue = this.queue;\n this.queue = [];\n\n await Promise.all(queue.map((item) => this.apply(item)));\n\n const destination = this.plugins.filter<DestinationPlugin>(\n (plugin: Plugin): plugin is DestinationPlugin => plugin.type === 'destination',\n );\n\n const executeDestinations = destination.map((plugin) => {\n return plugin.flush && plugin.flush();\n });\n\n await Promise.all(executeDestinations);\n }\n\n onIdentityChanged(identity: AnalyticsIdentity) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onIdentityChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onIdentityChanged?.(identity);\n });\n }\n\n onSessionIdChanged(sessionId: number) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onSessionIdChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onSessionIdChanged?.(sessionId);\n });\n }\n\n onOptOutChanged(optOut: boolean) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onOptOutChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onOptOutChanged?.(optOut);\n });\n }\n}\n"]}
@@ -73,13 +73,13 @@ export declare const DEFAULT_RAGE_CLICK_ALLOWLIST: string[];
73
73
  */
74
74
  export declare const DEFAULT_DEAD_CLICK_WINDOW_MS = 3000;
75
75
  /**
76
- * Default time window for rage clicks (3 seconds)
76
+ * Default time window for rage clicks (1 second)
77
77
  */
78
- export declare const DEFAULT_RAGE_CLICK_WINDOW_MS = 3000;
78
+ export declare const DEFAULT_RAGE_CLICK_WINDOW_MS = 1000;
79
79
  /**
80
- * Default threshold for rage clicks (5 clicks)
80
+ * Default threshold for rage clicks (4 clicks)
81
81
  */
82
- export declare const DEFAULT_RAGE_CLICK_THRESHOLD = 5;
82
+ export declare const DEFAULT_RAGE_CLICK_THRESHOLD = 4;
83
83
  type DomElement = typeof globalThis extends {
84
84
  Element: new (...args: any) => infer T;
85
85
  } ? T : never;
@@ -1 +1 @@
1
- {"version":3,"file":"frustration-interactions.d.ts","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAE/D;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAED;;;GAGG;AACH,MAAM,WAAW,8BAA8B;IAC7C;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IAEvC;;;;;;;OAOG;IACH,wBAAwB,CAAC,EAAE,CAAC,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,KAAK,OAAO,CAAC;IAEpF;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;OAEG;IACH,oBAAoB,CAAC,EAAE;QACrB,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB,SAAS,CAAC,EAAE,SAAS,CAAC;KACvB,CAAC;IACF;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAE9B;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC/B;AAgBD;;GAEG;AACH,eAAO,MAAM,4BAA4B,UAOxC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,4BAA4B,UAAQ,CAAC;AAElD;;GAEG;AACH,eAAO,MAAM,4BAA4B,OAAQ,CAAC;AAElD;;GAEG;AACH,eAAO,MAAM,4BAA4B,OAAO,CAAC;AAEjD;;GAEG;AACH,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAK9C,KAAK,UAAU,GAAG,OAAO,UAAU,SAAS;IAC1C,OAAO,EAAE,KAAK,GAAG,IAAI,EAAE,GAAG,KAAK,MAAM,CAAC,CAAC;CACxC,GACG,CAAC,GACD,KAAK,CAAC"}
1
+ {"version":3,"file":"frustration-interactions.d.ts","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAE/D;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAED;;;GAGG;AACH,MAAM,WAAW,8BAA8B;IAC7C;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IAEvC;;;;;;;OAOG;IACH,wBAAwB,CAAC,EAAE,CAAC,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,KAAK,OAAO,CAAC;IAEpF;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;OAEG;IACH,oBAAoB,CAAC,EAAE;QACrB,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB,SAAS,CAAC,EAAE,SAAS,CAAC;KACvB,CAAC;IACF;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAE9B;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC/B;AAgBD;;GAEG;AACH,eAAO,MAAM,4BAA4B,UAOxC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,4BAA4B,UAAQ,CAAC;AAElD;;GAEG;AACH,eAAO,MAAM,4BAA4B,OAAQ,CAAC;AAElD;;GAEG;AACH,eAAO,MAAM,4BAA4B,OAAQ,CAAC;AAElD;;GAEG;AACH,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAK9C,KAAK,UAAU,GAAG,OAAO,UAAU,SAAS;IAC1C,OAAO,EAAE,KAAK,GAAG,IAAI,EAAE,GAAG,KAAK,MAAM,CAAC,CAAC;CACxC,GACG,CAAC,GACD,KAAK,CAAC"}
@@ -34,11 +34,11 @@ exports.DEFAULT_RAGE_CLICK_ALLOWLIST = ['*'];
34
34
  */
35
35
  exports.DEFAULT_DEAD_CLICK_WINDOW_MS = 3000;
36
36
  /**
37
- * Default time window for rage clicks (3 seconds)
37
+ * Default time window for rage clicks (1 second)
38
38
  */
39
- exports.DEFAULT_RAGE_CLICK_WINDOW_MS = 3000;
39
+ exports.DEFAULT_RAGE_CLICK_WINDOW_MS = 1000;
40
40
  /**
41
- * Default threshold for rage clicks (5 clicks)
41
+ * Default threshold for rage clicks (4 clicks)
42
42
  */
43
- exports.DEFAULT_RAGE_CLICK_THRESHOLD = 5;
43
+ exports.DEFAULT_RAGE_CLICK_THRESHOLD = 4;
44
44
  //# sourceMappingURL=frustration-interactions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"frustration-interactions.js","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":";;;;AAsEA,IAAM,2BAA2B,GAAG;IAClC,GAAG;IACH,QAAQ;IACR,iBAAiB;IACjB,eAAe;IACf,mBAAmB;IACnB,2BAA2B;IAC3B,wBAAwB;IACxB,iBAAiB;IACjB,cAAc;IACd,mBAAmB;IACnB,4BAA4B;CAC7B,CAAC;AAEF;;GAEG;AACU,QAAA,4BAA4B;IACvC,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,qBAAqB;IACrB,oBAAoB;kBACjB,2BAA2B,UAC9B;AAEF;;GAEG;AACU,QAAA,4BAA4B,GAAG,CAAC,GAAG,CAAC,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,IAAI,CAAC;AAEjD;;GAEG;AACU,QAAA,4BAA4B,GAAG,CAAC,CAAC","sourcesContent":["import { ActionType, Messenger } from './element-interactions';\n\n/**\n * Configuration options for dead clicks tracking\n */\nexport interface DeadClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for dead clicks.\n * A dead click is a click that doesn't result in any visible change or navigation.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for rage clicks tracking\n */\nexport interface RageClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for rage clicks.\n * A rage click is multiple rapid clicks on the same element within a 3s time window.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for frustration interactions tracking.\n * This includes dead clicks and rage clicks tracking.\n */\nexport interface FrustrationInteractionsOptions {\n /**\n * List of page URLs to allow auto tracking on.\n * When provided, only allow tracking on these URLs.\n * Both full URLs and regex are supported.\n */\n pageUrlAllowlist?: (string | RegExp)[];\n\n /**\n * Function to determine whether an event should be tracked.\n * When provided, this function overwrites all other allowlists and configurations.\n * If the function returns true, the event will be tracked.\n * If the function returns false, the event will not be tracked.\n * @param actionType - The type of action that triggered the event.\n * @param element - The [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that triggered the event.\n */\n shouldTrackEventResolver?: (actionType: ActionType, element: DomElement) => boolean;\n\n /**\n * Prefix for data attributes to allow auto collecting.\n * Default is 'data-amp-track-'.\n */\n dataAttributePrefix?: string;\n\n /**\n * Options for integrating visual tagging selector.\n */\n visualTaggingOptions?: {\n enabled?: boolean;\n messenger?: Messenger;\n };\n /**\n * Configuration for dead clicks tracking\n */\n deadClicks?: DeadClickOptions;\n\n /**\n * Configuration for rage clicks tracking\n */\n rageClicks?: RageClickOptions;\n}\n\nconst CLICKABLE_ELEMENT_SELECTORS = [\n 'a',\n 'button',\n '[role=\"button\"]',\n '[role=\"link\"]',\n '[role=\"menuitem\"]',\n '[role=\"menuitemcheckbox\"]',\n '[role=\"menuitemradio\"]',\n '[role=\"option\"]',\n '[role=\"tab\"]',\n '[role=\"treeitem\"]',\n '[contenteditable=\"true\" i]',\n];\n\n/**\n * Default CSS selectors for dead clicks tracking\n */\nexport const DEFAULT_DEAD_CLICK_ALLOWLIST = [\n 'input[type=\"button\"]',\n 'input[type=\"submit\"]',\n 'input[type=\"reset\"]',\n 'input[type=\"image\"]',\n 'input[type=\"file\"]',\n ...CLICKABLE_ELEMENT_SELECTORS,\n];\n\n/**\n * Default CSS selectors for rage clicks tracking\n */\nexport const DEFAULT_RAGE_CLICK_ALLOWLIST = ['*'];\n\n/**\n * Default time window for dead clicks (3 seconds)\n */\nexport const DEFAULT_DEAD_CLICK_WINDOW_MS = 3_000;\n\n/**\n * Default time window for rage clicks (3 seconds)\n */\nexport const DEFAULT_RAGE_CLICK_WINDOW_MS = 3000;\n\n/**\n * Default threshold for rage clicks (5 clicks)\n */\nexport const DEFAULT_RAGE_CLICK_THRESHOLD = 5;\n\n// DomElement is [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) if the dom library is included in tsconfig.json\n// and never if it is not included\n// eslint-disable-next-line no-restricted-globals\ntype DomElement = typeof globalThis extends {\n Element: new (...args: any) => infer T;\n}\n ? T\n : never;\n"]}
1
+ {"version":3,"file":"frustration-interactions.js","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":";;;;AAsEA,IAAM,2BAA2B,GAAG;IAClC,GAAG;IACH,QAAQ;IACR,iBAAiB;IACjB,eAAe;IACf,mBAAmB;IACnB,2BAA2B;IAC3B,wBAAwB;IACxB,iBAAiB;IACjB,cAAc;IACd,mBAAmB;IACnB,4BAA4B;CAC7B,CAAC;AAEF;;GAEG;AACU,QAAA,4BAA4B;IACvC,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,qBAAqB;IACrB,oBAAoB;kBACjB,2BAA2B,UAC9B;AAEF;;GAEG;AACU,QAAA,4BAA4B,GAAG,CAAC,GAAG,CAAC,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,CAAC,CAAC","sourcesContent":["import { ActionType, Messenger } from './element-interactions';\n\n/**\n * Configuration options for dead clicks tracking\n */\nexport interface DeadClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for dead clicks.\n * A dead click is a click that doesn't result in any visible change or navigation.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for rage clicks tracking\n */\nexport interface RageClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for rage clicks.\n * A rage click is multiple rapid clicks on the same element within a 3s time window.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for frustration interactions tracking.\n * This includes dead clicks and rage clicks tracking.\n */\nexport interface FrustrationInteractionsOptions {\n /**\n * List of page URLs to allow auto tracking on.\n * When provided, only allow tracking on these URLs.\n * Both full URLs and regex are supported.\n */\n pageUrlAllowlist?: (string | RegExp)[];\n\n /**\n * Function to determine whether an event should be tracked.\n * When provided, this function overwrites all other allowlists and configurations.\n * If the function returns true, the event will be tracked.\n * If the function returns false, the event will not be tracked.\n * @param actionType - The type of action that triggered the event.\n * @param element - The [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that triggered the event.\n */\n shouldTrackEventResolver?: (actionType: ActionType, element: DomElement) => boolean;\n\n /**\n * Prefix for data attributes to allow auto collecting.\n * Default is 'data-amp-track-'.\n */\n dataAttributePrefix?: string;\n\n /**\n * Options for integrating visual tagging selector.\n */\n visualTaggingOptions?: {\n enabled?: boolean;\n messenger?: Messenger;\n };\n /**\n * Configuration for dead clicks tracking\n */\n deadClicks?: DeadClickOptions;\n\n /**\n * Configuration for rage clicks tracking\n */\n rageClicks?: RageClickOptions;\n}\n\nconst CLICKABLE_ELEMENT_SELECTORS = [\n 'a',\n 'button',\n '[role=\"button\"]',\n '[role=\"link\"]',\n '[role=\"menuitem\"]',\n '[role=\"menuitemcheckbox\"]',\n '[role=\"menuitemradio\"]',\n '[role=\"option\"]',\n '[role=\"tab\"]',\n '[role=\"treeitem\"]',\n '[contenteditable=\"true\" i]',\n];\n\n/**\n * Default CSS selectors for dead clicks tracking\n */\nexport const DEFAULT_DEAD_CLICK_ALLOWLIST = [\n 'input[type=\"button\"]',\n 'input[type=\"submit\"]',\n 'input[type=\"reset\"]',\n 'input[type=\"image\"]',\n 'input[type=\"file\"]',\n ...CLICKABLE_ELEMENT_SELECTORS,\n];\n\n/**\n * Default CSS selectors for rage clicks tracking\n */\nexport const DEFAULT_RAGE_CLICK_ALLOWLIST = ['*'];\n\n/**\n * Default time window for dead clicks (3 seconds)\n */\nexport const DEFAULT_DEAD_CLICK_WINDOW_MS = 3_000;\n\n/**\n * Default time window for rage clicks (1 second)\n */\nexport const DEFAULT_RAGE_CLICK_WINDOW_MS = 1_000;\n\n/**\n * Default threshold for rage clicks (4 clicks)\n */\nexport const DEFAULT_RAGE_CLICK_THRESHOLD = 4;\n\n// DomElement is [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) if the dom library is included in tsconfig.json\n// and never if it is not included\n// eslint-disable-next-line no-restricted-globals\ntype DomElement = typeof globalThis extends {\n Element: new (...args: any) => infer T;\n}\n ? T\n : never;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"core-client.d.ts","sourceRoot":"","sources":["../../src/core-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EACL,KAAK,EAIL,cAAc,EACf,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,SAAS,EAA6B,MAAM,YAAY,CAAC;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GAAG,CAAA;KAAE;IAsD/F,OAAO,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC;IA8B5C,SAAS,CAAC,MAAM,EAAE,OAAO;IAQzB,UAAU,CAAC,MAAM,EAAE,OAAO;IAO1B,KAAK;IAIL,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAUxC,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,WAAW,EAAE;QAAE,KAAK,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;KAAE,GAAG,CAAC,EAAE;CAGzE"}
@@ -24,6 +24,7 @@ var AmplitudeCore = /** @class */ (function () {
24
24
  case 0:
25
25
  this.config = config;
26
26
  this.timeline.reset(this);
27
+ this.timeline.loggerProvider = this.config.loggerProvider;
27
28
  return [4 /*yield*/, this.runQueuedFunctions('q')];
28
29
  case 1:
29
30
  _a.sent();
@@ -1 +1 @@
1
- {"version":3,"file":"core-client.js","sourceRoot":"","sources":["../../src/core-client.ts"],"names":[],"mappings":";AAIA,OAAO,EAEL,iBAAiB,EAEjB,gBAAgB,GAEjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAa,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAElE,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EACL,gBAAgB,EAChB,wBAAwB,EACxB,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAmB,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAmKxE;IAaE,uBAAY,IAAiB;QAAjB,qBAAA,EAAA,iBAAiB;QAZnB,iBAAY,GAAG,KAAK,CAAC;QAQ/B,YAAO,GAAG,KAAK,CAAC;QAC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B,CAAC;IAED,+BAAO,GAAP,UAA0B,WAAwC;QAChE,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,UAAC,MAAM,IAAK,OAAA,MAAM,YAAY,WAAW,EAA7B,CAA6B,CAAQ,CAAC;IACxF,CAAC;IACH,oBAAC;AAAD,CAAC,AA9PD,IA8PC","sourcesContent":["import { Plugin } from './types/plugin';\nimport { IConfig } from './config';\nimport { BaseEvent, EventOptions } from './types/event/base-event';\nimport { Result } from './types/result';\nimport {\n Event,\n IdentifyOperation,\n IdentifyUserProperties,\n SpecialEventType,\n UserProperties,\n} from './types/event/event';\nimport { IIdentify, OrderedIdentifyOperations } from './identify';\nimport { IRevenue } from './revenue';\nimport { CLIENT_NOT_INITIALIZED, OPT_OUT_MESSAGE } from './types/messages';\nimport { Timeline } from './timeline';\nimport {\n createGroupEvent,\n createGroupIdentifyEvent,\n createIdentifyEvent,\n createRevenueEvent,\n createTrackEvent,\n} from './utils/event-builder';\nimport { buildResult } from './utils/result-builder';\nimport { AmplitudeReturn, returnWrapper } from './utils/return-wrapper';\n\ninterface PluginHost {\n plugin(name: string): Plugin | undefined;\n plugins<T extends Plugin>(pluginClass: new (...args: any[]) => T): T[];\n}\n\nexport interface CoreClient {\n /**\n * Adds a new plugin.\n *\n * ```typescript\n * const plugin = {\n * name: 'myPlugin',\n * type: 'enrichment',\n * setup(config: Config) {\n * return;\n * },\n * execute(context: Event) {\n * return context;\n * },\n * };\n * amplitude.add(plugin);\n * ```\n */\n add(plugin: Plugin): AmplitudeReturn<void>;\n\n /**\n * Removes a plugin.\n *\n * ```typescript\n * amplitude.remove('myPlugin');\n * ```\n */\n remove(pluginName: string): AmplitudeReturn<void>;\n\n /**\n * Tracks user-defined event, with specified type, optional event properties and optional overwrites.\n *\n * ```typescript\n * // event tracking with event type only\n * track('Page Load');\n *\n * // event tracking with event type and additional event properties\n * track('Page Load', { loadTime: 1000 });\n *\n * // event tracking with event type, additional event properties, and overwritten event options\n * track('Page Load', { loadTime: 1000 }, { sessionId: -1 });\n *\n * // alternatively, this tracking method is awaitable\n * const result = await track('Page Load').promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n track(\n eventInput: BaseEvent | string,\n eventProperties?: Record<string, any>,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Alias for track()\n */\n logEvent(\n eventInput: BaseEvent | string,\n eventProperties?: Record<string, any>,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Sends an identify event containing user property operations\n *\n * ```typescript\n * const id = new Identify();\n * id.set('colors', ['rose', 'gold']);\n * identify(id);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await identify(id).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n identify(identify: IIdentify, eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sends a group identify event containing group property operations.\n *\n * ```typescript\n * const id = new Identify();\n * id.set('skills', ['js', 'ts']);\n * const groupType = 'org';\n * const groupName = 'engineering';\n * groupIdentify(groupType, groupName, id);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await groupIdentify(groupType, groupName, id).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n groupIdentify(\n groupType: string,\n groupName: string | string[],\n identify: IIdentify,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Assigns a user to group\n *\n * ```typescript\n * const groupType = 'orgId';\n * const groupName = '15';\n * setGroup(groupType, groupName, { user_id: '12345' })\n * ```\n */\n setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sends a revenue event containing revenue property operations.\n *\n * ```typescript\n * const rev = new Revenue();\n * rev.setRevenue(100);\n * revenue(rev);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await revenue(rev).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n revenue(revenue: IRevenue, eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sets a new optOut config value. This toggles event tracking on/off.\n *\n *```typescript\n * // Stops tracking\n * setOptOut(true);\n *\n * // Starts/resumes tracking\n * setOptOut(false);\n * ```\n */\n setOptOut(optOut: boolean): void;\n\n /**\n * Flush all unsent events.\n *\n *```typescript\n * flush();\n * ```\n */\n flush(): AmplitudeReturn<void>;\n}\n\nexport class AmplitudeCore implements CoreClient, PluginHost {\n protected initializing = false;\n protected name: string;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n config: IConfig;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n timeline: Timeline;\n isReady = false;\n protected q: Array<CallableFunction | typeof returnWrapper> = [];\n protected dispatchQ: Array<CallableFunction> = [];\n\n constructor(name = '$default') {\n this.timeline = new Timeline(this);\n this.name = name;\n }\n\n protected async _init(config: IConfig) {\n this.config = config;\n this.timeline.reset(this);\n await this.runQueuedFunctions('q');\n this.isReady = true;\n }\n\n async runQueuedFunctions(queueName: 'q' | 'dispatchQ') {\n const queuedFunctions = this[queueName];\n this[queueName] = [];\n for (const queuedFunction of queuedFunctions) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const val: ReturnType<typeof returnWrapper> | Promise<any> = queuedFunction();\n if (val && 'promise' in val) {\n await val.promise;\n } else {\n await val;\n }\n }\n // Rerun queued functions if the queue has accrued more while awaiting promises\n if (this[queueName].length) {\n await this.runQueuedFunctions(queueName);\n }\n }\n\n track(eventInput: BaseEvent | string, eventProperties?: Record<string, any>, eventOptions?: EventOptions) {\n const event = createTrackEvent(eventInput, eventProperties, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n logEvent = this.track.bind(this);\n\n identify(identify: IIdentify, eventOptions?: EventOptions) {\n const event = createIdentifyEvent(identify, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n groupIdentify(groupType: string, groupName: string | string[], identify: IIdentify, eventOptions?: EventOptions) {\n const event = createGroupIdentifyEvent(groupType, groupName, identify, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions) {\n const event = createGroupEvent(groupType, groupName, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n revenue(revenue: IRevenue, eventOptions?: EventOptions) {\n const event = createRevenueEvent(revenue, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n add(plugin: Plugin) {\n if (!this.isReady) {\n this.q.push(this._addPlugin.bind(this, plugin));\n return returnWrapper();\n }\n return this._addPlugin(plugin);\n }\n\n _addPlugin(plugin: Plugin) {\n return returnWrapper(this.timeline.register(plugin, this.config));\n }\n\n remove(pluginName: string) {\n if (!this.isReady) {\n this.q.push(this._removePlugin.bind(this, pluginName));\n return returnWrapper();\n }\n return this._removePlugin(pluginName);\n }\n\n _removePlugin(pluginName: string) {\n return returnWrapper(this.timeline.deregister(pluginName, this.config));\n }\n\n dispatchWithCallback(event: Event, callback: (result: Result) => void): void {\n if (!this.isReady) {\n return callback(buildResult(event, 0, CLIENT_NOT_INITIALIZED));\n }\n void this.process(event).then(callback);\n }\n\n async dispatch(event: Event): Promise<Result> {\n if (!this.isReady) {\n return new Promise<Result>((resolve) => {\n this.dispatchQ.push(this.dispatchWithCallback.bind(this, event, resolve));\n });\n }\n\n return this.process(event);\n }\n\n /**\n *\n * This method applies identify operations to user properties and\n * returns a single object representing the final user property state.\n *\n * This is a best-effort api that only supports $set, $clearAll, and $unset.\n * Other operations are not supported and are ignored.\n *\n *\n * @param userProperties The `event.userProperties` object from an Identify event.\n * @returns A key-value object user properties without operations.\n *\n * @example\n * Input:\n * {\n * $set: { plan: 'premium' },\n * custom_flag: true\n * }\n *\n * Output:\n * {\n * plan: 'premium',\n * custom_flag: true\n * }\n */\n getOperationAppliedUserProperties(userProperties: UserProperties | undefined): { [key: string]: any } {\n const updatedProperties: { [key: string]: any } = {};\n\n if (userProperties === undefined) {\n return updatedProperties;\n }\n\n // Keep non-operation keys for later merge\n const nonOpProperties: {\n [key in Exclude<string, IdentifyOperation>]: any;\n } = {};\n Object.keys(userProperties).forEach((key) => {\n if (!Object.values(IdentifyOperation).includes(key as IdentifyOperation)) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n nonOpProperties[key] = userProperties[key];\n }\n });\n\n OrderedIdentifyOperations.forEach((operation) => {\n // Skip when key is an operation.\n if (!Object.keys(userProperties).includes(operation)) return;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const opProperties: IdentifyUserProperties = userProperties[operation];\n\n switch (operation) {\n case IdentifyOperation.CLEAR_ALL:\n // Due to operation order, the following line will never execute.\n /* istanbul ignore next */\n Object.keys(updatedProperties).forEach((prop) => {\n delete updatedProperties[prop];\n });\n break;\n case IdentifyOperation.UNSET:\n Object.keys(opProperties).forEach((prop) => {\n delete updatedProperties[prop];\n });\n break;\n case IdentifyOperation.SET:\n Object.assign(updatedProperties, opProperties);\n break;\n }\n });\n\n // Merge non-operation properties.\n // Custom properties should not be affected by operations.\n // https://github.com/amplitude/nova/blob/343f678ded83c032e83b189796b3c2be161b48f5/src/main/java/com/amplitude/userproperty/model/ModifyUserPropertiesIdent.java#L79-L83\n Object.assign(updatedProperties, nonOpProperties);\n\n return updatedProperties;\n }\n\n async process(event: Event): Promise<Result> {\n try {\n // skip event processing if opt out\n if (this.config.optOut) {\n return buildResult(event, 0, OPT_OUT_MESSAGE);\n }\n\n if (event.event_type === SpecialEventType.IDENTIFY) {\n const userProperties = this.getOperationAppliedUserProperties(event.user_properties);\n this.timeline.onIdentityChanged({ userProperties: userProperties });\n }\n\n const result = await this.timeline.push(event);\n\n result.code === 200\n ? this.config.loggerProvider.log(result.message)\n : result.code === 100\n ? this.config.loggerProvider.warn(result.message)\n : this.config.loggerProvider.error(result.message);\n\n return result;\n } catch (e) {\n const message = String(e);\n this.config.loggerProvider.error(message);\n const result = buildResult(event, 0, message);\n\n return result;\n }\n }\n\n setOptOut(optOut: boolean) {\n if (!this.isReady) {\n this.q.push(this._setOptOut.bind(this, Boolean(optOut)));\n return;\n }\n this._setOptOut(optOut);\n }\n\n _setOptOut(optOut: boolean) {\n if (this.config.optOut !== optOut) {\n this.timeline.onOptOutChanged(optOut);\n this.config.optOut = Boolean(optOut);\n }\n }\n\n flush() {\n return returnWrapper(this.timeline.flush());\n }\n\n plugin(name: string): Plugin | undefined {\n const plugin = this.timeline.plugins.find((plugin) => plugin.name === name);\n if (plugin === undefined) {\n this.config.loggerProvider.debug(`Cannot find plugin with name ${name}`);\n return undefined;\n }\n\n return plugin;\n }\n\n plugins<T extends Plugin>(pluginClass: { new (...args: any[]): T }): T[] {\n return this.timeline.plugins.filter((plugin) => plugin instanceof pluginClass) as T[];\n }\n}\n"]}
1
+ {"version":3,"file":"core-client.js","sourceRoot":"","sources":["../../src/core-client.ts"],"names":[],"mappings":";AAIA,OAAO,EAEL,iBAAiB,EAEjB,gBAAgB,GAEjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAa,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAElE,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EACL,gBAAgB,EAChB,wBAAwB,EACxB,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAmB,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAmKxE;IAaE,uBAA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,CAAC;QAC5E,IAAI,MAAM,KAAK,SAAS,EAAE;YACxB,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,uCAAgC,IAAI,CAAE,CAAC,CAAC;YACzE,OAAO,SAAS,CAAC;SAClB;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,+BAAO,GAAP,UAA0B,WAAwC;QAChE,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,UAAC,MAAM,IAAK,OAAA,MAAM,YAAY,WAAW,EAA7B,CAA6B,CAAQ,CAAC;IACxF,CAAC;IACH,oBAAC;AAAD,CAAC,AA/PD,IA+PC","sourcesContent":["import { Plugin } from './types/plugin';\nimport { IConfig } from './config';\nimport { BaseEvent, EventOptions } from './types/event/base-event';\nimport { Result } from './types/result';\nimport {\n Event,\n IdentifyOperation,\n IdentifyUserProperties,\n SpecialEventType,\n UserProperties,\n} from './types/event/event';\nimport { IIdentify, OrderedIdentifyOperations } from './identify';\nimport { IRevenue } from './revenue';\nimport { CLIENT_NOT_INITIALIZED, OPT_OUT_MESSAGE } from './types/messages';\nimport { Timeline } from './timeline';\nimport {\n createGroupEvent,\n createGroupIdentifyEvent,\n createIdentifyEvent,\n createRevenueEvent,\n createTrackEvent,\n} from './utils/event-builder';\nimport { buildResult } from './utils/result-builder';\nimport { AmplitudeReturn, returnWrapper } from './utils/return-wrapper';\n\ninterface PluginHost {\n plugin(name: string): Plugin | undefined;\n plugins<T extends Plugin>(pluginClass: new (...args: any[]) => T): T[];\n}\n\nexport interface CoreClient {\n /**\n * Adds a new plugin.\n *\n * ```typescript\n * const plugin = {\n * name: 'myPlugin',\n * type: 'enrichment',\n * setup(config: Config) {\n * return;\n * },\n * execute(context: Event) {\n * return context;\n * },\n * };\n * amplitude.add(plugin);\n * ```\n */\n add(plugin: Plugin): AmplitudeReturn<void>;\n\n /**\n * Removes a plugin.\n *\n * ```typescript\n * amplitude.remove('myPlugin');\n * ```\n */\n remove(pluginName: string): AmplitudeReturn<void>;\n\n /**\n * Tracks user-defined event, with specified type, optional event properties and optional overwrites.\n *\n * ```typescript\n * // event tracking with event type only\n * track('Page Load');\n *\n * // event tracking with event type and additional event properties\n * track('Page Load', { loadTime: 1000 });\n *\n * // event tracking with event type, additional event properties, and overwritten event options\n * track('Page Load', { loadTime: 1000 }, { sessionId: -1 });\n *\n * // alternatively, this tracking method is awaitable\n * const result = await track('Page Load').promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n track(\n eventInput: BaseEvent | string,\n eventProperties?: Record<string, any>,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Alias for track()\n */\n logEvent(\n eventInput: BaseEvent | string,\n eventProperties?: Record<string, any>,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Sends an identify event containing user property operations\n *\n * ```typescript\n * const id = new Identify();\n * id.set('colors', ['rose', 'gold']);\n * identify(id);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await identify(id).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n identify(identify: IIdentify, eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sends a group identify event containing group property operations.\n *\n * ```typescript\n * const id = new Identify();\n * id.set('skills', ['js', 'ts']);\n * const groupType = 'org';\n * const groupName = 'engineering';\n * groupIdentify(groupType, groupName, id);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await groupIdentify(groupType, groupName, id).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n groupIdentify(\n groupType: string,\n groupName: string | string[],\n identify: IIdentify,\n eventOptions?: EventOptions,\n ): AmplitudeReturn<Result>;\n\n /**\n * Assigns a user to group\n *\n * ```typescript\n * const groupType = 'orgId';\n * const groupName = '15';\n * setGroup(groupType, groupName, { user_id: '12345' })\n * ```\n */\n setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sends a revenue event containing revenue property operations.\n *\n * ```typescript\n * const rev = new Revenue();\n * rev.setRevenue(100);\n * revenue(rev);\n *\n * // alternatively, this tracking method is awaitable\n * const result = await revenue(rev).promise;\n * console.log(result.event); // {...}\n * console.log(result.code); // 200\n * console.log(result.message); // \"Event tracked successfully\"\n * ```\n */\n revenue(revenue: IRevenue, eventOptions?: EventOptions): AmplitudeReturn<Result>;\n\n /**\n * Sets a new optOut config value. This toggles event tracking on/off.\n *\n *```typescript\n * // Stops tracking\n * setOptOut(true);\n *\n * // Starts/resumes tracking\n * setOptOut(false);\n * ```\n */\n setOptOut(optOut: boolean): void;\n\n /**\n * Flush all unsent events.\n *\n *```typescript\n * flush();\n * ```\n */\n flush(): AmplitudeReturn<void>;\n}\n\nexport class AmplitudeCore implements CoreClient, PluginHost {\n protected initializing = false;\n protected name: string;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n config: IConfig;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n timeline: Timeline;\n isReady = false;\n protected q: Array<CallableFunction | typeof returnWrapper> = [];\n protected dispatchQ: Array<CallableFunction> = [];\n\n constructor(name = '$default') {\n this.timeline = new Timeline(this);\n this.name = name;\n }\n\n protected async _init(config: IConfig) {\n this.config = config;\n this.timeline.reset(this);\n this.timeline.loggerProvider = this.config.loggerProvider;\n await this.runQueuedFunctions('q');\n this.isReady = true;\n }\n\n async runQueuedFunctions(queueName: 'q' | 'dispatchQ') {\n const queuedFunctions = this[queueName];\n this[queueName] = [];\n for (const queuedFunction of queuedFunctions) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const val: ReturnType<typeof returnWrapper> | Promise<any> = queuedFunction();\n if (val && 'promise' in val) {\n await val.promise;\n } else {\n await val;\n }\n }\n // Rerun queued functions if the queue has accrued more while awaiting promises\n if (this[queueName].length) {\n await this.runQueuedFunctions(queueName);\n }\n }\n\n track(eventInput: BaseEvent | string, eventProperties?: Record<string, any>, eventOptions?: EventOptions) {\n const event = createTrackEvent(eventInput, eventProperties, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n logEvent = this.track.bind(this);\n\n identify(identify: IIdentify, eventOptions?: EventOptions) {\n const event = createIdentifyEvent(identify, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n groupIdentify(groupType: string, groupName: string | string[], identify: IIdentify, eventOptions?: EventOptions) {\n const event = createGroupIdentifyEvent(groupType, groupName, identify, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions) {\n const event = createGroupEvent(groupType, groupName, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n revenue(revenue: IRevenue, eventOptions?: EventOptions) {\n const event = createRevenueEvent(revenue, eventOptions);\n return returnWrapper(this.dispatch(event));\n }\n\n add(plugin: Plugin) {\n if (!this.isReady) {\n this.q.push(this._addPlugin.bind(this, plugin));\n return returnWrapper();\n }\n return this._addPlugin(plugin);\n }\n\n _addPlugin(plugin: Plugin) {\n return returnWrapper(this.timeline.register(plugin, this.config));\n }\n\n remove(pluginName: string) {\n if (!this.isReady) {\n this.q.push(this._removePlugin.bind(this, pluginName));\n return returnWrapper();\n }\n return this._removePlugin(pluginName);\n }\n\n _removePlugin(pluginName: string) {\n return returnWrapper(this.timeline.deregister(pluginName, this.config));\n }\n\n dispatchWithCallback(event: Event, callback: (result: Result) => void): void {\n if (!this.isReady) {\n return callback(buildResult(event, 0, CLIENT_NOT_INITIALIZED));\n }\n void this.process(event).then(callback);\n }\n\n async dispatch(event: Event): Promise<Result> {\n if (!this.isReady) {\n return new Promise<Result>((resolve) => {\n this.dispatchQ.push(this.dispatchWithCallback.bind(this, event, resolve));\n });\n }\n\n return this.process(event);\n }\n\n /**\n *\n * This method applies identify operations to user properties and\n * returns a single object representing the final user property state.\n *\n * This is a best-effort api that only supports $set, $clearAll, and $unset.\n * Other operations are not supported and are ignored.\n *\n *\n * @param userProperties The `event.userProperties` object from an Identify event.\n * @returns A key-value object user properties without operations.\n *\n * @example\n * Input:\n * {\n * $set: { plan: 'premium' },\n * custom_flag: true\n * }\n *\n * Output:\n * {\n * plan: 'premium',\n * custom_flag: true\n * }\n */\n getOperationAppliedUserProperties(userProperties: UserProperties | undefined): { [key: string]: any } {\n const updatedProperties: { [key: string]: any } = {};\n\n if (userProperties === undefined) {\n return updatedProperties;\n }\n\n // Keep non-operation keys for later merge\n const nonOpProperties: {\n [key in Exclude<string, IdentifyOperation>]: any;\n } = {};\n Object.keys(userProperties).forEach((key) => {\n if (!Object.values(IdentifyOperation).includes(key as IdentifyOperation)) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n nonOpProperties[key] = userProperties[key];\n }\n });\n\n OrderedIdentifyOperations.forEach((operation) => {\n // Skip when key is an operation.\n if (!Object.keys(userProperties).includes(operation)) return;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const opProperties: IdentifyUserProperties = userProperties[operation];\n\n switch (operation) {\n case IdentifyOperation.CLEAR_ALL:\n // Due to operation order, the following line will never execute.\n /* istanbul ignore next */\n Object.keys(updatedProperties).forEach((prop) => {\n delete updatedProperties[prop];\n });\n break;\n case IdentifyOperation.UNSET:\n Object.keys(opProperties).forEach((prop) => {\n delete updatedProperties[prop];\n });\n break;\n case IdentifyOperation.SET:\n Object.assign(updatedProperties, opProperties);\n break;\n }\n });\n\n // Merge non-operation properties.\n // Custom properties should not be affected by operations.\n // https://github.com/amplitude/nova/blob/343f678ded83c032e83b189796b3c2be161b48f5/src/main/java/com/amplitude/userproperty/model/ModifyUserPropertiesIdent.java#L79-L83\n Object.assign(updatedProperties, nonOpProperties);\n\n return updatedProperties;\n }\n\n async process(event: Event): Promise<Result> {\n try {\n // skip event processing if opt out\n if (this.config.optOut) {\n return buildResult(event, 0, OPT_OUT_MESSAGE);\n }\n\n if (event.event_type === SpecialEventType.IDENTIFY) {\n const userProperties = this.getOperationAppliedUserProperties(event.user_properties);\n this.timeline.onIdentityChanged({ userProperties: userProperties });\n }\n\n const result = await this.timeline.push(event);\n\n result.code === 200\n ? this.config.loggerProvider.log(result.message)\n : result.code === 100\n ? this.config.loggerProvider.warn(result.message)\n : this.config.loggerProvider.error(result.message);\n\n return result;\n } catch (e) {\n const message = String(e);\n this.config.loggerProvider.error(message);\n const result = buildResult(event, 0, message);\n\n return result;\n }\n }\n\n setOptOut(optOut: boolean) {\n if (!this.isReady) {\n this.q.push(this._setOptOut.bind(this, Boolean(optOut)));\n return;\n }\n this._setOptOut(optOut);\n }\n\n _setOptOut(optOut: boolean) {\n if (this.config.optOut !== optOut) {\n this.timeline.onOptOutChanged(optOut);\n this.config.optOut = Boolean(optOut);\n }\n }\n\n flush() {\n return returnWrapper(this.timeline.flush());\n }\n\n plugin(name: string): Plugin | undefined {\n const plugin = this.timeline.plugins.find((plugin) => plugin.name === name);\n if (plugin === undefined) {\n this.config.loggerProvider.debug(`Cannot find plugin with name ${name}`);\n return undefined;\n }\n\n return plugin;\n }\n\n plugins<T extends Plugin>(pluginClass: { new (...args: any[]): T }): T[] {\n return this.timeline.plugins.filter((plugin) => plugin instanceof pluginClass) as T[];\n }\n}\n"]}
@@ -18,7 +18,6 @@ export type Source = 'cache' | 'remote';
18
18
  export declare const US_SERVER_URL = "https://sr-client-cfg.amplitude.com/config";
19
19
  export declare const EU_SERVER_URL = "https://sr-client-cfg.eu.amplitude.com/config";
20
20
  export declare const DEFAULT_MAX_RETRIES = 3;
21
- export declare const FETCHED_KEYS: string[];
22
21
  export interface RemoteConfig {
23
22
  [key: string]: any;
24
23
  }
@@ -80,6 +79,7 @@ export interface IRemoteConfigClient {
80
79
  updateConfigs(): void;
81
80
  }
82
81
  export declare class RemoteConfigClient implements IRemoteConfigClient {
82
+ static readonly CONFIG_GROUP = "browser";
83
83
  readonly apiKey: string;
84
84
  readonly serverUrl: string;
85
85
  readonly logger: ILogger;
@@ -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;;;;;GAKG;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;AASrC,eAAO,MAAM,YAAY,UAOxB,CAAC;AAEF,MAAM,WAAW,YAAY;IAC3B,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,MAAM,WAAW,gBAAgB;IAC/B,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;IAElC,SAAS,EAAE,IAAI,CAAC;CACjB;AAED,MAAM,WAAW,mBAAmB;IAClC;;OAEG;IACH,WAAW,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAEzC;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACvD;AAED;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,YAAY,CAAC;IAC3B,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,YAAY,CAAC,EAAE,IAAI,CAAC;CACrB;AAED;;;GAG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gB,CAAC;IA4ChH;;OAEG;IACH,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM;IAIzC,YAAY,IAAI,MAAM;CASvB"}
@@ -9,16 +9,6 @@ export var DEFAULT_MAX_RETRIES = 3;
9
9
  * Linear backoff policy: timeout / retry times is the interval between fetch retry.
10
10
  */
11
11
  var DEFAULT_TIMEOUT = 1000;
12
- // TODO(xinyi)
13
- // const DEFAULT_MIN_TIME_BETWEEN_FETCHES = 5 * 60 * 1000; // 5 minutes
14
- export var FETCHED_KEYS = [
15
- 'analyticsSDK.browserSDK',
16
- 'sessionReplay.sr_interaction_config',
17
- 'sessionReplay.sr_logging_config',
18
- 'sessionReplay.sr_privacy_config',
19
- 'sessionReplay.sr_sampling_config',
20
- 'sessionReplay.sr_targeting_config',
21
- ];
22
12
  var RemoteConfigClient = /** @class */ (function () {
23
13
  function RemoteConfigClient(apiKey, logger, serverZone) {
24
14
  if (serverZone === void 0) { serverZone = 'US'; }
@@ -247,14 +237,13 @@ var RemoteConfigClient = /** @class */ (function () {
247
237
  return Math.floor(Math.random() * baseDelay);
248
238
  };
249
239
  RemoteConfigClient.prototype.getUrlParams = function () {
250
- var urlParams = new URLSearchParams({
251
- api_key: this.apiKey,
252
- });
253
- FETCHED_KEYS.forEach(function (key) {
254
- urlParams.append('config_keys', key);
255
- });
256
- return "".concat(this.serverUrl, "?").concat(urlParams.toString());
240
+ // URL encode the API key to handle special characters
241
+ var encodedApiKey = encodeURIComponent(this.apiKey);
242
+ var urlParams = new URLSearchParams();
243
+ urlParams.append('config_group', RemoteConfigClient.CONFIG_GROUP);
244
+ return "".concat(this.serverUrl, "/").concat(encodedApiKey, "?").concat(urlParams.toString());
257
245
  };
246
+ RemoteConfigClient.CONFIG_GROUP = 'browser';
258
247
  return RemoteConfigClient;
259
248
  }());
260
249
  export { RemoteConfigClient };
@@ -1 +1 @@
1
- {"version":3,"file":"remote-config.js","sourceRoot":"","sources":["../../../src/remote-config/remote-config.ts"],"names":[],"m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AQ,CAAC,CAAC,EAAlD,CAAkD,CAAC,EAAA;;wBAAlF,SAAkF,CAAC;;;wBA9B9C,OAAO,EAAE,CAAA;;6BAkClD,sBAAO,sBAAsB,EAAC;;;;KAC/B;IAED;;OAEG;IACH,2CAAc,GAAd,UAAe,SAAiB;QAC9B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IAC/C,CAAC;IAED,yCAAY,GAAZ;QACE,IAAM,SAAS,GAAG,IAAI,eAAe,CAAC;YACpC,OAAO,EAAE,IAAI,CAAC,MAAM;SACrB,CAAC,CAAC;QACH,YAAY,CAAC,OAAO,CAAC,UAAC,GAAG;YACvB,SAAS,CAAC,MAAM,CAAC,aAAa,EAAE,GAAG,CAAC,CAAC;QACvC,CAAC,CAAC,CAAC;QAEH,OAAO,UAAG,IAAI,CAAC,SAAS,cAAI,SAAS,CAAC,QAAQ,EAAE,CAAE,CAAC;IACrD,CAAC;IACH,yBAAC;AAAD,CAAC,AAxMD,IAwMC","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'` – Receive all config updates as they occur.\n * - `{ timeout: number }` – Wait for a remote response until the specified timeout (in milliseconds),\n * then return a cached copy if available.\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;\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// TODO(xinyi)\n// const DEFAULT_MIN_TIME_BETWEEN_FETCHES = 5 * 60 * 1000; // 5 minutes\nexport const FETCHED_KEYS = [\n 'analyticsSDK.browserSDK',\n 'sessionReplay.sr_interaction_config',\n 'sessionReplay.sr_logging_config',\n 'sessionReplay.sr_privacy_config',\n 'sessionReplay.sr_sampling_config',\n 'sessionReplay.sr_targeting_config',\n];\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 readonly apiKey: string;\n readonly serverUrl: string;\n readonly logger: ILogger;\n readonly storage: RemoteConfigStorage;\n // Registered callbackInfos by subscribe().\n callbackInfos: CallbackInfo[] = [];\n\n constructor(apiKey: string, logger: ILogger, serverZone: ServerZoneType = 'US') {\n this.apiKey = apiKey;\n this.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 const result = await this.fetch();\n void this.storage.setConfig(result);\n this.callbackInfos.forEach((callbackInfo) => {\n this.sendCallback(callbackInfo, result, 'remote');\n });\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.fetch().then((result) => {\n this.logger.debug('Remote config client subscription all mode fetched from remote.');\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.');\n this.sendCallback(callbackInfo, result, 'cache');\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([this.fetch(), timeoutPromise])) 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 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 try {\n const res = await fetch(this.getUrlParams(), {\n method: 'GET',\n headers: {\n Accept: '*/*',\n },\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 } 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\n this.logger.debug(`Remote config client fetch with retry time ${retries} is rejected because: `, error);\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 const urlParams = new URLSearchParams({\n api_key: this.apiKey,\n });\n FETCHED_KEYS.forEach((key) => {\n urlParams.append('config_keys', key);\n });\n\n return `${this.serverUrl}?${urlParams.toString()}`;\n }\n}\n"]}
1
+ {"version":3,"file":"remote-config.js","sourceRoot":"","sources":["../../../src/remote-config/remote-config.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAA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C;IAC/C,CAAC;IAED,yCAAY,GAAZ;QACE,sDAAsD;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;IAvMe,+BAAY,GAAG,SAAS,CAAC;IAwM3C,yBAAC;CAAA,AAzMD,IAyMC;SAzMY,kBAAkB","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'` – Receive all config updates as they occur.\n * - `{ timeout: number }` – Wait for a remote response until the specified timeout (in milliseconds),\n * then return a cached copy if available.\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;\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// TODO(xinyi)\n// const 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\n constructor(apiKey: string, logger: ILogger, serverZone: ServerZoneType = 'US') {\n this.apiKey = apiKey;\n this.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 const result = await this.fetch();\n void this.storage.setConfig(result);\n this.callbackInfos.forEach((callbackInfo) => {\n this.sendCallback(callbackInfo, result, 'remote');\n });\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.fetch().then((result) => {\n this.logger.debug('Remote config client subscription all mode fetched from remote.');\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.');\n this.sendCallback(callbackInfo, result, 'cache');\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([this.fetch(), timeoutPromise])) 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 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 try {\n const res = await fetch(this.getUrlParams(), {\n method: 'GET',\n headers: {\n Accept: '*/*',\n },\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 } 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\n this.logger.debug(`Remote config client fetch with retry time ${retries} is rejected because: `, error);\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,6 +1,7 @@
1
1
  import { AnalyticsIdentity, Plugin } from './types/plugin';
2
2
  import { CoreClient } from './core-client';
3
3
  import { IConfig } from './config';
4
+ import { ILogger } from './logger';
4
5
  import { EventCallback } from './types/event-callback';
5
6
  import { Event } from './types/event/event';
6
7
  import { Result } from './types/result';
@@ -9,6 +10,7 @@ export declare class Timeline {
9
10
  queue: [Event, EventCallback][];
10
11
  applying: boolean;
11
12
  plugins: Plugin[];
13
+ loggerProvider: ILogger;
12
14
  constructor(client: CoreClient);
13
15
  register(plugin: Plugin, config: IConfig): Promise<void>;
14
16
  deregister(pluginName: string, config: IConfig): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"timeline.d.ts","sourceRoot":"","sources":["../../src/timeline.ts"],"names":[],"mappings":"AAAA,OA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C;AACnC,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAIxC,qBAAa,QAAQ;IAYP,OAAO,CAAC,MAAM;IAX1B,KAAK,EAAE,CAAC,KAAK,EAAE,aAAa,CAAC,EAAE,CAAM;IAErC,QAAQ,UAAS;IAGjB,OAAO,EAAE,MAAM,EAAE,CAAM;IAIvB,cAAc,EAAE,OAAO,CAAC;gBAEJ,MAAM,EAAE,UAAU;IAEhC,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IAmBxC,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IAWpD,KAAK,CAAC,MAAM,EAAE,UAAU;IAQxB,IAAI,CAAC,KAAK,EAAE,KAAK;IAOjB,aAAa,CAAC,OAAO,EAAE,MAAM;IAavB,KAAK,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,aAAa,CAAC,GAAG,SAAS;IAsF9C,KAAK;IAiBX,iBAAiB,CAAC,QAAQ,EAAE,iBAAiB;IAU7C,kBAAkB,CAAC,SAAS,EAAE,MAAM;IAUpC,eAAe,CAAC,MAAM,EAAE,OAAO;CAShC"}
@@ -19,12 +19,12 @@ var Timeline = /** @class */ (function () {
19
19
  case 0:
20
20
  if (this.plugins.some(function (existingPlugin) { return existingPlugin.name === plugin.name; })) {
21
21
  // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
22
- config.loggerProvider.warn("Plugin with name ".concat(plugin.name, " already exists, skipping registration"));
22
+ this.loggerProvider.warn("Plugin with name ".concat(plugin.name, " already exists, skipping registration"));
23
23
  return [2 /*return*/];
24
24
  }
25
25
  if (plugin.name === undefined) {
26
26
  plugin.name = UUID();
27
- config.loggerProvider.warn("Plugin name is undefined. \n Generating a random UUID for plugin name: ".concat(plugin.name, ". \n Set a name for the plugin to prevent it from being added multiple times."));
27
+ this.loggerProvider.warn("Plugin name is undefined. \n Generating a random UUID for plugin name: ".concat(plugin.name, ". \n Set a name for the plugin to prevent it from being added multiple times."));
28
28
  }
29
29
  plugin.type = (_a = plugin.type) !== null && _a !== void 0 ? _a : 'enrichment';
30
30
  return [4 /*yield*/, ((_b = plugin.setup) === null || _b === void 0 ? void 0 : _b.call(plugin, config, this.client))];
@@ -98,6 +98,8 @@ var Timeline = /** @class */ (function () {
98
98
  }
99
99
  _a = __read(item, 1), event = _a[0];
100
100
  _b = __read(item, 2), resolve = _b[1];
101
+ // Log initial event
102
+ this.loggerProvider.log('Timeline.apply: Initial event', event);
101
103
  before = this.plugins.filter(function (plugin) { return plugin.type === 'before'; });
102
104
  _e.label = 1;
103
105
  case 1:
@@ -116,11 +118,13 @@ var Timeline = /** @class */ (function () {
116
118
  case 3:
117
119
  e = _e.sent();
118
120
  if (e === null) {
121
+ this.loggerProvider.log("Timeline.apply: Event filtered out by before plugin '".concat(String(plugin.name), "', event: ").concat(JSON.stringify(event)));
119
122
  resolve({ event: event, code: 0, message: '' });
120
123
  return [2 /*return*/];
121
124
  }
122
125
  else {
123
126
  event = e;
127
+ this.loggerProvider.log("Timeline.apply: Event after before plugin '".concat(String(plugin.name), "', event: ").concat(JSON.stringify(event)));
124
128
  }
125
129
  _e.label = 4;
126
130
  case 4:
@@ -156,11 +160,13 @@ var Timeline = /** @class */ (function () {
156
160
  case 11:
157
161
  e = _e.sent();
158
162
  if (e === null) {
163
+ this.loggerProvider.log("Timeline.apply: Event filtered out by enrichment plugin '".concat(String(plugin.name), "', event: ").concat(JSON.stringify(event)));
159
164
  resolve({ event: event, code: 0, message: '' });
160
165
  return [2 /*return*/];
161
166
  }
162
167
  else {
163
168
  event = e;
169
+ this.loggerProvider.log("Timeline.apply: Event after enrichment plugin '".concat(String(plugin.name), "', event: ").concat(JSON.stringify(event)));
164
170
  }
165
171
  _e.label = 12;
166
172
  case 12:
@@ -179,6 +185,8 @@ var Timeline = /** @class */ (function () {
179
185
  return [7 /*endfinally*/];
180
186
  case 16:
181
187
  destination = this.plugins.filter(function (plugin) { return plugin.type === 'destination'; });
188
+ // Log final event before sending to destinations
189
+ this.loggerProvider.log("Timeline.apply: Final event before destinations, event: ".concat(JSON.stringify(event)));
182
190
  executeDestinations = destination.map(function (plugin) {
183
191
  var eventClone = __assign({}, event);
184
192
  return plugin.execute(eventClone).catch(function (e) { return buildResult(eventClone, 0, String(e)); });
@@ -1 +1 @@
1
- {"version":3,"file":"timeline.js","sourceRoot":"","sources":["../../src/timeline.ts"],"names":[],"mappings":";AAMA,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAEpC;IAQE,kBAAoB,MAAkB;QAAlB,WAAM,GAAN,MAAM,CAAY;QAPtC,UAAK,GAA6B,EAAE,CAAC;QACrC,kDAAkD;QAClD,aAAQ,GAAG,KAAK,CAAC;QACjB,4DAA4D;QAC5D,yFAAyF;QACzF,YAAO,GAAa,EAAE,CAAC;IAEkB,CAAC;IAEpC,2BAAQ,GAAd,UAAe,MAAc,EAAE,MAAe;;;;;;wBAC5C,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,UAAC,cAAc,IAAK,OAAA,cAAc,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,EAAnC,CAAmC,CAAC,EAAE;4BAC9E,4EAA4E;4BAC5E,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,2BAAoB,MAAM,CAAC,IAAI,2CAAwC,CAAC,CAAC;4BACpG,sBAAO;yBACR;wBAED,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,EAAE;4BAC7B,MAAM,CAAC,IAAI,GAAG,IAAI,EAAE,CAAC;4BACrB,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,sFACiB,MAAM,CAAC,IAAI,uFACkB,CAAC,CAAC;yBAC5E;wBAED,MAAM,CAAC,IAAI,GA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AAQ,CAAC,CAAA,CAAC;QAC5C,CAAC,CAAC,CAAC;IACL,CAAC;IAED,qCAAkB,GAAlB,UAAmB,SAAiB;QAClC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;;YAC1B,2EAA2E;YAC3E,wDAAwD;YACxD,0DAA0D;YAC1D,0BAA0B;YAC1B,KAAK,CAAA,MAAA,MAAM,CAAC,kBAAkB,uDAAG,SAAS,CAAC,CAAA,CAAC;QAC9C,CAAC,CAAC,CAAC;IACL,CAAC;IAED,kCAAe,GAAf,UAAgB,MAAe;QAC7B,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;;YAC1B,wEAAwE;YACxE,wDAAwD;YACxD,0DAA0D;YAC1D,0BAA0B;YAC1B,KAAK,CAAA,MAAA,MAAM,CAAC,eAAe,uDAAG,MAAM,CAAC,CAAA,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC;IACH,eAAC;AAAD,CAAC,AAlLD,IAkLC","sourcesContent":["import { AnalyticsIdentity, BeforePlugin, DestinationPlugin, EnrichmentPlugin, Plugin } from './types/plugin';\nimport { CoreClient } from './core-client';\nimport { IConfig } from './config';\nimport { EventCallback } from './types/event-callback';\nimport { Event } from './types/event/event';\nimport { Result } from './types/result';\nimport { buildResult } from './utils/result-builder';\nimport { UUID } from './utils/uuid';\n\nexport class Timeline {\n queue: [Event, EventCallback][] = [];\n // Flag to guarantee one schedule apply is running\n applying = false;\n // Flag indicates whether timeline is ready to process event\n // Events collected before timeline is ready will stay in the queue to be processed later\n plugins: Plugin[] = [];\n\n constructor(private client: CoreClient) {}\n\n async register(plugin: Plugin, config: IConfig) {\n if (this.plugins.some((existingPlugin) => existingPlugin.name === plugin.name)) {\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n config.loggerProvider.warn(`Plugin with name ${plugin.name} already exists, skipping registration`);\n return;\n }\n\n if (plugin.name === undefined) {\n plugin.name = UUID();\n config.loggerProvider.warn(`Plugin name is undefined. \n Generating a random UUID for plugin name: ${plugin.name}. \n Set a name for the plugin to prevent it from being added multiple times.`);\n }\n\n plugin.type = plugin.type ?? 'enrichment';\n await plugin.setup?.(config, this.client);\n this.plugins.push(plugin);\n }\n\n async deregister(pluginName: string, config: IConfig) {\n const index = this.plugins.findIndex((plugin) => plugin.name === pluginName);\n if (index === -1) {\n config.loggerProvider.warn(`Plugin with name ${pluginName} does not exist, skipping deregistration`);\n return;\n }\n const plugin = this.plugins[index];\n this.plugins.splice(index, 1);\n await plugin.teardown?.();\n }\n\n reset(client: CoreClient) {\n this.applying = false;\n const plugins = this.plugins;\n plugins.map((plugin) => plugin.teardown?.());\n this.plugins = [];\n this.client = client;\n }\n\n push(event: Event) {\n return new Promise<Result>((resolve) => {\n this.queue.push([event, resolve]);\n this.scheduleApply(0);\n });\n }\n\n scheduleApply(timeout: number) {\n if (this.applying) return;\n this.applying = true;\n setTimeout(() => {\n void this.apply(this.queue.shift()).then(() => {\n this.applying = false;\n if (this.queue.length > 0) {\n this.scheduleApply(0);\n }\n });\n }, timeout);\n }\n\n async apply(item: [Event, EventCallback] | undefined) {\n if (!item) {\n return;\n }\n\n let [event] = item;\n const [, resolve] = item;\n\n const before = this.plugins.filter<BeforePlugin>(\n (plugin: Plugin): plugin is BeforePlugin => plugin.type === 'before',\n );\n\n for (const plugin of before) {\n /* istanbul ignore if */\n if (!plugin.execute) {\n // do nothing\n continue;\n }\n const e = await plugin.execute({ ...event });\n if (e === null) {\n resolve({ event, code: 0, message: '' });\n return;\n } else {\n event = e;\n }\n }\n\n const enrichment = this.plugins.filter<EnrichmentPlugin>(\n (plugin: Plugin): plugin is EnrichmentPlugin => plugin.type === 'enrichment' || plugin.type === undefined,\n );\n\n for (const plugin of enrichment) {\n /* istanbul ignore if */\n if (!plugin.execute) {\n // do nothing\n continue;\n }\n const e = await plugin.execute({ ...event });\n if (e === null) {\n resolve({ event, code: 0, message: '' });\n return;\n } else {\n event = e;\n }\n }\n\n const destination = this.plugins.filter<DestinationPlugin>(\n (plugin: Plugin): plugin is DestinationPlugin => plugin.type === 'destination',\n );\n\n const executeDestinations = destination.map((plugin) => {\n const eventClone = { ...event };\n return plugin.execute(eventClone).catch((e) => buildResult(eventClone, 0, String(e)));\n });\n\n void Promise.all(executeDestinations).then(([result]) => {\n const resolveResult =\n result || buildResult(event, 100, 'Event not tracked, no destination plugins on the instance');\n resolve(resolveResult);\n });\n\n return;\n }\n\n async flush() {\n const queue = this.queue;\n this.queue = [];\n\n await Promise.all(queue.map((item) => this.apply(item)));\n\n const destination = this.plugins.filter<DestinationPlugin>(\n (plugin: Plugin): plugin is DestinationPlugin => plugin.type === 'destination',\n );\n\n const executeDestinations = destination.map((plugin) => {\n return plugin.flush && plugin.flush();\n });\n\n await Promise.all(executeDestinations);\n }\n\n onIdentityChanged(identity: AnalyticsIdentity) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onIdentityChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onIdentityChanged?.(identity);\n });\n }\n\n onSessionIdChanged(sessionId: number) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onSessionIdChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onSessionIdChanged?.(sessionId);\n });\n }\n\n onOptOutChanged(optOut: boolean) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onOptOutChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onOptOutChanged?.(optOut);\n });\n }\n}\n"]}
1
+ {"version":3,"file":"timeline.js","sourceRoot":"","sources":["../../src/timeline.ts"],"names":[],"mappings":";AAOA,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAE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C;wBACxC,CAAC,CAAC,CAAC;wBAEH,qBAAM,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,EAAA;;wBAAtC,SAAsC,CAAC;;;;;KACxC;IAED,oCAAiB,GAAjB,UAAkB,QAA2B;QAC3C,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;;YAC1B,0EAA0E;YAC1E,wDAAwD;YACxD,0DAA0D;YAC1D,0BAA0B;YAC1B,KAAK,CAAA,MAAA,MAAM,CAAC,iBAAiB,uDAAG,QAAQ,CAAC,CAAA,CAAC;QAC5C,CAAC,CAAC,CAAC;IACL,CAAC;IAED,qCAAkB,GAAlB,UAAmB,SAAiB;QAClC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;;YAC1B,2EAA2E;YAC3E,wDAAwD;YACxD,0DAA0D;YAC1D,0BAA0B;YAC1B,KAAK,CAAA,MAAA,MAAM,CAAC,kBAAkB,uDAAG,SAAS,CAAC,CAAA,CAAC;QAC9C,CAAC,CAAC,CAAC;IACL,CAAC;IAED,kCAAe,GAAf,UAAgB,MAAe;QAC7B,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;;YAC1B,wEAAwE;YACxE,wDAAwD;YACxD,0DAA0D;YAC1D,0BAA0B;YAC1B,KAAK,CAAA,MAAA,MAAM,CAAC,eAAe,uDAAG,MAAM,CAAC,CAAA,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC;IACH,eAAC;AAAD,CAAC,AA5MD,IA4MC","sourcesContent":["import { AnalyticsIdentity, BeforePlugin, DestinationPlugin, EnrichmentPlugin, Plugin } from './types/plugin';\nimport { CoreClient } from './core-client';\nimport { IConfig } from './config';\nimport { ILogger } from './logger';\nimport { EventCallback } from './types/event-callback';\nimport { Event } from './types/event/event';\nimport { Result } from './types/result';\nimport { buildResult } from './utils/result-builder';\nimport { UUID } from './utils/uuid';\n\nexport class Timeline {\n queue: [Event, EventCallback][] = [];\n // Flag to guarantee one schedule apply is running\n applying = false;\n // Flag indicates whether timeline is ready to process event\n // Events collected before timeline is ready will stay in the queue to be processed later\n plugins: Plugin[] = [];\n // loggerProvider is set by the client at _init()\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n loggerProvider: ILogger;\n\n constructor(private client: CoreClient) {}\n\n async register(plugin: Plugin, config: IConfig) {\n if (this.plugins.some((existingPlugin) => existingPlugin.name === plugin.name)) {\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n this.loggerProvider.warn(`Plugin with name ${plugin.name} already exists, skipping registration`);\n return;\n }\n\n if (plugin.name === undefined) {\n plugin.name = UUID();\n this.loggerProvider.warn(`Plugin name is undefined. \n Generating a random UUID for plugin name: ${plugin.name}. \n Set a name for the plugin to prevent it from being added multiple times.`);\n }\n\n plugin.type = plugin.type ?? 'enrichment';\n await plugin.setup?.(config, this.client);\n this.plugins.push(plugin);\n }\n\n async deregister(pluginName: string, config: IConfig) {\n const index = this.plugins.findIndex((plugin) => plugin.name === pluginName);\n if (index === -1) {\n config.loggerProvider.warn(`Plugin with name ${pluginName} does not exist, skipping deregistration`);\n return;\n }\n const plugin = this.plugins[index];\n this.plugins.splice(index, 1);\n await plugin.teardown?.();\n }\n\n reset(client: CoreClient) {\n this.applying = false;\n const plugins = this.plugins;\n plugins.map((plugin) => plugin.teardown?.());\n this.plugins = [];\n this.client = client;\n }\n\n push(event: Event) {\n return new Promise<Result>((resolve) => {\n this.queue.push([event, resolve]);\n this.scheduleApply(0);\n });\n }\n\n scheduleApply(timeout: number) {\n if (this.applying) return;\n this.applying = true;\n setTimeout(() => {\n void this.apply(this.queue.shift()).then(() => {\n this.applying = false;\n if (this.queue.length > 0) {\n this.scheduleApply(0);\n }\n });\n }, timeout);\n }\n\n async apply(item: [Event, EventCallback] | undefined) {\n if (!item) {\n return;\n }\n\n let [event] = item;\n const [, resolve] = item;\n\n // Log initial event\n this.loggerProvider.log('Timeline.apply: Initial event', event);\n\n const before = this.plugins.filter<BeforePlugin>(\n (plugin: Plugin): plugin is BeforePlugin => plugin.type === 'before',\n );\n\n for (const plugin of before) {\n /* istanbul ignore if */\n if (!plugin.execute) {\n // do nothing\n continue;\n }\n const e = await plugin.execute({ ...event });\n if (e === null) {\n this.loggerProvider.log(\n `Timeline.apply: Event filtered out by before plugin '${String(plugin.name)}', event: ${JSON.stringify(\n event,\n )}`,\n );\n resolve({ event, code: 0, message: '' });\n return;\n } else {\n event = e;\n this.loggerProvider.log(\n `Timeline.apply: Event after before plugin '${String(plugin.name)}', event: ${JSON.stringify(event)}`,\n );\n }\n }\n\n const enrichment = this.plugins.filter<EnrichmentPlugin>(\n (plugin: Plugin): plugin is EnrichmentPlugin => plugin.type === 'enrichment' || plugin.type === undefined,\n );\n\n for (const plugin of enrichment) {\n /* istanbul ignore if */\n if (!plugin.execute) {\n // do nothing\n continue;\n }\n const e = await plugin.execute({ ...event });\n if (e === null) {\n this.loggerProvider.log(\n `Timeline.apply: Event filtered out by enrichment plugin '${String(plugin.name)}', event: ${JSON.stringify(\n event,\n )}`,\n );\n resolve({ event, code: 0, message: '' });\n return;\n } else {\n event = e;\n this.loggerProvider.log(\n `Timeline.apply: Event after enrichment plugin '${String(plugin.name)}', event: ${JSON.stringify(event)}`,\n );\n }\n }\n\n const destination = this.plugins.filter<DestinationPlugin>(\n (plugin: Plugin): plugin is DestinationPlugin => plugin.type === 'destination',\n );\n\n // Log final event before sending to destinations\n this.loggerProvider.log(`Timeline.apply: Final event before destinations, event: ${JSON.stringify(event)}`);\n\n const executeDestinations = destination.map((plugin) => {\n const eventClone = { ...event };\n return plugin.execute(eventClone).catch((e) => buildResult(eventClone, 0, String(e)));\n });\n\n void Promise.all(executeDestinations).then(([result]) => {\n const resolveResult =\n result || buildResult(event, 100, 'Event not tracked, no destination plugins on the instance');\n resolve(resolveResult);\n });\n\n return;\n }\n\n async flush() {\n const queue = this.queue;\n this.queue = [];\n\n await Promise.all(queue.map((item) => this.apply(item)));\n\n const destination = this.plugins.filter<DestinationPlugin>(\n (plugin: Plugin): plugin is DestinationPlugin => plugin.type === 'destination',\n );\n\n const executeDestinations = destination.map((plugin) => {\n return plugin.flush && plugin.flush();\n });\n\n await Promise.all(executeDestinations);\n }\n\n onIdentityChanged(identity: AnalyticsIdentity) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onIdentityChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onIdentityChanged?.(identity);\n });\n }\n\n onSessionIdChanged(sessionId: number) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onSessionIdChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onSessionIdChanged?.(sessionId);\n });\n }\n\n onOptOutChanged(optOut: boolean) {\n this.plugins.forEach((plugin) => {\n // Intentionally to not await plugin.onOptOutChanged() for non-blocking.\n // Ignore optional channing next line for test coverage.\n // If the plugin doesn't implement it, it won't be called.\n /* istanbul ignore next */\n void plugin.onOptOutChanged?.(optOut);\n });\n }\n}\n"]}
@@ -73,13 +73,13 @@ export declare const DEFAULT_RAGE_CLICK_ALLOWLIST: string[];
73
73
  */
74
74
  export declare const DEFAULT_DEAD_CLICK_WINDOW_MS = 3000;
75
75
  /**
76
- * Default time window for rage clicks (3 seconds)
76
+ * Default time window for rage clicks (1 second)
77
77
  */
78
- export declare const DEFAULT_RAGE_CLICK_WINDOW_MS = 3000;
78
+ export declare const DEFAULT_RAGE_CLICK_WINDOW_MS = 1000;
79
79
  /**
80
- * Default threshold for rage clicks (5 clicks)
80
+ * Default threshold for rage clicks (4 clicks)
81
81
  */
82
- export declare const DEFAULT_RAGE_CLICK_THRESHOLD = 5;
82
+ export declare const DEFAULT_RAGE_CLICK_THRESHOLD = 4;
83
83
  type DomElement = typeof globalThis extends {
84
84
  Element: new (...args: any) => infer T;
85
85
  } ? T : never;
@@ -1 +1 @@
1
- {"version":3,"file":"frustration-interactions.d.ts","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAE/D;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAED;;;GAGG;AACH,MAAM,WAAW,8BAA8B;IAC7C;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IAEvC;;;;;;;OAOG;IACH,wBAAwB,CAAC,EAAE,CAAC,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,KAAK,OAAO,CAAC;IAEpF;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;OAEG;IACH,oBAAoB,CAAC,EAAE;QACrB,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB,SAAS,CAAC,EAAE,SAAS,CAAC;KACvB,CAAC;IACF;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAE9B;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC/B;AAgBD;;GAEG;AACH,eAAO,MAAM,4BAA4B,UAOxC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,4BAA4B,UAAQ,CAAC;AAElD;;GAEG;AACH,eAAO,MAAM,4BAA4B,OAAQ,CAAC;AAElD;;GAEG;AACH,eAAO,MAAM,4BAA4B,OAAO,CAAC;AAEjD;;GAEG;AACH,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAK9C,KAAK,UAAU,GAAG,OAAO,UAAU,SAAS;IAC1C,OAAO,EAAE,KAAK,GAAG,IAAI,EAAE,GAAG,KAAK,MAAM,CAAC,CAAC;CACxC,GACG,CAAC,GACD,KAAK,CAAC"}
1
+ {"version":3,"file":"frustration-interactions.d.ts","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAE/D;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAED;;;GAGG;AACH,MAAM,WAAW,8BAA8B;IAC7C;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IAEvC;;;;;;;OAOG;IACH,wBAAwB,CAAC,EAAE,CAAC,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,KAAK,OAAO,CAAC;IAEpF;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;OAEG;IACH,oBAAoB,CAAC,EAAE;QACrB,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB,SAAS,CAAC,EAAE,SAAS,CAAC;KACvB,CAAC;IACF;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAE9B;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC/B;AAgBD;;GAEG;AACH,eAAO,MAAM,4BAA4B,UAOxC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,4BAA4B,UAAQ,CAAC;AAElD;;GAEG;AACH,eAAO,MAAM,4BAA4B,OAAQ,CAAC;AAElD;;GAEG;AACH,eAAO,MAAM,4BAA4B,OAAQ,CAAC;AAElD;;GAEG;AACH,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAK9C,KAAK,UAAU,GAAG,OAAO,UAAU,SAAS;IAC1C,OAAO,EAAE,KAAK,GAAG,IAAI,EAAE,GAAG,KAAK,MAAM,CAAC,CAAC;CACxC,GACG,CAAC,GACD,KAAK,CAAC"}
@@ -31,11 +31,11 @@ export var DEFAULT_RAGE_CLICK_ALLOWLIST = ['*'];
31
31
  */
32
32
  export var DEFAULT_DEAD_CLICK_WINDOW_MS = 3000;
33
33
  /**
34
- * Default time window for rage clicks (3 seconds)
34
+ * Default time window for rage clicks (1 second)
35
35
  */
36
- export var DEFAULT_RAGE_CLICK_WINDOW_MS = 3000;
36
+ export var DEFAULT_RAGE_CLICK_WINDOW_MS = 1000;
37
37
  /**
38
- * Default threshold for rage clicks (5 clicks)
38
+ * Default threshold for rage clicks (4 clicks)
39
39
  */
40
- export var DEFAULT_RAGE_CLICK_THRESHOLD = 5;
40
+ export var DEFAULT_RAGE_CLICK_THRESHOLD = 4;
41
41
  //# sourceMappingURL=frustration-interactions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"frustration-interactions.js","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":";AAsEA,IAAM,2BAA2B,GAAG;IAClC,GAAG;IACH,QAAQ;IACR,iBAAiB;IACjB,eAAe;IACf,mBAAmB;IACnB,2BAA2B;IAC3B,wBAAwB;IACxB,iBAAiB;IACjB,cAAc;IACd,mBAAmB;IACnB,4BAA4B;CAC7B,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,IAAM,4BAA4B;IACvC,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,qBAAqB;IACrB,oBAAoB;UACjB,2BAA2B,SAC/B,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,IAAM,4BAA4B,GAAG,CAAC,GAAG,CAAC,CAAC;AAElD;;GAEG;AACH,MAAM,CAAC,IAAM,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACH,MAAM,CAAC,IAAM,4BAA4B,GAAG,IAAI,CAAC;AAEjD;;GAEG;AACH,MAAM,CAAC,IAAM,4BAA4B,GAAG,CAAC,CAAC","sourcesContent":["import { ActionType, Messenger } from './element-interactions';\n\n/**\n * Configuration options for dead clicks tracking\n */\nexport interface DeadClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for dead clicks.\n * A dead click is a click that doesn't result in any visible change or navigation.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for rage clicks tracking\n */\nexport interface RageClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for rage clicks.\n * A rage click is multiple rapid clicks on the same element within a 3s time window.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for frustration interactions tracking.\n * This includes dead clicks and rage clicks tracking.\n */\nexport interface FrustrationInteractionsOptions {\n /**\n * List of page URLs to allow auto tracking on.\n * When provided, only allow tracking on these URLs.\n * Both full URLs and regex are supported.\n */\n pageUrlAllowlist?: (string | RegExp)[];\n\n /**\n * Function to determine whether an event should be tracked.\n * When provided, this function overwrites all other allowlists and configurations.\n * If the function returns true, the event will be tracked.\n * If the function returns false, the event will not be tracked.\n * @param actionType - The type of action that triggered the event.\n * @param element - The [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that triggered the event.\n */\n shouldTrackEventResolver?: (actionType: ActionType, element: DomElement) => boolean;\n\n /**\n * Prefix for data attributes to allow auto collecting.\n * Default is 'data-amp-track-'.\n */\n dataAttributePrefix?: string;\n\n /**\n * Options for integrating visual tagging selector.\n */\n visualTaggingOptions?: {\n enabled?: boolean;\n messenger?: Messenger;\n };\n /**\n * Configuration for dead clicks tracking\n */\n deadClicks?: DeadClickOptions;\n\n /**\n * Configuration for rage clicks tracking\n */\n rageClicks?: RageClickOptions;\n}\n\nconst CLICKABLE_ELEMENT_SELECTORS = [\n 'a',\n 'button',\n '[role=\"button\"]',\n '[role=\"link\"]',\n '[role=\"menuitem\"]',\n '[role=\"menuitemcheckbox\"]',\n '[role=\"menuitemradio\"]',\n '[role=\"option\"]',\n '[role=\"tab\"]',\n '[role=\"treeitem\"]',\n '[contenteditable=\"true\" i]',\n];\n\n/**\n * Default CSS selectors for dead clicks tracking\n */\nexport const DEFAULT_DEAD_CLICK_ALLOWLIST = [\n 'input[type=\"button\"]',\n 'input[type=\"submit\"]',\n 'input[type=\"reset\"]',\n 'input[type=\"image\"]',\n 'input[type=\"file\"]',\n ...CLICKABLE_ELEMENT_SELECTORS,\n];\n\n/**\n * Default CSS selectors for rage clicks tracking\n */\nexport const DEFAULT_RAGE_CLICK_ALLOWLIST = ['*'];\n\n/**\n * Default time window for dead clicks (3 seconds)\n */\nexport const DEFAULT_DEAD_CLICK_WINDOW_MS = 3_000;\n\n/**\n * Default time window for rage clicks (3 seconds)\n */\nexport const DEFAULT_RAGE_CLICK_WINDOW_MS = 3000;\n\n/**\n * Default threshold for rage clicks (5 clicks)\n */\nexport const DEFAULT_RAGE_CLICK_THRESHOLD = 5;\n\n// DomElement is [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) if the dom library is included in tsconfig.json\n// and never if it is not included\n// eslint-disable-next-line no-restricted-globals\ntype DomElement = typeof globalThis extends {\n Element: new (...args: any) => infer T;\n}\n ? T\n : never;\n"]}
1
+ {"version":3,"file":"frustration-interactions.js","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":";AAsEA,IAAM,2BAA2B,GAAG;IAClC,GAAG;IACH,QAAQ;IACR,iBAAiB;IACjB,eAAe;IACf,mBAAmB;IACnB,2BAA2B;IAC3B,wBAAwB;IACxB,iBAAiB;IACjB,cAAc;IACd,mBAAmB;IACnB,4BAA4B;CAC7B,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,IAAM,4BAA4B;IACvC,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,qBAAqB;IACrB,oBAAoB;UACjB,2BAA2B,SAC/B,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,IAAM,4BAA4B,GAAG,CAAC,GAAG,CAAC,CAAC;AAElD;;GAEG;AACH,MAAM,CAAC,IAAM,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACH,MAAM,CAAC,IAAM,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACH,MAAM,CAAC,IAAM,4BAA4B,GAAG,CAAC,CAAC","sourcesContent":["import { ActionType, Messenger } from './element-interactions';\n\n/**\n * Configuration options for dead clicks tracking\n */\nexport interface DeadClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for dead clicks.\n * A dead click is a click that doesn't result in any visible change or navigation.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for rage clicks tracking\n */\nexport interface RageClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for rage clicks.\n * A rage click is multiple rapid clicks on the same element within a 3s time window.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for frustration interactions tracking.\n * This includes dead clicks and rage clicks tracking.\n */\nexport interface FrustrationInteractionsOptions {\n /**\n * List of page URLs to allow auto tracking on.\n * When provided, only allow tracking on these URLs.\n * Both full URLs and regex are supported.\n */\n pageUrlAllowlist?: (string | RegExp)[];\n\n /**\n * Function to determine whether an event should be tracked.\n * When provided, this function overwrites all other allowlists and configurations.\n * If the function returns true, the event will be tracked.\n * If the function returns false, the event will not be tracked.\n * @param actionType - The type of action that triggered the event.\n * @param element - The [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that triggered the event.\n */\n shouldTrackEventResolver?: (actionType: ActionType, element: DomElement) => boolean;\n\n /**\n * Prefix for data attributes to allow auto collecting.\n * Default is 'data-amp-track-'.\n */\n dataAttributePrefix?: string;\n\n /**\n * Options for integrating visual tagging selector.\n */\n visualTaggingOptions?: {\n enabled?: boolean;\n messenger?: Messenger;\n };\n /**\n * Configuration for dead clicks tracking\n */\n deadClicks?: DeadClickOptions;\n\n /**\n * Configuration for rage clicks tracking\n */\n rageClicks?: RageClickOptions;\n}\n\nconst CLICKABLE_ELEMENT_SELECTORS = [\n 'a',\n 'button',\n '[role=\"button\"]',\n '[role=\"link\"]',\n '[role=\"menuitem\"]',\n '[role=\"menuitemcheckbox\"]',\n '[role=\"menuitemradio\"]',\n '[role=\"option\"]',\n '[role=\"tab\"]',\n '[role=\"treeitem\"]',\n '[contenteditable=\"true\" i]',\n];\n\n/**\n * Default CSS selectors for dead clicks tracking\n */\nexport const DEFAULT_DEAD_CLICK_ALLOWLIST = [\n 'input[type=\"button\"]',\n 'input[type=\"submit\"]',\n 'input[type=\"reset\"]',\n 'input[type=\"image\"]',\n 'input[type=\"file\"]',\n ...CLICKABLE_ELEMENT_SELECTORS,\n];\n\n/**\n * Default CSS selectors for rage clicks tracking\n */\nexport const DEFAULT_RAGE_CLICK_ALLOWLIST = ['*'];\n\n/**\n * Default time window for dead clicks (3 seconds)\n */\nexport const DEFAULT_DEAD_CLICK_WINDOW_MS = 3_000;\n\n/**\n * Default time window for rage clicks (1 second)\n */\nexport const DEFAULT_RAGE_CLICK_WINDOW_MS = 1_000;\n\n/**\n * Default threshold for rage clicks (4 clicks)\n */\nexport const DEFAULT_RAGE_CLICK_THRESHOLD = 4;\n\n// DomElement is [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) if the dom library is included in tsconfig.json\n// and never if it is not included\n// eslint-disable-next-line no-restricted-globals\ntype DomElement = typeof globalThis extends {\n Element: new (...args: any) => infer T;\n}\n ? T\n : never;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amplitude/analytics-core",
3
- "version": "2.15.0",
3
+ "version": "2.16.0",
4
4
  "description": "",
5
5
  "author": "Amplitude Inc",
6
6
  "homepage": "https://github.com/amplitude/Amplitude-TypeScript",
@@ -42,5 +42,5 @@
42
42
  "files": [
43
43
  "lib"
44
44
  ],
45
- "gitHead": "e52a4375e646a60cc6f3d9f8b8c599816a6a5f73"
45
+ "gitHead": "1ff69489af101b6a8780786b54a1caf403a4a425"
46
46
  }