├── .github
└── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Gruntfile.js
├── LICENSE.txt
├── NOTICE.txt
├── README.md
├── bower.json
├── dist
├── aws-sdk-mobile-analytics.js
└── aws-sdk-mobile-analytics.min.js
├── doc
├── AMA.Client.html
├── AMA.Manager.html
├── AMA.Session.html
├── MobileAnalyticsClient.js.html
├── MobileAnalyticsSession.js.html
├── MobileAnalyticsSessionManager.js.html
├── ama.js.html
├── index.html
├── module-AMA.html
├── scripts
│ ├── linenumber.js
│ └── prettify
│ │ ├── Apache-License-2.0.txt
│ │ ├── lang-css.js
│ │ └── prettify.js
└── styles
│ ├── jsdoc-default.css
│ ├── prettify-jsdoc.css
│ └── prettify-tomorrow.css
├── grunttasks
├── blanket.js
├── browserify.js
├── clean.js
├── copy.js
├── jshint.js
├── mocha.js
├── mochaTest.js
└── uglify.js
├── lib
├── MobileAnalyticsClient.js
├── MobileAnalyticsSession.js
├── MobileAnalyticsSessionManager.js
├── MobileAnalyticsUtilities.js
├── StorageClients
│ ├── LocalStorage.js
│ └── StorageKeys.js
└── ama.js
├── package.json
└── test
├── browser
├── aws-sdk.min.js
├── mocha.css
├── mocha.js
└── unittests.html
├── helpers.coffee
├── mobileAnalyticsClient.coffee
├── mobileAnalyticsSessionClient.coffee
├── session.coffee
├── storage.coffee
├── utils.coffee
└── v090_migration_v091.coffee
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | *Issue #, if available:*
2 |
3 | *Description of changes:*
4 |
5 |
6 | By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/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/aws-sdk-mobile-analytics-js/issues), or [recently closed](https://github.com/aws/aws-sdk-mobile-analytics-js/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 *master* 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/aws-sdk-mobile-analytics-js/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/aws-sdk-mobile-analytics-js/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)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes.
62 |
--------------------------------------------------------------------------------
/Gruntfile.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
4 | the License. A copy of the License is located at http://aws.amazon.com/apache2.0/
5 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6 | CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
7 | and limitations under the License.
8 | */
9 |
10 | module.exports = function (grunt) {
11 | 'use strict';
12 |
13 | require('load-grunt-tasks')(grunt);
14 | grunt.loadTasks('grunttasks');
15 |
16 | // server-side tests
17 | grunt.registerTask('test-nodejs', ['blanket', 'copy:test-setup', 'mochaTest']);
18 | // client-side tests
19 | grunt.registerTask('test-phantomjs', ['copy:test-setup', 'copy:browserify-test-setup', 'copy:browserify-dist-setup', 'browserify:test', 'uglify:test', 'mocha']);
20 |
21 | // test, dist and release
22 | grunt.registerTask('test', ['jshint', 'test-nodejs', 'test-phantomjs']);
23 | grunt.registerTask('dist', ['copy:browserify-dist-setup', 'browserify:dist', 'uglify:dist']);
24 | grunt.registerTask('release', ['test', 'dist', 'clean']);
25 | };
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
4 | 1. Definitions.
5 |
6 | “License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
7 |
8 | “Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
9 |
10 | “Legal Entity” shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, “control” means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
11 |
12 | “You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
13 |
14 | “Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
15 |
16 | “Object” form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
17 |
18 | “Work” shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
19 |
20 | “Derivative Works” shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
21 |
22 | “Contribution” shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as “Not a Contribution.”
23 |
24 | “Contributor” shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
25 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
26 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
27 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
28 |
29 | You must give any other recipients of the Work or Derivative Works a copy of this License; and
30 | You must cause any modified files to carry prominent notices stating that You changed the files; and
31 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
32 | If the Work includes a “NOTICE” text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
33 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
34 |
35 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
36 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
37 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
38 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
39 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
40 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/NOTICE.txt:
--------------------------------------------------------------------------------
1 | Amazon Mobile Analytics SDK for JavaScript
2 | Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Amazon Mobile Analytics SDK for JavaScript
2 |
3 | **Developer Preview:** We welcome developer feedback on this project. You can reach us by creating an issue on the
4 | GitHub repository or posting to the Amazon Mobile Analytics forums:
5 | * https://github.com/aws/aws-sdk-mobile-analytics-js
6 | * https://forums.aws.amazon.com/forum.jspa?forumID=174
7 |
8 | Introduction
9 | ============
10 | The Mobile Analytics SDK for JavaScript allows JavaScript enabled applications to create and submit events for analysis in the AWS Console and through Auto Export to S3 and Redshift. The library uses the browser's local storage API to create a local cache for the data, allowing your web application to batch and record events even when the app is offline.
11 |
12 | ## Setup
13 |
14 | 1. Download and include the AWS JavaScript SDK (minimum version 2.1.18):
15 | * http://aws.amazon.com/sdk-for-browser/
16 |
17 | 2. Download and include the Amazon Mobile Analytics SDK for JavaScript:
18 | * [/dist/aws-sdk-mobile-analytics.min.js](https://raw.githubusercontent.com/aws/aws-sdk-mobile-analytics-js/master/dist/aws-sdk-mobile-analytics.min.js)
19 |
20 |
24 |
25 | ## Usage
26 |
27 | **Step 1.** Log in to the [Amazon Mobile Analytics management console](https://console.aws.amazon.com/mobileanalytics/home/?region=us-east-1) and create a new app. Be sure to note your App Id and Cognito Identity Pool Id.
28 | * https://console.aws.amazon.com/mobileanalytics/home/?region=us-east-1
29 |
30 | **Step 2.** Initialize the credentials provider using a Cognito Identity Pool ID. This is necessary for the AWS SDK to manage authentication to the Amazon Mobile Analytics REST API.
31 |
32 |
38 |
39 | **Step 3.** Instantiate the Mobile Analytics Manager, including your App ID generated in Step 1, above. Session events will be automatically recorded and the client will batch and automatically submit events to Amazon Mobile Analytics every 10 seconds.
40 |
41 |
42 | var options = {
43 | appId : MOBILE_ANALYTICS_APP_ID //Required e.g. 'c5d69c75a92646b8953126437d92c007'
44 | };
45 | mobileAnalyticsClient = new AMA.Manager(options);
46 |
47 |
48 | To manually force an event submission you can call:
49 |
50 | mobileAnalyticsClient.submitEvents();
51 |
52 |
53 | ## Additional Options
54 | ### Custom Events
55 | You can optionally add custom events to capture additional information you find valuable.
56 |
57 |
68 |
69 |
70 | ### Session Settings
71 | By default a session lasts 10 minutes. You can override this default setting when initializing the Mobile Analytics Manager by including "sessionLength" in the "options" object.
72 |
73 |
74 | var options = {
75 | appId : MOBILE_ANALYTICS_APP_ID,
76 | sessionLength: 300000 //Session Length in milliseconds. This will evaluate to 5min.
77 | };
78 | mobileAnalyticsClient = new AMA.Manager(options);
79 |
80 |
81 | A session's timeout can also be updated to allow for continuation of a session.
82 |
83 |
84 | //This will set the current session to expire in 5 seconds from now.
85 | mobileAnalyticsClient.resetSessionTimeout(5000);
86 |
87 | //This will reset the current session's expiration time using the time specified during initialization.
88 | //If the default setting was used (10 minutes) then the session will expire 10 minutes from now.
89 | mobileAnalyticsClient.resetSessionTimeout();
90 |
91 |
92 | ### Record Monetization Event
93 | You can record monetization events to enable reports such as Average Revenue Per User (ARPU) and more.
94 |
95 |
107 |
108 | ### Add App Details to Events
109 | Additional app and environment details can be added to the "options" object when initializing the SDK. These details will be captured and applied to all events and can be useful if using Auto Export for custom analysis of your data.
110 |
111 |
112 | var options = {
113 | appId : MOBILE_ANALYTICS_APP_ID, //Required e.g. 'c5d69c75a92646b8953126437d92c007'
114 | appTitle : APP_TITLE, //Optional e.g. 'Example App'
115 | appVersionName : APP_VERSION_NAME, //Optional e.g. '1.4.1'
116 | appVersionCode : APP_VERSION_CODE, //Optional e.g. '42'
117 | appPackageName : APP_PACKAGE_NAME, //Optional e.g. 'com.amazon.example'
118 | make : DEVICE_MAKE, //Optional e.g. 'Amazon'
119 | model : DEVICE_MODEL, //Optional e.g. 'KFTT'
120 | platform : DEVICE_PLATFORM, //Optional valid values: 'Android', 'iPhoneOS', 'WindowsPhone', 'Blackberry', 'Windows', 'MacOS', 'Linux'
121 | platformVersion : DEVICE_PLATFORM_VER //Optional e.g. '4.4'
122 | };
123 | mobileAnalyticsClient = new AMA.Manager(options);
124 |
125 |
126 | Please note, if device details are not specified Amazon Mobile Analytics will make best efforts to determine these values based on the User-Agent header value. It is always better to specify these values during initialization if they are available.
127 |
128 | ### Further Documentation
129 | Further documentation and advanced configurations can be found here:
130 |
131 | https://aws.github.io/aws-sdk-mobile-analytics-js/doc/AMA.Manager.html
132 |
133 | ## Network Configuration
134 | The Amazon Mobile Analytics JavaScript SDK will make requests to the following endpoints
135 | * For Event Submission: "https://mobileanalytics.us-east-1.amazonaws.com"
136 | * For Cognito Authentication: "https://cognito-identity.us-east-1.amazonaws.com"
137 | * This endpoint may change based on which region your Identity Pool was created in.
138 |
139 | For most frameworks you can whitelist both domains by whitelisting all AWS endpoints with "*.amazonaws.com".
140 |
141 | ## Change Log
142 | **v0.9.2:**
143 | * Bug Fixes:
144 | * Fixed data loss issue on migration from previous versions
145 |
146 | **v0.9.1:**
147 | * Updated Dependency: aws-sdk-js v2.2.37
148 | * Increase base delay between retries from 30ms to 3s
149 | * Allow passing of configurations to the low level client via clientOptions attribute
150 | * Local events from different apps are stored in different locations
151 | * Improved retry strategies
152 | * CorrectClockSkew is enabled by default for Sigv4 Signatures [per Issue#7](https://github.com/aws/aws-sdk-mobile-analytics-js/issues/7)
153 | * Bug Fixes:
154 | * Fixed timer from being killed in cases where multiple submissions happened in under a second
155 | * Fixed duplicate batch re-submission to the Mobile Analytics service
156 | * Fixed delayed auto-submission of first _session.start event
157 | * Fixed Safari throwing exception when in private browsing mode
158 |
159 | **v0.9.0:**
160 | * Initial release. Developer preview.
161 |
--------------------------------------------------------------------------------
/bower.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "aws-sdk-mobile-analytics",
3 | "version": "0.9.2",
4 | "main": "dist/aws-sdk-mobile-analytics.min.js",
5 | "ignore": [
6 | "lib",
7 | "node_modules",
8 | "test",
9 | "Gruntfile.js",
10 | "package.json"
11 | ],
12 | "dependencies": {
13 | "aws-sdk-js": ">=2.2.37"
14 | },
15 | "devDependencies": {
16 | }
17 | }
--------------------------------------------------------------------------------
/dist/aws-sdk-mobile-analytics.min.js:
--------------------------------------------------------------------------------
1 | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g50}function c(b){return a.attributes[b]&&a.attributes[b].length>200}function d(a){return e.logger.error(a),null}var e=this,f=[];return f=Object.keys(a.metrics).filter(function(b){return"number"!=typeof a.metrics[b]}),"v2.0"!==a.version?d("Event must have version v2.0"):"string"!=typeof a.eventType?d("Event Type must be a string"):f.length>0?d("Event Metrics must be numeric ("+f[0]+")"):Object.keys(a.metrics).length+Object.keys(a.attributes).length>40?d("Event Metric and Attribute Count cannot exceed 40"):Object.keys(a.attributes).filter(b).length?d("Event Attribute names must be 1-50 characters"):Object.keys(a.metrics).filter(b).length?d("Event Metric names must be 1-50 characters"):Object.keys(a.attributes).filter(c).length?d("Event Attribute values cannot be longer than 200 characters"):a},a.prototype.createEvent=function(a,b,c,e){var f=this;this.logger.log("[Function:(AMA.Client).createEvent]"+(a?"\neventType:"+a:"")+(b?"\nsession:"+b:"")+(c?"\nattributes:"+JSON.stringify(c):"")+(e?"\nmetrics:"+JSON.stringify(e):"")),c=c||{},e=e||{},d.Util.mergeObjects(c,this.options.globalAttributes),d.Util.mergeObjects(e,this.options.globalMetrics),Object.keys(c).forEach(function(a){if("string"!=typeof c[a])try{c[a]=JSON.stringify(c[a])}catch(b){f.logger.warn("Error parsing attribute "+a)}});var g={eventType:a,timestamp:(new Date).toISOString(),session:{id:b.id,startTimestamp:b.startTimestamp},version:"v2.0",attributes:c,metrics:e};return b.stopTimestamp&&(g.session.stopTimestamp=b.stopTimestamp,g.session.duration=new Date(g.stopTimestamp).getTime()-new Date(g.startTimestamp).getTime()),this.validateEvent(g)},a.prototype.pushEvent=function(a){if(!a)return-1;this.logger.log("[Function:(AMA.Client).pushEvent]"+(a?"\nevent:"+JSON.stringify(a):""));var b=this.outputs.events.push(a);return this.storage.set(this.StorageKeys.EVENTS,this.outputs.events),b-1},a.prototype.recordEvent=function(a,b,c,e){this.logger.log("[Function:(AMA.Client).recordEvent]"+(a?"\neventType:"+a:"")+(b?"\nsession:"+b:"")+(c?"\nattributes:"+JSON.stringify(c):"")+(e?"\nmetrics:"+JSON.stringify(e):""));var f,g=this.createEvent(a,b,c,e);return g?(f=this.pushEvent(g),d.Util.getRequestBodySize(this.outputs.events)>=this.options.batchSizeLimit&&this.submitEvents(),this.outputs.events[f]):null},a.prototype.recordMonetizationEvent=function(a,b,c,d){return this.logger.log("[Function:(AMA.Client).recordMonetizationEvent]"+(a?"\nsession:"+a:"")+(b?"\nmonetizationDetails:"+JSON.stringify(b):"")+(c?"\nattributes:"+JSON.stringify(c):"")+(d?"\nmetrics:"+JSON.stringify(d):"")),c=c||{},d=d||{},c._currency=b.currency||c._currency,c._product_id=b.productId||c._product_id,d._quantity=b.quantity||d._quantity,"number"==typeof b.price?d._item_price=b.price||d._item_price:c._item_price_formatted=b.price||c._item_price_formatted,this.recordEvent("_monetization.purchase",a,c,d)},a.prototype.submitEvents=function(a){a=a||{},a.submitCallback=a.submitCallback||this.options.submitCallback,this.logger.log("[Function:(AMA.Client).submitEvents]"+(a?"\noptions:"+JSON.stringify(a):"")),this.options.autoSubmitEvents&&(clearTimeout(this.outputs.timeoutReference),this.outputs.timeoutReference=setTimeout(this.submitEvents.bind(this),this.options.autoSubmitInterval));var b;return this.outputs.isThrottled&&this.throttlingSuppressionFunction()0?b="Prevented submission while batches are in flight":0===this.outputs.batches.length&&0===this.outputs.events.length?b="No batches or events to be submitted":this.outputs.lastSubmitTimestamp&&d.Util.timestamp()-this.outputs.lastSubmitTimestamp<1e3&&(b="Prevented multiple submissions in under a second"),b?(this.logger.warn(b),[]):(this.generateBatches(),this.outputs.lastSubmitTimestamp=d.Util.timestamp(),this.outputs.isThrottled?(this.logger.warn("Is throttled submitting first batch"),a.batchId=this.outputs.batchIndex[0],[this.submitBatchById(a)]):this.submitAllBatches(a))},a.prototype.throttlingSuppressionFunction=function(a){return a=a||d.Util.timestamp(),Math.pow(a-this.outputs.lastSubmitTimestamp,2)/Math.pow(6e4,2)},a.prototype.generateBatches=function(){for(;this.outputs.events.length>0;){var a=this.outputs.events.length;for(this.logger.log(this.outputs.events.length+" events to be submitted");a>1&&d.Util.getRequestBodySize(this.outputs.events.slice(0,a))>this.options.batchSizeLimit;)this.logger.log("Finding Batch Size ("+this.options.batchSizeLimit+"): "+a+"("+d.Util.getRequestBodySize(this.outputs.events.slice(0,a))+")"),a-=1;this.persistBatch(this.outputs.events.slice(0,a))&&(this.outputs.events.splice(0,a),this.storage.set(this.StorageKeys.EVENTS,this.outputs.events))}},a.prototype.persistBatch=function(a){if(this.logger.log(a.length+" events in batch"),d.Util.getRequestBodySize(a)<512e3){var b=d.Util.GUID();return this.outputs.batches[b]=a,this.storage.set(this.StorageKeys.BATCHES,this.outputs.batches),this.outputs.batchIndex.push(b),this.storage.set(this.StorageKeys.BATCH_INDEX,this.outputs.batchIndex),!0}return this.logger.error("Events too large"),!1},a.prototype.submitAllBatches=function(a){a.submitCallback=a.submitCallback||this.options.submitCallback,this.logger.log("[Function:(AMA.Client).submitAllBatches]"+(a?"\noptions:"+JSON.stringify(a):""));var b=[],c=this;return this.outputs.batchIndex.forEach(function(d){a.batchId=d,a.clientContext=a.clientContext||c.options.clientContext,c.outputs.batchesInFlight[d]||b.push(c.submitBatchById(a))}),b},a.NON_RETRYABLE_EXCEPTIONS=["BadRequestException","SerializationException","ValidationException"],a.prototype.submitBatchById=function(a){if("object"!=typeof a||!a.batchId)return void this.logger.error("Invalid Options passed to submitBatchById");a.submitCallback=a.submitCallback||this.options.submitCallback,this.logger.log("[Function:(AMA.Client).submitBatchById]"+(a?"\noptions:"+JSON.stringify(a):""));var b={events:this.outputs.batches[a.batchId],clientContext:JSON.stringify(a.clientContext||this.options.clientContext)};return this.outputs.batchesInFlight[a.batchId]=d.Util.timestamp(),this.outputs.MobileAnalytics.putEvents(b,this.handlePutEventsResponse(a.batchId,a.submitCallback)),a.batchId},a.prototype.handlePutEventsResponse=function(b,c){var d=this;return function(e,f){var g=!0,h=d.outputs.isThrottled;e?(d.logger.error(e,f),(void 0===e.statusCode||400===e.statusCode)&&(a.NON_RETRYABLE_EXCEPTIONS.indexOf(e.code)<0&&(g=!1),d.outputs.isThrottled="ThrottlingException"===e.code,d.outputs.isThrottled&&d.logger.warn("Application is currently throttled"))):(d.logger.info("Events Submitted Successfully"),d.outputs.isThrottled=!1),g&&d.clearBatchById(b),delete d.outputs.batchesInFlight[b],c(e,f,b),h&&!d.outputs.isThrottled&&(d.logger.warn("Was throttled flushing remaining batches",c),d.submitAllBatches({submitCallback:c}))}},a.prototype.clearBatchById=function(a){this.logger.log("[Function:(AMA.Client).clearBatchById]"+(a?"\nbatchId:"+a:"")),-1!==this.outputs.batchIndex.indexOf(a)&&(delete this.outputs.batches[a],this.outputs.batchIndex.splice(this.outputs.batchIndex.indexOf(a),1),this.storage.set(this.StorageKeys.BATCH_INDEX,this.outputs.batchIndex),this.storage.set(this.StorageKeys.BATCHES,this.outputs.batches))},a}(),b.exports=d.Client}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./MobileAnalyticsUtilities.js":4,"./StorageClients/LocalStorage.js":5,"./StorageClients/StorageKeys.js":6}],2:[function(a,b){(function(c){var d=c.AMA;d.Storage=a("./StorageClients/LocalStorage.js"),d.StorageKeys=a("./StorageClients/StorageKeys.js"),d.Util=a("./MobileAnalyticsUtilities.js"),d.Session=function(){"use strict";var a=function(a){this.options=a||{},this.options.logger=this.options.logger||{},this.logger={log:this.options.logger.log||d.Util.NOP,info:this.options.logger.info||d.Util.NOP,warn:this.options.logger.warn||d.Util.NOP,error:this.options.logger.error||d.Util.NOP},this.logger.log=this.logger.log.bind(this.options.logger),this.logger.info=this.logger.info.bind(this.options.logger),this.logger.warn=this.logger.warn.bind(this.options.logger),this.logger.error=this.logger.error.bind(this.options.logger),this.logger.log("[Function:(AWS.MobileAnalyticsClient)Session Constructor]"+(a?"\noptions:"+JSON.stringify(a):"")),this.options.expirationCallback=this.options.expirationCallback||d.Util.NOP,this.id=this.options.sessionId||d.Util.GUID(),this.sessionLength=this.options.sessionLength||6e5,this.StorageKeys={SESSION_ID:d.StorageKeys.SESSION_ID+this.id,SESSION_EXPIRATION:d.StorageKeys.SESSION_EXPIRATION+this.id,SESSION_START_TIMESTAMP:d.StorageKeys.SESSION_START_TIMESTAMP+this.id},this.startTimestamp=this.options.startTime||this.options.storage.get(this.StorageKeys.SESSION_START_TIMESTAMP)||(new Date).toISOString(),this.expirationDate=parseInt(this.options.storage.get(this.StorageKeys.SESSION_EXPIRATION),10),isNaN(this.expirationDate)&&(this.expirationDate=(new Date).getTime()+this.sessionLength),this.options.storage.set(this.StorageKeys.SESSION_ID,this.id),this.options.storage.set(this.StorageKeys.SESSION_EXPIRATION,this.expirationDate),this.options.storage.set(this.StorageKeys.SESSION_START_TIMESTAMP,this.startTimestamp),this.sessionTimeoutReference=setTimeout(this.expireSession.bind(this),this.sessionLength)};return a.prototype.expireSession=function(a){this.logger.log("[Function:(Session).expireSession]"),a=a||this.options.expirationCallback;var b=a(this);"boolean"==typeof b&&b&&(b=this.options.sessionLength),"number"==typeof b?this.extendSession(b):this.clearSession()},a.prototype.clearSession=function(){this.logger.log("[Function:(Session).clearSession]"),clearTimeout(this.sessionTimeoutReference),this.options.storage.delete(this.StorageKeys.SESSION_ID),this.options.storage.delete(this.StorageKeys.SESSION_EXPIRATION),this.options.storage.delete(this.StorageKeys.SESSION_START_TIMESTAMP)},a.prototype.extendSession=function(a){this.logger.log("[Function:(Session).extendSession]"+(a?"\nsessionExtensionLength:"+a:"")),a=a||this.sessionLength,this.setSessionTimeout(this.expirationDate+parseInt(a,10))},a.prototype.stopSession=function(a){this.logger.log("[Function:(Session).stopSession]"+(a?"\nstopDate:"+a:"")),this.stopTimestamp=a||(new Date).toISOString()},a.prototype.resetSessionTimeout=function(a){this.logger.log("[Function:(Session).resetSessionTimeout]"+(a?"\nmilliseconds:"+a:"")),a=a||this.sessionLength,this.setSessionTimeout((new Date).getTime()+a)},a.prototype.setSessionTimeout=function(a){this.logger.log("[Function:(Session).setSessionTimeout]"+(a?"\ntimeout:"+a:"")),clearTimeout(this.sessionTimeoutReference),this.expirationDate=a,this.options.storage.set(this.StorageKeys.SESSION_EXPIRATION,this.expirationDate),this.sessionTimeoutReference=setTimeout(this.expireSession.bind(this),this.expirationDate-(new Date).getTime())},a}(),b.exports=d.Session}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./MobileAnalyticsUtilities.js":4,"./StorageClients/LocalStorage.js":5,"./StorageClients/StorageKeys.js":6}],3:[function(a,b){(function(c){var d=c.AMA;d.Storage=a("./StorageClients/LocalStorage.js"),d.StorageKeys=a("./StorageClients/StorageKeys.js"),d.Session=a("./MobileAnalyticsSession.js"),d.Client=a("./MobileAnalyticsClient.js"),d.Manager=function(){"use strict";var a=function(a){function b(a){a.client.storage.each(function(b){0===b.indexOf(d.StorageKeys.SESSION_ID)&&(a.outputs.session=new d.Session({storage:a.client.storage,sessionId:a.client.storage.get(b),sessionLength:a.options.sessionLength,expirationCallback:function(b){var c=a.options.expirationCallback(b);return c===!0||"number"==typeof c?c:void a.stopSession()}}),(new Date).getTime()>a.outputs.session.expirationDate&&(a.outputs.session.expireSession(),delete a.outputs.session))})}a instanceof d.Client?this.client=a:(a._autoSubmitEvents=a.autoSubmitEvents,a.autoSubmitEvents=!1,this.client=new d.Client(a),a.autoSubmitEvents=a._autoSubmitEvents!==!1,delete a._autoSubmitEvents),this.options=this.client.options,this.outputs=this.client.outputs,this.options.expirationCallback=this.options.expirationCallback||d.Util.NOP,b(this),this.outputs.session||this.startSession(),this.options.autoSubmitEvents&&this.client.submitEvents()};return a.prototype.submitEvents=function(a){return this.client.submitEvents(a)},a.prototype.startSession=function(){return this.client.logger.log("[Function:(AMA.Manager).startSession]"),this.outputs.session&&this.outputs.session.clearSession(),this.outputs.session=new d.Session({storage:this.client.storage,logger:this.client.options.logger,sessionLength:this.options.sessionLength,expirationCallback:function(a){var b=this.options.expirationCallback(a);return b===!0||"number"==typeof b?b:void this.stopSession()}.bind(this)}),this.recordEvent("_session.start")},a.prototype.extendSession=function(a){return this.outputs.session.extendSession(a||this.options.sessionLength)},a.prototype.stopSession=function(){return this.client.logger.log("[Function:(AMA.Manager).stopSession]"),this.outputs.session.stopSession(),this.outputs.session.expireSession(d.Util.NOP),this.recordEvent("_session.stop")},a.prototype.renewSession=function(){return this.stopSession(),this.startSession(),this.outputs.session},a.prototype.createEvent=function(a,b,c){return this.client.createEvent(a,this.outputs.session,b,c)},a.prototype.recordEvent=function(a,b,c){return this.client.recordEvent(a,this.outputs.session,b,c)},a.prototype.recordMonetizationEvent=function(a,b,c){return this.client.recordMonetizationEvent(this.outputs.session,a,b,c)},a}(),b.exports=d.Manager}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./MobileAnalyticsClient.js":1,"./MobileAnalyticsSession.js":2,"./StorageClients/LocalStorage.js":5,"./StorageClients/StorageKeys.js":6}],4:[function(a,b){(function(a){var c=a.AMA;c.Util=function(){"use strict";function a(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function b(a){"string"!=typeof a&&(a=JSON.stringify(a));var b,c,d=a.length;for(b=a.length-1;b>=0;b-=1)c=a.charCodeAt(b),c>127&&2047>=c?d+=1:c>2047&&65535>=c&&(d+=2),c>=56320&&57343>=c&&(b-=1);return d}function c(){return a()+a()+"-"+a()+"-"+a()+"-"+a()+"-"+a()+a()+a()}function d(a,b){return Object.keys(b).forEach(function(c){b.hasOwnProperty(c)&&(a[c]=a[c]||b[c])}),a}function e(a,b){return d(JSON.parse(JSON.stringify(a)),b||{})}function f(){return void 0}function g(){return(new Date).getTime()}return{copy:e,GUID:c,getRequestBodySize:b,mergeObjects:d,NOP:f,timestamp:g}}(),b.exports=c.Util}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],5:[function(a,b){(function(c){var d=c.AMA;d.Util=a("../MobileAnalyticsUtilities.js"),d.Storage=function(){"use strict";var a=function(a){this.storageKey="AWSMobileAnalyticsStorage-"+a,c[this.storageKey]=c[this.storageKey]||{},this.cache=c[this.storageKey],this.cache.id=this.cache.id||d.Util.GUID(),this.logger={log:d.Util.NOP,info:d.Util.NOP,warn:d.Util.NOP,error:d.Util.NOP},this.reload()};if("object"==typeof localStorage&&"object"===Storage)try{localStorage.setItem("TestLocalStorage",1),localStorage.removeItem("TestLocalStorage")}catch(b){Storage.prototype._setItem=Storage.prototype.setItem,Storage.prototype.setItem=d.Util.NOP,console.warn('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.')}return a.prototype.type="LOCAL_STORAGE",a.prototype.get=function(a){return this.cache[a]},a.prototype.set=function(a,b){return this.cache[a]=b,this.saveToLocalStorage()},a.prototype.delete=function(a){delete this.cache[a],this.saveToLocalStorage()},a.prototype.each=function(a){var b;for(b in this.cache)this.cache.hasOwnProperty(b)&&a(b,this.cache[b])},a.prototype.saveToLocalStorage=function(){if(this.supportsLocalStorage())try{this.logger.log("[Function:(AWS.MobileAnalyticsClient.Storage).saveToLocalStorage]"),window.localStorage.setItem(this.storageKey,JSON.stringify(this.cache)),this.logger.log("LocalStorage Cache: "+JSON.stringify(this.cache))}catch(a){this.logger.log("Error saving to LocalStorage: "+JSON.stringify(a))}else this.logger.log("LocalStorage is not available")},a.prototype.reload=function(){if(this.supportsLocalStorage()){var a;try{if(this.logger.log("[Function:(AWS.MobileAnalyticsClient.Storage).loadLocalStorage]"),a=window.localStorage.getItem(this.storageKey),this.logger.log("LocalStorage Cache: "+a),a)try{this.cache=JSON.parse(a)}catch(b){this.clearLocalStorage()}}catch(c){this.logger.log("Error loading LocalStorage: "+JSON.stringify(c)),this.clearLocalStorage()}}else this.logger.log("LocalStorage is not available")},a.prototype.setLogger=function(a){this.logger=a},a.prototype.supportsLocalStorage=function(){try{return window&&window.localStorage}catch(a){return!1}},a.prototype.clearLocalStorage=function(){if(this.cache={},this.supportsLocalStorage())try{this.logger.log("[Function:(AWS.MobileAnalyticsClient.Storage).clearLocalStorage]"),window.localStorage.removeItem(this.storageKey),c[this.storageKey]={}}catch(a){this.logger.log("Error clearing LocalStorage: "+JSON.stringify(a))}else this.logger.log("LocalStorage is not available")},a}(),b.exports=d.Storage}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../MobileAnalyticsUtilities.js":4}],6:[function(a,b){(function(a){var c=a.AMA;c.StorageKeys={CLIENT_ID:"AWSMobileAnalyticsClientId",GLOBAL_ATTRIBUTES:"AWSMobileAnalyticsGlobalAttributes",GLOBAL_METRICS:"AWSMobileAnalyticsGlobalMetrics",SESSION_ID:"MobileAnalyticsSessionId",SESSION_EXPIRATION:"MobileAnalyticsSessionExpiration",SESSION_START_TIMESTAMP:"MobileAnalyticsSessionStartTimeStamp"},b.exports=c.StorageKeys}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],7:[function(a,b){(function(c){c.AMA=c.AMA||{},a("./MobileAnalyticsClient.js"),a("./MobileAnalyticsUtilities.js"),a("./StorageClients/StorageKeys.js"),a("./StorageClients/LocalStorage.js"),a("./MobileAnalyticsSession.js"),a("./MobileAnalyticsSessionManager.js"),b.exports=c.AMA}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./MobileAnalyticsClient.js":1,"./MobileAnalyticsSession.js":2,"./MobileAnalyticsSessionManager.js":3,"./MobileAnalyticsUtilities.js":4,"./StorageClients/LocalStorage.js":5,"./StorageClients/StorageKeys.js":6}]},{},[7]);
--------------------------------------------------------------------------------
/doc/MobileAnalyticsSession.js.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | JSDoc: Source: MobileAnalyticsSession.js
6 |
7 |
8 |
9 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
Source: MobileAnalyticsSession.js
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
var AMA = global.AMA;
29 | AMA.Storage = require('./StorageClients/LocalStorage.js');
30 | AMA.StorageKeys = require('./StorageClients/StorageKeys.js');
31 | AMA.Util = require('./MobileAnalyticsUtilities.js');
32 | /**
33 | * @name AMA.Session
34 | * @namespace AMA.Session
35 | * @constructor
36 | * @param {Object=} [options=] - A configuration map for the Session
37 | * @param {string=} [options.sessionId=Utilities.GUID()]- A sessionId for session.
38 | * @param {string=} [options.appId=new Date().toISOString()] - The start Timestamp (default now).
39 | * @param {number=} [options.sessionLength=600000] - Length of session in Milliseconds (default 10 minutes).
40 | * @param {AMA.Session.ExpirationCallback=} [options.expirationCallback] - Callback Function for when a session expires
41 | * @param {AMA.Client.Logger=} [options.logger=] - Object containing javascript style logger functions (passing console
42 | * will output to browser dev consoles)
43 | */
44 | /**
45 | * @callback AMA.Session.ExpirationCallback
46 | * @param {AMA.Session} session
47 | * @returns {boolean|int} - Returns either true to extend the session by the sessionLength or an int with the number of
48 | * seconds to extend the session. All other values will clear the session from storage.
49 | */
50 | AMA.Session = (function () {
51 | 'use strict';
52 | /**
53 | * @lends AMA.Session
54 | */
55 | var Session = function (options) {
56 | this.options = options || {};
57 | this.options.logger = this.options.logger || {};
58 | this.logger = {
59 | log: this.options.logger.log || AMA.Util.NOP,
60 | info: this.options.logger.info || AMA.Util.NOP,
61 | warn: this.options.logger.warn || AMA.Util.NOP,
62 | error: this.options.logger.error || AMA.Util.NOP
63 | };
64 | this.logger.log = this.logger.log.bind(this.options.logger);
65 | this.logger.info = this.logger.info.bind(this.options.logger);
66 | this.logger.warn = this.logger.warn.bind(this.options.logger);
67 | this.logger.error = this.logger.error.bind(this.options.logger);
68 | this.logger.log('[Function:(AWS.MobileAnalyticsClient)Session Constructor]' +
69 | (options ? '\noptions:' + JSON.stringify(options) : ''));
70 | this.options.expirationCallback = this.options.expirationCallback || AMA.Util.NOP;
71 | this.id = this.options.sessionId || AMA.Util.GUID();
72 | this.sessionLength = this.options.sessionLength || 600000; //Default session length is 10 minutes
73 | //Suffix the AMA.Storage Keys with Session Id to ensure proper scope
74 | this.StorageKeys = {
75 | 'SESSION_ID': AMA.StorageKeys.SESSION_ID + this.id,
76 | 'SESSION_EXPIRATION': AMA.StorageKeys.SESSION_EXPIRATION + this.id,
77 | 'SESSION_START_TIMESTAMP': AMA.StorageKeys.SESSION_START_TIMESTAMP + this.id
78 | };
79 | this.startTimestamp = this.options.startTime ||
80 | this.options.storage.get(this.StorageKeys.SESSION_START_TIMESTAMP) ||
81 | new Date().toISOString();
82 | this.expirationDate = parseInt(this.options.storage.get(this.StorageKeys.SESSION_EXPIRATION), 10);
83 | if (isNaN(this.expirationDate)) {
84 | this.expirationDate = (new Date().getTime() + this.sessionLength);
85 | }
86 | this.options.storage.set(this.StorageKeys.SESSION_ID, this.id);
87 | this.options.storage.set(this.StorageKeys.SESSION_EXPIRATION, this.expirationDate);
88 | this.options.storage.set(this.StorageKeys.SESSION_START_TIMESTAMP, this.startTimestamp);
89 | this.sessionTimeoutReference = setTimeout(this.expireSession.bind(this), this.sessionLength);
90 | };
91 |
92 | /**
93 | * Expire session and clear session
94 | * @param {expirationCallback=} Callback function to call when sessions expire
95 | */
96 | Session.prototype.expireSession = function (expirationCallback) {
97 | this.logger.log('[Function:(Session).expireSession]');
98 | expirationCallback = expirationCallback || this.options.expirationCallback;
99 | var shouldExtend = expirationCallback(this);
100 | if (typeof shouldExtend === 'boolean' && shouldExtend) {
101 | shouldExtend = this.options.sessionLength;
102 | }
103 | if (typeof shouldExtend === 'number') {
104 | this.extendSession(shouldExtend);
105 | } else {
106 | this.clearSession();
107 | }
108 | };
109 |
110 | /**
111 | * Clear session from storage system
112 | */
113 | Session.prototype.clearSession = function () {
114 | this.logger.log('[Function:(Session).clearSession]');
115 | clearTimeout(this.sessionTimeoutReference);
116 | this.options.storage.delete(this.StorageKeys.SESSION_ID);
117 | this.options.storage.delete(this.StorageKeys.SESSION_EXPIRATION);
118 | this.options.storage.delete(this.StorageKeys.SESSION_START_TIMESTAMP);
119 | };
120 |
121 |
122 |
123 | /**
124 | * Extend session by adding to the expiration timestamp
125 | * @param {int} [sessionExtensionLength=sessionLength] - The number of milliseconds to add to the expiration date
126 | * (session length by default).
127 | */
128 | Session.prototype.extendSession = function (sessionExtensionLength) {
129 | this.logger.log('[Function:(Session).extendSession]' +
130 | (sessionExtensionLength ? '\nsessionExtensionLength:' + sessionExtensionLength : ''));
131 | sessionExtensionLength = sessionExtensionLength || this.sessionLength;
132 | this.setSessionTimeout(this.expirationDate + parseInt(sessionExtensionLength, 10));
133 | };
134 |
135 | /**
136 | * @param {string} [stopDate=now] - The ISO Date String to set the stopTimestamp to (now for default).
137 | */
138 | Session.prototype.stopSession = function (stopDate) {
139 | this.logger.log('[Function:(Session).stopSession]' + (stopDate ? '\nstopDate:' + stopDate : ''));
140 | this.stopTimestamp = stopDate || new Date().toISOString();
141 | };
142 |
143 | /**
144 | * Reset session timeout to expire in a given number of seconds
145 | * @param {int} [milliseconds=sessionLength] - The number of milliseconds until the session should expire (from now).
146 | */
147 | Session.prototype.resetSessionTimeout = function (milliseconds) {
148 | this.logger.log('[Function:(Session).resetSessionTimeout]' +
149 | (milliseconds ? '\nmilliseconds:' + milliseconds : ''));
150 | milliseconds = milliseconds || this.sessionLength;
151 | this.setSessionTimeout(new Date().getTime() + milliseconds);
152 | };
153 |
154 | /**
155 | * Setter for the session timeout
156 | * @param {int} timeout - epoch timestamp
157 | */
158 | Session.prototype.setSessionTimeout = function (timeout) {
159 | this.logger.log('[Function:(Session).setSessionTimeout]' + (timeout ? '\ntimeout:' + timeout : ''));
160 | clearTimeout(this.sessionTimeoutReference);
161 | this.expirationDate = timeout;
162 | this.options.storage.set(this.StorageKeys.SESSION_EXPIRATION, this.expirationDate);
163 | this.sessionTimeoutReference = setTimeout(this.expireSession.bind(this),
164 | this.expirationDate - (new Date()).getTime());
165 | };
166 | return Session;
167 | }());
168 |
169 | module.exports = AMA.Session;
170 |
The Mobile Analytics SDK for JavaScript allows JavaScript enabled applications to create and submit events for analysis in the AWS Console and through Auto Export to S3 and Redshift. The library uses the browser's local storage API to create a local cache for the data, allowing your web application to batch and record events even when the app is offline.
51 |
Setup
52 |
53 |
Download and include the AWS JavaScript SDK (minimum version 2.1.18):
Step 2. Initialize the credentials provider using a Cognito Identity Pool ID. This is necessary for the AWS SDK to manage authentication to the Amazon Mobile Analytics REST API.
Step 3. Instantiate the Mobile Analytics Manager, including your App ID generated in Step 1, above. Session events will be automatically recorded and the client will batch and automatically submit events to Amazon Mobile Analytics every 10 seconds.
81 |
82 | var options = {
83 | appId : MOBILE_ANALYTICS_APP_ID //Required e.g. 'c5d69c75a92646b8953126437d92c007'
84 | };
85 | mobileAnalyticsClient = new AMA.Manager(options);
86 |
87 |
88 |
To manually force an event submission you can call:
89 |
90 | mobileAnalyticsClient.submitEvents();
91 |
92 |
93 |
Additional Options
94 |
Custom Events
95 |
You can optionally add custom events to capture additional information you find valuable.
By default a session lasts 10 minutes. You can override this default setting when initializing the Mobile Analytics Manager by including "sessionLength" in the "options" object.
111 |
112 | var options = {
113 | appId : MOBILE_ANALYTICS_APP_ID,
114 | sessionLength: 300000 //Session Length in milliseconds. This will evaluate to 5min.
115 | };
116 | mobileAnalyticsClient = new AMA.Manager(options);
117 |
118 |
119 |
A session's timeout can also be updated to allow for continuation of a session.
120 |
121 | //This will set the current session to expire in 5 seconds from now.
122 | mobileAnalyticsClient.resetSessionTimeout(5000);
123 |
124 | //This will reset the current session's expiration time using the time specified during initialization.
125 | //If the default setting was used (10 minutes) then the session will expire 10 minutes from now.
126 | mobileAnalyticsClient.resetSessionTimeout();
127 |
128 |
129 |
Record Monetization Event
130 |
You can record monetization events to enable reports such as Average Revenue Per User (ARPU) and more.
Additional app and environment details can be added to the "options" object when initializing the SDK. These details will be captured and applied to all events and can be useful if using Auto Export for custom analysis of your data.
146 |
147 | var options = {
148 | appId : MOBILE_ANALYTICS_APP_ID, //Required e.g. 'c5d69c75a92646b8953126437d92c007'
149 | appTitle : APP_TITLE, //Optional e.g. 'Example App'
150 | appVersionName : APP_VERSION_NAME, //Optional e.g. '1.4.1'
151 | appVersionCode : APP_VERSION_CODE, //Optional e.g. '42'
152 | appPackageName : APP_PACKAGE_NAME, //Optional e.g. 'com.amazon.example'
153 | make : DEVICE_MAKE, //Optional e.g. 'Amazon'
154 | model : DEVICE_MODEL, //Optional e.g. 'KFTT'
155 | platform : DEVICE_PLATFORM, //Required valid values: 'Android', 'iPhoneOS', 'WindowsPhone', 'Blackberry', 'Windows', 'MacOS', 'Linux'
156 | platformVersion : DEVICE_PLATFORM_VER //Optional e.g. '4.4'
157 | };
158 | mobileAnalyticsClient = new AMA.Manager(options);
159 |
160 |
161 |
Please note, if device details are not specified Amazon Mobile Analytics will make best efforts to determine these values based on the User-Agent header value. It is always better to specify these values during initialization if they are available.
162 |
Further Documentation
163 |
Further documentation and advanced configurations can be found here:
For most frameworks you can whitelist both domains by whitelisting all AWS endpoints with "*.amazonaws.com".
171 |
Change Log
172 |
v0.9.2:
173 | Bug Fixes:
174 | Fixed data loss issue on migration from previous versions
175 |
v0.9.1:
176 | Updated Dependency: aws-sdk-js v2.2.37
177 | Increase base delay between retries from 30ms to 3s
178 | Allow passing of configurations to the low level client via clientOptions attribute
179 | Local events from different apps are stored in different locations
180 | Improved retry strategies
181 | CorrectClockSkew is enabled by default for Sigv4 Signatures per Issue#7
182 | Bug Fixes:
183 | Fixed timer from being killed in cases where multiple submissions happened in under a second
184 | Fixed duplicate batch re-submission to the Mobile Analytics service
185 | Fixed delayed auto-submission of first _session.start event
186 | * Fixed Safari throwing exception when in private browsing mode
119 |
120 |
123 |
124 |
125 |
126 |
129 |
130 |
131 |
132 |
133 |
--------------------------------------------------------------------------------
/doc/scripts/linenumber.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
4 | the License. A copy of the License is located at http://aws.amazon.com/apache2.0/
5 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6 | CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
7 | and limitations under the License.
8 | */
9 |
10 | (function() {
11 | var counter = 0;
12 | var numbered;
13 | var source = document.getElementsByClassName('prettyprint source');
14 |
15 | if (source && source[0]) {
16 | source = source[0].getElementsByTagName('code')[0];
17 |
18 | numbered = source.innerHTML.split('\n');
19 | numbered = numbered.map(function(item) {
20 | counter++;
21 | return '' + item;
22 | });
23 |
24 | source.innerHTML = numbered.join('\n');
25 | }
26 | })();
27 |
--------------------------------------------------------------------------------
/doc/scripts/prettify/Apache-License-2.0.txt:
--------------------------------------------------------------------------------
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 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/doc/scripts/prettify/lang-css.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
4 | the License. A copy of the License is located at http://aws.amazon.com/apache2.0/
5 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6 | CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
7 | and limitations under the License.
8 | */
9 |
10 | PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n"]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com",
11 | /^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]);
12 |
--------------------------------------------------------------------------------
/doc/scripts/prettify/prettify.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
4 | the License. A copy of the License is located at http://aws.amazon.com/apache2.0/
5 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6 | CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
7 | and limitations under the License.
8 | */
9 |
10 | var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
11 | (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
12 | [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
18 | l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
19 | q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/,
20 | q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g,
21 | "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a),
22 | a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
23 | for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],
27 | "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"],
28 | H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],
29 | J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+
30 | I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]+/],["dec",/^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^
14 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
29 |