hina-cloud-js-sdk 3.1.6 → 3.1.8

Sign up to get free protection for your applications and to get access to all the features.
Files changed (45) hide show
  1. package/.gitlab-ci.yml +2 -6
  2. package/build/hina.cjs.min.js +1 -0
  3. package/build/hina.esm.min.js +1 -0
  4. package/build/hina.min.js +1 -4
  5. package/build/hotAnalyse.min.js +1 -1
  6. package/package.json +2 -7
  7. package/packages/core/dist/index.cjs.js +64 -0
  8. package/packages/core/dist/index.cjs.js.map +1 -0
  9. package/packages/core/dist/index.d.ts +45 -0
  10. package/packages/core/dist/index.esm.js +62 -0
  11. package/packages/core/dist/index.esm.js.map +1 -0
  12. package/packages/core/dist/index.global.js +1199 -0
  13. package/packages/core/dist/index.global.js.map +1 -0
  14. package/packages/core/dist/index.js +1200 -0
  15. package/packages/core/dist/index.js.map +1 -0
  16. package/packages/monitor/dist/index.cjs.js +150 -0
  17. package/packages/monitor/dist/index.cjs.js.map +1 -0
  18. package/packages/monitor/dist/index.d.ts +35 -0
  19. package/packages/monitor/dist/index.esm.js +145 -0
  20. package/packages/monitor/dist/index.esm.js.map +1 -0
  21. package/packages/monitor/dist/index.global.js +1343 -0
  22. package/packages/monitor/dist/index.global.js.map +1 -0
  23. package/packages/monitor/dist/index.js +1344 -0
  24. package/packages/monitor/dist/index.js.map +1 -0
  25. package/packages/track/dist/index.cjs.js +1930 -0
  26. package/packages/track/dist/index.cjs.js.map +1 -0
  27. package/packages/track/dist/index.d.ts +212 -0
  28. package/packages/track/dist/index.esm.js +1925 -0
  29. package/packages/track/dist/index.esm.js.map +1 -0
  30. package/packages/track/dist/index.global.js +4259 -0
  31. package/packages/track/dist/index.global.js.map +1 -0
  32. package/packages/track/dist/index.js +4260 -0
  33. package/packages/track/dist/index.js.map +1 -0
  34. package/packages/types/dist/index.d.ts +603 -0
  35. package/packages/types/dist/index.esm.js +25 -0
  36. package/packages/types/dist/index.esm.js.map +1 -0
  37. package/packages/utils/dist/index.cjs.js +1535 -0
  38. package/packages/utils/dist/index.cjs.js.map +1 -0
  39. package/packages/utils/dist/index.d.ts +394 -0
  40. package/packages/utils/dist/index.esm.js +1465 -0
  41. package/packages/utils/dist/index.esm.js.map +1 -0
  42. package/packages/utils/dist/index.global.js +2507 -0
  43. package/packages/utils/dist/index.global.js.map +1 -0
  44. package/packages/utils/dist/index.js +2508 -0
  45. package/packages/utils/dist/index.js.map +1 -0
