@amplitude/analytics-core 2.38.0 → 2.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/core-client.d.ts +9 -1
- package/lib/cjs/core-client.d.ts.map +1 -1
- package/lib/cjs/core-client.js +15 -5
- package/lib/cjs/core-client.js.map +1 -1
- package/lib/cjs/storage/cookie.d.ts +0 -1
- package/lib/cjs/storage/cookie.d.ts.map +1 -1
- package/lib/cjs/storage/cookie.js +4 -4
- package/lib/cjs/storage/cookie.js.map +1 -1
- package/lib/cjs/types/client/browser-client.d.ts +33 -0
- package/lib/cjs/types/client/browser-client.d.ts.map +1 -1
- package/lib/cjs/types/client/browser-client.js.map +1 -1
- package/lib/esm/core-client.d.ts +9 -1
- package/lib/esm/core-client.d.ts.map +1 -1
- package/lib/esm/core-client.js +16 -6
- package/lib/esm/core-client.js.map +1 -1
- package/lib/esm/storage/cookie.d.ts +0 -1
- package/lib/esm/storage/cookie.d.ts.map +1 -1
- package/lib/esm/storage/cookie.js +4 -4
- package/lib/esm/storage/cookie.js.map +1 -1
- package/lib/esm/types/client/browser-client.d.ts +33 -0
- package/lib/esm/types/client/browser-client.d.ts.map +1 -1
- package/lib/esm/types/client/browser-client.js.map +1 -1
- package/package.json +1 -1
package/lib/cjs/core-client.d.ts
CHANGED
|
@@ -16,6 +16,13 @@ export declare class AmplitudeCore implements CoreClient, PluginHost {
|
|
|
16
16
|
isReady: boolean;
|
|
17
17
|
protected q: Array<CallableFunction | typeof returnWrapper>;
|
|
18
18
|
protected dispatchQ: Array<CallableFunction>;
|
|
19
|
+
/**
|
|
20
|
+
* Current user properties (operation-applied, flat key-value).
|
|
21
|
+
* Only used by client-side SDKs; server SDKs may leave this undefined.
|
|
22
|
+
*/
|
|
23
|
+
userProperties: {
|
|
24
|
+
[key: string]: any;
|
|
25
|
+
} | undefined;
|
|
19
26
|
constructor(name?: string);
|
|
20
27
|
protected _init(config: IConfig): Promise<void>;
|
|
21
28
|
runQueuedFunctions(queueName: 'q' | 'dispatchQ'): Promise<void>;
|
|
@@ -39,8 +46,9 @@ export declare class AmplitudeCore implements CoreClient, PluginHost {
|
|
|
39
46
|
* This is a best-effort api that only supports $set, $clearAll, and $unset.
|
|
40
47
|
* Other operations are not supported and are ignored.
|
|
41
48
|
*
|
|
49
|
+
* Operations are applied on top of current client state (this.userProperties).
|
|
42
50
|
*
|
|
43
|
-
* @param userProperties The
|
|
51
|
+
* @param userProperties The new user properties object from identify() or setIdentity().
|
|
44
52
|
* @returns A key-value object user properties without operations.
|
|
45
53
|
*
|
|
46
54
|
* @example
|
|
@@ -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,4BAA4B,CAAC;AACrD,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;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAStC,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AACpE,qBAAa,aAAc,YAAW,UAAU,EAAE,UAAU;IAC1D,SAAS,CAAC,YAAY,UAAS;IAC/B,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;IAGvB,MAAM,EAAE,OAAO,CAAC;IAGhB,QAAQ,EAAE,QAAQ,CAAC;IACnB,OAAO,UAAS;IAChB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CAAC,MAAM,CAAC;IA+B5C,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"}
|
package/lib/cjs/core-client.js
CHANGED
|
@@ -91,10 +91,14 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
91
91
|
};
|
|
92
92
|
AmplitudeCore.prototype.track = function (eventInput, eventProperties, eventOptions) {
|
|
93
93
|
var event = (0, event_builder_1.createTrackEvent)(eventInput, eventProperties, eventOptions);
|
|
94
|
+
// Update client user properties immediately and synchronously
|
|
95
|
+
this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);
|
|
94
96
|
return (0, return_wrapper_1.returnWrapper)(this.dispatch(event));
|
|
95
97
|
};
|
|
96
98
|
AmplitudeCore.prototype.identify = function (identify, eventOptions) {
|
|
97
99
|
var event = (0, event_builder_1.createIdentifyEvent)(identify, eventOptions);
|
|
100
|
+
// Update client user properties immediately and synchronously
|
|
101
|
+
this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);
|
|
98
102
|
return (0, return_wrapper_1.returnWrapper)(this.dispatch(event));
|
|
99
103
|
};
|
|
100
104
|
AmplitudeCore.prototype.groupIdentify = function (groupType, groupName, identify, eventOptions) {
|
|
@@ -103,6 +107,8 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
103
107
|
};
|
|
104
108
|
AmplitudeCore.prototype.setGroup = function (groupType, groupName, eventOptions) {
|
|
105
109
|
var event = (0, event_builder_1.createGroupEvent)(groupType, groupName, eventOptions);
|
|
110
|
+
// Update client user properties immediately and synchronously
|
|
111
|
+
this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);
|
|
106
112
|
return (0, return_wrapper_1.returnWrapper)(this.dispatch(event));
|
|
107
113
|
};
|
|
108
114
|
AmplitudeCore.prototype.revenue = function (revenue, eventOptions) {
|
|
@@ -156,8 +162,9 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
156
162
|
* This is a best-effort api that only supports $set, $clearAll, and $unset.
|
|
157
163
|
* Other operations are not supported and are ignored.
|
|
158
164
|
*
|
|
165
|
+
* Operations are applied on top of current client state (this.userProperties).
|
|
159
166
|
*
|
|
160
|
-
* @param userProperties The
|
|
167
|
+
* @param userProperties The new user properties object from identify() or setIdentity().
|
|
161
168
|
* @returns A key-value object user properties without operations.
|
|
162
169
|
*
|
|
163
170
|
* @example
|
|
@@ -174,7 +181,9 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
174
181
|
* }
|
|
175
182
|
*/
|
|
176
183
|
AmplitudeCore.prototype.getOperationAppliedUserProperties = function (userProperties) {
|
|
177
|
-
var
|
|
184
|
+
var _a;
|
|
185
|
+
var base = (_a = this.userProperties) !== null && _a !== void 0 ? _a : {};
|
|
186
|
+
var updatedProperties = tslib_1.__assign({}, base);
|
|
178
187
|
if (userProperties === undefined) {
|
|
179
188
|
return updatedProperties;
|
|
180
189
|
}
|
|
@@ -220,7 +229,7 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
220
229
|
};
|
|
221
230
|
AmplitudeCore.prototype.process = function (event) {
|
|
222
231
|
return tslib_1.__awaiter(this, void 0, void 0, function () {
|
|
223
|
-
var
|
|
232
|
+
var result, e_2, message, result;
|
|
224
233
|
return tslib_1.__generator(this, function (_a) {
|
|
225
234
|
switch (_a.label) {
|
|
226
235
|
case 0:
|
|
@@ -230,8 +239,9 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
230
239
|
return [2 /*return*/, (0, result_builder_1.buildResult)(event, 0, messages_1.OPT_OUT_MESSAGE)];
|
|
231
240
|
}
|
|
232
241
|
if (event.event_type === event_1.SpecialEventType.IDENTIFY) {
|
|
233
|
-
|
|
234
|
-
|
|
242
|
+
// Do not update this.userProperties here.
|
|
243
|
+
// It is only set synchronously in identify() or setIdentity()
|
|
244
|
+
this.timeline.onIdentityChanged({ userProperties: this.userProperties });
|
|
235
245
|
}
|
|
236
246
|
return [4 /*yield*/, this.timeline.push(event)];
|
|
237
247
|
case 1:
|
|
@@ -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,yDAAuD;AAEvD;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,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QArC/B,IAAI,CAAC,QAAQ,GAAG,IAAI,mBAAQ,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAEe,6BAAK,GAArB,UAAsB,MAAe;;;;;wBACnC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;wBACrB,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;wBAC1B,IAAI,CAAC,QAAQ,CAAC,cAAc,GAAG,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC;wBAC1D,qBAAM,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAA;;wBAAlC,SAAkC,CAAC;wBACnC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;;;;;KACrB;IAEK,0CAAkB,GAAxB,UAAyB,SAA4B;;;;;;;wBAC7C,eAAe,GAAG,IAAI,CAAC,SAAS,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AAC,CAAC;IAC1B,CAAC;IAED,kCAAU,GAAV,UAAW,MAAe;QACxB,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,KAAK,MAAM,EAAE;YACjC,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;YACrC,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;SACvC;IACH,CAAC;IAED,6BAAK,GAAL;QACE,OAAO,IAAA,8BAAa,EAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAC9C,CAAC;IAED,8BAAM,GAAN,UAAO,IAAY;QACjB,IAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,UAAC,MAAM,IAAK,OAAA,MAAM,CAAC,IAAI,KAAK,IAAI,EAApB,CAAoB,CAAC,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;AA/PY,sCAAa","sourcesContent":["import { Plugin } from './types/plugin';\nimport { IConfig } from './types/config/core-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 { returnWrapper } from './utils/return-wrapper';\nimport { CoreClient, PluginHost } from './types/client/core-client';\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.config.optOut = Boolean(optOut);\n this.timeline.onOptOutChanged(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,yDAAuD;AAEvD;IAmBE,uBAAY,IAAiB;QAAjB,qBAAA,EAAA,iBAAiB;QAlBnB,iBAAY,GAAG,KAAK,CAAC;QAQ/B,YAAO,GAAG,KAAK,CAAC;QACN,MAAC,GAAmD,EAAE,CAAC;QACvD,cAAS,GAA4B,EAAE,CAAC;QAgDlD,aAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAvC/B,IAAI,CAAC,QAAQ,GAAG,IAAI,mBAAQ,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAEe,6BAAK,GAArB,UAAsB,MAAe;;;;;wBACnC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC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C,IAAI,KAAK,IAAI,EAApB,CAAoB,CAAC,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,AA9QD,IA8QC;AA9QY,sCAAa","sourcesContent":["import { Plugin } from './types/plugin';\nimport { IConfig } from './types/config/core-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 { returnWrapper } from './utils/return-wrapper';\nimport { CoreClient, PluginHost } from './types/client/core-client';\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 /**\n * Current user properties (operation-applied, flat key-value).\n * Only used by client-side SDKs; server SDKs may leave this undefined.\n */\n userProperties: { [key: string]: any } | undefined;\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 // Update client user properties immediately and synchronously\n this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);\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 // Update client user properties immediately and synchronously\n this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);\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 // Update client user properties immediately and synchronously\n this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);\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 * Operations are applied on top of current client state (this.userProperties).\n *\n * @param userProperties The new user properties object from identify() or setIdentity().\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 base = this.userProperties ?? {};\n const updatedProperties: { [key: string]: any } = { ...base };\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 // Do not update this.userProperties here.\n // It is only set synchronously in identify() or setIdentity()\n this.timeline.onIdentityChanged({ userProperties: this.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.config.optOut = Boolean(optOut);\n this.timeline.onOptOutChanged(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"]}
|
|
@@ -2,7 +2,6 @@ import { Storage, CookieStorageOptions, CookieStorageConfig } from '../types/sto
|
|
|
2
2
|
export declare class CookieStorage<T> implements Storage<T> {
|
|
3
3
|
options: CookieStorageOptions;
|
|
4
4
|
config: CookieStorageConfig;
|
|
5
|
-
private static testValue;
|
|
6
5
|
constructor(options?: CookieStorageOptions, config?: CookieStorageConfig);
|
|
7
6
|
isEnabled(): Promise<boolean>;
|
|
8
7
|
get(key: string): Promise<T | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookie.d.ts","sourceRoot":"","sources":["../../../src/storage/cookie.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAsBtF,qBAAa,aAAa,CAAC,CAAC,CAAE,YAAW,OAAO,CAAC,CAAC,CAAC;IACjD,OAAO,EAAE,oBAAoB,CAAC;IAC9B,MAAM,EAAE,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"cookie.d.ts","sourceRoot":"","sources":["../../../src/storage/cookie.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAsBtF,qBAAa,aAAa,CAAC,CAAC,CAAE,YAAW,OAAO,CAAC,CAAC,CAAC;IACjD,OAAO,EAAE,oBAAoB,CAAC;IAC9B,MAAM,EAAE,mBAAmB,CAAC;gBAEhB,OAAO,CAAC,EAAE,oBAAoB,EAAE,MAAM,GAAE,mBAAwB;IAKtE,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC;IAyB7B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC;IAmBxC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IA6DhD,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAkChD,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIlC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAG7B;AAoBD;;;GAGG;AACH,eAAO,MAAM,iBAAiB,UAAW,MAAM,KAAG,MAAM,GAAG,SAE1D,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,aAAa,YAAa,MAAM,GAAG,SAAS,WAAW,MAAM,GAAG,SAAS,KAAG,OAOxF,CAAC"}
|
|
@@ -12,7 +12,7 @@ var CookieStorage = /** @class */ (function () {
|
|
|
12
12
|
}
|
|
13
13
|
CookieStorage.prototype.isEnabled = function () {
|
|
14
14
|
return tslib_1.__awaiter(this, void 0, void 0, function () {
|
|
15
|
-
var testCookieOptions, testStorage, testKey, value, _a;
|
|
15
|
+
var testValue, testCookieOptions, testStorage, testKey, value, _a;
|
|
16
16
|
return tslib_1.__generator(this, function (_b) {
|
|
17
17
|
switch (_b.label) {
|
|
18
18
|
case 0:
|
|
@@ -20,20 +20,20 @@ var CookieStorage = /** @class */ (function () {
|
|
|
20
20
|
if (!(0, global_scope_1.getGlobalScope)()) {
|
|
21
21
|
return [2 /*return*/, false];
|
|
22
22
|
}
|
|
23
|
-
|
|
23
|
+
testValue = String(Date.now());
|
|
24
24
|
testCookieOptions = tslib_1.__assign(tslib_1.__assign({}, this.options), { expirationDays: 0.003 });
|
|
25
25
|
testStorage = new CookieStorage(testCookieOptions);
|
|
26
26
|
testKey = "AMP_TEST_".concat((0, uuid_1.UUID)().substring(0, 8));
|
|
27
27
|
_b.label = 1;
|
|
28
28
|
case 1:
|
|
29
29
|
_b.trys.push([1, 4, 5, 7]);
|
|
30
|
-
return [4 /*yield*/, testStorage.set(testKey,
|
|
30
|
+
return [4 /*yield*/, testStorage.set(testKey, testValue)];
|
|
31
31
|
case 2:
|
|
32
32
|
_b.sent();
|
|
33
33
|
return [4 /*yield*/, testStorage.get(testKey)];
|
|
34
34
|
case 3:
|
|
35
35
|
value = _b.sent();
|
|
36
|
-
return [2 /*return*/, value ===
|
|
36
|
+
return [2 /*return*/, value === testValue];
|
|
37
37
|
case 4:
|
|
38
38
|
_a = _b.sent();
|
|
39
39
|
/* istanbul ignore next */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookie.js","sourceRoot":"","sources":["../../../src/storage/cookie.ts"],"names":[],"mappings":";;;;AACA,gDAAiD;AACjD,sCAAqC;AAoBrC;IAKE,uBAAY,OAA8B,EAAE,MAAgC;QAAhC,uBAAA,EAAA,WAAgC;QAC1E,IAAI,CAAC,OAAO,wBAAQ,OAAO,CAAE,CAAC;QAC9B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAEK,iCAAS,GAAf;;;;;;wBACE,wBAAwB;wBACxB,IAAI,CAAC,IAAA,6BAAc,GAAE,EAAE;4BACrB,sBAAO,KAAK,EAAC;yBACd;wBAED,aAAa,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;wBACvC,iBAAiB,yCAClB,IAAI,CAAC,OAAO,KACf,cAAc,EAAE,KAAK,GACtB,CAAC;wBACI,WAAW,GAAG,IAAI,aAAa,CAAS,iBAAiB,CAAC,C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AI;QACF,OAAO,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;KACxC;IAAC,WAAM;QACN,OAAO,SAAS,CAAC;KAClB;AACH,CAAC,CAAC;AAEF,IAAM,kCAAkC,GAAG,UAAC,KAAa;IACvD,uEAAuE;IACvE,kEAAkE;IAClE,IAAI;QACF,OAAO,kBAAkB,CAAC,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC5D;IAAC,WAAM;QACN,OAAO,SAAS,CAAC;KAClB;AACH,CAAC,CAAC;AAEF;;;GAGG;AACI,IAAM,iBAAiB,GAAG,UAAC,KAAa;;IAC7C,OAAO,MAAA,sBAAsB,CAAC,KAAK,CAAC,mCAAI,kCAAkC,CAAC,KAAK,CAAC,CAAC;AACpF,CAAC,CAAC;AAFW,QAAA,iBAAiB,qBAE5B;AAEF;;;;GAIG;AACI,IAAM,aAAa,GAAG,UAAC,OAA2B,EAAE,OAA2B;IACpF,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE;QACxB,OAAO,KAAK,CAAC;KACd;IACD,IAAM,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7E,IAAM,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7E,OAAO,WAAW,CAAC,WAAW,EAAE,KAAK,WAAW,CAAC,WAAW,EAAE,CAAC;AACjE,CAAC,CAAC;AAPW,QAAA,aAAa,iBAOxB","sourcesContent":["import { Storage, CookieStorageOptions, CookieStorageConfig } from '../types/storage';\nimport { getGlobalScope } from '../global-scope';\nimport { UUID } from '../utils/uuid';\n\n// CookieStore is a Web API not included in standard TypeScript lib types\n// https://developer.mozilla.org/en-US/docs/Web/API/CookieStore\ninterface CookieStoreSetOptions {\n name: string;\n value: string;\n expires?: number;\n domain?: string;\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\ninterface CookieStore {\n getAll(key: string): Promise<CookieStoreSetOptions[] | undefined>;\n}\n\ntype GlobalScopeWithCookieStore = {\n cookieStore?: CookieStore;\n} & typeof global;\n\nexport class CookieStorage<T> implements Storage<T> {\n options: CookieStorageOptions;\n config: CookieStorageConfig;\n private static testValue: undefined | string;\n\n constructor(options?: CookieStorageOptions, config: CookieStorageConfig = {}) {\n this.options = { ...options };\n this.config = config;\n }\n\n async isEnabled(): Promise<boolean> {\n /* istanbul ignore if */\n if (!getGlobalScope()) {\n return false;\n }\n\n CookieStorage.testValue = String(Date.now());\n const testCookieOptions = {\n ...this.options,\n expirationDays: 0.003, // expire in ~5 minutes\n };\n const testStorage = new CookieStorage<string>(testCookieOptions);\n const testKey = `AMP_TEST_${UUID().substring(0, 8)}`;\n try {\n await testStorage.set(testKey, CookieStorage.testValue);\n const value = await testStorage.get(testKey);\n return value === CookieStorage.testValue;\n } catch {\n /* istanbul ignore next */\n return false;\n } finally {\n await testStorage.remove(testKey);\n }\n }\n\n async get(key: string): Promise<T | undefined> {\n const value = await this.getRaw(key);\n if (!value) {\n return undefined;\n }\n try {\n const decodedValue = decodeCookieValue(value);\n if (decodedValue === undefined) {\n console.error(`Amplitude Logger [Error]: Failed to decode cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return JSON.parse(decodedValue);\n } catch {\n console.error(`Amplitude Logger [Error]: Failed to parse cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n }\n\n async getRaw(key: string): Promise<string | undefined> {\n const globalScope = getGlobalScope();\n\n // use CookieStore if available and enabled\n const globalScopeWithCookiesStore = globalScope as GlobalScopeWithCookieStore;\n try {\n const cookieStore = globalScopeWithCookiesStore?.cookieStore;\n if (cookieStore) {\n const cookies = await cookieStore.getAll(key);\n if (cookies) {\n /* istanbul ignore if */\n if (cookies.length > 1) {\n this.config.diagnosticsClient?.recordEvent('cookies.duplicate', {\n cookies: cookies.map((cookie) => cookie.domain),\n });\n this.config.diagnosticsClient?.increment('cookies.duplicate.occurrence.cookieStore');\n }\n\n for (const cookie of cookies) {\n if (isDomainEqual(cookie.domain, this.options.domain)) {\n return cookie.value;\n }\n }\n }\n }\n } catch (ignoreError) {\n /* istanbul ignore next */\n // if cookieStore had a surprise failure, fallback to document.cookie\n }\n\n const cookies = (globalScope?.document?.cookie.split('; ') ?? []).filter((c) => c.indexOf(key + '=') === 0);\n let match: string | undefined = undefined;\n\n // if matcher function is provided, use it to de-duplicate when there's more than one cookie\n /* istanbul ignore if */\n const duplicateResolverFn = this.config.duplicateResolverFn;\n if (typeof duplicateResolverFn === 'function' && cookies.length > 1) {\n match = cookies.find((c) => {\n try {\n const res = duplicateResolverFn(c.substring(key.length + 1));\n if (!res) {\n this.config.diagnosticsClient?.increment('cookies.duplicate.occurrence.document.cookie');\n }\n return res;\n } catch (ignoreError) {\n /* istanbul ignore next */\n return false;\n }\n });\n }\n\n // if match was not found, just get the first one that matches the key\n if (!match) {\n match = cookies[0];\n }\n if (!match) {\n return undefined;\n }\n return match.substring(key.length + 1);\n }\n\n async set(key: string, value: T | null): Promise<void> {\n try {\n const expirationDays = this.options.expirationDays ?? 0;\n const expires = value !== null ? expirationDays : -1;\n let expireDate: Date | undefined = undefined;\n if (expires) {\n const date = new Date();\n date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);\n expireDate = date;\n }\n let str = `${key}=${btoa(encodeURIComponent(JSON.stringify(value)))}`;\n if (expireDate) {\n str += `; expires=${expireDate.toUTCString()}`;\n }\n str += '; path=/';\n if (this.options.domain) {\n str += `; domain=${this.options.domain}`;\n }\n if (this.options.secure) {\n str += '; Secure';\n }\n if (this.options.sameSite) {\n str += `; SameSite=${this.options.sameSite}`;\n }\n const globalScope = getGlobalScope();\n if (globalScope) {\n globalScope.document.cookie = str;\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.error(`Amplitude Logger [Error]: Failed to set cookie for key: ${key}. Error: ${errorMessage}`);\n }\n }\n\n async remove(key: string): Promise<void> {\n await this.set(key, null);\n }\n\n async reset(): Promise<void> {\n return;\n }\n}\n\nconst decodeCookiesAsDefault = (value: string): string | undefined => {\n try {\n return decodeURIComponent(atob(value));\n } catch {\n return undefined;\n }\n};\n\nconst decodeCookiesWithDoubleUrlEncoding = (value: string): string | undefined => {\n // Modern Ruby (v7+) automatically encodes cookies with URL encoding by\n // https://api.rubyonrails.org/classes/ActionDispatch/Cookies.html\n try {\n return decodeURIComponent(atob(decodeURIComponent(value)));\n } catch {\n return undefined;\n }\n};\n\n/**\n * Decodes a cookie value that was encoded with btoa(encodeURIComponent(...)).\n * Handles both standard encoding and double URL encoding (used by Ruby Rails v7+).\n */\nexport const decodeCookieValue = (value: string): string | undefined => {\n return decodeCookiesAsDefault(value) ?? decodeCookiesWithDoubleUrlEncoding(value);\n};\n\n/**\n * Compares two domain strings for equality, ignoring leading dots.\n * This is useful for comparing cookie domains since \".example.com\" and \"example.com\"\n * are effectively equivalent for cookie scoping.\n */\nexport const isDomainEqual = (domain1: string | undefined, domain2: string | undefined): boolean => {\n if (!domain1 || !domain2) {\n return false;\n }\n const normalized1 = domain1.startsWith('.') ? domain1.substring(1) : domain1;\n const normalized2 = domain2.startsWith('.') ? domain2.substring(1) : domain2;\n return normalized1.toLowerCase() === normalized2.toLowerCase();\n};\n"]}
|
|
1
|
+
{"version":3,"file":"cookie.js","sourceRoot":"","sources":["../../../src/storage/cookie.ts"],"names":[],"mappings":";;;;AACA,gDAAiD;AACjD,sCAAqC;AAoBrC;IAIE,uBAAY,OAA8B,EAAE,MAAgC;QAAhC,uBAAA,EAAA,WAAgC;QAC1E,IAAI,CAAC,OAAO,wBAAQ,OAAO,CAAE,CAAC;QAC9B,IAAI,CAAC,MAAM,GAAG,MAAM,CAA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CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7E,OAAO,WAAW,CAAC,WAAW,EAAE,KAAK,WAAW,CAAC,WAAW,EAAE,CAAC;AACjE,CAAC,CAAC;AAPW,QAAA,aAAa,iBAOxB","sourcesContent":["import { Storage, CookieStorageOptions, CookieStorageConfig } from '../types/storage';\nimport { getGlobalScope } from '../global-scope';\nimport { UUID } from '../utils/uuid';\n\n// CookieStore is a Web API not included in standard TypeScript lib types\n// https://developer.mozilla.org/en-US/docs/Web/API/CookieStore\ninterface CookieStoreSetOptions {\n name: string;\n value: string;\n expires?: number;\n domain?: string;\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\ninterface CookieStore {\n getAll(key: string): Promise<CookieStoreSetOptions[] | undefined>;\n}\n\ntype GlobalScopeWithCookieStore = {\n cookieStore?: CookieStore;\n} & typeof global;\n\nexport class CookieStorage<T> implements Storage<T> {\n options: CookieStorageOptions;\n config: CookieStorageConfig;\n\n constructor(options?: CookieStorageOptions, config: CookieStorageConfig = {}) {\n this.options = { ...options };\n this.config = config;\n }\n\n async isEnabled(): Promise<boolean> {\n /* istanbul ignore if */\n if (!getGlobalScope()) {\n return false;\n }\n\n const testValue = String(Date.now());\n const testCookieOptions = {\n ...this.options,\n expirationDays: 0.003, // expire in ~5 minutes\n };\n const testStorage = new CookieStorage<string>(testCookieOptions);\n const testKey = `AMP_TEST_${UUID().substring(0, 8)}`;\n try {\n await testStorage.set(testKey, testValue);\n const value = await testStorage.get(testKey);\n return value === testValue;\n } catch {\n /* istanbul ignore next */\n return false;\n } finally {\n await testStorage.remove(testKey);\n }\n }\n\n async get(key: string): Promise<T | undefined> {\n const value = await this.getRaw(key);\n if (!value) {\n return undefined;\n }\n try {\n const decodedValue = decodeCookieValue(value);\n if (decodedValue === undefined) {\n console.error(`Amplitude Logger [Error]: Failed to decode cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return JSON.parse(decodedValue);\n } catch {\n console.error(`Amplitude Logger [Error]: Failed to parse cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n }\n\n async getRaw(key: string): Promise<string | undefined> {\n const globalScope = getGlobalScope();\n\n // use CookieStore if available and enabled\n const globalScopeWithCookiesStore = globalScope as GlobalScopeWithCookieStore;\n try {\n const cookieStore = globalScopeWithCookiesStore?.cookieStore;\n if (cookieStore) {\n const cookies = await cookieStore.getAll(key);\n if (cookies) {\n /* istanbul ignore if */\n if (cookies.length > 1) {\n this.config.diagnosticsClient?.recordEvent('cookies.duplicate', {\n cookies: cookies.map((cookie) => cookie.domain),\n });\n this.config.diagnosticsClient?.increment('cookies.duplicate.occurrence.cookieStore');\n }\n\n for (const cookie of cookies) {\n if (isDomainEqual(cookie.domain, this.options.domain)) {\n return cookie.value;\n }\n }\n }\n }\n } catch (ignoreError) {\n /* istanbul ignore next */\n // if cookieStore had a surprise failure, fallback to document.cookie\n }\n\n const cookies = (globalScope?.document?.cookie.split('; ') ?? []).filter((c) => c.indexOf(key + '=') === 0);\n let match: string | undefined = undefined;\n\n // if matcher function is provided, use it to de-duplicate when there's more than one cookie\n /* istanbul ignore if */\n const duplicateResolverFn = this.config.duplicateResolverFn;\n if (typeof duplicateResolverFn === 'function' && cookies.length > 1) {\n match = cookies.find((c) => {\n try {\n const res = duplicateResolverFn(c.substring(key.length + 1));\n if (!res) {\n this.config.diagnosticsClient?.increment('cookies.duplicate.occurrence.document.cookie');\n }\n return res;\n } catch (ignoreError) {\n /* istanbul ignore next */\n return false;\n }\n });\n }\n\n // if match was not found, just get the first one that matches the key\n if (!match) {\n match = cookies[0];\n }\n if (!match) {\n return undefined;\n }\n return match.substring(key.length + 1);\n }\n\n async set(key: string, value: T | null): Promise<void> {\n try {\n const expirationDays = this.options.expirationDays ?? 0;\n const expires = value !== null ? expirationDays : -1;\n let expireDate: Date | undefined = undefined;\n if (expires) {\n const date = new Date();\n date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);\n expireDate = date;\n }\n let str = `${key}=${btoa(encodeURIComponent(JSON.stringify(value)))}`;\n if (expireDate) {\n str += `; expires=${expireDate.toUTCString()}`;\n }\n str += '; path=/';\n if (this.options.domain) {\n str += `; domain=${this.options.domain}`;\n }\n if (this.options.secure) {\n str += '; Secure';\n }\n if (this.options.sameSite) {\n str += `; SameSite=${this.options.sameSite}`;\n }\n const globalScope = getGlobalScope();\n if (globalScope) {\n globalScope.document.cookie = str;\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.error(`Amplitude Logger [Error]: Failed to set cookie for key: ${key}. Error: ${errorMessage}`);\n }\n }\n\n async remove(key: string): Promise<void> {\n await this.set(key, null);\n }\n\n async reset(): Promise<void> {\n return;\n }\n}\n\nconst decodeCookiesAsDefault = (value: string): string | undefined => {\n try {\n return decodeURIComponent(atob(value));\n } catch {\n return undefined;\n }\n};\n\nconst decodeCookiesWithDoubleUrlEncoding = (value: string): string | undefined => {\n // Modern Ruby (v7+) automatically encodes cookies with URL encoding by\n // https://api.rubyonrails.org/classes/ActionDispatch/Cookies.html\n try {\n return decodeURIComponent(atob(decodeURIComponent(value)));\n } catch {\n return undefined;\n }\n};\n\n/**\n * Decodes a cookie value that was encoded with btoa(encodeURIComponent(...)).\n * Handles both standard encoding and double URL encoding (used by Ruby Rails v7+).\n */\nexport const decodeCookieValue = (value: string): string | undefined => {\n return decodeCookiesAsDefault(value) ?? decodeCookiesWithDoubleUrlEncoding(value);\n};\n\n/**\n * Compares two domain strings for equality, ignoring leading dots.\n * This is useful for comparing cookie domains since \".example.com\" and \"example.com\"\n * are effectively equivalent for cookie scoping.\n */\nexport const isDomainEqual = (domain1: string | undefined, domain2: string | undefined): boolean => {\n if (!domain1 || !domain2) {\n return false;\n }\n const normalized1 = domain1.startsWith('.') ? domain1.substring(1) : domain1;\n const normalized2 = domain2.startsWith('.') ? domain2.substring(1) : domain2;\n return normalized1.toLowerCase() === normalized2.toLowerCase();\n};\n"]}
|
|
@@ -58,6 +58,39 @@ export interface BrowserClient extends Client {
|
|
|
58
58
|
* ```
|
|
59
59
|
*/
|
|
60
60
|
getIdentity(): AnalyticsIdentity;
|
|
61
|
+
/**
|
|
62
|
+
* Sets the identity (userId, deviceId, and/or userProperties).
|
|
63
|
+
* This is a unified shortcut for `setUserId()`, `setDeviceId()`, and setting user properties.
|
|
64
|
+
* When userProperties change, an identify event is automatically sent.
|
|
65
|
+
*
|
|
66
|
+
* **Important limitation:** When userProperties are replaced, the local state is fully replaced
|
|
67
|
+
* but the identify event sent to the server only includes `$set` operations for the new properties.
|
|
68
|
+
* Properties removed from the local state are **not** `$unset` on the server.
|
|
69
|
+
*
|
|
70
|
+
* For example, changing from `{plan: 'premium', theme: 'dark'}` to `{plan: 'basic'}` removes
|
|
71
|
+
* `theme` locally but leaves it on the server. To remove a property from the server, use
|
|
72
|
+
* `identify()` with `Identify.unset()` directly.
|
|
73
|
+
*
|
|
74
|
+
* ```typescript
|
|
75
|
+
* // Set user properties (auto-sends identify event with $set)
|
|
76
|
+
* setIdentity({ userProperties: { plan: 'premium' } });
|
|
77
|
+
*
|
|
78
|
+
* // Set userId (equivalent to setUserId('user-123'))
|
|
79
|
+
* setIdentity({ userId: 'user-123' });
|
|
80
|
+
*
|
|
81
|
+
* // Set deviceId (equivalent to setDeviceId('device-456'))
|
|
82
|
+
* setIdentity({ deviceId: 'device-456' });
|
|
83
|
+
*
|
|
84
|
+
* // Set multiple identity fields together
|
|
85
|
+
* setIdentity({ userId: 'user-123', deviceId: 'device-456', userProperties: { name: 'John' } });
|
|
86
|
+
*
|
|
87
|
+
* // To remove a property from the server, use identify() directly:
|
|
88
|
+
* const identify = new Identify();
|
|
89
|
+
* identify.unset('theme');
|
|
90
|
+
* amplitude.identify(identify);
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
setIdentity(identity: Partial<AnalyticsIdentity>): void;
|
|
61
94
|
/**
|
|
62
95
|
* Returns the current optOut config value.
|
|
63
96
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-client.d.ts","sourceRoot":"","sources":["../../../../src/types/client/browser-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAEzE,MAAM,WAAW,aAAc,SAAQ,MAAM;IAC3C;;;;;;;OAOG;IACH,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAEtE,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAEvF;;;;;;;;;;;;;;;;OAgBG;IACH,YAAY,CAAC,SAAS,EAAE,sBAAsB,GAAG,IAAI,CAAC;IAEtD;;;;;;;;;;;;;;;;OAgBG;IACH,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,aAAa,EAAE,aAAa,CAAC,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAEzE;;;;;;OAMG;IACH,WAAW,IAAI,iBAAiB,CAAC;IAEjC;;;;;;OAMG;IACH,SAAS,IAAI,OAAO,GAAG,SAAS,CAAC;IAEjC;;;;;;;OAOG;IACH,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CACrD"}
|
|
1
|
+
{"version":3,"file":"browser-client.d.ts","sourceRoot":"","sources":["../../../../src/types/client/browser-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAEzE,MAAM,WAAW,aAAc,SAAQ,MAAM;IAC3C;;;;;;;OAOG;IACH,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAEtE,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAEvF;;;;;;;;;;;;;;;;OAgBG;IACH,YAAY,CAAC,SAAS,EAAE,sBAAsB,GAAG,IAAI,CAAC;IAEtD;;;;;;;;;;;;;;;;OAgBG;IACH,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,aAAa,EAAE,aAAa,CAAC,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAEzE;;;;;;OAMG;IACH,WAAW,IAAI,iBAAiB,CAAC;IAEjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+BG;IACH,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC;IAExD;;;;;;OAMG;IACH,SAAS,IAAI,OAAO,GAAG,SAAS,CAAC;IAEjC;;;;;;;OAOG;IACH,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CACrD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-client.js","sourceRoot":"","sources":["../../../../src/types/client/browser-client.ts"],"names":[],"mappings":"","sourcesContent":["import { TransportTypeOrOptions } from '../transport';\nimport { Client } from './core-client';\nimport { AnalyticsIdentity, Plugin } from '../plugin';\nimport { AmplitudeReturn } from '../../utils/return-wrapper';\nimport { BrowserConfig, BrowserOptions } from '../config/browser-config';\n\nexport interface BrowserClient extends Client {\n /**\n * Initializes the Amplitude SDK with your apiKey, optional configurations.\n * This method must be called before any other operations.\n *\n * ```typescript\n * await init(API_KEY, options).promise;\n * ```\n */\n init(apiKey: string, options?: BrowserOptions): AmplitudeReturn<void>;\n\n init(apiKey: string, userId?: string, options?: BrowserOptions): AmplitudeReturn<void>;\n\n /**\n * Sets the network transport type for events.\n *\n * ```typescript\n * // Use Fetch API\n * setTransport('fetch');\n *\n * // Use XMLHttpRequest API\n * setTransport('xhr');\n *\n * // Use navigator.sendBeacon API\n * setTransport('beacon');\n *\n * // Use Fetch API with custom headers\n * setTransport({ type: 'fetch', headers: { 'X-Custom-Header': 'value' } });\n * ```\n */\n setTransport(transport: TransportTypeOrOptions): void;\n\n /**\n * Adds a new plugin.\n *\n * ```typescript\n * const plugin = {\n * name: 'my-plugin',\n * type: 'enrichment',\n * async setup(config: BrowserConfig, amplitude: BrowserClient) {\n * return;\n * },\n * async execute(event: Event) {\n * return event;\n * },\n * };\n * amplitude.add(plugin);\n * ```\n */\n add(plugin: Plugin<BrowserClient, BrowserConfig>): AmplitudeReturn<void>;\n\n /**\n * Returns the current identity.\n *\n * ```typescript\n * const identity = getIdentity();\n * ```\n */\n getIdentity(): AnalyticsIdentity;\n\n /**\n * Returns the current optOut config value.\n *\n * ```typescript\n * const optOut = getOptOut();\n * ```\n */\n getOptOut(): boolean | undefined;\n\n /**\n * @experimental\n * WARNING: This method is for internal testing only and is not part of the public API.\n * It may be changed or removed at any time without notice.\n *\n * Sets the diagnostics sample rate before amplitude.init()\n * @param sampleRate - The sample rate to set\n */\n _setDiagnosticsSampleRate(sampleRate: number): void;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"browser-client.js","sourceRoot":"","sources":["../../../../src/types/client/browser-client.ts"],"names":[],"mappings":"","sourcesContent":["import { TransportTypeOrOptions } from '../transport';\nimport { Client } from './core-client';\nimport { AnalyticsIdentity, Plugin } from '../plugin';\nimport { AmplitudeReturn } from '../../utils/return-wrapper';\nimport { BrowserConfig, BrowserOptions } from '../config/browser-config';\n\nexport interface BrowserClient extends Client {\n /**\n * Initializes the Amplitude SDK with your apiKey, optional configurations.\n * This method must be called before any other operations.\n *\n * ```typescript\n * await init(API_KEY, options).promise;\n * ```\n */\n init(apiKey: string, options?: BrowserOptions): AmplitudeReturn<void>;\n\n init(apiKey: string, userId?: string, options?: BrowserOptions): AmplitudeReturn<void>;\n\n /**\n * Sets the network transport type for events.\n *\n * ```typescript\n * // Use Fetch API\n * setTransport('fetch');\n *\n * // Use XMLHttpRequest API\n * setTransport('xhr');\n *\n * // Use navigator.sendBeacon API\n * setTransport('beacon');\n *\n * // Use Fetch API with custom headers\n * setTransport({ type: 'fetch', headers: { 'X-Custom-Header': 'value' } });\n * ```\n */\n setTransport(transport: TransportTypeOrOptions): void;\n\n /**\n * Adds a new plugin.\n *\n * ```typescript\n * const plugin = {\n * name: 'my-plugin',\n * type: 'enrichment',\n * async setup(config: BrowserConfig, amplitude: BrowserClient) {\n * return;\n * },\n * async execute(event: Event) {\n * return event;\n * },\n * };\n * amplitude.add(plugin);\n * ```\n */\n add(plugin: Plugin<BrowserClient, BrowserConfig>): AmplitudeReturn<void>;\n\n /**\n * Returns the current identity.\n *\n * ```typescript\n * const identity = getIdentity();\n * ```\n */\n getIdentity(): AnalyticsIdentity;\n\n /**\n * Sets the identity (userId, deviceId, and/or userProperties).\n * This is a unified shortcut for `setUserId()`, `setDeviceId()`, and setting user properties.\n * When userProperties change, an identify event is automatically sent.\n *\n * **Important limitation:** When userProperties are replaced, the local state is fully replaced\n * but the identify event sent to the server only includes `$set` operations for the new properties.\n * Properties removed from the local state are **not** `$unset` on the server.\n *\n * For example, changing from `{plan: 'premium', theme: 'dark'}` to `{plan: 'basic'}` removes\n * `theme` locally but leaves it on the server. To remove a property from the server, use\n * `identify()` with `Identify.unset()` directly.\n *\n * ```typescript\n * // Set user properties (auto-sends identify event with $set)\n * setIdentity({ userProperties: { plan: 'premium' } });\n *\n * // Set userId (equivalent to setUserId('user-123'))\n * setIdentity({ userId: 'user-123' });\n *\n * // Set deviceId (equivalent to setDeviceId('device-456'))\n * setIdentity({ deviceId: 'device-456' });\n *\n * // Set multiple identity fields together\n * setIdentity({ userId: 'user-123', deviceId: 'device-456', userProperties: { name: 'John' } });\n *\n * // To remove a property from the server, use identify() directly:\n * const identify = new Identify();\n * identify.unset('theme');\n * amplitude.identify(identify);\n * ```\n */\n setIdentity(identity: Partial<AnalyticsIdentity>): void;\n\n /**\n * Returns the current optOut config value.\n *\n * ```typescript\n * const optOut = getOptOut();\n * ```\n */\n getOptOut(): boolean | undefined;\n\n /**\n * @experimental\n * WARNING: This method is for internal testing only and is not part of the public API.\n * It may be changed or removed at any time without notice.\n *\n * Sets the diagnostics sample rate before amplitude.init()\n * @param sampleRate - The sample rate to set\n */\n _setDiagnosticsSampleRate(sampleRate: number): void;\n}\n"]}
|
package/lib/esm/core-client.d.ts
CHANGED
|
@@ -16,6 +16,13 @@ export declare class AmplitudeCore implements CoreClient, PluginHost {
|
|
|
16
16
|
isReady: boolean;
|
|
17
17
|
protected q: Array<CallableFunction | typeof returnWrapper>;
|
|
18
18
|
protected dispatchQ: Array<CallableFunction>;
|
|
19
|
+
/**
|
|
20
|
+
* Current user properties (operation-applied, flat key-value).
|
|
21
|
+
* Only used by client-side SDKs; server SDKs may leave this undefined.
|
|
22
|
+
*/
|
|
23
|
+
userProperties: {
|
|
24
|
+
[key: string]: any;
|
|
25
|
+
} | undefined;
|
|
19
26
|
constructor(name?: string);
|
|
20
27
|
protected _init(config: IConfig): Promise<void>;
|
|
21
28
|
runQueuedFunctions(queueName: 'q' | 'dispatchQ'): Promise<void>;
|
|
@@ -39,8 +46,9 @@ export declare class AmplitudeCore implements CoreClient, PluginHost {
|
|
|
39
46
|
* This is a best-effort api that only supports $set, $clearAll, and $unset.
|
|
40
47
|
* Other operations are not supported and are ignored.
|
|
41
48
|
*
|
|
49
|
+
* Operations are applied on top of current client state (this.userProperties).
|
|
42
50
|
*
|
|
43
|
-
* @param userProperties The
|
|
51
|
+
* @param userProperties The new user properties object from identify() or setIdentity().
|
|
44
52
|
* @returns A key-value object user properties without operations.
|
|
45
53
|
*
|
|
46
54
|
* @example
|
|
@@ -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,4BAA4B,CAAC;AACrD,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;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAStC,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AACpE,qBAAa,aAAc,YAAW,UAAU,EAAE,UAAU;IAC1D,SAAS,CAAC,YAAY,UAAS;IAC/B,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;IAGvB,MAAM,EAAE,OAAO,CAAC;IAGhB,QAAQ,EAAE,QAAQ,CAAC;IACnB,OAAO,UAAS;IAChB,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,gBAAgB,GAAG,OAAO,aAAa,CAAC,CAAM;IACjE,SAAS,CAAC,SAAS,EAAE,KAAK,CAAC,gBAAgB,CAAC,CAAM;
|
|
1
|
+
{"version":3,"file":"core-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;IAUxC,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,WAAW,EAAE;QAAE,KAAK,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;KAAE,GAAG,CAAC,EAAE;CAGzE"}
|
package/lib/esm/core-client.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { __awaiter, __generator, __values } from "tslib";
|
|
1
|
+
import { __assign, __awaiter, __generator, __values } from "tslib";
|
|
2
2
|
import { IdentifyOperation, SpecialEventType, } from './types/event/event';
|
|
3
3
|
import { OrderedIdentifyOperations } from './identify';
|
|
4
4
|
import { CLIENT_NOT_INITIALIZED, OPT_OUT_MESSAGE } from './types/messages';
|
|
@@ -88,10 +88,14 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
88
88
|
};
|
|
89
89
|
AmplitudeCore.prototype.track = function (eventInput, eventProperties, eventOptions) {
|
|
90
90
|
var event = createTrackEvent(eventInput, eventProperties, eventOptions);
|
|
91
|
+
// Update client user properties immediately and synchronously
|
|
92
|
+
this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);
|
|
91
93
|
return returnWrapper(this.dispatch(event));
|
|
92
94
|
};
|
|
93
95
|
AmplitudeCore.prototype.identify = function (identify, eventOptions) {
|
|
94
96
|
var event = createIdentifyEvent(identify, eventOptions);
|
|
97
|
+
// Update client user properties immediately and synchronously
|
|
98
|
+
this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);
|
|
95
99
|
return returnWrapper(this.dispatch(event));
|
|
96
100
|
};
|
|
97
101
|
AmplitudeCore.prototype.groupIdentify = function (groupType, groupName, identify, eventOptions) {
|
|
@@ -100,6 +104,8 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
100
104
|
};
|
|
101
105
|
AmplitudeCore.prototype.setGroup = function (groupType, groupName, eventOptions) {
|
|
102
106
|
var event = createGroupEvent(groupType, groupName, eventOptions);
|
|
107
|
+
// Update client user properties immediately and synchronously
|
|
108
|
+
this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);
|
|
103
109
|
return returnWrapper(this.dispatch(event));
|
|
104
110
|
};
|
|
105
111
|
AmplitudeCore.prototype.revenue = function (revenue, eventOptions) {
|
|
@@ -153,8 +159,9 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
153
159
|
* This is a best-effort api that only supports $set, $clearAll, and $unset.
|
|
154
160
|
* Other operations are not supported and are ignored.
|
|
155
161
|
*
|
|
162
|
+
* Operations are applied on top of current client state (this.userProperties).
|
|
156
163
|
*
|
|
157
|
-
* @param userProperties The
|
|
164
|
+
* @param userProperties The new user properties object from identify() or setIdentity().
|
|
158
165
|
* @returns A key-value object user properties without operations.
|
|
159
166
|
*
|
|
160
167
|
* @example
|
|
@@ -171,7 +178,9 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
171
178
|
* }
|
|
172
179
|
*/
|
|
173
180
|
AmplitudeCore.prototype.getOperationAppliedUserProperties = function (userProperties) {
|
|
174
|
-
var
|
|
181
|
+
var _a;
|
|
182
|
+
var base = (_a = this.userProperties) !== null && _a !== void 0 ? _a : {};
|
|
183
|
+
var updatedProperties = __assign({}, base);
|
|
175
184
|
if (userProperties === undefined) {
|
|
176
185
|
return updatedProperties;
|
|
177
186
|
}
|
|
@@ -217,7 +226,7 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
217
226
|
};
|
|
218
227
|
AmplitudeCore.prototype.process = function (event) {
|
|
219
228
|
return __awaiter(this, void 0, void 0, function () {
|
|
220
|
-
var
|
|
229
|
+
var result, e_2, message, result;
|
|
221
230
|
return __generator(this, function (_a) {
|
|
222
231
|
switch (_a.label) {
|
|
223
232
|
case 0:
|
|
@@ -227,8 +236,9 @@ var AmplitudeCore = /** @class */ (function () {
|
|
|
227
236
|
return [2 /*return*/, buildResult(event, 0, OPT_OUT_MESSAGE)];
|
|
228
237
|
}
|
|
229
238
|
if (event.event_type === SpecialEventType.IDENTIFY) {
|
|
230
|
-
|
|
231
|
-
|
|
239
|
+
// Do not update this.userProperties here.
|
|
240
|
+
// It is only set synchronously in identify() or setIdentity()
|
|
241
|
+
this.timeline.onIdentityChanged({ userProperties: this.userProperties });
|
|
232
242
|
}
|
|
233
243
|
return [4 /*yield*/, this.timeline.push(event)];
|
|
234
244
|
case 1:
|
|
@@ -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,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAEvD;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,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QArC/B,IAAI,CAAC,QAAQ,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAEe,6BAAK,GAArB,UAAsB,MAAe;;;;;wBACnC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;wBACrB,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;wBAC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AI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACzD,OAAO;SACR;QACD,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAED,kCAAU,GAAV,UAAW,MAAe;QACxB,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,KAAK,MAAM,EAAE;YACjC,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;YACrC,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;SACvC;IACH,CAAC;IAED,6BAAK,GAAL;QACE,OAAO,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAC9C,CAAC;IAED,8BAAM,GAAN,UAAO,IAAY;QACjB,IAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,UAAC,MAAM,IAAK,OAAA,MAAM,CAAC,IAAI,KAAK,IAAI,EAApB,CAAoB,CAAC,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 './types/config/core-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 { returnWrapper } from './utils/return-wrapper';\nimport { CoreClient, PluginHost } from './types/client/core-client';\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.config.optOut = Boolean(optOut);\n this.timeline.onOptOutChanged(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,EAAE,aAA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,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;YACrC,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;SACvC;IACH,CAAC;IAED,6BAAK,GAAL;QACE,OAAO,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAC9C,CAAC;IAED,8BAAM,GAAN,UAAO,IAAY;QACjB,IAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,UAAC,MAAM,IAAK,OAAA,MAAM,CAAC,IAAI,KAAK,IAAI,EAApB,CAAoB,CAAC,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,AA9QD,IA8QC","sourcesContent":["import { Plugin } from './types/plugin';\nimport { IConfig } from './types/config/core-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 { returnWrapper } from './utils/return-wrapper';\nimport { CoreClient, PluginHost } from './types/client/core-client';\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 /**\n * Current user properties (operation-applied, flat key-value).\n * Only used by client-side SDKs; server SDKs may leave this undefined.\n */\n userProperties: { [key: string]: any } | undefined;\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 // Update client user properties immediately and synchronously\n this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);\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 // Update client user properties immediately and synchronously\n this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);\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 // Update client user properties immediately and synchronously\n this.userProperties = this.getOperationAppliedUserProperties(event.user_properties);\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 * Operations are applied on top of current client state (this.userProperties).\n *\n * @param userProperties The new user properties object from identify() or setIdentity().\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 base = this.userProperties ?? {};\n const updatedProperties: { [key: string]: any } = { ...base };\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 // Do not update this.userProperties here.\n // It is only set synchronously in identify() or setIdentity()\n this.timeline.onIdentityChanged({ userProperties: this.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.config.optOut = Boolean(optOut);\n this.timeline.onOptOutChanged(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"]}
|
|
@@ -2,7 +2,6 @@ import { Storage, CookieStorageOptions, CookieStorageConfig } from '../types/sto
|
|
|
2
2
|
export declare class CookieStorage<T> implements Storage<T> {
|
|
3
3
|
options: CookieStorageOptions;
|
|
4
4
|
config: CookieStorageConfig;
|
|
5
|
-
private static testValue;
|
|
6
5
|
constructor(options?: CookieStorageOptions, config?: CookieStorageConfig);
|
|
7
6
|
isEnabled(): Promise<boolean>;
|
|
8
7
|
get(key: string): Promise<T | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookie.d.ts","sourceRoot":"","sources":["../../../src/storage/cookie.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAsBtF,qBAAa,aAAa,CAAC,CAAC,CAAE,YAAW,OAAO,CAAC,CAAC,CAAC;IACjD,OAAO,EAAE,oBAAoB,CAAC;IAC9B,MAAM,EAAE,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"cookie.d.ts","sourceRoot":"","sources":["../../../src/storage/cookie.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAsBtF,qBAAa,aAAa,CAAC,CAAC,CAAE,YAAW,OAAO,CAAC,CAAC,CAAC;IACjD,OAAO,EAAE,oBAAoB,CAAC;IAC9B,MAAM,EAAE,mBAAmB,CAAC;gBAEhB,OAAO,CAAC,EAAE,oBAAoB,EAAE,MAAM,GAAE,mBAAwB;IAKtE,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC;IAyB7B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC;IAmBxC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IA6DhD,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAkChD,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIlC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAG7B;AAoBD;;;GAGG;AACH,eAAO,MAAM,iBAAiB,UAAW,MAAM,KAAG,MAAM,GAAG,SAE1D,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,aAAa,YAAa,MAAM,GAAG,SAAS,WAAW,MAAM,GAAG,SAAS,KAAG,OAOxF,CAAC"}
|
|
@@ -9,7 +9,7 @@ var CookieStorage = /** @class */ (function () {
|
|
|
9
9
|
}
|
|
10
10
|
CookieStorage.prototype.isEnabled = function () {
|
|
11
11
|
return __awaiter(this, void 0, void 0, function () {
|
|
12
|
-
var testCookieOptions, testStorage, testKey, value, _a;
|
|
12
|
+
var testValue, testCookieOptions, testStorage, testKey, value, _a;
|
|
13
13
|
return __generator(this, function (_b) {
|
|
14
14
|
switch (_b.label) {
|
|
15
15
|
case 0:
|
|
@@ -17,20 +17,20 @@ var CookieStorage = /** @class */ (function () {
|
|
|
17
17
|
if (!getGlobalScope()) {
|
|
18
18
|
return [2 /*return*/, false];
|
|
19
19
|
}
|
|
20
|
-
|
|
20
|
+
testValue = String(Date.now());
|
|
21
21
|
testCookieOptions = __assign(__assign({}, this.options), { expirationDays: 0.003 });
|
|
22
22
|
testStorage = new CookieStorage(testCookieOptions);
|
|
23
23
|
testKey = "AMP_TEST_".concat(UUID().substring(0, 8));
|
|
24
24
|
_b.label = 1;
|
|
25
25
|
case 1:
|
|
26
26
|
_b.trys.push([1, 4, 5, 7]);
|
|
27
|
-
return [4 /*yield*/, testStorage.set(testKey,
|
|
27
|
+
return [4 /*yield*/, testStorage.set(testKey, testValue)];
|
|
28
28
|
case 2:
|
|
29
29
|
_b.sent();
|
|
30
30
|
return [4 /*yield*/, testStorage.get(testKey)];
|
|
31
31
|
case 3:
|
|
32
32
|
value = _b.sent();
|
|
33
|
-
return [2 /*return*/, value ===
|
|
33
|
+
return [2 /*return*/, value === testValue];
|
|
34
34
|
case 4:
|
|
35
35
|
_a = _b.sent();
|
|
36
36
|
/* istanbul ignore next */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookie.js","sourceRoot":"","sources":["../../../src/storage/cookie.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAoBrC;IAKE,uBAAY,OAA8B,EAAE,MAAgC;QAAhC,uBAAA,EAAA,WAAgC;QAC1E,IAAI,CAAC,OAAO,gBAAQ,OAAO,CAAE,CAAC;QAC9B,IAA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CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7E,OAAO,WAAW,CAAC,WAAW,EAAE,KAAK,WAAW,CAAC,WAAW,EAAE,CAAC;AACjE,CAAC,CAAC","sourcesContent":["import { Storage, CookieStorageOptions, CookieStorageConfig } from '../types/storage';\nimport { getGlobalScope } from '../global-scope';\nimport { UUID } from '../utils/uuid';\n\n// CookieStore is a Web API not included in standard TypeScript lib types\n// https://developer.mozilla.org/en-US/docs/Web/API/CookieStore\ninterface CookieStoreSetOptions {\n name: string;\n value: string;\n expires?: number;\n domain?: string;\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\ninterface CookieStore {\n getAll(key: string): Promise<CookieStoreSetOptions[] | undefined>;\n}\n\ntype GlobalScopeWithCookieStore = {\n cookieStore?: CookieStore;\n} & typeof global;\n\nexport class CookieStorage<T> implements Storage<T> {\n options: CookieStorageOptions;\n config: CookieStorageConfig;\n private static testValue: undefined | string;\n\n constructor(options?: CookieStorageOptions, config: CookieStorageConfig = {}) {\n this.options = { ...options };\n this.config = config;\n }\n\n async isEnabled(): Promise<boolean> {\n /* istanbul ignore if */\n if (!getGlobalScope()) {\n return false;\n }\n\n CookieStorage.testValue = String(Date.now());\n const testCookieOptions = {\n ...this.options,\n expirationDays: 0.003, // expire in ~5 minutes\n };\n const testStorage = new CookieStorage<string>(testCookieOptions);\n const testKey = `AMP_TEST_${UUID().substring(0, 8)}`;\n try {\n await testStorage.set(testKey, CookieStorage.testValue);\n const value = await testStorage.get(testKey);\n return value === CookieStorage.testValue;\n } catch {\n /* istanbul ignore next */\n return false;\n } finally {\n await testStorage.remove(testKey);\n }\n }\n\n async get(key: string): Promise<T | undefined> {\n const value = await this.getRaw(key);\n if (!value) {\n return undefined;\n }\n try {\n const decodedValue = decodeCookieValue(value);\n if (decodedValue === undefined) {\n console.error(`Amplitude Logger [Error]: Failed to decode cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return JSON.parse(decodedValue);\n } catch {\n console.error(`Amplitude Logger [Error]: Failed to parse cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n }\n\n async getRaw(key: string): Promise<string | undefined> {\n const globalScope = getGlobalScope();\n\n // use CookieStore if available and enabled\n const globalScopeWithCookiesStore = globalScope as GlobalScopeWithCookieStore;\n try {\n const cookieStore = globalScopeWithCookiesStore?.cookieStore;\n if (cookieStore) {\n const cookies = await cookieStore.getAll(key);\n if (cookies) {\n /* istanbul ignore if */\n if (cookies.length > 1) {\n this.config.diagnosticsClient?.recordEvent('cookies.duplicate', {\n cookies: cookies.map((cookie) => cookie.domain),\n });\n this.config.diagnosticsClient?.increment('cookies.duplicate.occurrence.cookieStore');\n }\n\n for (const cookie of cookies) {\n if (isDomainEqual(cookie.domain, this.options.domain)) {\n return cookie.value;\n }\n }\n }\n }\n } catch (ignoreError) {\n /* istanbul ignore next */\n // if cookieStore had a surprise failure, fallback to document.cookie\n }\n\n const cookies = (globalScope?.document?.cookie.split('; ') ?? []).filter((c) => c.indexOf(key + '=') === 0);\n let match: string | undefined = undefined;\n\n // if matcher function is provided, use it to de-duplicate when there's more than one cookie\n /* istanbul ignore if */\n const duplicateResolverFn = this.config.duplicateResolverFn;\n if (typeof duplicateResolverFn === 'function' && cookies.length > 1) {\n match = cookies.find((c) => {\n try {\n const res = duplicateResolverFn(c.substring(key.length + 1));\n if (!res) {\n this.config.diagnosticsClient?.increment('cookies.duplicate.occurrence.document.cookie');\n }\n return res;\n } catch (ignoreError) {\n /* istanbul ignore next */\n return false;\n }\n });\n }\n\n // if match was not found, just get the first one that matches the key\n if (!match) {\n match = cookies[0];\n }\n if (!match) {\n return undefined;\n }\n return match.substring(key.length + 1);\n }\n\n async set(key: string, value: T | null): Promise<void> {\n try {\n const expirationDays = this.options.expirationDays ?? 0;\n const expires = value !== null ? expirationDays : -1;\n let expireDate: Date | undefined = undefined;\n if (expires) {\n const date = new Date();\n date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);\n expireDate = date;\n }\n let str = `${key}=${btoa(encodeURIComponent(JSON.stringify(value)))}`;\n if (expireDate) {\n str += `; expires=${expireDate.toUTCString()}`;\n }\n str += '; path=/';\n if (this.options.domain) {\n str += `; domain=${this.options.domain}`;\n }\n if (this.options.secure) {\n str += '; Secure';\n }\n if (this.options.sameSite) {\n str += `; SameSite=${this.options.sameSite}`;\n }\n const globalScope = getGlobalScope();\n if (globalScope) {\n globalScope.document.cookie = str;\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.error(`Amplitude Logger [Error]: Failed to set cookie for key: ${key}. Error: ${errorMessage}`);\n }\n }\n\n async remove(key: string): Promise<void> {\n await this.set(key, null);\n }\n\n async reset(): Promise<void> {\n return;\n }\n}\n\nconst decodeCookiesAsDefault = (value: string): string | undefined => {\n try {\n return decodeURIComponent(atob(value));\n } catch {\n return undefined;\n }\n};\n\nconst decodeCookiesWithDoubleUrlEncoding = (value: string): string | undefined => {\n // Modern Ruby (v7+) automatically encodes cookies with URL encoding by\n // https://api.rubyonrails.org/classes/ActionDispatch/Cookies.html\n try {\n return decodeURIComponent(atob(decodeURIComponent(value)));\n } catch {\n return undefined;\n }\n};\n\n/**\n * Decodes a cookie value that was encoded with btoa(encodeURIComponent(...)).\n * Handles both standard encoding and double URL encoding (used by Ruby Rails v7+).\n */\nexport const decodeCookieValue = (value: string): string | undefined => {\n return decodeCookiesAsDefault(value) ?? decodeCookiesWithDoubleUrlEncoding(value);\n};\n\n/**\n * Compares two domain strings for equality, ignoring leading dots.\n * This is useful for comparing cookie domains since \".example.com\" and \"example.com\"\n * are effectively equivalent for cookie scoping.\n */\nexport const isDomainEqual = (domain1: string | undefined, domain2: string | undefined): boolean => {\n if (!domain1 || !domain2) {\n return false;\n }\n const normalized1 = domain1.startsWith('.') ? domain1.substring(1) : domain1;\n const normalized2 = domain2.startsWith('.') ? domain2.substring(1) : domain2;\n return normalized1.toLowerCase() === normalized2.toLowerCase();\n};\n"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AE;QACxB,OAAO,KAAK,CAAC;KACd;IACD,IAAM,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7E,IAAM,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7E,OAAO,WAAW,CAAC,WAAW,EAAE,KAAK,WAAW,CAAC,WAAW,EAAE,CAAC;AACjE,CAAC,CAAC","sourcesContent":["import { Storage, CookieStorageOptions, CookieStorageConfig } from '../types/storage';\nimport { getGlobalScope } from '../global-scope';\nimport { UUID } from '../utils/uuid';\n\n// CookieStore is a Web API not included in standard TypeScript lib types\n// https://developer.mozilla.org/en-US/docs/Web/API/CookieStore\ninterface CookieStoreSetOptions {\n name: string;\n value: string;\n expires?: number;\n domain?: string;\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\ninterface CookieStore {\n getAll(key: string): Promise<CookieStoreSetOptions[] | undefined>;\n}\n\ntype GlobalScopeWithCookieStore = {\n cookieStore?: CookieStore;\n} & typeof global;\n\nexport class CookieStorage<T> implements Storage<T> {\n options: CookieStorageOptions;\n config: CookieStorageConfig;\n\n constructor(options?: CookieStorageOptions, config: CookieStorageConfig = {}) {\n this.options = { ...options };\n this.config = config;\n }\n\n async isEnabled(): Promise<boolean> {\n /* istanbul ignore if */\n if (!getGlobalScope()) {\n return false;\n }\n\n const testValue = String(Date.now());\n const testCookieOptions = {\n ...this.options,\n expirationDays: 0.003, // expire in ~5 minutes\n };\n const testStorage = new CookieStorage<string>(testCookieOptions);\n const testKey = `AMP_TEST_${UUID().substring(0, 8)}`;\n try {\n await testStorage.set(testKey, testValue);\n const value = await testStorage.get(testKey);\n return value === testValue;\n } catch {\n /* istanbul ignore next */\n return false;\n } finally {\n await testStorage.remove(testKey);\n }\n }\n\n async get(key: string): Promise<T | undefined> {\n const value = await this.getRaw(key);\n if (!value) {\n return undefined;\n }\n try {\n const decodedValue = decodeCookieValue(value);\n if (decodedValue === undefined) {\n console.error(`Amplitude Logger [Error]: Failed to decode cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return JSON.parse(decodedValue);\n } catch {\n console.error(`Amplitude Logger [Error]: Failed to parse cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n }\n\n async getRaw(key: string): Promise<string | undefined> {\n const globalScope = getGlobalScope();\n\n // use CookieStore if available and enabled\n const globalScopeWithCookiesStore = globalScope as GlobalScopeWithCookieStore;\n try {\n const cookieStore = globalScopeWithCookiesStore?.cookieStore;\n if (cookieStore) {\n const cookies = await cookieStore.getAll(key);\n if (cookies) {\n /* istanbul ignore if */\n if (cookies.length > 1) {\n this.config.diagnosticsClient?.recordEvent('cookies.duplicate', {\n cookies: cookies.map((cookie) => cookie.domain),\n });\n this.config.diagnosticsClient?.increment('cookies.duplicate.occurrence.cookieStore');\n }\n\n for (const cookie of cookies) {\n if (isDomainEqual(cookie.domain, this.options.domain)) {\n return cookie.value;\n }\n }\n }\n }\n } catch (ignoreError) {\n /* istanbul ignore next */\n // if cookieStore had a surprise failure, fallback to document.cookie\n }\n\n const cookies = (globalScope?.document?.cookie.split('; ') ?? []).filter((c) => c.indexOf(key + '=') === 0);\n let match: string | undefined = undefined;\n\n // if matcher function is provided, use it to de-duplicate when there's more than one cookie\n /* istanbul ignore if */\n const duplicateResolverFn = this.config.duplicateResolverFn;\n if (typeof duplicateResolverFn === 'function' && cookies.length > 1) {\n match = cookies.find((c) => {\n try {\n const res = duplicateResolverFn(c.substring(key.length + 1));\n if (!res) {\n this.config.diagnosticsClient?.increment('cookies.duplicate.occurrence.document.cookie');\n }\n return res;\n } catch (ignoreError) {\n /* istanbul ignore next */\n return false;\n }\n });\n }\n\n // if match was not found, just get the first one that matches the key\n if (!match) {\n match = cookies[0];\n }\n if (!match) {\n return undefined;\n }\n return match.substring(key.length + 1);\n }\n\n async set(key: string, value: T | null): Promise<void> {\n try {\n const expirationDays = this.options.expirationDays ?? 0;\n const expires = value !== null ? expirationDays : -1;\n let expireDate: Date | undefined = undefined;\n if (expires) {\n const date = new Date();\n date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);\n expireDate = date;\n }\n let str = `${key}=${btoa(encodeURIComponent(JSON.stringify(value)))}`;\n if (expireDate) {\n str += `; expires=${expireDate.toUTCString()}`;\n }\n str += '; path=/';\n if (this.options.domain) {\n str += `; domain=${this.options.domain}`;\n }\n if (this.options.secure) {\n str += '; Secure';\n }\n if (this.options.sameSite) {\n str += `; SameSite=${this.options.sameSite}`;\n }\n const globalScope = getGlobalScope();\n if (globalScope) {\n globalScope.document.cookie = str;\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.error(`Amplitude Logger [Error]: Failed to set cookie for key: ${key}. Error: ${errorMessage}`);\n }\n }\n\n async remove(key: string): Promise<void> {\n await this.set(key, null);\n }\n\n async reset(): Promise<void> {\n return;\n }\n}\n\nconst decodeCookiesAsDefault = (value: string): string | undefined => {\n try {\n return decodeURIComponent(atob(value));\n } catch {\n return undefined;\n }\n};\n\nconst decodeCookiesWithDoubleUrlEncoding = (value: string): string | undefined => {\n // Modern Ruby (v7+) automatically encodes cookies with URL encoding by\n // https://api.rubyonrails.org/classes/ActionDispatch/Cookies.html\n try {\n return decodeURIComponent(atob(decodeURIComponent(value)));\n } catch {\n return undefined;\n }\n};\n\n/**\n * Decodes a cookie value that was encoded with btoa(encodeURIComponent(...)).\n * Handles both standard encoding and double URL encoding (used by Ruby Rails v7+).\n */\nexport const decodeCookieValue = (value: string): string | undefined => {\n return decodeCookiesAsDefault(value) ?? decodeCookiesWithDoubleUrlEncoding(value);\n};\n\n/**\n * Compares two domain strings for equality, ignoring leading dots.\n * This is useful for comparing cookie domains since \".example.com\" and \"example.com\"\n * are effectively equivalent for cookie scoping.\n */\nexport const isDomainEqual = (domain1: string | undefined, domain2: string | undefined): boolean => {\n if (!domain1 || !domain2) {\n return false;\n }\n const normalized1 = domain1.startsWith('.') ? domain1.substring(1) : domain1;\n const normalized2 = domain2.startsWith('.') ? domain2.substring(1) : domain2;\n return normalized1.toLowerCase() === normalized2.toLowerCase();\n};\n"]}
|
|
@@ -58,6 +58,39 @@ export interface BrowserClient extends Client {
|
|
|
58
58
|
* ```
|
|
59
59
|
*/
|
|
60
60
|
getIdentity(): AnalyticsIdentity;
|
|
61
|
+
/**
|
|
62
|
+
* Sets the identity (userId, deviceId, and/or userProperties).
|
|
63
|
+
* This is a unified shortcut for `setUserId()`, `setDeviceId()`, and setting user properties.
|
|
64
|
+
* When userProperties change, an identify event is automatically sent.
|
|
65
|
+
*
|
|
66
|
+
* **Important limitation:** When userProperties are replaced, the local state is fully replaced
|
|
67
|
+
* but the identify event sent to the server only includes `$set` operations for the new properties.
|
|
68
|
+
* Properties removed from the local state are **not** `$unset` on the server.
|
|
69
|
+
*
|
|
70
|
+
* For example, changing from `{plan: 'premium', theme: 'dark'}` to `{plan: 'basic'}` removes
|
|
71
|
+
* `theme` locally but leaves it on the server. To remove a property from the server, use
|
|
72
|
+
* `identify()` with `Identify.unset()` directly.
|
|
73
|
+
*
|
|
74
|
+
* ```typescript
|
|
75
|
+
* // Set user properties (auto-sends identify event with $set)
|
|
76
|
+
* setIdentity({ userProperties: { plan: 'premium' } });
|
|
77
|
+
*
|
|
78
|
+
* // Set userId (equivalent to setUserId('user-123'))
|
|
79
|
+
* setIdentity({ userId: 'user-123' });
|
|
80
|
+
*
|
|
81
|
+
* // Set deviceId (equivalent to setDeviceId('device-456'))
|
|
82
|
+
* setIdentity({ deviceId: 'device-456' });
|
|
83
|
+
*
|
|
84
|
+
* // Set multiple identity fields together
|
|
85
|
+
* setIdentity({ userId: 'user-123', deviceId: 'device-456', userProperties: { name: 'John' } });
|
|
86
|
+
*
|
|
87
|
+
* // To remove a property from the server, use identify() directly:
|
|
88
|
+
* const identify = new Identify();
|
|
89
|
+
* identify.unset('theme');
|
|
90
|
+
* amplitude.identify(identify);
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
setIdentity(identity: Partial<AnalyticsIdentity>): void;
|
|
61
94
|
/**
|
|
62
95
|
* Returns the current optOut config value.
|
|
63
96
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-client.d.ts","sourceRoot":"","sources":["../../../../src/types/client/browser-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAEzE,MAAM,WAAW,aAAc,SAAQ,MAAM;IAC3C;;;;;;;OAOG;IACH,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAEtE,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAEvF;;;;;;;;;;;;;;;;OAgBG;IACH,YAAY,CAAC,SAAS,EAAE,sBAAsB,GAAG,IAAI,CAAC;IAEtD;;;;;;;;;;;;;;;;OAgBG;IACH,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,aAAa,EAAE,aAAa,CAAC,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAEzE;;;;;;OAMG;IACH,WAAW,IAAI,iBAAiB,CAAC;IAEjC;;;;;;OAMG;IACH,SAAS,IAAI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;;;;OAOG;IACH,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CACrD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-client.js","sourceRoot":"","sources":["../../../../src/types/client/browser-client.ts"],"names":[],"mappings":"","sourcesContent":["import { TransportTypeOrOptions } from '../transport';\nimport { Client } from './core-client';\nimport { AnalyticsIdentity, Plugin } from '../plugin';\nimport { AmplitudeReturn } from '../../utils/return-wrapper';\nimport { BrowserConfig, BrowserOptions } from '../config/browser-config';\n\nexport interface BrowserClient extends Client {\n /**\n * Initializes the Amplitude SDK with your apiKey, optional configurations.\n * This method must be called before any other operations.\n *\n * ```typescript\n * await init(API_KEY, options).promise;\n * ```\n */\n init(apiKey: string, options?: BrowserOptions): AmplitudeReturn<void>;\n\n init(apiKey: string, userId?: string, options?: BrowserOptions): AmplitudeReturn<void>;\n\n /**\n * Sets the network transport type for events.\n *\n * ```typescript\n * // Use Fetch API\n * setTransport('fetch');\n *\n * // Use XMLHttpRequest API\n * setTransport('xhr');\n *\n * // Use navigator.sendBeacon API\n * setTransport('beacon');\n *\n * // Use Fetch API with custom headers\n * setTransport({ type: 'fetch', headers: { 'X-Custom-Header': 'value' } });\n * ```\n */\n setTransport(transport: TransportTypeOrOptions): void;\n\n /**\n * Adds a new plugin.\n *\n * ```typescript\n * const plugin = {\n * name: 'my-plugin',\n * type: 'enrichment',\n * async setup(config: BrowserConfig, amplitude: BrowserClient) {\n * return;\n * },\n * async execute(event: Event) {\n * return event;\n * },\n * };\n * amplitude.add(plugin);\n * ```\n */\n add(plugin: Plugin<BrowserClient, BrowserConfig>): AmplitudeReturn<void>;\n\n /**\n * Returns the current identity.\n *\n * ```typescript\n * const identity = getIdentity();\n * ```\n */\n getIdentity(): AnalyticsIdentity;\n\n /**\n * Returns the current optOut config value.\n *\n * ```typescript\n * const optOut = getOptOut();\n * ```\n */\n getOptOut(): boolean | undefined;\n\n /**\n * @experimental\n * WARNING: This method is for internal testing only and is not part of the public API.\n * It may be changed or removed at any time without notice.\n *\n * Sets the diagnostics sample rate before amplitude.init()\n * @param sampleRate - The sample rate to set\n */\n _setDiagnosticsSampleRate(sampleRate: number): void;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"browser-client.js","sourceRoot":"","sources":["../../../../src/types/client/browser-client.ts"],"names":[],"mappings":"","sourcesContent":["import { TransportTypeOrOptions } from '../transport';\nimport { Client } from './core-client';\nimport { AnalyticsIdentity, Plugin } from '../plugin';\nimport { AmplitudeReturn } from '../../utils/return-wrapper';\nimport { BrowserConfig, BrowserOptions } from '../config/browser-config';\n\nexport interface BrowserClient extends Client {\n /**\n * Initializes the Amplitude SDK with your apiKey, optional configurations.\n * This method must be called before any other operations.\n *\n * ```typescript\n * await init(API_KEY, options).promise;\n * ```\n */\n init(apiKey: string, options?: BrowserOptions): AmplitudeReturn<void>;\n\n init(apiKey: string, userId?: string, options?: BrowserOptions): AmplitudeReturn<void>;\n\n /**\n * Sets the network transport type for events.\n *\n * ```typescript\n * // Use Fetch API\n * setTransport('fetch');\n *\n * // Use XMLHttpRequest API\n * setTransport('xhr');\n *\n * // Use navigator.sendBeacon API\n * setTransport('beacon');\n *\n * // Use Fetch API with custom headers\n * setTransport({ type: 'fetch', headers: { 'X-Custom-Header': 'value' } });\n * ```\n */\n setTransport(transport: TransportTypeOrOptions): void;\n\n /**\n * Adds a new plugin.\n *\n * ```typescript\n * const plugin = {\n * name: 'my-plugin',\n * type: 'enrichment',\n * async setup(config: BrowserConfig, amplitude: BrowserClient) {\n * return;\n * },\n * async execute(event: Event) {\n * return event;\n * },\n * };\n * amplitude.add(plugin);\n * ```\n */\n add(plugin: Plugin<BrowserClient, BrowserConfig>): AmplitudeReturn<void>;\n\n /**\n * Returns the current identity.\n *\n * ```typescript\n * const identity = getIdentity();\n * ```\n */\n getIdentity(): AnalyticsIdentity;\n\n /**\n * Sets the identity (userId, deviceId, and/or userProperties).\n * This is a unified shortcut for `setUserId()`, `setDeviceId()`, and setting user properties.\n * When userProperties change, an identify event is automatically sent.\n *\n * **Important limitation:** When userProperties are replaced, the local state is fully replaced\n * but the identify event sent to the server only includes `$set` operations for the new properties.\n * Properties removed from the local state are **not** `$unset` on the server.\n *\n * For example, changing from `{plan: 'premium', theme: 'dark'}` to `{plan: 'basic'}` removes\n * `theme` locally but leaves it on the server. To remove a property from the server, use\n * `identify()` with `Identify.unset()` directly.\n *\n * ```typescript\n * // Set user properties (auto-sends identify event with $set)\n * setIdentity({ userProperties: { plan: 'premium' } });\n *\n * // Set userId (equivalent to setUserId('user-123'))\n * setIdentity({ userId: 'user-123' });\n *\n * // Set deviceId (equivalent to setDeviceId('device-456'))\n * setIdentity({ deviceId: 'device-456' });\n *\n * // Set multiple identity fields together\n * setIdentity({ userId: 'user-123', deviceId: 'device-456', userProperties: { name: 'John' } });\n *\n * // To remove a property from the server, use identify() directly:\n * const identify = new Identify();\n * identify.unset('theme');\n * amplitude.identify(identify);\n * ```\n */\n setIdentity(identity: Partial<AnalyticsIdentity>): void;\n\n /**\n * Returns the current optOut config value.\n *\n * ```typescript\n * const optOut = getOptOut();\n * ```\n */\n getOptOut(): boolean | undefined;\n\n /**\n * @experimental\n * WARNING: This method is for internal testing only and is not part of the public API.\n * It may be changed or removed at any time without notice.\n *\n * Sets the diagnostics sample rate before amplitude.init()\n * @param sampleRate - The sample rate to set\n */\n _setDiagnosticsSampleRate(sampleRate: number): void;\n}\n"]}
|