-
Notifications
You must be signed in to change notification settings - Fork 6
/
vaadin-usage-statistics-collect.html
511 lines (465 loc) · 16.5 KB
/
vaadin-usage-statistics-collect.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
<!-- This file is autogenerated from src/vaadin-usage-statistics.tpl.html -->
<!--
This script gathers usage statistics from the application running in development mode.
Statistics gathering is automatically disabled and excluded from production builds.
For details and to opt-out, see https://github.com/vaadin/vaadin-usage-statistics.
-->
<link rel="import" href="../vaadin-development-mode-detector/vaadin-development-mode-detector.html">
<script>
(function() {
function maybeGatherAndSendStats() {
/*! vaadin-dev-mode:start
(function () {
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var getPolymerVersion = function getPolymerVersion() {
return window.Polymer && window.Polymer.version;
};
var StatisticsGatherer = function () {
function StatisticsGatherer(logger) {
classCallCheck(this, StatisticsGatherer);
this.now = new Date().getTime();
this.logger = logger;
}
createClass(StatisticsGatherer, [{
key: 'frameworkVersionDetectors',
value: function frameworkVersionDetectors() {
return {
'Flow': function Flow() {
if (window.Vaadin && window.Vaadin.Flow && window.Vaadin.Flow.clients) {
var flowVersions = Object.keys(window.Vaadin.Flow.clients).map(function (key) {
return window.Vaadin.Flow.clients[key];
}).filter(function (client) {
return client.getVersionInfo;
}).map(function (client) {
return client.getVersionInfo().flow;
});
if (flowVersions.length > 0) {
return flowVersions[0];
}
}
},
'Vaadin Framework': function VaadinFramework() {
if (window.vaadin && window.vaadin.clients) {
var frameworkVersions = Object.values(window.vaadin.clients).filter(function (client) {
return client.getVersionInfo;
}).map(function (client) {
return client.getVersionInfo().vaadinVersion;
});
if (frameworkVersions.length > 0) {
return frameworkVersions[0];
}
}
},
'AngularJs': function AngularJs() {
if (window.angular && window.angular.version && window.angular.version) {
return window.angular.version.full;
}
},
'Angular': function Angular() {
if (window.ng) {
var tags = document.querySelectorAll("[ng-version]");
if (tags.length > 0) {
return tags[0].getAttribute("ng-version");
}
return "Unknown";
}
},
'Backbone.js': function BackboneJs() {
if (window.Backbone) {
return window.Backbone.VERSION;
}
},
'React': function React() {
var reactSelector = '[data-reactroot], [data-reactid]';
if (!!document.querySelector(reactSelector)) {
// React does not publish the version by default
return "unknown";
}
},
'Ember': function Ember() {
if (window.Em && window.Em.VERSION) {
return window.Em.VERSION;
} else if (window.Ember && window.Ember.VERSION) {
return window.Ember.VERSION;
}
},
'jQuery': function (_jQuery) {
function jQuery() {
return _jQuery.apply(this, arguments);
}
jQuery.toString = function () {
return _jQuery.toString();
};
return jQuery;
}(function () {
if (typeof jQuery === 'function' && jQuery.prototype.jquery !== undefined) {
return jQuery.prototype.jquery;
}
}),
'Polymer': function Polymer() {
var version = getPolymerVersion();
if (version) {
return version;
}
},
'LitElement': function LitElement() {
var version = window.litElementVersions && window.litElementVersions[0];
if (version) {
return version;
}
},
'LitHtml': function LitHtml() {
var version = window.litHtmlVersions && window.litHtmlVersions[0];
if (version) {
return version;
}
},
'Vue.js': function VueJs() {
if (window.Vue) {
return window.Vue.version;
}
}
};
}
}, {
key: 'getUsedVaadinElements',
value: function getUsedVaadinElements(elements) {
var version = getPolymerVersion();
var elementClasses = void 0;
// NOTE: In case you edit the code here, YOU MUST UPDATE any statistics reporting code in Flow.
// Check all locations calling the method getEntries() in
// https://github.com/vaadin/flow/blob/master/flow-server/src/main/java/com/vaadin/flow/internal/UsageStatistics.java#L106
// Currently it is only used by BootstrapHandler.
if (version && version.indexOf('2') === 0) {
// Polymer 2: components classes are stored in window.Vaadin
elementClasses = Object.keys(window.Vaadin).map(function (c) {
return window.Vaadin[c];
}).filter(function (c) {
return c.is;
});
} else {
// Polymer 3: components classes are stored in window.Vaadin.registrations
elementClasses = window.Vaadin.registrations || [];
}
elementClasses.forEach(function (klass) {
var version = klass.version ? klass.version : "0.0.0";
elements[klass.is] = { version: version };
});
}
}, {
key: 'getUsedVaadinThemes',
value: function getUsedVaadinThemes(themes) {
['Lumo', 'Material'].forEach(function (themeName) {
var theme;
var version = getPolymerVersion();
if (version && version.indexOf('2') === 0) {
// Polymer 2: themes are stored in window.Vaadin
theme = window.Vaadin[themeName];
} else {
// Polymer 3: themes are stored in custom element registry
theme = customElements.get('vaadin-' + themeName.toLowerCase() + '-styles');
}
if (theme && theme.version) {
themes[themeName] = { version: theme.version };
}
});
}
}, {
key: 'getFrameworks',
value: function getFrameworks(frameworks) {
var detectors = this.frameworkVersionDetectors();
Object.keys(detectors).forEach(function (framework) {
var detector = detectors[framework];
try {
var version = detector();
if (version) {
frameworks[framework] = { version: version };
}
} catch (e) {}
});
}
}, {
key: 'gather',
value: function gather(storage) {
var storedStats = storage.read();
var gatheredStats = {};
var types = ["elements", "frameworks", "themes"];
types.forEach(function (type) {
gatheredStats[type] = {};
if (!storedStats[type]) {
storedStats[type] = {};
}
});
var previousStats = JSON.stringify(storedStats);
this.getUsedVaadinElements(gatheredStats.elements);
this.getFrameworks(gatheredStats.frameworks);
this.getUsedVaadinThemes(gatheredStats.themes);
var now = this.now;
types.forEach(function (type) {
var keys = Object.keys(gatheredStats[type]);
keys.forEach(function (key) {
if (!storedStats[type][key] || _typeof(storedStats[type][key]) != _typeof({})) {
storedStats[type][key] = { firstUsed: now };
}
// Discards any previously logged version number
storedStats[type][key].version = gatheredStats[type][key].version;
storedStats[type][key].lastUsed = now;
});
});
var newStats = JSON.stringify(storedStats);
storage.write(newStats);
if (newStats != previousStats && Object.keys(storedStats).length > 0) {
this.logger.debug("New stats: " + newStats);
}
}
}]);
return StatisticsGatherer;
}();
var StatisticsStorage = function () {
function StatisticsStorage(key) {
classCallCheck(this, StatisticsStorage);
this.key = key;
}
createClass(StatisticsStorage, [{
key: 'read',
value: function read() {
var localStorageStatsString = localStorage.getItem(this.key);
try {
return JSON.parse(localStorageStatsString ? localStorageStatsString : '{}');
} catch (e) {
return {};
}
}
}, {
key: 'write',
value: function write(data) {
localStorage.setItem(this.key, data);
}
}, {
key: 'clear',
value: function clear() {
localStorage.removeItem(this.key);
}
}, {
key: 'isEmpty',
value: function isEmpty() {
var storedStats = this.read();
var empty = true;
Object.keys(storedStats).forEach(function (key) {
if (Object.keys(storedStats[key]).length > 0) {
empty = false;
}
});
return empty;
}
}]);
return StatisticsStorage;
}();
var StatisticsSender = function () {
function StatisticsSender(url, logger) {
classCallCheck(this, StatisticsSender);
this.url = url;
this.logger = logger;
}
createClass(StatisticsSender, [{
key: 'send',
value: function send(data, errorHandler) {
var logger = this.logger;
if (navigator.onLine === false) {
logger.debug("Offline, can't send");
errorHandler();
return;
}
logger.debug("Sending data to " + this.url);
var req = new XMLHttpRequest();
req.withCredentials = true;
req.addEventListener("load", function () {
// Stats sent, nothing more to do
logger.debug("Response: " + req.responseText);
});
req.addEventListener("error", function () {
logger.debug("Send failed");
errorHandler();
});
req.addEventListener("abort", function () {
logger.debug("Send aborted");
errorHandler();
});
req.open("POST", this.url);
req.setRequestHeader("Content-Type", "application/json");
req.send(data);
}
}]);
return StatisticsSender;
}();
var StatisticsLogger = function () {
function StatisticsLogger(id) {
classCallCheck(this, StatisticsLogger);
this.id = id;
}
createClass(StatisticsLogger, [{
key: '_isDebug',
value: function _isDebug() {
return localStorage.getItem("vaadin." + this.id + ".debug");
}
}, {
key: 'debug',
value: function debug(msg) {
if (this._isDebug()) {
console.info(this.id + ": " + msg);
}
}
}]);
return StatisticsLogger;
}();
var UsageStatistics = function () {
function UsageStatistics() {
classCallCheck(this, UsageStatistics);
this.now = new Date();
this.timeNow = this.now.getTime();
this.gatherDelay = 10; // Delay between loading this file and gathering stats
this.initialDelay = 24 * 60 * 60;
this.logger = new StatisticsLogger("statistics");
this.storage = new StatisticsStorage("vaadin.statistics.basket");
this.gatherer = new StatisticsGatherer(this.logger);
this.sender = new StatisticsSender("https://tools.vaadin.com/usage-stats/submit", this.logger);
}
createClass(UsageStatistics, [{
key: 'maybeGatherAndSend',
value: function maybeGatherAndSend() {
var _this = this;
if (localStorage.getItem(UsageStatistics.optOutKey)) {
return;
}
this.gatherer.gather(this.storage);
setTimeout(function () {
_this.maybeSend();
}, this.gatherDelay * 1000);
}
}, {
key: 'lottery',
value: function lottery() {
return true;
}
}, {
key: 'currentMonth',
value: function currentMonth() {
return this.now.getYear() * 12 + this.now.getMonth();
}
}, {
key: 'maybeSend',
value: function maybeSend() {
var firstUse = Number(localStorage.getItem(UsageStatistics.firstUseKey));
var monthProcessed = Number(localStorage.getItem(UsageStatistics.monthProcessedKey));
if (!firstUse) {
// Use a grace period to avoid interfering with tests, incognito mode etc
firstUse = this.timeNow;
localStorage.setItem(UsageStatistics.firstUseKey, firstUse);
}
if (this.timeNow < firstUse + this.initialDelay * 1000) {
this.logger.debug("No statistics will be sent until the initial delay of " + this.initialDelay + "s has passed");
return;
}
if (this.currentMonth() <= monthProcessed) {
this.logger.debug("This month has already been processed");
return;
}
localStorage.setItem(UsageStatistics.monthProcessedKey, this.currentMonth());
// Use random sampling
if (this.lottery()) {
this.logger.debug("Congratulations, we have a winner!");
} else {
this.logger.debug("Sorry, no stats from you this time");
return;
}
this.send();
}
}, {
key: 'send',
value: function send() {
// Ensure we have the latest data
this.gatherer.gather(this.storage);
// Read, send and clean up
var data = this.storage.read();
data["firstUse"] = Number(localStorage.getItem(UsageStatistics.firstUseKey));
data["usageStatisticsVersion"] = UsageStatistics.version;
var info = 'This request contains usage statistics gathered from the application running in development mode. \n\nStatistics gathering is automatically disabled and excluded from production builds.\n\nFor details and to opt-out, see https://github.com/vaadin/vaadin-usage-statistics.\n\n\n\n';
var self = this;
this.sender.send(info + JSON.stringify(data), function () {
// Revert the 'month processed' flag
localStorage.setItem(UsageStatistics.monthProcessedKey, self.currentMonth() - 1);
});
}
}], [{
key: 'version',
get: function get$1() {
return '2.1.2';
}
}, {
key: 'firstUseKey',
get: function get$1() {
return 'vaadin.statistics.firstuse';
}
}, {
key: 'monthProcessedKey',
get: function get$1() {
return 'vaadin.statistics.monthProcessed';
}
}, {
key: 'optOutKey',
get: function get$1() {
return 'vaadin.statistics.optout';
}
}]);
return UsageStatistics;
}();
try {
window.Vaadin = window.Vaadin || {};
window.Vaadin.usageStatsChecker = window.Vaadin.usageStatsChecker || new UsageStatistics();
window.Vaadin.usageStatsChecker.maybeGatherAndSend();
} catch (e) {
// Intentionally ignored as this is not a problem in the app being developed
}
}());
vaadin-dev-mode:end **/
};
/**
* @namespace Vaadin
*/
window.Vaadin = window.Vaadin || {};
/**
* @memberof Vaadin
*/
window.Vaadin.usageStatistics = function() {
if (typeof window.Vaadin.runIfDevelopmentMode === 'function') {
return window.Vaadin.runIfDevelopmentMode(maybeGatherAndSendStats);
}
};
})();
</script>