diff --git a/.eslintrc.json b/.eslintrc.json index f92368f4ec..6ef4c561ba 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -138,8 +138,7 @@ } ] } - ], - "sonarjs/todo-tag": "warn" + ] } }, { diff --git a/.github/workflows/deploy-npm.yml b/.github/workflows/deploy-npm.yml index f73132e335..63dfa3e0f7 100644 --- a/.github/workflows/deploy-npm.yml +++ b/.github/workflows/deploy-npm.yml @@ -155,7 +155,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_VALUE }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_VALUE }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -171,7 +171,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_VALUE }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_VALUE }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", @@ -205,7 +205,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_SW_VALUE }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_SW_VALUE }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -221,7 +221,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_SW_VALUE }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_SW_VALUE }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", @@ -255,7 +255,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_COOKIE_UTILS_VALUE }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_COOKIE_UTILS_VALUE }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -271,7 +271,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_COOKIE_UTILS_VALUE }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_COOKIE_UTILS_VALUE }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", diff --git a/.github/workflows/deploy-sanity-suite.yml b/.github/workflows/deploy-sanity-suite.yml index d5522ed839..600ef9f0d3 100644 --- a/.github/workflows/deploy-sanity-suite.yml +++ b/.github/workflows/deploy-sanity-suite.yml @@ -153,7 +153,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Deployment: ${{ env.PROJECT_NAME }} - <${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Deployment: ${{ env.PROJECT_NAME }} - <${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -169,7 +169,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 794a6c0e26..801fc3e96f 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -233,7 +233,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -249,7 +249,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", diff --git a/.github/workflows/publish-new-release.yml b/.github/workflows/publish-new-release.yml index 836fe8d05b..c03c086fb8 100644 --- a/.github/workflows/publish-new-release.yml +++ b/.github/workflows/publish-new-release.yml @@ -117,7 +117,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.TAG_COMPARE_URL }}${{ env.last_monorepo_version }}...v${{ steps.extract-version.outputs.release_version }}|v${{ steps.extract-version.outputs.release_version }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.TAG_COMPARE_URL }}${{ env.last_monorepo_version }}...v${{ steps.extract-version.outputs.release_version }}|v${{ steps.extract-version.outputs.release_version }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -133,7 +133,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.TAG_COMPARE_URL }}${{ env.last_monorepo_version }}...v${{ steps.extract-version.outputs.release_version }}|v${{ steps.extract-version.outputs.release_version }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.TAG_COMPARE_URL }}${{ env.last_monorepo_version }}...v${{ steps.extract-version.outputs.release_version }}|v${{ steps.extract-version.outputs.release_version }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", diff --git a/CODEOWNERS b/CODEOWNERS index ec64eff795..ba26277d24 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1,12 +1,12 @@ * @rudderlabs/js-sdk -/packages/analytics-js-integrations/src/ @rudderlabs/integrations -/packages/analytics-js-integrations/__fixtures__/ @rudderlabs/integrations -/packages/analytics-js-integrations/__tests__/ @rudderlabs/integrations -/packages/analytics-js-integrations/__mocks__/ @rudderlabs/integrations -/packages/analytics-js-integrations/README.md @rudderlabs/integrations -/packages/analytics-js-integrations/.size-limit.js @rudderlabs/integrations +/packages/analytics-js-integrations/src/ @rudderlabs/js-sdk-dm-intg-eng +/packages/analytics-js-integrations/__fixtures__/ @rudderlabs/js-sdk-dm-intg-eng +/packages/analytics-js-integrations/__tests__/ @rudderlabs/js-sdk-dm-intg-eng +/packages/analytics-js-integrations/__mocks__/ @rudderlabs/js-sdk-dm-intg-eng +/packages/analytics-js-integrations/README.md @rudderlabs/js-sdk-dm-intg-eng +/packages/analytics-js-integrations/.size-limit.js @rudderlabs/js-sdk-dm-intg-eng -/packages/analytics-js-common/src/constants/integrations/ @rudderlabs/integrations -/assets/integrations/AdobeAnalytics/ @rudderlabs/integrations -/examples/integrations/ @rudderlabs/integrations +/packages/analytics-js-common/src/constants/integrations/ @rudderlabs/js-sdk-dm-intg-eng +/assets/integrations/AdobeAnalytics/ @rudderlabs/js-sdk-dm-intg-eng +/examples/integrations/ @rudderlabs/js-sdk-dm-intg-eng diff --git a/package-lock.json b/package-lock.json index 93f11ecb6b..05e6a48a95 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@rudderstack/analytics-js-monorepo", - "version": "3.48.0", + "version": "3.49.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@rudderstack/analytics-js-monorepo", - "version": "3.48.0", + "version": "3.49.0", "hasInstallScript": true, "license": "Elastic-2.0", "workspaces": [ @@ -25284,7 +25284,7 @@ }, "packages/analytics-js": { "name": "@rudderstack/analytics-js", - "version": "3.10.0", + "version": "3.10.1", "license": "Elastic-2.0", "dependencies": { "@preact/signals-core": "1.8.0", @@ -25298,7 +25298,7 @@ }, "packages/analytics-js-common": { "name": "@rudderstack/analytics-js-common", - "version": "3.12.0", + "version": "3.12.1", "license": "Elastic-2.0", "dependencies": { "@lukeed/uuid": "2.0.1", @@ -25315,7 +25315,7 @@ }, "packages/analytics-js-cookies": { "name": "@rudderstack/analytics-js-cookies", - "version": "0.4.0", + "version": "0.4.1", "license": "Elastic-2.0", "dependencies": { "@rudderstack/analytics-js-common": "*" @@ -25324,7 +25324,7 @@ }, "packages/analytics-js-integrations": { "name": "@rudderstack/analytics-js-integrations", - "version": "3.10.2", + "version": "3.10.3", "license": "Elastic-2.0", "dependencies": { "@lukeed/uuid": "2.0.1", @@ -25344,7 +25344,7 @@ }, "packages/analytics-js-plugins": { "name": "@rudderstack/analytics-js-plugins", - "version": "3.6.0", + "version": "3.6.1", "license": "Elastic-2.0", "dependencies": { "@rudderstack/analytics-js-common": "*", @@ -25358,7 +25358,7 @@ }, "packages/analytics-js-service-worker": { "name": "@rudderstack/analytics-js-service-worker", - "version": "3.2.0", + "version": "3.2.1", "license": "Elastic-2.0", "dependencies": { "@lukeed/uuid": "2.0.1", @@ -25379,7 +25379,7 @@ }, "packages/analytics-v1.1": { "name": "rudder-sdk-js", - "version": "2.48.25", + "version": "2.48.26", "license": "Elastic-2.0", "dependencies": { "@rudderstack/analytics-js-common": "*" @@ -25388,7 +25388,7 @@ }, "packages/loading-scripts": { "name": "@rudderstack/analytics-js-loading-scripts", - "version": "3.0.40", + "version": "3.0.41", "license": "Elastic-2.0", "dependencies": { "@rudderstack/analytics-js": "*" @@ -25397,7 +25397,7 @@ }, "packages/sanity-suite": { "name": "@rudderstack/analytics-js-sanity-suite", - "version": "3.1.31", + "version": "3.1.32", "license": "Elastic-2.0", "dependencies": { "@rudderstack/analytics-js": "*", diff --git a/package.json b/package.json index fdb773def6..b26331e2a0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@rudderstack/analytics-js-monorepo", - "version": "3.48.0", + "version": "3.49.0", "private": true, "description": "Monorepo for RudderStack Analytics JS SDK", "workspaces": [ diff --git a/packages/analytics-js-common/CHANGELOG.md b/packages/analytics-js-common/CHANGELOG.md index 255cd712b8..98e005f0a3 100644 --- a/packages/analytics-js-common/CHANGELOG.md +++ b/packages/analytics-js-common/CHANGELOG.md @@ -2,6 +2,13 @@ This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver). +## [3.12.1](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-common@3.12.0...@rudderstack/analytics-js-common@3.12.1) (2024-11-12) + + +### Bug Fixes + +* revert sanitization changes ([#1916](https://github.com/rudderlabs/rudder-sdk-js/issues/1916)) ([890fb7b](https://github.com/rudderlabs/rudder-sdk-js/commit/890fb7b615535992290f5008b93d77b540c03955)), closes [#1907](https://github.com/rudderlabs/rudder-sdk-js/issues/1907) [#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902) + ## [3.12.0](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-common@3.11.1...@rudderstack/analytics-js-common@3.12.0) (2024-11-08) diff --git a/packages/analytics-js-common/CHANGELOG_LATEST.md b/packages/analytics-js-common/CHANGELOG_LATEST.md index de7a92db4d..599acb8c8c 100644 --- a/packages/analytics-js-common/CHANGELOG_LATEST.md +++ b/packages/analytics-js-common/CHANGELOG_LATEST.md @@ -1,8 +1,7 @@ -## [3.12.0](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-common@3.11.1...@rudderstack/analytics-js-common@3.12.0) (2024-11-08) +## [3.12.1](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-common@3.12.0...@rudderstack/analytics-js-common@3.12.1) (2024-11-12) -### Features +### Bug Fixes -* add error handling to all public apis ([#1907](https://github.com/rudderlabs/rudder-sdk-js/issues/1907)) ([9fbaf81](https://github.com/rudderlabs/rudder-sdk-js/commit/9fbaf819bb02320d2f8ae82a869ad2b85090ea34)) -* sanitize input data ([#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902)) ([b71c44a](https://github.com/rudderlabs/rudder-sdk-js/commit/b71c44ae61f6c35cadc6523b918e1a574e32bc23)) +* revert sanitization changes ([#1916](https://github.com/rudderlabs/rudder-sdk-js/issues/1916)) ([890fb7b](https://github.com/rudderlabs/rudder-sdk-js/commit/890fb7b615535992290f5008b93d77b540c03955)), closes [#1907](https://github.com/rudderlabs/rudder-sdk-js/issues/1907) [#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902) diff --git a/packages/analytics-js-common/__tests__/utilities/errors.test.ts b/packages/analytics-js-common/__tests__/utilities/errors.test.ts deleted file mode 100644 index d1dab56190..0000000000 --- a/packages/analytics-js-common/__tests__/utilities/errors.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { dispatchErrorEvent } from '../../src/utilities/errors'; - -describe('Errors - utilities', () => { - describe('dispatchErrorEvent', () => { - it('should dispatch an error event', () => { - const dispatchEvent = jest.fn(); - const originalDispatchEvent = globalThis.dispatchEvent; - - globalThis.dispatchEvent = dispatchEvent; - const error = new Error('Test error'); - dispatchErrorEvent(error); - expect(dispatchEvent).toHaveBeenCalledWith(new ErrorEvent('error', { error })); - - // Cleanup - globalThis.dispatchEvent = originalDispatchEvent; - }); - }); -}); diff --git a/packages/analytics-js-common/__tests__/utilities/json.test.ts b/packages/analytics-js-common/__tests__/utilities/json.test.ts index 2de316cb25..4515274032 100644 --- a/packages/analytics-js-common/__tests__/utilities/json.test.ts +++ b/packages/analytics-js-common/__tests__/utilities/json.test.ts @@ -1,250 +1,155 @@ -import { stringifyData, getSanitizedValue } from '../../src/utilities/json'; - -const circularReferenceNotice = '[Circular Reference]'; -const bigIntNotice = '[BigInt]'; - -describe('Common Utils - JSON', () => { - describe('stringifyData', () => { - it('should stringify json excluding null values', () => { - // Define an object with null values in multiple levels along with other data types - const obj = { - key1: 'value1', - key2: null, - key3: { - key4: null, - key5: 'value5', - key10: undefined, - key6: { - key7: null, - key8: 'value8', - key9: undefined, - key11: [1, 2, null, 3], +import { clone } from 'ramda'; +import { stringifyWithoutCircular } from '../../src/utilities/json'; + +const identifyTraitsPayloadMock: Record = { + firstName: 'Dummy Name', + phone: '1234567890', + email: 'dummy@email.com', + custom_flavor: 'chocolate', + custom_date: new Date(2022, 1, 21, 0, 0, 0), + address: [ + { + label: 'office', + city: 'Brussels', + country: 'Belgium', + }, + { + label: 'home', + city: 'Kolkata', + country: 'India', + nested: { + type: 'flat', + rooms: [ + { + name: 'kitchen', + size: 'small', }, - }, - }; - - expect(stringifyData(obj)).toBe( - '{"key1":"value1","key3":{"key5":"value5","key6":{"key8":"value8","key11":[1,2,null,3]}}}', - ); - }); - - it('should stringify json without excluding null values', () => { - // Define an object with null values in multiple levels along with other data types - const obj = { - key1: 'value1', - key2: null, - key3: { - key4: null, - key5: 'value5', - key6: { - key7: null, - key8: 'value8', + { + // eslint-disable-next-line sonarjs/no-duplicate-string + name: 'living room', + size: 'large', }, - }, - }; - - expect(stringifyData(obj, false)).toBe( - '{"key1":"value1","key2":null,"key3":{"key4":null,"key5":"value5","key6":{"key7":null,"key8":"value8"}}}', - ); - }); - - it('should stringify json after excluding certain keys', () => { - // Define an object with null values in multiple levels along with other data types - const obj = { - key1: 'value1', - key2: null, - key3: { - key4: null, - key5: 'value5', - key6: { - key7: null, - key8: 'value8', + { + name: 'bedroom', + size: 'large', }, - }, - }; + ], + }, + }, + { + label: 'work', + city: 'Kolkata', + country: 'India', + }, + ], + stringArray: ['string1', 'string2', 'string3'], + numberArray: [1, 2, 3], +}; - const keysToExclude = ['key1', 'key7']; +const circularReferenceNotice = '[Circular Reference]'; - expect(stringifyData(obj, true, keysToExclude)).toBe( - '{"key3":{"key5":"value5","key6":{"key8":"value8"}}}', - ); +describe('Common Utils - JSON', () => { + describe('stringifyWithoutCircular', () => { + it('should stringify json with circular references', () => { + const objWithCircular = clone(identifyTraitsPayloadMock); + objWithCircular.myself = objWithCircular; - expect(stringifyData(obj, false, keysToExclude)).toBe( - '{"key2":null,"key3":{"key4":null,"key5":"value5","key6":{"key8":"value8"}}}', - ); + const json = stringifyWithoutCircular(objWithCircular); + expect(json).toContain(circularReferenceNotice); }); - }); - describe('getSanitizedValue', () => { - const mockLogger = { - warn: jest.fn(), - }; - - it('should sanitize json without excluding null and undefined values', () => { - const obj = { - a: 1, - b: null, - c: 'value', - d: undefined, - i: () => {}, - e: { - f: 2, - g: null, - h: 'value', - i: undefined, - j: { - k: 3, - l: null, - m: 'value', - n: [1, 2, 3], - o: [1, 2, 3, new Date()], - s: () => {}, - }, - }, - }; + it('should stringify json with circular references and exclude null values', () => { + const objWithCircular = clone(identifyTraitsPayloadMock); + objWithCircular.myself = objWithCircular; + objWithCircular.keyToExclude = null; + objWithCircular.keyToNotExclude = ''; - expect(getSanitizedValue(obj)).toEqual(obj); + const json = stringifyWithoutCircular(objWithCircular, true); + expect(json).toContain(circularReferenceNotice); + expect(json).not.toContain('keyToExclude'); + expect(json).toContain('keyToNotExclude'); }); - it('should sanitize json after replacing BigInt and circular references', () => { - const obj = { - a: BigInt(1), - b: undefined, - c: 'value', - d: { - e: BigInt(2), - f: undefined, - g: 'value', - h: { - i: BigInt(3), - j: undefined, - k: 'value', - }, - }, - }; + it('should stringify json with out circular references', () => { + const objWithoutCircular = clone(identifyTraitsPayloadMock); + objWithoutCircular.myself = {}; - obj.myself = obj; - obj.d.myself2 = obj.d; - obj.d.h.myself3 = obj.d; - - expect(getSanitizedValue(obj, mockLogger)).toEqual({ - a: bigIntNotice, - c: 'value', - b: undefined, - myself: circularReferenceNotice, - d: { - e: bigIntNotice, - g: 'value', - f: undefined, - myself2: circularReferenceNotice, - h: { - i: bigIntNotice, - k: 'value', - j: undefined, - myself3: circularReferenceNotice, - }, - }, - }); - - expect(mockLogger.warn).toHaveBeenCalledTimes(6); - - expect(mockLogger.warn).toHaveBeenNthCalledWith( - 1, - 'JSON:: A bad data (like circular reference, BigInt) has been detected in the object and the property "a" has been dropped from the output.', - ); - - expect(mockLogger.warn).toHaveBeenNthCalledWith( - 2, - 'JSON:: A bad data (like circular reference, BigInt) has been detected in the object and the property "e" has been dropped from the output.', - ); - - expect(mockLogger.warn).toHaveBeenNthCalledWith( - 3, - 'JSON:: A bad data (like circular reference, BigInt) has been detected in the object and the property "i" has been dropped from the output.', - ); - - expect(mockLogger.warn).toHaveBeenNthCalledWith( - 4, - 'JSON:: A bad data (like circular reference, BigInt) has been detected in the object and the property "myself3" has been dropped from the output.', - ); - - expect(mockLogger.warn).toHaveBeenNthCalledWith( - 5, - 'JSON:: A bad data (like circular reference, BigInt) has been detected in the object and the property "myself2" has been dropped from the output.', - ); - - expect(mockLogger.warn).toHaveBeenNthCalledWith( - 6, - 'JSON:: A bad data (like circular reference, BigInt) has been detected in the object and the property "myself" has been dropped from the output.', - ); + const json = stringifyWithoutCircular(objWithoutCircular); + expect(json).not.toContain(circularReferenceNotice); }); - it('should sanitize json even if it contains reused objects', () => { - const obj = { - a: BigInt(1), - b: undefined, - c: 'value', - d: { - e: BigInt(2), - f: undefined, - g: 'value', - h: { - i: BigInt(3), - j: undefined, - k: 'value', - }, - }, - }; - + it('should stringify json with out circular references and reused objects', () => { + const objWithoutCircular = clone(identifyTraitsPayloadMock); const reusableArray = [1, 2, 3]; const reusableObject = { dummy: 'val' }; - obj.reused = reusableArray; - obj.reusedAgain = [1, 2, reusableArray]; - obj.reusedObj = reusableObject; - obj.reusedObjAgain = { reused: reusableObject }; - - obj.d.reused = reusableArray; - obj.d.h.reused = reusableObject; - obj.d.h.reusedAgain = [1, 2, reusableArray]; - - expect(getSanitizedValue(obj)).toEqual({ - a: bigIntNotice, - c: 'value', - b: undefined, - reused: [1, 2, 3], - reusedAgain: [1, 2, [1, 2, 3]], - reusedObj: { dummy: 'val' }, - reusedObjAgain: { reused: { dummy: 'val' } }, - d: { - e: bigIntNotice, - g: 'value', - f: undefined, - reused: [1, 2, 3], - h: { - i: bigIntNotice, - k: 'value', - j: undefined, - reused: { dummy: 'val' }, - reusedAgain: [1, 2, [1, 2, 3]], - }, - }, - }); + objWithoutCircular.reused = reusableArray; + objWithoutCircular.reusedAgain = [1, 2, reusableArray]; + objWithoutCircular.reusedObj = reusableObject; + objWithoutCircular.reusedObjAgain = { reused: reusableObject }; + objWithoutCircular.reusedObjAgainWithItself = { reused: reusableObject }; + + const json = stringifyWithoutCircular(objWithoutCircular); + expect(json).not.toContain(circularReferenceNotice); }); - it('should sanitize all data types', () => { + it('should stringify json with circular references for nested circular objects', () => { + const objWithoutCircular = clone(identifyTraitsPayloadMock); + const reusableObject = { dummy: 'val' }; + const objWithCircular = clone(reusableObject); + objWithCircular.myself = objWithCircular; + objWithoutCircular.reusedObjAgainWithItself = { reused: reusableObject }; + objWithoutCircular.objWithCircular = objWithCircular; + + const json = stringifyWithoutCircular(objWithoutCircular); + expect(json).toContain(circularReferenceNotice); + }); + + it('should stringify json for all input types', () => { const array = [1, 2, 3]; const number = 1; const string = ''; const object = {}; const date = new Date(2023, 1, 20, 0, 0, 0); - expect(getSanitizedValue(array)).toEqual(array); - expect(getSanitizedValue(number)).toEqual(number); - expect(getSanitizedValue(string)).toEqual(string); - expect(getSanitizedValue(object)).toEqual(object); - expect(getSanitizedValue(date)).toEqual(date); - expect(getSanitizedValue(null)).toEqual(null); - expect(getSanitizedValue(undefined)).toEqual(undefined); + const arrayJson = stringifyWithoutCircular(array); + const numberJson = stringifyWithoutCircular(number); + const stringJson = stringifyWithoutCircular(string); + const objectJson = stringifyWithoutCircular(object); + const dateJson = stringifyWithoutCircular(date); + const nullJson = stringifyWithoutCircular(null); + const undefinedJson = stringifyWithoutCircular(undefined); + + expect(arrayJson).toBe('[1,2,3]'); + expect(numberJson).toBe('1'); + expect(stringJson).toBe('""'); + expect(objectJson).toBe('{}'); + expect(dateJson).toBe('"2023-02-19T18:30:00.000Z"'); + expect(nullJson).toBe('null'); + expect(undefinedJson).toBe(undefined); + }); + + it('should stringify json after removing the exclude keys', () => { + const objWithoutCircular = clone(identifyTraitsPayloadMock); + + const json = stringifyWithoutCircular(objWithoutCircular, true, ['size', 'city']); + expect(json).not.toContain('size'); + expect(json).not.toContain('city'); + }); + + it('should return null for input containing BigInt values', () => { + const mockLogger = { + warn: jest.fn(), + }; + + const objWithBigInt = { + bigInt: BigInt(9007199254740991), + }; + const json = stringifyWithoutCircular(objWithBigInt, false, [], mockLogger); + expect(json).toBe(null); + expect(mockLogger.warn).toHaveBeenCalledWith( + 'Failed to convert the value to a JSON string.', + new TypeError('Do not know how to serialize a BigInt'), + ); }); }); }); diff --git a/packages/analytics-js-common/package.json b/packages/analytics-js-common/package.json index a6c9d2c342..a0dd3a130d 100644 --- a/packages/analytics-js-common/package.json +++ b/packages/analytics-js-common/package.json @@ -1,6 +1,6 @@ { "name": "@rudderstack/analytics-js-common", - "version": "3.12.0", + "version": "3.12.1", "private": true, "description": "RudderStack JavaScript SDK common code", "module": "dist/npm/index.js", diff --git a/packages/analytics-js-common/project.json b/packages/analytics-js-common/project.json index d689a5332f..84a1ebd3df 100644 --- a/packages/analytics-js-common/project.json +++ b/packages/analytics-js-common/project.json @@ -51,9 +51,9 @@ "github": { "executor": "@jscutlery/semver:github", "options": { - "tag": "@rudderstack/analytics-js-common@3.12.0", - "title": "@rudderstack/analytics-js-common@3.12.0", - "discussion-category": "@rudderstack/analytics-js-common@3.12.0", + "tag": "@rudderstack/analytics-js-common@3.12.1", + "title": "@rudderstack/analytics-js-common@3.12.1", + "discussion-category": "@rudderstack/analytics-js-common@3.12.1", "notesFile": "./packages/analytics-js-common/CHANGELOG_LATEST.md" } } diff --git a/packages/analytics-js-common/src/constants/integrations/integration_cname.js b/packages/analytics-js-common/src/constants/integrations/integration_cname.js index 1b3c6815d2..57ab51ec48 100644 --- a/packages/analytics-js-common/src/constants/integrations/integration_cname.js +++ b/packages/analytics-js-common/src/constants/integrations/integration_cname.js @@ -163,7 +163,7 @@ const commonNames = { ...Sprig, ...SpotifyPixel, ...XPixel, - ...Gainsight_PX, + ...Gainsight_PX }; export { commonNames }; diff --git a/packages/analytics-js-common/src/constants/logMessages.ts b/packages/analytics-js-common/src/constants/logMessages.ts index fbb06c6d8a..91eb20f04a 100644 --- a/packages/analytics-js-common/src/constants/logMessages.ts +++ b/packages/analytics-js-common/src/constants/logMessages.ts @@ -9,13 +9,16 @@ const SCRIPT_LOAD_ERROR = (id: string, url: string): string => const SCRIPT_LOAD_TIMEOUT_ERROR = (id: string, url: string, timeout: number): string => `A timeout of ${timeout} ms occurred while trying to load the script with id "${id}" from URL "${url}".`; -const BAD_DATA_WARNING = (context: string, key: string): string => - `${context}${LOG_CONTEXT_SEPARATOR}A bad data (like circular reference, BigInt) has been detected in the object and the property "${key}" has been dropped from the output.`; +const CIRCULAR_REFERENCE_WARNING = (context: string, key: string): string => + `${context}${LOG_CONTEXT_SEPARATOR}A circular reference has been detected in the object and the property "${key}" has been dropped from the output.`; + +const JSON_STRINGIFY_WARNING = `Failed to convert the value to a JSON string.`; export { LOG_CONTEXT_SEPARATOR, SCRIPT_ALREADY_EXISTS_ERROR, SCRIPT_LOAD_ERROR, SCRIPT_LOAD_TIMEOUT_ERROR, - BAD_DATA_WARNING, -}; + CIRCULAR_REFERENCE_WARNING, + JSON_STRINGIFY_WARNING +} diff --git a/packages/analytics-js-common/src/constants/loggerContexts.ts b/packages/analytics-js-common/src/constants/loggerContexts.ts index 65583c9774..2aa4f7f858 100644 --- a/packages/analytics-js-common/src/constants/loggerContexts.ts +++ b/packages/analytics-js-common/src/constants/loggerContexts.ts @@ -11,7 +11,7 @@ const LOAD_CONFIGURATION = 'LoadConfiguration'; const EVENT_REPOSITORY = 'EventRepository'; const EXTERNAL_SRC_LOADER = 'ExternalSrcLoader'; const HTTP_CLIENT = 'HttpClient'; -const RSA = 'RudderStackAnalytics'; +const RS_APP = 'RudderStackApplication'; const ANALYTICS_CORE = 'AnalyticsCore'; export { @@ -28,6 +28,6 @@ export { EVENT_REPOSITORY, EXTERNAL_SRC_LOADER, HTTP_CLIENT, - RSA, + RS_APP, ANALYTICS_CORE, }; diff --git a/packages/analytics-js-common/src/types/ApiObject.ts b/packages/analytics-js-common/src/types/ApiObject.ts index a72a68bacf..1265ec70d6 100644 --- a/packages/analytics-js-common/src/types/ApiObject.ts +++ b/packages/analytics-js-common/src/types/ApiObject.ts @@ -10,6 +10,6 @@ export type ApiObject = { | ApiObject | null | Date - | (string | number | boolean | null | Date | ApiObject | undefined)[] + | (string | number | boolean | null | Date | ApiObject)[] | undefined; }; diff --git a/packages/analytics-js-common/src/types/IRudderAnalytics.ts b/packages/analytics-js-common/src/types/IRudderAnalytics.ts index 3663b78c54..c9dcdbdfbc 100644 --- a/packages/analytics-js-common/src/types/IRudderAnalytics.ts +++ b/packages/analytics-js-common/src/types/IRudderAnalytics.ts @@ -85,7 +85,7 @@ export interface IRudderAnalytics { /** * Get the instance of Analytics that is set as default */ - getAnalyticsInstance(writeKey?: string): T | undefined; + getAnalyticsInstance(writeKey?: string): T; /** * Trigger load event in buffer queue if exists @@ -188,7 +188,7 @@ export interface IRudderAnalytics { /** * To fetch the current sessionId */ - getSessionId(): Nullable | undefined; + getSessionId(): Nullable; /** * To provide consent diff --git a/packages/analytics-js-common/src/utilities/checks.ts b/packages/analytics-js-common/src/utilities/checks.ts index fc973a34c5..afb4def565 100644 --- a/packages/analytics-js-common/src/utilities/checks.ts +++ b/packages/analytics-js-common/src/utilities/checks.ts @@ -35,13 +35,6 @@ const isUndefined = (value: any): value is undefined => typeof value === 'undefi */ const isNullOrUndefined = (value: any): boolean => isNull(value) || isUndefined(value); -/** - * Checks if the input is a BigInt - * @param value input value - * @returns True if the input is a BigInt - */ -const isBigInt = (value: any): value is bigint => typeof value === 'bigint'; - /** * A function to check given value is defined * @param value input value @@ -81,5 +74,4 @@ export { isDefined, isDefinedAndNotNull, isDefinedNotNullAndNotEmptyString, - isBigInt, }; diff --git a/packages/analytics-js-common/src/utilities/errors.ts b/packages/analytics-js-common/src/utilities/errors.ts index 29768eb791..5e806a6dce 100644 --- a/packages/analytics-js-common/src/utilities/errors.ts +++ b/packages/analytics-js-common/src/utilities/errors.ts @@ -1,7 +1,5 @@ import { isTypeOfError } from './checks'; -import { stringifyData } from './json'; - -const MANUAL_ERROR_IDENTIFIER = '[MANUAL ERROR]'; +import { stringifyWithoutCircular } from './json'; /** * Get mutated error with issue prepended to error message @@ -12,18 +10,11 @@ const MANUAL_ERROR_IDENTIFIER = '[MANUAL ERROR]'; const getMutatedError = (err: any, issue: string): Error => { let finalError = err; if (!isTypeOfError(err)) { - finalError = new Error(`${issue}: ${stringifyData(err as Record)}`); + finalError = new Error(`${issue}: ${stringifyWithoutCircular(err as Record)}`); } else { (finalError as Error).message = `${issue}: ${err.message}`; } return finalError; }; -const dispatchErrorEvent = (error: any) => { - if (isTypeOfError(error)) { - error.stack = `${error.stack ?? ''}\n${MANUAL_ERROR_IDENTIFIER}`; - } - (globalThis as typeof window).dispatchEvent(new ErrorEvent('error', { error })); -}; - -export { getMutatedError, dispatchErrorEvent, MANUAL_ERROR_IDENTIFIER }; +export { getMutatedError }; diff --git a/packages/analytics-js-common/src/utilities/eventMethodOverloads.ts b/packages/analytics-js-common/src/utilities/eventMethodOverloads.ts index f92b823ca9..4a7f063819 100644 --- a/packages/analytics-js-common/src/utilities/eventMethodOverloads.ts +++ b/packages/analytics-js-common/src/utilities/eventMethodOverloads.ts @@ -6,7 +6,6 @@ import { isObjectLiteralAndNotNull, mergeDeepRight } from './object'; import { isDefined, isDefinedAndNotNull, isFunction, isNull, isString } from './checks'; import { tryStringify } from './string'; import type { IdentifyTraits } from '../types/traits'; -import { getSanitizedValue } from './json'; export type PageCallOptions = { category?: string; @@ -57,70 +56,64 @@ const pageArgumentsToCallOptions = ( options?: Nullable | ApiCallback, callback?: ApiCallback, ): PageCallOptions => { - const sanitizedCategory = getSanitizedValue(category); - const sanitizedName = getSanitizedValue(name); - const sanitizedProperties = getSanitizedValue(properties); - const sanitizedOptions = getSanitizedValue(options); - const sanitizedCallback = getSanitizedValue(callback); - const payload: PageCallOptions = { - category: sanitizedCategory as string, - name: sanitizedName as string, - properties: sanitizedProperties as Nullable, - options: sanitizedOptions as Nullable, + category: category as string, + name: name as string, + properties: properties as Nullable, + options: options as Nullable, callback: undefined, }; - if (isFunction(sanitizedCallback)) { - payload.callback = sanitizedCallback; + if (isFunction(callback)) { + payload.callback = callback; } - if (isFunction(sanitizedOptions)) { - payload.category = sanitizedCategory as string; - payload.name = sanitizedName as string; - payload.properties = sanitizedProperties as Nullable; + if (isFunction(options)) { + payload.category = category as string; + payload.name = name as string; + payload.properties = properties as Nullable; payload.options = undefined; - payload.callback = sanitizedOptions; + payload.callback = options; } - if (isFunction(sanitizedProperties)) { - payload.category = sanitizedCategory as string; - payload.name = sanitizedName as string; + if (isFunction(properties)) { + payload.category = category as string; + payload.name = name as string; payload.properties = undefined; payload.options = undefined; - payload.callback = sanitizedProperties; + payload.callback = properties; } - if (isFunction(sanitizedName)) { - payload.category = sanitizedCategory as string; + if (isFunction(name)) { + payload.category = category as string; payload.name = undefined; payload.properties = undefined; payload.options = undefined; - payload.callback = sanitizedName; + payload.callback = name; } - if (isFunction(sanitizedCategory)) { + if (isFunction(category)) { payload.category = undefined; payload.name = undefined; payload.properties = undefined; payload.options = undefined; - payload.callback = sanitizedCategory; + payload.callback = category; } - if (isObjectLiteralAndNotNull(sanitizedCategory)) { + if (isObjectLiteralAndNotNull(category)) { payload.name = undefined; payload.category = undefined; - payload.properties = sanitizedCategory as Nullable; - if (!isFunction(sanitizedName)) { - payload.options = sanitizedName as Nullable; + payload.properties = category as Nullable; + if (!isFunction(name)) { + payload.options = name as Nullable; } else { payload.options = undefined; } - } else if (isObjectLiteralAndNotNull(sanitizedName)) { + } else if (isObjectLiteralAndNotNull(name)) { payload.name = undefined; - payload.properties = sanitizedName as Nullable; - if (!isFunction(sanitizedProperties)) { - payload.options = sanitizedProperties as Nullable; + payload.properties = name as Nullable; + if (!isFunction(properties)) { + payload.options = properties as Nullable; } else { payload.options = undefined; } @@ -128,9 +121,9 @@ const pageArgumentsToCallOptions = ( // if the category argument alone is provided b/w category and name, // use it as name and set category to undefined - if (isString(sanitizedCategory) && !isString(sanitizedName)) { + if (isString(category) && !isString(name)) { payload.category = undefined; - payload.name = sanitizedCategory; + payload.name = category; } // Rest of the code is just to clean up undefined values @@ -178,32 +171,27 @@ const trackArgumentsToCallOptions = ( options?: Nullable | ApiCallback, callback?: ApiCallback, ): TrackCallOptions => { - const sanitizedEvent = getSanitizedValue(event); - const sanitizedProperties = getSanitizedValue(properties); - const sanitizedOptions = getSanitizedValue(options); - const sanitizedCallback = getSanitizedValue(callback); - const payload: TrackCallOptions = { - name: sanitizedEvent, - properties: sanitizedProperties as Nullable, - options: sanitizedOptions as Nullable, + name: event, + properties: properties as Nullable, + options: options as Nullable, callback: undefined, }; - if (isFunction(sanitizedCallback)) { - payload.callback = sanitizedCallback; + if (isFunction(callback)) { + payload.callback = callback; } - if (isFunction(sanitizedOptions)) { - payload.properties = sanitizedProperties as Nullable; + if (isFunction(options)) { + payload.properties = properties as Nullable; payload.options = undefined; - payload.callback = sanitizedOptions; + payload.callback = options; } - if (isFunction(sanitizedProperties)) { + if (isFunction(properties)) { payload.properties = undefined; payload.options = undefined; - payload.callback = sanitizedProperties; + payload.callback = properties; } // Rest of the code is just to clean up undefined values @@ -229,43 +217,38 @@ const identifyArgumentsToCallOptions = ( options?: Nullable | ApiCallback, callback?: ApiCallback, ): IdentifyCallOptions => { - const sanitizedUserId = getSanitizedValue(userId); - const sanitizedTraits = getSanitizedValue(traits); - const sanitizedOptions = getSanitizedValue(options); - const sanitizedCallback = getSanitizedValue(callback); - const payload: IdentifyCallOptions = { - userId: sanitizedUserId as string, - traits: sanitizedTraits as Nullable, - options: sanitizedOptions as Nullable, + userId: userId as string, + traits: traits as Nullable, + options: options as Nullable, callback: undefined, }; - if (isFunction(sanitizedCallback)) { - payload.callback = sanitizedCallback; + if (isFunction(callback)) { + payload.callback = callback; } - if (isFunction(sanitizedOptions)) { - payload.userId = sanitizedUserId as string; - payload.traits = sanitizedTraits as Nullable; + if (isFunction(options)) { + payload.userId = userId as string; + payload.traits = traits as Nullable; payload.options = undefined; - payload.callback = sanitizedOptions; + payload.callback = options; } - if (isFunction(sanitizedTraits)) { - payload.userId = sanitizedUserId as string; + if (isFunction(traits)) { + payload.userId = userId as string; payload.traits = undefined; payload.options = undefined; - payload.callback = sanitizedTraits; + payload.callback = traits; } - if (isObjectLiteralAndNotNull(sanitizedUserId) || isNull(sanitizedUserId)) { + if (isObjectLiteralAndNotNull(userId) || isNull(userId)) { // Explicitly set null to prevent resetting the existing value // in the Analytics class payload.userId = null; - payload.traits = sanitizedUserId as Nullable; - if (!isFunction(sanitizedTraits)) { - payload.options = sanitizedTraits as Nullable; + payload.traits = userId as Nullable; + if (!isFunction(traits)) { + payload.options = traits as Nullable; } else { payload.options = undefined; } @@ -300,38 +283,33 @@ const aliasArgumentsToCallOptions = ( options?: Nullable | ApiCallback, callback?: ApiCallback, ): AliasCallOptions => { - const sanitizedTo = getSanitizedValue(to); - const sanitizedFrom = getSanitizedValue(from); - const sanitizedOptions = getSanitizedValue(options); - const sanitizedCallback = getSanitizedValue(callback); - const payload: AliasCallOptions = { - to: sanitizedTo, - from: sanitizedFrom as string, - options: sanitizedOptions as Nullable, + to, + from: from as string, + options: options as Nullable, callback: undefined, }; - if (isFunction(sanitizedCallback)) { - payload.callback = sanitizedCallback; + if (isFunction(callback)) { + payload.callback = callback; } - if (isFunction(sanitizedOptions)) { - payload.to = sanitizedTo; - payload.from = sanitizedFrom as string; + if (isFunction(options)) { + payload.to = to; + payload.from = from as string; payload.options = undefined; - payload.callback = sanitizedOptions; + payload.callback = options; } - if (isFunction(sanitizedFrom)) { - payload.to = sanitizedTo; + if (isFunction(from)) { + payload.to = to; payload.from = undefined; payload.options = undefined; - payload.callback = sanitizedFrom; - } else if (isObjectLiteralAndNotNull(sanitizedFrom) || isNull(sanitizedFrom)) { - payload.to = sanitizedTo; + payload.callback = from; + } else if (isObjectLiteralAndNotNull(from) || isNull(from)) { + payload.to = to; payload.from = undefined; - payload.options = sanitizedFrom as Nullable; + payload.options = from as Nullable; } // Rest of the code is just to clean up undefined values @@ -365,43 +343,38 @@ const groupArgumentsToCallOptions = ( options?: Nullable | ApiCallback, callback?: ApiCallback, ): GroupCallOptions => { - const sanitizedGroupId = getSanitizedValue(groupId); - const sanitizedTraits = getSanitizedValue(traits); - const sanitizedOptions = getSanitizedValue(options); - const sanitizedCallback = getSanitizedValue(callback); - const payload: GroupCallOptions = { - groupId: sanitizedGroupId as string, - traits: sanitizedTraits as Nullable, - options: sanitizedOptions as Nullable, + groupId: groupId as string, + traits: traits as Nullable, + options: options as Nullable, callback: undefined, }; - if (isFunction(sanitizedCallback)) { - payload.callback = sanitizedCallback; + if (isFunction(callback)) { + payload.callback = callback; } - if (isFunction(sanitizedOptions)) { - payload.groupId = sanitizedGroupId as string; - payload.traits = sanitizedTraits as Nullable; + if (isFunction(options)) { + payload.groupId = groupId as string; + payload.traits = traits as Nullable; payload.options = undefined; - payload.callback = sanitizedOptions; + payload.callback = options; } - if (isFunction(sanitizedTraits)) { - payload.groupId = sanitizedGroupId as string; + if (isFunction(traits)) { + payload.groupId = groupId as string; payload.traits = undefined; payload.options = undefined; - payload.callback = sanitizedTraits; + payload.callback = traits; } - if (isObjectLiteralAndNotNull(sanitizedGroupId) || isNull(sanitizedGroupId)) { + if (isObjectLiteralAndNotNull(groupId) || isNull(groupId)) { // Explicitly set null to prevent resetting the existing value // in the Analytics class payload.groupId = null; - payload.traits = sanitizedGroupId as Nullable; - if (!isFunction(sanitizedTraits)) { - payload.options = sanitizedTraits as Nullable; + payload.traits = groupId as Nullable; + if (!isFunction(traits)) { + payload.options = traits as Nullable; } else { payload.options = undefined; } diff --git a/packages/analytics-js-common/src/utilities/json.ts b/packages/analytics-js-common/src/utilities/json.ts index 2a12b96ad0..128d9edc55 100644 --- a/packages/analytics-js-common/src/utilities/json.ts +++ b/packages/analytics-js-common/src/utilities/json.ts @@ -1,103 +1,69 @@ -import { BAD_DATA_WARNING } from '../constants/logMessages'; import type { ILogger } from '../types/Logger'; import type { Nullable } from '../types/Nullable'; -import { isBigInt, isNull } from './checks'; -import { isObjectLiteralAndNotNull } from './object'; - -const JSON_UTIL = 'JSON'; - -/** - * Utility method for JSON stringify object excluding null values & circular references - * - * @param {*} value input value - * @param {boolean} excludeNull optional flag to exclude null values - * @param {string[]} excludeKeys optional array of keys to exclude - * @returns string - */ -const stringifyData = | any[] | number | string>( - value?: Nullable, - excludeNull: boolean = true, - excludeKeys: string[] = [], -): string => - JSON.stringify(value, (key: string, value: any): any => { - if ((excludeNull && isNull(value)) || excludeKeys.includes(key)) { +import { isNull, isNullOrUndefined } from './checks'; +import { CIRCULAR_REFERENCE_WARNING, JSON_STRINGIFY_WARNING } from '../constants/logMessages'; + +const JSON_STRINGIFY = 'JSONStringify'; + +const getCircularReplacer = ( + excludeNull?: boolean, + excludeKeys?: string[], + logger?: ILogger, +): ((key: string, value: any) => any) => { + const ancestors: any[] = []; + + // Here we do not want to use arrow function to use "this" in function context + // eslint-disable-next-line func-names + return function (key, value): any { + if (excludeKeys?.includes(key)) { return undefined; } - return value; - }); -const getReplacer = (logger?: ILogger): ((key: string, value: any) => any) => { - const ancestors: any[] = []; // Array to track ancestor objects + if (excludeNull && isNullOrUndefined(value)) { + return undefined; + } - // Using a regular function to use `this` for the parent context - return function replacer(key, value): any { - if (isBigInt(value)) { - logger?.warn(BAD_DATA_WARNING(JSON_UTIL, key)); - return '[BigInt]'; // Replace BigInt values + if (typeof value !== 'object' || isNull(value)) { + return value; } // `this` is the object that value is contained in, i.e., its direct parent. // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore-next-line while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) { - ancestors.pop(); // Remove ancestors that are no longer part of the chain + ancestors.pop(); } - // Check for circular references (if the value is already in the ancestors) if (ancestors.includes(value)) { - logger?.warn(BAD_DATA_WARNING(JSON_UTIL, key)); + logger?.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY, key)); return '[Circular Reference]'; } - // Add current value to ancestors ancestors.push(value); - return value; }; }; -const traverseWithThis = (obj: any, replacer: (key: string, value: any) => any): any => { - // Create a new result object or array - const result = Array.isArray(obj) ? [] : {}; - - // Traverse object properties or array elements - // eslint-disable-next-line no-restricted-syntax - for (const key in obj) { - if (Object.hasOwnProperty.call(obj, key)) { - const value = obj[key]; - - // Recursively apply the replacer and traversal - const sanitizedValue = replacer.call(obj, key, value); - - // If the value is an object or array, continue traversal - if (isObjectLiteralAndNotNull(sanitizedValue) || Array.isArray(sanitizedValue)) { - (result as any)[key] = traverseWithThis(sanitizedValue, replacer); - } else { - (result as any)[key] = sanitizedValue; - } - } - } - - return result; -}; - /** - * Recursively traverses an object similar to JSON.stringify, - * sanitizing BigInts and circular references - * @param value Input object - * @param logger Logger instance - * @returns Sanitized value + * Utility method for JSON stringify object excluding null values & circular references + * + * @param {*} value input + * @param {boolean} excludeNull if it should exclude nul or not + * @param {function} logger optional logger methods for warning + * @returns string */ -const getSanitizedValue = (value: T, logger?: ILogger): T => { - const replacer = getReplacer(logger); - - // This is needed for registering the first ancestor - const newValue = replacer.call(value, '', value); - - if (isObjectLiteralAndNotNull(value) || Array.isArray(value)) { - return traverseWithThis(value, replacer); +const stringifyWithoutCircular = | any[] | number | string>( + value?: Nullable, + excludeNull?: boolean, + excludeKeys?: string[], + logger?: ILogger, +): Nullable => { + try { + return JSON.stringify(value, getCircularReplacer(excludeNull, excludeKeys, logger)); + } catch (err) { + logger?.warn(JSON_STRINGIFY_WARNING, err); + return null; } - return newValue; }; -export { stringifyData, getSanitizedValue }; +export { stringifyWithoutCircular }; diff --git a/packages/analytics-js-common/src/utilities/object.ts b/packages/analytics-js-common/src/utilities/object.ts index 366e605a00..276aac1184 100644 --- a/packages/analytics-js-common/src/utilities/object.ts +++ b/packages/analytics-js-common/src/utilities/object.ts @@ -9,15 +9,13 @@ const getValueByPath = (obj: Record, keyPath: string): any => { const hasValueByPath = (obj: Record, path: string): boolean => Boolean(getValueByPath(obj, path)); -const isObject = (value: any): value is object => typeof value === 'object'; - /** * Checks if the input is an object literal or built-in object type and not null * @param value Input value * @returns true if the input is an object and not null */ const isObjectAndNotNull = (value: any): value is object => - !isNull(value) && isObject(value) && !Array.isArray(value); + !isNull(value) && typeof value === 'object' && !Array.isArray(value); /** * Checks if the input is an object literal and not null @@ -118,5 +116,4 @@ export { removeUndefinedValues, removeUndefinedAndNullValues, getObjectValues, - isObject, }; diff --git a/packages/analytics-js-cookies/CHANGELOG.md b/packages/analytics-js-cookies/CHANGELOG.md index 252ebfa370..bbc6d0a056 100644 --- a/packages/analytics-js-cookies/CHANGELOG.md +++ b/packages/analytics-js-cookies/CHANGELOG.md @@ -2,6 +2,16 @@ This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver). +## [0.4.1](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-cookies@0.4.0...@rudderstack/analytics-js-cookies@0.4.1) (2024-11-12) + +### Dependency Updates + +* `@rudderstack/analytics-js-common` updated to version `3.12.1` + +### Bug Fixes + +* revert sanitization changes ([#1916](https://github.com/rudderlabs/rudder-sdk-js/issues/1916)) ([890fb7b](https://github.com/rudderlabs/rudder-sdk-js/commit/890fb7b615535992290f5008b93d77b540c03955)), closes [#1907](https://github.com/rudderlabs/rudder-sdk-js/issues/1907) [#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902) + ## [0.4.0](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-cookies@0.3.14...@rudderstack/analytics-js-cookies@0.4.0) (2024-11-08) ### Dependency Updates diff --git a/packages/analytics-js-cookies/CHANGELOG_LATEST.md b/packages/analytics-js-cookies/CHANGELOG_LATEST.md index 7b79aaf136..8821efa6e2 100644 --- a/packages/analytics-js-cookies/CHANGELOG_LATEST.md +++ b/packages/analytics-js-cookies/CHANGELOG_LATEST.md @@ -1,10 +1,10 @@ -## [0.4.0](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-cookies@0.3.14...@rudderstack/analytics-js-cookies@0.4.0) (2024-11-08) +## [0.4.1](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-cookies@0.4.0...@rudderstack/analytics-js-cookies@0.4.1) (2024-11-12) ### Dependency Updates -* `@rudderstack/analytics-js-common` updated to version `3.12.0` +* `@rudderstack/analytics-js-common` updated to version `3.12.1` -### Features +### Bug Fixes -* sanitize input data ([#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902)) ([b71c44a](https://github.com/rudderlabs/rudder-sdk-js/commit/b71c44ae61f6c35cadc6523b918e1a574e32bc23)) +* revert sanitization changes ([#1916](https://github.com/rudderlabs/rudder-sdk-js/issues/1916)) ([890fb7b](https://github.com/rudderlabs/rudder-sdk-js/commit/890fb7b615535992290f5008b93d77b540c03955)), closes [#1907](https://github.com/rudderlabs/rudder-sdk-js/issues/1907) [#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902) diff --git a/packages/analytics-js-cookies/__tests__/cookieUtilities.test.ts b/packages/analytics-js-cookies/__tests__/cookieUtilities.test.ts index 14691053c9..538303972c 100644 --- a/packages/analytics-js-cookies/__tests__/cookieUtilities.test.ts +++ b/packages/analytics-js-cookies/__tests__/cookieUtilities.test.ts @@ -173,6 +173,11 @@ describe('Cookie Utilities', () => { ); }); + it('should return null if the input cannot be json stringified', () => { + const inputVal = { testKey: BigInt(123) }; + expect(getEncryptedValueBrowser(inputVal)).toBeNull(); + }); + it('should return encoded value if the input contains unicode characters', () => { const inputVal = { testKey: '✓' }; expect(getEncryptedValueBrowser(inputVal)).toBe('RS_ENC_v3_eyJ0ZXN0S2V5Ijoi4pyTIn0='); @@ -244,6 +249,11 @@ describe('Cookie Utilities', () => { ); }); + it('should return null if the input cannot be json stringified', () => { + const inputVal = { testKey: BigInt(123) }; + expect(getEncryptedValue(inputVal)).toBeNull(); + }); + it('should return encoded value if the input contains unicode characters', () => { const inputVal = { testKey: '✓' }; expect(getEncryptedValue(inputVal)).toBe('RS_ENC_v3_eyJ0ZXN0S2V5Ijoi4pyTIn0='); diff --git a/packages/analytics-js-cookies/package.json b/packages/analytics-js-cookies/package.json index b1c8d27d33..11be833f99 100644 --- a/packages/analytics-js-cookies/package.json +++ b/packages/analytics-js-cookies/package.json @@ -1,6 +1,6 @@ { "name": "@rudderstack/analytics-js-cookies", - "version": "0.4.0", + "version": "0.4.1", "description": "RudderStack JavaScript SDK Cookies Utilities", "main": "dist/npm/modern/cjs/index.cjs", "module": "dist/npm/modern/esm/index.mjs", diff --git a/packages/analytics-js-cookies/project.json b/packages/analytics-js-cookies/project.json index 6689cd1d0f..81cd6925ed 100644 --- a/packages/analytics-js-cookies/project.json +++ b/packages/analytics-js-cookies/project.json @@ -51,9 +51,9 @@ "github": { "executor": "@jscutlery/semver:github", "options": { - "tag": "@rudderstack/analytics-js-cookies@0.4.0", - "title": "@rudderstack/analytics-js-cookies@0.4.0", - "discussion-category": "@rudderstack/analytics-js-cookies@0.4.0", + "tag": "@rudderstack/analytics-js-cookies@0.4.1", + "title": "@rudderstack/analytics-js-cookies@0.4.1", + "discussion-category": "@rudderstack/analytics-js-cookies@0.4.1", "notesFile": "./packages/analytics-js-cookies/CHANGELOG_LATEST.md" } } diff --git a/packages/analytics-js-cookies/src/cookiesUtilities.ts b/packages/analytics-js-cookies/src/cookiesUtilities.ts index 68652e7e92..8d7254b1bf 100644 --- a/packages/analytics-js-cookies/src/cookiesUtilities.ts +++ b/packages/analytics-js-cookies/src/cookiesUtilities.ts @@ -2,7 +2,7 @@ import { fromBase64, toBase64 } from '@rudderstack/analytics-js-common/utilities import type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable'; import { isNull, isNullOrUndefined } from '@rudderstack/analytics-js-common/utilities/checks'; import type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject'; -import { stringifyData } from '@rudderstack/analytics-js-common/utilities/json'; +import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json'; import { COOKIE_KEYS, ENCRYPTION_PREFIX_V3 } from './constants/cookies'; import { cookie } from './component-cookie'; @@ -13,7 +13,7 @@ const getEncryptedValueInternal = ( ): Nullable => { const fallbackValue = null; try { - const strValue = stringifyData(value, false); + const strValue = stringifyWithoutCircular(value, false); if (isNull(strValue)) { return null; } diff --git a/packages/analytics-js-integrations/CHANGELOG.md b/packages/analytics-js-integrations/CHANGELOG.md index 0f5308a396..8ad43f0e18 100644 --- a/packages/analytics-js-integrations/CHANGELOG.md +++ b/packages/analytics-js-integrations/CHANGELOG.md @@ -2,6 +2,11 @@ This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver). +## [3.10.3](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-integrations@3.10.2...@rudderstack/analytics-js-integrations@3.10.3) (2024-11-12) + +### Dependency Updates + +* `@rudderstack/analytics-js-common` updated to version `3.12.1` ## [3.10.2](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-integrations@3.10.1...@rudderstack/analytics-js-integrations@3.10.2) (2024-11-08) ### Dependency Updates diff --git a/packages/analytics-js-integrations/CHANGELOG_LATEST.md b/packages/analytics-js-integrations/CHANGELOG_LATEST.md index cbff7b802b..c0215e3a3d 100644 --- a/packages/analytics-js-integrations/CHANGELOG_LATEST.md +++ b/packages/analytics-js-integrations/CHANGELOG_LATEST.md @@ -1,5 +1,5 @@ -## [3.10.2](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-integrations@3.10.1...@rudderstack/analytics-js-integrations@3.10.2) (2024-11-08) +## [3.10.3](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-integrations@3.10.2...@rudderstack/analytics-js-integrations@3.10.3) (2024-11-12) ### Dependency Updates -* `@rudderstack/analytics-js-common` updated to version `3.12.0` +* `@rudderstack/analytics-js-common` updated to version `3.12.1` diff --git a/packages/analytics-js-integrations/package.json b/packages/analytics-js-integrations/package.json index da29bb3f04..a47716cbd6 100644 --- a/packages/analytics-js-integrations/package.json +++ b/packages/analytics-js-integrations/package.json @@ -1,6 +1,6 @@ { "name": "@rudderstack/analytics-js-integrations", - "version": "3.10.2", + "version": "3.10.3", "private": true, "description": "RudderStack JavaScript SDK device mode integrations", "main": "dist/npm/modern/cjs/index.js", diff --git a/packages/analytics-js-integrations/project.json b/packages/analytics-js-integrations/project.json index 1d80bce24a..69d77e7dd0 100644 --- a/packages/analytics-js-integrations/project.json +++ b/packages/analytics-js-integrations/project.json @@ -51,9 +51,9 @@ "github": { "executor": "@jscutlery/semver:github", "options": { - "tag": "@rudderstack/analytics-js-integrations@3.10.2", - "title": "@rudderstack/analytics-js-integrations@3.10.2", - "discussion-category": "@rudderstack/analytics-js-integrations@3.10.2", + "tag": "@rudderstack/analytics-js-integrations@3.10.3", + "title": "@rudderstack/analytics-js-integrations@3.10.3", + "discussion-category": "@rudderstack/analytics-js-integrations@3.10.3", "notesFile": "./packages/analytics-js-integrations/CHANGELOG_LATEST.md" } } diff --git a/packages/analytics-js-plugins/CHANGELOG.md b/packages/analytics-js-plugins/CHANGELOG.md index c922241688..cf14c1e9e5 100644 --- a/packages/analytics-js-plugins/CHANGELOG.md +++ b/packages/analytics-js-plugins/CHANGELOG.md @@ -2,6 +2,19 @@ This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver). +## [3.6.1](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-plugins@3.6.0...@rudderstack/analytics-js-plugins@3.6.1) (2024-11-12) + +### Dependency Updates + +* `@rudderstack/analytics-js-common` updated to version `3.12.1` +* `@rudderstack/analytics-js` updated to version `3.10.0` +* `@rudderstack/analytics-js-cookies` updated to version `0.4.0` + +### Bug Fixes + +* batch entry retry ([#1918](https://github.com/rudderlabs/rudder-sdk-js/issues/1918)) ([ff346b8](https://github.com/rudderlabs/rudder-sdk-js/commit/ff346b867335750d7b428cab9c650a4d9dbfde57)) +* revert sanitization changes ([#1916](https://github.com/rudderlabs/rudder-sdk-js/issues/1916)) ([890fb7b](https://github.com/rudderlabs/rudder-sdk-js/commit/890fb7b615535992290f5008b93d77b540c03955)), closes [#1907](https://github.com/rudderlabs/rudder-sdk-js/issues/1907) [#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902) + ## [3.6.0](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-plugins@3.5.2...@rudderstack/analytics-js-plugins@3.6.0) (2024-11-08) ### Dependency Updates diff --git a/packages/analytics-js-plugins/CHANGELOG_LATEST.md b/packages/analytics-js-plugins/CHANGELOG_LATEST.md index b24633e7e7..2347b6c63b 100644 --- a/packages/analytics-js-plugins/CHANGELOG_LATEST.md +++ b/packages/analytics-js-plugins/CHANGELOG_LATEST.md @@ -1,12 +1,13 @@ -## [3.6.0](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-plugins@3.5.2...@rudderstack/analytics-js-plugins@3.6.0) (2024-11-08) +## [3.6.1](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-plugins@3.6.0...@rudderstack/analytics-js-plugins@3.6.1) (2024-11-12) ### Dependency Updates -* `@rudderstack/analytics-js-common` updated to version `3.12.0` -* `@rudderstack/analytics-js` updated to version `3.9.1` -* `@rudderstack/analytics-js-cookies` updated to version `0.3.14` +* `@rudderstack/analytics-js-common` updated to version `3.12.1` +* `@rudderstack/analytics-js` updated to version `3.10.0` +* `@rudderstack/analytics-js-cookies` updated to version `0.4.0` -### Features +### Bug Fixes -* sanitize input data ([#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902)) ([b71c44a](https://github.com/rudderlabs/rudder-sdk-js/commit/b71c44ae61f6c35cadc6523b918e1a574e32bc23)) +* batch entry retry ([#1918](https://github.com/rudderlabs/rudder-sdk-js/issues/1918)) ([ff346b8](https://github.com/rudderlabs/rudder-sdk-js/commit/ff346b867335750d7b428cab9c650a4d9dbfde57)) +* revert sanitization changes ([#1916](https://github.com/rudderlabs/rudder-sdk-js/issues/1916)) ([890fb7b](https://github.com/rudderlabs/rudder-sdk-js/commit/890fb7b615535992290f5008b93d77b540c03955)), closes [#1907](https://github.com/rudderlabs/rudder-sdk-js/issues/1907) [#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902) diff --git a/packages/analytics-js-plugins/__tests__/bugsnag/utils.test.ts b/packages/analytics-js-plugins/__tests__/bugsnag/utils.test.ts index e83671df87..6d58890430 100644 --- a/packages/analytics-js-plugins/__tests__/bugsnag/utils.test.ts +++ b/packages/analytics-js-plugins/__tests__/bugsnag/utils.test.ts @@ -695,6 +695,13 @@ describe('Bugsnag utilities', () => { }, ['key4', 'key6'], // excluded keys ], + [ + { + someKey: BigInt(123), + }, + undefined, + [], + ], ]; it.each(tcData)('should convert signals to JSON %#', (input, expected, excludes) => { diff --git a/packages/analytics-js-plugins/__tests__/deviceModeTransformation/index.test.ts b/packages/analytics-js-plugins/__tests__/deviceModeTransformation/index.test.ts index bdcc3c4f18..544957d15f 100644 --- a/packages/analytics-js-plugins/__tests__/deviceModeTransformation/index.test.ts +++ b/packages/analytics-js-plugins/__tests__/deviceModeTransformation/index.test.ts @@ -280,6 +280,7 @@ describe('Device mode transformation plugin', () => { id: 'sample_uuid', time: expect.any(Number), // time: 1 + 500 * 2 ** 1, // this is the delay calculation in RetryQueue + type: 'Single', }, ]); mockSendTransformedEventToDestinations.mockRestore(); diff --git a/packages/analytics-js-plugins/__tests__/errorReporting/utils.test.ts b/packages/analytics-js-plugins/__tests__/errorReporting/utils.test.ts index 0e0ecb8dbe..1853279900 100644 --- a/packages/analytics-js-plugins/__tests__/errorReporting/utils.test.ts +++ b/packages/analytics-js-plugins/__tests__/errorReporting/utils.test.ts @@ -275,6 +275,13 @@ describe('Error Reporting utilities', () => { }, ['key4', 'key6'], // excluded keys ], + [ + { + someKey: BigInt(123), + }, + {}, + [], + ], ]; it.each(tcData)('should convert signals to JSON %#', (input, expected, excludes) => { diff --git a/packages/analytics-js-plugins/__tests__/utilities/queue.test.ts b/packages/analytics-js-plugins/__tests__/utilities/queue.test.ts index f98262da13..0f60b8eac1 100644 --- a/packages/analytics-js-plugins/__tests__/utilities/queue.test.ts +++ b/packages/analytics-js-plugins/__tests__/utilities/queue.test.ts @@ -158,6 +158,92 @@ describe('Queue Plugins Utilities', () => { '{"channel":"test","type":"track","anonymousId":"test","context":{"traits":{"trait_1":"trait_1","trait_2":"trait_2"},"sessionId":1,"sessionStart":true,"ua-ch":{"test":"test"},"app":{"name":"test","version":"test","namespace":"test"},"library":{"name":"test","version":"test"},"userAgent":"test","os":{"name":"test","version":"test"},"locale":"test","screen":{"width":1,"height":1,"density":1,"innerWidth":1,"innerHeight":1}},"originalTimestamp":"test","integrations":{"All":true},"messageId":"test","previousId":"test","sentAt":"test","category":"test","groupId":"test","event":"test","userId":"test","properties":{"test":"test"}}', ); }); + + it('should return string with circular dependencies replaced with static string', () => { + const event = { + channel: 'test', + type: 'track', + anonymousId: 'test', + context: { + traits: { + trait_1: 'trait_1', + trait_2: 'trait_2', + }, + sessionId: 1, + sessionStart: true, + consentManagement: { + deniedConsentIds: ['1', '2', '3'], + }, + 'ua-ch': { + test: 'test', + }, + app: { + name: 'test', + version: 'test', + namespace: 'test', + }, + library: { + name: 'test', + version: 'test', + }, + userAgent: 'test', + os: { + name: 'test', + version: 'test', + }, + locale: 'test', + screen: { + width: 1, + height: 1, + density: 1, + innerWidth: 1, + innerHeight: 1, + }, + campaign: { + source: 'test', + medium: 'test', + name: 'test', + term: 'test', + content: 'test', + }, + }, + originalTimestamp: 'test', + integrations: { + All: true, + }, + messageId: 'test', + previousId: 'test', + sentAt: 'test', + category: 'test', + traits: { + trait_1: 'trait_11', + trait_2: 'trait_12', + }, + groupId: 'test', + event: 'test', + userId: 'test', + properties: { + test: 'test', + }, + } as RudderEvent; + + event.traits = event.context.traits; + event.context.traits.newTraits = event.traits; + + expect(getDeliveryPayload(event, mockLogger)).toContain('[Circular Reference]'); + }); + + it('should return null if the payload cannot be stringified', () => { + const event = { + channel: 'test', + type: 'track', + properties: { + someBigInt: BigInt(9007199254740991), + }, + } as unknown as RudderEvent; + + expect(getDeliveryPayload(event, mockLogger)).toBeNull(); + }); }); describe('validateEventPayloadSize', () => { @@ -215,5 +301,27 @@ describe('Queue Plugins Utilities', () => { expect(mockLogger.warn).not.toHaveBeenCalled(); }); + + it('should log a warning if the payload size could not be calculated', () => { + const event = { + channel: 'test', + type: 'track', + traits: { + trait_1: 'trait_1', + trait_2: 'trait_2', + }, + userId: 'test', + properties: { + test: 'test', + test1: BigInt(9007199254740991), + }, + } as unknown as RudderEvent; + + validateEventPayloadSize(event, mockLogger); + + expect(mockLogger.warn).toHaveBeenCalledWith( + 'QueueUtilities:: Failed to validate event payload size. Please make sure that the event payload is within the size limit and is a valid JSON object.', + ); + }); }); }); diff --git a/packages/analytics-js-plugins/__tests__/utilities/retryQueue/RetryQueue.test.ts b/packages/analytics-js-plugins/__tests__/utilities/retryQueue/RetryQueue.test.ts index 999950b53b..fba64dc8e4 100644 --- a/packages/analytics-js-plugins/__tests__/utilities/retryQueue/RetryQueue.test.ts +++ b/packages/analytics-js-plugins/__tests__/utilities/retryQueue/RetryQueue.test.ts @@ -67,6 +67,7 @@ describe('Queue', () => { attemptNumber: 0, time: expect.any(Number), id: expect.any(String), + type: 'Single', }, ]); }); @@ -87,6 +88,7 @@ describe('Queue', () => { attemptNumber: 0, time: expect.any(Number), id: expect.any(String), + type: 'Single', }, ]); @@ -112,6 +114,7 @@ describe('Queue', () => { attemptNumber: 0, time: expect.any(Number), id: expect.any(String), + type: 'Batch', }, ]); }); @@ -138,6 +141,7 @@ describe('Queue', () => { attemptNumber: 0, time: expect.any(Number), id: expect.any(String), + type: 'Batch', }, ]); }); @@ -165,6 +169,7 @@ describe('Queue', () => { attemptNumber: 0, time: expect.any(Number), id: expect.any(String), + type: 'Batch', }, ]); }); @@ -192,6 +197,7 @@ describe('Queue', () => { attemptNumber: 0, time: expect.any(Number), id: expect.any(String), + type: 'Single', }, ]); @@ -235,7 +241,7 @@ describe('Queue', () => { queue.processQueueCb = mockProcessItemCb; queue.start(); - queue.requeue('b', 1); + queue.requeue({ item: 'b', attemptNumber: 0, type: 'Single' }); queue.addItem('a'); expect(queue.processQueueCb).toHaveBeenCalledTimes(1); @@ -260,17 +266,17 @@ describe('Queue', () => { queue.start(); // over maxattempts - queue.requeue('a', 3); + queue.requeue({ item: 'b', attemptNumber: 2, type: 'Single' }); jest.advanceTimersByTime(queue.getDelay(3)); expect(queue.processQueueCb).toHaveBeenCalledTimes(0); mockProcessItemCb.mockReset(); - queue.requeue('a', 2); + queue.requeue({ item: ['a', 'b'], attemptNumber: 1, type: 'Batch' }); jest.advanceTimersByTime(queue.getDelay(2)); expect(queue.processQueueCb).toHaveBeenCalledTimes(1); mockProcessItemCb.mockReset(); - queue.requeue('a', 3); + queue.requeue({ item: 'b', attemptNumber: 2, type: 'Single' }); jest.advanceTimersByTime(queue.getDelay(1)); expect(queue.processQueueCb).toHaveBeenCalledTimes(0); }); @@ -307,6 +313,23 @@ describe('Queue', () => { item: 'a', time: 0, attemptNumber: 0, + type: 'Single', + }, + { + item: ['b', 'c'], + time: 0, + attemptNumber: 0, + type: 'Batch', + }, + { + item: ['d', 'e'], + time: 0, + attemptNumber: 0, + }, + { + item: 'f', + time: 0, + attemptNumber: 0, }, ]); @@ -318,8 +341,39 @@ describe('Queue', () => { // wait long enough for the other queue to expire and be reclaimed jest.advanceTimersByTime(queue.timeouts.reclaimTimer + queue.timeouts.reclaimWait * 2); - expect(queue.processQueueCb).toHaveBeenCalledTimes(1); - expect(queue.processQueueCb).toHaveBeenCalledWith('a', expect.any(Function), 0, Infinity, true); + expect(queue.processQueueCb).toHaveBeenCalledTimes(4); + expect(queue.processQueueCb).toHaveBeenNthCalledWith( + 1, + 'a', + expect.any(Function), + 0, + Infinity, + true, + ); + expect(queue.processQueueCb).toHaveBeenNthCalledWith( + 2, + ['b', 'c'], + expect.any(Function), + 0, + Infinity, + true, + ); + expect(queue.processQueueCb).toHaveBeenNthCalledWith( + 3, + ['d', 'e'], + expect.any(Function), + 0, + Infinity, + true, + ); + expect(queue.processQueueCb).toHaveBeenNthCalledWith( + 4, + 'f', + expect.any(Function), + 0, + Infinity, + true, + ); }); it('should take over an in-progress task if a queue is abandoned', () => { @@ -334,10 +388,27 @@ describe('Queue', () => { ); foundQueue.set(foundQueue.validKeys.ACK, -15000); foundQueue.set(foundQueue.validKeys.IN_PROGRESS, { - 'task-id': { + 'task-id-1': { item: 'a', time: 0, attemptNumber: 0, + type: 'Single', + }, + 'task-id-2': { + item: ['b', 'c'], + time: 0, + attemptNumber: 0, + type: 'Batch', + }, + 'task-id-3': { + item: ['d', 'e'], + time: 0, + attemptNumber: 0, + }, + 'task-id-4': { + item: 'f', + time: 0, + attemptNumber: 0, }, }); @@ -349,8 +420,39 @@ describe('Queue', () => { // wait long enough for the other queue to expire and be reclaimed jest.advanceTimersByTime(queue.timeouts.reclaimTimer + queue.timeouts.reclaimWait * 2); - expect(queue.processQueueCb).toHaveBeenCalledTimes(1); - expect(queue.processQueueCb).toHaveBeenCalledWith('a', expect.any(Function), 1, Infinity, true); + expect(queue.processQueueCb).toHaveBeenCalledTimes(4); + expect(queue.processQueueCb).toHaveBeenNthCalledWith( + 1, + 'a', + expect.any(Function), + 1, + Infinity, + true, + ); + expect(queue.processQueueCb).toHaveBeenNthCalledWith( + 2, + ['b', 'c'], + expect.any(Function), + 1, + Infinity, + true, + ); + expect(queue.processQueueCb).toHaveBeenNthCalledWith( + 3, + ['d', 'e'], + expect.any(Function), + 1, + Infinity, + true, + ); + expect(queue.processQueueCb).toHaveBeenNthCalledWith( + 4, + 'f', + expect.any(Function), + 1, + Infinity, + true, + ); }); it('should take over a batch queued task if a queue is abandoned', () => { @@ -376,6 +478,7 @@ describe('Queue', () => { item: 'a', time: 0, attemptNumber: 0, + type: 'Single', }, { item: 'b', @@ -419,6 +522,7 @@ describe('Queue', () => { item: 'a', time: 0, attemptNumber: 0, + type: 'Single', }, { item: 'b', @@ -1070,18 +1174,21 @@ describe('Queue', () => { attemptNumber: 0, time: expect.any(Number), id: expect.any(String), + type: 'Single', }, { item: 'b', attemptNumber: 0, time: expect.any(Number), id: expect.any(String), + type: 'Single', }, { item: 'c', attemptNumber: 0, time: expect.any(Number), id: expect.any(String), + type: 'Single', }, ]); diff --git a/packages/analytics-js-plugins/__tests__/xhrQueue/index.test.ts b/packages/analytics-js-plugins/__tests__/xhrQueue/index.test.ts index d20a4f5053..360f5ff5e2 100644 --- a/packages/analytics-js-plugins/__tests__/xhrQueue/index.test.ts +++ b/packages/analytics-js-plugins/__tests__/xhrQueue/index.test.ts @@ -208,6 +208,7 @@ describe('XhrQueue', () => { attemptNumber: 1, id: 'sample_uuid', time: 1 + 1000 * 2 ** 1, // this is the delay calculation in RetryQueue + type: 'Single', }, ]); }); diff --git a/packages/analytics-js-plugins/__tests__/xhrQueue/utilities.test.ts b/packages/analytics-js-plugins/__tests__/xhrQueue/utilities.test.ts index 7cfb073bac..9b1a15bdf4 100644 --- a/packages/analytics-js-plugins/__tests__/xhrQueue/utilities.test.ts +++ b/packages/analytics-js-plugins/__tests__/xhrQueue/utilities.test.ts @@ -328,5 +328,61 @@ describe('xhrQueue Plugin Utilities', () => { '{"batch":[{"channel":"test","type":"track","anonymousId":"test","properties":{"test":"test"}},{"channel":"test","type":"track","anonymousId":"test","properties":{"test1":"test1","test3":{}}}],"sentAt":"2021-01-01T00:00:00.000Z"}', ); }); + + it('should return string with circular dependencies replaced with static string', () => { + const events = [ + { + channel: 'test', + type: 'track', + anonymousId: 'test', + userId: null, + properties: { + test: 'test', + test2: null, + }, + } as unknown as RudderEvent, + { + channel: 'test', + type: 'track', + anonymousId: 'test', + groupId: null, + properties: { + test1: 'test1', + test3: { + test4: null, + }, + }, + } as unknown as RudderEvent, + ]; + + events[1].properties.test5 = events[1]; + + expect(getBatchDeliveryPayload(events, currentTime, mockLogger)).toContain( + '[Circular Reference]', + ); + }); + + it('should return null if the payload cannot be stringified', () => { + const events = [ + { + channel: 'test', + type: 'track', + anonymousId: 'test', + properties: { + someBigInt: BigInt(9007199254740991), + }, + } as unknown as RudderEvent, + { + channel: 'test', + type: 'track', + anonymousId: 'test', + properties: { + test1: 'test1', + }, + } as unknown as RudderEvent, + ]; + + expect(getBatchDeliveryPayload(events, currentTime, mockLogger)).toBeNull(); + }); }); }); diff --git a/packages/analytics-js-plugins/package.json b/packages/analytics-js-plugins/package.json index dc70743708..941d933c9d 100644 --- a/packages/analytics-js-plugins/package.json +++ b/packages/analytics-js-plugins/package.json @@ -1,6 +1,6 @@ { "name": "@rudderstack/analytics-js-plugins", - "version": "3.6.0", + "version": "3.6.1", "private": true, "description": "RudderStack JavaScript SDK plugins", "main": "dist/npm/modern/cjs/index.cjs", diff --git a/packages/analytics-js-plugins/project.json b/packages/analytics-js-plugins/project.json index 41ea9633e2..51bcca01b4 100644 --- a/packages/analytics-js-plugins/project.json +++ b/packages/analytics-js-plugins/project.json @@ -51,9 +51,9 @@ "github": { "executor": "@jscutlery/semver:github", "options": { - "tag": "@rudderstack/analytics-js-plugins@3.6.0", - "title": "@rudderstack/analytics-js-plugins@3.6.0", - "discussion-category": "@rudderstack/analytics-js-plugins@3.6.0", + "tag": "@rudderstack/analytics-js-plugins@3.6.1", + "title": "@rudderstack/analytics-js-plugins@3.6.1", + "discussion-category": "@rudderstack/analytics-js-plugins@3.6.1", "notesFile": "./packages/analytics-js-plugins/CHANGELOG_LATEST.md" } } diff --git a/packages/analytics-js-plugins/src/beaconQueue/utilities.ts b/packages/analytics-js-plugins/src/beaconQueue/utilities.ts index 2e1e83c5ef..049196b2cf 100644 --- a/packages/analytics-js-plugins/src/beaconQueue/utilities.ts +++ b/packages/analytics-js-plugins/src/beaconQueue/utilities.ts @@ -31,7 +31,7 @@ const getBatchDeliveryPayload = ( }; try { - const blobPayload = json.stringifyData(data); + const blobPayload = json.stringifyWithoutCircular(data, true); const blobOptions: BlobPropertyBag = { type: 'text/plain' }; if (blobPayload) { diff --git a/packages/analytics-js-plugins/src/bugsnag/constants.ts b/packages/analytics-js-plugins/src/bugsnag/constants.ts index 5b45e385e7..931af3da70 100644 --- a/packages/analytics-js-plugins/src/bugsnag/constants.ts +++ b/packages/analytics-js-plugins/src/bugsnag/constants.ts @@ -31,7 +31,6 @@ const APP_STATE_EXCLUDE_KEYS = [ 'instance', // destination instance objects 'eventBuffer', // pre-load event buffer (may contain PII) 'traits', - 'authToken', ]; const BUGSNAG_PLUGIN = 'BugsnagPlugin'; diff --git a/packages/analytics-js-plugins/src/bugsnag/utils.ts b/packages/analytics-js-plugins/src/bugsnag/utils.ts index 8407876b4c..2dfa8b8aff 100644 --- a/packages/analytics-js-plugins/src/bugsnag/utils.ts +++ b/packages/analytics-js-plugins/src/bugsnag/utils.ts @@ -65,8 +65,8 @@ const isRudderSDKError = (event: BugsnagLib.Report) => { }; const getAppStateForMetadata = (state: ApplicationState): Record | undefined => { - const stateStr = json.stringifyData(state, true, APP_STATE_EXCLUDE_KEYS); - return JSON.parse(stateStr); + const stateStr = json.stringifyWithoutCircular(state, false, APP_STATE_EXCLUDE_KEYS); + return stateStr !== null ? JSON.parse(stateStr) : undefined; }; const enhanceErrorEventMutator = (state: ApplicationState, event: BugsnagLib.Report): void => { diff --git a/packages/analytics-js-plugins/src/errorReporting/constants.ts b/packages/analytics-js-plugins/src/errorReporting/constants.ts index 6fa61398c0..9765e672c6 100644 --- a/packages/analytics-js-plugins/src/errorReporting/constants.ts +++ b/packages/analytics-js-plugins/src/errorReporting/constants.ts @@ -17,7 +17,6 @@ const APP_STATE_EXCLUDE_KEYS = [ 'instance', // destination instance objects 'eventBuffer', // pre-load event buffer (may contain PII) 'traits', - 'authToken', ]; const REQUEST_TIMEOUT_MS = 10 * 1000; // 10 seconds const NOTIFIER_NAME = 'RudderStack JavaScript SDK Error Notifier'; diff --git a/packages/analytics-js-plugins/src/errorReporting/event/event.ts b/packages/analytics-js-plugins/src/errorReporting/event/event.ts index 3af8e3f73c..50f09c5c95 100644 --- a/packages/analytics-js-plugins/src/errorReporting/event/event.ts +++ b/packages/analytics-js-plugins/src/errorReporting/event/event.ts @@ -1,7 +1,8 @@ +import type { ErrorState } from '@rudderstack/analytics-js-common/types/ErrorHandler'; import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; import ErrorStackParser from 'error-stack-parser'; import type { Exception, Stackframe } from '@rudderstack/analytics-js-common/types/Metrics'; -import { stringifyData } from '@rudderstack/analytics-js-common/utilities/json'; +import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json'; import type { FrameType, IErrorFormat } from '../types'; import { hasStack, isError } from './utils'; import { ERROR_REPORTING_PLUGIN } from '../constants'; @@ -68,7 +69,7 @@ const normaliseError = (maybeError: any, component: string, logger?: ILogger) => error = maybeError; } else { logger?.warn( - `${ERROR_REPORTING_PLUGIN}:: ${component} received a non-error: ${stringifyData(error, false)}`, + `${ERROR_REPORTING_PLUGIN}:: ${component} received a non-error: ${stringifyWithoutCircular(error)}`, ); error = undefined; } diff --git a/packages/analytics-js-plugins/src/errorReporting/utils.ts b/packages/analytics-js-plugins/src/errorReporting/utils.ts index 7a8fcb8c92..3beeef3add 100644 --- a/packages/analytics-js-plugins/src/errorReporting/utils.ts +++ b/packages/analytics-js-plugins/src/errorReporting/utils.ts @@ -16,7 +16,7 @@ import type { } from '@rudderstack/analytics-js-common/types/Metrics'; import { generateUUID } from '@rudderstack/analytics-js-common/utilities/uuId'; import { METRICS_PAYLOAD_VERSION } from '@rudderstack/analytics-js-common/constants/metrics'; -import { stringifyData } from '@rudderstack/analytics-js-common/utilities/json'; +import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json'; import { ERROR_MESSAGES_TO_BE_FILTERED } from '@rudderstack/analytics-js-common/constants/errors'; import { APP_STATE_EXCLUDE_KEYS, @@ -67,8 +67,8 @@ const getReleaseStage = () => { }; const getAppStateForMetadata = (state: ApplicationState): Record => { - const stateStr = json.stringifyData(state, true, APP_STATE_EXCLUDE_KEYS); - return JSON.parse(stateStr); + const stateStr = json.stringifyWithoutCircular(state, false, APP_STATE_EXCLUDE_KEYS); + return stateStr !== null ? JSON.parse(stateStr) : {}; }; const getURLWithoutQueryString = () => { @@ -188,7 +188,7 @@ const getErrorDeliveryPayload = (payload: ErrorEventPayload, state: ApplicationS }, errors: payload, }; - return stringifyData(data) as string; + return stringifyWithoutCircular(data) as string; }; export { diff --git a/packages/analytics-js-plugins/src/types/plugins.ts b/packages/analytics-js-plugins/src/types/plugins.ts index 251048406f..bbb62ae972 100644 --- a/packages/analytics-js-plugins/src/types/plugins.ts +++ b/packages/analytics-js-plugins/src/types/plugins.ts @@ -7,11 +7,14 @@ export type RudderEventType = 'page' | 'track' | 'identify' | 'alias' | 'group'; export type LogLevel = 'LOG' | 'INFO' | 'DEBUG' | 'WARN' | 'ERROR' | 'NONE'; +export type QueueItemType = 'Single' | 'Batch'; + export type QueueItem = { item: T; attemptNumber: number; time: number; id: string; + type: QueueItemType; }; export type QueueItemData = diff --git a/packages/analytics-js-plugins/src/utilities/eventsDelivery.ts b/packages/analytics-js-plugins/src/utilities/eventsDelivery.ts index ad963f2b82..f6bbbedaeb 100644 --- a/packages/analytics-js-plugins/src/utilities/eventsDelivery.ts +++ b/packages/analytics-js-plugins/src/utilities/eventsDelivery.ts @@ -3,7 +3,7 @@ import { clone } from 'ramda'; import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages'; import type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable'; import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; -import { stringifyData } from '@rudderstack/analytics-js-common/utilities/json'; +import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json'; import { EVENT_PAYLOAD_SIZE_BYTES_LIMIT } from './constants'; import type { TransformationRequestPayload } from '../deviceModeTransformation/types'; @@ -14,6 +14,9 @@ const EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING = ( ): string => `${context}${LOG_CONTEXT_SEPARATOR}The size of the event payload (${payloadSize} bytes) exceeds the maximum limit of ${sizeLimit} bytes. Events with large payloads may be dropped in the future. Please review your instrumentation to ensure that event payloads are within the size limit.`; +const EVENT_PAYLOAD_SIZE_VALIDATION_WARNING = (context: string): string => + `${context}${LOG_CONTEXT_SEPARATOR}Failed to validate event payload size. Please make sure that the event payload is within the size limit and is a valid JSON object.`; + const QUEUE_UTILITIES = 'QueueUtilities'; /** @@ -22,11 +25,19 @@ const QUEUE_UTILITIES = 'QueueUtilities'; * @param logger Logger instance * @returns stringified event payload. Empty string if error occurs. */ -const getDeliveryPayload = (event: RudderEvent): string => - stringifyData(event) as string; +const getDeliveryPayload = (event: RudderEvent, logger?: ILogger): Nullable => + stringifyWithoutCircular(event, true, undefined, logger); -const getDMTDeliveryPayload = (dmtRequestPayload: TransformationRequestPayload): Nullable => - stringifyData(dmtRequestPayload); +const getDMTDeliveryPayload = ( + dmtRequestPayload: TransformationRequestPayload, + logger?: ILogger, +): Nullable => + stringifyWithoutCircular( + dmtRequestPayload, + true, + undefined, + logger, + ); /** * Utility to validate final payload size before sending to server @@ -34,16 +45,20 @@ const getDMTDeliveryPayload = (dmtRequestPayload: TransformationRequestPayload): * @param logger Logger instance */ const validateEventPayloadSize = (event: RudderEvent, logger?: ILogger) => { - const payloadStr = getDeliveryPayload(event); - const payloadSize = payloadStr.length; - if (payloadSize > EVENT_PAYLOAD_SIZE_BYTES_LIMIT) { - logger?.warn( - EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING( - QUEUE_UTILITIES, - payloadSize, - EVENT_PAYLOAD_SIZE_BYTES_LIMIT, - ), - ); + const payloadStr = getDeliveryPayload(event, logger); + if (payloadStr) { + const payloadSize = payloadStr.length; + if (payloadSize > EVENT_PAYLOAD_SIZE_BYTES_LIMIT) { + logger?.warn( + EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING( + QUEUE_UTILITIES, + payloadSize, + EVENT_PAYLOAD_SIZE_BYTES_LIMIT, + ), + ); + } + } else { + logger?.warn(EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(QUEUE_UTILITIES)); } }; diff --git a/packages/analytics-js-plugins/src/utilities/retryQueue/RetryQueue.ts b/packages/analytics-js-plugins/src/utilities/retryQueue/RetryQueue.ts index 721301960e..443b2f6563 100644 --- a/packages/analytics-js-plugins/src/utilities/retryQueue/RetryQueue.ts +++ b/packages/analytics-js-plugins/src/utilities/retryQueue/RetryQueue.ts @@ -19,6 +19,7 @@ import type { QueueItemData, QueueBatchItemsSizeCalculatorCallback, QueueProcessCallback, + QueueItemType, } from '../../types/plugins'; import { Schedule, ScheduleModes } from './Schedule'; import { RETRY_QUEUE_ENTRY_REMOVE_ERROR, RETRY_QUEUE_PROCESS_ERROR } from './logMessages'; @@ -39,6 +40,8 @@ import { DEFAULT_BATCH_FLUSH_INTERVAL_MS, MIN_TIMER_SCALE_FACTOR, MAX_TIMER_SCALE_FACTOR, + SINGLE_QUEUE_ITEM_TYPE, + BATCH_QUEUE_ITEM_TYPE, } from './constants'; const sortByTime = (a: QueueItem, b: QueueItem) => a.time - b.time; @@ -251,7 +254,10 @@ class RetryQueue implements IQueue { if (batchQueue.length > 0) { batchQueue = batchQueue.slice(-batchQueue.length); - const batchEntry = this.genQueueItem(batchQueue.map(queueItem => queueItem.item)); + const batchEntry = this.genQueueItem( + batchQueue.map(queueItem => queueItem.item), + BATCH_QUEUE_ITEM_TYPE, + ); this.setStorageEntry(QueueStatuses.BATCH_QUEUE, []); @@ -300,7 +306,7 @@ class RetryQueue implements IQueue { enqueue(entry: QueueItem) { let curEntry: QueueItem | undefined; - if (this.batch.enabled) { + if (this.batch.enabled && entry.type === SINGLE_QUEUE_ITEM_TYPE) { curEntry = this.handleNewItemForBatch(entry); } else { curEntry = entry; @@ -341,7 +347,7 @@ class RetryQueue implements IQueue { // Don't make any batch request if there are no items if (batchItems.length > 0) { - curEntry = this.genQueueItem(batchItems); + curEntry = this.genQueueItem(batchItems, BATCH_QUEUE_ITEM_TYPE); } // re-attach the timeout handler @@ -386,30 +392,36 @@ class RetryQueue implements IQueue { * @param itemData Queue item data * @returns Queue item */ - genQueueItem(itemData: QueueItemData): QueueItem { + genQueueItem( + itemData: QueueItemData, + type: QueueItemType = SINGLE_QUEUE_ITEM_TYPE, + ): QueueItem { return { item: itemData, attemptNumber: 0, time: this.schedule.now(), id: generateUUID(), + type, }; } /** * Adds an item to the retry queue * - * @param {Object} itemData The item to retry - * @param {Number} attemptNumber The attempt number (1 for first retry) - * @param {Error} [error] The error from previous attempt, if there was one - * @param {String} [id] The id of the queued message used for tracking duplicate entries + * @param {Object} qItem The item to process + * @param {Error} [error] The error that occurred during processing */ - requeue(itemData: QueueItemData, attemptNumber: number, error?: Error, id?: string) { - if (this.shouldRetry(itemData, attemptNumber)) { + requeue(qItem: QueueItem, error?: Error) { + const { attemptNumber, item, type, id } = qItem; + // Increment the attempt number as we're about to retry + const attemptNumberToUse = attemptNumber + 1; + if (this.shouldRetry(item, attemptNumberToUse)) { this.enqueue({ - item: itemData, - attemptNumber, - time: this.schedule.now() + this.getDelay(attemptNumber), + item, + attemptNumber: attemptNumberToUse, + time: this.schedule.now() + this.getDelay(attemptNumberToUse), id: id ?? generateUUID(), + type, }); } else { // Discard item @@ -474,7 +486,7 @@ class RetryQueue implements IQueue { this.setStorageEntry(QueueStatuses.IN_PROGRESS, inProgress); if (err) { - this.requeue(el.item, el.attemptNumber + 1, err, el.id); + this.requeue(el, err); } }; @@ -512,6 +524,7 @@ class RetryQueue implements IQueue { item: el.item, attemptNumber: el.attemptNumber, time: this.schedule.now(), + type: el.type, }; } @@ -591,11 +604,17 @@ class RetryQueue implements IQueue { if (trackMessageIds.includes(id)) { // duplicated event } else { + // Hack to determine the item type by the contents of the entry + // After some point, we can remove this hack as most of the stale data will have been processed + // and the new entries will have the type field set + const type = Array.isArray(el.item) ? BATCH_QUEUE_ITEM_TYPE : SINGLE_QUEUE_ITEM_TYPE; + our.queue.push({ item: el.item, attemptNumber: el.attemptNumber + incrementAttemptNumberBy, time: this.schedule.now(), id, + type: el.type ?? type, }); trackMessageIds.push(id); } @@ -615,6 +634,9 @@ class RetryQueue implements IQueue { if (this.batch.enabled) { their.batchQueue.forEach((el: QueueItem) => { const id = el.id ?? generateUUID(); + el.type = el.type ?? SINGLE_QUEUE_ITEM_TYPE; + el.time = this.schedule.now(); + if (trackMessageIds.includes(id)) { // duplicated event } else { diff --git a/packages/analytics-js-plugins/src/utilities/retryQueue/constants.ts b/packages/analytics-js-plugins/src/utilities/retryQueue/constants.ts index 5ed1d8023f..213ff150b0 100644 --- a/packages/analytics-js-plugins/src/utilities/retryQueue/constants.ts +++ b/packages/analytics-js-plugins/src/utilities/retryQueue/constants.ts @@ -17,6 +17,9 @@ const DEFAULT_MAX_BATCH_SIZE_BYTES = 512 * 1024; // 512 KB; this is also the max const DEFAULT_MAX_BATCH_ITEMS = 100; const DEFAULT_BATCH_FLUSH_INTERVAL_MS = 60 * 1000; // 1 minutes +const BATCH_QUEUE_ITEM_TYPE = 'Batch'; +const SINGLE_QUEUE_ITEM_TYPE = 'Single'; + export { DEFAULT_MIN_RETRY_DELAY_MS, DEFAULT_MAX_RETRY_DELAY_MS, @@ -33,4 +36,6 @@ export { DEFAULT_BATCH_FLUSH_INTERVAL_MS, MIN_TIMER_SCALE_FACTOR, MAX_TIMER_SCALE_FACTOR, + BATCH_QUEUE_ITEM_TYPE, + SINGLE_QUEUE_ITEM_TYPE, }; diff --git a/packages/analytics-js-plugins/src/xhrQueue/index.ts b/packages/analytics-js-plugins/src/xhrQueue/index.ts index c194e5a9ac..13978bc499 100644 --- a/packages/analytics-js-plugins/src/xhrQueue/index.ts +++ b/packages/analytics-js-plugins/src/xhrQueue/index.ts @@ -66,7 +66,11 @@ const XhrQueue = (): ExtensionPlugin => ({ maxRetryAttempts?: number, willBeRetried?: boolean, ) => { - const { data, url, headers } = getRequestInfo(itemData as XHRRetryQueueItemData, state); + const { data, url, headers } = getRequestInfo( + itemData as XHRRetryQueueItemData, + state, + logger, + ); httpClient.getAsyncData({ url, @@ -102,7 +106,7 @@ const XhrQueue = (): ExtensionPlugin => ({ const currentTime = getCurrentTimeFormatted(); const events = itemData.map((queueItemData: XHRQueueItemData) => queueItemData.event); // type casting to string as we know that the event has already been validated prior to enqueue - return (getBatchDeliveryPayload(events, currentTime) as string)?.length; + return (getBatchDeliveryPayload(events, currentTime, logger) as string)?.length; }, ); diff --git a/packages/analytics-js-plugins/src/xhrQueue/utilities.ts b/packages/analytics-js-plugins/src/xhrQueue/utilities.ts index 9f1ecf3bf7..4a3df97a3b 100644 --- a/packages/analytics-js-plugins/src/xhrQueue/utilities.ts +++ b/packages/analytics-js-plugins/src/xhrQueue/utilities.ts @@ -4,6 +4,7 @@ import type { ResponseDetails } from '@rudderstack/analytics-js-common/types/Htt import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; import type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState'; import type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event'; +import type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable'; import { clone } from 'ramda'; import { getCurrentTimeFormatted } from '@rudderstack/analytics-js-common/utilities/timestamp'; import { checks, http, url, json, eventsDelivery } from '../shared-chunks/common'; @@ -11,9 +12,13 @@ import { DATA_PLANE_API_VERSION, DEFAULT_RETRY_QUEUE_OPTIONS, XHR_QUEUE_PLUGIN } import type { XHRRetryQueueItemData, XHRQueueItemData, XHRBatchPayload } from './types'; import { EVENT_DELIVERY_FAILURE_ERROR_PREFIX } from './logMessages'; -const getBatchDeliveryPayload = (events: RudderEvent[], currentTime: string): string => { +const getBatchDeliveryPayload = ( + events: RudderEvent[], + currentTime: string, + logger?: ILogger, +): Nullable => { const batchPayload: XHRBatchPayload = { batch: events, sentAt: currentTime }; - return json.stringifyData(batchPayload); + return json.stringifyWithoutCircular(batchPayload, true, undefined, logger); }; const getNormalizedQueueOptions = (queueOpts: QueueOpts): QueueOpts => @@ -61,7 +66,11 @@ const logErrorOnFailure = ( logger?.error(errMsg); }; -const getRequestInfo = (itemData: XHRRetryQueueItemData, state: ApplicationState) => { +const getRequestInfo = ( + itemData: XHRRetryQueueItemData, + state: ApplicationState, + logger?: ILogger, +) => { let data; let headers; let url: string; @@ -70,14 +79,14 @@ const getRequestInfo = (itemData: XHRRetryQueueItemData, state: ApplicationState const finalEvents = itemData.map((queueItemData: XHRQueueItemData) => eventsDelivery.getFinalEventForDeliveryMutator(queueItemData.event, currentTime), ); - data = getBatchDeliveryPayload(finalEvents, currentTime); + data = getBatchDeliveryPayload(finalEvents, currentTime, logger); headers = itemData[0] ? clone(itemData[0].headers) : {}; url = getBatchDeliveryUrl(state.lifecycle.activeDataplaneUrl.value as string); } else { const { url: eventUrl, event, headers: eventHeaders } = itemData; const finalEvent = eventsDelivery.getFinalEventForDeliveryMutator(event, currentTime); - data = eventsDelivery.getDeliveryPayload(finalEvent); + data = eventsDelivery.getDeliveryPayload(finalEvent, logger); headers = clone(eventHeaders); url = eventUrl; } diff --git a/packages/analytics-js-service-worker/CHANGELOG.md b/packages/analytics-js-service-worker/CHANGELOG.md index 698140e14c..b0a32a48a9 100644 --- a/packages/analytics-js-service-worker/CHANGELOG.md +++ b/packages/analytics-js-service-worker/CHANGELOG.md @@ -2,6 +2,11 @@ This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver). +## [3.2.1](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-service-worker@3.2.0...@rudderstack/analytics-js-service-worker@3.2.1) (2024-11-12) + +### Dependency Updates + +* `@rudderstack/analytics-js-common` updated to version `3.12.1` ## [3.2.0](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-service-worker@3.1.17...@rudderstack/analytics-js-service-worker@3.2.0) (2024-11-08) ### Dependency Updates diff --git a/packages/analytics-js-service-worker/CHANGELOG_LATEST.md b/packages/analytics-js-service-worker/CHANGELOG_LATEST.md index 2a7228524e..1591cab7bb 100644 --- a/packages/analytics-js-service-worker/CHANGELOG_LATEST.md +++ b/packages/analytics-js-service-worker/CHANGELOG_LATEST.md @@ -1,10 +1,5 @@ -## [3.2.0](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-service-worker@3.1.17...@rudderstack/analytics-js-service-worker@3.2.0) (2024-11-08) +## [3.2.1](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-service-worker@3.2.0...@rudderstack/analytics-js-service-worker@3.2.1) (2024-11-12) ### Dependency Updates -* `@rudderstack/analytics-js-common` updated to version `3.12.0` - -### Features - -* add date datatype ([#1906](https://github.com/rudderlabs/rudder-sdk-js/issues/1906)) ([9c207f1](https://github.com/rudderlabs/rudder-sdk-js/commit/9c207f19f34b998cdb15b34eed3f435daff86dfd)) - +* `@rudderstack/analytics-js-common` updated to version `3.12.1` diff --git a/packages/analytics-js-service-worker/package.json b/packages/analytics-js-service-worker/package.json index a30cb02c02..e5e70cbdda 100644 --- a/packages/analytics-js-service-worker/package.json +++ b/packages/analytics-js-service-worker/package.json @@ -1,6 +1,6 @@ { "name": "@rudderstack/analytics-js-service-worker", - "version": "3.2.0", + "version": "3.2.1", "description": "RudderStack JavaScript Service Worker SDK", "main": "dist/npm/modern/cjs/index.cjs", "module": "dist/npm/modern/esm/index.mjs", diff --git a/packages/analytics-js-service-worker/project.json b/packages/analytics-js-service-worker/project.json index 6705ea047c..9196352812 100644 --- a/packages/analytics-js-service-worker/project.json +++ b/packages/analytics-js-service-worker/project.json @@ -51,9 +51,9 @@ "github": { "executor": "@jscutlery/semver:github", "options": { - "tag": "@rudderstack/analytics-js-service-worker@3.2.0", - "title": "rudderstack/analytics-js-service-worker@3.2.0", - "discussion-category": "rudderstack/analytics-js-service-worker@3.2.0", + "tag": "@rudderstack/analytics-js-service-worker@3.2.1", + "title": "rudderstack/analytics-js-service-worker@3.2.1", + "discussion-category": "rudderstack/analytics-js-service-worker@3.2.1", "notesFile": "./packages/analytics-js-service-worker/CHANGELOG_LATEST.md" } } diff --git a/packages/analytics-js/CHANGELOG.md b/packages/analytics-js/CHANGELOG.md index 02d271834d..0b7d1436cc 100644 --- a/packages/analytics-js/CHANGELOG.md +++ b/packages/analytics-js/CHANGELOG.md @@ -2,6 +2,19 @@ This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver). +## [3.10.1](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js@3.10.0...@rudderstack/analytics-js@3.10.1) (2024-11-12) + +### Dependency Updates + +* `@rudderstack/analytics-js-cookies` updated to version `0.4.1` +* `@rudderstack/analytics-js-common` updated to version `3.12.1` +* `@rudderstack/analytics-js-plugins` updated to version `3.6.1` + +### Bug Fixes + +* batch entry retry ([#1918](https://github.com/rudderlabs/rudder-sdk-js/issues/1918)) ([ff346b8](https://github.com/rudderlabs/rudder-sdk-js/commit/ff346b867335750d7b428cab9c650a4d9dbfde57)) +* revert sanitization changes ([#1916](https://github.com/rudderlabs/rudder-sdk-js/issues/1916)) ([890fb7b](https://github.com/rudderlabs/rudder-sdk-js/commit/890fb7b615535992290f5008b93d77b540c03955)), closes [#1907](https://github.com/rudderlabs/rudder-sdk-js/issues/1907) [#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902) + ## [3.10.0](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js@3.9.1...@rudderstack/analytics-js@3.10.0) (2024-11-08) ### Dependency Updates diff --git a/packages/analytics-js/CHANGELOG_LATEST.md b/packages/analytics-js/CHANGELOG_LATEST.md index ec0763b201..dfbd9e70a9 100644 --- a/packages/analytics-js/CHANGELOG_LATEST.md +++ b/packages/analytics-js/CHANGELOG_LATEST.md @@ -1,13 +1,13 @@ -## [3.10.0](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js@3.9.1...@rudderstack/analytics-js@3.10.0) (2024-11-08) +## [3.10.1](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js@3.10.0...@rudderstack/analytics-js@3.10.1) (2024-11-12) ### Dependency Updates -* `@rudderstack/analytics-js-cookies` updated to version `0.4.0` -* `@rudderstack/analytics-js-common` updated to version `3.12.0` -* `@rudderstack/analytics-js-plugins` updated to version `3.6.0` +* `@rudderstack/analytics-js-cookies` updated to version `0.4.1` +* `@rudderstack/analytics-js-common` updated to version `3.12.1` +* `@rudderstack/analytics-js-plugins` updated to version `3.6.1` -### Features +### Bug Fixes -* add error handling to all public apis ([#1907](https://github.com/rudderlabs/rudder-sdk-js/issues/1907)) ([9fbaf81](https://github.com/rudderlabs/rudder-sdk-js/commit/9fbaf819bb02320d2f8ae82a869ad2b85090ea34)) -* sanitize input data ([#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902)) ([b71c44a](https://github.com/rudderlabs/rudder-sdk-js/commit/b71c44ae61f6c35cadc6523b918e1a574e32bc23)) +* batch entry retry ([#1918](https://github.com/rudderlabs/rudder-sdk-js/issues/1918)) ([ff346b8](https://github.com/rudderlabs/rudder-sdk-js/commit/ff346b867335750d7b428cab9c650a4d9dbfde57)) +* revert sanitization changes ([#1916](https://github.com/rudderlabs/rudder-sdk-js/issues/1916)) ([890fb7b](https://github.com/rudderlabs/rudder-sdk-js/commit/890fb7b615535992290f5008b93d77b540c03955)), closes [#1907](https://github.com/rudderlabs/rudder-sdk-js/issues/1907) [#1902](https://github.com/rudderlabs/rudder-sdk-js/issues/1902) diff --git a/packages/analytics-js/__tests__/app/RudderAnalytics.test.ts b/packages/analytics-js/__tests__/app/RudderAnalytics.test.ts index 690c96114b..85afcbd90b 100644 --- a/packages/analytics-js/__tests__/app/RudderAnalytics.test.ts +++ b/packages/analytics-js/__tests__/app/RudderAnalytics.test.ts @@ -16,6 +16,7 @@ describe('Core - Rudder Analytics Facade', () => { } as LoadOptions; beforeEach(() => { + Analytics.mockClear(); analyticsInstanceMock = new Analytics() as jest.Mocked; (window as any).rudderanalytics = [ ['track'], @@ -30,10 +31,11 @@ describe('Core - Rudder Analytics Facade', () => { }); afterEach(() => { + (rudderAnalytics as any).globalSingleton = null; jest.resetAllMocks(); }); - it('should return the global singleton from "rudderanalytics" global object', () => { + it('should return the global singleton from "rudderanalytics" global object', done => { const expectedPreloadedEvents = [ ['consent', { sendPageEvent: true }], ['consent', { sendPageEvent: false }], @@ -44,6 +46,7 @@ describe('Core - Rudder Analytics Facade', () => { expect(window.RudderStackGlobals?.app?.preloadedEventsBuffer).toEqual(expectedPreloadedEvents); expect(window.rudderanalytics).toEqual(globalSingleton); + done(); }); it('should retrieve all preloaded events and set to global', () => { @@ -55,27 +58,6 @@ describe('Core - Rudder Analytics Facade', () => { ]); }); - it('should return an empty array when globalThis.rudderanalytics is not an array', () => { - const rudderAnalyticsInstance = new RudderAnalytics(); - (globalThis as typeof window).rudderanalytics = undefined; - const result = rudderAnalyticsInstance.getPreloadedEvents(); - expect(result).toEqual([]); - }); - - it('should return buffered events array when globalThis.rudderanalytics is an array', () => { - const bufferedEvents = [ - ['track'], - ['consent', { sendPageEvent: true }], - ['load', 'dummyWriteKey', 'dummyDataPlaneUrl', { option1: true }], - ['consent', { sendPageEvent: false }], - ['track'], - ]; - (window as any).rudderanalytics = bufferedEvents; - const rudderAnalyticsInstance = new RudderAnalytics(); - const result = rudderAnalyticsInstance.getPreloadedEvents(); - expect(result).toEqual(bufferedEvents); - }); - it('should return the global singleton if it exists', () => { const globalSingleton = rudderAnalytics; rudderAnalytics = new RudderAnalytics(); @@ -83,54 +65,20 @@ describe('Core - Rudder Analytics Facade', () => { expect(rudderAnalytics).toEqual(globalSingleton); }); - it('should dispatch an error event if an exception is thrown during the construction', () => { - const originalSingleton = RudderAnalytics.globalSingleton; - - RudderAnalytics.globalSingleton = null; - - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Explicitly throw an error during the construction - const nowSpy = jest.spyOn(Date, 'now').mockImplementation(() => { - throw new Error('Error in now function'); - }); - - // eslint-disable-next-line sonarjs/constructor-for-side-effects, no-new - new RudderAnalytics(); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in now function'), - }), - ); - - RudderAnalytics.globalSingleton = originalSingleton; - nowSpy.mockRestore(); - - dispatchEventSpy.mockRestore(); - }); - it('should auto set the default analytics key if no analytics instances exist', () => { (rudderAnalytics as any).analyticsInstances = {}; (rudderAnalytics as any).defaultAnalyticsKey = ''; - rudderAnalytics.setDefaultInstanceKey('writeKey'); expect(rudderAnalytics.defaultAnalyticsKey).toEqual('writeKey'); }); - it('should set the default analytics key even if analytics instances exist', () => { + it('should auto set the default analytics key if analytics instances exist', () => { rudderAnalytics.setDefaultInstanceKey('writeKey2'); expect(rudderAnalytics.defaultAnalyticsKey).toEqual('writeKey2'); }); - it('should not set default analytics key if the key is not a valid string', () => { - rudderAnalytics.setDefaultInstanceKey(''); - - expect(rudderAnalytics.defaultAnalyticsKey).toEqual('writeKey'); - }); - it('should return an existing analytics instance', () => { expect(rudderAnalytics.getAnalyticsInstance('writeKey')).toStrictEqual(analyticsInstanceMock); }); @@ -158,25 +106,6 @@ describe('Core - Rudder Analytics Facade', () => { expect(rudderAnalytics.getAnalyticsInstance('writeKey')).toStrictEqual(analyticsInstance); }); - it('should return undefined and log error if an exception is thrown while getting the analytics instance', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally set the parameter to undefined to trigger an error - (rudderAnalytics as any).analyticsInstances = undefined; - - const result = rudderAnalytics.getAnalyticsInstance('writeKey2'); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new TypeError("Cannot read properties of undefined (reading 'writeKey2')"), - }), - ); - - expect(result).toBeUndefined(); - - dispatchEventSpy.mockRestore(); - }); - it('should set the default analytics key if none has been set', () => { rudderAnalytics.load('writeKey', 'data-plane-url'); @@ -187,674 +116,298 @@ describe('Core - Rudder Analytics Facade', () => { rudderAnalytics.analyticsInstances = {}; rudderAnalytics.defaultAnalyticsKey = ''; rudderAnalytics.load('writeKey', 'data-plane-url', mockLoadOptions); - const analyticsInstance = rudderAnalytics.getAnalyticsInstance('writeKey') as Analytics; + const analyticsInstance = rudderAnalytics.getAnalyticsInstance('writeKey'); const loadSpy = jest.spyOn(analyticsInstance, 'load'); expect(rudderAnalytics.analyticsInstances).toHaveProperty('writeKey', analyticsInstance); expect(loadSpy).toHaveBeenCalledWith('writeKey', 'data-plane-url', mockLoadOptions); }); - it('should dispatch an error event if an exception is thrown during the load', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally set the parameter to undefined to trigger an error - (rudderAnalytics as any).analyticsInstances = undefined; - - rudderAnalytics.defaultAnalyticsKey = ''; - rudderAnalytics.load('writeKey', 'data-plane-url', mockLoadOptions); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new TypeError("Cannot read properties of undefined (reading 'writeKey')"), - }), - ); - - dispatchEventSpy.mockRestore(); - }); - it('should process ready arguments and forwards to ready call', () => { - const callback = () => console.log('Ready!'); - - rudderAnalytics.ready(callback); - expect(analyticsInstanceMock.ready).toHaveBeenCalledWith(expect.any(Function)); - }); - - it('should dispatch an error event if an exception is thrown during the ready call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the ready call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const readySpy = jest.spyOn(analyticsInstance, 'ready'); const callback = () => console.log('Ready!'); rudderAnalytics.ready(callback); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); - getAnalyticsInstanceSpy.mockRestore(); + expect(readySpy).toHaveBeenCalledWith(expect.any(Function)); }); it('should process page arguments and forwards to page call', () => { + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const pageSpy = jest.spyOn(analyticsInstance, 'page'); + rudderAnalytics.page('category'); - expect(analyticsInstanceMock.page).toHaveBeenCalledWith({ + expect(pageSpy).toHaveBeenCalledWith({ name: 'category', properties: { name: 'category' }, }); }); - it('should dispatch an error event if an exception is thrown during the page call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the page call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - rudderAnalytics.page('category'); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); - - getAnalyticsInstanceSpy.mockRestore(); - }); - it('should process track arguments and forwards to track call', () => { - rudderAnalytics.track('event'); - expect(analyticsInstanceMock.track).toHaveBeenCalledWith({ name: 'event', properties: {} }); - }); - - it('should dispatch an error event if an exception is thrown during the track call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the track call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const trackSpy = jest.spyOn(analyticsInstance, 'track'); rudderAnalytics.track('event'); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); - - getAnalyticsInstanceSpy.mockRestore(); + expect(trackSpy).toHaveBeenCalledWith({ name: 'event', properties: {} }); }); it('should process identify arguments and forwards to identify call', () => { - rudderAnalytics.identify('1234'); - expect(analyticsInstanceMock.identify).toHaveBeenCalledWith({ userId: '1234' }); - }); - - it('should dispatch an error event if an exception is thrown during the identify call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the identify call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - rudderAnalytics.identify('1234'); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const identifySpy = jest.spyOn(analyticsInstance, 'identify'); - getAnalyticsInstanceSpy.mockRestore(); + rudderAnalytics.identify(1234); + expect(identifySpy).toHaveBeenCalledWith({ userId: '1234' }); }); it('should process alias arguments and forwards to alias call', () => { - rudderAnalytics.alias('abc'); - expect(analyticsInstanceMock.alias).toHaveBeenCalledWith({ to: 'abc' }); - }); - - it('should dispatch an error event if an exception is thrown during the alias call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the alias call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - rudderAnalytics.alias('abc'); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const aliasSpy = jest.spyOn(analyticsInstance, 'alias'); - getAnalyticsInstanceSpy.mockRestore(); + rudderAnalytics.alias('1234'); + expect(aliasSpy).toHaveBeenCalledWith({ to: '1234' }); }); it('should process group arguments and forwards to group call', () => { - rudderAnalytics.group('5678'); - expect(analyticsInstanceMock.group).toHaveBeenCalledWith({ groupId: '5678' }); - }); - - it('should dispatch an error event if an exception is thrown during the group call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the group call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - rudderAnalytics.group('5678'); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const groupSpy = jest.spyOn(analyticsInstance, 'group'); - getAnalyticsInstanceSpy.mockRestore(); + rudderAnalytics.group(1234); + expect(groupSpy).toHaveBeenCalledWith({ groupId: '1234' }); }); it('should process reset arguments and forwards to reset call', () => { - rudderAnalytics.reset(true); - expect(analyticsInstanceMock.reset).toHaveBeenCalledWith(true); - }); - - it('should dispatch an error event if an exception is thrown during the reset call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the reset call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const resetSpy = jest.spyOn(analyticsInstance, 'reset'); rudderAnalytics.reset(true); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); - - getAnalyticsInstanceSpy.mockRestore(); + expect(resetSpy).toHaveBeenCalledWith(true); }); it('should process getAnonymousId arguments and forwards to getAnonymousId call', () => { + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const getAnonymousIdSpy = jest.spyOn(analyticsInstance, 'getAnonymousId'); + rudderAnalytics.getAnonymousId({ autoCapture: { enabled: true, }, }); - expect(analyticsInstanceMock.getAnonymousId).toHaveBeenCalledWith({ - autoCapture: { enabled: true }, - }); - }); - - it('should return undefined and log an error if an exception is thrown during the getAnonymousId call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the getAnonymousId call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - const result = rudderAnalytics.getAnonymousId(); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); - expect(result).toBeUndefined(); - - getAnalyticsInstanceSpy.mockRestore(); + expect(getAnonymousIdSpy).toHaveBeenCalledWith({ autoCapture: { enabled: true } }); }); it('should process setAnonymousId arguments and forwards to setAnonymousId call', () => { - rudderAnalytics.setAnonymousId('id', 'param'); - expect(analyticsInstanceMock.setAnonymousId).toHaveBeenCalledWith('id', 'param'); - }); - - it('should dispatch an error event if an exception is thrown during the setAnonymousId call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the setAnonymousId call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - rudderAnalytics.setAnonymousId('id'); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const setAnonymousIdSpy = jest.spyOn(analyticsInstance, 'setAnonymousId'); - getAnalyticsInstanceSpy.mockRestore(); + rudderAnalytics.setAnonymousId('id', 'param'); + expect(setAnonymousIdSpy).toHaveBeenCalledWith('id', 'param'); }); it('should process getUserId arguments and forwards to getUserId call', () => { + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const getUserIdSpy = jest.spyOn(analyticsInstance, 'getUserId'); + rudderAnalytics.getUserId(); - expect(analyticsInstanceMock.getUserId).toHaveBeenCalledTimes(1); + expect(getUserIdSpy).toHaveBeenCalledTimes(1); }); it('should process getUserTraits arguments and forwards to getUserTraits call', () => { + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const getUserTraitsSpy = jest.spyOn(analyticsInstance, 'getUserTraits'); + rudderAnalytics.getUserTraits(); - expect(analyticsInstanceMock.getUserTraits).toHaveBeenCalledTimes(1); + expect(getUserTraitsSpy).toHaveBeenCalledTimes(1); }); it('should process getGroupId arguments and forwards to getGroupId call', () => { + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const getGroupIdSpy = jest.spyOn(analyticsInstance, 'getGroupId'); + rudderAnalytics.getGroupId(); - expect(analyticsInstanceMock.getGroupId).toHaveBeenCalledTimes(1); + expect(getGroupIdSpy).toHaveBeenCalledTimes(1); }); it('should process getGroupTraits arguments and forwards to getGroupTraits call', () => { + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const getGroupTraitsSpy = jest.spyOn(analyticsInstance, 'getGroupTraits'); + rudderAnalytics.getGroupTraits(); - expect(analyticsInstanceMock.getGroupTraits).toHaveBeenCalledTimes(1); + expect(getGroupTraitsSpy).toHaveBeenCalledTimes(1); }); it('should process startSession arguments and forwards to startSession call', () => { - rudderAnalytics.startSession(1234); - expect(analyticsInstanceMock.startSession).toHaveBeenCalledWith(1234); - }); - - it('should dispatch an error event if an exception is thrown during the startSession call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the startSession call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const startSessionSpy = jest.spyOn(analyticsInstance, 'startSession'); rudderAnalytics.startSession(1234); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); - - getAnalyticsInstanceSpy.mockRestore(); + expect(startSessionSpy).toHaveBeenCalledWith(1234); }); it('should process endSession arguments and forwards to endSession call', () => { + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const endSessionSpy = jest.spyOn(analyticsInstance, 'endSession'); + rudderAnalytics.endSession(); - expect(analyticsInstanceMock.endSession).toHaveBeenCalledTimes(1); + expect(endSessionSpy).toHaveBeenCalledTimes(1); }); it('should process getSessionId arguments and forwards to getSessionId call', () => { + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const getSessionIdSpy = jest.spyOn(analyticsInstance, 'getSessionId'); + rudderAnalytics.getSessionId(); - expect(analyticsInstanceMock.getSessionId).toHaveBeenCalledTimes(1); + expect(getSessionIdSpy).toHaveBeenCalledTimes(1); }); it('should process setAuthToken arguments and forwards to setAuthToken call', () => { - rudderAnalytics.setAuthToken('token'); - expect(analyticsInstanceMock.setAuthToken).toHaveBeenCalledWith('token'); - }); - - it('should dispatch an error event if an exception is thrown during the setAuthToken call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the setAuthToken call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const setAuthTokenSpy = jest.spyOn(analyticsInstance, 'setAuthToken'); rudderAnalytics.setAuthToken('token'); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); - - getAnalyticsInstanceSpy.mockRestore(); + expect(setAuthTokenSpy).toHaveBeenCalledWith('token'); }); it('should process consent arguments and forwards to consent call', () => { + const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); + const consentSpy = jest.spyOn(analyticsInstance, 'consent'); + rudderAnalytics.consent({ consentManagement: { allowedConsentIds: ['1'], deniedConsentIds: ['2'], }, }); - expect(analyticsInstanceMock.consent).toHaveBeenCalledWith({ - consentManagement: { - allowedConsentIds: ['1'], - deniedConsentIds: ['2'], - }, - }); - }); - - it('should dispatch an error event if an exception is thrown during the consent call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the consent call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - rudderAnalytics.consent({ + expect(consentSpy).toHaveBeenCalledWith({ consentManagement: { allowedConsentIds: ['1'], deniedConsentIds: ['2'], }, }); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - dispatchEventSpy.mockRestore(); - - getAnalyticsInstanceSpy.mockRestore(); }); - it('should dispatch an error event if an exception is thrown during the getUserId call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the getUserId call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - const userIdVal = rudderAnalytics.getUserId(); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - expect(userIdVal).toBeUndefined(); - - dispatchEventSpy.mockRestore(); - - getAnalyticsInstanceSpy.mockRestore(); + it('should return an empty array when globalThis.rudderanalytics is not an array', () => { + const rudderAnalyticsInstance = new RudderAnalytics(); + (globalThis as typeof window).rudderanalytics = undefined; + const result = rudderAnalyticsInstance.getPreloadedEvents(); + expect(result).toEqual([]); }); - it('should dispatch an error event if an exception is thrown during the getUserTraits call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the getUserTraits call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - const traitsVal = rudderAnalytics.getUserTraits(); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - expect(traitsVal).toBeUndefined(); - - dispatchEventSpy.mockRestore(); - - getAnalyticsInstanceSpy.mockRestore(); + it('should return buffered events array when globalThis.rudderanalytics is an array', () => { + const bufferedEvents = [ + ['track'], + ['consent', { sendPageEvent: true }], + ['load', 'dummyWriteKey', 'dummyDataPlaneUrl', { option1: true }], + ['consent', { sendPageEvent: false }], + ['track'], + ]; + (window as any).rudderanalytics = bufferedEvents; + const rudderAnalyticsInstance = new RudderAnalytics(); + const result = rudderAnalyticsInstance.getPreloadedEvents(); + expect(result).toEqual(bufferedEvents); }); +}); - it('should dispatch an error event if an exception is thrown during the getGroupId call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the getGroupId call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - const groupId = rudderAnalytics.getGroupId(); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - expect(groupId).toBeUndefined(); - - dispatchEventSpy.mockRestore(); +describe('trackPageLifecycleEvents', () => { + let rudderAnalyticsInstance: RudderAnalytics; - getAnalyticsInstanceSpy.mockRestore(); + beforeEach(() => { + (window as any).rudderanalytics = []; + rudderAnalyticsInstance = new RudderAnalytics(); + rudderAnalyticsInstance.analyticsInstances = {}; }); - it('should dispatch an error event if an exception is thrown during the getGroupTraits call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the getGroupTraits call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - const traitsVal = rudderAnalytics.getGroupTraits(); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - expect(traitsVal).toBeUndefined(); - - dispatchEventSpy.mockRestore(); - - getAnalyticsInstanceSpy.mockRestore(); + afterEach(() => { + (rudderAnalyticsInstance as any).globalSingleton = null; + jest.resetAllMocks(); }); - it('should dispatch an error event if an exception is thrown during the endSession call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the endSession call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - rudderAnalytics.endSession(); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); + it('should not add pageLifecycleEvents in the buffer when the tracking is not enabled through load options', () => { + const bufferedEvents: PreloadedEventCall[] = []; + rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, {}); - dispatchEventSpy.mockRestore(); - - getAnalyticsInstanceSpy.mockRestore(); + expect(bufferedEvents).toEqual([]); }); - it('should dispatch an error event if an exception is thrown during the getSessionId call', () => { - const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - - // Intentionally cause an error during the getSessionId call - const getAnalyticsInstanceSpy = jest - .spyOn(rudderAnalytics, 'getAnalyticsInstance') - .mockImplementation(() => { - throw new Error('Error in getAnalyticsInstance'); - }); - - const sessionId = rudderAnalytics.getSessionId(); - - expect(dispatchEventSpy).toHaveBeenCalledWith( - new ErrorEvent('error', { - error: new Error('Error in getAnalyticsInstance'), - }), - ); - - expect(sessionId).toBeUndefined(); - - dispatchEventSpy.mockRestore(); + it('should inherit enabled and options properties from autoTrack load option', () => { + const bufferedEvents: PreloadedEventCall[] = []; + rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { + autoTrack: { + enabled: true, + options: { key: 'value' }, + }, + }); - getAnalyticsInstanceSpy.mockRestore(); + expect(bufferedEvents).toEqual([ + ['track', 'Page Loaded', {}, { key: 'value', originalTimestamp: expect.any(String) }], + ]); }); - describe('trackPageLifecycleEvents', () => { - let rudderAnalyticsInstance: RudderAnalytics; - - beforeEach(() => { - (window as any).rudderanalytics = []; - rudderAnalyticsInstance = new RudderAnalytics(); - rudderAnalyticsInstance.analyticsInstances = {}; - }); - - afterEach(() => { - (rudderAnalyticsInstance as any).globalSingleton = null; - jest.resetAllMocks(); + it('should override enabled and options properties of autoTrack if provided in load option', () => { + const bufferedEvents: PreloadedEventCall[] = []; + rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { + autoTrack: { + enabled: true, + options: { key: 'value' }, + pageLifecycle: { + enabled: false, + }, + }, }); - it('should not add pageLifecycleEvents in the buffer when the tracking is not enabled through load options', () => { - const bufferedEvents: PreloadedEventCall[] = []; - rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, {}); - - expect(bufferedEvents).toEqual([]); - }); + expect(bufferedEvents).toEqual([]); + }); - it('should inherit enabled and options properties from autoTrack load option', () => { - const bufferedEvents: PreloadedEventCall[] = []; - rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { - autoTrack: { + it('should track Page Loaded event irrespective of useBeacon load option', () => { + const bufferedEvents: PreloadedEventCall[] = []; + rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { + useBeacon: false, + autoTrack: { + pageLifecycle: { enabled: true, - options: { key: 'value' }, }, - }); - - expect(bufferedEvents).toEqual([ - ['track', 'Page Loaded', {}, { key: 'value', originalTimestamp: expect.any(String) }], - ]); + }, }); - it('should override enabled and options properties of autoTrack if provided in load option', () => { - const bufferedEvents: PreloadedEventCall[] = []; - rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { - autoTrack: { - enabled: true, - options: { key: 'value' }, - pageLifecycle: { - enabled: false, - }, - }, - }); - - expect(bufferedEvents).toEqual([]); - }); + expect(bufferedEvents).toEqual([ + ['track', 'Page Loaded', {}, { originalTimestamp: expect.any(String) }], + ]); + }); - it('should track Page Loaded event irrespective of useBeacon load option', () => { - const bufferedEvents: PreloadedEventCall[] = []; - rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { - useBeacon: false, - autoTrack: { - pageLifecycle: { - enabled: true, - }, + it('should track Page Unloaded event if useBeacon is set to true and trackPageLifecycle feature is enabled', () => { + const bufferedEvents: PreloadedEventCall[] = []; + rudderAnalyticsInstance.track = jest.fn(); + rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { + useBeacon: true, + autoTrack: { + pageLifecycle: { + enabled: true, }, - }); - - expect(bufferedEvents).toEqual([ - ['track', 'Page Loaded', {}, { originalTimestamp: expect.any(String) }], - ]); + }, }); + state.lifecycle.loaded.value = true; + const event = new Event('beforeunload'); + // Simulate the event + window.dispatchEvent(event); + + expect(rudderAnalyticsInstance.track).toHaveBeenCalledWith( + 'Page Unloaded', + { visitDuration: expect.any(Number) }, + { originalTimestamp: expect.any(String) }, + ); + }); - it('should track Page Unloaded event if useBeacon is set to true and trackPageLifecycle feature is enabled', () => { - const bufferedEvents: PreloadedEventCall[] = []; - rudderAnalyticsInstance.track = jest.fn(); - rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { - useBeacon: true, - autoTrack: { - pageLifecycle: { - enabled: true, - }, - }, - }); - state.lifecycle.loaded.value = true; - const event = new Event('beforeunload'); - // Simulate the event - window.dispatchEvent(event); - - expect(rudderAnalyticsInstance.track).toHaveBeenCalledWith( - 'Page Unloaded', - { visitDuration: expect.any(Number) }, - { originalTimestamp: expect.any(String) }, - ); + it('should invoke trackPageLifecycleEvents method when load API is called', () => { + rudderAnalyticsInstance.trackPageLifecycleEvents = jest.fn(); + rudderAnalyticsInstance.load('writeKey', 'data-plane-url', { + autoTrack: { + enabled: true, + }, }); - - it('should invoke trackPageLifecycleEvents method when load API is called', () => { - rudderAnalyticsInstance.trackPageLifecycleEvents = jest.fn(); - rudderAnalyticsInstance.load('writeKey', 'data-plane-url', { - autoTrack: { - enabled: true, - }, - }); - expect(rudderAnalyticsInstance.trackPageLifecycleEvents).toHaveBeenCalledWith([], { - autoTrack: { - enabled: true, - }, - }); + expect(rudderAnalyticsInstance.trackPageLifecycleEvents).toHaveBeenCalledWith([], { + autoTrack: { + enabled: true, + }, }); }); }); diff --git a/packages/analytics-js/__tests__/components/configManager/ConfigManager.test.ts b/packages/analytics-js/__tests__/components/configManager/ConfigManager.test.ts index 9f1fc09154..df73dd4f04 100644 --- a/packages/analytics-js/__tests__/components/configManager/ConfigManager.test.ts +++ b/packages/analytics-js/__tests__/components/configManager/ConfigManager.test.ts @@ -85,6 +85,23 @@ describe('ConfigManager', () => { server.close(); }); + it('should throw an error for invalid writeKey', () => { + state.lifecycle.writeKey.value = ' '; + expect(() => { + configManagerInstance.init(); + }).toThrow(errorMsg); + }); + + it('should throw error for invalid data plane url', () => { + state.lifecycle.writeKey.value = sampleWriteKey; + state.lifecycle.dataPlaneUrl.value = ' '; + expect(() => { + configManagerInstance.init(); + }).toThrow( + 'The data plane URL " " is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.', + ); + }); + it('should update lifecycle state with proper values', () => { getSDKUrl.mockImplementation(() => sampleScriptURL); diff --git a/packages/analytics-js/__tests__/components/configManager/validate.test.ts b/packages/analytics-js/__tests__/components/configManager/validate.test.ts index ccaa68f39a..2176388a7b 100644 --- a/packages/analytics-js/__tests__/components/configManager/validate.test.ts +++ b/packages/analytics-js/__tests__/components/configManager/validate.test.ts @@ -1,10 +1,38 @@ import { + validateLoadArgs, getTopDomainUrl, getDataServiceUrl, isWebpageTopLevelDomain, } from '../../../src/components/configManager/util/validate'; describe('Config manager util - validate load arguments', () => { + const sampleWriteKey = 'dummyWriteKey'; + const sampleDataPlaneUrl = 'https://www.dummy.url'; + const errorMsg = + 'The write key " " is invalid. It must be a non-empty string. Please check that the write key is correct and try again.'; + + it('should not throw error for valid write key', () => { + expect(() => { + validateLoadArgs(sampleWriteKey); + }).not.toThrow(errorMsg); + }); + it('should not throw error for valid data plane url', () => { + expect(() => { + validateLoadArgs(sampleWriteKey, sampleDataPlaneUrl); + }).not.toThrow('Unable to load the SDK due to invalid data plane URL: " "'); + }); + it('should throw error for invalid write key', () => { + expect(() => { + validateLoadArgs(' '); + }).toThrow(errorMsg); + }); + it('should throw error for invalid data plane url', () => { + expect(() => { + validateLoadArgs(sampleWriteKey, ' '); + }).toThrow( + 'The data plane URL " " is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.', + ); + }); describe('getTopDomainUrl', () => { const testCaseData = [ ['https://sub.example.com', 'https://example.com'], diff --git a/packages/analytics-js/__tests__/components/core/Analytics.test.ts b/packages/analytics-js/__tests__/components/core/Analytics.test.ts index f10e2ff0fa..e85709a4d6 100644 --- a/packages/analytics-js/__tests__/components/core/Analytics.test.ts +++ b/packages/analytics-js/__tests__/components/core/Analytics.test.ts @@ -128,77 +128,12 @@ describe('Core - Analytics', () => { expect(setMinLogLevelSpy).toHaveBeenCalledWith('ERROR'); expect(setExposedGlobal).toHaveBeenCalledWith('state', state, dummyWriteKey); }); - - it('should not load if the write key is invalid', () => { - const startLifecycleSpy = jest.spyOn(analytics, 'startLifecycle'); - const errorSpy = jest.spyOn(analytics.logger, 'error'); - - analytics.load('', sampleDataPlaneUrl, { logLevel: 'ERROR' }); - - expect(state.lifecycle.status.value).toBeUndefined(); - expect(startLifecycleSpy).not.toHaveBeenCalled(); - - expect(errorSpy).toHaveBeenCalledTimes(1); - expect(errorSpy).toHaveBeenNthCalledWith( - 1, - 'AnalyticsCore:: The write key "" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.', - ); - - // Try with different invalid write key - errorSpy.mockClear(); - analytics.load(' ', sampleDataPlaneUrl, { logLevel: 'ERROR' }); - - expect(errorSpy).toHaveBeenNthCalledWith( - 1, - 'AnalyticsCore:: The write key " " is invalid. It must be a non-empty string. Please check that the write key is correct and try again.', - ); - - // Try with different invalid write key - errorSpy.mockClear(); - analytics.load({} as any, sampleDataPlaneUrl, { logLevel: 'ERROR' }); - - expect(errorSpy).toHaveBeenNthCalledWith( - 1, - 'AnalyticsCore:: The write key "[object Object]" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.', - ); - - errorSpy.mockRestore(); - }); - - it('should not load if the data plane URL is invalid', () => { + it('should load the analytics script without dataPlaneUrl with the given options', () => { const startLifecycleSpy = jest.spyOn(analytics, 'startLifecycle'); - const errorSpy = jest.spyOn(analytics.logger, 'error'); - - analytics.load(dummyWriteKey, '', { logLevel: 'ERROR' }); - - expect(state.lifecycle.status.value).toBeUndefined(); - expect(startLifecycleSpy).not.toHaveBeenCalled(); - - expect(errorSpy).toHaveBeenCalledTimes(1); - expect(errorSpy).toHaveBeenNthCalledWith( - 1, - 'AnalyticsCore:: The data plane URL "" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.', - ); - - // Try with different invalid data plane URL - errorSpy.mockClear(); - analytics.load(dummyWriteKey, undefined as any, { logLevel: 'ERROR' }); - - expect(errorSpy).toHaveBeenNthCalledWith( - 1, - 'AnalyticsCore:: The data plane URL "undefined" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.', - ); - - // Try with different invalid data plane URL - errorSpy.mockClear(); - analytics.load(dummyWriteKey, 'https:///someinvalidurl', { logLevel: 'ERROR' }); - - expect(errorSpy).toHaveBeenNthCalledWith( - 1, - 'AnalyticsCore:: The data plane URL "https:///someinvalidurl" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.', - ); - - errorSpy.mockRestore(); + analytics.load(dummyWriteKey, { logLevel: 'ERROR' }); + expect(state.lifecycle.status.value).toBe('browserCapabilitiesReady'); + expect(startLifecycleSpy).toHaveBeenCalledTimes(1); + expect(setExposedGlobal).toHaveBeenCalledWith('state', state, dummyWriteKey); }); }); diff --git a/packages/analytics-js/__tests__/components/userSessionManager/UserSessionManager.test.ts b/packages/analytics-js/__tests__/components/userSessionManager/UserSessionManager.test.ts index 62e967731e..f7b0571eaa 100644 --- a/packages/analytics-js/__tests__/components/userSessionManager/UserSessionManager.test.ts +++ b/packages/analytics-js/__tests__/components/userSessionManager/UserSessionManager.test.ts @@ -1,5 +1,5 @@ import type { IPluginsManager } from '@rudderstack/analytics-js-common/types/PluginsManager'; -import { stringifyData } from '@rudderstack/analytics-js-common/utilities/json'; +import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json'; import { COOKIE_KEYS } from '@rudderstack/analytics-js-cookies/constants/cookies'; import { UserSessionManager } from '../../../src/components/userSessionManager'; import { DEFAULT_USER_SESSION_VALUES } from '../../../src/components/userSessionManager/constants'; @@ -27,7 +27,7 @@ jest.mock('@rudderstack/analytics-js-common/utilities/uuId', () => ({ })); jest.mock('@rudderstack/analytics-js-common/utilities/json', () => ({ - stringifyData: jest.fn(d => JSON.stringify(d)), + stringifyWithoutCircular: jest.fn(d => JSON.stringify(d)), })); describe('User session manager', () => { @@ -1713,7 +1713,7 @@ describe('User session manager', () => { prop2: 12345678, prop3: { city: 'Kolkata', zip: '700001' }, }); - expect(stringifyData).toHaveBeenCalled(); + expect(stringifyWithoutCircular).toHaveBeenCalled(); expect(defaultLogger.error).not.toHaveBeenCalledWith( 'The server failed to set the key cookie. As a fallback, the cookies will be set client side.', ); @@ -1739,7 +1739,7 @@ describe('User session manager', () => { ); setTimeout(() => { expect(mockCookieStore.get).toHaveBeenCalledWith('key'); - expect(stringifyData).toHaveBeenCalled(); + expect(stringifyWithoutCircular).toHaveBeenCalled(); expect(defaultLogger.error).toHaveBeenCalledWith( 'The server failed to set the key cookie. As a fallback, the cookies will be set client side.', ); diff --git a/packages/analytics-js/__tests__/services/HttpClient/HttpClient.test.ts b/packages/analytics-js/__tests__/services/HttpClient/HttpClient.test.ts index fd0bbe2af0..2e7349d8df 100644 --- a/packages/analytics-js/__tests__/services/HttpClient/HttpClient.test.ts +++ b/packages/analytics-js/__tests__/services/HttpClient/HttpClient.test.ts @@ -230,4 +230,26 @@ describe('HttpClient', () => { url: `${dummyDataplaneHost}/emptyJsonSample`, }); }); + + it('should handle if input data contains non-stringifiable values', done => { + const callback = (response: any) => { + expect(response).toBeUndefined(); + expect(defaultErrorHandler.onError).toHaveBeenCalledTimes(1); + expect(defaultErrorHandler.onError).toHaveBeenCalledWith( + new Error('Failed to prepare data for the request.'), + 'HttpClient', + ); + done(); + }; + clientInstance.getAsyncData({ + callback, + url: `${dummyDataplaneHost}/nonStringifiableDataSample`, + options: { + data: { + a: 1, + b: BigInt(1), + }, + }, + }); + }); }); diff --git a/packages/analytics-js/package.json b/packages/analytics-js/package.json index 37d34835b9..74de6a0b0c 100644 --- a/packages/analytics-js/package.json +++ b/packages/analytics-js/package.json @@ -1,6 +1,6 @@ { "name": "@rudderstack/analytics-js", - "version": "3.10.0", + "version": "3.10.1", "description": "RudderStack JavaScript SDK", "main": "dist/npm/modern/cjs/index.cjs", "module": "dist/npm/modern/esm/index.mjs", diff --git a/packages/analytics-js/project.json b/packages/analytics-js/project.json index a6e4979a2f..057a7a73cb 100644 --- a/packages/analytics-js/project.json +++ b/packages/analytics-js/project.json @@ -59,9 +59,9 @@ "github": { "executor": "@jscutlery/semver:github", "options": { - "tag": "@rudderstack/analytics-js@3.10.0", - "title": "@rudderstack/analytics-js@3.10.0", - "discussion-category": "@rudderstack/analytics-js@3.10.0", + "tag": "@rudderstack/analytics-js@3.10.1", + "title": "@rudderstack/analytics-js@3.10.1", + "discussion-category": "@rudderstack/analytics-js@3.10.1", "notesFile": "./packages/analytics-js/CHANGELOG_LATEST.md" } } diff --git a/packages/analytics-js/src/app/RudderAnalytics.ts b/packages/analytics-js/src/app/RudderAnalytics.ts index 8ea3ed5085..dabf2b1918 100644 --- a/packages/analytics-js/src/app/RudderAnalytics.ts +++ b/packages/analytics-js/src/app/RudderAnalytics.ts @@ -17,14 +17,12 @@ import { } from '@rudderstack/analytics-js-common/types/LoadOptions'; import type { ApiCallback, ApiOptions } from '@rudderstack/analytics-js-common/types/EventApi'; import type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject'; -import { RSA } from '@rudderstack/analytics-js-common/constants/loggerContexts'; +import { RS_APP } from '@rudderstack/analytics-js-common/constants/loggerContexts'; +import { isString } from '@rudderstack/analytics-js-common/utilities/checks'; import type { IdentifyTraits } from '@rudderstack/analytics-js-common/types/traits'; import { generateUUID } from '@rudderstack/analytics-js-common/utilities/uuId'; import { onPageLeave } from '@rudderstack/analytics-js-common/utilities/page'; -import { isString } from '@rudderstack/analytics-js-common/utilities/checks'; import { getFormattedTimestamp } from '@rudderstack/analytics-js-common/utilities/timestamp'; -import { getSanitizedValue } from '@rudderstack/analytics-js-common/utilities/json'; -import { dispatchErrorEvent } from '@rudderstack/analytics-js-common/utilities/errors'; import { GLOBAL_PRELOAD_BUFFER } from '../constants/app'; import { getPreloadedLoadEvent, @@ -35,7 +33,11 @@ import { setExposedGlobal } from '../components/utilities/globals'; import type { IAnalytics } from '../components/core/IAnalytics'; import { Analytics } from '../components/core/Analytics'; import { defaultLogger } from '../services/Logger/Logger'; -import { PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING } from '../constants/logMessages'; +import { + EMPTY_GROUP_CALL_ERROR, + PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING, + WRITE_KEY_NOT_A_STRING_ERROR, +} from '../constants/logMessages'; import { defaultErrorHandler } from '../services/ErrorHandler'; import { state } from '../state'; @@ -48,62 +50,55 @@ import { state } from '../state'; * consume SDK preload event buffer */ class RudderAnalytics implements IRudderAnalytics { - // START-NO-SONAR-SCAN - // eslint-disable-next-line sonarjs/public-static-readonly static globalSingleton: Nullable = null; - // END-NO-SONAR-SCAN analyticsInstances: Record = {}; defaultAnalyticsKey = ''; logger = defaultLogger; // Singleton with constructor bind methods constructor() { - try { - if (RudderAnalytics.globalSingleton) { - // START-NO-SONAR-SCAN - // eslint-disable-next-line no-constructor-return - return RudderAnalytics.globalSingleton; - // END-NO-SONAR-SCAN - } - defaultErrorHandler.attachErrorListeners(); - - this.setDefaultInstanceKey = this.setDefaultInstanceKey.bind(this); - this.getAnalyticsInstance = this.getAnalyticsInstance.bind(this); - this.load = this.load.bind(this); - this.ready = this.ready.bind(this); - this.triggerBufferedLoadEvent = this.triggerBufferedLoadEvent.bind(this); - this.page = this.page.bind(this); - this.track = this.track.bind(this); - this.identify = this.identify.bind(this); - this.alias = this.alias.bind(this); - this.group = this.group.bind(this); - this.reset = this.reset.bind(this); - this.getAnonymousId = this.getAnonymousId.bind(this); - this.setAnonymousId = this.setAnonymousId.bind(this); - this.getUserId = this.getUserId.bind(this); - this.getUserTraits = this.getUserTraits.bind(this); - this.getGroupId = this.getGroupId.bind(this); - this.getGroupTraits = this.getGroupTraits.bind(this); - this.startSession = this.startSession.bind(this); - this.endSession = this.endSession.bind(this); - this.getSessionId = this.getSessionId.bind(this); - this.setAuthToken = this.setAuthToken.bind(this); - this.consent = this.consent.bind(this); - - RudderAnalytics.globalSingleton = this; - - state.autoTrack.pageLifecycle.visitId.value = generateUUID(); - state.autoTrack.pageLifecycle.pageLoadedTimestamp.value = Date.now(); - - // start loading if a load event was buffered or wait for explicit load call - this.triggerBufferedLoadEvent(); - - // Assign to global "rudderanalytics" object after processing the preload buffer (if any exists) - // for CDN bundling IIFE exports covers this but for npm ESM and CJS bundling has to be done explicitly - (globalThis as typeof window).rudderanalytics = this; - } catch (error: any) { - dispatchErrorEvent(error); + if (RudderAnalytics.globalSingleton) { + // START-NO-SONAR-SCAN + // eslint-disable-next-line no-constructor-return + return RudderAnalytics.globalSingleton; + // END-NO-SONAR-SCAN } + defaultErrorHandler.attachErrorListeners(); + + this.setDefaultInstanceKey = this.setDefaultInstanceKey.bind(this); + this.getAnalyticsInstance = this.getAnalyticsInstance.bind(this); + this.load = this.load.bind(this); + this.ready = this.ready.bind(this); + this.triggerBufferedLoadEvent = this.triggerBufferedLoadEvent.bind(this); + this.page = this.page.bind(this); + this.track = this.track.bind(this); + this.identify = this.identify.bind(this); + this.alias = this.alias.bind(this); + this.group = this.group.bind(this); + this.reset = this.reset.bind(this); + this.getAnonymousId = this.getAnonymousId.bind(this); + this.setAnonymousId = this.setAnonymousId.bind(this); + this.getUserId = this.getUserId.bind(this); + this.getUserTraits = this.getUserTraits.bind(this); + this.getGroupId = this.getGroupId.bind(this); + this.getGroupTraits = this.getGroupTraits.bind(this); + this.startSession = this.startSession.bind(this); + this.endSession = this.endSession.bind(this); + this.getSessionId = this.getSessionId.bind(this); + this.setAuthToken = this.setAuthToken.bind(this); + this.consent = this.consent.bind(this); + + RudderAnalytics.globalSingleton = this; + + state.autoTrack.pageLifecycle.visitId.value = generateUUID(); + state.autoTrack.pageLifecycle.pageLoadedTimestamp.value = Date.now(); + + // start loading if a load event was buffered or wait for explicit load call + this.triggerBufferedLoadEvent(); + + // Assign to global "rudderanalytics" object after processing the preload buffer (if any exists) + // for CDN bundling IIFE exports covers this but for npm ESM and CJS bundling has to be done explicitly + (globalThis as typeof window).rudderanalytics = this; } /** @@ -112,11 +107,7 @@ class RudderAnalytics implements IRudderAnalytics { * TODO: to support multiple analytics instances in the near future */ setDefaultInstanceKey(writeKey: string) { - // IMP: Add try-catch block to handle any unhandled errors - // similar to other public methods - // if the implementation of this method goes beyond - // this simple implementation - if (isString(writeKey) && writeKey) { + if (writeKey) { this.defaultAnalyticsKey = writeKey; } } @@ -124,59 +115,44 @@ class RudderAnalytics implements IRudderAnalytics { /** * Retrieve an existing analytics instance */ - getAnalyticsInstance(writeKey?: string): IAnalytics | undefined { - try { - let instanceId = writeKey; - if (!isString(instanceId) || !instanceId) { - instanceId = this.defaultAnalyticsKey; - } + getAnalyticsInstance(writeKey?: string): IAnalytics { + const instanceId = writeKey ?? this.defaultAnalyticsKey; - const analyticsInstanceExists = Boolean(this.analyticsInstances[instanceId]); + const analyticsInstanceExists = Boolean(this.analyticsInstances[instanceId]); - if (!analyticsInstanceExists) { - this.analyticsInstances[instanceId] = new Analytics(); - } - - return this.analyticsInstances[instanceId] as IAnalytics; - } catch (error: any) { - dispatchErrorEvent(error); - return undefined; + if (!analyticsInstanceExists) { + this.analyticsInstances[instanceId] = new Analytics(); } + + return this.analyticsInstances[instanceId] as IAnalytics; } /** - * Loads the SDK - * @param writeKey Source write key - * @param dataPlaneUrl Data plane URL - * @param loadOptions Additional options for loading the SDK - * @returns none + * Create new analytics instance and trigger application lifecycle start */ - load(writeKey: string, dataPlaneUrl: string, loadOptions?: Partial): void { - try { - if (this.analyticsInstances[writeKey]) { - return; - } + load(writeKey: string, dataPlaneUrl: string, loadOptions?: Partial) { + if (!isString(writeKey)) { + this.logger.error(WRITE_KEY_NOT_A_STRING_ERROR(RS_APP, writeKey)); + return; + } - this.setDefaultInstanceKey(writeKey); - const preloadedEventsArray = this.getPreloadedEvents(); + if (this.analyticsInstances[writeKey]) { + return; + } - // Track page loaded lifecycle event if enabled - this.trackPageLifecycleEvents(preloadedEventsArray, loadOptions); + this.setDefaultInstanceKey(writeKey); + const preloadedEventsArray = this.getPreloadedEvents(); - // The array will be mutated in the below method - promotePreloadedConsentEventsToTop(preloadedEventsArray); + // Track page loaded lifecycle event if enabled + this.trackPageLifecycleEvents(preloadedEventsArray, loadOptions); - setExposedGlobal(GLOBAL_PRELOAD_BUFFER, clone(preloadedEventsArray)); + // The array will be mutated in the below method + promotePreloadedConsentEventsToTop(preloadedEventsArray); - this.analyticsInstances[writeKey] = new Analytics(); - this.getAnalyticsInstance(writeKey)?.load( - writeKey, - dataPlaneUrl, - getSanitizedValue(loadOptions), - ); - } catch (error: any) { - dispatchErrorEvent(error); - } + setExposedGlobal(GLOBAL_PRELOAD_BUFFER, clone(preloadedEventsArray)); + + this.analyticsInstances[writeKey] = new Analytics(); + this.getAnalyticsInstance(writeKey).load(writeKey, dataPlaneUrl, loadOptions); } /** @@ -234,7 +210,7 @@ class RudderAnalytics implements IRudderAnalytics { * @param preloadedEventsArray */ // eslint-disable-next-line class-methods-use-this - trackPageLoadedEvent( + private trackPageLoadedEvent( events: PageLifecycleEvents[], options: ApiOptions, preloadedEventsArray: PreloadedEventCall[], @@ -260,7 +236,7 @@ class RudderAnalytics implements IRudderAnalytics { * @param useBeacon * @param options */ - setupPageUnloadTracking( + private setupPageUnloadTracking( events: PageLifecycleEvents[], useBeacon: boolean | undefined, options: ApiOptions, @@ -288,7 +264,7 @@ class RudderAnalytics implements IRudderAnalytics { }); } else { // throw warning if beacon is disabled - this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RSA)); + this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RS_APP)); } } } @@ -322,11 +298,7 @@ class RudderAnalytics implements IRudderAnalytics { * Get ready callback arguments and forward to ready call */ ready(callback: ApiCallback) { - try { - this.getAnalyticsInstance()?.ready(getSanitizedValue(callback)); - } catch (error: any) { - dispatchErrorEvent(error); - } + this.getAnalyticsInstance().ready(callback); } /** @@ -369,13 +341,9 @@ class RudderAnalytics implements IRudderAnalytics { options?: Nullable | ApiCallback, callback?: ApiCallback, ) { - try { - this.getAnalyticsInstance()?.page( - pageArgumentsToCallOptions(category, name, properties, options, callback), - ); - } catch (error: any) { - dispatchErrorEvent(error); - } + this.getAnalyticsInstance().page( + pageArgumentsToCallOptions(category, name, properties, options, callback), + ); } /** @@ -396,13 +364,9 @@ class RudderAnalytics implements IRudderAnalytics { options?: Nullable | ApiCallback, callback?: ApiCallback, ) { - try { - this.getAnalyticsInstance()?.track( - trackArgumentsToCallOptions(event, properties, options, callback), - ); - } catch (error: any) { - dispatchErrorEvent(error); - } + this.getAnalyticsInstance().track( + trackArgumentsToCallOptions(event, properties, options, callback), + ); } /** @@ -429,13 +393,9 @@ class RudderAnalytics implements IRudderAnalytics { options?: Nullable | ApiCallback, callback?: ApiCallback, ) { - try { - this.getAnalyticsInstance()?.identify( - identifyArgumentsToCallOptions(userId, traits, options, callback), - ); - } catch (error: any) { - dispatchErrorEvent(error); - } + this.getAnalyticsInstance().identify( + identifyArgumentsToCallOptions(userId, traits, options, callback), + ); } /** @@ -452,11 +412,7 @@ class RudderAnalytics implements IRudderAnalytics { options?: Nullable | ApiCallback, callback?: ApiCallback, ) { - try { - this.getAnalyticsInstance()?.alias(aliasArgumentsToCallOptions(to, from, options, callback)); - } catch (error: any) { - dispatchErrorEvent(error); - } + this.getAnalyticsInstance().alias(aliasArgumentsToCallOptions(to, from, options, callback)); } /** @@ -483,118 +439,62 @@ class RudderAnalytics implements IRudderAnalytics { options?: Nullable | ApiCallback, callback?: ApiCallback, ) { - try { - this.getAnalyticsInstance()?.group( - groupArgumentsToCallOptions(groupId, traits, options, callback), - ); - } catch (error: any) { - dispatchErrorEvent(error); + if (arguments.length === 0) { + this.logger.error(EMPTY_GROUP_CALL_ERROR(RS_APP)); + return; } + + this.getAnalyticsInstance().group( + groupArgumentsToCallOptions(groupId, traits, options, callback), + ); } reset(resetAnonymousId?: boolean) { - try { - this.getAnalyticsInstance()?.reset(getSanitizedValue(resetAnonymousId)); - } catch (error: any) { - dispatchErrorEvent(error); - } + this.getAnalyticsInstance().reset(resetAnonymousId); } - getAnonymousId(options?: AnonymousIdOptions): string | undefined { - try { - return this.getAnalyticsInstance()?.getAnonymousId(getSanitizedValue(options)); - } catch (error: any) { - dispatchErrorEvent(error); - return undefined; - } + getAnonymousId(options?: AnonymousIdOptions) { + return this.getAnalyticsInstance().getAnonymousId(options); } - setAnonymousId(anonymousId?: string, rudderAmpLinkerParam?: string): void { - try { - this.getAnalyticsInstance()?.setAnonymousId( - getSanitizedValue(anonymousId), - getSanitizedValue(rudderAmpLinkerParam), - ); - } catch (error: any) { - dispatchErrorEvent(error); - } + setAnonymousId(anonymousId?: string, rudderAmpLinkerParam?: string) { + this.getAnalyticsInstance().setAnonymousId(anonymousId, rudderAmpLinkerParam); } getUserId() { - try { - return this.getAnalyticsInstance()?.getUserId(); - } catch (error: any) { - dispatchErrorEvent(error); - return undefined; - } + return this.getAnalyticsInstance().getUserId(); } getUserTraits() { - try { - return this.getAnalyticsInstance()?.getUserTraits(); - } catch (error: any) { - dispatchErrorEvent(error); - return undefined; - } + return this.getAnalyticsInstance().getUserTraits(); } getGroupId() { - try { - return this.getAnalyticsInstance()?.getGroupId(); - } catch (error: any) { - dispatchErrorEvent(error); - return undefined; - } + return this.getAnalyticsInstance().getGroupId(); } getGroupTraits() { - try { - return this.getAnalyticsInstance()?.getGroupTraits(); - } catch (error: any) { - dispatchErrorEvent(error); - return undefined; - } + return this.getAnalyticsInstance().getGroupTraits(); } - startSession(sessionId?: number): void { - try { - this.getAnalyticsInstance()?.startSession(getSanitizedValue(sessionId)); - } catch (error: any) { - dispatchErrorEvent(error); - } + startSession(sessionId?: number) { + return this.getAnalyticsInstance().startSession(sessionId); } - endSession(): void { - try { - this.getAnalyticsInstance()?.endSession(); - } catch (error: any) { - dispatchErrorEvent(error); - } + endSession() { + return this.getAnalyticsInstance().endSession(); } getSessionId() { - try { - return this.getAnalyticsInstance()?.getSessionId(); - } catch (error: any) { - dispatchErrorEvent(error); - return undefined; - } + return this.getAnalyticsInstance().getSessionId(); } - setAuthToken(token: string): void { - try { - this.getAnalyticsInstance()?.setAuthToken(getSanitizedValue(token)); - } catch (error: any) { - dispatchErrorEvent(error); - } + setAuthToken(token: string) { + return this.getAnalyticsInstance().setAuthToken(token); } - consent(options?: ConsentOptions): void { - try { - this.getAnalyticsInstance()?.consent(getSanitizedValue(options)); - } catch (error: any) { - dispatchErrorEvent(error); - } + consent(options?: ConsentOptions) { + return this.getAnalyticsInstance().consent(options); } } diff --git a/packages/analytics-js/src/components/configManager/ConfigManager.ts b/packages/analytics-js/src/components/configManager/ConfigManager.ts index 315f2ab5a5..fec3eacbb3 100644 --- a/packages/analytics-js/src/components/configManager/ConfigManager.ts +++ b/packages/analytics-js/src/components/configManager/ConfigManager.ts @@ -10,7 +10,7 @@ import type { Destination } from '@rudderstack/analytics-js-common/types/Destina import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; import { CONFIG_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts'; import type { IntegrationOpts } from '@rudderstack/analytics-js-common/types/Integration'; -import { isValidSourceConfig } from './util/validate'; +import { isValidSourceConfig, validateLoadArgs } from './util/validate'; import { SOURCE_CONFIG_FETCH_ERROR, SOURCE_CONFIG_OPTION_ERROR, @@ -62,6 +62,8 @@ class ConfigManager implements IConfigManager { init() { this.attachEffects(); + validateLoadArgs(state.lifecycle.writeKey.value, state.lifecycle.dataPlaneUrl.value); + const { logLevel, configUrl, diff --git a/packages/analytics-js/src/components/configManager/util/validate.ts b/packages/analytics-js/src/components/configManager/util/validate.ts index fc22c51405..6090e231cd 100644 --- a/packages/analytics-js/src/components/configManager/util/validate.ts +++ b/packages/analytics-js/src/components/configManager/util/validate.ts @@ -1,9 +1,31 @@ import { isObjectLiteralAndNotNull } from '@rudderstack/analytics-js-common/utilities/object'; -import { isNullOrUndefined } from '@rudderstack/analytics-js-common/utilities/checks'; +import { isNullOrUndefined, isString } from '@rudderstack/analytics-js-common/utilities/checks'; import { SUPPORTED_STORAGE_TYPES, type StorageType, } from '@rudderstack/analytics-js-common/types/Storage'; +import { isValidURL } from '@rudderstack/analytics-js-common/utilities/url'; +import { + WRITE_KEY_VALIDATION_ERROR, + DATA_PLANE_URL_VALIDATION_ERROR, +} from '../../../constants/logMessages'; + +const validateWriteKey = (writeKey?: string) => { + if (!isString(writeKey) || (writeKey as string).trim().length === 0) { + throw new Error(WRITE_KEY_VALIDATION_ERROR(writeKey)); + } +}; + +const validateDataPlaneUrl = (dataPlaneUrl?: string) => { + if (!isValidURL(dataPlaneUrl)) { + throw new Error(DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl)); + } +}; + +const validateLoadArgs = (writeKey?: string, dataPlaneUrl?: string) => { + validateWriteKey(writeKey); + validateDataPlaneUrl(dataPlaneUrl); +}; const isValidSourceConfig = (res: any): boolean => isObjectLiteralAndNotNull(res) && @@ -53,8 +75,11 @@ const isWebpageTopLevelDomain = (providedDomain: string): boolean => { }; export { + validateLoadArgs, isValidSourceConfig, isValidStorageType, + validateWriteKey, + validateDataPlaneUrl, getTopDomainUrl, getDataServiceUrl, isWebpageTopLevelDomain, diff --git a/packages/analytics-js/src/components/core/Analytics.ts b/packages/analytics-js/src/components/core/Analytics.ts index 8421dda6cf..31948370f2 100644 --- a/packages/analytics-js/src/components/core/Analytics.ts +++ b/packages/analytics-js/src/components/core/Analytics.ts @@ -18,6 +18,7 @@ import type { LoadOptions, } from '@rudderstack/analytics-js-common/types/LoadOptions'; import type { ApiCallback } from '@rudderstack/analytics-js-common/types/EventApi'; +import { isObjectAndNotNull } from '@rudderstack/analytics-js-common/utilities/object'; import { ANALYTICS_CORE, READY_API, @@ -59,15 +60,10 @@ import { ADBLOCK_PAGE_PATH, CONSENT_TRACK_EVENT_NAME, } from '../../constants/app'; -import { - DATA_PLANE_URL_VALIDATION_ERROR, - READY_API_CALLBACK_ERROR, - READY_CALLBACK_INVOKE_ERROR, - WRITE_KEY_VALIDATION_ERROR, -} from '../../constants/logMessages'; +import { READY_API_CALLBACK_ERROR, READY_CALLBACK_INVOKE_ERROR } from '../../constants/logMessages'; import type { IAnalytics } from './IAnalytics'; import { getConsentManagementData, getValidPostConsentOptions } from '../utilities/consent'; -import { dispatchSDKEvent, isDataPlaneUrlValid, isWriteKeyValid } from './utilities'; +import { dispatchSDKEvent } from './utilities'; /* * Analytics class with lifecycle based on state ad user triggered events @@ -104,26 +100,29 @@ class Analytics implements IAnalytics { /** * Start application lifecycle if not already started */ - load(writeKey: string, dataPlaneUrl: string, loadOptions: Partial = {}) { + load( + writeKey: string, + dataPlaneUrl?: string | Partial, + loadOptions: Partial = {}, + ) { if (state.lifecycle.status.value) { return; } - if (!isWriteKeyValid(writeKey)) { - this.logger.error(WRITE_KEY_VALIDATION_ERROR(ANALYTICS_CORE, writeKey)); - return; - } + let clonedDataPlaneUrl = clone(dataPlaneUrl); + let clonedLoadOptions = clone(loadOptions); - if (!isDataPlaneUrlValid(dataPlaneUrl)) { - this.logger.error(DATA_PLANE_URL_VALIDATION_ERROR(ANALYTICS_CORE, dataPlaneUrl)); - return; + // dataPlaneUrl is not provided + if (isObjectAndNotNull(dataPlaneUrl)) { + clonedLoadOptions = dataPlaneUrl; + clonedDataPlaneUrl = undefined; } // Set initial state values batch(() => { - state.lifecycle.writeKey.value = clone(writeKey); - state.lifecycle.dataPlaneUrl.value = clone(dataPlaneUrl); - state.loadOptions.value = normalizeLoadOptions(state.loadOptions.value, loadOptions); + state.lifecycle.writeKey.value = writeKey; + state.lifecycle.dataPlaneUrl.value = clonedDataPlaneUrl as string | undefined; + state.loadOptions.value = normalizeLoadOptions(state.loadOptions.value, clonedLoadOptions); state.lifecycle.status.value = 'mounted'; }); diff --git a/packages/analytics-js/src/components/core/utilities.ts b/packages/analytics-js/src/components/core/utilities.ts index b9c11e7fd9..ca1dfd0c0b 100644 --- a/packages/analytics-js/src/components/core/utilities.ts +++ b/packages/analytics-js/src/components/core/utilities.ts @@ -1,6 +1,3 @@ -import { isString } from '@rudderstack/analytics-js-common/utilities/checks'; -import { isValidURL } from '@rudderstack/analytics-js-common/utilities/url'; - const dispatchSDKEvent = (event: string): void => { const customEvent = new CustomEvent(event, { detail: { analyticsInstance: (globalThis as typeof window).rudderanalytics }, @@ -12,8 +9,4 @@ const dispatchSDKEvent = (event: string): void => { (globalThis as typeof window).document.dispatchEvent(customEvent); }; -const isWriteKeyValid = (writeKey: string) => isString(writeKey) && writeKey.trim().length > 0; - -const isDataPlaneUrlValid = (dataPlaneUrl: string) => isValidURL(dataPlaneUrl); - -export { dispatchSDKEvent, isWriteKeyValid, isDataPlaneUrlValid }; +export { dispatchSDKEvent }; diff --git a/packages/analytics-js/src/components/userSessionManager/UserSessionManager.ts b/packages/analytics-js/src/components/userSessionManager/UserSessionManager.ts index dd5fd436b7..1bc46c1726 100644 --- a/packages/analytics-js/src/components/userSessionManager/UserSessionManager.ts +++ b/packages/analytics-js/src/components/userSessionManager/UserSessionManager.ts @@ -32,7 +32,7 @@ import type { AsyncRequestCallback, IHttpClient, } from '@rudderstack/analytics-js-common/types/HttpClient'; -import { stringifyData } from '@rudderstack/analytics-js-common/utilities/json'; +import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json'; import { COOKIE_KEYS } from '@rudderstack/analytics-js-cookies/constants/cookies'; import { CLIENT_DATA_STORE_COOKIE, @@ -304,7 +304,9 @@ class UserSessionManager implements IUserSessionManager { getEncryptedCookieData(cookiesData: CookieData[], store?: IStore): EncryptedCookieData[] { const encryptedCookieData: EncryptedCookieData[] = []; cookiesData.forEach(cData => { - const encryptedValue = store?.encrypt(stringifyData(cData.value, false)); + const encryptedValue = store?.encrypt( + stringifyWithoutCircular(cData.value, false, [], this.logger), + ); if (isDefinedAndNotNull(encryptedValue)) { encryptedCookieData.push({ name: cData.name, @@ -328,24 +330,21 @@ class UserSessionManager implements IUserSessionManager { url: state.serverCookies.dataServiceUrl.value as string, options: { method: 'POST', - data: stringifyData( - { - reqType: 'setCookies', - workspaceId: state.source.value?.workspaceId, - data: { - options: { - maxAge: state.storage.cookie.value?.maxage, - path: state.storage.cookie.value?.path, - domain: state.storage.cookie.value?.domain, - sameSite: state.storage.cookie.value?.samesite, - secure: state.storage.cookie.value?.secure, - expires: state.storage.cookie.value?.expires, - }, - cookies: encryptedCookieData, + data: stringifyWithoutCircular({ + reqType: 'setCookies', + workspaceId: state.source.value?.workspaceId, + data: { + options: { + maxAge: state.storage.cookie.value?.maxage, + path: state.storage.cookie.value?.path, + domain: state.storage.cookie.value?.domain, + sameSite: state.storage.cookie.value?.samesite, + secure: state.storage.cookie.value?.secure, + expires: state.storage.cookie.value?.expires, }, + cookies: encryptedCookieData, }, - false, - ), + }) as string, sendRawData: true, withCredentials: true, }, @@ -369,8 +368,8 @@ class UserSessionManager implements IUserSessionManager { if (details?.xhr?.status === 200) { cookiesData.forEach(cData => { const cookieValue = store?.get(cData.name); - const before = stringifyData(cData.value, false); - const after = stringifyData(cookieValue, false); + const before = stringifyWithoutCircular(cData.value, false, []); + const after = stringifyWithoutCircular(cookieValue, false, []); if (after !== before) { this.logger?.error(FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(cData.name)); if (cb) { @@ -469,11 +468,7 @@ class UserSessionManager implements IUserSessionManager { * 3. generateUUID: A new unique id is generated and assigned. */ setAnonymousId(anonymousId?: string, rudderAmpLinkerParam?: string) { - let finalAnonymousId: string | undefined = anonymousId; - if (!isString(anonymousId) || !finalAnonymousId) { - finalAnonymousId = undefined; - } - + let finalAnonymousId: string | undefined | null = anonymousId; if (this.isPersistenceEnabledForStorageEntry('anonymousId')) { if (!finalAnonymousId && rudderAmpLinkerParam) { const linkerPluginsResult = this.pluginsManager?.invokeSingle( @@ -673,7 +668,7 @@ class UserSessionManager implements IUserSessionManager { session.groupTraits.value = DEFAULT_USER_SESSION_VALUES.groupTraits; session.authToken.value = DEFAULT_USER_SESSION_VALUES.authToken; - if (resetAnonymousId === true) { + if (resetAnonymousId) { // This will generate a new anonymous ID this.setAnonymousId(); } diff --git a/packages/analytics-js/src/constants/logMessages.ts b/packages/analytics-js/src/constants/logMessages.ts index 0020c5fdb4..8295a634e8 100644 --- a/packages/analytics-js/src/constants/logMessages.ts +++ b/packages/analytics-js/src/constants/logMessages.ts @@ -66,14 +66,14 @@ const STORAGE_UNAVAILABILITY_ERROR_PREFIX = (context: string, storageType: Stora const SOURCE_CONFIG_FETCH_ERROR = (reason: Error | undefined): string => `Failed to fetch the source config. Reason: ${reason}`; -const WRITE_KEY_VALIDATION_ERROR = (context: string, writeKey: string): string => - `${context}${LOG_CONTEXT_SEPARATOR}The write key "${writeKey}" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`; +const WRITE_KEY_VALIDATION_ERROR = (writeKey?: string): string => + `The write key "${writeKey}" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`; -const DATA_PLANE_URL_VALIDATION_ERROR = (context: string, dataPlaneUrl: string): string => - `${context}${LOG_CONTEXT_SEPARATOR}The data plane URL "${dataPlaneUrl}" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.`; +const DATA_PLANE_URL_VALIDATION_ERROR = (dataPlaneUrl: string | undefined): string => + `The data plane URL "${dataPlaneUrl}" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.`; const READY_API_CALLBACK_ERROR = (context: string): string => - `${context}${LOG_CONTEXT_SEPARATOR}The provided callback is not a function.`; + `${context}${LOG_CONTEXT_SEPARATOR}The callback is not a function.`; const XHR_DELIVERY_ERROR = ( prefix: string, @@ -193,6 +193,12 @@ const STORAGE_UNAVAILABLE_WARNING = ( ): string => `${context}${LOG_CONTEXT_SEPARATOR}The storage type "${selectedStorageType}" is not available for entry "${entry}". The SDK will initialize the entry with "${finalStorageType}" storage type instead.`; +const WRITE_KEY_NOT_A_STRING_ERROR = (context: string, writeKey: string | undefined): string => + `${context}${LOG_CONTEXT_SEPARATOR}The write key "${writeKey}" is not a string. Please check that the write key is correct and try again.`; + +const EMPTY_GROUP_CALL_ERROR = (context: string): string => + `${context}${LOG_CONTEXT_SEPARATOR}The group() method must be called with at least one argument.`; + const READY_CALLBACK_INVOKE_ERROR = `Failed to invoke the ready callback`; const API_CALLBACK_INVOKE_ERROR = `API Callback Invocation Failed`; @@ -294,6 +300,8 @@ export { PLUGIN_EXT_POINT_MISSING_ERROR, PLUGIN_EXT_POINT_INVALID_ERROR, STORAGE_TYPE_VALIDATION_WARNING, + WRITE_KEY_NOT_A_STRING_ERROR, + EMPTY_GROUP_CALL_ERROR, READY_CALLBACK_INVOKE_ERROR, API_CALLBACK_INVOKE_ERROR, INVALID_CONFIG_URL_WARNING, diff --git a/packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts b/packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts index 7d2fbc5f4c..405d91e5d8 100644 --- a/packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts +++ b/packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts @@ -14,7 +14,6 @@ import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constant import { BufferQueue } from '@rudderstack/analytics-js-common/services/BufferQueue/BufferQueue'; import type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient'; import type { IExternalSrcLoader } from '@rudderstack/analytics-js-common/services/ExternalSrcLoader/types'; -import { MANUAL_ERROR_IDENTIFIER } from '@rudderstack/analytics-js-common/utilities/errors'; import { NOTIFY_FAILURE_ERROR, REPORTING_PLUGIN_INIT_FAILURE_ERROR, @@ -169,8 +168,6 @@ class ErrorHandler implements IErrorHandler { } else { throw normalizedError; } - } else if ((error as any).error?.stack?.includes(MANUAL_ERROR_IDENTIFIER)) { - this.logger?.error('An unknown error occurred:', (error as ErrorEvent).error?.message); } } diff --git a/packages/analytics-js/src/services/ErrorHandler/processError.ts b/packages/analytics-js/src/services/ErrorHandler/processError.ts index 92e8db6505..bd5588bffd 100644 --- a/packages/analytics-js/src/services/ErrorHandler/processError.ts +++ b/packages/analytics-js/src/services/ErrorHandler/processError.ts @@ -1,4 +1,4 @@ -import { stringifyData } from '@rudderstack/analytics-js-common/utilities/json'; +import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json'; import { isString } from '@rudderstack/analytics-js-common/utilities/checks'; import type { ErrorTarget, SDKError } from '@rudderstack/analytics-js-common/types/ErrorHandler'; import { LOAD_ORIGIN } from './constant'; @@ -19,7 +19,7 @@ const processError = (error: SDKError): string => { } else { errorMessage = (error as any).message ? (error as any).message - : stringifyData(error as Record); + : stringifyWithoutCircular(error as Record); } } catch (e) { errorMessage = `Unknown error: ${(e as Error).message}`; diff --git a/packages/analytics-js/src/services/HttpClient/HttpClient.ts b/packages/analytics-js/src/services/HttpClient/HttpClient.ts index 5aab7e3c18..ee3f7e3ada 100644 --- a/packages/analytics-js/src/services/HttpClient/HttpClient.ts +++ b/packages/analytics-js/src/services/HttpClient/HttpClient.ts @@ -44,6 +44,7 @@ class HttpClient implements IHttpClient { const data = await xhrRequest( createXhrRequestOptions(url, options, this.basicAuthHeader), timeout, + this.logger, ); return { data: isRawResponse ? data.response : responseTextToJson(data.response, this.onError), @@ -62,7 +63,7 @@ class HttpClient implements IHttpClient { const { callback, url, options, timeout, isRawResponse } = config; const isFireAndForget = !isFunction(callback); - xhrRequest(createXhrRequestOptions(url, options, this.basicAuthHeader), timeout) + xhrRequest(createXhrRequestOptions(url, options, this.basicAuthHeader), timeout, this.logger) .then((data: ResponseDetails) => { if (!isFireAndForget) { callback( diff --git a/packages/analytics-js/src/services/HttpClient/xhr/xhrRequestHandler.ts b/packages/analytics-js/src/services/HttpClient/xhr/xhrRequestHandler.ts index 182d155b86..c8202d918c 100644 --- a/packages/analytics-js/src/services/HttpClient/xhr/xhrRequestHandler.ts +++ b/packages/analytics-js/src/services/HttpClient/xhr/xhrRequestHandler.ts @@ -1,11 +1,12 @@ /* eslint-disable prefer-promise-reject-errors */ import { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object'; -import { stringifyData } from '@rudderstack/analytics-js-common/utilities/json'; +import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json'; import { isNull } from '@rudderstack/analytics-js-common/utilities/checks'; import type { IXHRRequestOptions, ResponseDetails, } from '@rudderstack/analytics-js-common/types/HttpClient'; +import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; import { getMutatedError } from '@rudderstack/analytics-js-common/utilities/errors'; import { FAILED_REQUEST_ERR_MSG_PREFIX } from '@rudderstack/analytics-js-common/constants/errors'; import { DEFAULT_XHR_TIMEOUT_MS } from '../../../constants/timeouts'; @@ -56,13 +57,14 @@ const createXhrRequestOptions = ( const xhrRequest = ( options: IXHRRequestOptions, timeout = DEFAULT_XHR_TIMEOUT_MS, + logger?: ILogger, ): Promise => new Promise((resolve, reject) => { let payload; if (options.sendRawData === true) { payload = options.data; } else { - payload = stringifyData(options.data); + payload = stringifyWithoutCircular(options.data, false, [], logger); if (isNull(payload)) { reject({ error: new Error(XHR_PAYLOAD_PREP_ERROR), diff --git a/packages/analytics-js/src/services/StoreManager/Store.ts b/packages/analytics-js/src/services/StoreManager/Store.ts index f55f0924d7..da079a8a64 100644 --- a/packages/analytics-js/src/services/StoreManager/Store.ts +++ b/packages/analytics-js/src/services/StoreManager/Store.ts @@ -1,6 +1,6 @@ import { trim } from '@rudderstack/analytics-js-common/utilities/string'; import { isNullOrUndefined, isString } from '@rudderstack/analytics-js-common/utilities/checks'; -import { stringifyData } from '@rudderstack/analytics-js-common/utilities/json'; +import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json'; import type { IStorage, IStore, IStoreConfig } from '@rudderstack/analytics-js-common/types/Store'; import type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler'; import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; @@ -107,7 +107,10 @@ class Store implements IStore { try { // storejs that is used in localstorage engine already stringifies json - this.engine.setItem(validKey, this.encrypt(stringifyData(value, false))); + this.engine.setItem( + validKey, + this.encrypt(stringifyWithoutCircular(value, false, [], this.logger)), + ); } catch (err) { if (isStorageQuotaExceeded(err)) { this.logger?.warn(STORAGE_QUOTA_EXCEEDED_WARNING(`Store ${this.id}`)); @@ -205,7 +208,7 @@ class Store implements IStore { ? this.pluginsManager.invokeSingle(extensionPointName, value) : value; - return typeof formattedValue === 'undefined' ? value : (formattedValue ?? ''); + return typeof formattedValue === 'undefined' ? value : formattedValue ?? ''; } /** diff --git a/packages/analytics-v1.1/CHANGELOG.md b/packages/analytics-v1.1/CHANGELOG.md index 0cb748a782..e994c19e50 100644 --- a/packages/analytics-v1.1/CHANGELOG.md +++ b/packages/analytics-v1.1/CHANGELOG.md @@ -2,6 +2,11 @@ This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver). +## [2.48.26](https://github.com/rudderlabs/rudder-sdk-js/compare/rudder-sdk-js@2.48.25...rudder-sdk-js@2.48.26) (2024-11-12) + +### Dependency Updates + +* `@rudderstack/analytics-js-common` updated to version `3.12.1` ## [2.48.25](https://github.com/rudderlabs/rudder-sdk-js/compare/rudder-sdk-js@2.48.24...rudder-sdk-js@2.48.25) (2024-11-08) ### Dependency Updates diff --git a/packages/analytics-v1.1/CHANGELOG_LATEST.md b/packages/analytics-v1.1/CHANGELOG_LATEST.md index 8e6deaebc6..26e1bc4b3e 100644 --- a/packages/analytics-v1.1/CHANGELOG_LATEST.md +++ b/packages/analytics-v1.1/CHANGELOG_LATEST.md @@ -1,5 +1,5 @@ -## [2.48.25](https://github.com/rudderlabs/rudder-sdk-js/compare/rudder-sdk-js@2.48.24...rudder-sdk-js@2.48.25) (2024-11-08) +## [2.48.26](https://github.com/rudderlabs/rudder-sdk-js/compare/rudder-sdk-js@2.48.25...rudder-sdk-js@2.48.26) (2024-11-12) ### Dependency Updates -* `@rudderstack/analytics-js-common` updated to version `3.12.0` +* `@rudderstack/analytics-js-common` updated to version `3.12.1` diff --git a/packages/analytics-v1.1/package.json b/packages/analytics-v1.1/package.json index 32675296dc..a269a2b974 100644 --- a/packages/analytics-v1.1/package.json +++ b/packages/analytics-v1.1/package.json @@ -1,6 +1,6 @@ { "name": "rudder-sdk-js", - "version": "2.48.25", + "version": "2.48.26", "description": "RudderStack JavaScript SDK", "main": "dist/npm/index.js", "module": "dist/npm/index.es.js", diff --git a/packages/analytics-v1.1/project.json b/packages/analytics-v1.1/project.json index 137f23fc2f..afdd1bc961 100644 --- a/packages/analytics-v1.1/project.json +++ b/packages/analytics-v1.1/project.json @@ -59,9 +59,9 @@ "github": { "executor": "@jscutlery/semver:github", "options": { - "tag": "rudder-sdk-js@2.48.25", - "title": "rudder-sdk-js@2.48.25", - "discussion-category": "rudder-sdk-js@2.48.25", + "tag": "rudder-sdk-js@2.48.26", + "title": "rudder-sdk-js@2.48.26", + "discussion-category": "rudder-sdk-js@2.48.26", "notesFile": "./packages/analytics-v1.1/CHANGELOG_LATEST.md" } } diff --git a/packages/loading-scripts/CHANGELOG.md b/packages/loading-scripts/CHANGELOG.md index 584a10c007..ce9945d802 100644 --- a/packages/loading-scripts/CHANGELOG.md +++ b/packages/loading-scripts/CHANGELOG.md @@ -2,6 +2,11 @@ This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver). +## [3.0.41](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-loading-scripts@3.0.40...@rudderstack/analytics-js-loading-scripts@3.0.41) (2024-11-12) + +### Dependency Updates + +* `@rudderstack/analytics-js` updated to version `3.10.1` ## [3.0.40](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-loading-scripts@3.0.39...@rudderstack/analytics-js-loading-scripts@3.0.40) (2024-11-08) ### Dependency Updates diff --git a/packages/loading-scripts/CHANGELOG_LATEST.md b/packages/loading-scripts/CHANGELOG_LATEST.md index 0e2e672b9d..ddafa77076 100644 --- a/packages/loading-scripts/CHANGELOG_LATEST.md +++ b/packages/loading-scripts/CHANGELOG_LATEST.md @@ -1,5 +1,5 @@ -## [3.0.40](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-loading-scripts@3.0.39...@rudderstack/analytics-js-loading-scripts@3.0.40) (2024-11-08) +## [3.0.41](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-loading-scripts@3.0.40...@rudderstack/analytics-js-loading-scripts@3.0.41) (2024-11-12) ### Dependency Updates -* `@rudderstack/analytics-js` updated to version `3.10.0` +* `@rudderstack/analytics-js` updated to version `3.10.1` diff --git a/packages/loading-scripts/package.json b/packages/loading-scripts/package.json index 0c7a60de70..2e1210a4b9 100644 --- a/packages/loading-scripts/package.json +++ b/packages/loading-scripts/package.json @@ -1,6 +1,6 @@ { "name": "@rudderstack/analytics-js-loading-scripts", - "version": "3.0.40", + "version": "3.0.41", "private": true, "description": "Loading script for RudderStack JavaScript SDK", "main": "./src/index.js", diff --git a/packages/loading-scripts/project.json b/packages/loading-scripts/project.json index 4c749e8d3d..a81e8580f2 100644 --- a/packages/loading-scripts/project.json +++ b/packages/loading-scripts/project.json @@ -51,9 +51,9 @@ "github": { "executor": "@jscutlery/semver:github", "options": { - "tag": "@rudderstack/analytics-js-loading-scripts@3.0.40", - "title": "@rudderstack/analytics-js-loading-scripts@3.0.40", - "discussion-category": "@rudderstack/analytics-js-loading-scripts@3.0.40", + "tag": "@rudderstack/analytics-js-loading-scripts@3.0.41", + "title": "@rudderstack/analytics-js-loading-scripts@3.0.41", + "discussion-category": "@rudderstack/analytics-js-loading-scripts@3.0.41", "notesFile": "./packages/loading-scripts/CHANGELOG_LATEST.md" } } diff --git a/packages/sanity-suite/CHANGELOG.md b/packages/sanity-suite/CHANGELOG.md index ad2fed5cc4..36d3d34381 100644 --- a/packages/sanity-suite/CHANGELOG.md +++ b/packages/sanity-suite/CHANGELOG.md @@ -2,6 +2,11 @@ This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver). +## [3.1.32](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-sanity-suite@3.1.31...@rudderstack/analytics-js-sanity-suite@3.1.32) (2024-11-12) + +### Dependency Updates + +* `@rudderstack/analytics-js` updated to version `3.10.1` ## [3.1.31](https://github.com/rudderlabs/rudder-sdk-js/compare/@rudderstack/analytics-js-sanity-suite@3.1.30...@rudderstack/analytics-js-sanity-suite@3.1.31) (2024-11-08) ### Dependency Updates diff --git a/packages/sanity-suite/package.json b/packages/sanity-suite/package.json index 58436da9fd..64305216d4 100644 --- a/packages/sanity-suite/package.json +++ b/packages/sanity-suite/package.json @@ -1,6 +1,6 @@ { "name": "@rudderstack/analytics-js-sanity-suite", - "version": "3.1.31", + "version": "3.1.32", "private": true, "description": "Sanity suite for testing JS SDK package", "main": "./dist/v3/cdn/testBook.js", diff --git a/sonar-project.properties b/sonar-project.properties index 22cc127746..98bcdd661e 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -6,7 +6,7 @@ sonar.qualitygate.wait=false sonar.projectKey=rudderlabs_rudder-sdk-js sonar.organization=rudderlabs sonar.projectName=rudder-sdk-js -sonar.projectVersion=3.48.0 +sonar.projectVersion=3.49.0 # Meta-data for the project sonar.links.scm=https://github.com/rudderlabs/rudder-sdk-js