lee_web_track_sdk 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1142 @@
1
+ "use strict";
2
+ function _array_like_to_array(arr, len) {
3
+ if (len == null || len > arr.length) len = arr.length;
4
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
+ return arr2;
6
+ }
7
+ function _array_without_holes(arr) {
8
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
9
+ }
10
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
11
+ try {
12
+ var info = gen[key](arg);
13
+ var value = info.value;
14
+ } catch (error) {
15
+ reject(error);
16
+ return;
17
+ }
18
+ if (info.done) {
19
+ resolve(value);
20
+ } else {
21
+ Promise.resolve(value).then(_next, _throw);
22
+ }
23
+ }
24
+ function _async_to_generator(fn) {
25
+ return function() {
26
+ var self = this, args = arguments;
27
+ return new Promise(function(resolve, reject) {
28
+ var gen = fn.apply(self, args);
29
+ function _next(value) {
30
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
31
+ }
32
+ function _throw(err) {
33
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
34
+ }
35
+ _next(undefined);
36
+ });
37
+ };
38
+ }
39
+ function _class_call_check(instance, Constructor) {
40
+ if (!(instance instanceof Constructor)) {
41
+ throw new TypeError("Cannot call a class as a function");
42
+ }
43
+ }
44
+ function _defineProperties(target, props) {
45
+ for(var i = 0; i < props.length; i++){
46
+ var descriptor = props[i];
47
+ descriptor.enumerable = descriptor.enumerable || false;
48
+ descriptor.configurable = true;
49
+ if ("value" in descriptor) descriptor.writable = true;
50
+ Object.defineProperty(target, descriptor.key, descriptor);
51
+ }
52
+ }
53
+ function _create_class(Constructor, protoProps, staticProps) {
54
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
55
+ if (staticProps) _defineProperties(Constructor, staticProps);
56
+ return Constructor;
57
+ }
58
+ function _iterable_to_array(iter) {
59
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
60
+ }
61
+ function _non_iterable_spread() {
62
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
63
+ }
64
+ function _to_consumable_array(arr) {
65
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
66
+ }
67
+ function _type_of(obj) {
68
+ "@swc/helpers - typeof";
69
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
70
+ }
71
+ function _unsupported_iterable_to_array(o, minLen) {
72
+ if (!o) return;
73
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
74
+ var n = Object.prototype.toString.call(o).slice(8, -1);
75
+ if (n === "Object" && o.constructor) n = o.constructor.name;
76
+ if (n === "Map" || n === "Set") return Array.from(n);
77
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
78
+ }
79
+ function _ts_generator(thisArg, body) {
80
+ var f, y, t, _ = {
81
+ label: 0,
82
+ sent: function() {
83
+ if (t[0] & 1) throw t[1];
84
+ return t[1];
85
+ },
86
+ trys: [],
87
+ ops: []
88
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
89
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
90
+ return this;
91
+ }), g;
92
+ function verb(n) {
93
+ return function(v) {
94
+ return step([
95
+ n,
96
+ v
97
+ ]);
98
+ };
99
+ }
100
+ function step(op) {
101
+ if (f) throw new TypeError("Generator is already executing.");
102
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
103
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
104
+ if (y = 0, t) op = [
105
+ op[0] & 2,
106
+ t.value
107
+ ];
108
+ switch(op[0]){
109
+ case 0:
110
+ case 1:
111
+ t = op;
112
+ break;
113
+ case 4:
114
+ _.label++;
115
+ return {
116
+ value: op[1],
117
+ done: false
118
+ };
119
+ case 5:
120
+ _.label++;
121
+ y = op[1];
122
+ op = [
123
+ 0
124
+ ];
125
+ continue;
126
+ case 7:
127
+ op = _.ops.pop();
128
+ _.trys.pop();
129
+ continue;
130
+ default:
131
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
132
+ _ = 0;
133
+ continue;
134
+ }
135
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
136
+ _.label = op[1];
137
+ break;
138
+ }
139
+ if (op[0] === 6 && _.label < t[1]) {
140
+ _.label = t[1];
141
+ t = op;
142
+ break;
143
+ }
144
+ if (t && _.label < t[2]) {
145
+ _.label = t[2];
146
+ _.ops.push(op);
147
+ break;
148
+ }
149
+ if (t[2]) _.ops.pop();
150
+ _.trys.pop();
151
+ continue;
152
+ }
153
+ op = body.call(thisArg, _);
154
+ } catch (e) {
155
+ op = [
156
+ 6,
157
+ e
158
+ ];
159
+ y = 0;
160
+ } finally{
161
+ f = t = 0;
162
+ }
163
+ if (op[0] & 5) throw op[1];
164
+ return {
165
+ value: op[0] ? op[1] : void 0,
166
+ done: true
167
+ };
168
+ }
169
+ }
170
+ var __create = Object.create;
171
+ var __defProp = Object.defineProperty;
172
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
173
+ var __getOwnPropNames = Object.getOwnPropertyNames;
174
+ var __getProtoOf = Object.getPrototypeOf;
175
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
176
+ var __export = function(target, all) {
177
+ for(var name in all)__defProp(target, name, {
178
+ get: all[name],
179
+ enumerable: true
180
+ });
181
+ };
182
+ var __copyProps = function(to, from, except, desc) {
183
+ if (from && (typeof from === "undefined" ? "undefined" : _type_of(from)) === "object" || typeof from === "function") {
184
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
185
+ try {
186
+ var _loop = function() {
187
+ var key = _step.value;
188
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
189
+ get: function() {
190
+ return from[key];
191
+ },
192
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
193
+ });
194
+ };
195
+ for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
196
+ } catch (err) {
197
+ _didIteratorError = true;
198
+ _iteratorError = err;
199
+ } finally{
200
+ try {
201
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
202
+ _iterator.return();
203
+ }
204
+ } finally{
205
+ if (_didIteratorError) {
206
+ throw _iteratorError;
207
+ }
208
+ }
209
+ }
210
+ }
211
+ return to;
212
+ };
213
+ var __toESM = function(mod, isNodeMode, target) {
214
+ return target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM
215
+ // file that has been converted to a CommonJS file using a Babel-
216
+ // compatible transform (i.e. "__esModule" has not been set), then set
217
+ // "default" to the CommonJS "module.exports" for node compatibility.
218
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
219
+ value: mod,
220
+ enumerable: true
221
+ }) : target, mod);
222
+ };
223
+ var __toCommonJS = function(mod) {
224
+ return __copyProps(__defProp({}, "__esModule", {
225
+ value: true
226
+ }), mod);
227
+ };
228
+ // src/index.ts
229
+ var index_exports = {};
230
+ __export(index_exports, {
231
+ default: function() {
232
+ return index_default;
233
+ }
234
+ });
235
+ module.exports = __toCommonJS(index_exports);
236
+ var localForage3 = __toESM(require("localforage"), 1);
237
+ // src/core/track/cache.ts
238
+ var localForage2 = __toESM(require("localforage"), 1);
239
+ // src/config/constant.ts
240
+ var EVENT_TYPES = [
241
+ "page_view",
242
+ "user_view",
243
+ "page_destroy",
244
+ "click_event",
245
+ "module_click",
246
+ "module_view",
247
+ "login_event",
248
+ "order_event",
249
+ "custom_event",
250
+ "log_event"
251
+ ];
252
+ var CAN_AGGREGATION_TYPES = [
253
+ "page_view",
254
+ "user_view",
255
+ "module_view"
256
+ ];
257
+ var EVENT_KEYS = [
258
+ "project_name",
259
+ "event_type",
260
+ "event_name",
261
+ "event_time",
262
+ "user_timezone",
263
+ "user_id",
264
+ "device_type",
265
+ "app_version",
266
+ "user_agent",
267
+ "screen_resolution",
268
+ "custom_data"
269
+ ];
270
+ var CACHE_DATA_NAME = "fr-track-cache-data";
271
+ var CACHE_ERR_DATA_NAME = "fr-track-cache-err-data";
272
+ // src/utils/utils.ts
273
+ var getVariableType = function(variable) {
274
+ var typeString = Object.prototype.toString.call(variable);
275
+ return typeString.slice(8, -1).toLowerCase();
276
+ };
277
+ var generateFallbackUUID = function() {
278
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
279
+ var r = Math.random() * 16 | 0;
280
+ var v = c === "x" ? r : r & 3 | 8;
281
+ return v.toString(16);
282
+ });
283
+ };
284
+ var generateUserId = function() {
285
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
286
+ return crypto.randomUUID();
287
+ }
288
+ return generateFallbackUUID();
289
+ };
290
+ var overrideHistoryMethods = function(type) {
291
+ var originalMethod = history[type];
292
+ return function overrideHistoryMethods() {
293
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
294
+ args[_key] = arguments[_key];
295
+ }
296
+ var res = originalMethod.apply(this, args);
297
+ var e = new Event(type);
298
+ window.dispatchEvent(e);
299
+ return res;
300
+ };
301
+ };
302
+ var getUserTimeZone = function() {
303
+ try {
304
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
305
+ } catch (error) {
306
+ console.warn("\u65E0\u6CD5\u83B7\u53D6\u65F6\u533A\u540D\u79F0\uFF0C\u4F7F\u7528\u504F\u79FB\u91CF\u63A8\u7B97:", error);
307
+ var offset = /* @__PURE__ */ new Date().getTimezoneOffset();
308
+ if (offset >= 0) {
309
+ return "西".concat(offset / 60, "区");
310
+ } else {
311
+ return "东".concat(-offset / 60, "区");
312
+ }
313
+ }
314
+ };
315
+ // src/utils/validator.ts
316
+ function validateEventType(eventType) {
317
+ return typeof eventType === "string" && EVENT_TYPES.includes(eventType);
318
+ }
319
+ function validateEventKey(params) {
320
+ var type = getVariableType(params);
321
+ if (!params || type !== "object") {
322
+ console.warn("[Fr-track warning]: Event params must be an object");
323
+ return false;
324
+ }
325
+ if (typeof params[Symbol.iterator] !== "function") {
326
+ console.warn("[Fr-track warning]: Event params must be an iterable object");
327
+ return false;
328
+ }
329
+ var keys = Object.keys(params);
330
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
331
+ try {
332
+ for(var _iterator = keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
333
+ var key = _step.value;
334
+ if (!EVENT_KEYS.includes(key)) {
335
+ console.warn("[Fr-track warning]: Invalid event key: ".concat(key));
336
+ return false;
337
+ }
338
+ }
339
+ } catch (err) {
340
+ _didIteratorError = true;
341
+ _iteratorError = err;
342
+ } finally{
343
+ try {
344
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
345
+ _iterator.return();
346
+ }
347
+ } finally{
348
+ if (_didIteratorError) {
349
+ throw _iteratorError;
350
+ }
351
+ }
352
+ }
353
+ return true;
354
+ }
355
+ // src/core/report/clean.ts
356
+ var cleanData = function(rawData) {
357
+ try {
358
+ var tempIds = /* @__PURE__ */ new Set();
359
+ var resultData = rawData.filter(function(rawItem) {
360
+ var eventKeyResult = validateEventKey(rawItem);
361
+ if (!eventKeyResult) {
362
+ return false;
363
+ }
364
+ var eventTypeResult = validateEventType(rawItem.event_type);
365
+ if (!eventTypeResult) {
366
+ console.warn("[Fr-track warning]: error event type");
367
+ return false;
368
+ }
369
+ var eventTime = rawItem.event_time;
370
+ var minDateTime = /* @__PURE__ */ new Date("2025-12-01").getTime();
371
+ if (!eventTime || typeof eventTime !== "number" || eventTime < minDateTime) {
372
+ return false;
373
+ }
374
+ var id = "".concat(rawItem.event_type, "-").concat(rawItem.event_name, "-").concat(rawItem.event_time);
375
+ if (tempIds.has(id)) {
376
+ return false;
377
+ } else {
378
+ tempIds.add(id);
379
+ }
380
+ return true;
381
+ });
382
+ return {
383
+ type: "success",
384
+ data: resultData
385
+ };
386
+ } catch (error) {
387
+ console.warn("[Fr-track warning]: cleanData error", error);
388
+ var errReason = error.message || "Unknown error";
389
+ return {
390
+ type: "fail",
391
+ errReason: errReason,
392
+ data: rawData
393
+ };
394
+ }
395
+ };
396
+ // src/core/report/aggregation.ts
397
+ var aggregationData = function(rawData) {
398
+ try {
399
+ var _loop = function(i) {
400
+ var item = rawData[i];
401
+ if (CAN_AGGREGATION_TYPES.includes(item.event_type) || item.is_aggregation) {
402
+ var currentDate = new Date(item.event_time).setHours(0, 0, 0, 0);
403
+ var resultItem = resultData.find(function(r) {
404
+ return r.event_time === currentDate && r.event_type === item.event_type && r.event_name === item.event_name;
405
+ });
406
+ if (!resultItem) {
407
+ item.event_time = currentDate;
408
+ resultData.push(item);
409
+ } else {
410
+ var customData = resultItem.custom_data;
411
+ if (customData && customData.count) {
412
+ customData.count += 1;
413
+ resultItem.custom_data = customData;
414
+ }
415
+ }
416
+ } else {
417
+ resultData.push(item);
418
+ }
419
+ };
420
+ var resultData = [];
421
+ for(var i = 0; i < rawData.length; i++)_loop(i);
422
+ return resultData;
423
+ } catch (error) {
424
+ console.warn("[Fr-track warn]: \u805A\u5408\u5931\u8D25", error);
425
+ return rawData;
426
+ }
427
+ };
428
+ // src/core/report/index.ts
429
+ var localForage = __toESM(require("localforage"), 1);
430
+ var request = function(url, data) {
431
+ return _async_to_generator(function() {
432
+ return _ts_generator(this, function(_state) {
433
+ return [
434
+ 2,
435
+ new Promise(function(resolve, reject) {
436
+ if ("sendBeacon" in navigator) {
437
+ var dataJson = JSON.stringify(data);
438
+ var blob = new Blob([
439
+ dataJson
440
+ ], {
441
+ type: "application/json"
442
+ });
443
+ var status = navigator.sendBeacon(url, blob);
444
+ if (status) {
445
+ resolve(true);
446
+ } else {
447
+ reject();
448
+ }
449
+ } else {
450
+ var xhr = new XMLHttpRequest();
451
+ xhr.open("POST", url, true);
452
+ xhr.setRequestHeader("Content-Type", "application/json");
453
+ xhr.onload = function() {
454
+ if (xhr.status === 200) {
455
+ resolve(xhr.response);
456
+ } else {
457
+ reject();
458
+ }
459
+ };
460
+ xhr.onerror = function() {
461
+ reject();
462
+ };
463
+ xhr.send(JSON.stringify(data));
464
+ }
465
+ })
466
+ ];
467
+ });
468
+ })();
469
+ };
470
+ var onReportFail = function(url, data, clearCacheKey, retryCount) {
471
+ return _async_to_generator(function() {
472
+ var reportErrorData, _reportErrorData;
473
+ return _ts_generator(this, function(_state) {
474
+ switch(_state.label){
475
+ case 0:
476
+ if (!(retryCount < 3)) return [
477
+ 3,
478
+ 2
479
+ ];
480
+ return [
481
+ 4,
482
+ reportDataRequest(url, data, clearCacheKey, retryCount)
483
+ ];
484
+ case 1:
485
+ _state.sent();
486
+ return [
487
+ 3,
488
+ 5
489
+ ];
490
+ case 2:
491
+ return [
492
+ 4,
493
+ localForage.getItem(CACHE_ERR_DATA_NAME)
494
+ ];
495
+ case 3:
496
+ reportErrorData = _state.sent();
497
+ if (reportErrorData) {
498
+ ;
499
+ (_reportErrorData = reportErrorData).push.apply(_reportErrorData, _to_consumable_array(data));
500
+ } else {
501
+ reportErrorData = data;
502
+ }
503
+ return [
504
+ 4,
505
+ localForage.setItem(CACHE_ERR_DATA_NAME, reportErrorData)
506
+ ];
507
+ case 4:
508
+ _state.sent();
509
+ _state.label = 5;
510
+ case 5:
511
+ return [
512
+ 2
513
+ ];
514
+ }
515
+ });
516
+ })();
517
+ };
518
+ var reportDataRequest = function(url, data) {
519
+ var clearCacheKey = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "", retryCount = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 1;
520
+ return _async_to_generator(function() {
521
+ var reportData, error;
522
+ return _ts_generator(this, function(_state) {
523
+ switch(_state.label){
524
+ case 0:
525
+ reportData = Array.isArray(data) ? data : [
526
+ data
527
+ ];
528
+ _state.label = 1;
529
+ case 1:
530
+ _state.trys.push([
531
+ 1,
532
+ 5,
533
+ ,
534
+ 6
535
+ ]);
536
+ return [
537
+ 4,
538
+ request(url, reportData)
539
+ ];
540
+ case 2:
541
+ _state.sent();
542
+ if (!clearCacheKey) return [
543
+ 3,
544
+ 4
545
+ ];
546
+ return [
547
+ 4,
548
+ localForage.removeItem(clearCacheKey)
549
+ ];
550
+ case 3:
551
+ _state.sent();
552
+ _state.label = 4;
553
+ case 4:
554
+ return [
555
+ 3,
556
+ 6
557
+ ];
558
+ case 5:
559
+ error = _state.sent();
560
+ onReportFail(url, reportData, clearCacheKey, retryCount + 1);
561
+ return [
562
+ 3,
563
+ 6
564
+ ];
565
+ case 6:
566
+ return [
567
+ 2
568
+ ];
569
+ }
570
+ });
571
+ })();
572
+ };
573
+ var reportCacheData = function(url) {
574
+ return _async_to_generator(function() {
575
+ var cacheData, cleanInfo, result, error;
576
+ return _ts_generator(this, function(_state) {
577
+ switch(_state.label){
578
+ case 0:
579
+ _state.trys.push([
580
+ 0,
581
+ 4,
582
+ ,
583
+ 5
584
+ ]);
585
+ return [
586
+ 4,
587
+ getCacheData()
588
+ ];
589
+ case 1:
590
+ cacheData = _state.sent();
591
+ if (!(cacheData === null || cacheData === void 0 ? void 0 : cacheData.length)) return [
592
+ 2
593
+ ];
594
+ cleanInfo = cleanData(cacheData);
595
+ if (!(cleanInfo.type !== "success")) return [
596
+ 3,
597
+ 3
598
+ ];
599
+ console.warn("[Fr-track warn]:", cleanInfo.errReason);
600
+ return [
601
+ 4,
602
+ localForage.removeItem(CACHE_DATA_NAME)
603
+ ];
604
+ case 2:
605
+ _state.sent();
606
+ return [
607
+ 2
608
+ ];
609
+ case 3:
610
+ result = aggregationData(cleanInfo.data);
611
+ if (result && result.length) {
612
+ reportDataRequest(url, result, CACHE_DATA_NAME);
613
+ }
614
+ return [
615
+ 3,
616
+ 5
617
+ ];
618
+ case 4:
619
+ error = _state.sent();
620
+ console.error("[Fr-track error]:", error);
621
+ return [
622
+ 3,
623
+ 5
624
+ ];
625
+ case 5:
626
+ return [
627
+ 2
628
+ ];
629
+ }
630
+ });
631
+ })();
632
+ };
633
+ // src/core/track/cache.ts
634
+ var setCacheData = function(data, url, maxLen) {
635
+ var retryCount = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 1;
636
+ return _async_to_generator(function() {
637
+ var cacheData, error, errMsg;
638
+ return _ts_generator(this, function(_state) {
639
+ switch(_state.label){
640
+ case 0:
641
+ _state.trys.push([
642
+ 0,
643
+ 3,
644
+ ,
645
+ 4
646
+ ]);
647
+ return [
648
+ 4,
649
+ localForage2.getItem(CACHE_DATA_NAME)
650
+ ];
651
+ case 1:
652
+ cacheData = _state.sent();
653
+ if (cacheData) {
654
+ cacheData.push(data);
655
+ cacheData.length >= maxLen && reportCacheData(url);
656
+ } else {
657
+ cacheData = [
658
+ data
659
+ ];
660
+ }
661
+ return [
662
+ 4,
663
+ localForage2.setItem(CACHE_DATA_NAME, cacheData)
664
+ ];
665
+ case 2:
666
+ _state.sent();
667
+ return [
668
+ 3,
669
+ 4
670
+ ];
671
+ case 3:
672
+ error = _state.sent();
673
+ errMsg = retryCount > 3 ? error : "Retrying...";
674
+ if (retryCount <= 3) {
675
+ console.warn("[Fr-track warning]:" + errMsg);
676
+ setCacheData(data, url, retryCount + 1);
677
+ } else {
678
+ console.error("[Fr-track error]:" + errMsg);
679
+ reportDataRequest(url, data);
680
+ }
681
+ return [
682
+ 3,
683
+ 4
684
+ ];
685
+ case 4:
686
+ return [
687
+ 2
688
+ ];
689
+ }
690
+ });
691
+ })();
692
+ };
693
+ var getCacheData = function() {
694
+ return _async_to_generator(function() {
695
+ var cacheData, error;
696
+ return _ts_generator(this, function(_state) {
697
+ switch(_state.label){
698
+ case 0:
699
+ _state.trys.push([
700
+ 0,
701
+ 2,
702
+ ,
703
+ 3
704
+ ]);
705
+ return [
706
+ 4,
707
+ localForage2.getItem(CACHE_DATA_NAME)
708
+ ];
709
+ case 1:
710
+ cacheData = _state.sent();
711
+ return [
712
+ 2,
713
+ cacheData || []
714
+ ];
715
+ case 2:
716
+ error = _state.sent();
717
+ console.error("[Fr-track error]:" + error);
718
+ return [
719
+ 2,
720
+ []
721
+ ];
722
+ case 3:
723
+ return [
724
+ 2
725
+ ];
726
+ }
727
+ });
728
+ })();
729
+ };
730
+ // src/utils/uuid.ts
731
+ var getUserId = function() {
732
+ var track_uuid = localStorage.getItem("track_uuid");
733
+ if (track_uuid) {
734
+ return track_uuid;
735
+ }
736
+ var uuid = generateUserId();
737
+ localStorage.setItem("track_uuid", uuid);
738
+ return uuid;
739
+ };
740
+ // src/utils/browser.ts
741
+ var Browser = __toESM(require("bowser"), 1);
742
+ var getBrowserAndDeviceInfo = function() {
743
+ var defRes = {
744
+ browserName: "unknown",
745
+ browserVersion: "unknown",
746
+ osName: "unknown",
747
+ osVersion: "unknown",
748
+ platformName: "unknown"
749
+ };
750
+ try {
751
+ var ua = window.navigator.userAgent;
752
+ if (!ua) return defRes;
753
+ var info = Browser.parse(ua);
754
+ var browser = info.browser, os = info.os, platform = info.platform;
755
+ return {
756
+ browserName: browser.name || "unknown",
757
+ browserVersion: browser.version || "unknown",
758
+ osName: os.name || "unknown",
759
+ osVersion: os.version || "unknown",
760
+ platformName: platform.type || "unknown"
761
+ };
762
+ } catch (error) {
763
+ return defRes;
764
+ }
765
+ };
766
+ var getDeviceResolution = function() {
767
+ if (!window) return "unknown";
768
+ var screen = window.screen;
769
+ return "".concat(screen.width, "x").concat(screen.height);
770
+ };
771
+ // src/index.ts
772
+ var FrTrack = /*#__PURE__*/ function() {
773
+ function FrTrack(options) {
774
+ _class_call_check(this, FrTrack);
775
+ this.option = {
776
+ project_name: "",
777
+ report_url: "",
778
+ app_version: "",
779
+ auto_pv: false,
780
+ maxCacheSize: 15,
781
+ maxCacheTime: 3e5
782
+ };
783
+ this.userId = getUserId();
784
+ this.routeMode = "history";
785
+ this.timer = null;
786
+ this.uvTimer = null;
787
+ this.browserInfo = null;
788
+ var project_name = options.project_name, report_url = options.report_url, _options_app_version = options.app_version, app_version = _options_app_version === void 0 ? "unknown" : _options_app_version, _options_auto_pv = options.auto_pv, auto_pv = _options_auto_pv === void 0 ? false : _options_auto_pv, _options_maxCacheTime = options.maxCacheTime, maxCacheTime = _options_maxCacheTime === void 0 ? 3e5 : _options_maxCacheTime, _options_maxCacheSize = options.maxCacheSize, maxCacheSize = _options_maxCacheSize === void 0 ? 15 : _options_maxCacheSize;
789
+ Object.assign(this.option, {
790
+ project_name: project_name,
791
+ report_url: report_url,
792
+ auto_pv: auto_pv,
793
+ maxCacheTime: maxCacheTime,
794
+ maxCacheSize: maxCacheSize,
795
+ app_version: app_version
796
+ });
797
+ this.init();
798
+ }
799
+ _create_class(FrTrack, [
800
+ {
801
+ key: "reportPrevData",
802
+ value: function reportPrevData() {
803
+ return _async_to_generator(function() {
804
+ var res, res1, err;
805
+ return _ts_generator(this, function(_state) {
806
+ switch(_state.label){
807
+ case 0:
808
+ _state.trys.push([
809
+ 0,
810
+ 3,
811
+ ,
812
+ 4
813
+ ]);
814
+ return [
815
+ 4,
816
+ localForage3.getItem(CACHE_DATA_NAME)
817
+ ];
818
+ case 1:
819
+ res = _state.sent();
820
+ return [
821
+ 4,
822
+ localForage3.getItem(CACHE_ERR_DATA_NAME)
823
+ ];
824
+ case 2:
825
+ res1 = _state.sent();
826
+ if (res && res.length) {
827
+ reportCacheData(this.option.report_url);
828
+ }
829
+ if (res1 && res1.length) {
830
+ reportDataRequest(this.option.report_url, res1, CACHE_ERR_DATA_NAME);
831
+ }
832
+ return [
833
+ 3,
834
+ 4
835
+ ];
836
+ case 3:
837
+ err = _state.sent();
838
+ console.warn("[Fr-track warn]: \u68C0\u9A8C\u5386\u53F2\u6570\u636E\u5931\u8D25");
839
+ return [
840
+ 3,
841
+ 4
842
+ ];
843
+ case 4:
844
+ return [
845
+ 2
846
+ ];
847
+ }
848
+ });
849
+ }).call(this);
850
+ }
851
+ },
852
+ {
853
+ key: "loopReport",
854
+ value: function loopReport() {
855
+ var _this = this;
856
+ this.timer = setInterval(function() {
857
+ reportCacheData(_this.option.report_url);
858
+ }, this.option.maxCacheTime);
859
+ }
860
+ },
861
+ {
862
+ key: "onBrowserClose",
863
+ value: function onBrowserClose() {
864
+ var _this = this;
865
+ window.addEventListener("beforeunload", function() {
866
+ if (_this.timer) {
867
+ clearInterval(_this.timer);
868
+ _this.timer = null;
869
+ }
870
+ if (_this.uvTimer) {
871
+ clearInterval(_this.uvTimer);
872
+ _this.uvTimer = null;
873
+ }
874
+ reportCacheData(_this.option.report_url);
875
+ });
876
+ window.addEventListener("visibilitychange", function() {
877
+ if (document.visibilityState !== "visible") {
878
+ _this.loopReport();
879
+ } else {
880
+ if (_this.timer) {
881
+ clearInterval(_this.timer);
882
+ _this.timer = null;
883
+ }
884
+ reportCacheData(_this.option.report_url);
885
+ }
886
+ });
887
+ }
888
+ },
889
+ {
890
+ key: "init",
891
+ value: function init() {
892
+ this.browserInfo = getBrowserAndDeviceInfo();
893
+ this.reportPrevData();
894
+ this.loopReport();
895
+ this.onBrowserClose();
896
+ this.frUserView();
897
+ if (this.option.auto_pv) {
898
+ if (this.routeMode === "history") {
899
+ window.history.pushState = overrideHistoryMethods("pushState");
900
+ window.history.replaceState = overrideHistoryMethods("replaceState");
901
+ }
902
+ this.frAutoPageView();
903
+ }
904
+ }
905
+ },
906
+ {
907
+ key: "track",
908
+ value: function track(params) {
909
+ var _this_option = this.option, project_name = _this_option.project_name, app_version = _this_option.app_version, maxCacheSize = _this_option.maxCacheSize, report_url = _this_option.report_url;
910
+ var _this_browserInfo = this.browserInfo, osName = _this_browserInfo.osName, osVersion = _this_browserInfo.osVersion, browserName = _this_browserInfo.browserName, browserVersion = _this_browserInfo.browserVersion, platformName = _this_browserInfo.platformName;
911
+ var trackParams = Object.assign({
912
+ project_name: project_name,
913
+ app_version: app_version,
914
+ user_id: this.userId,
915
+ device_type: platformName,
916
+ user_agent: "os: ".concat(osName, "--v").concat(osVersion, ", browser: ").concat(browserName, "--v").concat(browserVersion),
917
+ screen_resolution: getDeviceResolution(),
918
+ user_timezone: getUserTimeZone(),
919
+ event_time: Date.now(),
920
+ custom_data: null
921
+ }, params);
922
+ setCacheData(trackParams, report_url, maxCacheSize);
923
+ }
924
+ },
925
+ {
926
+ key: "singleTrack",
927
+ value: function singleTrack(eventType, params) {
928
+ var baseParams = {
929
+ event_type: eventType
930
+ };
931
+ var trackParams = Object.assign(baseParams, params);
932
+ this.track(trackParams);
933
+ }
934
+ },
935
+ {
936
+ /**
937
+ * @method 自定义用户id
938
+ */ key: "setUser",
939
+ value: function setUser(id) {
940
+ this.userId = id;
941
+ }
942
+ },
943
+ {
944
+ /**
945
+ * @method 自定义路由方式
946
+ */ key: "setRouteMode",
947
+ value: function setRouteMode(mode) {
948
+ this.routeMode = mode;
949
+ }
950
+ },
951
+ {
952
+ /**
953
+ * @method 模块view
954
+ */ key: "frModuleView",
955
+ value: function frModuleView(event_name, custom_data) {
956
+ var params = {
957
+ event_name: event_name,
958
+ custom_data: custom_data
959
+ };
960
+ this.singleTrack("module_view", params);
961
+ }
962
+ },
963
+ {
964
+ /**
965
+ * @method 模块click
966
+ */ key: "frModuleClick",
967
+ value: function frModuleClick(event_name, custom_data) {
968
+ var is_aggregation = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
969
+ var params = {
970
+ event_name: event_name,
971
+ custom_data: custom_data,
972
+ is_aggregation: is_aggregation
973
+ };
974
+ this.singleTrack("module_click", params);
975
+ }
976
+ },
977
+ {
978
+ /**
979
+ * @method 登录事件
980
+ */ key: "frLoginEvent",
981
+ value: function frLoginEvent(event_name, custom_data) {
982
+ var is_aggregation = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
983
+ var params = {
984
+ event_name: event_name,
985
+ custom_data: custom_data,
986
+ is_aggregation: is_aggregation
987
+ };
988
+ this.singleTrack("login_event", params);
989
+ }
990
+ },
991
+ {
992
+ /**
993
+ * @method 生单事件
994
+ */ key: "frOrderEvent",
995
+ value: function frOrderEvent(event_name, custom_data) {
996
+ var is_aggregation = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
997
+ var params = {
998
+ event_name: event_name,
999
+ custom_data: custom_data,
1000
+ is_aggregation: is_aggregation
1001
+ };
1002
+ this.singleTrack("order_event", params);
1003
+ }
1004
+ },
1005
+ {
1006
+ /**
1007
+ * @method 自定义事件
1008
+ */ key: "frCustomEvent",
1009
+ value: function frCustomEvent(event_name, custom_data) {
1010
+ var is_aggregation = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
1011
+ var params = {
1012
+ event_name: event_name,
1013
+ custom_data: custom_data,
1014
+ is_aggregation: is_aggregation
1015
+ };
1016
+ this.singleTrack("custom_event", params);
1017
+ }
1018
+ },
1019
+ {
1020
+ /**
1021
+ * @method 日志事件
1022
+ */ key: "frLogEvent",
1023
+ value: function frLogEvent(event_name, custom_data) {
1024
+ var is_aggregation = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
1025
+ var params = {
1026
+ event_name: event_name,
1027
+ custom_data: custom_data,
1028
+ is_aggregation: is_aggregation
1029
+ };
1030
+ this.singleTrack("log_event", params);
1031
+ }
1032
+ },
1033
+ {
1034
+ /**
1035
+ * @method 点击事件
1036
+ */ key: "frClickEvent",
1037
+ value: function frClickEvent(event_name, custom_data) {
1038
+ var is_aggregation = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
1039
+ var params = {
1040
+ event_name: event_name,
1041
+ custom_data: custom_data,
1042
+ is_aggregation: is_aggregation
1043
+ };
1044
+ this.singleTrack("click_event", params);
1045
+ }
1046
+ },
1047
+ {
1048
+ /**
1049
+ * @method 自动收集pv事件
1050
+ */ key: "frAutoPageView",
1051
+ value: function frAutoPageView() {
1052
+ var _this = this;
1053
+ var methodsList = [];
1054
+ if (this.routeMode === "hash") {
1055
+ methodsList.push("hashchange");
1056
+ } else {
1057
+ var _methodsList;
1058
+ (_methodsList = methodsList).push.apply(_methodsList, [
1059
+ "popstate",
1060
+ "pushState",
1061
+ "replaceState"
1062
+ ]);
1063
+ }
1064
+ methodsList.forEach(function(method) {
1065
+ window.addEventListener(method, function() {
1066
+ var href = window.location.href || "";
1067
+ var params = {
1068
+ event_name: href,
1069
+ custom_data: {
1070
+ page_url: href,
1071
+ page_name: "unknown",
1072
+ count: 1
1073
+ }
1074
+ };
1075
+ _this.singleTrack("page_view", params);
1076
+ });
1077
+ });
1078
+ }
1079
+ },
1080
+ {
1081
+ /**
1082
+ * @method pv事件
1083
+ */ key: "frPageView",
1084
+ value: function frPageView(event_name, custom_data) {
1085
+ var params = {
1086
+ event_name: event_name,
1087
+ custom_data: custom_data
1088
+ };
1089
+ this.singleTrack("page_view", params);
1090
+ }
1091
+ },
1092
+ {
1093
+ /**
1094
+ * @method uv事件
1095
+ */ key: "frUserView",
1096
+ value: function frUserView() {
1097
+ var _this = this;
1098
+ var currentDate = /* @__PURE__ */ new Date().setHours(0, 0, 0, 0);
1099
+ var interval = 60 * 60 * 1e3;
1100
+ var params = {
1101
+ event_name: "user_view"
1102
+ };
1103
+ this.singleTrack("user_view", params);
1104
+ if (this.uvTimer) {
1105
+ clearInterval(this.uvTimer);
1106
+ this.uvTimer = null;
1107
+ }
1108
+ this.uvTimer = setInterval(function() {
1109
+ var now = /* @__PURE__ */ new Date().setHours(0, 0, 0, 0);
1110
+ if (now > currentDate + 24 * interval) {
1111
+ _this.singleTrack("user_view", params);
1112
+ }
1113
+ }, interval);
1114
+ }
1115
+ },
1116
+ {
1117
+ /**
1118
+ * @method 页面销毁事件
1119
+ */ key: "frPageDestroy",
1120
+ value: function frPageDestroy(event_name, custom_data) {
1121
+ var is_aggregation = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
1122
+ var params = {
1123
+ event_name: event_name,
1124
+ custom_data: custom_data,
1125
+ is_aggregation: is_aggregation
1126
+ };
1127
+ this.singleTrack("page_destroy", params);
1128
+ }
1129
+ },
1130
+ {
1131
+ /**
1132
+ * @method 手动立即上报缓存的数据
1133
+ */ key: "frReport",
1134
+ value: function frReport() {
1135
+ reportCacheData(this.option.report_url);
1136
+ }
1137
+ }
1138
+ ]);
1139
+ return FrTrack;
1140
+ }();
1141
+ var index_default = FrTrack;
1142
+ //# sourceMappingURL=index.js.map