@@ -0,0 +1,1930 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var hinaCloudCore = require('hina-cloud-core');
6
+ var hinaCloudTypes = require('hina-cloud-types');
7
+ var hinaCloudUtils = require('hina-cloud-utils');
8
+
9
+ /******************************************************************************
10
+ Copyright (c) Microsoft Corporation.
11
+
12
+ Permission to use, copy, modify, and/or distribute this software for any
13
+ purpose with or without fee is hereby granted.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
16
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
18
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
19
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
+ PERFORMANCE OF THIS SOFTWARE.
22
+ ***************************************************************************** */
23
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
24
+
25
+ var extendStatics = function(d, b) {
26
+ extendStatics = Object.setPrototypeOf ||
27
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
29
+ return extendStatics(d, b);
30
+ };
31
+
32
+ function __extends(d, b) {
33
+ if (typeof b !== "function" && b !== null)
34
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
35
+ extendStatics(d, b);
36
+ function __() { this.constructor = d; }
37
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
38
+ }
39
+
40
+ var __assign = function() {
41
+ __assign = Object.assign || function __assign(t) {
42
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
43
+ s = arguments[i];
44
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
45
+ }
46
+ return t;
47
+ };
48
+ return __assign.apply(this, arguments);
49
+ };
50
+
51
+ function __values(o) {
52
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
53
+ if (m) return m.call(o);
54
+ if (o && typeof o.length === "number") return {
55
+ next: function () {
56
+ if (o && i >= o.length) o = void 0;
57
+ return { value: o && o[i++], done: !o };
58
+ }
59
+ };
60
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
61
+ }
62
+
63
+ function __read(o, n) {
64
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
65
+ if (!m) return o;
66
+ var i = m.call(o), r, ar = [], e;
67
+ try {
68
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
69
+ }
70
+ catch (error) { e = { error: error }; }
71
+ finally {
72
+ try {
73
+ if (r && !r.done && (m = i["return"])) m.call(i);
74
+ }
75
+ finally { if (e) throw e.error; }
76
+ }
77
+ return ar;
78
+ }
79
+
80
+ function __spreadArray(to, from, pack) {
81
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
82
+ if (ar || !(i in from)) {
83
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
84
+ ar[i] = from[i];
85
+ }
86
+ }
87
+ return to.concat(ar || Array.prototype.slice.call(from));
88
+ }
89
+
90
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
91
+ var e = new Error(message);
92
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
93
+ };
94
+
95
+ var GET_DEFAULT_OPTIONS = function () {
96
+ return {
97
+ name: '',
98
+ serverUrl: '',
99
+ showLog: false,
100
+ autoTrackConfig: {
101
+ clickAutoTrack: true,
102
+ stayAutoTrack: true,
103
+ isCollectUrl: function () { return true; },
104
+ isCollectElement: function () { return true; },
105
+ isCollectInput: function () { return false; },
106
+ addCustomProperty: function () { },
107
+ stayDelayTime: 4000,
108
+ maxStayPageDuration: 18000,
109
+ collectTags: {
110
+ div: false
111
+ },
112
+ trackAttr: ['hn-click'],
113
+ pageviewAutoTrack: false,
114
+ pageLeaveAutoTrack: false
115
+ },
116
+ stayAutoTrackConfig: {
117
+ isCollectUrl: function () { return true; }
118
+ },
119
+ imgUseCrossOrigin: false,
120
+ isSinglePage: false,
121
+ batchSend: false,
122
+ appJsBridge: false,
123
+ sendType: hinaCloudTypes.ReportType.IMAGE,
124
+ dataSendTimeout: 3000,
125
+ presetProperties: {
126
+ latest_utm: true,
127
+ latest_utm_source: true,
128
+ latest_traffic_source_type: true,
129
+ latest_search_keyword: true,
130
+ latest_referrer: true,
131
+ url: true,
132
+ title: true
133
+ }
134
+ };
135
+ };
136
+ var ignoreTags = [
137
+ 'mark',
138
+ '/mark',
139
+ 'strong',
140
+ 'b',
141
+ 'em',
142
+ 'i',
143
+ 'u',
144
+ 'abbr',
145
+ 'ins',
146
+ 'del',
147
+ 's',
148
+ 'sup'
149
+ ];
150
+ var defaultTags = ['a', 'input', 'button', 'textarea'];
151
+
152
+ /**
153
+ * @description 批量发送数据
154
+ */
155
+ var BatchSend = /** @class */ (function () {
156
+ function BatchSend(context) {
157
+ this.context = context;
158
+ this.batchKey = 'hinasdk_tab';
159
+ this.batchDataKey = 'hinasdk_data_';
160
+ this.batchInterval();
161
+ }
162
+ BatchSend.prototype.getBatchConfig = function () {
163
+ var batchSend = this.context.options.batchSend;
164
+ return batchSend;
165
+ };
166
+ BatchSend.prototype.getStorageList = function () {
167
+ var _a;
168
+ var list = [];
169
+ var tabStorage = (_a = this.context.store.localStorage) === null || _a === void 0 ? void 0 : _a.get(this.batchKey);
170
+ if (tabStorage) {
171
+ list = hinaCloudUtils.safeJSONParse(tabStorage);
172
+ if (!hinaCloudUtils.isArray(list)) {
173
+ list = [];
174
+ }
175
+ }
176
+ return list;
177
+ };
178
+ BatchSend.prototype.batchInterval = function () {
179
+ var _this = this;
180
+ var sendInterval = this.getBatchConfig().sendInterval;
181
+ setTimeout(function () {
182
+ _this.send().then(function () {
183
+ _this.batchInterval();
184
+ });
185
+ }, sendInterval);
186
+ };
187
+ BatchSend.prototype.send = function () {
188
+ var _this = this;
189
+ return new Promise(function (resolve) {
190
+ var _a;
191
+ var tabStorageList = _this.getStorageList();
192
+ if (tabStorageList.length > 0) {
193
+ var _b = _this.getBatchConfig(), storageLimit = _b.storageLimit, dataSendTimeout = _b.dataSendTimeout;
194
+ var now = hinaCloudUtils.nowStamp();
195
+ var list = [];
196
+ var removeKeys_1 = [];
197
+ var len = tabStorageList.length;
198
+ for (var i = 0; i < len; i++) {
199
+ var _c = tabStorageList[i], dataKey = _c.dataKey, expireTime = _c.expireTime;
200
+ removeKeys_1.push(dataKey);
201
+ if (expireTime >= now) {
202
+ var data = (_a = _this.context.store.localStorage) === null || _a === void 0 ? void 0 : _a.get(dataKey);
203
+ if (data) {
204
+ list.push(hinaCloudUtils.safeJSONParse(data));
205
+ }
206
+ }
207
+ }
208
+ list = list.filter(Boolean);
209
+ if (list.length > storageLimit) {
210
+ list = list.slice(0, storageLimit);
211
+ }
212
+ if (list.length === 0) {
213
+ resolve();
214
+ }
215
+ else {
216
+ var serverUrl = _this.context.options.serverUrl;
217
+ var listStr = JSON.stringify(list);
218
+ new hinaCloudUtils.AjaxRequest({
219
+ url: serverUrl,
220
+ data: "data_list=".concat(hinaCloudUtils.base64Encode(listStr)),
221
+ timeout: dataSendTimeout
222
+ })
223
+ .run()
224
+ .then(function (res) {
225
+ if (res.type === 'success') {
226
+ _this.remove(removeKeys_1);
227
+ }
228
+ resolve();
229
+ });
230
+ }
231
+ }
232
+ });
233
+ };
234
+ BatchSend.prototype.remove = function (removeKeys) {
235
+ var _this = this;
236
+ var _a;
237
+ var firstKey = removeKeys[0];
238
+ var tabStorageList = this.getStorageList();
239
+ // 删除hinasdk_data_开头的数据
240
+ removeKeys.forEach(function (key) {
241
+ var _a;
242
+ (_a = _this.context.store.localStorage) === null || _a === void 0 ? void 0 : _a.remove(key);
243
+ });
244
+ // 删除hinasdk_tab数据
245
+ var index = tabStorageList.findIndex(function (item) { return item.dataKey === firstKey; });
246
+ if (index >= 0) {
247
+ var list = tabStorageList.slice(0, index);
248
+ (_a = this.context.store.localStorage) === null || _a === void 0 ? void 0 : _a.set(this.batchKey, JSON.stringify(list));
249
+ }
250
+ };
251
+ BatchSend.prototype.add = function (data) {
252
+ var _a, _b;
253
+ var _c = this.getBatchConfig(), sendInterval = _c.sendInterval, storageLimit = _c.storageLimit;
254
+ var dataKey = this.batchDataKey + hinaCloudUtils.getRandom();
255
+ var tabStorage = this.getStorageList();
256
+ tabStorage.unshift({
257
+ dataKey: dataKey,
258
+ expireTime: hinaCloudUtils.nowStamp() + sendInterval * 2
259
+ });
260
+ (_a = this.context.store.localStorage) === null || _a === void 0 ? void 0 : _a.set(this.batchKey, JSON.stringify(tabStorage));
261
+ (_b = this.context.store.localStorage) === null || _b === void 0 ? void 0 : _b.set(dataKey, JSON.stringify(data));
262
+ /**
263
+ * 满足以下条件,则发送数据
264
+ * 1. localStorage 条数超过最大限制
265
+ * 2. 发送类型为 track_signup 或 H_pageview
266
+ */
267
+ if (tabStorage.length > storageLimit ||
268
+ data.type === 'track_signup' ||
269
+ data.event === 'H_pageview') {
270
+ this.send();
271
+ }
272
+ };
273
+ return BatchSend;
274
+ }());
275
+
276
+ var ClickTrackPlugin = /** @class */ (function (_super) {
277
+ __extends(ClickTrackPlugin, _super);
278
+ function ClickTrackPlugin(options, context) {
279
+ var _this = _super.call(this, options, context) || this;
280
+ _this.options = options;
281
+ _this.context = context;
282
+ /**
283
+ * 插件名
284
+ */
285
+ _this.name = 'ClickTrackPlugin';
286
+ /**
287
+ * 默认采集标签
288
+ */
289
+ _this.isTrackList = {
290
+ a: true,
291
+ button: true
292
+ };
293
+ return _this;
294
+ }
295
+ ClickTrackPlugin.prototype.init = function (notify) {
296
+ var _this = this;
297
+ var _a = this.options.autoTrackConfig, clickAutoTrack = _a.clickAutoTrack, isCollectUrl = _a.isCollectUrl, isCollectElement = _a.isCollectElement, addCustomProperty = _a.addCustomProperty;
298
+ if (clickAutoTrack !== true)
299
+ return;
300
+ document.addEventListener('click', function (e) {
301
+ if (!isCollectUrl())
302
+ return;
303
+ var event = e || window.event;
304
+ if (!event)
305
+ return;
306
+ var eventTarget = event.target || event.srcElement;
307
+ var target = _this.getTargetElement(eventTarget, event);
308
+ if (target) {
309
+ // 判断是否要上报此元素的点击事件
310
+ if (hinaCloudUtils.isFunction(isCollectElement) && !isCollectElement(target)) {
311
+ return false;
312
+ }
313
+ var props = _this.getClickElementInfo(target);
314
+ var _a = _this.getPageXYInfo(event, target), H_page_x = _a.H_page_x, H_page_y = _a.H_page_y;
315
+ props.H_page_x = H_page_x;
316
+ props.H_page_y = H_page_y;
317
+ if (hinaCloudUtils.isFunction(addCustomProperty)) {
318
+ var customProperty = addCustomProperty(target);
319
+ if (hinaCloudUtils.isObject(customProperty)) {
320
+ props = hinaCloudUtils.merge(props, customProperty);
321
+ }
322
+ }
323
+ notify(props);
324
+ }
325
+ }, true);
326
+ };
327
+ ClickTrackPlugin.prototype.transform = function (data) {
328
+ var props = this.context.getReportData('track', 'H_WebClick', data);
329
+ return props;
330
+ };
331
+ ClickTrackPlugin.prototype.hasAttribute = function (element, attrName) {
332
+ var _a;
333
+ if (element.hasAttribute) {
334
+ return element.hasAttribute(attrName);
335
+ }
336
+ if (element.attributes) {
337
+ return !!((_a = element.attributes[attrName]) === null || _a === void 0 ? void 0 : _a.value);
338
+ }
339
+ };
340
+ ClickTrackPlugin.prototype.hasAttributes = function (element, attrNames) {
341
+ if (hinaCloudUtils.isArray(attrNames)) {
342
+ for (var i = 0; i < attrNames.length; i++) {
343
+ if (this.hasAttribute(element, attrNames[i])) {
344
+ return true;
345
+ }
346
+ }
347
+ }
348
+ return false;
349
+ };
350
+ ClickTrackPlugin.prototype.hasElement = function (element) {
351
+ var e_1, _a;
352
+ var _b;
353
+ var paths = hinaCloudUtils.getElementParents(element);
354
+ var trackAttr = this.options.autoTrackConfig.trackAttr || [];
355
+ if (hinaCloudUtils.isArray(paths) && paths.length > 0) {
356
+ try {
357
+ for (var paths_1 = __values(paths), paths_1_1 = paths_1.next(); !paths_1_1.done; paths_1_1 = paths_1.next()) {
358
+ var path = paths_1_1.value;
359
+ var tagName = (_b = path.tagName) === null || _b === void 0 ? void 0 : _b.toLowerCase();
360
+ if (hinaCloudUtils.isElement(path) &&
361
+ (this.isTrackList[tagName] || this.hasAttributes(path, trackAttr))) {
362
+ return path;
363
+ }
364
+ }
365
+ }
366
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
367
+ finally {
368
+ try {
369
+ if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) _a.call(paths_1);
370
+ }
371
+ finally { if (e_1) throw e_1.error; }
372
+ }
373
+ }
374
+ };
375
+ ClickTrackPlugin.prototype.getDivMaxLevel = function () {
376
+ var _a;
377
+ var collectTags = this.options.autoTrackConfig.collectTags;
378
+ return ((_a = collectTags.div) === null || _a === void 0 ? void 0 : _a.maxLevel) || 1;
379
+ };
380
+ /**
381
+ * 针对div标签,判断是否是忽略的样式标签
382
+ * @param tagName
383
+ */
384
+ ClickTrackPlugin.prototype.isStyleTag = function (tagName) {
385
+ var _a;
386
+ var collectTags = this.options.autoTrackConfig.collectTags;
387
+ var ignoreTags = ((_a = collectTags.div) === null || _a === void 0 ? void 0 : _a.ignoreTags) || [];
388
+ return ignoreTags === null || ignoreTags === void 0 ? void 0 : ignoreTags.includes(tagName);
389
+ };
390
+ /**
391
+ * 获取可采集元素的父元素
392
+ * @param target
393
+ */
394
+ ClickTrackPlugin.prototype.getCollectableParent = function (target) {
395
+ var _a;
396
+ try {
397
+ var parentNode = target.parentNode;
398
+ var parentTagName = parentNode ? (_a = parentNode.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase() : '';
399
+ if (parentTagName === 'body') {
400
+ return false;
401
+ }
402
+ var maxLevel = this.getDivMaxLevel();
403
+ if (parentTagName === 'div' &&
404
+ (maxLevel > 1 || this.isCollectableDiv(parentNode))) {
405
+ return parentNode;
406
+ }
407
+ if (parentNode && this.isStyleTag(parentTagName)) {
408
+ return this.getCollectableParent(parentNode);
409
+ }
410
+ }
411
+ catch (error) {
412
+ this.context.log(error, hinaCloudTypes.ConsoleTypes.ERROR);
413
+ }
414
+ return false;
415
+ };
416
+ /**
417
+ * 是否是可以收集的div
418
+ * @param element
419
+ */
420
+ ClickTrackPlugin.prototype.isCollectableDiv = function (element) {
421
+ var _a;
422
+ try {
423
+ var children = element.children || [];
424
+ if (children.length === 0) {
425
+ return true;
426
+ }
427
+ for (var i = 0; i < children.length; i++) {
428
+ var child = children[i];
429
+ if (hinaCloudUtils.isElement(child)) {
430
+ var tagName = (_a = child.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase();
431
+ var maxLevel = this.getDivMaxLevel();
432
+ if ((tagName === 'div' && maxLevel > 1) || this.isStyleTag(tagName)) {
433
+ if (!this.isCollectableDiv(child)) {
434
+ return false;
435
+ }
436
+ }
437
+ else {
438
+ return false;
439
+ }
440
+ }
441
+ }
442
+ return true;
443
+ }
444
+ catch (error) {
445
+ this.context.log(error, hinaCloudTypes.ConsoleTypes.ERROR);
446
+ }
447
+ return false;
448
+ };
449
+ /**
450
+ * 判断div的层级是否有效
451
+ * @param rootElement
452
+ */
453
+ ClickTrackPlugin.prototype.isDivLevelValid = function (rootElement) {
454
+ var maxLevel = this.getDivMaxLevel();
455
+ var htmlCollection = rootElement.getElementsByTagName('div');
456
+ for (var i = htmlCollection.length - 1; i >= 0; i--) {
457
+ if (this.getDivLevels(htmlCollection[i], rootElement) > maxLevel) {
458
+ return false;
459
+ }
460
+ }
461
+ return true;
462
+ };
463
+ /**
464
+ * 获取指定元素的路径
465
+ * @param element 当前元素
466
+ * @param ignoreId 是否忽略id
467
+ * @param rootElement 根元素
468
+ */
469
+ ClickTrackPlugin.prototype.getElementPath = function (element, ignoreId, rootElement) {
470
+ var _a, _b;
471
+ var names = [];
472
+ while (hinaCloudUtils.isElement(element) && element.parentNode) {
473
+ if (element.id &&
474
+ !ignoreId &&
475
+ /^[A-Za-z][-A-Za-z0-9_:.]*$/.test(element.id)) {
476
+ var tagName = element.tagName || '';
477
+ names.unshift("".concat(tagName.toLowerCase(), "#").concat(element.id));
478
+ break;
479
+ }
480
+ else {
481
+ if (rootElement && element === rootElement) {
482
+ names.unshift((_a = element.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase());
483
+ break;
484
+ }
485
+ else if (element === document.body) {
486
+ names.unshift('body');
487
+ break;
488
+ }
489
+ else {
490
+ names.unshift((_b = element.tagName) === null || _b === void 0 ? void 0 : _b.toLowerCase());
491
+ }
492
+ element = element.parentNode;
493
+ }
494
+ }
495
+ return names.join(' > ');
496
+ };
497
+ ClickTrackPlugin.prototype.getDivLevels = function (element, rootElement) {
498
+ var path = this.getElementPath(element, true, rootElement);
499
+ var pathArr = path.split(' > ');
500
+ var level = 0;
501
+ pathArr.forEach(function (tag) {
502
+ if (tag === 'div') {
503
+ level++;
504
+ }
505
+ });
506
+ return level;
507
+ };
508
+ ClickTrackPlugin.prototype.getTargetElement = function (eventTarget, event) {
509
+ var _a;
510
+ if (!hinaCloudUtils.isElement(eventTarget)) {
511
+ return null;
512
+ }
513
+ var tagName = (_a = eventTarget.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase();
514
+ if (!hinaCloudUtils.isString(tagName)) {
515
+ return null;
516
+ }
517
+ if (['body', 'html'].includes(tagName)) {
518
+ return null;
519
+ }
520
+ if (this.context.trackTags.includes(tagName) && tagName !== 'div') {
521
+ return eventTarget;
522
+ }
523
+ /**
524
+ * div处理情况
525
+ * 1.div为子结点(无子元素)时采集 div 的点击;
526
+ * 2.div中有且只有样式标签([‘mark’,’strong’,’b’,’em’,’i’,’u’,’abbr’,’ins’,’del’,’s’,’sup’])时,点击 div 或者样式标签都采集 div 的点击。
527
+ * 3.div 通过配置最多可以采集3层嵌套情况
528
+ */
529
+ if (tagName === 'div') {
530
+ if (this.isDivLevelValid(eventTarget)) {
531
+ var maxLevel = this.getDivMaxLevel();
532
+ if (maxLevel > 1 || this.isCollectableDiv(eventTarget)) {
533
+ return eventTarget;
534
+ }
535
+ }
536
+ }
537
+ if (this.isStyleTag(tagName) &&
538
+ this.options.autoTrackConfig.collectTags.div) {
539
+ var parentTrackDiv = this.getCollectableParent(eventTarget);
540
+ if (parentTrackDiv && this.isDivLevelValid(parentTrackDiv)) {
541
+ return parentTrackDiv;
542
+ }
543
+ }
544
+ return this.hasElement(eventTarget) || null;
545
+ };
546
+ ClickTrackPlugin.prototype.getPageXYInfo = function (event, target) {
547
+ if (!event) {
548
+ return {};
549
+ }
550
+ var scrollLeft = hinaCloudUtils.getScrollLeft();
551
+ var scrollTop = hinaCloudUtils.getScrollTop();
552
+ var rect = target.getBoundingClientRect();
553
+ var pageX = event.pageX ||
554
+ event.clientX + scrollLeft ||
555
+ event.offsetX + ((rect === null || rect === void 0 ? void 0 : rect.left) || 0) + scrollLeft;
556
+ var pageY = event.pageY ||
557
+ event.clientY + scrollTop ||
558
+ event.offsetY + ((rect === null || rect === void 0 ? void 0 : rect.top) || 0) + scrollTop;
559
+ return {
560
+ H_page_x: hinaCloudUtils.formatDecimal(pageX, 3),
561
+ H_page_y: hinaCloudUtils.formatDecimal(pageY, 3)
562
+ };
563
+ };
564
+ ClickTrackPlugin.prototype.getClickElementInfo = function (element) {
565
+ var isCollectInput = this.options.autoTrackConfig.isCollectInput;
566
+ var isCollectInputValue = false;
567
+ if (hinaCloudUtils.isFunction(isCollectInput)) {
568
+ isCollectInputValue = isCollectInput(element);
569
+ }
570
+ var selector = this.getDomSelector(element);
571
+ var props = hinaCloudUtils.getElementProperties(element, isCollectInputValue);
572
+ props.H_element_selector = selector;
573
+ props.H_element_path = this.getElementPath(element, false);
574
+ return props;
575
+ };
576
+ ClickTrackPlugin.prototype.getDomSelector = function (element) {
577
+ var _a;
578
+ var paths = [];
579
+ while (element) {
580
+ var tagName = (_a = element.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase();
581
+ if (tagName === 'body' || !hinaCloudUtils.isElement(element)) {
582
+ paths.unshift('body');
583
+ break;
584
+ }
585
+ paths.unshift(this.getSelector(element));
586
+ if ((element === null || element === void 0 ? void 0 : element.getAttribute('id')) &&
587
+ /^[A-Za-z][-A-Za-z0-9_:.]*$/.test(element.getAttribute('id'))) {
588
+ break;
589
+ }
590
+ element = element.parentNode;
591
+ }
592
+ return paths.join(' > ');
593
+ };
594
+ ClickTrackPlugin.prototype.getSelector = function (element) {
595
+ var _a, _b;
596
+ var tagName = (_a = element.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase();
597
+ var i = -1;
598
+ if (((_b = element.parentNode) === null || _b === void 0 ? void 0 : _b.nodeType) !== 9) {
599
+ i = this.getDomIndex(element);
600
+ }
601
+ var idValue = element.getAttribute('id');
602
+ if (idValue && /^[A-Za-z][-A-Za-z0-9_:.]*$/.test(idValue)) {
603
+ return "#".concat(idValue);
604
+ }
605
+ return tagName + (i > -1 ? ":nth-of-type(".concat(i + 1, ")") : '');
606
+ };
607
+ ClickTrackPlugin.prototype.getDomIndex = function (element) {
608
+ var _a, _b;
609
+ if (element.parentNode) {
610
+ var index = 0;
611
+ var tagName = (_a = element.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase();
612
+ var children = element.parentNode.children;
613
+ for (var i = 0; i < children.length; i++) {
614
+ var child = children[i];
615
+ var childTagName = (_b = child.tagName) === null || _b === void 0 ? void 0 : _b.toLowerCase();
616
+ if (childTagName === tagName) {
617
+ if (child === element) {
618
+ return index;
619
+ }
620
+ index++;
621
+ }
622
+ }
623
+ }
624
+ return -1;
625
+ };
626
+ return ClickTrackPlugin;
627
+ }(hinaCloudTypes.PluginBase));
628
+
629
+ var StayTrackPlugin = /** @class */ (function (_super) {
630
+ __extends(StayTrackPlugin, _super);
631
+ function StayTrackPlugin(options, context) {
632
+ var _this = _super.call(this, options, context) || this;
633
+ _this.options = options;
634
+ _this.context = context;
635
+ _this.name = 'StayTrackPlugin';
636
+ _this.timer = null;
637
+ _this.previousTime = hinaCloudUtils.nowStamp();
638
+ _this.previousOffsetTop = 0;
639
+ return _this;
640
+ }
641
+ StayTrackPlugin.prototype.init = function (notify) {
642
+ var _this = this;
643
+ var _a = this.options, autoTrackConfig = _a.autoTrackConfig, stayAutoTrackConfig = _a.stayAutoTrackConfig;
644
+ if (autoTrackConfig.stayAutoTrack !== true) {
645
+ return;
646
+ }
647
+ var isCollectUrl = stayAutoTrackConfig.isCollectUrl;
648
+ if (!hinaCloudUtils.isFunction(isCollectUrl)) {
649
+ isCollectUrl = function () { return true; };
650
+ }
651
+ if (this.timer) {
652
+ clearTimeout(this.timer);
653
+ this.timer = null;
654
+ }
655
+ this.previousTime = hinaCloudUtils.nowStamp();
656
+ window.addEventListener('load', function () {
657
+ _this.previousOffsetTop = hinaCloudUtils.getScrollTop();
658
+ });
659
+ window.addEventListener('scroll', function () {
660
+ if (!isCollectUrl())
661
+ return;
662
+ if (_this.timer)
663
+ return;
664
+ _this.timer = setTimeout(function () {
665
+ _this.run(notify);
666
+ clearTimeout(_this.timer);
667
+ _this.timer = null;
668
+ }, 1000);
669
+ });
670
+ window.addEventListener('unload', function () {
671
+ if (!isCollectUrl())
672
+ return;
673
+ _this.run(notify, true);
674
+ });
675
+ };
676
+ StayTrackPlugin.prototype.transform = function (data) {
677
+ var props = this.context.getReportData('track', 'H_WebStay', data);
678
+ return props;
679
+ };
680
+ StayTrackPlugin.prototype.run = function (notify, isClosePage) {
681
+ if (isClosePage === void 0) { isClosePage = false; }
682
+ var autoTrackConfig = this.options.autoTrackConfig;
683
+ var stayDelayTime = autoTrackConfig.stayDelayTime, maxStayPageDuration = autoTrackConfig.maxStayPageDuration;
684
+ var offsetTop = hinaCloudUtils.getScrollTop();
685
+ var nowTime = hinaCloudUtils.nowStamp();
686
+ var duration = nowTime - this.previousTime;
687
+ if (isClosePage ||
688
+ (duration > stayDelayTime && offsetTop !== this.previousOffsetTop)) {
689
+ var props = {
690
+ H_viewport_position: this.previousOffsetTop,
691
+ event_duration: Math.min(duration / 1000, maxStayPageDuration)
692
+ };
693
+ notify(props);
694
+ }
695
+ this.previousTime = nowTime;
696
+ this.previousOffsetTop = offsetTop;
697
+ };
698
+ return StayTrackPlugin;
699
+ }(hinaCloudTypes.PluginBase));
700
+
701
+ var PageLeavePluginName = 'PageLeavePlugin';
702
+ var PageLeavePlugin = /** @class */ (function (_super) {
703
+ __extends(PageLeavePlugin, _super);
704
+ function PageLeavePlugin(options, context) {
705
+ var _this = _super.call(this, options, context) || this;
706
+ _this.options = options;
707
+ _this.context = context;
708
+ _this.name = PageLeavePluginName;
709
+ _this.pageId = Number(String(hinaCloudUtils.getRandom()).slice(2, 5) +
710
+ String(hinaCloudUtils.getRandom()).slice(2, 4) +
711
+ String(hinaCloudUtils.nowStamp()).slice(-4));
712
+ _this.storageName = 'hinasdk_pageleave_';
713
+ _this.heartbeatIntervalTime = 5000; // 5s
714
+ _this.maxDuration = 432000; // 5天
715
+ _this.heartbeatIntervalTimer = null;
716
+ _this.startTime = hinaCloudUtils.nowStamp();
717
+ /**
718
+ * 页面url
719
+ */
720
+ _this.url = window.location.href;
721
+ /**
722
+ * 上一个页面url
723
+ */
724
+ _this.previousUrl = document.referrer;
725
+ /**
726
+ * 页面显示状态
727
+ */
728
+ _this.pageShowStatus = true;
729
+ return _this;
730
+ }
731
+ PageLeavePlugin.prototype.init = function () {
732
+ var pageLeaveAutoTrack = this.options.autoTrackConfig.pageLeaveAutoTrack;
733
+ if (!pageLeaveAutoTrack)
734
+ return;
735
+ var _a = this.normalizePageLeaveAutoTrack(), heartbeat_interval_time = _a.heartbeat_interval_time, max_duration = _a.max_duration;
736
+ if (heartbeat_interval_time && heartbeat_interval_time > 0) {
737
+ this.heartbeatIntervalTime = heartbeat_interval_time * 1000;
738
+ }
739
+ if (max_duration && max_duration > 0) {
740
+ this.maxDuration = Number(max_duration);
741
+ }
742
+ this.startTime = hinaCloudUtils.nowStamp();
743
+ this.addPageLeaveEventListener();
744
+ if (document.hidden) {
745
+ this.pageShowStatus = false;
746
+ }
747
+ else {
748
+ this.addHeartBeatInterval();
749
+ }
750
+ };
751
+ PageLeavePlugin.prototype.transform = function (data) {
752
+ return undefined;
753
+ };
754
+ PageLeavePlugin.prototype.normalizePageLeaveAutoTrack = function () {
755
+ var pageLeaveAutoTrack = this.options.autoTrackConfig.pageLeaveAutoTrack;
756
+ return hinaCloudUtils.isObject(pageLeaveAutoTrack)
757
+ ? pageLeaveAutoTrack
758
+ : {};
759
+ };
760
+ PageLeavePlugin.prototype.addPageLeaveEventListener = function () {
761
+ this.addPageStartListener();
762
+ this.addPageSwitchListener();
763
+ this.addSinglePageListener();
764
+ this.addPageEndListener();
765
+ };
766
+ PageLeavePlugin.prototype.addPageStartListener = function () {
767
+ var _this = this;
768
+ if ('onpageshow' in window) {
769
+ window.addEventListener('pageshow', function () {
770
+ _this.pageStartHandler();
771
+ });
772
+ }
773
+ };
774
+ PageLeavePlugin.prototype.addPageSwitchListener = function () {
775
+ var _this = this;
776
+ new hinaCloudUtils.ListenPageState({
777
+ visible: function () {
778
+ _this.pageStartHandler();
779
+ _this.addHeartBeatInterval();
780
+ },
781
+ hidden: function () {
782
+ _this.url = window.location.href;
783
+ _this.pageEndHandler();
784
+ _this.stopHeartBeatInterval();
785
+ }
786
+ });
787
+ };
788
+ PageLeavePlugin.prototype.addSinglePageListener = function () {
789
+ var _this = this;
790
+ hinaCloudUtils.mitt.on('urlChange', function (params) {
791
+ var fromHref = params.fromHref;
792
+ if (fromHref !== window.location.href) {
793
+ _this.url = fromHref;
794
+ _this.pageEndHandler();
795
+ _this.stopHeartBeatInterval();
796
+ _this.pageStartHandler();
797
+ _this.addHeartBeatInterval();
798
+ }
799
+ });
800
+ };
801
+ PageLeavePlugin.prototype.addPageEndListener = function () {
802
+ var _this = this;
803
+ var events = ['pagehide', 'beforeunload', 'unload'];
804
+ events.forEach(function (event) {
805
+ if ("on".concat(events) in window) {
806
+ window.addEventListener(event, function () {
807
+ _this.pageEndHandler();
808
+ _this.stopHeartBeatInterval();
809
+ });
810
+ }
811
+ });
812
+ };
813
+ PageLeavePlugin.prototype.pageStartHandler = function () {
814
+ this.startTime = hinaCloudUtils.nowStamp();
815
+ this.pageShowStatus = !document.hidden;
816
+ this.url = window.location.href;
817
+ };
818
+ PageLeavePlugin.prototype.pageEndHandler = function () {
819
+ if (!this.pageShowStatus)
820
+ return;
821
+ this.pageShowStatus = false;
822
+ if (this.isCollectUrl()) {
823
+ var properties = this.getPageLeaveProperties();
824
+ var data = this.context.getReportData('track', 'H_WebPageLeave', properties);
825
+ this.context.report(data);
826
+ }
827
+ this.delHeartBeatData();
828
+ };
829
+ PageLeavePlugin.prototype.addHeartBeatInterval = function () {
830
+ if (!this.context.store.localStorage)
831
+ return;
832
+ this.startHeartBeatInterval();
833
+ };
834
+ PageLeavePlugin.prototype.startHeartBeatInterval = function () {
835
+ var _this = this;
836
+ if (this.heartbeatIntervalTimer) {
837
+ this.stopHeartBeatInterval();
838
+ }
839
+ if (this.isCollectUrl()) {
840
+ this.heartbeatIntervalTimer = setInterval(function () {
841
+ _this.saveHeartBeatData();
842
+ }, this.heartbeatIntervalTime);
843
+ this.saveHeartBeatData('first_heartbeat');
844
+ }
845
+ this.reissueHeartBeatData();
846
+ };
847
+ PageLeavePlugin.prototype.reissueHeartBeatData = function () {
848
+ var localStorage = this.context.store.localStorage;
849
+ var storageLen = localStorage.length();
850
+ for (var i = 0; i < storageLen; i++) {
851
+ var itemKey = localStorage.key(i);
852
+ if (itemKey &&
853
+ itemKey !== this.storageName + this.pageId &&
854
+ itemKey.includes(this.storageName)) {
855
+ var value = localStorage.get(itemKey);
856
+ var result = hinaCloudUtils.safeJSONParse(value);
857
+ if (hinaCloudUtils.isObject(result) &&
858
+ hinaCloudUtils.nowStamp() - result.time > result.heartbeat_interval_time + 5000) {
859
+ delete result.heartbeat_interval_time;
860
+ this.context.report(result);
861
+ }
862
+ this.delHeartBeatData(itemKey);
863
+ }
864
+ }
865
+ };
866
+ PageLeavePlugin.prototype.stopHeartBeatInterval = function () {
867
+ if (this.heartbeatIntervalTimer) {
868
+ clearInterval(this.heartbeatIntervalTimer);
869
+ this.heartbeatIntervalTimer = null;
870
+ }
871
+ };
872
+ PageLeavePlugin.prototype.delHeartBeatData = function (storageKey) {
873
+ if (this.context.store.localStorage) {
874
+ this.context.store.localStorage.remove(storageKey || this.storageName + this.pageId);
875
+ }
876
+ };
877
+ PageLeavePlugin.prototype.isCollectUrl = function () {
878
+ var isCollectUrl = this.normalizePageLeaveAutoTrack().isCollectUrl;
879
+ if (hinaCloudUtils.isFunction(isCollectUrl)) {
880
+ return isCollectUrl(this.url);
881
+ }
882
+ return true;
883
+ };
884
+ PageLeavePlugin.prototype.saveHeartBeatData = function (type) {
885
+ var properties = this.getPageLeaveProperties();
886
+ properties.H_time = hinaCloudUtils.nowStamp();
887
+ if (type === 'first_heartbeat') {
888
+ properties.event_duration = 3;
889
+ }
890
+ var props = this.context.getReportData('track', 'H_WebPageLeave', properties);
891
+ props.heartbeat_interval_time = this.heartbeatIntervalTime;
892
+ this.context.store.localStorage.set(this.storageName + this.pageId, JSON.stringify(props));
893
+ };
894
+ PageLeavePlugin.prototype.getPageLeaveProperties = function () {
895
+ var duration = (hinaCloudUtils.nowStamp() - this.startTime) / 1000;
896
+ if (duration <= 0 || duration > this.maxDuration) {
897
+ duration = 0;
898
+ }
899
+ else {
900
+ duration = hinaCloudUtils.formatDecimal(duration, 3);
901
+ }
902
+ var _a = hinaCloudUtils.getURL(this.url), pathname = _a.pathname, hash = _a.hash;
903
+ var referrer = hinaCloudUtils.getReferrer(this.previousUrl);
904
+ var properties = {
905
+ H_url: this.url,
906
+ H_url_path: pathname,
907
+ H_url_hash: hash,
908
+ H_referrer: referrer,
909
+ H_referrer_host: referrer ? hinaCloudUtils.getHostname(referrer) : ''
910
+ };
911
+ if (duration) {
912
+ properties.event_duration = duration;
913
+ }
914
+ var custom_props = this.normalizePageLeaveAutoTrack().custom_props;
915
+ if (hinaCloudUtils.isObject(custom_props)) {
916
+ properties = __assign(__assign({}, properties), (custom_props || {}));
917
+ }
918
+ return properties;
919
+ };
920
+ return PageLeavePlugin;
921
+ }(hinaCloudTypes.PluginBase));
922
+
923
+ var SiteLinkerPluginName = 'SiteLinkerPlugin';
924
+ var SiteLinkerPlugin = /** @class */ (function (_super) {
925
+ __extends(SiteLinkerPlugin, _super);
926
+ function SiteLinkerPlugin(options, context) {
927
+ var _this = _super.call(this, options, context) || this;
928
+ _this.options = options;
929
+ _this.context = context;
930
+ _this.name = SiteLinkerPluginName;
931
+ _this.linker = [];
932
+ return _this;
933
+ }
934
+ SiteLinkerPlugin.prototype.init = function () {
935
+ var linker = this.getLinkerConfig().linker;
936
+ if (!(hinaCloudUtils.isArray(linker) && linker.length > 0)) {
937
+ this.context.log('siteLinker plugin: Please configure the linker parameter', hinaCloudTypes.ConsoleTypes.WARN);
938
+ return;
939
+ }
940
+ // 处理配置
941
+ this.resolveOption();
942
+ this.setRefferId();
943
+ this.addClickListen();
944
+ };
945
+ SiteLinkerPlugin.prototype.transform = function () {
946
+ return undefined;
947
+ };
948
+ SiteLinkerPlugin.prototype.getLinkerConfig = function () {
949
+ var _a = this.options.siteLinkerConfig || {}, _b = _a.linker, linker = _b === void 0 ? [] : _b, re_login = _a.re_login;
950
+ return {
951
+ linker: linker || [],
952
+ re_login: re_login
953
+ };
954
+ };
955
+ SiteLinkerPlugin.prototype.resolveOption = function () {
956
+ var linker = this.getLinkerConfig().linker;
957
+ var len = linker.length;
958
+ var arr = [];
959
+ for (var i = 0; i < len; i++) {
960
+ var _a = linker[i], part_url = _a.part_url, after_hash = _a.after_hash;
961
+ if (/[A-Za-z0-9]+\./.test(part_url) && hinaCloudUtils.isBoolean(after_hash)) {
962
+ arr.push({
963
+ part_url: part_url,
964
+ after_hash: after_hash
965
+ });
966
+ }
967
+ else {
968
+ this.context.log("The configuration of linker ".concat(i + 1, " is not supported.Please check format"), hinaCloudTypes.ConsoleTypes.WARN);
969
+ }
970
+ }
971
+ this.linker = arr;
972
+ };
973
+ /**
974
+ * 多域名打通设置
975
+ */
976
+ SiteLinkerPlugin.prototype.setRefferId = function () {
977
+ var re_login = this.getLinkerConfig().re_login;
978
+ var urlId = this.getUrlId();
979
+ var isAnonymousId = urlId.startsWith('a');
980
+ urlId = urlId.substring(1);
981
+ if (urlId === '')
982
+ return;
983
+ var anonymousId = this.context.store.getAnonymousId();
984
+ var accountId = this.context.store.getAccountId();
985
+ if (isAnonymousId) {
986
+ if (urlId !== anonymousId) {
987
+ this.context.store.state.anonymousId = urlId;
988
+ this.context.store.save();
989
+ }
990
+ if (accountId) {
991
+ var props = this.context.getReportData('track_signup', 'H_SignUp', {});
992
+ this.context.report(props);
993
+ }
994
+ }
995
+ else if (!accountId || (re_login && accountId !== urlId)) {
996
+ this.context.setUserUId(urlId);
997
+ }
998
+ };
999
+ /**
1000
+ * 获取链接上的id
1001
+ */
1002
+ SiteLinkerPlugin.prototype.getUrlId = function () {
1003
+ /**
1004
+ * 匿名ID:a 登录ID:u
1005
+ * 如果是匿名ID:返回的是a+匿名ID 如果是登录ID:返回的是u+登录ID
1006
+ */
1007
+ var hnId = window.location.href.match(/_hnsdk=([au][^\?\#\&\=]+)/);
1008
+ if (hinaCloudUtils.isArray(hnId) && hnId[1]) {
1009
+ return hinaCloudUtils.handleDecodeURLComponent(hnId[1]);
1010
+ }
1011
+ return '';
1012
+ };
1013
+ /**
1014
+ * 判断url链接是否包含part_url
1015
+ * @param url
1016
+ */
1017
+ SiteLinkerPlugin.prototype.getPartUrl = function (url) {
1018
+ var len = this.linker.length;
1019
+ for (var i = 0; i < len; i++) {
1020
+ if (url.includes(this.linker[i].part_url)) {
1021
+ return true;
1022
+ }
1023
+ }
1024
+ return false;
1025
+ };
1026
+ /**
1027
+ * 获取url链接对应的linker配置中after_hash的值
1028
+ * @param url
1029
+ */
1030
+ SiteLinkerPlugin.prototype.getPartHash = function (url) {
1031
+ var len = this.linker.length;
1032
+ for (var i = 0; i < len; i++) {
1033
+ if (url.includes(this.linker[i].part_url)) {
1034
+ return this.linker[i].after_hash;
1035
+ }
1036
+ }
1037
+ return false;
1038
+ };
1039
+ /**
1040
+ * 获取当前的匿名ID和当前的登录ID
1041
+ */
1042
+ SiteLinkerPlugin.prototype.getCurrentId = function () {
1043
+ var accountId = this.context.store.getAccountId();
1044
+ var anonymousId = this.context.store.getAnonymousId();
1045
+ var hnId = accountId ? "u".concat(accountId) : "a".concat(anonymousId);
1046
+ return hinaCloudUtils.handleEncodeURLComponent(hnId);
1047
+ };
1048
+ /**
1049
+ * 重写a 标签的href链接
1050
+ * @param url
1051
+ * @param dom
1052
+ */
1053
+ SiteLinkerPlugin.prototype.rewriteUrl = function (url, dom) {
1054
+ /**
1055
+ * ([^?#]+):匹配直到遇到 ? 或 # 之前的任何字符,并将这部分捕获为第一组。
1056
+ * (\?[^#]*)?:可选地匹配 ? 后面直到遇到 # 之前的任何字符,并将这部分捕获为第二组。
1057
+ * (#.*)?:可选地匹配 # 后面的任何字符,并将这部分捕获为第三组。
1058
+ */
1059
+ var reg = /([^?#]+)(\?[^#]*)?(#.*)?/;
1060
+ var arr = reg.exec(url);
1061
+ var normalizeUrl = '';
1062
+ if (!arr)
1063
+ return;
1064
+ var host = arr[1] || ''; // 'http://www.xx.com'
1065
+ var search = arr[2] || ''; // '?xxx=xxx'
1066
+ var hash = arr[3] || ''; // '#xxx=xxx'
1067
+ var hnId = "_hnsdk=".concat(this.getCurrentId());
1068
+ var changeHnId = function (str) {
1069
+ var list = str.split('&');
1070
+ var result = [];
1071
+ list.forEach(function (value) {
1072
+ if (value.includes('_hnsdk')) {
1073
+ result.push(hnId);
1074
+ }
1075
+ else {
1076
+ result.push(value);
1077
+ }
1078
+ });
1079
+ return result.join('&');
1080
+ };
1081
+ if (this.getPartHash(url)) {
1082
+ var hasQuery = hash.includes('?'); // 判断是#xxx?xxx=xxx的格式
1083
+ var index = hash.indexOf('_hnsdk');
1084
+ if (hasQuery) {
1085
+ if (index >= 0) {
1086
+ normalizeUrl = "".concat(host).concat(search, "#").concat(hash.substring(1, index)).concat(changeHnId(hash.substring(index, hash.length)));
1087
+ }
1088
+ else {
1089
+ normalizeUrl = "".concat(host).concat(search, "#").concat(hash.substring(1), "&").concat(hnId);
1090
+ }
1091
+ }
1092
+ else {
1093
+ normalizeUrl = "".concat(host).concat(search, "#").concat(hash.substring(1), "?").concat(hnId);
1094
+ }
1095
+ }
1096
+ else {
1097
+ var hasQuery = /^\?(\w)+/.test(search); // 判断是否有?xxx=xxx的格式
1098
+ if (hasQuery) {
1099
+ if (search.includes('_hnsdk')) {
1100
+ normalizeUrl = "".concat(host, "?").concat(changeHnId(search.substring(1))).concat(hash);
1101
+ }
1102
+ else {
1103
+ normalizeUrl = "".concat(host).concat(search, "&").concat(hnId).concat(hash);
1104
+ }
1105
+ }
1106
+ else {
1107
+ normalizeUrl = "".concat(host, "?").concat(hnId).concat(hash);
1108
+ }
1109
+ }
1110
+ if (dom) {
1111
+ dom.href = normalizeUrl;
1112
+ }
1113
+ return normalizeUrl;
1114
+ };
1115
+ SiteLinkerPlugin.prototype.addClickListen = function () {
1116
+ var _this = this;
1117
+ var handleClick = function (event) {
1118
+ var _a, _b;
1119
+ var target = event.target;
1120
+ if (!target)
1121
+ return;
1122
+ var tagName = (_a = target.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase();
1123
+ var parentNode = target.parentNode;
1124
+ var parentTagName = (_b = parentNode === null || parentNode === void 0 ? void 0 : parentNode.tagName) === null || _b === void 0 ? void 0 : _b.toLowerCase();
1125
+ if ((tagName === 'a' && target.href) ||
1126
+ (parentTagName === 'a' && parentNode.href)) {
1127
+ var sdkUrl = void 0;
1128
+ var sdkTarget = void 0;
1129
+ if (tagName === 'a' && target.href) {
1130
+ sdkUrl = target.href;
1131
+ sdkTarget = target;
1132
+ }
1133
+ else {
1134
+ sdkUrl = parentNode.href;
1135
+ sdkTarget = parentNode;
1136
+ }
1137
+ var protocol = hinaCloudUtils.getURL(sdkUrl).protocol;
1138
+ if (protocol === 'http:' || protocol === 'https:') {
1139
+ if (_this.getPartUrl(sdkUrl)) {
1140
+ _this.rewriteUrl(sdkUrl, sdkTarget);
1141
+ }
1142
+ }
1143
+ }
1144
+ };
1145
+ if ('PointerEvent' in window) {
1146
+ document.addEventListener('pointerdown', handleClick);
1147
+ }
1148
+ else {
1149
+ document.addEventListener('mousedown', handleClick);
1150
+ }
1151
+ };
1152
+ return SiteLinkerPlugin;
1153
+ }(hinaCloudTypes.PluginBase));
1154
+
1155
+ var HistoryPlugin = /** @class */ (function (_super) {
1156
+ __extends(HistoryPlugin, _super);
1157
+ function HistoryPlugin(options, context) {
1158
+ var _this = _super.call(this, options, context) || this;
1159
+ _this.options = options;
1160
+ _this.context = context;
1161
+ _this.name = 'HistoryPlugin';
1162
+ /**
1163
+ * 上一次页面url
1164
+ */
1165
+ _this.lastHref = window.location.href;
1166
+ /**
1167
+ * 上一次路由path
1168
+ */
1169
+ _this.lastPath = window.location.pathname;
1170
+ return _this;
1171
+ }
1172
+ HistoryPlugin.prototype.init = function (notify) {
1173
+ if (!hinaCloudUtils.supportHistory())
1174
+ return;
1175
+ var _a = this.options, isSinglePage = _a.isSinglePage, pageviewAutoTrack = _a.autoTrackConfig.pageviewAutoTrack;
1176
+ var self = this;
1177
+ var originalOnpopstate = window.onpopstate;
1178
+ var handleRouterChange = function (currentPath, currentHref) {
1179
+ var params = {
1180
+ fromPath: self.lastPath,
1181
+ fromHref: self.lastHref,
1182
+ toPath: currentPath,
1183
+ toHref: currentHref
1184
+ };
1185
+ self.lastPath = currentPath;
1186
+ self.lastHref = currentHref;
1187
+ hinaCloudUtils.mitt.emit('urlChange', __assign(__assign({}, params), { mode: 'history' }));
1188
+ if (isSinglePage || pageviewAutoTrack === 'singlePage') {
1189
+ if (hinaCloudUtils.isFunction(isSinglePage)) {
1190
+ var extra = isSinglePage();
1191
+ if (hinaCloudUtils.isObject(extra)) {
1192
+ params = __assign(__assign({}, params), extra);
1193
+ }
1194
+ }
1195
+ notify(__assign(__assign({}, params), { H_referrer: self.lastHref }));
1196
+ }
1197
+ };
1198
+ window.onpopstate = function () {
1199
+ var args = [];
1200
+ for (var _i = 0; _i < arguments.length; _i++) {
1201
+ args[_i] = arguments[_i];
1202
+ }
1203
+ var currentPath = window.location.pathname;
1204
+ var currentHref = window.location.href;
1205
+ handleRouterChange(currentPath, currentHref);
1206
+ originalOnpopstate && originalOnpopstate.apply(this, args);
1207
+ };
1208
+ function historyReplaceFn(originalHistoryFn) {
1209
+ return function () {
1210
+ var args = [];
1211
+ for (var _i = 0; _i < arguments.length; _i++) {
1212
+ args[_i] = arguments[_i];
1213
+ }
1214
+ var currentPath = args[2];
1215
+ originalHistoryFn.apply(this, args);
1216
+ var currentHref = window.location.href;
1217
+ handleRouterChange(currentPath, currentHref);
1218
+ };
1219
+ }
1220
+ hinaCloudUtils.replaceOld(window.history, 'pushState', historyReplaceFn);
1221
+ hinaCloudUtils.replaceOld(window.history, 'replaceState', historyReplaceFn);
1222
+ };
1223
+ HistoryPlugin.prototype.transform = function (data) {
1224
+ this.context.autoTrack(data);
1225
+ return undefined;
1226
+ };
1227
+ return HistoryPlugin;
1228
+ }(hinaCloudTypes.PluginBase));
1229
+
1230
+ var HashPlugin = /** @class */ (function (_super) {
1231
+ __extends(HashPlugin, _super);
1232
+ function HashPlugin(options, context) {
1233
+ var _this = _super.call(this, options, context) || this;
1234
+ _this.options = options;
1235
+ _this.context = context;
1236
+ _this.name = 'HashPlugin';
1237
+ /**
1238
+ * 上一次页面url
1239
+ */
1240
+ _this.lastHref = window.location.href;
1241
+ /**
1242
+ * 上一次路由path
1243
+ */
1244
+ _this.lastPath = window.location.hash;
1245
+ return _this;
1246
+ }
1247
+ HashPlugin.prototype.init = function (notify) {
1248
+ var _this = this;
1249
+ var _a = this.options, isSinglePage = _a.isSinglePage, pageviewAutoTrack = _a.autoTrackConfig.pageviewAutoTrack;
1250
+ window.addEventListener('hashchange', function (event) {
1251
+ var newURL = event.newURL;
1252
+ var currentPath = hinaCloudUtils.getURL(newURL).hash;
1253
+ var params = {
1254
+ fromPath: _this.lastPath,
1255
+ fromHref: _this.lastHref,
1256
+ toPath: currentPath,
1257
+ toHref: newURL
1258
+ };
1259
+ hinaCloudUtils.mitt.emit('urlChange', __assign(__assign({}, params), { mode: 'history' }));
1260
+ _this.lastHref = newURL;
1261
+ _this.lastPath = currentPath;
1262
+ if (isSinglePage || pageviewAutoTrack === 'singlePage') {
1263
+ if (hinaCloudUtils.isFunction(isSinglePage)) {
1264
+ var extra = isSinglePage();
1265
+ if (hinaCloudUtils.isObject(extra)) {
1266
+ params = __assign(__assign({}, params), extra);
1267
+ }
1268
+ }
1269
+ notify(__assign(__assign({}, params), { H_referrer: _this.lastHref }));
1270
+ }
1271
+ });
1272
+ };
1273
+ HashPlugin.prototype.transform = function (data) {
1274
+ this.context.autoTrack(data);
1275
+ return undefined;
1276
+ };
1277
+ return HashPlugin;
1278
+ }(hinaCloudTypes.PluginBase));
1279
+
1280
+ var HinaTrack = /** @class */ (function (_super) {
1281
+ __extends(HinaTrack, _super);
1282
+ function HinaTrack(options, useInstancing) {
1283
+ if (useInstancing === void 0) { useInstancing = true; }
1284
+ var _this = _super.call(this, options, useInstancing) || this;
1285
+ /**
1286
+ * 上报数据的dom元素 默认有 'a', 'input', 'button', 'textarea'
1287
+ */
1288
+ _this.trackTags = defaultTags;
1289
+ /**
1290
+ * 事件静态公共属性
1291
+ */
1292
+ _this.presetProps = {};
1293
+ /**
1294
+ * 插件列表
1295
+ */
1296
+ _this.plugins = [];
1297
+ _this.consolePrefix = '埋点SDK';
1298
+ // 使用new的方式初始化SDK,需要默认调用init方法进行初始化
1299
+ if (_this.useInstancing) {
1300
+ _this.init(options);
1301
+ }
1302
+ return _this;
1303
+ }
1304
+ /**
1305
+ * 注册/初始化SDK
1306
+ * @param options
1307
+ */
1308
+ HinaTrack.prototype.init = function (options) {
1309
+ if (this.isReady) {
1310
+ this.log('hinaSDK has been initialized', hinaCloudTypes.ConsoleTypes.ERROR);
1311
+ return;
1312
+ }
1313
+ // 默认配置项
1314
+ var default_config = GET_DEFAULT_OPTIONS();
1315
+ // 将用户配置项和默认配置项合并
1316
+ this.options = hinaCloudUtils.merge(default_config, options);
1317
+ // 处理配置信息
1318
+ this.normalizeConfig();
1319
+ // 初始化state
1320
+ this.initState();
1321
+ // 处理广告参数
1322
+ this.initAdvProps();
1323
+ // 插件初始化
1324
+ this.initPlugins();
1325
+ // SDK初始化成功,一切准备就绪
1326
+ this.isReady = true;
1327
+ this.log('hinaSDK initialized successfully');
1328
+ };
1329
+ /**
1330
+ * 处理配置信息
1331
+ */
1332
+ HinaTrack.prototype.normalizeConfig = function () {
1333
+ var _a = this.options, serverUrl = _a.serverUrl, sendType = _a.sendType, batchSend = _a.batchSend, _b = _a.autoTrackConfig, _c = _b === void 0 ? {} : _b, _d = _c.trackAttr, trackAttr = _d === void 0 ? [] : _d, collectTags = _c.collectTags, pageLeaveAutoTrack = _c.pageLeaveAutoTrack, pageviewAutoTrack = _c.pageviewAutoTrack;
1334
+ serverUrl = serverUrl || '';
1335
+ serverUrl = serverUrl.trim();
1336
+ if (serverUrl === '') {
1337
+ this.log('当前 serverUrl 为空或不正确,network 中不会发数据,请配置正确的 serverUrl!', hinaCloudTypes.ConsoleTypes.WARN);
1338
+ }
1339
+ else {
1340
+ var href = window.location.href;
1341
+ var currentProtocol = hinaCloudUtils.getURL(href).protocol || '';
1342
+ var serverProtocol = hinaCloudUtils.getURL(serverUrl).protocol || '';
1343
+ if (serverProtocol !== currentProtocol) {
1344
+ this.log('SDK 检测到您的数据发送地址和当前页面地址的协议不一致,建议您修改成一致的协议。因为:https 下面发送 http 的图片请求会失败。', hinaCloudTypes.ConsoleTypes.WARN);
1345
+ }
1346
+ }
1347
+ if (![hinaCloudTypes.ReportType.IMAGE, hinaCloudTypes.ReportType.AJAX, hinaCloudTypes.ReportType.BEACON].includes(sendType)) {
1348
+ this.setConfig({
1349
+ sendType: hinaCloudTypes.ReportType.IMAGE
1350
+ });
1351
+ }
1352
+ // 处理pageLeaveAutoTrack
1353
+ if (pageLeaveAutoTrack === true) {
1354
+ this.options.autoTrackConfig.pageLeaveAutoTrack = {
1355
+ heartbeat_interval_time: 5000,
1356
+ max_duration: 432000
1357
+ };
1358
+ }
1359
+ // 处理trackAttr
1360
+ if (hinaCloudUtils.isArray(trackAttr)) {
1361
+ trackAttr = trackAttr.filter(function (v) { return hinaCloudUtils.isString(v); });
1362
+ if (!trackAttr.includes('hn-click'))
1363
+ trackAttr.push('hn-click');
1364
+ }
1365
+ else {
1366
+ trackAttr = ['hn-click'];
1367
+ }
1368
+ this.options.autoTrackConfig.trackAttr = trackAttr;
1369
+ // 处理collectTags
1370
+ if (hinaCloudUtils.isObject(collectTags)) {
1371
+ if (collectTags.div === true) {
1372
+ this.options.autoTrackConfig.collectTags.div = {
1373
+ ignoreTags: ignoreTags,
1374
+ maxLevel: 1
1375
+ };
1376
+ }
1377
+ else if (hinaCloudUtils.isObject(collectTags.div)) {
1378
+ var maxLevel = 1;
1379
+ var oDiv = collectTags.div;
1380
+ if (hinaCloudUtils.isNumber(oDiv.maxLevel) && [1, 2, 3].includes(oDiv.maxLevel)) {
1381
+ maxLevel = oDiv.maxLevel;
1382
+ }
1383
+ this.options.autoTrackConfig.collectTags.div = {
1384
+ ignoreTags: ignoreTags,
1385
+ maxLevel: maxLevel
1386
+ };
1387
+ }
1388
+ else {
1389
+ this.options.autoTrackConfig.collectTags.div = false;
1390
+ }
1391
+ }
1392
+ else {
1393
+ this.options.autoTrackConfig.collectTags = {
1394
+ div: false
1395
+ };
1396
+ }
1397
+ this.updateTrackTags();
1398
+ // 处理批量发送
1399
+ if (batchSend === true || hinaCloudUtils.isObject(batchSend)) {
1400
+ this.options.batchSend = __assign({ dataSendTimeout: 6000, sendInterval: 6000, storageLimit: 200 }, batchSend);
1401
+ this.batchSender = new BatchSend(this);
1402
+ }
1403
+ // 处理pageviewAutoTrack
1404
+ if (pageviewAutoTrack === 'auto') {
1405
+ this.autoTrack();
1406
+ }
1407
+ };
1408
+ /**
1409
+ * 初始化广告参数
1410
+ */
1411
+ HinaTrack.prototype.initAdvProps = function () {
1412
+ var advProps = {};
1413
+ var presetProperties = this.options.presetProperties || {};
1414
+ Object.keys(presetProperties).forEach(function (key) {
1415
+ var value = presetProperties[key];
1416
+ if (key.includes('latest_')) {
1417
+ key = key.slice(7);
1418
+ if (value) {
1419
+ var url_domain = hinaCloudUtils.getCurrentDomain();
1420
+ if (key !== 'utm' && url_domain === 'url解析失败') {
1421
+ advProps["H_latest_".concat(key)] = 'url的domain解析失败';
1422
+ }
1423
+ else if (hinaCloudUtils.isReferralTraffic()) {
1424
+ switch (key) {
1425
+ case 'traffic_source_type':
1426
+ advProps.H_latest_traffic_source_type =
1427
+ hinaCloudUtils.SearchKeyword.getSourceFromReferrer();
1428
+ break;
1429
+ case 'search_keyword':
1430
+ var searchKeyword = hinaCloudUtils.SearchKeyword.getKeywordFromReferrer();
1431
+ if (searchKeyword) {
1432
+ advProps.H_latest_search_keyword = searchKeyword;
1433
+ }
1434
+ break;
1435
+ case 'referrer': // todo 这块似乎没有什么用
1436
+ advProps.H_latest_referrer = '';
1437
+ break;
1438
+ }
1439
+ }
1440
+ }
1441
+ }
1442
+ });
1443
+ this.store.state.props = advProps;
1444
+ if (presetProperties.latest_utm) {
1445
+ this.getUmtsParams('H_latest_');
1446
+ }
1447
+ this.getUmtsParams('H_');
1448
+ this.store.setProps(this.store.state.props);
1449
+ };
1450
+ /**
1451
+ * 处理广告参数
1452
+ * @param prefix
1453
+ */
1454
+ HinaTrack.prototype.getUmtsParams = function (prefix) {
1455
+ if (prefix === void 0) { prefix = ''; }
1456
+ var allUtms = hinaCloudUtils.getUmtsParams(prefix);
1457
+ if (this.store.state.props && this.store.state.props.H_latest_utm_source) {
1458
+ this.store.state.props = __assign(__assign({}, this.store.state.props), allUtms);
1459
+ }
1460
+ return allUtms;
1461
+ };
1462
+ /**
1463
+ * 初始化共享数据
1464
+ */
1465
+ HinaTrack.prototype.initState = function () {
1466
+ this.store = new hinaCloudUtils.State(this.options);
1467
+ this.store.init();
1468
+ };
1469
+ /**
1470
+ * 更新采集的dom元素
1471
+ */
1472
+ HinaTrack.prototype.updateTrackTags = function () {
1473
+ var collectTags = this.options.autoTrackConfig.collectTags;
1474
+ var tags = __spreadArray([], __read(defaultTags), false);
1475
+ Object.keys(collectTags || {}).forEach(function (key) {
1476
+ var value = collectTags[key];
1477
+ if ((value === true || hinaCloudUtils.isObject(value)) && !tags.includes(key)) {
1478
+ tags.push(key);
1479
+ }
1480
+ });
1481
+ this.trackTags = tags;
1482
+ };
1483
+ /**
1484
+ * 应用插件
1485
+ */
1486
+ HinaTrack.prototype.initPlugins = function () {
1487
+ var _this = this;
1488
+ var _a = this.options.plugins, plugins = _a === void 0 ? [] : _a;
1489
+ plugins = plugins || [];
1490
+ var clickCrackPlugin = new ClickTrackPlugin(this.options, this);
1491
+ var stayTrackPlugin = new StayTrackPlugin(this.options, this);
1492
+ var pageLeavePlugin = new PageLeavePlugin(this.options, this);
1493
+ var siteLinkerPlugin = new SiteLinkerPlugin(this.options, this);
1494
+ var historyPlugin = new HistoryPlugin(this.options, this);
1495
+ var hashPlugin = new HashPlugin(this.options, this);
1496
+ this.plugins = [
1497
+ clickCrackPlugin,
1498
+ stayTrackPlugin,
1499
+ pageLeavePlugin,
1500
+ siteLinkerPlugin,
1501
+ historyPlugin,
1502
+ hashPlugin
1503
+ ];
1504
+ plugins.forEach(function (Plugin) {
1505
+ var instance = new Plugin(_this.options, _this);
1506
+ _this.plugins.push(instance);
1507
+ });
1508
+ this.runPlugins(this.plugins);
1509
+ };
1510
+ /**
1511
+ * @deprecated
1512
+ * 启动内置插件,v4版本后不建议使用该方法启动插件
1513
+ * 建议通过配置项的方式启动内置插件
1514
+ */
1515
+ HinaTrack.prototype.use = function (pluginName, options) {
1516
+ var _this = this;
1517
+ var _a = this.options, autoTrackConfig = _a.autoTrackConfig, siteLinkerConfig = _a.siteLinkerConfig;
1518
+ var pageLeaveAutoTrack = autoTrackConfig.pageLeaveAutoTrack;
1519
+ var startPlugin = function (pluginName) {
1520
+ var pluginInstance = _this.plugins.find(function (plugin) { return plugin.name === pluginName; });
1521
+ if (pluginInstance)
1522
+ pluginInstance.init();
1523
+ };
1524
+ if (!hinaCloudUtils.isObject(options)) {
1525
+ this.log("".concat(pluginName, "\u63D2\u4EF6\u914D\u7F6E\u9879\u5FC5\u987B\u662F\u4E00\u4E2A\u5BF9\u8C61\u7C7B\u578B"), hinaCloudTypes.ConsoleTypes.WARN);
1526
+ return;
1527
+ }
1528
+ if (pluginName === 'PageLeave') {
1529
+ if (hinaCloudUtils.isObject(pageLeaveAutoTrack)) {
1530
+ this.log('PageLeave插件已通过pageLeaveAutoTrack的配置参数启动,不可重复启动,如果想通过use方式启动,请删除配置项中的pageLeaveAutoTrack', hinaCloudTypes.ConsoleTypes.WARN);
1531
+ }
1532
+ else {
1533
+ this.options.autoTrackConfig.pageLeaveAutoTrack =
1534
+ options;
1535
+ startPlugin(PageLeavePluginName);
1536
+ }
1537
+ }
1538
+ else if (pluginName === 'SiteLinker') {
1539
+ if (hinaCloudUtils.isObject(siteLinkerConfig)) {
1540
+ this.log('SiteLinker插件已通过siteLinkerConfig的配置参数启动,不可重复启动,如果想通过use方式启动,请删除配置项中的siteLinkerConfig', hinaCloudTypes.ConsoleTypes.WARN);
1541
+ }
1542
+ else {
1543
+ this.options.siteLinkerConfig = options;
1544
+ startPlugin(SiteLinkerPluginName);
1545
+ }
1546
+ }
1547
+ };
1548
+ /**
1549
+ * 设置配置选项
1550
+ * @param options 配置对象
1551
+ */
1552
+ HinaTrack.prototype.setConfig = function (options) {
1553
+ this.options = hinaCloudUtils.merge(this.options, options);
1554
+ this.normalizeConfig();
1555
+ };
1556
+ /**
1557
+ * 获取配置选项 参数为空时 返回整个配置对象
1558
+ * @param key
1559
+ */
1560
+ HinaTrack.prototype.getConfig = function (key) {
1561
+ if (!key) {
1562
+ return this.options;
1563
+ }
1564
+ return this.options[key];
1565
+ };
1566
+ /**
1567
+ * 上报数据
1568
+ * @param data
1569
+ * @param callback
1570
+ * @param type
1571
+ */
1572
+ HinaTrack.prototype.report = function (data, callback, type) {
1573
+ console.log('report', data);
1574
+ var _a = this.options, batchSend = _a.batchSend, globalCallback = _a.globalCallback, serverUrl = _a.serverUrl, dataSendTimeout = _a.dataSendTimeout, sendType = _a.sendType, imgUseCrossOrigin = _a.imgUseCrossOrigin;
1575
+ sendType = type || sendType;
1576
+ // 批量发送
1577
+ if (batchSend) {
1578
+ this.batchSender.add(data);
1579
+ }
1580
+ else {
1581
+ var dataStr_1 = data;
1582
+ if (!hinaCloudUtils.isString(data)) {
1583
+ dataStr_1 = JSON.stringify(data);
1584
+ }
1585
+ var base64Data = hinaCloudUtils.base64Encode(dataStr_1);
1586
+ var params = {
1587
+ data: "data=".concat(base64Data),
1588
+ url: serverUrl,
1589
+ timeout: dataSendTimeout,
1590
+ imgUseCrossOrigin: imgUseCrossOrigin
1591
+ };
1592
+ var request = void 0;
1593
+ if (sendType === hinaCloudTypes.ReportType.BEACON && navigator.sendBeacon) {
1594
+ request = new hinaCloudUtils.BeaconRequest(params);
1595
+ }
1596
+ else if (sendType === hinaCloudTypes.ReportType.IMAGE && params.data.length < 2048) {
1597
+ request = new hinaCloudUtils.ImageRequest(params);
1598
+ }
1599
+ else {
1600
+ request = new hinaCloudUtils.AjaxRequest(params);
1601
+ }
1602
+ return request.run().then(function (res) {
1603
+ if (hinaCloudUtils.isFunction(globalCallback)) {
1604
+ globalCallback(serverUrl, dataStr_1, res.type, res.msg);
1605
+ }
1606
+ if (hinaCloudUtils.isFunction(callback)) {
1607
+ callback(serverUrl, dataStr_1, res.type, res.msg);
1608
+ }
1609
+ return res;
1610
+ });
1611
+ }
1612
+ };
1613
+ /**
1614
+ * 设置用户登录的唯一标识
1615
+ * @param uid
1616
+ * @param callback
1617
+ */
1618
+ HinaTrack.prototype.setUserUId = function (uid, callback) {
1619
+ uid = uid !== null && uid !== void 0 ? uid : '';
1620
+ if (hinaCloudUtils.isNumber(uid) || hinaCloudUtils.isString(uid)) {
1621
+ uid = String(uid).trim();
1622
+ if (!uid) {
1623
+ this.log('setUserUId: uid is empty', hinaCloudTypes.ConsoleTypes.WARN);
1624
+ }
1625
+ var accountId = this.store.getAccountId();
1626
+ if (accountId !== uid) {
1627
+ this.store.setAccountId(uid);
1628
+ var props = this.getReportData('track_signup', 'H_SignUp', {});
1629
+ this.report(props, callback);
1630
+ }
1631
+ else {
1632
+ this.log('setUserUId: uid is equal to account_id, , failed to execute setUserUId', hinaCloudTypes.ConsoleTypes.WARN);
1633
+ }
1634
+ }
1635
+ else {
1636
+ this.log('setUserUId: uid must be string or number', hinaCloudTypes.ConsoleTypes.WARN);
1637
+ }
1638
+ };
1639
+ /**
1640
+ * 设置设备ID
1641
+ * @param uid
1642
+ */
1643
+ HinaTrack.prototype.setDeviceUId = function (uid) {
1644
+ this.store.setDeviceId(uid);
1645
+ };
1646
+ /**
1647
+ * 获取设备ID
1648
+ */
1649
+ HinaTrack.prototype.getDeviceUId = function () {
1650
+ return this.store.getDeviceId();
1651
+ };
1652
+ /**
1653
+ * 自定义埋点事件
1654
+ * @param event
1655
+ * @param properties
1656
+ * @param callback
1657
+ */
1658
+ HinaTrack.prototype.track = function (event, properties, callback) {
1659
+ callback = callback || (function () { });
1660
+ if (hinaCloudUtils.isString(event)) {
1661
+ properties = hinaCloudUtils.isObject(properties) ? properties : {};
1662
+ var props = this.getReportData('track', event, properties);
1663
+ this.report(props, callback);
1664
+ }
1665
+ else {
1666
+ this.log('eventName must be a sting and properties must be an object', hinaCloudTypes.ConsoleTypes.WARN);
1667
+ }
1668
+ };
1669
+ /**
1670
+ * @param name
1671
+ * @param data
1672
+ * @param callback
1673
+ */
1674
+ HinaTrack.prototype.quick = function (name, data, callback) {
1675
+ var params = {};
1676
+ callback = callback || (function () { });
1677
+ if (hinaCloudUtils.isObject(data)) {
1678
+ params = data;
1679
+ }
1680
+ else if (hinaCloudUtils.isFunction(data)) {
1681
+ callback = data;
1682
+ }
1683
+ this.autoTrack(params, callback);
1684
+ };
1685
+ /**
1686
+ * 开启页面浏览采集
1687
+ * @param data
1688
+ * @param callback
1689
+ */
1690
+ HinaTrack.prototype.autoTrack = function (data, callback) {
1691
+ if (data === void 0) { data = {}; }
1692
+ if (callback === void 0) { callback = hinaCloudUtils.noop; }
1693
+ var props = this.getReportData('track', 'H_pageview', data);
1694
+ this.report(props, callback);
1695
+ if (this.store.isSetFirstVisit) {
1696
+ this.store.isSetFirstVisit = false;
1697
+ var referrer = hinaCloudUtils.getReferrer();
1698
+ this.userSetOnce({
1699
+ H_first_visit_time: hinaCloudUtils.nowStamp(),
1700
+ H_first_referrer: referrer,
1701
+ H_first_host: referrer ? hinaCloudUtils.getHostname(referrer, '取值异常') : '',
1702
+ H_first_browser_language: hinaCloudUtils.isString(navigator.language)
1703
+ ? navigator.language.toLowerCase()
1704
+ : '取值异常',
1705
+ H_first_traffic_source_type: hinaCloudUtils.SearchKeyword.getSourceFromReferrer(),
1706
+ H_first_search_keyword: hinaCloudUtils.SearchKeyword.getKeywordFromReferrer()
1707
+ });
1708
+ }
1709
+ };
1710
+ /**
1711
+ * 添加用户属性
1712
+ * 直接设置用户的属性,如果存在则覆盖。
1713
+ * @param data
1714
+ * @param callback
1715
+ */
1716
+ HinaTrack.prototype.userSet = function (data, callback) {
1717
+ if (hinaCloudUtils.isObject(data) && !hinaCloudUtils.isEmptyObject(data)) {
1718
+ var props = this.getReportData('user_set', '', data);
1719
+ this.report(props, callback);
1720
+ }
1721
+ };
1722
+ /**
1723
+ * 添加用户属性
1724
+ * 如果不存在则设置,存在就不设置
1725
+ * @param data
1726
+ * @param callback
1727
+ */
1728
+ HinaTrack.prototype.userSetOnce = function (data, callback) {
1729
+ if (hinaCloudUtils.isObject(data) && !hinaCloudUtils.isEmptyObject(data)) {
1730
+ var props = this.getReportData('user_setOnce', '', data);
1731
+ this.report(props, callback);
1732
+ }
1733
+ };
1734
+ /**
1735
+ * 对当前用户的属性做递增或者递减
1736
+ * @param data
1737
+ * @param callback
1738
+ */
1739
+ HinaTrack.prototype.userAdd = function (data, callback) {
1740
+ var _a;
1741
+ var _this = this;
1742
+ if (hinaCloudUtils.isString(data)) {
1743
+ data = (_a = {},
1744
+ _a[data] = 1,
1745
+ _a);
1746
+ }
1747
+ var isValid = function (params) {
1748
+ for (var key in params) {
1749
+ if (!/-*\d+/.test(String(params[key]))) {
1750
+ _this.log('userAdd: value is must be number', hinaCloudTypes.ConsoleTypes.WARN);
1751
+ return false;
1752
+ }
1753
+ }
1754
+ return true;
1755
+ };
1756
+ if (hinaCloudUtils.isObject(data) && !hinaCloudUtils.isEmptyObject(data) && isValid(data)) {
1757
+ var props = this.getReportData('user_add', '', data);
1758
+ this.report(props, callback);
1759
+ }
1760
+ };
1761
+ /**
1762
+ * 删除当前用户的一些属性
1763
+ * @param data
1764
+ * @param callback
1765
+ */
1766
+ HinaTrack.prototype.userUnset = function (data, callback) {
1767
+ var _this = this;
1768
+ var obj = {};
1769
+ if (hinaCloudUtils.isString(data)) {
1770
+ data = [data];
1771
+ }
1772
+ if (hinaCloudUtils.isArray(data)) {
1773
+ data.forEach(function (value) {
1774
+ if (hinaCloudUtils.isString(value)) {
1775
+ obj[value] = true;
1776
+ }
1777
+ else {
1778
+ _this.log("userUnset: value inside the array must be string and have already been filtered out:".concat(value), hinaCloudTypes.ConsoleTypes.WARN);
1779
+ }
1780
+ });
1781
+ if (!hinaCloudUtils.isEmptyObject(obj)) {
1782
+ var props = this.getReportData('user_unset', '', obj);
1783
+ this.report(props, callback);
1784
+ }
1785
+ }
1786
+ else {
1787
+ this.log('userUnset: param must be an array or string', hinaCloudTypes.ConsoleTypes.WARN);
1788
+ }
1789
+ };
1790
+ /**
1791
+ * 删除当前用户及他的所有属性。
1792
+ * @param callback
1793
+ */
1794
+ HinaTrack.prototype.userDelete = function (callback) {
1795
+ var props = this.getReportData('user_delete', '', {});
1796
+ this.report(props, callback);
1797
+ this.store.setAccountId('');
1798
+ };
1799
+ /**
1800
+ * 添加事件属性
1801
+ * 当使用函数类型作为属性值、函数返回值只能是string、bool、number、date、array类型
1802
+ * @param params
1803
+ */
1804
+ HinaTrack.prototype.registerCommonProperties = function (params) {
1805
+ this.presetProps = hinaCloudUtils.merge(this.presetProps, params);
1806
+ };
1807
+ /**
1808
+ * 获取预置属性
1809
+ * 此方法可获取,页面地址,页面标题,前向地址,SDK 类型及版本,屏幕宽高,最近一次的相关属性
1810
+ */
1811
+ HinaTrack.prototype.getPresetProperties = function () {
1812
+ return {
1813
+ H_is_first_day: this.store.isFirstDay,
1814
+ H_is_first_time: this.store.isFirstTime,
1815
+ device_id: this.store.getDeviceId(),
1816
+ anonymous_id: this.store.getAnonymousId(),
1817
+ account_id: this.store.getAccountId(),
1818
+ properties: __assign(__assign(__assign({}, this.presetProps), hinaCloudUtils.getPageProperties()), hinaCloudUtils.getBrowserInfo())
1819
+ };
1820
+ };
1821
+ /**
1822
+ * 清空预置属性
1823
+ * @param payload
1824
+ */
1825
+ HinaTrack.prototype.clearPageRegister = function (payload) {
1826
+ var _this = this;
1827
+ if (payload === void 0) { payload = true; }
1828
+ if (payload === true) {
1829
+ this.presetProps = {};
1830
+ }
1831
+ else if (hinaCloudUtils.isArray(payload)) {
1832
+ payload.forEach(function (key) {
1833
+ if (key in _this.presetProps)
1834
+ delete _this.presetProps[key];
1835
+ });
1836
+ }
1837
+ };
1838
+ /**
1839
+ * 检查发送数据
1840
+ * @param props
1841
+ */
1842
+ HinaTrack.prototype.checkReportProperties = function (props) {
1843
+ var _this = this;
1844
+ Object.keys(props).forEach(function (key) {
1845
+ var value = props[key];
1846
+ if (hinaCloudUtils.isString(value) && value.length > hinaCloudUtils.MAX_STRING_LENGTH) {
1847
+ _this.log("\u5C5E\u6027--".concat(key, " \u5185\u5BB9\u8FC7\u957F\uFF0C\u5DF2\u88AB\u5220\u9664"), hinaCloudTypes.ConsoleTypes.WARN);
1848
+ delete props[key];
1849
+ }
1850
+ else if (hinaCloudUtils.isObject(value)) {
1851
+ _this.checkReportProperties(value);
1852
+ }
1853
+ else if (hinaCloudUtils.isFunction(value)) {
1854
+ props[key] = value(props);
1855
+ if (hinaCloudUtils.isObject(props[key])) {
1856
+ _this.checkReportProperties(props[key]);
1857
+ }
1858
+ else if (hinaCloudUtils.isString(props[key]) &&
1859
+ props[key].length > hinaCloudUtils.MAX_STRING_LENGTH) {
1860
+ _this.log("\u5C5E\u6027--".concat(key, " \u5185\u5BB9\u8FC7\u957F\uFF0C\u5DF2\u88AB\u5220\u9664"), hinaCloudTypes.ConsoleTypes.WARN);
1861
+ delete props[key];
1862
+ }
1863
+ }
1864
+ });
1865
+ };
1866
+ /**
1867
+ * 获取上报数据
1868
+ * @param type
1869
+ * @param event
1870
+ * @param data
1871
+ */
1872
+ HinaTrack.prototype.getReportData = function (type, event, data) {
1873
+ var anonymous_id = this.store.getAnonymousId();
1874
+ var accountId = this.store.getAccountId();
1875
+ var time = hinaCloudUtils.nowStamp();
1876
+ var reportProperties = this.getReportProperties(type, event);
1877
+ var properties = __assign(__assign({}, reportProperties), (data || {}));
1878
+ this.checkReportProperties(properties);
1879
+ var props = {
1880
+ anonymous_id: anonymous_id,
1881
+ type: type,
1882
+ event: event,
1883
+ time: time,
1884
+ _track_id: Number(String(hinaCloudUtils.getRandom()).slice(2, 5) +
1885
+ String(hinaCloudUtils.getRandom()).slice(2, 4) +
1886
+ String(hinaCloudUtils.nowStamp()).slice(-4)),
1887
+ properties: properties
1888
+ };
1889
+ if (accountId) {
1890
+ props.account_id = accountId;
1891
+ }
1892
+ props.send_time = hinaCloudUtils.nowStamp();
1893
+ return props;
1894
+ };
1895
+ /**
1896
+ * 获取通用的上报数据
1897
+ * @param type 上报类型
1898
+ * @param event 事件名称
1899
+ */
1900
+ HinaTrack.prototype.getReportProperties = function (type, event) {
1901
+ if (type === void 0) { type = ''; }
1902
+ if (event === void 0) { event = ''; }
1903
+ // 这里对预置属性进行merge是为了防止影响this.presetProps的自身结构,深拷贝的操作
1904
+ var presetProps = hinaCloudUtils.merge(this.presetProps);
1905
+ var properties = __assign(__assign({ device_id: this.store.getDeviceId() }, this.store.state.props), presetProps);
1906
+ // user_set、user_setOnce、user_add、user_unset、user_delete
1907
+ if (!type || type.slice(0, 4) !== 'user') {
1908
+ properties = __assign(__assign(__assign({}, properties), hinaCloudUtils.getPageProperties()), hinaCloudUtils.getBrowserInfo());
1909
+ }
1910
+ if (type === 'track') {
1911
+ properties.H_is_first_day = this.store.isFirstDay;
1912
+ this.store.isFirstDay = false;
1913
+ if (event === 'H_pageview') {
1914
+ properties.H_is_first_time = this.store.isFirstTime;
1915
+ this.store.isFirstTime = false;
1916
+ }
1917
+ }
1918
+ return properties;
1919
+ };
1920
+ return HinaTrack;
1921
+ }(hinaCloudCore.BaseCore));
1922
+
1923
+ function createInstance(options) {
1924
+ return new HinaTrack(options, false);
1925
+ }
1926
+ var hinaSdk = createInstance({});
1927
+
1928
+ exports.HinaTrack = HinaTrack;
1929
+ exports.default = hinaSdk;
1930
+ //# sourceMappingURL=index.cjs.js.map