├── .eslintrc.json ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.yaml │ ├── config.yml │ ├── feature_request.yaml │ └── general-issues.md ├── PULL_REQUEST_TEMPLATE.md └── dependabot.yml ├── .gitignore ├── .prettierignore ├── .prettierrc.js ├── .viperlightignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── SECURITY.md ├── buildspec.yml ├── deployment ├── build-open-source-dist.sh ├── build-s3-dist.sh └── run-unit-tests.sh ├── gtm-template └── ClickstreamAnalytics-gtm-template.tpl ├── jest.config.ts ├── package-lock.json ├── package.json ├── release.sh ├── scripts └── GenerateConfig.ts ├── solution-manifest.yaml ├── sonar-project.properties ├── src ├── ClickstreamAnalytics.ts ├── browser │ ├── BrowserInfo.ts │ └── index.ts ├── index.ts ├── network │ └── NetRequest.ts ├── provider │ ├── AnalyticsEventBuilder.ts │ ├── ClickstreamContext.ts │ ├── ClickstreamProvider.ts │ ├── Event.ts │ ├── EventChecker.ts │ ├── EventRecorder.ts │ └── index.ts ├── tracker │ ├── BaseTracker.ts │ ├── ClickTracker.ts │ ├── PageLoadTracker.ts │ ├── PageViewTracker.ts │ ├── ScrollTracker.ts │ ├── Session.ts │ ├── SessionTracker.ts │ └── index.ts ├── types │ ├── Analytics.ts │ ├── Provider.ts │ └── index.ts └── util │ ├── HashUtil.ts │ ├── MethodEmbed.ts │ └── StorageUtil.ts ├── test ├── ClickstreamAnalytics.test.ts ├── browser │ ├── BrowserInfo.test.ts │ ├── BrowserUtil.ts │ └── MockObserver.ts ├── network │ └── NetRequest.test.ts ├── provider │ ├── AnalyticsEventBuilder.test.ts │ ├── BatchModeTimer.test.ts │ ├── ClickstreamProvider.test.ts │ ├── EventChecker.test.ts │ ├── EventRecorder.test.ts │ └── ImmediateModeCache.test.ts ├── tracker │ ├── ClickTracker.test.ts │ ├── PageLoadTracker.test.ts │ ├── PageViewTracker.test.ts │ ├── ScrollTracker.test.ts │ └── SessionTracker.test.ts └── util │ └── StorageUtil.test.ts ├── tsconfig.json ├── webpack.config.dev.js └── webpack.config.js /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "es6": true 5 | }, 6 | "extends": [ 7 | "eslint:recommended", 8 | "plugin:@typescript-eslint/recommended", 9 | "prettier" 10 | ], 11 | "overrides": [ 12 | { 13 | "files": ["test/**/*"], 14 | "env": { 15 | "jest": true 16 | } 17 | } 18 | ], 19 | "parserOptions": { 20 | "ecmaVersion": "latest", 21 | "sourceType": "module" 22 | }, 23 | "plugins": [ 24 | "import" 25 | ], 26 | "rules": { 27 | "eqeqeq": "warn", 28 | "@typescript-eslint/no-explicit-any": "off", 29 | "import/order": [ 30 | "error", 31 | { 32 | "groups": [ 33 | "builtin", 34 | "external" 35 | ], 36 | "alphabetize": { 37 | "order": "asc", 38 | "caseInsensitive": true 39 | } 40 | } 41 | ] 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.yaml: -------------------------------------------------------------------------------- 1 | name: Bug Report 2 | about: Create a report to help us improve 3 | title: '' 4 | labels: 'bug' 5 | assignees: '' 6 | body: 7 | - type: textarea 8 | id: description 9 | attributes: 10 | label: Describe the bug 11 | description: A clear and concise description of what the bug is. 12 | validations: 13 | required: true 14 | - type: textarea 15 | id: repro 16 | attributes: 17 | label: Steps To Reproduce 18 | description: How do you trigger this bug? Please walk us through it step by step. 19 | value: | 20 | Steps to reproduce the behavior: 21 | 1. Go to '...' 22 | 2. Click on '....' 23 | 3. Scroll down to '....' 24 | 4. See error 25 | render: typescript 26 | validations: 27 | required: true 28 | - type: textarea 29 | id: behavior 30 | attributes: 31 | label: Expected behavior 32 | description: A clear and concise description of what you expected to happen. 33 | validations: 34 | required: true 35 | - type: input 36 | id: clickstream-version 37 | attributes: 38 | label: Clickstream-Web Version 39 | placeholder: e.g. 1.0.0 40 | validations: 41 | required: true 42 | - type: input 43 | id: node 44 | attributes: 45 | label: Node version 46 | placeholder: e.g. 18.12.1 47 | validations: 48 | required: true 49 | - type: input 50 | id: typescript 51 | attributes: 52 | label: TypeScript version 53 | placeholder: | 54 | - e.g. 4.9.5 55 | validations: 56 | required: true 57 | - type: textarea 58 | id: logs 59 | attributes: 60 | label: Relevant log output 61 | description: >- 62 | Include any relevant log output 63 | value: | 64 |
65 | Log Messages 66 | 67 | ``` 68 | INSERT LOG MESSAGES HERE 69 | ``` 70 |
71 | render: shell 72 | - type: dropdown 73 | id: regression 74 | attributes: 75 | label: Is this a regression? 76 | multiple: false 77 | options: 78 | - "Yes" 79 | - "No" 80 | validations: 81 | required: true 82 | - type: textarea 83 | id: regression-info 84 | attributes: 85 | label: Regression additional context 86 | placeholder: If it was a regression provide the versions used before and after the upgrade. 87 | - type: input 88 | id: device 89 | attributes: 90 | label: Browser 91 | placeholder: | 92 | - e.g. Chrome/114.0.0.0 93 | - Safari/537.36 94 | validations: 95 | required: true 96 | - type: textarea 97 | id: context 98 | attributes: 99 | label: Screenshots 100 | description: If applicable, add screenshots to help explain your problem (please **DO NOT include sensitive information**). 101 | - type: textarea 102 | id: context 103 | attributes: 104 | label: Additional context 105 | description: Add any other context about the problem here. 106 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yaml: -------------------------------------------------------------------------------- 1 | name: Feature request 2 | description: Suggest an idea for this project 3 | body: 4 | - type: textarea 5 | id: description 6 | attributes: 7 | label: Is your feature request related to a problem? Please describe. 8 | description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | validations: 10 | required: true 11 | 12 | - type: textarea 13 | id: proposal 14 | attributes: 15 | label: Describe the feature you'd like 16 | description: A clear and concise description of what you want to happen. 17 | validations: 18 | required: true 19 | 20 | - type: textarea 21 | id: alternatives 22 | attributes: 23 | label: Describe alternatives you've considered 24 | description: A clear and concise description of any alternative solutions or features you've considered. 25 | validations: 26 | required: true 27 | 28 | - type: textarea 29 | id: context 30 | attributes: 31 | label: Additional context 32 | description: Add any other context about the problem here. 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/general-issues.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U00002753 General Issue" 3 | about: Create a new issue 4 | title: "" 5 | labels: needs-triage, guidance 6 | --- 7 | 8 | ## :question: General Issue 9 | 10 | ### The Question 11 | 16 | 17 | ### Other information 18 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. 6 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Basic `dependabot.yml` file with 2 | 3 | version: 2 4 | updates: 5 | # Enable version updates for github-actions 6 | - package-ecosystem: "github-actions" 7 | directory: "/" 8 | # Check the actions for updates every week 9 | schedule: 10 | interval: "weekly" -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | **/node_modules 5 | 6 | # production 7 | /dist 8 | /lib 9 | /lib-esm 10 | 11 | # misc 12 | .DS_Store 13 | npm-debug.log* 14 | yarn-error.log 15 | 16 | /coverage 17 | .idea 18 | yarn.lock 19 | *.tsbuildinfo 20 | *.tgz 21 | /src/config.ts 22 | .scannerwork/* 23 | deployment/open-source/ 24 | deployment/regional-s3-assets 25 | deployment/global-s3-assets 26 | deployment/exclude-open-source-list.txt 27 | 28 | build 29 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | package.json 4 | package-lock.json 5 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | module.exports = { 5 | trailingComma: 'es5', 6 | singleQuote: true, 7 | useTabs: true, 8 | tabWidth: 2, 9 | arrowParens: 'avoid', 10 | }; 11 | -------------------------------------------------------------------------------- /.viperlightignore: -------------------------------------------------------------------------------- 1 | # Use of opensource-codeofconduct email for amazon is expected 2 | CONTRIBUTING.md 3 | CODE_OF_CONDUCT.md 4 | 5 | .github/ 6 | node_modules/ 7 | coverage/ 8 | .*/package-lock.json -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [0.12.5] - 2025-05-29 9 | 10 | ### Bug 11 | 12 | - Fix "no-cors" setting in compiled code 13 | 14 | ## [0.12.4] - 2025-04-09 15 | 16 | ### Security 17 | 18 | - Updated npm dependencies 19 | 20 | ## [0.12.3] - 2025-02-28 21 | 22 | ### Added 23 | 24 | - Updated GitHub link to https://github.com/aws-solutions/clickstream-analytics-on-aws-web-sdk 25 | - Update gradle and fix vulnerabilities -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check [existing open](https://github.com/aws-solutions/clickstream-analytics-on-aws-web-sdk/issues), or [recently closed](https://github.com/aws-solutions/clickstream-analytics-on-aws-web-sdk/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/aws-solutions/clickstream-analytics-on-aws-web-sdk/labels/help%20wanted) issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](https://github.com/aws-solutions/%%SOLUTION_NAME%%/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](https://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | 63 | 64 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AWS Solution Clickstream Analytics SDK for Web 2 | 3 | ## Introduction 4 | 5 | Clickstream Web SDK can help you easily collect and report events from browser to AWS. This SDK is part of an AWS solution - [Clickstream Analytics on AWS](https://github.com/aws-solutions/clickstream-analytics-on-aws), which provisions data pipeline to ingest and process event data into AWS services such as S3, Redshift. 6 | 7 | The SDK relies on the Amplify for JS SDK Core Library and is developed according to the Amplify AnalyticsProvider interface. In addition, we've added features that automatically collect common user events and attributes (e.g., page view, first open) to simplify data collection for users. 8 | 9 | Visit our [Documentation site](https://aws-solutions.github.io/clickstream-analytics-on-aws/en/latest/sdk-manual/web/) to learn more about Clickstream Web SDK. 10 | 11 | ## Integrate SDK 12 | 13 | ### Include SDK 14 | 15 | ```bash 16 | $ npm install @aws/clickstream-web 17 | ``` 18 | 19 | ### Initialize the SDK 20 | Copy your configuration code from your clickstream solution web console, we recommended you add the code to your app's root entry point, for example `index.js/app.tsx` in React or `main.ts` in Vue/Angular, the configuration code should look like as follows. You can also manually add this code snippet and replace the values of appId and endpoint after you registered app to a data pipeline in the Clickstream Analytics solution console. 21 | 22 | ```typescript 23 | import { ClickstreamAnalytics } from '@aws/clickstream-web'; 24 | 25 | ClickstreamAnalytics.init({ 26 | appId: "your appId", 27 | endpoint: "https://example.com/collect", 28 | }); 29 | ``` 30 | 31 | Your `appId` and `endpoint` are already set up in it. 32 | 33 | ### Start using 34 | 35 | #### Record event 36 | 37 | Add the following code where you need to record event. 38 | 39 | ```typescript 40 | import { ClickstreamAnalytics } from '@aws/clickstream-web'; 41 | 42 | // record event with attributes 43 | ClickstreamAnalytics.record({ 44 | name: 'button_click', 45 | attributes: { 46 | event_category: 'shoes', 47 | currency: 'CNY', 48 | value: 279.9, 49 | } 50 | }); 51 | 52 | //record event with name 53 | ClickstreamAnalytics.record({ name: 'button_click' }); 54 | ``` 55 | 56 | #### Login and logout 57 | 58 | ```typescript 59 | import { ClickstreamAnalytics } from '@aws/clickstream-web'; 60 | 61 | // when user login success. 62 | ClickstreamAnalytics.setUserId("UserId"); 63 | 64 | // when user logout 65 | ClickstreamAnalytics.setUserId(null); 66 | ``` 67 | 68 | #### Add user attribute 69 | 70 | ```typescript 71 | ClickstreamAnalytics.setUserAttributes({ 72 | userName:"carl", 73 | userAge: 22 74 | }); 75 | ``` 76 | 77 | When opening for the first time after integrating the SDK, you need to manually set the user attributes once, and current login user's attributes will be cached in localStorage, so the next time browser open you don't need to set all user's attribute again, of course you can use the same api `ClickstreamAnalytics.setUserAttributes()` to update the current user's attribute when it changes. 78 | 79 | #### Add global attribute 80 | 1. Add global attributes when initializing the SDK 81 | 82 | The following example code shows how to add traffic source fields as global attributes when initializing the SDK. 83 | 84 | ```typescript 85 | import { ClickstreamAnalytics, Attr } from '@aws/clickstream-web'; 86 | 87 | ClickstreamAnalytics.init({ 88 | appId: "your appId", 89 | endpoint: "https://example.com/collect", 90 | globalAttributes:{ 91 | [Attr.TRAFFIC_SOURCE_SOURCE]: 'amazon', 92 | [Attr.TRAFFIC_SOURCE_MEDIUM]: 'cpc', 93 | [Attr.TRAFFIC_SOURCE_CAMPAIGN]: 'summer_promotion', 94 | [Attr.TRAFFIC_SOURCE_CAMPAIGN_ID]: 'summer_promotion_01', 95 | [Attr.TRAFFIC_SOURCE_TERM]: 'running_shoes', 96 | [Attr.TRAFFIC_SOURCE_CONTENT]: 'banner_ad_1', 97 | [Attr.TRAFFIC_SOURCE_CLID]: 'amazon_ad_123', 98 | [Attr.TRAFFIC_SOURCE_CLID_PLATFORM]: 'amazon_ads', 99 | } 100 | }); 101 | ``` 102 | 103 | 2. Add global attributes after initializing the SDK 104 | 105 | ``` typescript 106 | import { ClickstreamAnalytics, Attr } from '@aws/clickstream-web'; 107 | 108 | ClickstreamAnalytics.setGlobalAttributes({ 109 | [Attr.TRAFFIC_SOURCE_MEDIUM]: "Search engine", 110 | level: 10, 111 | }); 112 | ``` 113 | 114 | It is recommended to set global attributes when initializing the SDK, global attributes will be included in all events that occur after it is set, you also can remove a global attribute by setting its value to `null`. 115 | 116 | #### Record event with items 117 | 118 | You can add the following code to log an event with an item. 119 | 120 | **Note: Only pipelines from version 1.1+ can handle items with custom attribute.** 121 | 122 | ```typescript 123 | import { ClickstreamAnalytics, Item, Attr } from '@aws/clickstream-web'; 124 | 125 | const itemBook: Item = { 126 | id: '123', 127 | name: 'Nature', 128 | category: 'book', 129 | price: 99, 130 | book_publisher: "Nature Research", 131 | }; 132 | ClickstreamAnalytics.record({ 133 | name: 'view_item', 134 | attributes: { 135 | [Attr.CURRENCY]: 'USD', 136 | [Attr.VALUE]: 99, 137 | event_category: 'recommended', 138 | }, 139 | items: [itemBook], 140 | }); 141 | ``` 142 | 143 | #### Send event immediate in batch mode 144 | 145 | When you are in batch mode, you can still send an event immediately by setting the `isImmediate` attribute, as in the following code: 146 | 147 | ```typescript 148 | import { ClickstreamAnalytics } from '@aws/clickstream-web'; 149 | 150 | ClickstreamAnalytics.record({ 151 | name: 'button_click', 152 | isImmediate: true, 153 | }); 154 | ``` 155 | 156 | #### Other configurations 157 | In addition to the required `appId` and `endpoint`, you can configure other information to get more customized usage: 158 | 159 | ```typescript 160 | import { ClickstreamAnalytics, EventMode, PageType } from '@aws/clickstream-web'; 161 | 162 | ClickstreamAnalytics.init({ 163 | appId: "your appId", 164 | endpoint: "https://example.com/collect", 165 | sendMode: EventMode.Batch, 166 | sendEventsInterval: 5000, 167 | isTrackPageViewEvents: true, 168 | isTrackUserEngagementEvents: true, 169 | isTrackClickEvents: true, 170 | isTrackSearchEvents: true, 171 | isTrackScrollEvents: true, 172 | isTrackPageLoadEvents: true, 173 | isTrackAppStartEvents: true, 174 | isTrackAppEndEvents: true, 175 | pageType: PageType.SPA, 176 | isLogEvents: false, 177 | authCookie: "your auth cookie", 178 | sessionTimeoutDuration: 1800000, 179 | idleTimeoutDuration: 120000, 180 | searchKeyWords: ['product', 'class'], 181 | domainList: ['example1.com', 'example2.com'], 182 | }); 183 | ``` 184 | 185 | Here is an explanation of each property: 186 | 187 | - **appId (Required)**: the app id of your project in control plane. 188 | - **endpoint (Required)**: the endpoint path you will upload the event to AWS server. 189 | - **sendMode**: EventMode.Immediate, EventMode.Batch, default is Immediate mode. 190 | - **sendEventsInterval**: event sending interval millisecond, works only bath send mode, the default value is `5000` 191 | - **isTrackPageViewEvents**: whether auto record page view events in browser, default is `true` 192 | - **isTrackUserEngagementEvents**: whether auto record user engagement events in browser, default is `true` 193 | - **isTrackClickEvents**: whether auto record link click events in browser, default is `true` 194 | - **isTrackSearchEvents**: whether auto record search result page events in browser, default is `true` 195 | - **isTrackScrollEvents**: whether auto record page scroll events in browser, default is `true` 196 | - **isTrackPageLoadEvents**: whether auto record page load performance events in browser, default is `false` 197 | - **isTrackAppStartEvents**: whether auto record app start events in browser when pages becomes visible, default is `false` 198 | - **isTrackAppEndEvents**: whether auto record app end events in browser when pages becomes invisible, default is `false` 199 | - **pageType**: the website type, `SPA` for single page application, `multiPageApp` for multiple page application, default is `SPA`. This attribute works only when the attribute `isTrackPageViewEvents`'s value is `true` 200 | - **isLogEvents**: whether to print out event json for debugging, default is false. 201 | - **authCookie**: your auth cookie for AWS application load balancer auth cookie. 202 | - **sessionTimeoutDuration**: the duration for session timeout millisecond, default is 1800000 203 | - **idleTimeoutDuration**: the maximum duration of user inactivity before triggering an idle state, default is 120000 millisecond, Any idle duration exceeding this threshold will be removed in the user_engagement events on the current page. 204 | - **searchKeyWords**: the customized Keywords for trigger the `_search` event, by default we detect `q`, `s`, `search`, `query` and `keyword` in query parameters. 205 | - **domainList**: if your website cross multiple domain, you can customize the domain list. The `_outbound` attribute of the `_click` event will be true when a link leads to a website that's not a part of your configured domain. 206 | 207 | #### Configuration update 208 | You can update the default configuration after initializing the SDK, below are the additional configuration options you can customize. 209 | 210 | ```typescript 211 | import { ClickstreamAnalytics } from '@aws/clickstream-web'; 212 | 213 | ClickstreamAnalytics.updateConfigure({ 214 | isLogEvents: true, 215 | authCookie: 'your auth cookie', 216 | isTrackPageViewEvents: false, 217 | isTrackUserEngagementEvents: false, 218 | isTrackClickEvents: false, 219 | isTrackScrollEvents: false, 220 | isTrackSearchEvents: false, 221 | isTrackPageLoadEvents: false, 222 | isTrackAppStartEvents: true, 223 | isTrackAppEndEvents: true, 224 | }); 225 | ``` 226 | 227 | ## Implementing Clickstream Web SDK in Google Tag Manager Using Template 228 | 229 | 1. Download the Clickstream SDK template file (.tpl) from the [SDK Release Page](https://github.com/aws-solutions/clickstream-analytics-on-aws-web-sdk/releases). 230 | 2. Refer to the Google Tag Manager [Import Guide](https://developers.google.com/tag-platform/tag-manager/templates#export_and_import) for instructions on importing the .tpl file as a custom template in your tag manager console. 231 | 3. Refer to the [Use your new tag](https://developers.google.com/tag-platform/tag-manager/templates#use_your_new_tag) to add ClickstreamAnalytics tag to your container. 232 | 4. The ClickstreamAnalytics tag currently supports four tag types: 233 | * Initialize SDK 234 | * Record Custom Event 235 | * Set User ID 236 | * Set User Attribute 237 | 238 | Note: Ensure that you initialize the SDK tag first before use other ClickstreamAnalytics tag types. 239 | 240 | ## How to integrate and test locally 241 | 242 | ### Integrate the `.tgz` file 243 | 244 | Clone this repository locally and execute the following script to generate `aws-clickstream-web-0.12.5.tgz` zip package, which will be located in the project root folder. 245 | ```bash 246 | $ cd clickstream-web && npm i && npm run pack 247 | ``` 248 | 249 | Copy the `aws-clickstream-web-0.12.5.tgz` into your project, then execute the script in your project root folder to install the SDK. 250 | ```bash 251 | $ npm install ./aws-clickstream-web-0.12.5.tgz 252 | ``` 253 | **Note**: Please correct the SDK version and change the path to where the `aws-clickstream-web-0.12.5.tgz` file is located. 254 | 255 | ### Integrate the `clickstream-web.min.js` file 256 | Execute the following script to generate `clickstream-web.min.js`, located in the `/dist` folder. 257 | ```bash 258 | $ cd clickstream-web && npm i && npm run pack 259 | ``` 260 | Copy the `clickstream-web.min.js` into your project and add the following initial code into your `index.html`. 261 | 262 | ```html 263 | 264 | 273 | ``` 274 | You can also find the `clickstream-web.min.js` file in the [Release](https://github.com/aws-solutions/clickstream-analytics-on-aws-web-sdk/releases) page. 275 | 276 | ### Test 277 | 278 | ```bash 279 | $ npm run test 280 | 281 | # with lint 282 | $ sh ./deployment/run-unit-tests.sh 283 | ``` 284 | 285 | ## Collection of operational metrics 286 | 287 | This solution collects anonymized operational metrics to help AWS improve the 288 | quality of features of the solution. For more information, including how to disable 289 | this capability, please see the [implementation guide](https://docs.aws.amazon.com/solutions/latest/clickstream-analytics-on-aws). 290 | 291 | ## Security 292 | 293 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 294 | 295 | ## License 296 | 297 | This library is licensed under the [Apache 2.0 License](./LICENSE). 298 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | ## Reporting Security Issues 2 | 3 | We take all security reports seriously. When we receive such reports, 4 | we will investigate and subsequently address any potential vulnerabilities as 5 | quickly as possible. If you discover a potential security issue in this project, 6 | please notify AWS/Amazon Security via our [vulnerability reporting page] 7 | (http://aws.amazon.com/security/vulnerability-reporting/) or directly via email 8 | to [AWS Security](mailto:aws-security@amazon.com). 9 | Please do *not* create a public GitHub issue in this project. -------------------------------------------------------------------------------- /buildspec.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | 3 | env: 4 | shell: bash 5 | # Define global variables 6 | variables: 7 | PACKAGE_VERSION: "0.12.5" 8 | PACKAGE_NAME: "aws-clickstream-web" 9 | 10 | phases: 11 | install: 12 | runtime-versions: 13 | nodejs: latest 14 | commands: 15 | - n 20.16.0 16 | pre_build: 17 | commands: 18 | - echo "=== Starting Pre-Build Phase ===" 19 | - echo "Installing npm dependencies..." 20 | - npm i 21 | - echo "Dependencies installed successfully" 22 | 23 | - |- 24 | # Quality assurance and testing block 25 | echo "=== Starting Quality Checks ===" 26 | 27 | # Enable strict error handling 28 | set -euxo pipefail 29 | 30 | echo "Running code formatting..." 31 | npm run format 32 | echo "✓ Code formatting complete" 33 | 34 | echo "Running linting checks..." 35 | npm run lint 36 | echo "✓ Linting complete" 37 | 38 | echo "Running test suites..." 39 | npm run test 40 | 41 | TEST_EXIT_CODE=$? 42 | if [ $TEST_EXIT_CODE -ne 0 ]; then 43 | echo "❌ Error: Test suite failed with exit code $TEST_EXIT_CODE" >&2 44 | exit 1 45 | fi 46 | echo "✓ All tests passed successfully" 47 | build: 48 | commands: 49 | - echo "=== Starting Build Phase @ $(date) ===" 50 | - CURRENT_DIR=$(pwd) 51 | - cd deployment 52 | - chmod +x ./build-s3-dist.sh && ./build-s3-dist.sh --template-bucket ${TEMPLATE_OUTPUT_BUCKET} --version ${VERSION} --region ${AWS_REGION} 53 | - echo "Build completed `date`" 54 | - echo "Starting open-source-dist `date` in `pwd`" 55 | - chmod +x ./build-open-source-dist.sh && ./build-open-source-dist.sh $SOLUTION_NAME 56 | - echo "Open Source Dist completed `date`" 57 | - cd $CURRENT_DIR 58 | - echo "Creating distribution package..." 59 | - npm run pack 60 | - echo "✓ Package creation complete" 61 | post_build: 62 | commands: 63 | - echo "=== Starting Post-Build Phase ===" 64 | - |- 65 | set -euxo pipefail 66 | echo "Verifying package artifact..." 67 | 68 | # Define package filename 69 | PACKAGE_FILENAME="${PACKAGE_NAME}-${PACKAGE_VERSION}.tgz" 70 | echo "Package filename: ${PACKAGE_FILENAME}" 71 | 72 | if [ ! -f "$PACKAGE_FILENAME" ]; then 73 | echo "❌ Error: Package file $PACKAGE_FILENAME not found" >&2 74 | exit 1 75 | fi 76 | 77 | echo "✓ Package verified successfully at $(date)" 78 | echo "Build artifacts:" 79 | ls -la *.tgz 80 | echo "Build Summary:" 81 | echo "- Node Version: $(node -v)" 82 | echo "- NPM Version: $(npm -v)" 83 | echo "- Build Timestamp: $(date)" 84 | echo "- Package Size: $(ls -lh $PACKAGE_FILENAME | awk '{print $5}')" 85 | - echo "=== Build Process Completed Successfully ===" 86 | artifacts: 87 | exclude-paths: 88 | - .nightswatch/**/* 89 | files: 90 | - '**/*' 91 | -------------------------------------------------------------------------------- /deployment/build-open-source-dist.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # This script packages your project into an open-source solution distributable 4 | # that can be published to sites like GitHub. 5 | # 6 | # Important notes and prereq's: 7 | # 1. The initialize-repo.sh script must have been run in order for this script to 8 | # function properly. 9 | # 2. This script should be run from the repo's /deployment folder. 10 | # 11 | # This script will perform the following tasks: 12 | # 1. Remove any old dist files from previous runs. 13 | # 2. Package the GitHub contribution and pull request templates (typically 14 | # found in the /.github folder). 15 | # 3. Package the /source folder along with the necessary root-level 16 | # open-source artifacts (i.e. CHANGELOG, etc.). 17 | # 4. Remove any unecessary artifacts from the /open-source folder (i.e. 18 | # node_modules, package-lock.json, etc.). 19 | # 5. Zip up the /open-source folder and create the distributable. 20 | # 6. Remove any temporary files used for staging. 21 | # 22 | # Parameters: 23 | # - solution-name: name of the solution for consistency 24 | 25 | # Check to see if the required parameters have been provided: 26 | if [ -z "$1" ]; then 27 | echo "Please provide the trademark approved solution name for the open source package." 28 | echo "For example: ./build-open-source-dist.sh trademarked-solution-name" 29 | exit 1 30 | fi 31 | 32 | # Check to see if the required tools have been installed 33 | for cmd in rsync zip; do 34 | if ! command -v $cmd &> /dev/null; then 35 | echo "Error: $cmd is not installed" 36 | exit 1 37 | fi 38 | done 39 | 40 | echo "All required tools are installed" 41 | 42 | # Get reference for all important folders 43 | source_template_dir="$PWD" 44 | dist_dir="$source_template_dir/open-source" 45 | source_dir="$source_template_dir/../" 46 | github_dir="$source_template_dir/../.github" 47 | 48 | echo "------------------------------------------------------------------------------" 49 | echo "[Init] Remove any old dist files from previous runs" 50 | echo "------------------------------------------------------------------------------" 51 | 52 | echo "rm -rf $dist_dir" 53 | rm -rf $dist_dir 54 | echo "mkdir -p $dist_dir" 55 | mkdir -p $dist_dir 56 | 57 | echo "------------------------------------------------------------------------------" 58 | echo "[Packing] all source files" 59 | echo "------------------------------------------------------------------------------" 60 | 61 | echo " 62 | Config 63 | .crux_template.md 64 | " > exclude-open-source-list.txt 65 | echo "rsync -av --exclude-from='exclude-open-source-list.txt' --exclude-from='../.gitignore' $source_dir $dist_dir" 66 | rsync -av --exclude-from='exclude-open-source-list.txt' --exclude-from='../.gitignore' $source_dir $dist_dir 67 | 68 | echo "------------------------------------------------------------------------------" 69 | echo "[Packing] Create GitHub (open-source) zip file" 70 | echo "------------------------------------------------------------------------------" 71 | 72 | # Create the zip file 73 | echo "cd $dist_dir" 74 | cd $dist_dir 75 | 76 | echo "zip -q -r9 ../$1.zip ." 77 | zip -q -r9 ../$1.zip . 78 | 79 | # Cleanup any temporary/unnecessary files 80 | echo "Clean up open-source folder" 81 | echo "rm -rf open-source/" 82 | rm -rf * .* 83 | 84 | # Place final zip file in $dist_dir 85 | echo "mv ../$1.zip ." 86 | mv ../$1.zip . 87 | 88 | echo "Completed building $1.zip dist" 89 | -------------------------------------------------------------------------------- /deployment/build-s3-dist.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # This solution does not use CDK, The Script is used as a placeholder for code build pipeline release stage. 4 | 5 | # This assumes all of the OS-level configuration has been completed and git repo has already been cloned 6 | # 7 | # This script should be run from the repo's deployment directory 8 | # cd deployment 9 | # ./build-s3-dist.sh source-bucket-base-name solution-name version-code 10 | # 11 | # Paramenters: 12 | # - source-bucket-base-name: Name for the S3 bucket location where the template will source the Lambda 13 | # code from. The template will append '-[region_name]' to this bucket name. 14 | # For example: ./build-s3-dist.sh solutions v1.1.0 15 | # The template will then expect the source code to be located in the solutions-[region_name] bucket 16 | # 17 | # - solution-name: name of the solution for consistency 18 | # 19 | # - version-code: version of the package 20 | 21 | # Check to see if input has been provided: 22 | if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then 23 | echo "Please provide the base source bucket name, trademark approved solution name and version where the lambda code will eventually reside." 24 | echo "For example: ./build-s3-dist.sh solutions trademarked-solution-name v1.1.0" 25 | exit 1 26 | fi 27 | 28 | set -x 29 | 30 | # Get reference for all important folders 31 | template_dir="$PWD" 32 | template_dist_dir="$template_dir/global-s3-assets" 33 | build_dist_dir="$template_dir/regional-s3-assets" 34 | 35 | echo "------------------------------------------------------------------------------" 36 | echo "[Init] Clean output folders" 37 | echo "------------------------------------------------------------------------------" 38 | rm -rf $template_dist_dir 39 | mkdir -p $template_dist_dir 40 | rm -rf $build_dist_dir 41 | mkdir -p $build_dist_dir 42 | 43 | echo "------------------------------------------------------------------------------" 44 | echo "[Init] Add global-s3-assets and regional-s3-assets README files" 45 | echo "------------------------------------------------------------------------------" 46 | echo "This folder is intentionally empty because this solution is a code-only SDK." >$template_dist_dir/README.txt 47 | echo "This folder is intentionally empty because this solution is a code-only SDK." >$build_dist_dir/README.txt 48 | 49 | exit 0 50 | -------------------------------------------------------------------------------- /deployment/run-unit-tests.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # sh ./deployment/run-unit-tests.sh 4 | 5 | set -euxo pipefail 6 | 7 | log() { 8 | echo -e "[INFO] $1" 9 | } 10 | 11 | error() { 12 | echo -e "[ERROR] $1" 13 | exit 1 14 | } 15 | 16 | # Install dependencies 17 | log "Installing dependencies..." 18 | npm i || error "Failed to install dependencies" 19 | 20 | 21 | # Run prettier format 22 | log "Running prettier..." 23 | npm run format || error "Prettier failed." 24 | 25 | # Run linting 26 | log "Running linter..." 27 | npm run lint || error "Linting failed." 28 | 29 | # Run tests 30 | log "Running tests..." 31 | npm run test || error "Tests failed" 32 | 33 | log "All tests passed!" 34 | -------------------------------------------------------------------------------- /jest.config.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | module.exports = { 5 | preset: 'ts-jest', 6 | testMatch: ['**/*.test.ts'], 7 | moduleFileExtensions: ['ts', 'js'], 8 | testEnvironment: 'jsdom', 9 | coveragePathIgnorePatterns: ['test'], 10 | transform: { 11 | "^.+\\.(js|ts|tsx)$": [ 12 | "ts-jest", 13 | {} 14 | ] 15 | }, 16 | transformIgnorePatterns: [ 17 | "/node_modules/(?!(\@fetch-mock/jest|fetch-mock)/)" 18 | ], 19 | verbose: true, 20 | collectCoverage: true, 21 | coverageThreshold: { 22 | global: { 23 | branches: 100, 24 | functions: 100, 25 | lines: 100, 26 | statements: 100, 27 | }, 28 | } 29 | }; 30 | 31 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@aws/clickstream-web", 3 | "version": "0.12.5", 4 | "description": "ClickstreamAnalytics Web SDK", 5 | "license": "Apache-2.0", 6 | "main": "./lib/index.js", 7 | "module": "./lib-esm/index.js", 8 | "typings": "./lib-esm/index.d.ts", 9 | "publishConfig": { 10 | "access": "public" 11 | }, 12 | "scripts": { 13 | "prebuild": "ts-node scripts/GenerateConfig.ts", 14 | "build": "npm run prebuild && npm run clean && npm run build:esm && npm run build:cjs", 15 | "build-dev": "npm run clean && npx tsc && npx webpack --config webpack.config.dev.js", 16 | "build:cjs": "npx tsc --module commonjs && webpack && webpack --config webpack.config.dev.js", 17 | "build:esm": "npx tsc --module esnext --outDir lib-esm", 18 | "format": "npx prettier --check 'src/**/*.{js,ts}'", 19 | "lint": "npx eslint src", 20 | "test": "npm run prebuild && npx jest --clear-cache && npx jest -w 1 --coverage || exit 0", 21 | "clean": "rimraf lib-esm lib dist", 22 | "pack": "npm run build && npm pack" 23 | }, 24 | "repository": { 25 | "type": "git", 26 | "url": "git+https://github.com/aws-solutions/clickstream-analytics-on-aws-web-sdk.git" 27 | }, 28 | "author": "AWS GCR Solutions Team", 29 | "dependencies": { 30 | "@aws-amplify/core": "^5.5.1", 31 | "@aws-crypto/sha256-browser": "^4.0.0", 32 | "cookie": "^0.7.0", 33 | "micromatch": "^4.0.8", 34 | "send": "^0.19.0", 35 | "serve-static": "^1.16.0", 36 | "tslib": "^2.6.0", 37 | "uuid": "^9.0.0" 38 | }, 39 | "devDependencies": { 40 | "@fetch-mock/jest": "^0.2.3", 41 | "@types/jest": "^29.5.14", 42 | "@types/jsdom": "^21.1.1", 43 | "@types/uuid": "^9.0.0", 44 | "@typescript-eslint/eslint-plugin": "^5.60.0", 45 | "babel-loader": "^9.1.3", 46 | "eslint": "^8.43.0", 47 | "eslint-config-prettier": "8.8.0", 48 | "eslint-plugin-import": "^2.27.5", 49 | "jest": "^29.7.0", 50 | "jest-environment-jsdom": "29.5.0", 51 | "prettier": "^2.8.8", 52 | "terser-webpack-plugin": "^5.3.9", 53 | "ts-jest": "^29.2.5", 54 | "ts-node": "^10.9.2", 55 | "typescript": "^4.9.5", 56 | "webpack-cli": "^5.1.4", 57 | "webpack": "^5.94.0" 58 | }, 59 | "files": [ 60 | "lib", 61 | "lib-esm", 62 | "src" 63 | ], 64 | "engines": { 65 | "node": ">=20.16.0" 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | version="$1" 4 | echo ${version} 5 | regex="[0-9]\+\.[0-9]\+\.[0-9]\+" 6 | 7 | sed -i "s/\"version\": \"${regex}\"/\"version\": \"${version}\"/g" package.json 8 | sed -i "s/aws-clickstream-web-${regex}.tgz/aws-clickstream-web-${version}.tgz/g" README.md 9 | sed -i "s#v${regex}/clickstream-web.min.js#v${version}/clickstream-web.min.js#g" gtm-template/ClickstreamAnalytics-gtm-template.tpl 10 | -------------------------------------------------------------------------------- /scripts/GenerateConfig.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import fs from 'fs'; 5 | import { version } from '../package.json'; 6 | 7 | const config = `{ 8 | sdkVersion: '${version}', 9 | }; 10 | `; 11 | fs.writeFileSync('./src/config.ts', `export default ${config}`); 12 | console.log(`Version ${version} written to .env file.`); 13 | -------------------------------------------------------------------------------- /solution-manifest.yaml: -------------------------------------------------------------------------------- 1 | id: SO0318 2 | name: clickstream-analytics-on-aws-web-sdk 3 | version: v0.12.5 4 | cloudformation_templates: [] 5 | build_environment: 6 | build_image: 'aws/codebuild/standard:7.0' -------------------------------------------------------------------------------- /sonar-project.properties: -------------------------------------------------------------------------------- 1 | # Customize sonar.sources, sonar.exclusions, sonar.coverage.exclusions, sonar.tests and sonar 2 | # unit test coverage reports based on your solutions 3 | 4 | # Refer to https://docs.sonarqube.org/latest/project-administration/narrowing-the-focus/ 5 | # for details on sources and exclusions. Note also .gitignore 6 | # 7 | sonar.sources=src/ 8 | sonar.tests=test/ 9 | sonar.test.inclusions=test/**/*,\ 10 | 11 | 12 | # Code coverage Specific Properties 13 | sonar.javascript.lcov.reportPaths=coverage/lcov.info 14 | 15 | # Encoding of the source files 16 | sonar.sourceEncoding=UTF-8 17 | -------------------------------------------------------------------------------- /src/ClickstreamAnalytics.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { ConsoleLogger as Logger } from '@aws-amplify/core'; 5 | import { ClickstreamProvider } from './provider'; 6 | import { 7 | ClickstreamAttribute, 8 | ClickstreamConfiguration, 9 | ClickstreamEvent, 10 | Configuration, 11 | } from './types'; 12 | 13 | export class ClickstreamAnalytics { 14 | private static provider: ClickstreamProvider; 15 | private static logger = new Logger('ClickstreamAnalytics'); 16 | 17 | /** 18 | * the init method for clickstream SDK 19 | * @param configure 20 | * @return the SDK initialize boolean result 21 | */ 22 | public static init(configure: ClickstreamConfiguration): boolean { 23 | if (this.provider !== undefined) { 24 | this.logger.warn('Clickstream SDK has initialized'); 25 | return false; 26 | } 27 | this.provider = new ClickstreamProvider(); 28 | this.provider.configure(configure); 29 | return true; 30 | } 31 | 32 | public static record(event: ClickstreamEvent) { 33 | this.provider.record(event); 34 | } 35 | 36 | public static setUserId(userId: string | null) { 37 | this.provider.setUserId(userId); 38 | } 39 | 40 | public static setUserAttributes(attributes: ClickstreamAttribute) { 41 | this.provider.setUserAttributes(attributes); 42 | } 43 | 44 | public static updateConfigure(configure: Configuration) { 45 | this.provider.updateConfigure(configure); 46 | } 47 | 48 | public static setGlobalAttributes(attributes: ClickstreamAttribute) { 49 | this.provider.setGlobalAttributes(attributes); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/browser/BrowserInfo.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { Logger } from '@aws-amplify/core'; 5 | import { StorageUtil } from '../util/StorageUtil'; 6 | 7 | const logger = new Logger('BrowserInfo'); 8 | 9 | export class BrowserInfo { 10 | locale: string; 11 | system_language: string; 12 | country_code: string; 13 | make: string; 14 | userAgent: string; 15 | zoneOffset: number; 16 | hostName: string; 17 | latestReferrer: string; 18 | latestReferrerHost: string; 19 | 20 | constructor() { 21 | if (!BrowserInfo.isBrowser()) return; 22 | const { product, vendor, userAgent, language } = window.navigator; 23 | this.locale = language; 24 | this.initLocalInfo(language); 25 | this.make = product || vendor; 26 | this.userAgent = userAgent; 27 | this.zoneOffset = -new Date().getTimezoneOffset() * 60000; 28 | this.hostName = window.location.hostname; 29 | this.latestReferrer = window.document.referrer; 30 | if (this.latestReferrer && this.latestReferrer !== '') { 31 | try { 32 | const url = new URL(this.latestReferrer); 33 | this.latestReferrerHost = url.host; 34 | } catch (error) { 35 | logger.warn('parse latest referrer domain failed: ' + error); 36 | } 37 | } 38 | } 39 | 40 | initLocalInfo(locale: string) { 41 | if (locale.indexOf('-') > 0) { 42 | this.system_language = locale.split('-')[0]; 43 | this.country_code = locale.split('-')[1].toUpperCase(); 44 | } else { 45 | this.system_language = locale; 46 | this.country_code = ''; 47 | } 48 | } 49 | 50 | static isBrowser(): boolean { 51 | return ( 52 | typeof window !== 'undefined' && typeof window.document !== 'undefined' 53 | ); 54 | } 55 | 56 | static isFirefox(): boolean { 57 | return navigator.userAgent.toLowerCase().indexOf('firefox') > -1; 58 | } 59 | 60 | static isNetworkOnLine(): boolean { 61 | return navigator.onLine; 62 | } 63 | 64 | static getCurrentPageUrl(): string { 65 | if (!BrowserInfo.isBrowser()) return ''; 66 | else return window.location.href; 67 | } 68 | 69 | static getCurrentPageTitle(): string { 70 | if (!BrowserInfo.isBrowser()) return ''; 71 | return window.document.title ?? ''; 72 | } 73 | 74 | static isFromReload() { 75 | if (performance && performance.getEntriesByType) { 76 | const performanceEntries = performance.getEntriesByType('navigation'); 77 | if (performanceEntries && performanceEntries.length > 0) { 78 | const type = (performanceEntries[0] as any)['type']; 79 | return type === 'reload' && StorageUtil.getPreviousPageUrl() !== ''; 80 | } 81 | } else { 82 | logger.warn('unsupported web environment for performance'); 83 | } 84 | return false; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/browser/index.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export * from './BrowserInfo'; 5 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export { ClickstreamAnalytics } from './ClickstreamAnalytics'; 5 | export { PageType, SendMode, Item, Attr } from './types'; 6 | -------------------------------------------------------------------------------- /src/network/NetRequest.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { ConsoleLogger as Logger } from '@aws-amplify/core'; 5 | import { ClickstreamContext } from '../provider'; 6 | import { HashUtil } from '../util/HashUtil'; 7 | 8 | const logger = new Logger('NetRequest'); 9 | 10 | export class NetRequest { 11 | static readonly REQUEST_TIMEOUT = 10000; 12 | static readonly BATCH_REQUEST_TIMEOUT = 15000; 13 | static readonly REQUEST_RETRY_TIMES = 3; 14 | static readonly BATCH_REQUEST_RETRY_TIMES = 1; 15 | static readonly KEEP_ALIVE_SIZE_LIMIT = 64 * 1024; 16 | 17 | static async sendRequest( 18 | eventsJson: string, 19 | context: ClickstreamContext, 20 | bundleSequenceId: number, 21 | retryTimes = NetRequest.REQUEST_RETRY_TIMES, 22 | timeout = NetRequest.REQUEST_TIMEOUT 23 | ): Promise { 24 | const { configuration, browserInfo } = context; 25 | const eventsHash = await HashUtil.getHashCode(eventsJson); 26 | const queryParams = new URLSearchParams({ 27 | platform: 'Web', 28 | appId: configuration.appId, 29 | event_bundle_sequence_id: bundleSequenceId.toString(), 30 | upload_timestamp: new Date().getTime().toString(), 31 | hashCode: eventsHash, 32 | }); 33 | const url = `${configuration.endpoint}?${queryParams.toString()}`; 34 | 35 | const controller = new AbortController(); 36 | const timeoutId = setTimeout(() => { 37 | controller.abort(); 38 | }, timeout); 39 | const inputSizeInBytes = new Blob([eventsJson]).size; 40 | const isKeepAlive = inputSizeInBytes < NetRequest.KEEP_ALIVE_SIZE_LIMIT; 41 | const requestOptions: RequestInit = { 42 | method: 'POST', 43 | mode: 'cors', 44 | headers: { 45 | 'Content-Type': 'application/json; charset=utf-8', 46 | cookie: configuration.authCookie?.toString() ?? '', 47 | 'User-Agent': browserInfo.userAgent?.toString() ?? '', 48 | }, 49 | credentials: 'include', 50 | body: eventsJson, 51 | keepalive: isKeepAlive, 52 | }; 53 | requestOptions.signal = controller.signal; 54 | 55 | let retries = 0; 56 | while (retries < retryTimes) { 57 | try { 58 | const response = await fetch(url, requestOptions); 59 | if (response.ok && response.status === 200) { 60 | return true; 61 | } else { 62 | logger.error(`Request failed with status code ${response.status}`); 63 | } 64 | } catch (error) { 65 | logger.error(`Error during request: ${error}`); 66 | } finally { 67 | clearTimeout(timeoutId); 68 | retries++; 69 | } 70 | } 71 | logger.error(`Request failed after ${retryTimes} retries`); 72 | return false; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/provider/AnalyticsEventBuilder.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { v4 as uuidV4 } from 'uuid'; 5 | import { ClickstreamContext } from './ClickstreamContext'; 6 | import { Event } from './Event'; 7 | import { EventChecker } from './EventChecker'; 8 | import { BrowserInfo } from '../browser'; 9 | import config from '../config'; 10 | import { Session } from '../tracker'; 11 | import { 12 | AnalyticsEvent, 13 | ClickstreamAttribute, 14 | ClickstreamEvent, 15 | Item, 16 | UserAttribute, 17 | } from '../types'; 18 | import { StorageUtil } from '../util/StorageUtil'; 19 | 20 | const sdkVersion = config.sdkVersion; 21 | 22 | export class AnalyticsEventBuilder { 23 | static createEvent( 24 | context: ClickstreamContext, 25 | event: ClickstreamEvent, 26 | userAttributes: UserAttribute, 27 | globalAttributes = {}, 28 | session?: Session 29 | ): AnalyticsEvent { 30 | const { browserInfo, configuration } = context; 31 | const attributes = this.getEventAttributesWithCheck( 32 | event.attributes, 33 | globalAttributes 34 | ); 35 | if (session !== undefined) { 36 | attributes[Event.ReservedAttribute.SESSION_ID] = session.sessionId; 37 | attributes[Event.ReservedAttribute.SESSION_START_TIMESTAMP] = 38 | session.startTime; 39 | attributes[Event.ReservedAttribute.SESSION_DURATION] = 40 | session.getDuration(); 41 | attributes[Event.ReservedAttribute.SESSION_NUMBER] = session.sessionIndex; 42 | } 43 | attributes[Event.ReservedAttribute.PAGE_TITLE] = 44 | BrowserInfo.getCurrentPageTitle(); 45 | attributes[Event.ReservedAttribute.PAGE_URL] = 46 | BrowserInfo.getCurrentPageUrl(); 47 | attributes[Event.ReservedAttribute.LATEST_REFERRER] = 48 | browserInfo.latestReferrer; 49 | attributes[Event.ReservedAttribute.LATEST_REFERRER_HOST] = 50 | browserInfo.latestReferrerHost; 51 | 52 | const items = this.getEventItemsWithCheck(event.items, attributes); 53 | return { 54 | event_type: event.name, 55 | event_id: uuidV4(), 56 | device_id: StorageUtil.getDeviceId(), 57 | unique_id: context.userUniqueId, 58 | app_id: configuration.appId, 59 | timestamp: new Date().getTime(), 60 | host_name: browserInfo.hostName, 61 | locale: browserInfo.locale, 62 | system_language: browserInfo.system_language, 63 | country_code: browserInfo.country_code, 64 | zone_offset: browserInfo.zoneOffset, 65 | make: browserInfo.make, 66 | platform: 'Web', 67 | screen_height: window.screen.height, 68 | screen_width: window.screen.width, 69 | viewport_height: window.innerHeight, 70 | viewport_width: window.innerWidth, 71 | sdk_name: 'aws-solution-clickstream-sdk', 72 | sdk_version: sdkVersion, 73 | items: items, 74 | user: userAttributes ?? {}, 75 | attributes: attributes, 76 | }; 77 | } 78 | 79 | static getEventAttributesWithCheck( 80 | eventAttributes: ClickstreamAttribute, 81 | globalAttributes = {} 82 | ): ClickstreamAttribute { 83 | const customAttributes: ClickstreamAttribute = {}; 84 | const { checkAttributes } = EventChecker; 85 | const globalAttributesLength = Object.keys(globalAttributes).length; 86 | for (const key in eventAttributes) { 87 | const value = eventAttributes[key]; 88 | if (value !== null) { 89 | const currentNumber = 90 | Object.keys(customAttributes).length + globalAttributesLength; 91 | const result = checkAttributes(currentNumber, key, value); 92 | const { ERROR_CODE, ERROR_MESSAGE } = Event.ReservedAttribute; 93 | if (result.error_code > 0) { 94 | customAttributes[ERROR_CODE] = result.error_code; 95 | customAttributes[ERROR_MESSAGE] = result.error_message; 96 | } else { 97 | customAttributes[key] = value; 98 | } 99 | } 100 | } 101 | return Object.assign(customAttributes, globalAttributes); 102 | } 103 | 104 | static getEventItemsWithCheck( 105 | items: Item[], 106 | attributes: ClickstreamAttribute 107 | ): Item[] { 108 | let resultItems = undefined; 109 | if (items !== undefined) { 110 | resultItems = []; 111 | const { checkItems } = EventChecker; 112 | for (const item of items) { 113 | const result = checkItems(resultItems.length, item); 114 | const { ERROR_CODE, ERROR_MESSAGE } = Event.ReservedAttribute; 115 | if (result.error_code > 0) { 116 | attributes[ERROR_CODE] = result.error_code; 117 | attributes[ERROR_MESSAGE] = result.error_message; 118 | } 119 | if (result.error_code === Event.ErrorCode.NO_ERROR) { 120 | resultItems.push(item); 121 | } 122 | } 123 | } 124 | return resultItems; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/provider/ClickstreamContext.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { BrowserInfo } from '../browser'; 5 | import { ClickstreamConfiguration } from '../types'; 6 | import { StorageUtil } from '../util/StorageUtil'; 7 | 8 | export class ClickstreamContext { 9 | browserInfo: BrowserInfo; 10 | configuration: ClickstreamConfiguration; 11 | userUniqueId: string; 12 | 13 | constructor( 14 | browserInfo: BrowserInfo, 15 | configuration: ClickstreamConfiguration 16 | ) { 17 | this.browserInfo = browserInfo; 18 | this.configuration = configuration; 19 | this.userUniqueId = StorageUtil.getCurrentUserUniqueId(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/provider/ClickstreamProvider.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { ConsoleLogger as Logger } from '@aws-amplify/core'; 5 | import { LOG_TYPE } from '@aws-amplify/core/lib/Logger'; 6 | import { AnalyticsEventBuilder } from './AnalyticsEventBuilder'; 7 | import { ClickstreamContext } from './ClickstreamContext'; 8 | import { Event } from './Event'; 9 | import { EventChecker } from './EventChecker'; 10 | import { EventRecorder } from './EventRecorder'; 11 | import { BrowserInfo } from '../browser'; 12 | import { PageViewTracker, SessionTracker } from '../tracker'; 13 | import { ClickTracker } from '../tracker/ClickTracker'; 14 | import { PageLoadTracker } from '../tracker/PageLoadTracker'; 15 | import { ScrollTracker } from '../tracker/ScrollTracker'; 16 | import { 17 | AnalyticsEvent, 18 | AnalyticsProvider, 19 | ClickstreamAttribute, 20 | ClickstreamConfiguration, 21 | ClickstreamEvent, 22 | Configuration, 23 | EventError, 24 | PageType, 25 | SendMode, 26 | UserAttribute, 27 | } from '../types'; 28 | import { StorageUtil } from '../util/StorageUtil'; 29 | 30 | const logger = new Logger('ClickstreamProvider'); 31 | 32 | export class ClickstreamProvider implements AnalyticsProvider { 33 | configuration: ClickstreamConfiguration; 34 | eventRecorder: EventRecorder; 35 | userAttributes: UserAttribute; 36 | globalAttributes: ClickstreamAttribute; 37 | context: ClickstreamContext; 38 | sessionTracker: SessionTracker; 39 | pageViewTracker: PageViewTracker; 40 | clickTracker: ClickTracker; 41 | scrollTracker: ScrollTracker; 42 | pageLoadTracker: PageLoadTracker; 43 | 44 | constructor() { 45 | this.configuration = { 46 | appId: '', 47 | endpoint: '', 48 | sendMode: SendMode.Immediate, 49 | sendEventsInterval: 5000, 50 | isTrackPageViewEvents: true, 51 | isTrackUserEngagementEvents: true, 52 | isTrackClickEvents: true, 53 | isTrackSearchEvents: true, 54 | isTrackScrollEvents: true, 55 | isTrackPageLoadEvents: false, 56 | isTrackAppStartEvents: false, 57 | isTrackAppEndEvents: false, 58 | pageType: PageType.SPA, 59 | isLogEvents: false, 60 | sessionTimeoutDuration: 1800000, 61 | idleTimeoutDuration: 120000, 62 | searchKeyWords: [], 63 | domainList: [], 64 | globalAttributes: {}, 65 | }; 66 | } 67 | 68 | configure(configuration: ClickstreamConfiguration): object { 69 | if (configuration.appId === '' || configuration.endpoint === '') { 70 | logger.error('Please configure your appId and endpoint'); 71 | return configuration; 72 | } 73 | Object.assign(this.configuration, configuration); 74 | this.context = new ClickstreamContext( 75 | new BrowserInfo(), 76 | this.configuration 77 | ); 78 | this.eventRecorder = new EventRecorder(this.context); 79 | this.globalAttributes = {}; 80 | this.setGlobalAttributes(configuration.globalAttributes); 81 | this.userAttributes = StorageUtil.getSimpleUserAttributes(); 82 | this.sessionTracker = new SessionTracker(this, this.context); 83 | this.pageViewTracker = new PageViewTracker(this, this.context); 84 | this.clickTracker = new ClickTracker(this, this.context); 85 | this.scrollTracker = new ScrollTracker(this, this.context); 86 | this.pageLoadTracker = new PageLoadTracker(this, this.context); 87 | this.sessionTracker.setUp(); 88 | this.pageViewTracker.setUp(); 89 | this.clickTracker.setUp(); 90 | this.scrollTracker.setUp(); 91 | this.pageLoadTracker.setUp(); 92 | if (configuration.sendMode === SendMode.Batch) { 93 | this.startTimer(); 94 | } 95 | if (this.context.configuration.isLogEvents) { 96 | logger.level = LOG_TYPE.DEBUG; 97 | } 98 | logger.debug( 99 | 'Initialize the SDK successfully, configuration is:\n' + 100 | JSON.stringify(this.configuration) 101 | ); 102 | if (this.eventRecorder.getFailedEventsLength() > 0) { 103 | this.eventRecorder.haveFailedEvents = true; 104 | this.eventRecorder.sendFailedEvents(); 105 | } 106 | return this.configuration; 107 | } 108 | 109 | updateConfigure(configuration: Configuration) { 110 | Object.assign(this.configuration, configuration); 111 | } 112 | 113 | getCategory(): string { 114 | return 'Analytics'; 115 | } 116 | 117 | getProviderName(): string { 118 | return 'ClickstreamProvider'; 119 | } 120 | 121 | record(event: ClickstreamEvent) { 122 | const result = EventChecker.checkEventName(event.name); 123 | if (result.error_code > 0) { 124 | logger.error(result.error_message); 125 | this.recordClickstreamError(result); 126 | return; 127 | } 128 | const resultEvent = this.createEvent(event); 129 | this.recordEvent(resultEvent, event.isImmediate); 130 | } 131 | 132 | createEvent( 133 | event: ClickstreamEvent, 134 | allUserAttributes: UserAttribute = null 135 | ) { 136 | return AnalyticsEventBuilder.createEvent( 137 | this.context, 138 | event, 139 | allUserAttributes === null ? this.userAttributes : allUserAttributes, 140 | this.globalAttributes, 141 | this.sessionTracker.session 142 | ); 143 | } 144 | 145 | recordEvent(event: AnalyticsEvent, isImmediate = false) { 146 | this.eventRecorder.record(event, isImmediate); 147 | } 148 | 149 | setUserId(userId: string | null) { 150 | let previousUserId = ''; 151 | if (Event.ReservedAttribute.USER_ID in this.userAttributes) { 152 | previousUserId = 153 | this.userAttributes[Event.ReservedAttribute.USER_ID].value.toString(); 154 | } 155 | if (userId === null) { 156 | delete this.userAttributes[Event.ReservedAttribute.USER_ID]; 157 | } else if (userId !== previousUserId) { 158 | const userInfo = StorageUtil.getUserInfoFromMapping(userId); 159 | const newUserAttribute: UserAttribute = {}; 160 | newUserAttribute[Event.ReservedAttribute.USER_ID] = { 161 | value: userId, 162 | set_timestamp: new Date().getTime(), 163 | }; 164 | newUserAttribute[Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP] = 165 | userInfo[Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP]; 166 | StorageUtil.updateUserAttributes(newUserAttribute); 167 | this.userAttributes = newUserAttribute; 168 | this.context.userUniqueId = StorageUtil.getCurrentUserUniqueId(); 169 | } 170 | this.recordProfileSet(this.userAttributes); 171 | StorageUtil.updateUserAttributes(this.userAttributes); 172 | } 173 | 174 | setUserAttributes(attributes: ClickstreamAttribute) { 175 | const timestamp = new Date().getTime(); 176 | const allUserAttributes = StorageUtil.getAllUserAttributes(); 177 | for (const key in attributes) { 178 | const value = attributes[key]; 179 | if (value === null) { 180 | delete allUserAttributes[key]; 181 | } else { 182 | const currentNumber = Object.keys(allUserAttributes).length; 183 | const { checkUserAttribute } = EventChecker; 184 | const result = checkUserAttribute(currentNumber, key, value); 185 | if (result.error_code > 0) { 186 | this.recordClickstreamError(result); 187 | } else { 188 | allUserAttributes[key] = { 189 | value: value, 190 | set_timestamp: timestamp, 191 | }; 192 | } 193 | } 194 | } 195 | StorageUtil.updateUserAttributes(allUserAttributes); 196 | this.recordProfileSet(allUserAttributes); 197 | } 198 | 199 | setGlobalAttributes(attributes: ClickstreamAttribute) { 200 | for (const key in attributes) { 201 | const value = attributes[key]; 202 | if (value === null) { 203 | delete this.globalAttributes[key]; 204 | } else { 205 | const currentNumber = Object.keys(this.globalAttributes).length; 206 | const { checkAttributes } = EventChecker; 207 | const result = checkAttributes(currentNumber, key, value); 208 | if (result.error_code > 0) { 209 | this.recordClickstreamError(result); 210 | } else { 211 | this.globalAttributes[key] = value; 212 | } 213 | } 214 | } 215 | } 216 | 217 | recordClickstreamError(error: EventError) { 218 | const { ERROR_CODE, ERROR_MESSAGE } = Event.ReservedAttribute; 219 | const errorEvent = this.createEvent({ 220 | name: Event.PresetEvent.CLICKSTREAM_ERROR, 221 | attributes: { 222 | [ERROR_CODE]: error.error_code, 223 | [ERROR_MESSAGE]: error.error_message, 224 | }, 225 | }); 226 | this.recordEvent(errorEvent); 227 | } 228 | 229 | recordProfileSet(allUserAttributes: UserAttribute) { 230 | const profileSetEvent = this.createEvent( 231 | { name: Event.PresetEvent.PROFILE_SET }, 232 | allUserAttributes 233 | ); 234 | this.recordEvent(profileSetEvent); 235 | } 236 | 237 | startTimer() { 238 | setInterval( 239 | this.flushEvents.bind(this, this.eventRecorder), 240 | this.configuration.sendEventsInterval 241 | ); 242 | } 243 | 244 | flushEvents(eventRecorder: EventRecorder) { 245 | eventRecorder.flushEvents(); 246 | } 247 | 248 | sendEventsInBackground(isWindowClosing: boolean) { 249 | if ( 250 | !(BrowserInfo.isFirefox() && isWindowClosing) && 251 | BrowserInfo.isNetworkOnLine() 252 | ) { 253 | this.eventRecorder.sendEventsInBackground(isWindowClosing); 254 | } 255 | } 256 | } 257 | -------------------------------------------------------------------------------- /src/provider/Event.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export class Event { 5 | static readonly Limit = { 6 | MAX_EVENT_TYPE_LENGTH: 50, 7 | MAX_NUM_OF_ATTRIBUTES: 500, 8 | MAX_NUM_OF_USER_ATTRIBUTES: 100, 9 | MAX_LENGTH_OF_NAME: 50, 10 | MAX_LENGTH_OF_VALUE: 1024, 11 | MAX_LENGTH_OF_USER_VALUE: 256, 12 | MAX_EVENT_NUMBER_OF_BATCH: 100, 13 | MAX_LENGTH_OF_ERROR_VALUE: 256, 14 | MAX_NUM_OF_ITEMS: 100, 15 | MAX_LENGTH_OF_ITEM_VALUE: 256, 16 | MAX_NUM_OF_CUSTOM_ITEM_ATTRIBUTE: 10, 17 | }; 18 | 19 | static readonly ErrorCode = { 20 | NO_ERROR: 0, 21 | EVENT_NAME_INVALID: 1001, 22 | EVENT_NAME_LENGTH_EXCEED: 1002, 23 | ATTRIBUTE_NAME_LENGTH_EXCEED: 2001, 24 | ATTRIBUTE_NAME_INVALID: 2002, 25 | ATTRIBUTE_VALUE_LENGTH_EXCEED: 2003, 26 | ATTRIBUTE_SIZE_EXCEED: 2004, 27 | USER_ATTRIBUTE_SIZE_EXCEED: 3001, 28 | USER_ATTRIBUTE_NAME_LENGTH_EXCEED: 3002, 29 | USER_ATTRIBUTE_NAME_INVALID: 3003, 30 | USER_ATTRIBUTE_VALUE_LENGTH_EXCEED: 3004, 31 | ITEM_SIZE_EXCEED: 4001, 32 | ITEM_VALUE_LENGTH_EXCEED: 4002, 33 | ITEM_CUSTOM_ATTRIBUTE_SIZE_EXCEED: 4003, 34 | ITEM_CUSTOM_ATTRIBUTE_KEY_LENGTH_EXCEED: 4004, 35 | ITEM_CUSTOM_ATTRIBUTE_KEY_INVALID: 4005, 36 | }; 37 | 38 | static readonly ReservedAttribute = { 39 | USER_ID: '_user_id', 40 | USER_FIRST_TOUCH_TIMESTAMP: '_user_first_touch_timestamp', 41 | ERROR_CODE: '_error_code', 42 | ERROR_MESSAGE: '_error_message', 43 | IS_FIRST_TIME: '_is_first_time', 44 | ENGAGEMENT_TIMESTAMP: '_engagement_time_msec', 45 | PAGE_URL: '_page_url', 46 | PAGE_TITLE: '_page_title', 47 | PAGE_REFERRER: '_page_referrer', 48 | PAGE_REFERRER_TITLE: '_page_referrer_title', 49 | LATEST_REFERRER: '_latest_referrer', 50 | LATEST_REFERRER_HOST: '_latest_referrer_host', 51 | PREVIOUS_TIMESTAMP: '_previous_timestamp', 52 | ENTRANCES: '_entrances', 53 | SESSION_ID: '_session_id', 54 | SESSION_DURATION: '_session_duration', 55 | SESSION_NUMBER: '_session_number', 56 | SESSION_START_TIMESTAMP: '_session_start_timestamp', 57 | LINK_CLASSES: '_link_classes', 58 | LINK_DOMAIN: '_link_domain', 59 | LINK_ID: '_link_id', 60 | LINK_URL: '_link_url', 61 | OUTBOUND: '_outbound', 62 | SEARCH_KEY: '_search_key', 63 | SEARCH_TERM: '_search_term', 64 | TIMING_ATTRIBUTES: [ 65 | 'duration', 66 | 'deliveryType', 67 | 'nextHopProtocol', 68 | 'renderBlockingStatus', 69 | 'startTime', 70 | 'redirectStart', 71 | 'redirectEnd', 72 | 'workerStart', 73 | 'fetchStart', 74 | 'domainLookupStart', 75 | 'domainLookupEnd', 76 | 'connectStart', 77 | 'secureConnectionStart', 78 | 'connectEnd', 79 | 'requestStart', 80 | 'firstInterimResponseStart', 81 | 'responseStart', 82 | 'responseEnd', 83 | 'transferSize', 84 | 'encodedBodySize', 85 | 'decodedBodySize', 86 | 'responseStatus', 87 | 'unloadEventStart', 88 | 'unloadEventEnd', 89 | 'domInteractive', 90 | 'domContentLoadedEventStart', 91 | 'domContentLoadedEventEnd', 92 | 'domComplete', 93 | 'loadEventStart', 94 | 'loadEventEnd', 95 | 'type', 96 | 'redirectCount', 97 | 'activationStart', 98 | 'criticalCHRestart', 99 | 'serverTiming', 100 | ], 101 | }; 102 | 103 | static readonly PresetEvent = { 104 | FIRST_OPEN: '_first_open', 105 | APP_START: '_app_start', 106 | APP_END: '_app_end', 107 | PROFILE_SET: '_profile_set', 108 | CLICKSTREAM_ERROR: '_clickstream_error', 109 | SESSION_START: '_session_start', 110 | USER_ENGAGEMENT: '_user_engagement', 111 | PAGE_VIEW: '_page_view', 112 | CLICK: '_click', 113 | SEARCH: '_search', 114 | SCROLL: '_scroll', 115 | PAGE_LOAD: '_page_load', 116 | }; 117 | 118 | static readonly Constants = { 119 | PREFIX: '[', 120 | SUFFIX: ']', 121 | LAST_EVENT_IDENTIFIER: '},{"event_type":', 122 | KEYWORDS: ['q', 's', 'search', 'query', 'keyword'], 123 | }; 124 | } 125 | -------------------------------------------------------------------------------- /src/provider/EventChecker.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { ConsoleLogger as Logger } from '@aws-amplify/core'; 5 | import { Event } from './Event'; 6 | import { EventError, Item } from '../types'; 7 | 8 | const logger = new Logger('ClickstreamProvider'); 9 | 10 | export class EventChecker { 11 | static itemKeySet: Set; 12 | 13 | static checkEventName(eventName: string): EventError { 14 | const { EVENT_NAME_INVALID, EVENT_NAME_LENGTH_EXCEED, NO_ERROR } = 15 | Event.ErrorCode; 16 | const { MAX_EVENT_TYPE_LENGTH } = Event.Limit; 17 | if (!EventChecker.isValidName(eventName)) { 18 | return { 19 | error_code: EVENT_NAME_INVALID, 20 | error_message: 21 | `Event name can only contains uppercase and lowercase letters, ` + 22 | `underscores, number, and is not start with a number. event name: ${eventName}`, 23 | }; 24 | } else if (eventName.length > MAX_EVENT_TYPE_LENGTH) { 25 | return { 26 | error_code: EVENT_NAME_LENGTH_EXCEED, 27 | error_message: 28 | `Event name is too long, the max event type length is ` + 29 | `${MAX_EVENT_TYPE_LENGTH} characters. event name: ${eventName}`, 30 | }; 31 | } 32 | return { 33 | error_code: NO_ERROR, 34 | }; 35 | } 36 | 37 | static isValidName(name: string): boolean { 38 | const regex = /^(?![0-9])[0-9a-zA-Z_]+$/; 39 | return regex.test(name); 40 | } 41 | 42 | static checkAttributes( 43 | currentNumber: number, 44 | key: string, 45 | value: string | number | boolean 46 | ): EventError { 47 | const { MAX_NUM_OF_ATTRIBUTES, MAX_LENGTH_OF_NAME, MAX_LENGTH_OF_VALUE } = 48 | Event.Limit; 49 | const { 50 | NO_ERROR, 51 | ATTRIBUTE_SIZE_EXCEED, 52 | ATTRIBUTE_NAME_INVALID, 53 | ATTRIBUTE_NAME_LENGTH_EXCEED, 54 | ATTRIBUTE_VALUE_LENGTH_EXCEED, 55 | } = Event.ErrorCode; 56 | let error: EventError; 57 | let errorMsg; 58 | if (currentNumber >= MAX_NUM_OF_ATTRIBUTES) { 59 | errorMsg = 60 | `reached the max number of attributes limit ${MAX_NUM_OF_ATTRIBUTES}. ` + 61 | `and the attribute: ${key} will not be recorded`; 62 | const errorString = `attribute name: ${key}`; 63 | error = { 64 | error_message: EventChecker.getLimitString(errorString), 65 | error_code: ATTRIBUTE_SIZE_EXCEED, 66 | }; 67 | } else if (key.length > MAX_LENGTH_OF_NAME) { 68 | errorMsg = 69 | `attribute : ${key}, reached the max length of attributes name ` + 70 | `limit(${MAX_LENGTH_OF_NAME}). current length is: (${key.length}) ` + 71 | `and the attribute will not be recorded`; 72 | const errorString = `attribute name length is: (${key.length}) name is: ${key}`; 73 | error = { 74 | error_message: EventChecker.getLimitString(errorString), 75 | error_code: ATTRIBUTE_NAME_LENGTH_EXCEED, 76 | }; 77 | } else if (!EventChecker.isValidName(key)) { 78 | errorMsg = 79 | `attribute : ${key}, was not valid, attribute name can only ` + 80 | `contains uppercase and lowercase letters, underscores, number, and is not ` + 81 | `start with a number, so the attribute will not be recorded`; 82 | error = { 83 | error_message: EventChecker.getLimitString(key), 84 | error_code: ATTRIBUTE_NAME_INVALID, 85 | }; 86 | } else if (String(value).length > MAX_LENGTH_OF_VALUE) { 87 | errorMsg = 88 | `attribute : ${key}, reached the max length of attributes value limit ` + 89 | `(${MAX_LENGTH_OF_VALUE}). current length is: (${ 90 | String(value).length 91 | }). ` + 92 | `and the attribute will not be recorded, attribute value: ${value}`; 93 | const errorString = `attribute name: ${key}, attribute value: ${value}`; 94 | error = { 95 | error_message: EventChecker.getLimitString(errorString), 96 | error_code: ATTRIBUTE_VALUE_LENGTH_EXCEED, 97 | }; 98 | } 99 | if (error) { 100 | logger.warn(errorMsg); 101 | return error; 102 | } 103 | return { 104 | error_code: NO_ERROR, 105 | }; 106 | } 107 | 108 | static getLimitString(str: string): string { 109 | return str.substring(0, Event.Limit.MAX_LENGTH_OF_ERROR_VALUE); 110 | } 111 | 112 | static checkUserAttribute( 113 | currentNumber: number, 114 | key: string, 115 | value: string | number | boolean 116 | ): EventError { 117 | const { 118 | MAX_NUM_OF_USER_ATTRIBUTES, 119 | MAX_LENGTH_OF_NAME, 120 | MAX_LENGTH_OF_USER_VALUE, 121 | } = Event.Limit; 122 | const { 123 | NO_ERROR, 124 | USER_ATTRIBUTE_SIZE_EXCEED, 125 | USER_ATTRIBUTE_NAME_LENGTH_EXCEED, 126 | USER_ATTRIBUTE_NAME_INVALID, 127 | USER_ATTRIBUTE_VALUE_LENGTH_EXCEED, 128 | } = Event.ErrorCode; 129 | let error: EventError; 130 | let errorMsg; 131 | if (currentNumber >= MAX_NUM_OF_USER_ATTRIBUTES) { 132 | errorMsg = 133 | `reached the max number of user attributes limit (${MAX_NUM_OF_USER_ATTRIBUTES}). ` + 134 | `and the user attribute: ${key} will not be recorded`; 135 | const errorString = `attribute name:${key}`; 136 | error = { 137 | error_message: EventChecker.getLimitString(errorString), 138 | error_code: USER_ATTRIBUTE_SIZE_EXCEED, 139 | }; 140 | } else if (key.length > MAX_LENGTH_OF_NAME) { 141 | errorMsg = 142 | `user attribute : ${key}, reached the max length of attributes name limit ` + 143 | `(${MAX_LENGTH_OF_NAME}). current length is: (${key.length}) ` + 144 | `and the attribute will not be recorded`; 145 | const errorString = `user attribute name length is: (${key.length}) name is: ${key}`; 146 | error = { 147 | error_message: EventChecker.getLimitString(errorString), 148 | error_code: USER_ATTRIBUTE_NAME_LENGTH_EXCEED, 149 | }; 150 | } else if (!EventChecker.isValidName(key)) { 151 | errorMsg = 152 | `user attribute : ${key}, was not valid, user attribute name can only ` + 153 | `contains uppercase and lowercase letters, underscores, number, and is not ` + 154 | `start with a number. so the attribute will not be recorded`; 155 | error = { 156 | error_message: EventChecker.getLimitString(key), 157 | error_code: USER_ATTRIBUTE_NAME_INVALID, 158 | }; 159 | } else if (String(value).length > MAX_LENGTH_OF_USER_VALUE) { 160 | errorMsg = 161 | `user attribute : ${key}, reached the max length of attributes value limit ` + 162 | `(${MAX_LENGTH_OF_USER_VALUE}). current length is: (${ 163 | String(value).length 164 | }). ` + 165 | `and the attribute will not be recorded, attribute value: ${value}`; 166 | const errorString = `attribute name: ${key}, attribute value: ${value}`; 167 | error = { 168 | error_message: EventChecker.getLimitString(errorString), 169 | error_code: USER_ATTRIBUTE_VALUE_LENGTH_EXCEED, 170 | }; 171 | } 172 | if (error) { 173 | logger.warn(errorMsg); 174 | return error; 175 | } 176 | return { 177 | error_code: NO_ERROR, 178 | }; 179 | } 180 | 181 | static checkItems(currentNumber: number, item: Item): EventError { 182 | if (EventChecker.itemKeySet === undefined) { 183 | EventChecker.initItemKeySet(); 184 | } 185 | const { 186 | MAX_NUM_OF_ITEMS, 187 | MAX_LENGTH_OF_ITEM_VALUE, 188 | MAX_NUM_OF_CUSTOM_ITEM_ATTRIBUTE, 189 | MAX_LENGTH_OF_NAME, 190 | } = Event.Limit; 191 | const { 192 | NO_ERROR, 193 | ITEM_SIZE_EXCEED, 194 | ITEM_VALUE_LENGTH_EXCEED, 195 | ITEM_CUSTOM_ATTRIBUTE_SIZE_EXCEED, 196 | ITEM_CUSTOM_ATTRIBUTE_KEY_LENGTH_EXCEED, 197 | ITEM_CUSTOM_ATTRIBUTE_KEY_INVALID, 198 | } = Event.ErrorCode; 199 | const itemKey = JSON.stringify(item); 200 | if (currentNumber >= MAX_NUM_OF_ITEMS) { 201 | const errorMsg = 202 | `reached the max number of items limit ${MAX_NUM_OF_ITEMS}. ` + 203 | `and the item: ${itemKey} will not be recorded`; 204 | logger.warn(errorMsg); 205 | const errorString = `item: ${itemKey}`; 206 | return { 207 | error_message: EventChecker.getLimitString(errorString), 208 | error_code: ITEM_SIZE_EXCEED, 209 | }; 210 | } 211 | let customKeyNumber = 0; 212 | let errorMsg; 213 | let error: EventError; 214 | for (const [key, value] of Object.entries(item)) { 215 | const valueStr = String(value); 216 | if (!EventChecker.itemKeySet.has(key)) { 217 | customKeyNumber += 1; 218 | if (customKeyNumber > MAX_NUM_OF_CUSTOM_ITEM_ATTRIBUTE) { 219 | errorMsg = 220 | `reached the max number of custom item attributes limit (${MAX_NUM_OF_CUSTOM_ITEM_ATTRIBUTE}` + 221 | `). and the item: ${itemKey} will not be recorded`; 222 | const errorString = `item attribute key: ${key}`; 223 | error = { 224 | error_message: EventChecker.getLimitString(errorString), 225 | error_code: ITEM_CUSTOM_ATTRIBUTE_SIZE_EXCEED, 226 | }; 227 | } else if (key.length > Event.Limit.MAX_LENGTH_OF_NAME) { 228 | errorMsg = 229 | `item attribute key: ${key} , reached the max length of item attributes key limit(` + 230 | `${MAX_LENGTH_OF_NAME}). current length is:(${key.length}) and the item: ${itemKey} will not be recorded`; 231 | const errorString = 'item attribute key: ' + key; 232 | error = { 233 | error_message: EventChecker.getLimitString(errorString), 234 | error_code: ITEM_CUSTOM_ATTRIBUTE_KEY_LENGTH_EXCEED, 235 | }; 236 | } else if (!EventChecker.isValidName(key)) { 237 | errorMsg = 238 | `item attribute key: ${key}, was not valid, item attribute key can only contains` + 239 | ' uppercase and lowercase letters, underscores, number, and is not start with a number.' + 240 | ` so the item: ${itemKey} will not be recorded`; 241 | error = { 242 | error_message: EventChecker.getLimitString(key), 243 | error_code: ITEM_CUSTOM_ATTRIBUTE_KEY_INVALID, 244 | }; 245 | } 246 | } 247 | if (!error && valueStr.length > MAX_LENGTH_OF_ITEM_VALUE) { 248 | errorMsg = 249 | `item attribute : ${key}, reached the max length of item attribute value limit ` + 250 | `(${MAX_LENGTH_OF_ITEM_VALUE}). current length is: (${valueStr.length}). ` + 251 | `and the item: ${itemKey} will not be recorded`; 252 | const errorString = `item attribute name: ${key}, item attribute value: ${valueStr}`; 253 | error = { 254 | error_message: EventChecker.getLimitString(errorString), 255 | error_code: ITEM_VALUE_LENGTH_EXCEED, 256 | }; 257 | } 258 | if (error) { 259 | logger.warn(errorMsg); 260 | return error; 261 | } 262 | } 263 | return { 264 | error_code: NO_ERROR, 265 | }; 266 | } 267 | 268 | static initItemKeySet() { 269 | EventChecker.itemKeySet = new Set(); 270 | EventChecker.itemKeySet.add('id'); 271 | EventChecker.itemKeySet.add('name'); 272 | EventChecker.itemKeySet.add('location_id'); 273 | EventChecker.itemKeySet.add('brand'); 274 | EventChecker.itemKeySet.add('currency'); 275 | EventChecker.itemKeySet.add('price'); 276 | EventChecker.itemKeySet.add('quantity'); 277 | EventChecker.itemKeySet.add('creative_name'); 278 | EventChecker.itemKeySet.add('creative_slot'); 279 | EventChecker.itemKeySet.add('category'); 280 | EventChecker.itemKeySet.add('category2'); 281 | EventChecker.itemKeySet.add('category3'); 282 | EventChecker.itemKeySet.add('category4'); 283 | EventChecker.itemKeySet.add('category5'); 284 | } 285 | } 286 | -------------------------------------------------------------------------------- /src/provider/EventRecorder.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { ConsoleLogger as Logger } from '@aws-amplify/core'; 5 | import { LOG_TYPE } from '@aws-amplify/core/lib/Logger'; 6 | import { ClickstreamContext } from './ClickstreamContext'; 7 | import { Event } from './Event'; 8 | import { NetRequest } from '../network/NetRequest'; 9 | import { AnalyticsEvent, SendMode } from '../types'; 10 | import { StorageUtil } from '../util/StorageUtil'; 11 | 12 | const logger = new Logger('EventRecorder'); 13 | 14 | export class EventRecorder { 15 | context: ClickstreamContext; 16 | bundleSequenceId: number; 17 | isFlushingEvents: boolean; 18 | isSendingFailedEvents: boolean; 19 | haveFailedEvents: boolean; 20 | 21 | constructor(context: ClickstreamContext) { 22 | this.context = context; 23 | this.bundleSequenceId = StorageUtil.getBundleSequenceId(); 24 | } 25 | 26 | record(event: AnalyticsEvent, isImmediate = false) { 27 | if (this.context.configuration.isLogEvents) { 28 | logger.level = LOG_TYPE.DEBUG; 29 | logger.debug(`Logged event ${event.event_type}\n`, event); 30 | } 31 | const currentMode = this.context.configuration.sendMode; 32 | if (currentMode === SendMode.Immediate || isImmediate) { 33 | this.sendEventImmediate(event); 34 | } else { 35 | if (!StorageUtil.saveEvent(event)) { 36 | this.sendEventImmediate(event); 37 | } 38 | } 39 | } 40 | 41 | sendEventImmediate(event: AnalyticsEvent) { 42 | const eventsJson = JSON.stringify([event]); 43 | NetRequest.sendRequest( 44 | eventsJson, 45 | this.context, 46 | this.bundleSequenceId 47 | ).then(result => { 48 | if (result) { 49 | logger.debug('Event send success'); 50 | if (this.haveFailedEvents) { 51 | this.sendFailedEvents(); 52 | } 53 | } else { 54 | StorageUtil.saveFailedEvent(event); 55 | this.haveFailedEvents = true; 56 | } 57 | }); 58 | this.plusSequenceId(); 59 | } 60 | 61 | sendFailedEvents() { 62 | if (this.isSendingFailedEvents) return; 63 | this.isSendingFailedEvents = true; 64 | const failedEvents = StorageUtil.getFailedEvents(); 65 | if (failedEvents.length > 0) { 66 | const eventsJson = failedEvents + Event.Constants.SUFFIX; 67 | NetRequest.sendRequest( 68 | eventsJson, 69 | this.context, 70 | this.bundleSequenceId 71 | ).then(result => { 72 | if (result) { 73 | logger.debug('Failed events send success'); 74 | StorageUtil.clearFailedEvents(); 75 | this.haveFailedEvents = false; 76 | } 77 | this.isSendingFailedEvents = false; 78 | }); 79 | this.plusSequenceId(); 80 | } 81 | } 82 | 83 | flushEvents() { 84 | if (this.isFlushingEvents) { 85 | return; 86 | } 87 | const [eventsJson, needsFlushTwice] = this.getBatchEvents(); 88 | if (eventsJson === '') { 89 | return; 90 | } 91 | this.isFlushingEvents = true; 92 | NetRequest.sendRequest( 93 | eventsJson, 94 | this.context, 95 | this.bundleSequenceId, 96 | NetRequest.BATCH_REQUEST_RETRY_TIMES, 97 | NetRequest.BATCH_REQUEST_TIMEOUT 98 | ).then(result => { 99 | if (result) { 100 | StorageUtil.clearEvents(eventsJson); 101 | } 102 | this.isFlushingEvents = false; 103 | if (result && needsFlushTwice) { 104 | this.flushEvents(); 105 | } 106 | }); 107 | this.plusSequenceId(); 108 | } 109 | 110 | getBatchEvents(): [string, boolean] { 111 | let allEventsStr = StorageUtil.getAllEvents(); 112 | if (allEventsStr === '') { 113 | return [allEventsStr, false]; 114 | } else if (allEventsStr.length <= StorageUtil.MAX_REQUEST_EVENTS_SIZE) { 115 | return [allEventsStr + Event.Constants.SUFFIX, false]; 116 | } else { 117 | const isOnlyOneEvent = 118 | allEventsStr.lastIndexOf(Event.Constants.LAST_EVENT_IDENTIFIER) < 0; 119 | const firstEventSize = allEventsStr.indexOf( 120 | Event.Constants.LAST_EVENT_IDENTIFIER 121 | ); 122 | if (isOnlyOneEvent) { 123 | return [allEventsStr + Event.Constants.SUFFIX, false]; 124 | } else if (firstEventSize > StorageUtil.MAX_REQUEST_EVENTS_SIZE) { 125 | allEventsStr = allEventsStr.substring(0, firstEventSize + 1); 126 | return [allEventsStr + Event.Constants.SUFFIX, true]; 127 | } else { 128 | allEventsStr = allEventsStr.substring( 129 | 0, 130 | StorageUtil.MAX_REQUEST_EVENTS_SIZE 131 | ); 132 | const endIndex = allEventsStr.lastIndexOf( 133 | Event.Constants.LAST_EVENT_IDENTIFIER 134 | ); 135 | return [ 136 | allEventsStr.substring(0, endIndex + 1) + Event.Constants.SUFFIX, 137 | true, 138 | ]; 139 | } 140 | } 141 | } 142 | 143 | plusSequenceId() { 144 | this.bundleSequenceId += 1; 145 | StorageUtil.saveBundleSequenceId(this.bundleSequenceId); 146 | } 147 | 148 | sendEventsInBackground(isWindowClosing: boolean) { 149 | if ( 150 | this.haveFailedEvents && 151 | this.getFailedEventsLength() < NetRequest.KEEP_ALIVE_SIZE_LIMIT 152 | ) { 153 | this.sendFailedEvents(); 154 | if (isWindowClosing) { 155 | StorageUtil.clearFailedEvents(); 156 | } 157 | } 158 | if (this.context.configuration.sendMode === SendMode.Batch) { 159 | const eventLength = this.getEventsLength(); 160 | if (eventLength > 0 && eventLength < NetRequest.KEEP_ALIVE_SIZE_LIMIT) { 161 | this.flushEvents(); 162 | if (isWindowClosing) { 163 | StorageUtil.clearAllEvents(); 164 | } 165 | } 166 | } 167 | } 168 | 169 | getFailedEventsLength(): number { 170 | const failedEvents = StorageUtil.getFailedEvents(); 171 | return new Blob([failedEvents]).size; 172 | } 173 | 174 | getEventsLength(): number { 175 | const events = StorageUtil.getAllEvents(); 176 | return new Blob([events]).size; 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /src/provider/index.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export { AnalyticsEventBuilder } from './AnalyticsEventBuilder'; 5 | export { ClickstreamContext } from './ClickstreamContext'; 6 | export { ClickstreamProvider } from './ClickstreamProvider'; 7 | export { EventRecorder } from './EventRecorder'; 8 | export { Event } from './Event'; 9 | export { EventChecker } from './EventChecker'; 10 | -------------------------------------------------------------------------------- /src/tracker/BaseTracker.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { Logger } from '@aws-amplify/core'; 5 | import { BrowserInfo } from '../browser'; 6 | import { ClickstreamContext, ClickstreamProvider } from '../provider'; 7 | 8 | const logger = new Logger('BaseTracker'); 9 | 10 | export abstract class BaseTracker { 11 | provider: ClickstreamProvider; 12 | context: ClickstreamContext; 13 | 14 | constructor(provider: ClickstreamProvider, context: ClickstreamContext) { 15 | this.provider = provider; 16 | this.context = context; 17 | } 18 | 19 | setUp() { 20 | if ( 21 | !BrowserInfo.isBrowser() || 22 | !document.addEventListener || 23 | !window.addEventListener || 24 | !history.pushState 25 | ) { 26 | logger.warn('not in the supported web environment'); 27 | } else { 28 | this.init(); 29 | } 30 | } 31 | 32 | abstract init(): void; 33 | } 34 | -------------------------------------------------------------------------------- /src/tracker/ClickTracker.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { Logger } from '@aws-amplify/core'; 5 | import { BaseTracker } from './BaseTracker'; 6 | import { PageViewTracker } from './PageViewTracker'; 7 | import { Event } from '../provider'; 8 | 9 | const logger = new Logger('ClickTracker'); 10 | 11 | export class ClickTracker extends BaseTracker { 12 | processedElements = new WeakSet(); 13 | 14 | init() { 15 | this.trackClick = this.trackClick.bind(this); 16 | this.trackDocumentClick = this.trackDocumentClick.bind(this); 17 | document.addEventListener('click', this.trackDocumentClick); 18 | const currentDomain = window.location.host; 19 | const domainList = this.context.configuration.domainList; 20 | if (!domainList.includes(currentDomain)) { 21 | domainList.push(currentDomain); 22 | } 23 | this.addClickListenerForATag(); 24 | } 25 | 26 | trackDocumentClick(event: MouseEvent) { 27 | PageViewTracker.updateIdleDuration(); 28 | if (!this.context.configuration.isTrackClickEvents) return; 29 | const targetElement = event.target as Element; 30 | const element = this.findATag(targetElement); 31 | if (!element || this.processedElements.has(element)) return; 32 | this.trackClick(event, element); 33 | } 34 | 35 | trackClick( 36 | event: MouseEvent, 37 | documentElement: Element | undefined = undefined 38 | ) { 39 | if (!this.context.configuration.isTrackClickEvents) return; 40 | let element = documentElement; 41 | if (!element) { 42 | const targetElement = event.target as Element; 43 | element = this.findATag(targetElement); 44 | } 45 | if (element !== null) { 46 | const linkUrl = element.getAttribute('href'); 47 | if (linkUrl === null || linkUrl.length === 0) return; 48 | let linkDomain = ''; 49 | try { 50 | const url = new URL(linkUrl); 51 | linkDomain = url.host; 52 | } catch (error) { 53 | logger.debug('parse link domain failed: ' + error); 54 | } 55 | if (linkDomain === '') return; 56 | const linkClasses = element.getAttribute('class'); 57 | const linkId = element.getAttribute('id'); 58 | const outbound = 59 | !this.context.configuration.domainList.includes(linkDomain); 60 | this.provider.record({ 61 | name: Event.PresetEvent.CLICK, 62 | attributes: { 63 | [Event.ReservedAttribute.LINK_URL]: linkUrl, 64 | [Event.ReservedAttribute.LINK_DOMAIN]: linkDomain, 65 | [Event.ReservedAttribute.LINK_CLASSES]: linkClasses, 66 | [Event.ReservedAttribute.LINK_ID]: linkId, 67 | [Event.ReservedAttribute.OUTBOUND]: outbound, 68 | }, 69 | }); 70 | } 71 | } 72 | 73 | addClickListenerForATag() { 74 | const observer = new MutationObserver(mutationsList => { 75 | for (const mutation of mutationsList) { 76 | if (mutation.type === 'childList' && mutation.addedNodes.length > 0) { 77 | const target = mutation.target; 78 | if (target instanceof Element) { 79 | const aTags = target.querySelectorAll('a'); 80 | aTags.forEach(aTag => { 81 | if (!this.processedElements.has(aTags)) { 82 | aTag.addEventListener('click', this.trackClick); 83 | this.processedElements.add(aTag); 84 | } 85 | }); 86 | } 87 | } 88 | } 89 | }); 90 | observer.observe(document.documentElement, { 91 | childList: true, 92 | subtree: true, 93 | }); 94 | } 95 | 96 | findATag(element: Element, depth = 0): Element { 97 | if (element && depth < 3) { 98 | if (element.tagName === 'A') { 99 | return element; 100 | } else { 101 | depth += 1; 102 | return this.findATag(element.parentElement, depth); 103 | } 104 | } 105 | return null; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/tracker/PageLoadTracker.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { BaseTracker } from './BaseTracker'; 5 | import { Event } from '../provider'; 6 | import { ClickstreamAttribute } from '../types'; 7 | 8 | export class PageLoadTracker extends BaseTracker { 9 | observer: PerformanceObserver; 10 | 11 | init() { 12 | this.trackPageLoad = this.trackPageLoad.bind(this); 13 | if (this.isSupportedEnv()) { 14 | this.observer = new PerformanceObserver(() => { 15 | this.trackPageLoad(); 16 | }); 17 | this.observer.observe({ entryTypes: ['navigation'] }); 18 | } 19 | if (this.isPageLoaded()) { 20 | this.trackPageLoad(); 21 | } 22 | } 23 | 24 | trackPageLoad() { 25 | if (!this.context.configuration.isTrackPageLoadEvents) return; 26 | const performanceEntries = performance.getEntriesByType('navigation'); 27 | if (performanceEntries && performanceEntries.length > 0) { 28 | const latestPerformance = 29 | performanceEntries[performanceEntries.length - 1]; 30 | const eventAttributes: ClickstreamAttribute = {}; 31 | for (const key in latestPerformance) { 32 | const value = (latestPerformance as any)[key]; 33 | const valueType = typeof value; 34 | if (Event.ReservedAttribute.TIMING_ATTRIBUTES.includes(key)) { 35 | if (valueType === 'string' || valueType === 'number') { 36 | eventAttributes[key] = value; 37 | } else if (Array.isArray(value) && value.length > 0) { 38 | eventAttributes[key] = JSON.stringify(value); 39 | } 40 | } 41 | } 42 | this.provider.record({ 43 | name: Event.PresetEvent.PAGE_LOAD, 44 | attributes: eventAttributes, 45 | }); 46 | } 47 | } 48 | 49 | isPageLoaded() { 50 | const performanceEntries = performance.getEntriesByType('navigation'); 51 | return performanceEntries?.[0]?.duration > 0 || false; 52 | } 53 | 54 | isSupportedEnv(): boolean { 55 | return !!performance && !!PerformanceObserver; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/tracker/PageViewTracker.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { BaseTracker } from './BaseTracker'; 5 | import { BrowserInfo } from '../browser'; 6 | import { ClickstreamContext, ClickstreamProvider, Event } from '../provider'; 7 | import { PageType } from '../types'; 8 | import { MethodEmbed } from '../util/MethodEmbed'; 9 | import { StorageUtil } from '../util/StorageUtil'; 10 | 11 | export class PageViewTracker extends BaseTracker { 12 | provider: ClickstreamProvider; 13 | context: ClickstreamContext; 14 | isEntrances = false; 15 | searchKeywords = Event.Constants.KEYWORDS; 16 | lastEngageTime = 0; 17 | lastScreenStartTimestamp = 0; 18 | isFirstTime = true; 19 | static lastActiveTimestamp = 0; 20 | static idleDuration = 0; 21 | private static idleTimeoutDuration = 0; 22 | 23 | init() { 24 | PageViewTracker.lastActiveTimestamp = new Date().getTime(); 25 | PageViewTracker.idleTimeoutDuration = 26 | this.provider.configuration.idleTimeoutDuration; 27 | const configuredSearchKeywords = this.provider.configuration.searchKeyWords; 28 | Object.assign(this.searchKeywords, configuredSearchKeywords); 29 | this.onPageChange = this.onPageChange.bind(this); 30 | if (this.isMultiPageApp()) { 31 | if (!BrowserInfo.isFromReload()) { 32 | this.onPageChange(); 33 | } 34 | } else { 35 | this.trackPageViewForSPA(); 36 | } 37 | this.isFirstTime = false; 38 | } 39 | 40 | trackPageViewForSPA() { 41 | MethodEmbed.add(history, 'pushState', this.onPageChange); 42 | MethodEmbed.add(history, 'replaceState', this.onPageChange); 43 | window.addEventListener('popstate', this.onPageChange); 44 | if (!BrowserInfo.isFromReload()) { 45 | this.onPageChange(); 46 | } 47 | } 48 | 49 | onPageChange() { 50 | PageViewTracker.updateIdleDuration(); 51 | if (this.context.configuration.isTrackPageViewEvents) { 52 | const previousPageUrl = StorageUtil.getPreviousPageUrl(); 53 | const previousPageTitle = StorageUtil.getPreviousPageTitle(); 54 | const currentPageUrl = BrowserInfo.getCurrentPageUrl(); 55 | const currentPageTitle = BrowserInfo.getCurrentPageTitle(); 56 | if ( 57 | this.isFirstTime || 58 | this.isMultiPageApp() || 59 | previousPageUrl !== currentPageUrl || 60 | previousPageTitle !== currentPageTitle 61 | ) { 62 | this.provider.scrollTracker?.enterNewPage(); 63 | if ( 64 | !this.isMultiPageApp() && 65 | !this.isFirstTime && 66 | previousPageUrl !== '' 67 | ) { 68 | this.recordUserEngagement(); 69 | } 70 | this.trackPageView(previousPageUrl, previousPageTitle); 71 | this.trackSearchEvents(); 72 | 73 | StorageUtil.savePreviousPageUrl(currentPageUrl); 74 | StorageUtil.savePreviousPageTitle(currentPageTitle); 75 | } 76 | } 77 | } 78 | 79 | trackPageView(previousPageUrl: string, previousPageTitle: string) { 80 | const previousPageStartTime = StorageUtil.getPreviousPageStartTime(); 81 | const analyticsEvent = this.provider.createEvent({ 82 | name: Event.PresetEvent.PAGE_VIEW, 83 | }); 84 | const currentPageStartTime = analyticsEvent.timestamp; 85 | 86 | const eventAttributes = { 87 | [Event.ReservedAttribute.PAGE_REFERRER]: previousPageUrl, 88 | [Event.ReservedAttribute.PAGE_REFERRER_TITLE]: previousPageTitle, 89 | [Event.ReservedAttribute.ENTRANCES]: this.isEntrances ? 1 : 0, 90 | }; 91 | if (previousPageStartTime > 0) { 92 | eventAttributes[Event.ReservedAttribute.PREVIOUS_TIMESTAMP] = 93 | previousPageStartTime; 94 | } 95 | if (this.lastEngageTime > 0) { 96 | eventAttributes[Event.ReservedAttribute.ENGAGEMENT_TIMESTAMP] = 97 | this.lastEngageTime; 98 | } 99 | Object.assign(analyticsEvent.attributes, eventAttributes); 100 | this.provider.recordEvent(analyticsEvent); 101 | 102 | this.isEntrances = false; 103 | 104 | StorageUtil.savePreviousPageStartTime(currentPageStartTime); 105 | this.lastScreenStartTimestamp = currentPageStartTime; 106 | } 107 | 108 | setIsEntrances() { 109 | this.isEntrances = true; 110 | } 111 | 112 | updateLastScreenStartTimestamp() { 113 | this.lastScreenStartTimestamp = new Date().getTime(); 114 | PageViewTracker.idleDuration = 0; 115 | PageViewTracker.lastActiveTimestamp = this.lastScreenStartTimestamp; 116 | } 117 | 118 | recordUserEngagement(isImmediate = false) { 119 | this.lastEngageTime = this.getLastEngageTime(); 120 | if ( 121 | this.provider.configuration.isTrackUserEngagementEvents && 122 | this.lastEngageTime > Constants.minEngagementTime 123 | ) { 124 | this.provider.record({ 125 | name: Event.PresetEvent.USER_ENGAGEMENT, 126 | attributes: { 127 | [Event.ReservedAttribute.ENGAGEMENT_TIMESTAMP]: this.lastEngageTime, 128 | }, 129 | isImmediate: isImmediate, 130 | }); 131 | } 132 | } 133 | 134 | getLastEngageTime() { 135 | const duration = new Date().getTime() - this.lastScreenStartTimestamp; 136 | const engageTime = duration - PageViewTracker.idleDuration; 137 | PageViewTracker.idleDuration = 0; 138 | return engageTime; 139 | } 140 | 141 | isMultiPageApp() { 142 | return this.context.configuration.pageType === PageType.multiPageApp; 143 | } 144 | 145 | trackSearchEvents() { 146 | if (!this.context.configuration.isTrackSearchEvents) return; 147 | const searchStr = window.location.search; 148 | if (!searchStr || searchStr.length === 0) return; 149 | const urlParams = new URLSearchParams(searchStr); 150 | for (const keyword of this.searchKeywords) { 151 | if (urlParams.has(keyword)) { 152 | const searchTerm = urlParams.get(keyword); 153 | this.provider.record({ 154 | name: Event.PresetEvent.SEARCH, 155 | attributes: { 156 | [Event.ReservedAttribute.SEARCH_KEY]: keyword, 157 | [Event.ReservedAttribute.SEARCH_TERM]: searchTerm, 158 | }, 159 | }); 160 | break; 161 | } 162 | } 163 | } 164 | 165 | static updateIdleDuration() { 166 | const currentTimestamp = new Date().getTime(); 167 | const idleDuration = currentTimestamp - PageViewTracker.lastActiveTimestamp; 168 | if (idleDuration > PageViewTracker.idleTimeoutDuration) { 169 | PageViewTracker.idleDuration += idleDuration; 170 | } 171 | PageViewTracker.lastActiveTimestamp = currentTimestamp; 172 | } 173 | } 174 | 175 | export enum Constants { 176 | minEngagementTime = 1000, 177 | } 178 | -------------------------------------------------------------------------------- /src/tracker/ScrollTracker.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { BaseTracker } from './BaseTracker'; 5 | import { PageViewTracker } from './PageViewTracker'; 6 | import { Event } from '../provider'; 7 | import { StorageUtil } from '../util/StorageUtil'; 8 | 9 | export class ScrollTracker extends BaseTracker { 10 | isFirstTime: boolean; 11 | 12 | init() { 13 | this.trackScroll = this.trackScroll.bind(this); 14 | const throttledTrackScroll = this.throttle(this.trackScroll, 100); 15 | document.addEventListener('scroll', throttledTrackScroll, { 16 | passive: true, 17 | }); 18 | const throttledMouseMove = this.throttle(this.onMouseMove, 100); 19 | document.addEventListener('mousemove', throttledMouseMove, { 20 | passive: true, 21 | }); 22 | this.isFirstTime = true; 23 | } 24 | 25 | enterNewPage() { 26 | this.isFirstTime = true; 27 | } 28 | 29 | trackScroll() { 30 | PageViewTracker.updateIdleDuration(); 31 | if (!this.context.configuration.isTrackScrollEvents) return; 32 | const scrollY = window.scrollY || document.documentElement.scrollTop; 33 | const ninetyPercentHeight = document.body.scrollHeight * 0.9; 34 | const viewedHeight = scrollY + window.innerHeight; 35 | if (scrollY > 0 && viewedHeight > ninetyPercentHeight && this.isFirstTime) { 36 | const engagementTime = 37 | new Date().getTime() - StorageUtil.getPreviousPageStartTime(); 38 | this.provider.record({ 39 | name: Event.PresetEvent.SCROLL, 40 | attributes: { 41 | [Event.ReservedAttribute.ENGAGEMENT_TIMESTAMP]: engagementTime, 42 | }, 43 | }); 44 | this.isFirstTime = false; 45 | } 46 | } 47 | 48 | onMouseMove() { 49 | PageViewTracker.updateIdleDuration(); 50 | } 51 | 52 | throttle(func: (...args: any[]) => void, delay: number) { 53 | let timeout: ReturnType | null = null; 54 | return function (this: any, ...args: any[]) { 55 | if (!timeout) { 56 | timeout = setTimeout(() => { 57 | func.apply(this, args); 58 | timeout = null; 59 | }, delay); 60 | } 61 | }; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/tracker/Session.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { ClickstreamContext } from '../provider'; 5 | import { StorageUtil } from '../util/StorageUtil'; 6 | 7 | export class Session { 8 | sessionId: string; 9 | startTime: number; 10 | sessionIndex: number; 11 | pauseTime: number; 12 | isRecorded = false; 13 | 14 | static createSession(uniqueId: string, sessionIndex: number): Session { 15 | return new Session( 16 | this.getSessionId(uniqueId), 17 | sessionIndex, 18 | new Date().getTime() 19 | ); 20 | } 21 | 22 | constructor( 23 | sessionId: string, 24 | sessionIndex: number, 25 | startTime: number, 26 | pauseTime: number = undefined 27 | ) { 28 | this.sessionId = sessionId; 29 | this.sessionIndex = sessionIndex; 30 | this.startTime = startTime; 31 | this.pauseTime = pauseTime; 32 | } 33 | 34 | isNewSession(): boolean { 35 | return this.pauseTime === undefined && !this.isRecorded; 36 | } 37 | 38 | getDuration(): number { 39 | return new Date().getTime() - this.startTime; 40 | } 41 | 42 | pause() { 43 | this.pauseTime = new Date().getTime(); 44 | } 45 | 46 | static getCurrentSession( 47 | context: ClickstreamContext, 48 | previousSession: Session = null 49 | ): Session { 50 | let session = previousSession; 51 | if (previousSession === null) { 52 | session = StorageUtil.getSession(); 53 | } 54 | if (session !== null) { 55 | if ( 56 | session.pauseTime === undefined || 57 | new Date().getTime() - session.pauseTime < 58 | context.configuration.sessionTimeoutDuration 59 | ) { 60 | return session; 61 | } else { 62 | return Session.createSession( 63 | context.userUniqueId, 64 | session.sessionIndex + 1 65 | ); 66 | } 67 | } else { 68 | return Session.createSession(context.userUniqueId, 1); 69 | } 70 | } 71 | 72 | private static getSessionId(uniqueId: string): string { 73 | const uniqueIdKey = uniqueId.slice(-Constants.maxUniqueIdLength); 74 | return `${uniqueIdKey}-${this.getFormatTime()}`; 75 | } 76 | 77 | private static getFormatTime() { 78 | const now = new Date(); 79 | const year = now.getUTCFullYear().toString().padStart(4, '0'); 80 | const month = (now.getUTCMonth() + 1).toString().padStart(2, '0'); 81 | const day = now.getUTCDate().toString().padStart(2, '0'); 82 | const hours = now.getUTCHours().toString().padStart(2, '0'); 83 | const minutes = now.getUTCMinutes().toString().padStart(2, '0'); 84 | const seconds = now.getUTCSeconds().toString().padStart(2, '0'); 85 | const milliseconds = now.getUTCMilliseconds().toString().padStart(3, '0'); 86 | return `${year}${month}${day}-${hours}${minutes}${seconds}${milliseconds}`; 87 | } 88 | } 89 | 90 | enum Constants { 91 | maxUniqueIdLength = 8, 92 | } 93 | -------------------------------------------------------------------------------- /src/tracker/SessionTracker.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { Logger } from '@aws-amplify/core'; 5 | import { BaseTracker } from './BaseTracker'; 6 | import { PageViewTracker } from './PageViewTracker'; 7 | import { Session } from './Session'; 8 | import { BrowserInfo } from '../browser'; 9 | import { Event } from '../provider'; 10 | import { StorageUtil } from '../util/StorageUtil'; 11 | 12 | const logger = new Logger('SessionTracker'); 13 | 14 | export class SessionTracker extends BaseTracker { 15 | hiddenStr: string; 16 | visibilityChange: string; 17 | session: Session; 18 | isWindowClosing = false; 19 | 20 | init() { 21 | this.onVisibilityChange = this.onVisibilityChange.bind(this); 22 | this.onBeforeUnload = this.onBeforeUnload.bind(this); 23 | 24 | this.handleInit(); 25 | if (!this.checkEnv()) { 26 | logger.warn('not supported env'); 27 | } else { 28 | document.addEventListener( 29 | this.visibilityChange, 30 | this.onVisibilityChange, 31 | false 32 | ); 33 | window.addEventListener('beforeunload', this.onBeforeUnload, false); 34 | } 35 | } 36 | 37 | onVisibilityChange() { 38 | if (document.visibilityState === this.hiddenStr) { 39 | this.onPageHide(); 40 | } else { 41 | this.onPageAppear(); 42 | } 43 | } 44 | 45 | handleInit() { 46 | this.session = Session.getCurrentSession(this.context); 47 | if (StorageUtil.getIsFirstOpen()) { 48 | this.provider.record({ 49 | name: Event.PresetEvent.FIRST_OPEN, 50 | }); 51 | StorageUtil.saveIsFirstOpenToFalse(); 52 | } 53 | this.onPageAppear(true); 54 | } 55 | 56 | onPageAppear(isFirstTime = false) { 57 | logger.debug('page appear'); 58 | const pageViewTracker = this.provider.pageViewTracker; 59 | pageViewTracker.updateLastScreenStartTimestamp(); 60 | if (!isFirstTime) { 61 | this.session = Session.getCurrentSession(this.context, this.session); 62 | } 63 | if (this.session.isNewSession()) { 64 | pageViewTracker.setIsEntrances(); 65 | StorageUtil.clearPageInfo(); 66 | this.provider.record({ name: Event.PresetEvent.SESSION_START }); 67 | this.session.isRecorded = true; 68 | if (!isFirstTime) { 69 | pageViewTracker.onPageChange(); 70 | } 71 | } 72 | if (!this.provider.configuration.isTrackAppStartEvents) return; 73 | if (isFirstTime && this.isFromCurrentHost()) return; 74 | if (isFirstTime && BrowserInfo.isFromReload()) return; 75 | this.provider.record({ 76 | name: Event.PresetEvent.APP_START, 77 | attributes: { 78 | [Event.ReservedAttribute.IS_FIRST_TIME]: isFirstTime, 79 | }, 80 | }); 81 | } 82 | 83 | isFromCurrentHost() { 84 | return window.location.host === this.context.browserInfo.latestReferrerHost; 85 | } 86 | 87 | onPageHide() { 88 | logger.debug('page hide'); 89 | this.storeSession(); 90 | StorageUtil.checkClickstreamId(); 91 | const isImmediate = !(this.isWindowClosing && BrowserInfo.isFirefox()); 92 | this.recordUserEngagement(isImmediate); 93 | this.recordAppEnd(isImmediate); 94 | this.provider.sendEventsInBackground(this.isWindowClosing); 95 | } 96 | 97 | recordUserEngagement(isImmediate: boolean) { 98 | PageViewTracker.updateIdleDuration(); 99 | this.provider.pageViewTracker.recordUserEngagement(isImmediate); 100 | } 101 | 102 | recordAppEnd(isImmediate: boolean) { 103 | if (!this.provider.configuration.isTrackAppEndEvents) return; 104 | this.provider.record({ 105 | name: Event.PresetEvent.APP_END, 106 | isImmediate: isImmediate, 107 | }); 108 | } 109 | 110 | onBeforeUnload() { 111 | logger.debug('onBeforeUnload'); 112 | this.isWindowClosing = true; 113 | } 114 | 115 | storeSession() { 116 | this.session.pause(); 117 | StorageUtil.saveSession(this.session); 118 | } 119 | 120 | checkEnv(): boolean { 121 | if (!document || !document.addEventListener) { 122 | logger.debug('not in the supported web environment'); 123 | return false; 124 | } 125 | if (typeof document.hidden !== 'undefined') { 126 | this.hiddenStr = 'hidden'; 127 | this.visibilityChange = 'visibilitychange'; 128 | } else if (typeof (document as any).msHidden !== 'undefined') { 129 | this.hiddenStr = 'msHidden'; 130 | this.visibilityChange = 'msvisibilitychange'; 131 | } else if (typeof (document as any).webkitHidden !== 'undefined') { 132 | this.hiddenStr = 'webkitHidden'; 133 | this.visibilityChange = 'webkitvisibilitychange'; 134 | } else { 135 | logger.debug('not in the supported web environment'); 136 | return false; 137 | } 138 | return true; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/tracker/index.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export { SessionTracker } from './SessionTracker'; 5 | export { Session } from './Session'; 6 | export { PageViewTracker } from './PageViewTracker'; 7 | -------------------------------------------------------------------------------- /src/types/Analytics.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export interface ClickstreamConfiguration extends Configuration { 5 | readonly appId: string; 6 | readonly endpoint: string; 7 | readonly sendMode?: SendMode; 8 | readonly sendEventsInterval?: number; 9 | readonly pageType?: PageType; 10 | readonly sessionTimeoutDuration?: number; 11 | readonly idleTimeoutDuration?: number; 12 | readonly searchKeyWords?: string[]; 13 | readonly domainList?: string[]; 14 | readonly globalAttributes?: ClickstreamAttribute; 15 | } 16 | 17 | export interface Configuration { 18 | isLogEvents?: boolean; 19 | authCookie?: string; 20 | isTrackPageViewEvents?: boolean; 21 | isTrackUserEngagementEvents?: boolean; 22 | isTrackClickEvents?: boolean; 23 | isTrackScrollEvents?: boolean; 24 | isTrackSearchEvents?: boolean; 25 | isTrackPageLoadEvents?: boolean; 26 | isTrackAppStartEvents?: boolean; 27 | isTrackAppEndEvents?: boolean; 28 | } 29 | 30 | export enum SendMode { 31 | Immediate = 'Immediate', 32 | Batch = 'Batch', 33 | } 34 | 35 | export enum PageType { 36 | SPA = 'SPA', 37 | multiPageApp = 'multiPageApp', 38 | } 39 | 40 | export enum Attr { 41 | TRAFFIC_SOURCE_SOURCE = '_traffic_source_source', 42 | TRAFFIC_SOURCE_MEDIUM = '_traffic_source_medium', 43 | TRAFFIC_SOURCE_CAMPAIGN = '_traffic_source_campaign', 44 | TRAFFIC_SOURCE_CAMPAIGN_ID = '_traffic_source_campaign_id', 45 | TRAFFIC_SOURCE_TERM = '_traffic_source_term', 46 | TRAFFIC_SOURCE_CONTENT = '_traffic_source_content', 47 | TRAFFIC_SOURCE_CLID = '_traffic_source_clid', 48 | TRAFFIC_SOURCE_CLID_PLATFORM = '_traffic_source_clid_platform', 49 | VALUE = '_value', 50 | CURRENCY = '_currency', 51 | } 52 | 53 | export interface ClickstreamAttribute { 54 | [Attr.TRAFFIC_SOURCE_SOURCE]?: string; 55 | [Attr.TRAFFIC_SOURCE_MEDIUM]?: string; 56 | [Attr.TRAFFIC_SOURCE_CAMPAIGN]?: string; 57 | [Attr.TRAFFIC_SOURCE_CAMPAIGN_ID]?: string; 58 | [Attr.TRAFFIC_SOURCE_TERM]?: string; 59 | [Attr.TRAFFIC_SOURCE_CONTENT]?: string; 60 | [Attr.TRAFFIC_SOURCE_CLID]?: string; 61 | [Attr.TRAFFIC_SOURCE_CLID_PLATFORM]?: string; 62 | [Attr.VALUE]?: number; 63 | [Attr.CURRENCY]?: string; 64 | 65 | [key: string]: string | number | boolean | null; 66 | } 67 | 68 | export interface UserAttributeObject { 69 | value: string | number | boolean; 70 | set_timestamp: number; 71 | } 72 | 73 | export interface UserAttribute { 74 | [key: string]: UserAttributeObject; 75 | } 76 | 77 | export interface Item { 78 | id?: string; 79 | name?: string; 80 | location_id?: string; 81 | brand?: string; 82 | currency?: string; 83 | price?: number; 84 | quantity?: number; 85 | creative_name?: string; 86 | creative_slot?: string; 87 | category?: string; 88 | category2?: string; 89 | category3?: string; 90 | category4?: string; 91 | category5?: string; 92 | 93 | [key: string]: string | number | boolean | null; 94 | } 95 | 96 | export interface ClickstreamEvent { 97 | name: string; 98 | attributes?: ClickstreamAttribute; 99 | items?: Item[]; 100 | isImmediate?: boolean; 101 | } 102 | 103 | export interface AnalyticsEvent { 104 | unique_id: string; 105 | event_type: string; 106 | event_id: string; 107 | timestamp: number; 108 | device_id: string; 109 | platform: string; 110 | make: string; 111 | locale: string; 112 | screen_height: number; 113 | screen_width: number; 114 | viewport_height: number; 115 | viewport_width: number; 116 | zone_offset: number; 117 | system_language: string; 118 | country_code: string; 119 | sdk_version: string; 120 | sdk_name: string; 121 | host_name: string; 122 | app_id: string; 123 | items: Item[]; 124 | user: UserAttribute; 125 | attributes: ClickstreamAttribute; 126 | } 127 | 128 | export interface EventError { 129 | error_code: number; 130 | error_message?: string; 131 | } 132 | -------------------------------------------------------------------------------- /src/types/Provider.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export interface AnalyticsProvider { 5 | // you need to implement those methods 6 | 7 | // configure your provider 8 | configure(config: object): object; 9 | 10 | // record events 11 | record(params: object): void; 12 | 13 | // return 'Analytics' 14 | getCategory(): string; 15 | 16 | // return the name of you provider 17 | getProviderName(): string; 18 | } 19 | -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export * from './Provider'; 5 | export * from './Analytics'; 6 | -------------------------------------------------------------------------------- /src/util/HashUtil.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { Sha256 } from '@aws-crypto/sha256-browser'; 5 | 6 | export class HashUtil { 7 | static async getHashCode(str: string): Promise { 8 | const hash = new Sha256(); 9 | hash.update(str); 10 | const result = await hash.digest(); 11 | return this.uint8ArrayToHexString(result).substring(0, 8); 12 | } 13 | 14 | private static uint8ArrayToHexString(array: Uint8Array): string { 15 | return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join( 16 | '' 17 | ); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/util/MethodEmbed.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export class MethodEmbed { 5 | public context; 6 | public methodName; 7 | private readonly originalMethod; 8 | 9 | static add(context: any, methodName: string, methodOverride: any) { 10 | new MethodEmbed(context, methodName).set(methodOverride); 11 | } 12 | 13 | constructor(context: any, methodName: string) { 14 | this.context = context; 15 | this.methodName = methodName; 16 | 17 | this.originalMethod = context[methodName].bind(context); 18 | } 19 | 20 | public set(methodOverride: any) { 21 | this.context[this.methodName] = (...args: any) => { 22 | return methodOverride(this.originalMethod(...args)); 23 | }; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/util/StorageUtil.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { ConsoleLogger as Logger } from '@aws-amplify/core'; 5 | import { v4 as uuidV4 } from 'uuid'; 6 | import { Event } from '../provider'; 7 | import { Session } from '../tracker'; 8 | import { AnalyticsEvent, UserAttribute } from '../types'; 9 | 10 | const logger = new Logger('StorageUtil'); 11 | 12 | export class StorageUtil { 13 | static readonly MAX_REQUEST_EVENTS_SIZE = 1024 * 512; 14 | static readonly MAX_FAILED_EVENTS_SIZE = this.MAX_REQUEST_EVENTS_SIZE; 15 | static readonly MAX_BATCH_EVENTS_SIZE = 1024 * 1024; 16 | 17 | static readonly prefix = 'aws-solution/clickstream-web/'; 18 | static readonly deviceIdKey = this.prefix + 'deviceIdKey'; 19 | static readonly userUniqueIdKey = this.prefix + 'userUniqueIdKey'; 20 | static readonly bundleSequenceIdKey = this.prefix + 'bundleSequenceIdKey'; 21 | static readonly userAttributesKey = this.prefix + 'userAttributesKey'; 22 | static readonly userFirstTouchTimestampKey = 23 | this.prefix + 'userFirstTouchTimestampKey'; 24 | static readonly failedEventsKey = this.prefix + 'failedEventsKey'; 25 | static readonly eventsKey = this.prefix + 'eventsKey'; 26 | static readonly sessionKey = this.prefix + 'sessionKey'; 27 | static readonly isFirstOpenKey = this.prefix + 'isFirstOpenKey'; 28 | static readonly previousPageUrlKey = this.prefix + 'previousPageUrlKey'; 29 | static readonly previousPageTitleKey = this.prefix + 'previousPageTitleKey'; 30 | static readonly previousPageStartTimeKey = 31 | this.prefix + 'previousPageStartTimeKey'; 32 | static readonly userIdMappingKey = this.prefix + 'userIdMappingKey'; 33 | private static deviceId = ''; 34 | private static userUniqueId = ''; 35 | 36 | static getDeviceId(): string { 37 | if (StorageUtil.deviceId !== '') { 38 | return StorageUtil.deviceId; 39 | } 40 | let deviceId = localStorage.getItem(StorageUtil.deviceIdKey); 41 | if (deviceId === null) { 42 | deviceId = uuidV4(); 43 | localStorage.setItem(StorageUtil.deviceIdKey, deviceId); 44 | } 45 | StorageUtil.deviceId = deviceId; 46 | return deviceId; 47 | } 48 | 49 | static setCurrentUserUniqueId(userUniqueId: string) { 50 | StorageUtil.userUniqueId = userUniqueId; 51 | localStorage.setItem(StorageUtil.userUniqueIdKey, userUniqueId); 52 | } 53 | 54 | static getCurrentUserUniqueId(): string { 55 | if (StorageUtil.userUniqueId !== '') { 56 | return StorageUtil.userUniqueId; 57 | } 58 | let userUniqueId = localStorage.getItem(StorageUtil.userUniqueIdKey); 59 | if (userUniqueId === null) { 60 | userUniqueId = uuidV4(); 61 | StorageUtil.setCurrentUserUniqueId(userUniqueId); 62 | localStorage.setItem(StorageUtil.userUniqueIdKey, userUniqueId); 63 | StorageUtil.saveUserFirstTouchTimestamp(); 64 | } 65 | StorageUtil.userUniqueId = userUniqueId; 66 | return userUniqueId; 67 | } 68 | 69 | static saveUserFirstTouchTimestamp() { 70 | const firstTouchTimestamp = new Date().getTime(); 71 | localStorage.setItem( 72 | StorageUtil.userFirstTouchTimestampKey, 73 | String(firstTouchTimestamp) 74 | ); 75 | StorageUtil.updateUserAttributes({ 76 | [Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP]: { 77 | value: firstTouchTimestamp, 78 | set_timestamp: firstTouchTimestamp, 79 | }, 80 | }); 81 | } 82 | 83 | static saveUserIdMapping(userIdMappingObject: string) { 84 | localStorage.setItem( 85 | StorageUtil.userIdMappingKey, 86 | JSON.stringify(userIdMappingObject) 87 | ); 88 | } 89 | 90 | static getUserIdMapping() { 91 | return JSON.parse(localStorage.getItem(StorageUtil.userIdMappingKey)); 92 | } 93 | 94 | static getUserInfoFromMapping(userId: string): UserAttribute { 95 | let userIdMapping = StorageUtil.getUserIdMapping(); 96 | let userInfo: UserAttribute; 97 | const timestamp = new Date().getTime(); 98 | if (userIdMapping === null) { 99 | userIdMapping = {}; 100 | userInfo = { 101 | user_uniqueId: { 102 | value: StorageUtil.getCurrentUserUniqueId(), 103 | set_timestamp: timestamp, 104 | }, 105 | [Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP]: 106 | StorageUtil.getAllUserAttributes()[ 107 | Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP 108 | ], 109 | }; 110 | } else if (userId in userIdMapping) { 111 | userInfo = userIdMapping[userId]; 112 | StorageUtil.setCurrentUserUniqueId( 113 | userInfo.user_uniqueId.value.toString() 114 | ); 115 | } else { 116 | const userUniqueId = uuidV4(); 117 | StorageUtil.setCurrentUserUniqueId(userUniqueId); 118 | userInfo = { 119 | user_uniqueId: { 120 | value: userUniqueId, 121 | set_timestamp: timestamp, 122 | }, 123 | [Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP]: { 124 | value: timestamp, 125 | set_timestamp: timestamp, 126 | }, 127 | }; 128 | } 129 | userIdMapping[userId] = userInfo; 130 | StorageUtil.saveUserIdMapping(userIdMapping); 131 | return userInfo; 132 | } 133 | 134 | static getBundleSequenceId(): number { 135 | return parseInt( 136 | localStorage.getItem(StorageUtil.bundleSequenceIdKey) ?? '1' 137 | ); 138 | } 139 | 140 | static saveBundleSequenceId(bundleSequenceId: number) { 141 | localStorage.setItem( 142 | StorageUtil.bundleSequenceIdKey, 143 | String(bundleSequenceId) 144 | ); 145 | } 146 | 147 | static updateUserAttributes(userAttributes: UserAttribute) { 148 | localStorage.setItem( 149 | StorageUtil.userAttributesKey, 150 | JSON.stringify(userAttributes) 151 | ); 152 | } 153 | 154 | static getAllUserAttributes(): UserAttribute { 155 | const userAttributes = 156 | localStorage.getItem(StorageUtil.userAttributesKey) ?? '{}'; 157 | return JSON.parse(userAttributes); 158 | } 159 | 160 | static getSimpleUserAttributes(): UserAttribute { 161 | const allUserAttributes = StorageUtil.getAllUserAttributes(); 162 | const simpleUserAttributes: UserAttribute = { 163 | [Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP]: 164 | allUserAttributes[Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP], 165 | }; 166 | if (allUserAttributes[Event.ReservedAttribute.USER_ID] !== undefined) { 167 | simpleUserAttributes[Event.ReservedAttribute.USER_ID] = 168 | allUserAttributes[Event.ReservedAttribute.USER_ID]; 169 | } 170 | return simpleUserAttributes; 171 | } 172 | 173 | static getFailedEvents(): string { 174 | return localStorage.getItem(StorageUtil.failedEventsKey) ?? ''; 175 | } 176 | 177 | static saveFailedEvent(event: AnalyticsEvent) { 178 | const { MAX_FAILED_EVENTS_SIZE } = StorageUtil; 179 | const allEvents = StorageUtil.getFailedEvents(); 180 | let eventsStr = ''; 181 | if (allEvents === '') { 182 | eventsStr = Event.Constants.PREFIX + JSON.stringify(event); 183 | } else { 184 | eventsStr = allEvents + ',' + JSON.stringify(event); 185 | } 186 | if (eventsStr.length <= MAX_FAILED_EVENTS_SIZE) { 187 | localStorage.setItem(StorageUtil.failedEventsKey, eventsStr); 188 | } else { 189 | const maxSize = MAX_FAILED_EVENTS_SIZE / 1024; 190 | logger.warn(`Failed events reached max cache size of ${maxSize}kb`); 191 | } 192 | } 193 | 194 | static clearFailedEvents() { 195 | localStorage.removeItem(StorageUtil.failedEventsKey); 196 | } 197 | 198 | static getAllEvents(): string { 199 | return localStorage.getItem(StorageUtil.eventsKey) ?? ''; 200 | } 201 | 202 | static saveEvent(event: AnalyticsEvent): boolean { 203 | const { MAX_BATCH_EVENTS_SIZE } = StorageUtil; 204 | const allEvents = StorageUtil.getAllEvents(); 205 | let eventsStr = ''; 206 | if (allEvents === '') { 207 | eventsStr = Event.Constants.PREFIX + JSON.stringify(event); 208 | } else { 209 | eventsStr = allEvents + ',' + JSON.stringify(event); 210 | } 211 | if (eventsStr.length <= MAX_BATCH_EVENTS_SIZE) { 212 | localStorage.setItem(StorageUtil.eventsKey, eventsStr); 213 | return true; 214 | } else { 215 | const maxSize = MAX_BATCH_EVENTS_SIZE / 1024; 216 | logger.warn(`Events reached max cache size of ${maxSize}kb`); 217 | return false; 218 | } 219 | } 220 | 221 | static clearEvents(eventsJson: string) { 222 | const eventsString = this.getAllEvents(); 223 | if (eventsString === '') return; 224 | const deletedEvents = JSON.parse(eventsJson); 225 | const allEvents = JSON.parse(this.getAllEvents() + Event.Constants.SUFFIX); 226 | if (allEvents.length > deletedEvents.length) { 227 | const leftEvents = allEvents.splice(deletedEvents.length); 228 | let leftEventsStr = JSON.stringify(leftEvents); 229 | leftEventsStr = leftEventsStr.substring(0, leftEventsStr.length - 1); 230 | localStorage.setItem(StorageUtil.eventsKey, leftEventsStr); 231 | } else { 232 | localStorage.removeItem(StorageUtil.eventsKey); 233 | } 234 | } 235 | 236 | static clearAllEvents() { 237 | localStorage.removeItem(StorageUtil.eventsKey); 238 | } 239 | 240 | static saveSession(session: Session) { 241 | localStorage.setItem(StorageUtil.sessionKey, JSON.stringify(session)); 242 | } 243 | 244 | static getSession(): Session { 245 | const sessionStr = localStorage.getItem(StorageUtil.sessionKey); 246 | if (sessionStr === null) { 247 | return null; 248 | } 249 | const sessionObject = JSON.parse(sessionStr); 250 | return new Session( 251 | sessionObject.sessionId, 252 | sessionObject.sessionIndex, 253 | sessionObject.startTime, 254 | sessionObject.pauseTime 255 | ); 256 | } 257 | 258 | static getIsFirstOpen(): boolean { 259 | return localStorage.getItem(StorageUtil.isFirstOpenKey) === null; 260 | } 261 | 262 | static saveIsFirstOpenToFalse() { 263 | localStorage.setItem(StorageUtil.isFirstOpenKey, '0'); 264 | } 265 | 266 | static clearPageInfo() { 267 | localStorage.setItem(StorageUtil.previousPageUrlKey, ''); 268 | localStorage.setItem(StorageUtil.previousPageTitleKey, ''); 269 | } 270 | 271 | static getPreviousPageUrl(): string { 272 | return localStorage.getItem(StorageUtil.previousPageUrlKey) ?? ''; 273 | } 274 | 275 | static savePreviousPageUrl(url: string) { 276 | localStorage.setItem(StorageUtil.previousPageUrlKey, url); 277 | } 278 | 279 | static getPreviousPageTitle(): string { 280 | return localStorage.getItem(StorageUtil.previousPageTitleKey) ?? ''; 281 | } 282 | 283 | static savePreviousPageTitle(title: string) { 284 | localStorage.setItem(StorageUtil.previousPageTitleKey, title); 285 | } 286 | 287 | static getPreviousPageStartTime(): number { 288 | const startTime = localStorage.getItem( 289 | StorageUtil.previousPageStartTimeKey 290 | ); 291 | if (startTime === null) { 292 | return 0; 293 | } else { 294 | return Number(startTime); 295 | } 296 | } 297 | 298 | static savePreviousPageStartTime(timestamp: number) { 299 | localStorage.setItem( 300 | StorageUtil.previousPageStartTimeKey, 301 | timestamp.toString() 302 | ); 303 | } 304 | 305 | static checkDeviceId() { 306 | const currentDeviceId = localStorage.getItem(StorageUtil.deviceIdKey) ?? ''; 307 | if (StorageUtil.deviceId !== '' && currentDeviceId === '') { 308 | localStorage.setItem(StorageUtil.deviceIdKey, StorageUtil.deviceId); 309 | } 310 | } 311 | 312 | static checkUserUniqueId() { 313 | const currentUserUniqueId = 314 | localStorage.getItem(StorageUtil.userUniqueIdKey) ?? ''; 315 | if (StorageUtil.userUniqueId !== '' && currentUserUniqueId === '') { 316 | localStorage.setItem( 317 | StorageUtil.userUniqueIdKey, 318 | StorageUtil.userUniqueId 319 | ); 320 | } 321 | } 322 | 323 | static checkIsFirstOpen() { 324 | if (StorageUtil.getIsFirstOpen()) { 325 | StorageUtil.saveIsFirstOpenToFalse(); 326 | } 327 | } 328 | 329 | static checkClickstreamId() { 330 | StorageUtil.checkDeviceId(); 331 | StorageUtil.checkUserUniqueId(); 332 | StorageUtil.checkIsFirstOpen(); 333 | } 334 | 335 | static clearAll() { 336 | localStorage.clear(); 337 | (StorageUtil as any).deviceid = ''; 338 | (StorageUtil as any).userUniqueId = ''; 339 | } 340 | } 341 | -------------------------------------------------------------------------------- /test/ClickstreamAnalytics.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { setUpBrowserPerformance } from './browser/BrowserUtil'; 5 | import { ClickstreamAnalytics, Item, SendMode, Attr } from '../src'; 6 | import { NetRequest } from '../src/network/NetRequest'; 7 | import { Event } from '../src/provider'; 8 | import { StorageUtil } from '../src/util/StorageUtil'; 9 | 10 | describe('ClickstreamAnalytics test', () => { 11 | beforeEach(() => { 12 | StorageUtil.clearAll(); 13 | const mockSendRequestSuccess = jest.fn().mockResolvedValue(true); 14 | jest 15 | .spyOn(NetRequest, 'sendRequest') 16 | .mockImplementation(mockSendRequestSuccess); 17 | setUpBrowserPerformance(); 18 | }); 19 | 20 | afterEach(() => { 21 | ClickstreamAnalytics['provider'] = undefined; 22 | jest.restoreAllMocks(); 23 | jest.clearAllMocks(); 24 | }); 25 | 26 | test('test init sdk', () => { 27 | const result = ClickstreamAnalytics.init({ 28 | appId: 'testApp', 29 | endpoint: 'https://example.com/collect', 30 | }); 31 | expect(result).toBeTruthy(); 32 | const result1 = ClickstreamAnalytics.init({ 33 | appId: 'testApp', 34 | endpoint: 'https://example.com/collect', 35 | }); 36 | expect(result1).toBeFalsy(); 37 | }); 38 | 39 | test('test init sdk with global attributes', async () => { 40 | const result = ClickstreamAnalytics.init({ 41 | appId: 'testApp', 42 | endpoint: 'https://example.com/collect', 43 | sendMode: SendMode.Batch, 44 | globalAttributes: { 45 | brand: 'Samsung', 46 | level: 10, 47 | }, 48 | }); 49 | ClickstreamAnalytics.setGlobalAttributes({ brand: null }); 50 | ClickstreamAnalytics.record({ 51 | name: 'testEvent', 52 | }); 53 | expect(result).toBeTruthy(); 54 | await sleep(100); 55 | const eventList = JSON.parse( 56 | StorageUtil.getAllEvents() + Event.Constants.SUFFIX 57 | ); 58 | const firstEvent = eventList[0]; 59 | expect(firstEvent.event_type).toBe(Event.PresetEvent.FIRST_OPEN); 60 | expect( 61 | firstEvent.user[Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP] 62 | ).not.toBeUndefined(); 63 | expect(firstEvent.attributes.brand).toBe('Samsung'); 64 | expect(firstEvent.attributes.level).toBe(10); 65 | expect( 66 | firstEvent.attributes[Event.ReservedAttribute.SESSION_ID] 67 | ).not.toBeUndefined(); 68 | expect( 69 | firstEvent.attributes[Event.ReservedAttribute.SESSION_NUMBER] 70 | ).not.toBeUndefined(); 71 | expect( 72 | firstEvent.attributes[Event.ReservedAttribute.SESSION_START_TIMESTAMP] 73 | ).not.toBeUndefined(); 74 | expect( 75 | firstEvent.attributes[Event.ReservedAttribute.SESSION_DURATION] 76 | ).not.toBeUndefined(); 77 | const testEvent = eventList[eventList.length - 1]; 78 | expect(testEvent.attributes.brand).toBeUndefined(); 79 | }); 80 | 81 | test('test init sdk with traffic source global attributes', async () => { 82 | const result = ClickstreamAnalytics.init({ 83 | appId: 'testApp', 84 | endpoint: 'https://example.com/collect', 85 | sendMode: SendMode.Batch, 86 | globalAttributes: { 87 | [Attr.TRAFFIC_SOURCE_SOURCE]: 'amazon', 88 | [Attr.TRAFFIC_SOURCE_MEDIUM]: 'cpc', 89 | [Attr.TRAFFIC_SOURCE_CAMPAIGN]: 'summer_promotion', 90 | [Attr.TRAFFIC_SOURCE_CAMPAIGN_ID]: 'summer_promotion_01', 91 | [Attr.TRAFFIC_SOURCE_TERM]: 'running_shoes', 92 | [Attr.TRAFFIC_SOURCE_CONTENT]: 'banner_ad_1', 93 | [Attr.TRAFFIC_SOURCE_CLID]: 'amazon_ad_123', 94 | [Attr.TRAFFIC_SOURCE_CLID_PLATFORM]: 'amazon_ads', 95 | }, 96 | }); 97 | expect(result).toBeTruthy(); 98 | await sleep(100); 99 | const eventList = JSON.parse( 100 | StorageUtil.getAllEvents() + Event.Constants.SUFFIX 101 | ); 102 | const firstEvent = eventList[0]; 103 | expect(firstEvent.event_type).toBe(Event.PresetEvent.FIRST_OPEN); 104 | expect(firstEvent.attributes[Attr.TRAFFIC_SOURCE_SOURCE]).toBe('amazon'); 105 | expect(firstEvent.attributes[Attr.TRAFFIC_SOURCE_MEDIUM]).toBe('cpc'); 106 | expect(firstEvent.attributes[Attr.TRAFFIC_SOURCE_CAMPAIGN]).toBe( 107 | 'summer_promotion' 108 | ); 109 | expect(firstEvent.attributes[Attr.TRAFFIC_SOURCE_CAMPAIGN_ID]).toBe( 110 | 'summer_promotion_01' 111 | ); 112 | expect(firstEvent.attributes[Attr.TRAFFIC_SOURCE_TERM]).toBe( 113 | 'running_shoes' 114 | ); 115 | expect(firstEvent.attributes[Attr.TRAFFIC_SOURCE_CONTENT]).toBe( 116 | 'banner_ad_1' 117 | ); 118 | expect(firstEvent.attributes[Attr.TRAFFIC_SOURCE_CLID]).toBe( 119 | 'amazon_ad_123' 120 | ); 121 | expect(firstEvent.attributes[Attr.TRAFFIC_SOURCE_CLID_PLATFORM]).toBe( 122 | 'amazon_ads' 123 | ); 124 | }); 125 | 126 | test('test record event with name success', async () => { 127 | const sendRequestMock = jest.spyOn(NetRequest, 'sendRequest'); 128 | ClickstreamAnalytics.init({ 129 | appId: 'testApp', 130 | endpoint: 'https://localhost:8080/collect', 131 | }); 132 | ClickstreamAnalytics.record({ 133 | name: 'testEvent', 134 | }); 135 | await sleep(100); 136 | expect(sendRequestMock).toBeCalled(); 137 | expect(StorageUtil.getFailedEvents().length).toBe(0); 138 | }); 139 | 140 | test('test record event with all attributes', async () => { 141 | const sendRequestMock = jest.spyOn(NetRequest, 'sendRequest'); 142 | ClickstreamAnalytics.init({ 143 | appId: 'testApp', 144 | endpoint: 'https://localhost:8080/collect', 145 | }); 146 | ClickstreamAnalytics.setUserId('32133'); 147 | ClickstreamAnalytics.setUserAttributes({ 148 | _user_name: 'carl', 149 | _user_age: 20, 150 | }); 151 | ClickstreamAnalytics.setGlobalAttributes({ 152 | brand: 'Samsung', 153 | level: 10, 154 | }); 155 | const item: Item = { 156 | id: '1', 157 | name: 'Nature', 158 | category: 'book', 159 | price: 56.5, 160 | customKey: 'customValue', 161 | }; 162 | ClickstreamAnalytics.record({ 163 | name: 'testEvent', 164 | attributes: { 165 | _channel: 'SMS', 166 | longValue: 4232032890992380000, 167 | isNew: true, 168 | score: 85.22, 169 | [Attr.VALUE]: 56.5, 170 | [Attr.CURRENCY]: 'USD', 171 | }, 172 | items: [item], 173 | }); 174 | await sleep(100); 175 | expect(sendRequestMock).toBeCalled(); 176 | expect(StorageUtil.getFailedEvents().length).toBe(0); 177 | }); 178 | 179 | test('test send event immediately in batch mode', async () => { 180 | const sendRequestMock = jest.spyOn(NetRequest, 'sendRequest'); 181 | ClickstreamAnalytics.init({ 182 | appId: 'testApp', 183 | endpoint: 'https://localhost:8080/collect', 184 | sendMode: SendMode.Batch, 185 | }); 186 | ClickstreamAnalytics.record({ 187 | name: 'testEvent', 188 | isImmediate: true, 189 | }); 190 | await sleep(100); 191 | expect(sendRequestMock).toBeCalled(); 192 | expect(StorageUtil.getFailedEvents().length).toBe(0); 193 | const eventList = JSON.parse( 194 | StorageUtil.getAllEvents() + Event.Constants.SUFFIX 195 | ); 196 | for (const event of eventList) { 197 | expect(event.event_type).not.toBe('testEvent'); 198 | } 199 | }); 200 | 201 | test('test add global attribute in subsequent event', async () => { 202 | ClickstreamAnalytics.init({ 203 | appId: 'testApp', 204 | endpoint: 'https://localhost:8080/collect', 205 | sendMode: SendMode.Batch, 206 | }); 207 | ClickstreamAnalytics.setGlobalAttributes({ 208 | _traffic_source_medium: 'Search engine', 209 | _traffic_source_name: 'Summer promotion', 210 | }); 211 | ClickstreamAnalytics.record({ name: 'testEvent' }); 212 | await sleep(100); 213 | const eventList = JSON.parse( 214 | StorageUtil.getAllEvents() + Event.Constants.SUFFIX 215 | ); 216 | const testEvent = eventList[eventList.length - 1]; 217 | expect(testEvent.event_type).toBe('testEvent'); 218 | expect(testEvent.attributes._traffic_source_medium).toBe('Search engine'); 219 | expect(testEvent.attributes._traffic_source_name).toBe('Summer promotion'); 220 | }); 221 | 222 | test('test update configuration', () => { 223 | ClickstreamAnalytics.init({ 224 | appId: 'testApp', 225 | endpoint: 'https://localhost:8080/collect', 226 | }); 227 | ClickstreamAnalytics.updateConfigure({ 228 | isLogEvents: true, 229 | authCookie: 'testCookie', 230 | isTrackPageViewEvents: false, 231 | isTrackClickEvents: false, 232 | isTrackScrollEvents: false, 233 | isTrackSearchEvents: false, 234 | }); 235 | const newConfigure = ClickstreamAnalytics['provider'].configuration; 236 | expect(newConfigure.isLogEvents).toBeTruthy(); 237 | expect(newConfigure.authCookie).toBe('testCookie'); 238 | expect(newConfigure.isTrackPageViewEvents).toBeFalsy(); 239 | expect(newConfigure.isTrackClickEvents).toBeFalsy(); 240 | expect(newConfigure.isTrackScrollEvents).toBeFalsy(); 241 | expect(newConfigure.isTrackSearchEvents).toBeFalsy(); 242 | expect(newConfigure.searchKeyWords.length).toBe(0); 243 | }); 244 | 245 | function sleep(ms: number): Promise { 246 | return new Promise(resolve => setTimeout(resolve, ms)); 247 | } 248 | }); 249 | -------------------------------------------------------------------------------- /test/browser/BrowserInfo.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { setPerformanceEntries } from './BrowserUtil'; 5 | import { MockObserver } from './MockObserver'; 6 | import { BrowserInfo } from '../../src/browser'; 7 | import { StorageUtil } from '../../src/util/StorageUtil'; 8 | 9 | describe('BrowserInfo test', () => { 10 | afterEach(() => { 11 | jest.clearAllMocks(); 12 | jest.resetAllMocks(); 13 | jest.restoreAllMocks(); 14 | }); 15 | test('test create BrowserInfo', () => { 16 | StorageUtil.clearAllEvents(); 17 | const referrer = 'https://example.com/collect'; 18 | Object.defineProperty(window.document, 'referrer', { 19 | writable: true, 20 | value: referrer, 21 | }); 22 | const browserInfo = new BrowserInfo(); 23 | expect(browserInfo.userAgent.length > 0).toBeTruthy(); 24 | expect(browserInfo.hostName.length > 0).toBeTruthy(); 25 | expect(browserInfo.locale.length > 0).toBeTruthy(); 26 | expect(browserInfo.system_language.length > 0).toBeTruthy(); 27 | expect(browserInfo.zoneOffset).not.toBeUndefined(); 28 | expect(browserInfo.make.length > 0).toBeTruthy(); 29 | expect(browserInfo.latestReferrer).toBe(referrer); 30 | expect(browserInfo.latestReferrerHost).toBe('example.com'); 31 | }); 32 | 33 | test('test invalid latest referrer host', () => { 34 | const referrer = '/collect'; 35 | Object.defineProperty(window.document, 'referrer', { 36 | writable: true, 37 | value: referrer, 38 | }); 39 | const browserInfo = new BrowserInfo(); 40 | expect(browserInfo.latestReferrer).toBe(referrer); 41 | expect(browserInfo.latestReferrerHost).toBeUndefined(); 42 | }); 43 | 44 | test('test init locale', () => { 45 | const browserInfo = new BrowserInfo(); 46 | browserInfo.initLocalInfo(''); 47 | expect(browserInfo.system_language).toBe(''); 48 | expect(browserInfo.country_code).toBe(''); 49 | 50 | browserInfo.initLocalInfo('en'); 51 | expect(browserInfo.system_language).toBe('en'); 52 | expect(browserInfo.country_code).toBe(''); 53 | 54 | browserInfo.initLocalInfo('fr-fr'); 55 | expect(browserInfo.system_language).toBe('fr'); 56 | expect(browserInfo.country_code).toBe('FR'); 57 | }); 58 | 59 | test('test get current page url', () => { 60 | jest.spyOn(BrowserInfo, 'isBrowser').mockReturnValue(false); 61 | const url = BrowserInfo.getCurrentPageUrl(); 62 | expect(url).toBe(''); 63 | const title = BrowserInfo.getCurrentPageTitle(); 64 | expect(title).toBe(''); 65 | }); 66 | 67 | test('test get current page title', () => { 68 | const originTitle = window.document.title; 69 | Object.defineProperty(window.document, 'title', { 70 | writable: true, 71 | value: undefined, 72 | }); 73 | const title = BrowserInfo.getCurrentPageTitle(); 74 | expect(title).toBe(''); 75 | Object.defineProperty(window.document, 'title', { 76 | writable: true, 77 | value: originTitle, 78 | }); 79 | }); 80 | 81 | test('test get make and return vendor', () => { 82 | const vendor = window.navigator.vendor; 83 | jest.spyOn(window.navigator, 'product', 'get').mockReturnValue(undefined); 84 | const browserInfo = new BrowserInfo(); 85 | expect(browserInfo.make).toBe(vendor); 86 | }); 87 | 88 | test('test browser type', () => { 89 | const isFirefox = BrowserInfo.isFirefox(); 90 | expect(isFirefox).toBeFalsy(); 91 | }); 92 | 93 | test('test unsupported web environment for performance', () => { 94 | expect(BrowserInfo.isFromReload()).toBeFalsy(); 95 | }); 96 | 97 | test('test web page from reload', () => { 98 | (global as any).PerformanceObserver = MockObserver; 99 | setPerformanceEntries(); 100 | expect(BrowserInfo.isFromReload()).toBeFalsy(); 101 | }); 102 | 103 | test('test web page not from reload', () => { 104 | (global as any).PerformanceObserver = MockObserver; 105 | setPerformanceEntries(true, true); 106 | StorageUtil.savePreviousPageUrl('http://localhost:8080'); 107 | expect(BrowserInfo.isFromReload()).toBeTruthy(); 108 | }); 109 | }); 110 | -------------------------------------------------------------------------------- /test/browser/BrowserUtil.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { MockObserver } from './MockObserver'; 5 | 6 | export function setUpBrowserPerformance() { 7 | (global as any).PerformanceObserver = MockObserver; 8 | setPerformanceEntries(false); 9 | } 10 | 11 | export function setPerformanceEntries(isLoaded = true, isReload = false) { 12 | Object.defineProperty(window, 'performance', { 13 | writable: true, 14 | value: { 15 | getEntriesByType: jest 16 | .fn() 17 | .mockImplementation( 18 | isLoaded 19 | ? isReload 20 | ? getEntriesByTypeForReload 21 | : getEntriesByType 22 | : getEntriesByTypeUnload 23 | ), 24 | }, 25 | }); 26 | } 27 | 28 | function getEntriesByType(): PerformanceEntryList { 29 | return ([ 30 | { 31 | name: 'https://aws.amazon.com/cn/', 32 | entryType: 'navigation', 33 | startTime: 0, 34 | duration: 3444.4000000059605, 35 | initiatorType: 'navigation', 36 | deliveryType: 'indirect', 37 | nextHopProtocol: 'h2', 38 | renderBlockingStatus: 'non-blocking', 39 | workerStart: 0, 40 | redirectStart: 2, 41 | redirectEnd: 2.2, 42 | fetchStart: 2.2000000178813934, 43 | domainLookupStart: 2.2000000178813934, 44 | domainLookupEnd: 2.2000000178813934, 45 | connectStart: 2.2000000178813934, 46 | secureConnectionStart: 2.2000000178813934, 47 | connectEnd: 2.2000000178813934, 48 | requestStart: 745.9000000059605, 49 | responseStart: 1006.7000000178814, 50 | firstInterimResponseStart: 0, 51 | responseEnd: 1321.300000011921, 52 | transferSize: 167553, 53 | encodedBodySize: 167253, 54 | decodedBodySize: 1922019, 55 | responseStatus: 200, 56 | serverTiming: [ 57 | { 58 | name: 'cache', 59 | duration: 0, 60 | description: 'hit-front', 61 | }, 62 | { 63 | name: 'host', 64 | duration: 0, 65 | description: 'cp3062', 66 | }, 67 | ], 68 | unloadEventStart: 1011.9000000059605, 69 | unloadEventEnd: 1011.9000000059605, 70 | domInteractive: 1710.9000000059605, 71 | domContentLoadedEventStart: 1712.7000000178814, 72 | domContentLoadedEventEnd: 1714.7000000178814, 73 | domComplete: 3440.4000000059605, 74 | loadEventStart: 3444.2000000178814, 75 | loadEventEnd: 3444.4000000059605, 76 | type: 'navigate', 77 | redirectCount: 0, 78 | activationStart: 0, 79 | criticalCHRestart: 0, 80 | }, 81 | ]); 82 | } 83 | 84 | function getEntriesByTypeForReload(): PerformanceEntryList { 85 | return ([ 86 | { 87 | type: 'reload', 88 | }, 89 | ]); 90 | } 91 | 92 | function getEntriesByTypeUnload(): PerformanceEntryList { 93 | return ([ 94 | { 95 | name: 'https://aws.amazon.com/cn/', 96 | entryType: 'navigation', 97 | startTime: 0, 98 | duration: 0, 99 | }, 100 | ]); 101 | } 102 | -------------------------------------------------------------------------------- /test/browser/MockObserver.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export class MockObserver { 5 | private readonly callback: () => void; 6 | 7 | constructor(callback: () => void) { 8 | this.callback = callback; 9 | } 10 | 11 | observe(options: any) { 12 | console.log(options); 13 | } 14 | 15 | call() { 16 | this.callback(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /test/network/NetRequest.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import fetchMock from '@fetch-mock/jest'; 5 | import { ClickstreamAnalytics } from '../../src'; 6 | import { BrowserInfo } from '../../src/browser'; 7 | import { NetRequest } from '../../src/network/NetRequest'; 8 | import { AnalyticsEventBuilder, ClickstreamContext } from '../../src/provider'; 9 | import { Session } from '../../src/tracker'; 10 | import { HashUtil } from '../../src/util/HashUtil'; 11 | 12 | function mockFetch( 13 | ok: boolean = true, 14 | status: number = 200, 15 | delay?: number 16 | ) { 17 | return jest.spyOn(global, 'fetch').mockImplementation(() => { 18 | const responsePromise = Promise.resolve({ 19 | ok, 20 | status, 21 | json: () => Promise.resolve([]), 22 | text: () => Promise.resolve(''), 23 | } as Response); 24 | 25 | if (delay !== undefined && delay > 0) { 26 | return new Promise(resolve => { 27 | setTimeout(() => resolve(responsePromise), delay); 28 | }); 29 | } else { 30 | return responsePromise; 31 | } 32 | }); 33 | } 34 | 35 | 36 | describe('ClickstreamAnalytics test', () => { 37 | let context: ClickstreamContext; 38 | let eventJson: string; 39 | let fetchSpy: jest.SpyInstance; 40 | 41 | beforeEach(async () => { 42 | fetchSpy = mockFetch(); 43 | context = new ClickstreamContext(new BrowserInfo(), { 44 | appId: 'testApp', 45 | endpoint: 'https://localhost:8080/collect', 46 | }); 47 | const event = AnalyticsEventBuilder.createEvent( 48 | context, 49 | { name: 'testEvent' }, 50 | {}, 51 | Session.getCurrentSession(context) 52 | ); 53 | eventJson = JSON.stringify([event]); 54 | }); 55 | 56 | afterEach(() => { 57 | fetchMock.mockReset(); 58 | fetchSpy.mockRestore(); 59 | ClickstreamAnalytics['provider'] = undefined; 60 | }); 61 | 62 | test('test request success', async () => { 63 | jest.spyOn(global, 'fetch').mockImplementation(() => 64 | Promise.resolve({ 65 | ok: true, 66 | status: 200, 67 | json: () => Promise.resolve([]), 68 | } as Response) 69 | ); 70 | fetchMock.post('begin:https://localhost:8080/collect', { 71 | status: 200, 72 | body: [], 73 | }); 74 | const result = await NetRequest.sendRequest(eventJson, context, 1); 75 | expect(result).toBeTruthy(); 76 | expect(fetchSpy).toHaveBeenCalledTimes(1); 77 | }); 78 | 79 | test('test request fail', async () => { 80 | fetchSpy.mockRestore(); 81 | fetchSpy = mockFetch(false, 400); 82 | context = new ClickstreamContext(new BrowserInfo(), { 83 | appId: 'testApp', 84 | endpoint: 'https://localhost:8080/failed', 85 | }); 86 | const result = await NetRequest.sendRequest(eventJson, context, 1); 87 | expect(result).toBeFalsy(); 88 | expect(fetchSpy).toHaveBeenCalledTimes(3); 89 | }); 90 | 91 | test('test request fail with code 404', async () => { 92 | fetchSpy.mockRestore(); 93 | fetchSpy = mockFetch(false, 404); 94 | fetchMock.post('begin:https://localhost:8080/collectFail', 404); 95 | context = new ClickstreamContext(new BrowserInfo(), { 96 | appId: 'testApp', 97 | endpoint: 'https://localhost:8080/collectFail', 98 | }); 99 | const result = await NetRequest.sendRequest(eventJson, context, 1); 100 | expect(result).toBeFalsy(); 101 | expect(fetchSpy).toHaveBeenCalledTimes(3); 102 | }); 103 | 104 | test('test request timeout', async () => { 105 | fetchSpy.mockRestore(); 106 | fetchSpy = mockFetch(false, 504, 1000); 107 | fetchMock.post( 108 | 'begin:https://localhost:8080/collect', 109 | { 110 | status: 504, 111 | body: [], 112 | }, 113 | { 114 | delay: 1000, 115 | } 116 | ); 117 | context = new ClickstreamContext(new BrowserInfo(), { 118 | appId: 'testApp', 119 | endpoint: 'https://localhost:8080/collect', 120 | }); 121 | const startTime = Date.now(); 122 | const result = await NetRequest.sendRequest(eventJson, context, 1, 1, 200); 123 | const endTime = Date.now(); 124 | 125 | expect(result).toBeFalsy(); 126 | expect(fetchSpy).toHaveBeenCalledTimes(1); 127 | expect(endTime - startTime).toBeGreaterThanOrEqual(1000); 128 | 129 | const response = await fetchSpy.mock.results[0].value; 130 | expect(response.ok).toBe(false); 131 | expect(response.status).toBe(504); 132 | }); 133 | 134 | test('test request success with hash code', async () => { 135 | fetchMock.post('begin:https://localhost:8080/collect', { 136 | status: 200, 137 | body: [], 138 | }); 139 | const eventJsonHashCode = await HashUtil.getHashCode(eventJson); 140 | const result = await NetRequest.sendRequest(eventJson, context, 1); 141 | expect(result).toBeTruthy(); 142 | 143 | const [requestUrl] = fetchSpy.mock.calls[0]; 144 | const requestHashCode = new URL(requestUrl.toString()).searchParams.get( 145 | 'hashCode' 146 | ); 147 | expect(eventJsonHashCode).toBe(requestHashCode); 148 | }); 149 | 150 | test('test request success with upload timestamp', async () => { 151 | fetchMock.post('begin:https://localhost:8080/collect', { 152 | status: 200, 153 | body: [], 154 | }); 155 | const result = await NetRequest.sendRequest(eventJson, context, 1); 156 | expect(result).toBeTruthy(); 157 | 158 | const [requestUrl] = fetchSpy.mock.calls[0]; 159 | const uploadTimestamp = new URL(requestUrl.toString()).searchParams.get( 160 | 'upload_timestamp' 161 | ); 162 | expect(uploadTimestamp).not.toBeNull(); 163 | }); 164 | 165 | test('test error handling', async () => { 166 | const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); 167 | fetchSpy.mockRestore(); 168 | fetchSpy = jest.spyOn(global, 'fetch').mockImplementation(() => { 169 | throw new Error('Network error'); 170 | }); 171 | 172 | const result = await NetRequest.sendRequest(eventJson, context, 1, 1); 173 | expect(result).toBeFalsy(); 174 | expect(fetchSpy).toHaveBeenCalledTimes(1); 175 | expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('Error during request: Error: Network error')); 176 | consoleErrorSpy.mockRestore(); 177 | }) 178 | 179 | test('should use authCookie value when present', async () => { 180 | const testCookie = 'session=abc123'; 181 | context = new ClickstreamContext(new BrowserInfo(), { 182 | appId: 'testApp', 183 | endpoint: 'https://localhost:8080/collect', 184 | }); 185 | context.configuration.authCookie = testCookie; 186 | const result = await NetRequest.sendRequest( 187 | '{}', 188 | context, 189 | 1 190 | ); 191 | 192 | expect(global.fetch).toHaveBeenCalledWith( 193 | expect.any(String), 194 | expect.objectContaining({ 195 | headers: expect.objectContaining({ 196 | cookie: testCookie 197 | }) 198 | }) 199 | ); 200 | }); 201 | 202 | test('should use empty string when authCookie is undefined', async () => { 203 | context = new ClickstreamContext(new BrowserInfo(), { 204 | appId: 'testApp', 205 | endpoint: 'https://localhost:8080/collect', 206 | }); 207 | context.configuration.authCookie = undefined; 208 | const result = await NetRequest.sendRequest( 209 | '{}', 210 | context, 211 | 1 212 | ); 213 | 214 | // Verify fetch was called with empty cookie header 215 | expect(global.fetch).toHaveBeenCalledWith( 216 | expect.any(String), 217 | expect.objectContaining({ 218 | headers: expect.objectContaining({ 219 | cookie: '' 220 | }) 221 | }) 222 | ); 223 | }); 224 | 225 | test('should use userAgent value when present', async () => { 226 | const testUserAgent = 'Mozilla/5.0 Test Browser'; 227 | context = new ClickstreamContext(new BrowserInfo(), { 228 | appId: 'testApp', 229 | endpoint: 'https://localhost:8080/collect', 230 | }); 231 | context.browserInfo.userAgent = testUserAgent; 232 | const result = await NetRequest.sendRequest( 233 | '{}', 234 | context, 235 | 1 236 | ); 237 | 238 | expect(global.fetch).toHaveBeenCalledWith( 239 | expect.any(String), 240 | expect.objectContaining({ 241 | headers: expect.objectContaining({ 242 | 'User-Agent': testUserAgent 243 | }) 244 | }) 245 | ); 246 | }); 247 | 248 | test('should use empty string when userAgent is null', async () => { 249 | context = new ClickstreamContext(new BrowserInfo(), { 250 | appId: 'testApp', 251 | endpoint: 'https://localhost:8080/collect', 252 | }); 253 | context.browserInfo.userAgent = null; 254 | const result = await NetRequest.sendRequest( 255 | '{}', 256 | context, 257 | 1 258 | ); 259 | 260 | expect(global.fetch).toHaveBeenCalledWith( 261 | expect.any(String), 262 | expect.objectContaining({ 263 | headers: expect.objectContaining({ 264 | 'User-Agent': '' 265 | }) 266 | }) 267 | ); 268 | }); 269 | }); 270 | -------------------------------------------------------------------------------- /test/provider/AnalyticsEventBuilder.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | 5 | import { version } from '../../package.json'; 6 | import { BrowserInfo } from '../../src/browser'; 7 | import { 8 | AnalyticsEventBuilder, 9 | ClickstreamContext, 10 | Event, 11 | } from '../../src/provider'; 12 | import { Session } from '../../src/tracker'; 13 | import { ClickstreamAttribute, Item } from '../../src/types'; 14 | 15 | describe('AnalyticsEventBuilder test', () => { 16 | test('test create event with common attributes', async () => { 17 | const referrer = 'https://example1.com/collect'; 18 | Object.defineProperty(window.document, 'referrer', { 19 | writable: true, 20 | value: referrer, 21 | }); 22 | Object.defineProperty(window.screen, 'width', { 23 | writable: true, 24 | value: 1920, 25 | }); 26 | Object.defineProperty(window.screen, 'height', { 27 | writable: true, 28 | value: 1080, 29 | }); 30 | const context = new ClickstreamContext(new BrowserInfo(), { 31 | appId: 'testApp', 32 | endpoint: 'https://example.com/collect', 33 | }); 34 | const event = AnalyticsEventBuilder.createEvent( 35 | context, 36 | { name: 'testEvent' }, 37 | {}, 38 | Session.getCurrentSession(context) 39 | ); 40 | expect((event as any).hashCode).toBeUndefined(); 41 | expect(event.event_type).toBe('testEvent'); 42 | expect(event.event_id.length > 0).toBeTruthy(); 43 | expect(event.device_id.length > 0).toBeTruthy(); 44 | expect(event.unique_id.length > 0).toBeTruthy(); 45 | expect(event.timestamp > 0).toBeTruthy(); 46 | expect(event.host_name.length > 0).toBeTruthy(); 47 | expect(event.locale.length > 0).toBeTruthy(); 48 | expect(event.system_language.length > 0).toBeTruthy(); 49 | expect(event.zone_offset).not.toBeUndefined(); 50 | expect(event.make.length > 0).toBeTruthy(); 51 | expect(event.platform).toBe('Web'); 52 | expect(event.sdk_name).toBe('aws-solution-clickstream-sdk'); 53 | expect(event.screen_height > 0).toBeTruthy(); 54 | expect(event.screen_width > 0).toBeTruthy(); 55 | expect(event.viewport_height > 0).toBeTruthy(); 56 | expect(event.viewport_width > 0).toBeTruthy(); 57 | expect(event.sdk_version).toBe(version); 58 | expect(event.user).toStrictEqual({}); 59 | expect(Event.ReservedAttribute.PAGE_TITLE in event.attributes); 60 | expect(Event.ReservedAttribute.PAGE_URL in event.attributes); 61 | expect(Event.ReservedAttribute.SESSION_ID in event.attributes); 62 | expect(Event.ReservedAttribute.SESSION_DURATION in event.attributes); 63 | expect(Event.ReservedAttribute.SESSION_NUMBER in event.attributes); 64 | expect(Event.ReservedAttribute.SESSION_START_TIMESTAMP in event.attributes); 65 | expect(Event.ReservedAttribute.LATEST_REFERRER in event.attributes); 66 | expect(Event.ReservedAttribute.LATEST_REFERRER_HOST in event.attributes); 67 | }); 68 | 69 | test('test check event attribute reached max attribute number limit', () => { 70 | let clickstreamAttribute: ClickstreamAttribute = {}; 71 | for (let i = 0; i < 501; i++) { 72 | clickstreamAttribute[`attribute${i}`] = i; 73 | } 74 | clickstreamAttribute = 75 | AnalyticsEventBuilder.getEventAttributesWithCheck(clickstreamAttribute); 76 | expect( 77 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 78 | ).toBeTruthy(); 79 | expect(clickstreamAttribute[Event.ReservedAttribute.ERROR_CODE]).toBe( 80 | Event.ErrorCode.ATTRIBUTE_SIZE_EXCEED 81 | ); 82 | }); 83 | 84 | test('test check event attribute reached max length of name', () => { 85 | let clickstreamAttribute: ClickstreamAttribute = {}; 86 | let longKey = ''; 87 | for (let i = 0; i < 10; i++) { 88 | longKey += 'abcdeabcdef'; 89 | } 90 | clickstreamAttribute[longKey] = 'testValue'; 91 | clickstreamAttribute = 92 | AnalyticsEventBuilder.getEventAttributesWithCheck(clickstreamAttribute); 93 | expect( 94 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 95 | ).toBeTruthy(); 96 | expect(clickstreamAttribute[Event.ReservedAttribute.ERROR_CODE]).toBe( 97 | Event.ErrorCode.ATTRIBUTE_NAME_LENGTH_EXCEED 98 | ); 99 | }); 100 | 101 | test('test check event attribute with invalid name', () => { 102 | let clickstreamAttribute: ClickstreamAttribute = {}; 103 | clickstreamAttribute['3abc'] = 'testValue'; 104 | clickstreamAttribute = 105 | AnalyticsEventBuilder.getEventAttributesWithCheck(clickstreamAttribute); 106 | expect( 107 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 108 | ).toBeTruthy(); 109 | expect(clickstreamAttribute[Event.ReservedAttribute.ERROR_CODE]).toBe( 110 | Event.ErrorCode.ATTRIBUTE_NAME_INVALID 111 | ); 112 | }); 113 | 114 | test('test check event attribute with invalid value', () => { 115 | let clickstreamAttribute: ClickstreamAttribute = {}; 116 | clickstreamAttribute['testUndefinedKey'] = undefined; 117 | clickstreamAttribute['testNullKey'] = null; 118 | clickstreamAttribute = 119 | AnalyticsEventBuilder.getEventAttributesWithCheck(clickstreamAttribute); 120 | expect( 121 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 122 | ).toBeFalsy(); 123 | }); 124 | 125 | test('test check event attribute reached max attribute value length', () => { 126 | let clickstreamAttribute: ClickstreamAttribute = {}; 127 | let longValue = ''; 128 | for (let i = 0; i < 100; i++) { 129 | longValue += 'abcdeabcdef'; 130 | } 131 | clickstreamAttribute['testKey'] = longValue; 132 | clickstreamAttribute = 133 | AnalyticsEventBuilder.getEventAttributesWithCheck(clickstreamAttribute); 134 | expect( 135 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 136 | ).toBeTruthy(); 137 | expect(clickstreamAttribute[Event.ReservedAttribute.ERROR_CODE]).toBe( 138 | Event.ErrorCode.ATTRIBUTE_VALUE_LENGTH_EXCEED 139 | ); 140 | }); 141 | 142 | test('test check event item reached max item number limit', () => { 143 | const clickstreamAttribute: ClickstreamAttribute = {}; 144 | const items: Item[] = []; 145 | const exceedNumber = Event.Limit.MAX_NUM_OF_ITEMS + 1; 146 | for (let i = 0; i < exceedNumber; i++) { 147 | const item: Item = { 148 | id: String(i), 149 | name: 'item' + i, 150 | }; 151 | items.push(item); 152 | } 153 | const resultItems = AnalyticsEventBuilder.getEventItemsWithCheck( 154 | items, 155 | clickstreamAttribute 156 | ); 157 | expect(resultItems.length).toBe(Event.Limit.MAX_NUM_OF_ITEMS); 158 | expect( 159 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 160 | ).toBeTruthy(); 161 | expect(clickstreamAttribute[Event.ReservedAttribute.ERROR_CODE]).toBe( 162 | Event.ErrorCode.ITEM_SIZE_EXCEED 163 | ); 164 | }); 165 | 166 | test('test check event item reached max item attribute value length limit', () => { 167 | const clickstreamAttribute: ClickstreamAttribute = {}; 168 | const items: Item[] = []; 169 | let longValue = ''; 170 | for (let i = 0; i < 26; i++) { 171 | longValue += 'abcdeabcde'; 172 | } 173 | const item1: Item = { 174 | id: 'invalid1', 175 | name: longValue, 176 | category: 'category', 177 | }; 178 | items.push(item1); 179 | const resultItems = AnalyticsEventBuilder.getEventItemsWithCheck( 180 | items, 181 | clickstreamAttribute 182 | ); 183 | expect(resultItems.length).toBe(0); 184 | expect( 185 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 186 | ).toBeTruthy(); 187 | expect(clickstreamAttribute[Event.ReservedAttribute.ERROR_CODE]).toBe( 188 | Event.ErrorCode.ITEM_VALUE_LENGTH_EXCEED 189 | ); 190 | }); 191 | 192 | test('test add custom item attribute success', () => { 193 | const clickstreamAttribute: ClickstreamAttribute = {}; 194 | const items: Item[] = []; 195 | const item: Item = { 196 | id: 'item_1', 197 | category: 'category', 198 | customAttribute: 'customValue', 199 | item_style: 'style', 200 | item_type: 'type', 201 | }; 202 | items.push(item); 203 | const resultItems = AnalyticsEventBuilder.getEventItemsWithCheck( 204 | items, 205 | clickstreamAttribute 206 | ); 207 | expect(resultItems.length).toBe(1); 208 | expect( 209 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 210 | ).toBeFalsy(); 211 | }); 212 | 213 | test('test add custom item attribute exceed the max custom item attribute limit', () => { 214 | const clickstreamAttribute: ClickstreamAttribute = {}; 215 | const items: Item[] = []; 216 | const item: Item = { 217 | id: 'item_1', 218 | category: 'category', 219 | }; 220 | for (let i = 0; i < Event.Limit.MAX_NUM_OF_CUSTOM_ITEM_ATTRIBUTE + 1; i++) { 221 | item['custom_attr_' + i] += 'customValue_' + i; 222 | } 223 | items.push(item); 224 | const resultItems = AnalyticsEventBuilder.getEventItemsWithCheck( 225 | items, 226 | clickstreamAttribute 227 | ); 228 | expect(resultItems.length).toBe(0); 229 | expect( 230 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 231 | ).toBeTruthy(); 232 | expect(clickstreamAttribute[Event.ReservedAttribute.ERROR_CODE]).toBe( 233 | Event.ErrorCode.ITEM_CUSTOM_ATTRIBUTE_SIZE_EXCEED 234 | ); 235 | }); 236 | 237 | test('test check item key reached max length limit', () => { 238 | const clickstreamAttribute: ClickstreamAttribute = {}; 239 | const items: Item[] = []; 240 | let longKey = ''; 241 | for (let i = 0; i < 6; i++) { 242 | longKey += 'abcdeabcde'; 243 | } 244 | const item: Item = { 245 | id: 'item_1', 246 | category: 'category', 247 | }; 248 | item[longKey] = 'testValue'; 249 | items.push(item); 250 | const resultItems = AnalyticsEventBuilder.getEventItemsWithCheck( 251 | items, 252 | clickstreamAttribute 253 | ); 254 | expect(resultItems.length).toBe(0); 255 | expect( 256 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 257 | ).toBeTruthy(); 258 | expect(clickstreamAttribute[Event.ReservedAttribute.ERROR_CODE]).toBe( 259 | Event.ErrorCode.ITEM_CUSTOM_ATTRIBUTE_KEY_LENGTH_EXCEED 260 | ); 261 | }); 262 | 263 | test('test check item key for invalid', () => { 264 | const clickstreamAttribute: ClickstreamAttribute = {}; 265 | const items: Item[] = []; 266 | const item: Item = { 267 | id: 'item_1', 268 | category: 'category', 269 | }; 270 | item['1_key'] = 'testValue'; 271 | items.push(item); 272 | const resultItems = AnalyticsEventBuilder.getEventItemsWithCheck( 273 | items, 274 | clickstreamAttribute 275 | ); 276 | expect(resultItems.length).toBe(0); 277 | expect( 278 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 279 | ).toBeTruthy(); 280 | expect(clickstreamAttribute[Event.ReservedAttribute.ERROR_CODE]).toBe( 281 | Event.ErrorCode.ITEM_CUSTOM_ATTRIBUTE_KEY_INVALID 282 | ); 283 | }); 284 | 285 | test('test check item value for undefined or null', () => { 286 | const clickstreamAttribute: ClickstreamAttribute = {}; 287 | const items: Item[] = []; 288 | const item: Item = { 289 | id: 'item_1', 290 | undefinedKey: undefined, 291 | nullKey: null, 292 | }; 293 | items.push(item); 294 | const resultItems = AnalyticsEventBuilder.getEventItemsWithCheck( 295 | items, 296 | clickstreamAttribute 297 | ); 298 | expect(resultItems.length).toBe(1); 299 | expect( 300 | Event.ReservedAttribute.ERROR_CODE in clickstreamAttribute 301 | ).toBeFalsy(); 302 | }); 303 | 304 | test('test check event attributes will not affect global attributes', () => { 305 | const customAttributes: ClickstreamAttribute = { 306 | testKey: 'testValue', 307 | testKey1: 'testValue1', 308 | }; 309 | const globalAttributes = { 310 | level: 5, 311 | _traffic_source_medium: 'Search engine', 312 | }; 313 | const resultAttributes = AnalyticsEventBuilder.getEventAttributesWithCheck( 314 | customAttributes, 315 | globalAttributes 316 | ); 317 | expect('level' in resultAttributes).toBeTruthy(); 318 | expect('_traffic_source_medium' in resultAttributes).toBeTruthy(); 319 | expect(Object.keys(globalAttributes).length).toBe(2); 320 | }); 321 | }); 322 | -------------------------------------------------------------------------------- /test/provider/BatchModeTimer.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { SendMode } from '../../src'; 5 | import { NetRequest } from '../../src/network/NetRequest'; 6 | import { ClickstreamProvider } from '../../src/provider'; 7 | import { StorageUtil } from '../../src/util/StorageUtil'; 8 | import { setUpBrowserPerformance } from '../browser/BrowserUtil'; 9 | 10 | describe('ClickstreamProvider timer test', () => { 11 | let provider: ClickstreamProvider; 12 | beforeEach(() => { 13 | StorageUtil.clearAll(); 14 | setUpBrowserPerformance(); 15 | provider = new ClickstreamProvider(); 16 | const mockSendRequest = jest.fn().mockResolvedValue(true); 17 | jest.spyOn(NetRequest, 'sendRequest').mockImplementation(mockSendRequest); 18 | }); 19 | 20 | afterEach(() => { 21 | provider = undefined; 22 | jest.restoreAllMocks(); 23 | }); 24 | test('test config batch mode with timer', async () => { 25 | const startTimerMock = jest.spyOn(provider, 'startTimer'); 26 | const flushEventsMock = jest.spyOn(provider, 'flushEvents'); 27 | provider.configure({ 28 | appId: 'testAppId', 29 | endpoint: 'https://example.com/collect', 30 | sendMode: SendMode.Batch, 31 | sendEventsInterval: 10, 32 | }); 33 | await sleep(100); 34 | expect(startTimerMock).toBeCalled(); 35 | expect(flushEventsMock).toBeCalled(); 36 | }); 37 | }); 38 | 39 | function sleep(ms: number): Promise { 40 | return new Promise(resolve => setTimeout(resolve, ms)); 41 | } 42 | -------------------------------------------------------------------------------- /test/provider/ClickstreamProvider.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { NetRequest } from '../../src/network/NetRequest'; 5 | import { 6 | AnalyticsEventBuilder, 7 | ClickstreamProvider, 8 | Event, 9 | } from '../../src/provider'; 10 | import { 11 | ClickstreamAttribute, 12 | ClickstreamConfiguration, 13 | PageType, 14 | SendMode, 15 | } from '../../src/types'; 16 | import { StorageUtil } from '../../src/util/StorageUtil'; 17 | import { setUpBrowserPerformance } from '../browser/BrowserUtil'; 18 | 19 | describe('ClickstreamProvider test', () => { 20 | let provider: ClickstreamProvider; 21 | let mockProviderCreateEvent: any; 22 | let mockCreateEvent: any; 23 | let mockRecordProfileSet: any; 24 | 25 | beforeEach(async () => { 26 | StorageUtil.clearAll(); 27 | setUpBrowserPerformance(); 28 | const mockSendRequest = jest.fn().mockResolvedValue(true); 29 | jest.spyOn(NetRequest, 'sendRequest').mockImplementation(mockSendRequest); 30 | provider = new ClickstreamProvider(); 31 | provider.configure({ 32 | appId: 'testAppId', 33 | endpoint: 'https://example.com/collect', 34 | }); 35 | mockProviderCreateEvent = jest.spyOn(provider, 'createEvent'); 36 | mockCreateEvent = jest.spyOn(AnalyticsEventBuilder, 'createEvent'); 37 | mockRecordProfileSet = jest.spyOn(provider, 'recordProfileSet'); 38 | }); 39 | 40 | afterEach(() => { 41 | provider = undefined; 42 | jest.restoreAllMocks(); 43 | jest.clearAllMocks(); 44 | }); 45 | 46 | test('test default value', async () => { 47 | await sleep(100); 48 | expect(provider.configuration.appId).toBe('testAppId'); 49 | expect(provider.configuration.endpoint).toBe('https://example.com/collect'); 50 | expect(provider.configuration.sendMode).toBe(SendMode.Immediate); 51 | expect(provider.configuration.sendEventsInterval).toBe(5000); 52 | expect(provider.configuration.isTrackPageViewEvents).toBe(true); 53 | expect(provider.configuration.isLogEvents).toBe(false); 54 | expect(provider.configuration.sessionTimeoutDuration).toBe(1800000); 55 | }); 56 | 57 | test('test config with empty appId or endpoint', () => { 58 | const configuration = provider.configure({ 59 | appId: '', 60 | endpoint: '', 61 | }) as ClickstreamConfiguration; 62 | 63 | expect(configuration.appId).toBe(''); 64 | expect(configuration.endpoint).toBe(''); 65 | }); 66 | 67 | test('test modify configuration', () => { 68 | const configuration = provider.configure({ 69 | appId: 'testAppId', 70 | endpoint: 'https://example.com/collect', 71 | isLogEvents: true, 72 | sendMode: SendMode.Batch, 73 | sendEventsInterval: 2000, 74 | isTrackPageViewEvents: false, 75 | pageType: PageType.multiPageApp, 76 | sessionTimeoutDuration: 300000, 77 | authCookie: 'your auth cookie', 78 | }) as ClickstreamConfiguration; 79 | expect(configuration.appId).toBe('testAppId'); 80 | expect(configuration.endpoint).toBe('https://example.com/collect'); 81 | expect(configuration.isLogEvents).toBe(true); 82 | expect(configuration.sendEventsInterval).toBe(2000); 83 | expect(configuration.isTrackPageViewEvents).toBe(false); 84 | expect(configuration.pageType).toBe(PageType.multiPageApp); 85 | expect(configuration.sessionTimeoutDuration).toBe(300000); 86 | expect(configuration.authCookie).toBe('your auth cookie'); 87 | }); 88 | 89 | test('test get category and provider name', () => { 90 | expect(provider.getCategory()).toBe('Analytics'); 91 | expect(provider.getProviderName()).toBe('ClickstreamProvider'); 92 | }); 93 | 94 | test('test record event with valid event name', () => { 95 | mockCreateEvent = jest.spyOn(AnalyticsEventBuilder, 'createEvent'); 96 | provider.record({ name: 'testEvent' }); 97 | expect(mockCreateEvent).toHaveBeenCalled(); 98 | }); 99 | 100 | test('test record event with invalid event name', () => { 101 | const mockProviderCreateEvent = jest.spyOn(provider, 'createEvent'); 102 | provider.record({ name: '01testEvent' }); 103 | const { ERROR_CODE, ERROR_MESSAGE } = Event.ReservedAttribute; 104 | expect(mockProviderCreateEvent).toHaveBeenCalledWith( 105 | expect.objectContaining({ 106 | name: Event.PresetEvent.CLICKSTREAM_ERROR, 107 | attributes: { 108 | [ERROR_CODE]: Event.ErrorCode.EVENT_NAME_INVALID, 109 | [ERROR_MESSAGE]: expect.anything(), 110 | }, 111 | }) 112 | ); 113 | }); 114 | 115 | test('test setUserAttributes reached max number limit', () => { 116 | const clickstreamAttribute: ClickstreamAttribute = {}; 117 | for (let i = 0; i < 101; i++) { 118 | clickstreamAttribute[`attribute${i}`] = i; 119 | } 120 | provider.setUserAttributes(clickstreamAttribute); 121 | const { ERROR_CODE, ERROR_MESSAGE } = Event.ReservedAttribute; 122 | const expectedData = { 123 | name: Event.PresetEvent.CLICKSTREAM_ERROR, 124 | attributes: { 125 | [ERROR_CODE]: Event.ErrorCode.USER_ATTRIBUTE_SIZE_EXCEED, 126 | [ERROR_MESSAGE]: expect.anything(), 127 | }, 128 | }; 129 | expect(mockProviderCreateEvent).toHaveBeenCalledWith( 130 | expect.objectContaining(expectedData) 131 | ); 132 | }); 133 | 134 | test('test setUserAttributes reached max length of name', () => { 135 | const clickstreamAttribute: ClickstreamAttribute = {}; 136 | let longKey = ''; 137 | for (let i = 0; i < 10; i++) { 138 | longKey += 'abcdeabcdef'; 139 | } 140 | clickstreamAttribute[longKey] = 'testValue'; 141 | provider.setUserAttributes(clickstreamAttribute); 142 | const { ERROR_CODE, ERROR_MESSAGE } = Event.ReservedAttribute; 143 | expect(mockProviderCreateEvent).toHaveBeenCalledWith( 144 | expect.objectContaining({ 145 | name: Event.PresetEvent.CLICKSTREAM_ERROR, 146 | attributes: { 147 | [ERROR_CODE]: Event.ErrorCode.USER_ATTRIBUTE_NAME_LENGTH_EXCEED, 148 | [ERROR_MESSAGE]: expect.anything(), 149 | }, 150 | }) 151 | ); 152 | }); 153 | 154 | test('test setUserAttributes with invalid name', () => { 155 | const clickstreamAttribute: ClickstreamAttribute = {}; 156 | clickstreamAttribute['3abc'] = 'testValue'; 157 | provider.setUserAttributes(clickstreamAttribute); 158 | const { ERROR_CODE, ERROR_MESSAGE } = Event.ReservedAttribute; 159 | expect(mockProviderCreateEvent).toHaveBeenCalledWith( 160 | expect.objectContaining({ 161 | name: Event.PresetEvent.CLICKSTREAM_ERROR, 162 | attributes: { 163 | [ERROR_CODE]: Event.ErrorCode.USER_ATTRIBUTE_NAME_INVALID, 164 | [ERROR_MESSAGE]: expect.anything(), 165 | }, 166 | }) 167 | ); 168 | }); 169 | 170 | test('test setUserAttributes reached max attribute value length', () => { 171 | const clickstreamAttribute: ClickstreamAttribute = {}; 172 | let longValue = ''; 173 | for (let i = 0; i < 100; i++) { 174 | longValue += 'abcdeabcdef'; 175 | } 176 | clickstreamAttribute['testKey'] = longValue; 177 | provider.setUserAttributes(clickstreamAttribute); 178 | const { ERROR_CODE, ERROR_MESSAGE } = Event.ReservedAttribute; 179 | expect(mockProviderCreateEvent).toHaveBeenCalledWith( 180 | expect.objectContaining({ 181 | name: Event.PresetEvent.CLICKSTREAM_ERROR, 182 | attributes: { 183 | [ERROR_CODE]: Event.ErrorCode.USER_ATTRIBUTE_VALUE_LENGTH_EXCEED, 184 | [ERROR_MESSAGE]: expect.anything(), 185 | }, 186 | }) 187 | ); 188 | }); 189 | 190 | test('test delete user attribute', () => { 191 | const clickstreamAttribute: ClickstreamAttribute = { 192 | testAttribute: 'testValue', 193 | }; 194 | provider.setUserAttributes(clickstreamAttribute); 195 | provider.setUserAttributes({ 196 | testAttribute: null, 197 | }); 198 | expect('testAttribute' in provider.userAttributes).toBeFalsy(); 199 | expect(mockRecordProfileSet).toBeCalled(); 200 | }); 201 | 202 | test('test set userId null', () => { 203 | provider.setUserId('232121'); 204 | provider.setUserId(null); 205 | expect( 206 | Event.ReservedAttribute.USER_ID in provider.userAttributes 207 | ).toBeFalsy(); 208 | expect(mockRecordProfileSet).toBeCalledTimes(2); 209 | }); 210 | 211 | test('test set userId not null', () => { 212 | expect(StorageUtil.getUserIdMapping()).toBeNull(); 213 | const userUniqueId = StorageUtil.getCurrentUserUniqueId(); 214 | const firstTouchTimeStamp = 215 | provider.userAttributes[ 216 | Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP 217 | ]; 218 | provider.setUserId('113'); 219 | expect( 220 | provider.userAttributes[ 221 | Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP 222 | ].toString() 223 | ).toBe(firstTouchTimeStamp.toString()); 224 | expect(StorageUtil.getCurrentUserUniqueId()).toBe(userUniqueId); 225 | expect(StorageUtil.getUserIdMapping()).not.toBeNull(); 226 | expect(mockRecordProfileSet).toBeCalled(); 227 | }); 228 | 229 | test('test set userId twice', () => { 230 | provider.setUserId('113'); 231 | provider.setUserId('114'); 232 | const userIdMapping = StorageUtil.getUserIdMapping(); 233 | expect(userIdMapping).not.toBeNull(); 234 | expect('113' in userIdMapping).toBeTruthy(); 235 | expect('114' in userIdMapping).toBeTruthy(); 236 | expect(provider.context.userUniqueId).toBe( 237 | userIdMapping['114'].user_uniqueId.value 238 | ); 239 | }); 240 | 241 | test('test set userId A to B to A', () => { 242 | const userUniqueIdNotLogin = provider.context.userUniqueId; 243 | const userFirstTouchTimestamp = 244 | provider.userAttributes[ 245 | Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP 246 | ].value; 247 | provider.setUserId('A'); 248 | const userUniqueIdA = provider.context.userUniqueId; 249 | provider.setUserId('B'); 250 | const userUniqueIdB = provider.context.userUniqueId; 251 | provider.setUserId('A'); 252 | const userUniqueIdReturnA = provider.context.userUniqueId; 253 | const userIdMapping = StorageUtil.getUserIdMapping(); 254 | expect(userIdMapping).not.toBeNull(); 255 | expect('A' in userIdMapping).toBeTruthy(); 256 | expect('B' in userIdMapping).toBeTruthy(); 257 | expect(userUniqueIdNotLogin === userUniqueIdA).toBeTruthy(); 258 | expect(userUniqueIdB !== userUniqueIdA).toBeTruthy(); 259 | expect(userUniqueIdA === userUniqueIdReturnA).toBeTruthy(); 260 | expect( 261 | provider.userAttributes[ 262 | Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP 263 | ].value 264 | ).toBe(userFirstTouchTimestamp); 265 | }); 266 | 267 | test('test custom user attribute not in the subsequent event', async () => { 268 | (provider.configuration as any).sendMode = SendMode.Batch; 269 | provider.setUserId('123'); 270 | provider.setUserAttributes({ 271 | testAttribute: 'testValue', 272 | }); 273 | provider.record({ name: 'testEvent' }); 274 | await sleep(100); 275 | const eventList = JSON.parse( 276 | StorageUtil.getAllEvents() + Event.Constants.SUFFIX 277 | ); 278 | const lastEvent = eventList[eventList.length - 1]; 279 | expect(lastEvent.event_type).toBe('testEvent'); 280 | expect(lastEvent.user[Event.ReservedAttribute.USER_ID].value).toBe('123'); 281 | expect(lastEvent.user.testAttribute).toBeUndefined(); 282 | }); 283 | 284 | test('test add global attribute with invalid name', () => { 285 | const clickstreamAttribute: ClickstreamAttribute = {}; 286 | clickstreamAttribute['3abc'] = 'testValue'; 287 | provider.setGlobalAttributes(clickstreamAttribute); 288 | const { ERROR_CODE, ERROR_MESSAGE } = Event.ReservedAttribute; 289 | expect(mockProviderCreateEvent).toHaveBeenCalledWith( 290 | expect.objectContaining({ 291 | name: Event.PresetEvent.CLICKSTREAM_ERROR, 292 | attributes: { 293 | [ERROR_CODE]: Event.ErrorCode.ATTRIBUTE_NAME_INVALID, 294 | [ERROR_MESSAGE]: expect.anything(), 295 | }, 296 | }) 297 | ); 298 | }); 299 | 300 | test('test delete global attribute', () => { 301 | const clickstreamAttribute: ClickstreamAttribute = { 302 | _channel: 'SMS', 303 | }; 304 | provider.setGlobalAttributes(clickstreamAttribute); 305 | expect(provider.globalAttributes['_channel']).toBe('SMS'); 306 | provider.setGlobalAttributes({ 307 | _channel: null, 308 | }); 309 | expect(provider.globalAttributes['_channel']).toBeUndefined(); 310 | }); 311 | 312 | function sleep(ms: number): Promise { 313 | return new Promise(resolve => setTimeout(resolve, ms)); 314 | } 315 | }); 316 | -------------------------------------------------------------------------------- /test/provider/EventChecker.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { EventChecker, Event } from '../../src/provider'; 5 | 6 | describe('Event test', () => { 7 | test('test checkEventName with no error', () => { 8 | const error = EventChecker.checkEventName('testEvent'); 9 | expect(error.error_code).toEqual(Event.ErrorCode.NO_ERROR); 10 | }); 11 | test('test checkEventName with invalid name', () => { 12 | const error = EventChecker.checkEventName('1abc'); 13 | expect(error.error_code).toEqual(Event.ErrorCode.EVENT_NAME_INVALID); 14 | }); 15 | 16 | test('test checkEventName with name length exceed', () => { 17 | let longName = ''; 18 | for (let i = 0; i < 10; i++) { 19 | longName += 'abcdeabcdef'; 20 | } 21 | const error = EventChecker.checkEventName(longName); 22 | expect(error.error_code).toEqual(Event.ErrorCode.EVENT_NAME_LENGTH_EXCEED); 23 | }); 24 | 25 | test('test isValidName method', () => { 26 | expect(EventChecker.isValidName('testName')).toBeTruthy(); 27 | expect(EventChecker.isValidName('_app_start')).toBeTruthy(); 28 | expect(EventChecker.isValidName('AAA')).toBeTruthy(); 29 | expect(EventChecker.isValidName('a_ab')).toBeTruthy(); 30 | expect(EventChecker.isValidName('a_ab_1A')).toBeTruthy(); 31 | expect(EventChecker.isValidName('add_to_cart')).toBeTruthy(); 32 | expect(EventChecker.isValidName('Screen_view')).toBeTruthy(); 33 | expect(EventChecker.isValidName('')).toBeFalsy(); 34 | expect(EventChecker.isValidName('*&')).toBeFalsy(); 35 | expect(EventChecker.isValidName('0abc')).toBeFalsy(); 36 | expect(EventChecker.isValidName('123')).toBeFalsy(); 37 | }); 38 | }); 39 | -------------------------------------------------------------------------------- /test/provider/EventRecorder.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { BrowserInfo } from '../../src/browser'; 5 | import { NetRequest } from '../../src/network/NetRequest'; 6 | import { 7 | AnalyticsEventBuilder, 8 | ClickstreamContext, 9 | EventRecorder, 10 | } from '../../src/provider'; 11 | import { Session } from '../../src/tracker'; 12 | import { AnalyticsEvent, Item, SendMode } from '../../src/types'; 13 | import { StorageUtil } from '../../src/util/StorageUtil'; 14 | 15 | describe('EventRecorder test', () => { 16 | let eventRecorder: EventRecorder; 17 | let context: ClickstreamContext; 18 | beforeEach(() => { 19 | StorageUtil.clearAll() 20 | context = new ClickstreamContext(new BrowserInfo(), { 21 | appId: 'testApp', 22 | endpoint: 'https://localhost:8080/collect', 23 | sendMode: SendMode.Batch, 24 | }); 25 | eventRecorder = new EventRecorder(context); 26 | const mockSendRequest = jest.fn().mockResolvedValue(true); 27 | jest.spyOn(NetRequest, 'sendRequest').mockImplementation(mockSendRequest); 28 | }); 29 | 30 | afterEach(() => { 31 | jest.restoreAllMocks(); 32 | jest.clearAllMocks(); 33 | }); 34 | 35 | test('test getBatchEvents for empty cache', () => { 36 | const [eventsJson, needsFlush] = eventRecorder.getBatchEvents(); 37 | expect(eventsJson).toBe(''); 38 | expect(needsFlush).toBeFalsy(); 39 | }); 40 | 41 | test('test getBatchEvents for not reached the max request events size', async () => { 42 | const event = await getTestEvent(); 43 | eventRecorder.record(event); 44 | eventRecorder.record(event); 45 | const [eventsJson, needsFlush] = eventRecorder.getBatchEvents(); 46 | expect(JSON.parse(eventsJson).length).toBe(2); 47 | expect(needsFlush).toBeFalsy(); 48 | }); 49 | 50 | test('test getBatchEvents for reached the max request events size', async () => { 51 | await saveEventsForReachedOneRequestLimit(); 52 | const [eventsJson, needsFlush] = eventRecorder.getBatchEvents(); 53 | expect(JSON.parse(eventsJson).length).toBe(5); 54 | expect(needsFlush).toBeTruthy(); 55 | }); 56 | 57 | test('test getBatchEvents for only one large event', async () => { 58 | const event = await getLargeEventExceed512k(); 59 | StorageUtil.saveEvent(event); 60 | const [eventsJson, needsFlush] = eventRecorder.getBatchEvents(); 61 | expect(JSON.parse(eventsJson).length).toBe(1); 62 | expect(needsFlush).toBeFalsy(); 63 | }); 64 | 65 | test('test getBatchEvents for only one large event with large items', async () => { 66 | const event = await getLargeEventExceed512k(); 67 | const items: Item[] = []; 68 | const longValue = 'a'.repeat(255); 69 | const item: Item = { 70 | id: longValue, 71 | name: longValue, 72 | brand: longValue, 73 | category: longValue, 74 | category2: longValue, 75 | category3: longValue, 76 | category4: longValue, 77 | category5: longValue, 78 | creative_name: longValue, 79 | creative_slot: longValue, 80 | location_id: longValue, 81 | price: 99.9, 82 | currency: '$', 83 | quantity: 1000000, 84 | }; 85 | for (let i = 0; i < 100; i++) { 86 | items.push(item); 87 | } 88 | event.items = items; 89 | StorageUtil.saveEvent(event); 90 | const [eventsJson, needsFlush] = eventRecorder.getBatchEvents(); 91 | expect(JSON.parse(eventsJson).length).toBe(1); 92 | expect(needsFlush).toBeFalsy(); 93 | }); 94 | 95 | test('test getBatchEvents for have large event', async () => { 96 | const event = await getLargeEventExceed512k(); 97 | StorageUtil.saveEvent(event); 98 | const testEvent = await getTestEvent(); 99 | StorageUtil.saveEvent(testEvent); 100 | const [eventsJson, needsFlush] = eventRecorder.getBatchEvents(); 101 | expect(JSON.parse(eventsJson).length).toBe(1); 102 | expect(needsFlush).toBeTruthy(); 103 | }); 104 | 105 | test('test flush one events', async () => { 106 | eventRecorder.context.configuration.isLogEvents = true; 107 | const sendRequestMock = jest.spyOn(NetRequest, 'sendRequest'); 108 | const event = await getTestEvent(); 109 | eventRecorder.record(event); 110 | eventRecorder.flushEvents(); 111 | await sleep(100); 112 | expect(sendRequestMock).toBeCalled(); 113 | expect(StorageUtil.getAllEvents()).toBe(''); 114 | expect(eventRecorder.bundleSequenceId).toBe(2); 115 | }); 116 | 117 | test('test flush multiple events', async () => { 118 | const sendRequestMock = jest.spyOn(NetRequest, 'sendRequest'); 119 | const event = await getTestEvent(); 120 | eventRecorder.record(event); 121 | eventRecorder.record(event); 122 | eventRecorder.flushEvents(); 123 | await sleep(100); 124 | expect(sendRequestMock).toBeCalled(); 125 | expect(StorageUtil.getAllEvents()).toBe(''); 126 | expect(eventRecorder.bundleSequenceId).toBe(2); 127 | }); 128 | 129 | test('test flush events needs flush twice', async () => { 130 | const sendRequestMock = jest.spyOn(NetRequest, 'sendRequest'); 131 | await saveEventsForReachedOneRequestLimit(); 132 | eventRecorder.flushEvents(); 133 | await sleep(100); 134 | expect(sendRequestMock).toBeCalled(); 135 | expect(StorageUtil.getAllEvents()).toBe(''); 136 | expect(eventRecorder.bundleSequenceId).toBe(3); 137 | }); 138 | 139 | test('test flush event when flushing', async () => { 140 | const event = await getTestEvent(); 141 | eventRecorder.record(event); 142 | eventRecorder.flushEvents(); 143 | eventRecorder.flushEvents(); 144 | expect(eventRecorder.isFlushingEvents).toBeTruthy(); 145 | }); 146 | 147 | test('test record event reached max batch cache limit', async () => { 148 | const sendEventImmediateMock = jest.spyOn( 149 | eventRecorder, 150 | 'sendEventImmediate' 151 | ); 152 | const event = await getLargeEvent(); 153 | for (let i = 0; i < 11; i++) { 154 | eventRecorder.record(event); 155 | } 156 | expect(sendEventImmediateMock).toBeCalled(); 157 | }); 158 | 159 | test('test send failed events when window is closing ', async () => { 160 | const clearFailedEventsMock = jest.spyOn(StorageUtil, 'clearFailedEvents'); 161 | StorageUtil.saveFailedEvent(await getTestEvent()); 162 | eventRecorder.haveFailedEvents = true; 163 | eventRecorder.sendEventsInBackground(true); 164 | expect(clearFailedEventsMock).toBeCalled(); 165 | }); 166 | 167 | test('test do not send events when window is closing and event size is exceed max keep alive size limit', async () => { 168 | const flushEventsMock = jest.spyOn(eventRecorder, 'flushEvents'); 169 | const clearAllEventsMock = jest.spyOn(StorageUtil, 'clearAllEvents'); 170 | StorageUtil.saveEvent(await getLargeEvent()); 171 | eventRecorder.sendEventsInBackground(true); 172 | expect(flushEventsMock).not.toBeCalled(); 173 | expect(clearAllEventsMock).not.toBeCalled(); 174 | }); 175 | 176 | test('test send failed events twice', () => { 177 | const getFailedEventsMock = jest.spyOn(StorageUtil, 'getFailedEvents'); 178 | eventRecorder.sendFailedEvents(); 179 | eventRecorder.sendFailedEvents(); 180 | expect(getFailedEventsMock).toBeCalledTimes(1); 181 | }); 182 | 183 | test('test immediate mode send failure events when an event is sent successfully', async () => { 184 | const sendFailedEventsMock = jest.spyOn(eventRecorder, 'sendFailedEvents'); 185 | const event = await getTestEvent(); 186 | eventRecorder.haveFailedEvents = true; 187 | eventRecorder.sendEventImmediate(event); 188 | await sleep(100); 189 | expect(sendFailedEventsMock).toBeCalled(); 190 | }); 191 | 192 | async function saveEventsForReachedOneRequestLimit() { 193 | const event = await getLargeEvent(); 194 | for (let i = 0; i < 6; i++) { 195 | StorageUtil.saveEvent(event); 196 | } 197 | } 198 | 199 | async function getLargeEvent() { 200 | const event = await getTestEvent('testLargeEvent'); 201 | let longValue = ''; 202 | const str = 'abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde'; 203 | for (let i = 0; i < 20; i++) { 204 | longValue += str; 205 | } 206 | for (let i = 0; i < 100; i++) { 207 | event.attributes['attribute' + i] = longValue + i; 208 | } 209 | return event; 210 | } 211 | 212 | async function getLargeEventExceed512k() { 213 | const event = await getTestEvent('testLargeOneEvent'); 214 | const longValue = 'a'.repeat(1020); 215 | for (let i = 0; i < 500; i++) { 216 | event.attributes['attribute' + i] = longValue + i; 217 | } 218 | const longUserValue = 'b'.repeat(252); 219 | for (let i = 0; i < 500; i++) { 220 | event.user['attribute' + i] = { 221 | set_timestamp: new Date().getTime(), 222 | value: longUserValue + i, 223 | }; 224 | } 225 | return event; 226 | } 227 | 228 | async function getTestEvent( 229 | eventName = 'testEvent' 230 | ): Promise { 231 | return AnalyticsEventBuilder.createEvent( 232 | context, 233 | { name: eventName }, 234 | {}, 235 | Session.getCurrentSession(context) 236 | ); 237 | } 238 | 239 | function sleep(ms: number): Promise { 240 | return new Promise(resolve => setTimeout(resolve, ms)); 241 | } 242 | }); 243 | -------------------------------------------------------------------------------- /test/provider/ImmediateModeCache.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { ClickstreamAnalytics } from '../../src'; 5 | import { NetRequest } from '../../src/network/NetRequest'; 6 | import { Event } from '../../src/provider'; 7 | import { StorageUtil } from '../../src/util/StorageUtil'; 8 | import { setUpBrowserPerformance } from '../browser/BrowserUtil'; 9 | 10 | describe('ImmediateModeCache test', () => { 11 | beforeEach(() => { 12 | setUpBrowserPerformance(); 13 | const mockSendRequestFail = jest.fn().mockResolvedValue(false); 14 | jest 15 | .spyOn(NetRequest, 'sendRequest') 16 | .mockImplementation(mockSendRequestFail); 17 | }); 18 | 19 | afterEach(() => { 20 | ClickstreamAnalytics['provider'] = undefined; 21 | jest.resetAllMocks(); 22 | }); 23 | 24 | test('test record event failed and stores the event then send the event', async () => { 25 | const sendRequestMock = jest.spyOn(NetRequest, 'sendRequest'); 26 | ClickstreamAnalytics.init({ 27 | appId: 'testApp', 28 | endpoint: 'https://localhost:8080/failed', 29 | }); 30 | ClickstreamAnalytics.record({ 31 | name: 'testEvent', 32 | }); 33 | await sleep(100); 34 | expect(sendRequestMock).toBeCalled(); 35 | const failedEvents = JSON.parse( 36 | StorageUtil.getFailedEvents() + Event.Constants.SUFFIX 37 | ); 38 | expect(failedEvents.length).toBeGreaterThan(3); 39 | const mockSendRequestSuccess = jest.fn().mockResolvedValue(true); 40 | jest 41 | .spyOn(NetRequest, 'sendRequest') 42 | .mockImplementation(mockSendRequestSuccess); 43 | const provider = ClickstreamAnalytics['provider']; 44 | provider.configure({ 45 | appId: 'testAppId', 46 | endpoint: 'https://example.com/collect', 47 | }); 48 | await sleep(100); 49 | expect(StorageUtil.getFailedEvents().length).toBe(0); 50 | }); 51 | 52 | function sleep(ms: number): Promise { 53 | return new Promise(resolve => setTimeout(resolve, ms)); 54 | } 55 | }); 56 | -------------------------------------------------------------------------------- /test/tracker/ClickTracker.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { SendMode } from '../../src'; 5 | import { BrowserInfo } from '../../src/browser'; 6 | import { 7 | ClickstreamContext, 8 | ClickstreamProvider, 9 | Event, 10 | EventRecorder, 11 | } from '../../src/provider'; 12 | import { Session, SessionTracker } from '../../src/tracker'; 13 | import { ClickTracker } from '../../src/tracker/ClickTracker'; 14 | import { StorageUtil } from "../../src/util/StorageUtil"; 15 | 16 | describe('ClickTracker test', () => { 17 | let provider: ClickstreamProvider; 18 | let clickTracker: ClickTracker; 19 | let context: ClickstreamContext; 20 | let recordMethodMock: any; 21 | 22 | beforeEach(() => { 23 | StorageUtil.clearAll() 24 | provider = new ClickstreamProvider(); 25 | Object.assign(provider.configuration, { 26 | appId: 'testAppId', 27 | endpoint: 'https://example.com/click', 28 | sendMode: SendMode.Batch, 29 | domainList: ['example1.com', 'example2.com'], 30 | }); 31 | context = new ClickstreamContext(new BrowserInfo(), provider.configuration); 32 | const sessionTracker = new SessionTracker(provider, context); 33 | sessionTracker.session = Session.getCurrentSession(context); 34 | provider.sessionTracker = sessionTracker; 35 | provider.context = context; 36 | provider.eventRecorder = new EventRecorder(context); 37 | clickTracker = new ClickTracker(provider, context); 38 | recordMethodMock = jest.spyOn(provider, 'record'); 39 | }); 40 | 41 | afterEach(() => { 42 | recordMethodMock.mockClear(); 43 | jest.restoreAllMocks(); 44 | provider = undefined; 45 | }); 46 | 47 | test('test setup not in the browser env', () => { 48 | const addEventListenerMock = jest.spyOn(document, 'addEventListener'); 49 | jest.spyOn(BrowserInfo, 'isBrowser').mockReturnValue(false); 50 | clickTracker.setUp(); 51 | expect(addEventListenerMock).not.toBeCalled(); 52 | }); 53 | 54 | test('test not for click a element', () => { 55 | const trackClickMock = jest.spyOn(clickTracker, 'trackClick'); 56 | clickTracker.setUp(); 57 | window.document.dispatchEvent(new window.Event('click')); 58 | expect(recordMethodMock).not.toBeCalled(); 59 | expect(trackClickMock).not.toBeCalled(); 60 | }); 61 | 62 | test('test click a element with current domain', () => { 63 | const clickEvent = getMockMouseEvent( 64 | 'A', 65 | 'https://localhost/collect', 66 | 'link-class', 67 | 'link-id' 68 | ); 69 | clickTracker.setUp(); 70 | clickTracker.trackClick(clickEvent); 71 | expect(recordMethodMock).toBeCalledWith({ 72 | name: Event.PresetEvent.CLICK, 73 | attributes: { 74 | [Event.ReservedAttribute.LINK_URL]: 'https://localhost/collect', 75 | [Event.ReservedAttribute.LINK_DOMAIN]: 'localhost', 76 | [Event.ReservedAttribute.LINK_CLASSES]: 'link-class', 77 | [Event.ReservedAttribute.LINK_ID]: 'link-id', 78 | [Event.ReservedAttribute.OUTBOUND]: false, 79 | }, 80 | }); 81 | }); 82 | 83 | test('test disable the configuration for track click event', () => { 84 | provider.configuration.isTrackClickEvents = false; 85 | const clickEvent = getMockMouseEvent( 86 | 'A', 87 | 'https://localhost/collect', 88 | 'link-class', 89 | 'link-id' 90 | ); 91 | clickTracker.setUp(); 92 | clickTracker.trackClick(clickEvent); 93 | expect(recordMethodMock).not.toBeCalled(); 94 | }); 95 | 96 | test('test click a element in configured domain', () => { 97 | const clickEvent = getMockMouseEvent( 98 | 'A', 99 | 'https://example1.com/collect', 100 | 'link-class', 101 | 'link-id' 102 | ); 103 | clickTracker.setUp(); 104 | clickTracker.trackClick(clickEvent); 105 | expect(recordMethodMock).toBeCalledWith({ 106 | name: Event.PresetEvent.CLICK, 107 | attributes: { 108 | [Event.ReservedAttribute.LINK_URL]: 'https://example1.com/collect', 109 | [Event.ReservedAttribute.LINK_DOMAIN]: 'example1.com', 110 | [Event.ReservedAttribute.LINK_CLASSES]: 'link-class', 111 | [Event.ReservedAttribute.LINK_ID]: 'link-id', 112 | [Event.ReservedAttribute.OUTBOUND]: false, 113 | }, 114 | }); 115 | }); 116 | 117 | test('test click a element without link', () => { 118 | const clickEvent = getMockMouseEvent('A', '', 'link-class', 'link-id'); 119 | clickTracker.setUp(); 120 | clickTracker.trackClick(clickEvent); 121 | expect(recordMethodMock).not.toBeCalled(); 122 | }); 123 | 124 | test('test click a element without host', () => { 125 | const clickEvent = getMockMouseEvent( 126 | 'A', 127 | '/products', 128 | 'link-class', 129 | 'link-id' 130 | ); 131 | clickTracker.setUp(); 132 | clickTracker.trackClick(clickEvent); 133 | expect(recordMethodMock).not.toBeCalled(); 134 | }); 135 | 136 | test('test click a element with outbound', () => { 137 | const clickEvent = getMockMouseEvent( 138 | 'A', 139 | 'https://example3.com', 140 | 'link-class', 141 | 'link-id' 142 | ); 143 | clickTracker.setUp(); 144 | clickTracker.trackClick(clickEvent); 145 | expect(recordMethodMock).toBeCalledWith({ 146 | name: Event.PresetEvent.CLICK, 147 | attributes: { 148 | [Event.ReservedAttribute.LINK_URL]: 'https://example3.com', 149 | [Event.ReservedAttribute.LINK_DOMAIN]: 'example3.com', 150 | [Event.ReservedAttribute.LINK_CLASSES]: 'link-class', 151 | [Event.ReservedAttribute.LINK_ID]: 'link-id', 152 | [Event.ReservedAttribute.OUTBOUND]: true, 153 | }, 154 | }); 155 | }); 156 | 157 | test('test click a element wrapped by a tag', () => { 158 | const clickEvent = getMockMouseEvent('SPAN', '', '', ''); 159 | const targetElement = document.createElement('A'); 160 | targetElement.setAttribute('href', 'https://example.com'); 161 | targetElement.setAttribute('class', 'link-class'); 162 | targetElement.setAttribute('id', 'link-id'); 163 | Object.defineProperty(clickEvent.target, 'parentElement', { 164 | writable: true, 165 | value: targetElement, 166 | }); 167 | clickTracker.setUp(); 168 | clickTracker.trackClick(clickEvent); 169 | expect(recordMethodMock).toBeCalledWith({ 170 | name: Event.PresetEvent.CLICK, 171 | attributes: { 172 | [Event.ReservedAttribute.LINK_URL]: 'https://example.com', 173 | [Event.ReservedAttribute.LINK_DOMAIN]: 'example.com', 174 | [Event.ReservedAttribute.LINK_CLASSES]: 'link-class', 175 | [Event.ReservedAttribute.LINK_ID]: 'link-id', 176 | [Event.ReservedAttribute.OUTBOUND]: true, 177 | }, 178 | }); 179 | }); 180 | 181 | test('test click a element with out a tag in parent', () => { 182 | const clickEvent = getMockMouseEvent('SPAN', '', '', ''); 183 | const targetElement = document.createElement('SPAN'); 184 | Object.defineProperty(clickEvent.target, 'parentElement', { 185 | writable: true, 186 | value: targetElement, 187 | }); 188 | clickTracker.setUp(); 189 | clickTracker.trackClick(clickEvent); 190 | expect(recordMethodMock).not.toBeCalled(); 191 | }); 192 | 193 | test('test add A tag and trigger MutationObserver', async () => { 194 | clickTracker.setUp(); 195 | const div = document.createElement('div'); 196 | const aTag = document.createElement('A'); 197 | div.appendChild(aTag); 198 | document.body.appendChild(div); 199 | await sleep(100); 200 | expect(clickTracker.processedElements.has(aTag)).toBeTruthy(); 201 | }); 202 | 203 | test('test track click event with document listener', async () => { 204 | const trackDocumentClickMethodMock = jest.spyOn( 205 | clickTracker, 206 | 'trackDocumentClick' 207 | ); 208 | const trackClickMethodMock = jest.spyOn(clickTracker, 'trackClick'); 209 | jest.spyOn(clickTracker.processedElements, 'has').mockReturnValue(false); 210 | clickTracker.setUp(); 211 | const div = document.createElement('div'); 212 | const aTag = document.createElement('A'); 213 | aTag.setAttribute('href', 'https://example.com'); 214 | div.appendChild(aTag); 215 | document.body.appendChild(div); 216 | const clickEvent = new MouseEvent('click', { 217 | bubbles: true, 218 | cancelable: true, 219 | view: window, 220 | }); 221 | aTag.dispatchEvent(clickEvent); 222 | expect(trackDocumentClickMethodMock).toBeCalledTimes(1); 223 | expect(trackClickMethodMock).toBeCalledTimes(1); 224 | expect(recordMethodMock).toBeCalledTimes(1); 225 | }); 226 | 227 | function getMockMouseEvent( 228 | tagName: string, 229 | href: string, 230 | className: string, 231 | id: string 232 | ) { 233 | const event = document.createEvent('MouseEvents'); 234 | const targetElement = document.createElement(tagName); 235 | targetElement.setAttribute('href', href); 236 | targetElement.setAttribute('class', className); 237 | targetElement.setAttribute('id', id); 238 | Object.defineProperty(event, 'target', { 239 | writable: true, 240 | value: targetElement, 241 | }); 242 | return event; 243 | } 244 | 245 | function sleep(ms: number): Promise { 246 | return new Promise(resolve => setTimeout(resolve, ms)); 247 | } 248 | }); 249 | -------------------------------------------------------------------------------- /test/tracker/PageLoadTracker.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { SendMode } from '../../src'; 5 | import { BrowserInfo } from '../../src/browser'; 6 | import { 7 | ClickstreamContext, 8 | ClickstreamProvider, 9 | EventRecorder, 10 | } from '../../src/provider'; 11 | import { Session, SessionTracker } from '../../src/tracker'; 12 | import { PageLoadTracker } from '../../src/tracker/PageLoadTracker'; 13 | import { setPerformanceEntries } from '../browser/BrowserUtil'; 14 | import { MockObserver } from '../browser/MockObserver'; 15 | import { StorageUtil } from "../../src/util/StorageUtil"; 16 | 17 | describe('PageLoadTracker test', () => { 18 | let provider: ClickstreamProvider; 19 | let pageLoadTracker: PageLoadTracker; 20 | let context: ClickstreamContext; 21 | let recordMethodMock: any; 22 | 23 | beforeEach(() => { 24 | StorageUtil.clearAll() 25 | provider = new ClickstreamProvider(); 26 | Object.assign(provider.configuration, { 27 | appId: 'testAppId', 28 | endpoint: 'https://example.com/collect', 29 | sendMode: SendMode.Batch, 30 | isTrackPageLoadEvents: true, 31 | }); 32 | context = new ClickstreamContext(new BrowserInfo(), provider.configuration); 33 | const sessionTracker = new SessionTracker(provider, context); 34 | sessionTracker.session = Session.getCurrentSession(context); 35 | recordMethodMock = jest.spyOn(provider, 'record'); 36 | provider.context = context; 37 | provider.eventRecorder = new EventRecorder(context); 38 | provider.sessionTracker = sessionTracker; 39 | pageLoadTracker = new PageLoadTracker(provider, context); 40 | provider.sessionTracker = sessionTracker; 41 | (global as any).PerformanceObserver = MockObserver; 42 | }); 43 | 44 | afterEach(() => { 45 | recordMethodMock.mockClear(); 46 | jest.restoreAllMocks(); 47 | provider = undefined; 48 | }); 49 | 50 | test('test setup not in the browser env', () => { 51 | jest.spyOn(BrowserInfo, 'isBrowser').mockReturnValue(false); 52 | pageLoadTracker.setUp(); 53 | }); 54 | 55 | test('test in supported env ', () => { 56 | expect(pageLoadTracker.isSupportedEnv()).toBeTruthy(); 57 | }); 58 | 59 | test('test not in supported env ', () => { 60 | const performance = window.performance; 61 | setPerformanceUndefined(); 62 | expect(pageLoadTracker.isSupportedEnv()).toBeFalsy(); 63 | Object.defineProperty(window, 'performance', { 64 | writable: true, 65 | value: performance, 66 | }); 67 | }); 68 | 69 | test('test page not loaded when performanceEntries is undefined', () => { 70 | Object.defineProperty(window, 'performance', { 71 | writable: true, 72 | value: { 73 | getEntriesByType: jest.fn().mockImplementation(undefined), 74 | }, 75 | }); 76 | expect(pageLoadTracker.isPageLoaded()).toBeFalsy(); 77 | }); 78 | 79 | test('test page not loaded when performanceEntries is empty', () => { 80 | Object.defineProperty(window, 'performance', { 81 | writable: true, 82 | value: { 83 | getEntriesByType: jest.fn().mockImplementation(() => { 84 | return ([]); 85 | }), 86 | }, 87 | }); 88 | expect(pageLoadTracker.isPageLoaded()).toBeFalsy(); 89 | }); 90 | 91 | test('test page loaded when initialize the SDK', () => { 92 | setPerformanceEntries(true); 93 | pageLoadTracker.setUp(); 94 | expect(recordMethodMock).toBeCalled(); 95 | }); 96 | 97 | test('test record page load event by PerformanceObserver', () => { 98 | setPerformanceEntries(false); 99 | pageLoadTracker.setUp(); 100 | setPerformanceEntries(true); 101 | (pageLoadTracker.observer as any).call(); 102 | expect(recordMethodMock).toBeCalled(); 103 | }); 104 | 105 | test('test not record page load event when configuration is disable', () => { 106 | setPerformanceEntries(false); 107 | pageLoadTracker.setUp(); 108 | provider.configuration.isTrackPageLoadEvents = false; 109 | setPerformanceEntries(true); 110 | (pageLoadTracker.observer as any).call(); 111 | expect(recordMethodMock).not.toBeCalled(); 112 | }); 113 | 114 | function setPerformanceUndefined() { 115 | Object.defineProperty(window, 'performance', { 116 | writable: true, 117 | value: undefined, 118 | }); 119 | } 120 | }); 121 | -------------------------------------------------------------------------------- /test/tracker/ScrollTracker.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { SendMode } from '../../src'; 5 | import { BrowserInfo } from '../../src/browser'; 6 | import { 7 | ClickstreamContext, 8 | ClickstreamProvider, 9 | EventRecorder, 10 | } from '../../src/provider'; 11 | import { Session, SessionTracker, PageViewTracker } from '../../src/tracker'; 12 | import { ScrollTracker } from '../../src/tracker/ScrollTracker'; 13 | import { StorageUtil } from '../../src/util/StorageUtil'; 14 | 15 | describe('ScrollTracker test', () => { 16 | let provider: ClickstreamProvider; 17 | let scrollTracker: ScrollTracker; 18 | let context: ClickstreamContext; 19 | let recordMethodMock: any; 20 | 21 | beforeEach(() => { 22 | StorageUtil.clearAll(); 23 | provider = new ClickstreamProvider(); 24 | 25 | Object.assign(provider.configuration, { 26 | appId: 'testAppId', 27 | endpoint: 'https://example.com/collect', 28 | sendMode: SendMode.Batch, 29 | }); 30 | context = new ClickstreamContext(new BrowserInfo(), provider.configuration); 31 | const sessionTracker = new SessionTracker(provider, context); 32 | sessionTracker.session = Session.getCurrentSession(context); 33 | provider.context = context; 34 | provider.eventRecorder = new EventRecorder(context); 35 | provider.sessionTracker = sessionTracker; 36 | scrollTracker = new ScrollTracker(provider, context); 37 | provider.sessionTracker = sessionTracker; 38 | recordMethodMock = jest.spyOn(provider, 'record'); 39 | }); 40 | 41 | afterEach(() => { 42 | recordMethodMock.mockClear(); 43 | jest.restoreAllMocks(); 44 | provider = undefined; 45 | }); 46 | 47 | test('test setup not in the browser env', () => { 48 | jest.spyOn(BrowserInfo, 'isBrowser').mockReturnValue(false); 49 | scrollTracker.setUp(); 50 | }); 51 | 52 | test('test setup', () => { 53 | scrollTracker.setUp(); 54 | expect(scrollTracker.isFirstTime).toBeTruthy(); 55 | }); 56 | 57 | test('test scroll for not reach ninety percent', async () => { 58 | const trackScrollMock = jest.spyOn(scrollTracker, 'trackScroll'); 59 | scrollTracker.setUp(); 60 | setScrollHeight(2000); 61 | (window as any).innerHeight = 1000; 62 | setScrollY(100); 63 | window.document.dispatchEvent(new window.Event('scroll')); 64 | await sleep(110); 65 | expect(recordMethodMock).not.toBeCalled(); 66 | expect(trackScrollMock).toBeCalled(); 67 | }); 68 | 69 | test('test scroll for reached ninety percent', async () => { 70 | const trackScrollMock = jest.spyOn(scrollTracker, 'trackScroll'); 71 | scrollTracker.setUp(); 72 | await performScrollToBottom(); 73 | await sleep(110); 74 | expect(recordMethodMock).toBeCalled(); 75 | expect(trackScrollMock).toBeCalled(); 76 | expect(scrollTracker.isFirstTime).toBeFalsy(); 77 | }); 78 | 79 | test('test window scroll for reached ninety percent using scrollTop api', async () => { 80 | const trackScrollMock = jest.spyOn(scrollTracker, 'trackScroll'); 81 | scrollTracker.setUp(); 82 | Object.defineProperty(window, 'scrollY', { 83 | writable: true, 84 | value: undefined, 85 | }); 86 | setScrollHeight(1000); 87 | (window as any).innerHeight = 800; 88 | Object.defineProperty(document.documentElement, 'scrollTop', { 89 | writable: true, 90 | value: 150, 91 | }); 92 | window.document.dispatchEvent(new window.Event('scroll')); 93 | await sleep(110); 94 | expect(trackScrollMock).toBeCalled(); 95 | expect(recordMethodMock).toBeCalled(); 96 | }); 97 | 98 | test('test scroll for reached ninety percent and scroll event is disabled', async () => { 99 | const trackScrollMock = jest.spyOn(scrollTracker, 'trackScroll'); 100 | provider.configuration.isTrackScrollEvents = false; 101 | scrollTracker.setUp(); 102 | await performScrollToBottom(); 103 | expect(trackScrollMock).toBeCalled(); 104 | expect(recordMethodMock).not.toBeCalled(); 105 | }); 106 | 107 | test('test scroll for reached ninety percent twice', async () => { 108 | const trackScrollMock = jest.spyOn(scrollTracker, 'trackScroll'); 109 | scrollTracker.setUp(); 110 | await performScrollToBottom(); 111 | window.document.dispatchEvent(new window.Event('scroll')); 112 | await sleep(110); 113 | expect(recordMethodMock).toBeCalledTimes(1); 114 | expect(trackScrollMock).toBeCalledTimes(2); 115 | expect(scrollTracker.isFirstTime).toBeFalsy(); 116 | }); 117 | 118 | test('test scroll for enter new page', async () => { 119 | const trackScrollMock = jest.spyOn(scrollTracker, 'trackScroll'); 120 | scrollTracker.setUp(); 121 | await performScrollToBottom(); 122 | scrollTracker.enterNewPage(); 123 | expect(scrollTracker.isFirstTime).toBeTruthy(); 124 | window.document.dispatchEvent(new window.Event('scroll')); 125 | await sleep(110); 126 | expect(recordMethodMock).toBeCalledTimes(2); 127 | expect(trackScrollMock).toBeCalledTimes(2); 128 | expect(scrollTracker.isFirstTime).toBeFalsy(); 129 | }); 130 | 131 | test('test mouse move will update the idle duration', async () => { 132 | const onMouseMoveMock = jest.spyOn(scrollTracker, 'onMouseMove'); 133 | scrollTracker.setUp(); 134 | window.document.dispatchEvent(new window.Event('mousemove')); 135 | await sleep(110); 136 | expect(onMouseMoveMock).toBeCalled(); 137 | expect(PageViewTracker.lastActiveTimestamp > 0).toBeTruthy(); 138 | }); 139 | 140 | async function performScrollToBottom() { 141 | setScrollHeight(1000); 142 | (window as any).innerHeight = 800; 143 | setScrollY(150); 144 | window.document.dispatchEvent(new window.Event('scroll')); 145 | await sleep(110); 146 | } 147 | 148 | function setScrollHeight(height: number) { 149 | Object.defineProperty(window.document.body, 'scrollHeight', { 150 | writable: true, 151 | value: height, 152 | }); 153 | } 154 | 155 | function setScrollY(height: number) { 156 | Object.defineProperty(window, 'scrollY', { 157 | writable: true, 158 | value: height, 159 | }); 160 | } 161 | 162 | function sleep(ms: number): Promise { 163 | return new Promise(resolve => setTimeout(resolve, ms)); 164 | } 165 | }); 166 | -------------------------------------------------------------------------------- /test/util/StorageUtil.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { BrowserInfo } from '../../src/browser'; 5 | import { 6 | AnalyticsEventBuilder, 7 | ClickstreamContext, 8 | Event, 9 | } from '../../src/provider'; 10 | import { Session } from '../../src/tracker'; 11 | import { AnalyticsEvent } from '../../src/types'; 12 | import { StorageUtil } from '../../src/util/StorageUtil'; 13 | 14 | describe('StorageUtil test', () => { 15 | beforeEach(() => { 16 | StorageUtil.clearAll() 17 | }); 18 | 19 | test('test get device id', () => { 20 | const deviceId = StorageUtil.getDeviceId(); 21 | expect(deviceId).not.toBeNull(); 22 | expect(deviceId.length > 0).toBeTruthy(); 23 | const deviceId1 = StorageUtil.getDeviceId(); 24 | expect(deviceId).toEqual(deviceId1); 25 | }); 26 | 27 | test('test get user Attributes return null object', () => { 28 | const userAttribute = StorageUtil.getAllUserAttributes(); 29 | expect(JSON.stringify(userAttribute)).toBe('{}'); 30 | }); 31 | 32 | test('test get current user unique id', () => { 33 | const userUniqueId = StorageUtil.getCurrentUserUniqueId(); 34 | expect(userUniqueId).not.toBeNull(); 35 | expect(userUniqueId.length > 0).toBeTruthy(); 36 | const userAttribute = StorageUtil.getAllUserAttributes(); 37 | expect(userAttribute).not.toBeNull(); 38 | expect(Object.keys(userAttribute).length > 0).toBeTruthy(); 39 | expect( 40 | userAttribute[Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP]['value'] 41 | ).not.toBeUndefined(); 42 | }); 43 | 44 | test('test save bundleSequenceId', () => { 45 | const initialBundleSequenceId = StorageUtil.getBundleSequenceId(); 46 | expect(initialBundleSequenceId).toBe(1); 47 | StorageUtil.saveBundleSequenceId(2); 48 | expect(StorageUtil.getBundleSequenceId()).toBe(2); 49 | }); 50 | 51 | test('test update userAttributes', () => { 52 | StorageUtil.updateUserAttributes({ 53 | userAge: { 54 | set_timestamp: new Date().getTime(), 55 | value: 18, 56 | }, 57 | userName: { 58 | set_timestamp: new Date().getTime(), 59 | value: 'carl', 60 | }, 61 | }); 62 | const userAttribute = StorageUtil.getAllUserAttributes(); 63 | expect(Object.keys(userAttribute).length).toBe(2); 64 | expect(userAttribute['userAge']['value']).toBe(18); 65 | }); 66 | 67 | test('test get simple user attributes', () => { 68 | const userId = Event.ReservedAttribute.USER_ID; 69 | const firstTimestamp = Event.ReservedAttribute.USER_FIRST_TOUCH_TIMESTAMP; 70 | const currentTimeStamp = new Date().getTime(); 71 | StorageUtil.updateUserAttributes({ 72 | [userId]: { 73 | set_timestamp: currentTimeStamp, 74 | value: 1234, 75 | }, 76 | [firstTimestamp]: { 77 | set_timestamp: currentTimeStamp, 78 | value: currentTimeStamp, 79 | }, 80 | userAge: { 81 | set_timestamp: currentTimeStamp, 82 | value: 18, 83 | }, 84 | }); 85 | const simpleUserAttribute = StorageUtil.getSimpleUserAttributes(); 86 | expect(Object.keys(simpleUserAttribute).length).toBe(2); 87 | expect(simpleUserAttribute[userId].value).toBe(1234); 88 | expect(simpleUserAttribute[firstTimestamp].value).toBe(currentTimeStamp); 89 | expect(simpleUserAttribute['userAge']).toBeUndefined(); 90 | }); 91 | 92 | test('test save and clear failed event', async () => { 93 | const event = await getTestEvent(); 94 | StorageUtil.saveFailedEvent(event); 95 | const failedEventsStr = StorageUtil.getFailedEvents(); 96 | const failedEvents = JSON.parse(failedEventsStr + Event.Constants.SUFFIX); 97 | expect(failedEvents.length).toBe(1); 98 | expect(failedEvents[0].event_id).toEqual(event.event_id); 99 | StorageUtil.clearFailedEvents(); 100 | const events = StorageUtil.getFailedEvents(); 101 | expect(events).toBe(''); 102 | }); 103 | 104 | test('test save failed events reached max failed event size', async () => { 105 | const event = await getLargeEvent(); 106 | for (let i = 0; i < 6; i++) { 107 | StorageUtil.saveFailedEvent(event); 108 | } 109 | const events = JSON.parse( 110 | StorageUtil.getFailedEvents() + Event.Constants.SUFFIX 111 | ); 112 | expect(events.length < 6).toBeTruthy(); 113 | }); 114 | 115 | test('test save event', async () => { 116 | const event = await getTestEvent(); 117 | StorageUtil.saveEvent(event); 118 | StorageUtil.saveEvent(event); 119 | const allEventsStr = StorageUtil.getAllEvents(); 120 | const allEvents = JSON.parse(allEventsStr + Event.Constants.SUFFIX); 121 | expect(allEvents.length).toBe(2); 122 | }); 123 | 124 | test('test save events reached max event size', async () => { 125 | const event = await getLargeEvent(); 126 | for (let i = 0; i < 11; i++) { 127 | StorageUtil.saveEvent(event); 128 | } 129 | const events = JSON.parse( 130 | StorageUtil.getAllEvents() + Event.Constants.SUFFIX 131 | ); 132 | expect(events.length < 11).toBeTruthy(); 133 | }); 134 | 135 | test('test save and clear one events', async () => { 136 | const event = await getTestEvent(); 137 | StorageUtil.saveEvent(event); 138 | StorageUtil.clearEvents(JSON.stringify([event])); 139 | expect(StorageUtil.getAllEvents()).toBe(''); 140 | }); 141 | 142 | test('test clear a part of events', async () => { 143 | const event1 = await getTestEvent('event1'); 144 | const event2 = await getTestEvent('event2'); 145 | StorageUtil.saveEvent(event1); 146 | StorageUtil.saveEvent(event2); 147 | StorageUtil.clearEvents(JSON.stringify([event1])); 148 | const leftEvents = JSON.parse( 149 | StorageUtil.getAllEvents() + Event.Constants.SUFFIX 150 | ); 151 | expect(leftEvents.length).toBe(1); 152 | expect(leftEvents[0].event_type).toBe('event2'); 153 | }); 154 | 155 | test('test save 1000 events parallel', () => { 156 | const promises = []; 157 | const eventCount = 1000; 158 | for (let i = 0; i < eventCount; i++) { 159 | promises.push(saveEvent()); 160 | } 161 | Promise.all(promises) 162 | .then(() => { 163 | console.log('finish'); 164 | const eventsStr = StorageUtil.getAllEvents() + Event.Constants.SUFFIX; 165 | expect(JSON.parse(eventsStr).length).toBe(eventCount); 166 | }) 167 | .catch(error => { 168 | console.error('error:', error); 169 | throw error; 170 | }); 171 | }); 172 | 173 | test('test clear page information', () => { 174 | StorageUtil.savePreviousPageTitle('pageA'); 175 | StorageUtil.savePreviousPageUrl('https://example.com/pageA'); 176 | StorageUtil.clearPageInfo(); 177 | expect(StorageUtil.getPreviousPageTitle()).toBe(''); 178 | expect(StorageUtil.getPreviousPageUrl()).toBe(''); 179 | }); 180 | 181 | async function saveEvent() { 182 | const event = await getTestEvent(); 183 | return StorageUtil.saveEvent(event); 184 | } 185 | 186 | async function getLargeEvent() { 187 | const event = await getTestEvent('LargeTestEvent'); 188 | let longValue = ''; 189 | const str = 'abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde'; 190 | for (let i = 0; i < 20; i++) { 191 | longValue += str; 192 | } 193 | for (let i = 0; i < 100; i++) { 194 | event.attributes['attribute' + i] = longValue + i; 195 | } 196 | return event; 197 | } 198 | 199 | async function getTestEvent( 200 | eventName = 'testEvent' 201 | ): Promise { 202 | const context = new ClickstreamContext(new BrowserInfo(), { 203 | appId: 'testApp', 204 | endpoint: 'https://example.com/collect', 205 | }); 206 | return AnalyticsEventBuilder.createEvent( 207 | context, 208 | { name: eventName }, 209 | {}, 210 | Session.getCurrentSession(context) 211 | ); 212 | } 213 | }); 214 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "esModuleInterop": true, 4 | "noImplicitAny": true, 5 | "lib": [ 6 | "dom", 7 | "dom.iterable", 8 | "es2019" 9 | ], 10 | "downlevelIteration": true, 11 | "target": "es5", 12 | "moduleResolution": "node", 13 | "declaration": true, 14 | "noEmitOnError": false, 15 | "importHelpers": true, 16 | "outDir": "lib", 17 | "resolveJsonModule": true, 18 | "allowJs": true, 19 | }, 20 | "include": [ 21 | "src" 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /webpack.config.dev.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | const config = require('./webpack.config.js'); 5 | 6 | const entry = { 'clickstream-web': './lib-esm/index.js' }; 7 | module.exports = Object.assign(config, { entry, mode: 'development' }); 8 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | const TerserPlugin = require('terser-webpack-plugin'); 5 | module.exports = { 6 | entry: { 'clickstream-web.min': './lib-esm/index.js' }, 7 | mode: 'production', 8 | output: { 9 | filename: '[name].js', 10 | path: __dirname + '/dist', 11 | library: { 12 | type: 'umd', 13 | }, 14 | umdNamedDefine: true, 15 | globalObject: 'this', 16 | }, 17 | devtool: 'source-map', 18 | resolve: { 19 | extensions: ['.js', '.json'], 20 | }, 21 | module: { 22 | rules: [ 23 | { 24 | test: /\.js?$/, 25 | exclude: /node_modules/, 26 | use: { 27 | loader: 'babel-loader', 28 | options: { 29 | presets: ['@babel/preset-env'], 30 | }, 31 | }, 32 | }, 33 | ], 34 | }, 35 | optimization: { 36 | minimizer: [ 37 | new TerserPlugin({ 38 | extractComments: false, 39 | }), 40 | ], 41 | }, 42 | }; 43 | --------------------------------------------------------------------------------