@yysports/tools 1.1.0 → 2.0.0

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.
Files changed (56) hide show
  1. package/dist/Track/core/auth.d.ts +16 -0
  2. package/dist/Track/core/auth.js +83 -0
  3. package/dist/Track/core/constants.d.ts +14 -0
  4. package/dist/Track/core/constants.js +25 -0
  5. package/dist/Track/core/envelope.d.ts +9 -0
  6. package/dist/Track/core/envelope.js +54 -0
  7. package/dist/Track/core/instance.d.ts +108 -0
  8. package/dist/Track/core/instance.js +365 -0
  9. package/dist/Track/core/lifecycle.d.ts +18 -0
  10. package/dist/Track/core/lifecycle.js +59 -0
  11. package/dist/Track/core/profile.d.ts +5 -0
  12. package/dist/Track/core/profile.js +30 -0
  13. package/dist/Track/core/queue.d.ts +13 -0
  14. package/dist/Track/core/queue.js +36 -0
  15. package/dist/Track/core/replay.d.ts +17 -0
  16. package/dist/Track/core/replay.js +117 -0
  17. package/dist/Track/core/router.d.ts +6 -0
  18. package/dist/Track/core/router.js +15 -0
  19. package/dist/Track/core/system.d.ts +14 -0
  20. package/dist/Track/core/system.js +36 -0
  21. package/dist/Track/core/transport.d.ts +18 -0
  22. package/dist/Track/core/transport.js +151 -0
  23. package/dist/Track/index.d.ts +31 -28
  24. package/dist/Track/index.js +212 -392
  25. package/dist/Utils/common.js +5 -6
  26. package/dist/Utils/route.js +1 -6
  27. package/dist/Utils/url.js +1 -3
  28. package/dist/Utils/wx.js +2 -7
  29. package/dist/interfaces/track.interface.d.ts +14 -4
  30. package/lib/Track/core/auth.d.ts +16 -0
  31. package/lib/Track/core/auth.js +67 -0
  32. package/lib/Track/core/constants.d.ts +14 -0
  33. package/lib/Track/core/constants.js +56 -0
  34. package/lib/Track/core/envelope.d.ts +9 -0
  35. package/lib/Track/core/envelope.js +61 -0
  36. package/lib/Track/core/instance.d.ts +108 -0
  37. package/lib/Track/core/instance.js +257 -0
  38. package/lib/Track/core/lifecycle.d.ts +18 -0
  39. package/lib/Track/core/lifecycle.js +74 -0
  40. package/lib/Track/core/profile.d.ts +5 -0
  41. package/lib/Track/core/profile.js +47 -0
  42. package/lib/Track/core/queue.d.ts +13 -0
  43. package/lib/Track/core/queue.js +49 -0
  44. package/lib/Track/core/replay.d.ts +17 -0
  45. package/lib/Track/core/replay.js +131 -0
  46. package/lib/Track/core/router.d.ts +6 -0
  47. package/lib/Track/core/router.js +39 -0
  48. package/lib/Track/core/system.d.ts +14 -0
  49. package/lib/Track/core/system.js +53 -0
  50. package/lib/Track/core/transport.d.ts +18 -0
  51. package/lib/Track/core/transport.js +115 -0
  52. package/lib/Track/index.d.ts +31 -28
  53. package/lib/Track/index.js +126 -312
  54. package/lib/Utils/common.js +4 -6
  55. package/lib/interfaces/track.interface.d.ts +14 -4
  56. package/package.json +11 -10
@@ -1,433 +1,253 @@
1
- var _excluded = ["roles"],
2
- _excluded2 = ["userProfile", "menuNameMap", "routes", "getAuth", "menuBuild", "getDataScopeZonePermissions"];
3
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
4
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
5
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
6
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
7
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
8
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
9
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
10
- function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
11
- function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
12
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
13
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
14
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
15
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
16
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
17
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
18
- function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
19
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
20
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
21
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
22
- function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
23
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
24
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
25
- function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
26
- function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
27
- import pako from 'pako';
28
- import { version } from "../../package.json";
29
- import { generateRandomString, getAuthMapByAuthCenter, getRoutesMap } from "../Utils";
30
- var Track = /*#__PURE__*/function () {
31
- function Track() {
32
- _classCallCheck(this, Track);
33
- }
34
- _createClass(Track, null, [{
35
- key: "checkConfig",
36
- value:
37
- // 检查必填配置项
38
- function checkConfig(config) {
39
- if (!config) {
40
- throw new Error('请配置Track');
41
- }
42
- if (!config.domain) {
43
- throw new Error('请设置信息采集中心域名');
44
- }
45
- if (!config.appId) {
46
- throw new Error('请设置appId');
1
+ import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
2
+ import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
3
+ import _createClass from "@babel/runtime/helpers/esm/createClass";
4
+ import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
5
+ import _regeneratorRuntime from "@babel/runtime/helpers/esm/regeneratorRuntime";
6
+ import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
7
+ /**
8
+ * 新版多实例埋点入口
9
+ * 提供统一 createTracker(config, { lazy }) API
10
+ */
11
+
12
+ import { TrackerInstance } from "./core/instance";
13
+
14
+ // ---------------- 多实例工厂 ----------------
15
+
16
+ /**
17
+ * 创建埋点实例
18
+ * @param config TrackConfig
19
+ * @param options { lazy } 是否延迟 init(默认 false)
20
+ * - lazy=false: 返回 Promise<TrackerInstance>(已完成 init)
21
+ * - lazy=true: 返回未初始化实例 (TrackerInstance),需外部手动调用 init()
22
+ */
23
+ export function createTracker(config, options) {
24
+ var _ref = options || {},
25
+ lazy = _ref.lazy;
26
+ var ins = new TrackerInstance(config);
27
+ if (lazy) return ins;
28
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
29
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
30
+ while (1) switch (_context.prev = _context.next) {
31
+ case 0:
32
+ _context.next = 2;
33
+ return ins.init();
34
+ case 2:
35
+ return _context.abrupt("return", ins);
36
+ case 3:
37
+ case "end":
38
+ return _context.stop();
47
39
  }
48
- this.config = config;
49
- }
50
-
51
- // 发送埋点数据
52
- }, {
53
- key: "send",
54
- value: function () {
55
- var _send = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
56
- var debug, data, compressed;
57
- return _regeneratorRuntime().wrap(function _callee$(_context) {
58
- while (1) switch (_context.prev = _context.next) {
40
+ }, _callee);
41
+ }))();
42
+ }
43
+
44
+ // ---------------- 静态外观(兼容方便使用) ----------------
45
+ var TrackFacade = /*#__PURE__*/function () {
46
+ function TrackFacade() {
47
+ _classCallCheck(this, TrackFacade);
48
+ }
49
+ _createClass(TrackFacade, null, [{
50
+ key: "init",
51
+ value: ( /** 初始化(必须先调用一次)。重复调用直接返回已存在实例 */function () {
52
+ var _init = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(config) {
53
+ var _this = this;
54
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
55
+ while (1) switch (_context3.prev = _context3.next) {
59
56
  case 0:
60
- debug = this.config.debug;
61
- data = this.trackQueue.splice(0, this.trackQueue.length);
62
- compressed = pako.deflate(JSON.stringify(data));
63
- if (data.length) {
64
- debug && console.debug('[track:debug] push data', data);
65
- navigator.sendBeacon("".concat(this.config.domain, "/pousheng-guard/api/track"), compressed);
57
+ if (!this._instance) {
58
+ _context3.next = 2;
59
+ break;
66
60
  }
61
+ return _context3.abrupt("return", this._instance);
62
+ case 2:
63
+ if (!this._initPromise) {
64
+ this._initPromise = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
65
+ var ins;
66
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
67
+ while (1) switch (_context2.prev = _context2.next) {
68
+ case 0:
69
+ ins = new TrackerInstance(config);
70
+ _context2.next = 3;
71
+ return ins.init();
72
+ case 3:
73
+ _this._instance = ins;
74
+ // 回放预队列
75
+ _this._queue.forEach(function (_ref4) {
76
+ var _ref5;
77
+ var method = _ref4.method,
78
+ args = _ref4.args;
79
+ return (_ref5 = ins)[method].apply(_ref5, _toConsumableArray(args));
80
+ });
81
+ _this._queue.length = 0;
82
+ return _context2.abrupt("return", ins);
83
+ case 7:
84
+ case "end":
85
+ return _context2.stop();
86
+ }
87
+ }, _callee2);
88
+ }))();
89
+ }
90
+ return _context3.abrupt("return", this._initPromise);
67
91
  case 4:
68
92
  case "end":
69
- return _context.stop();
93
+ return _context3.stop();
70
94
  }
71
- }, _callee, this);
95
+ }, _callee3, this);
72
96
  }));
73
- function send() {
74
- return _send.apply(this, arguments);
97
+ function init(_x) {
98
+ return _init.apply(this, arguments);
75
99
  }
76
- return send;
77
- }() // 挂载自动化任务
100
+ return init;
101
+ }() /** 是否已就绪 */)
78
102
  }, {
79
- key: "mountAutoTask",
80
- value: function mountAutoTask() {
81
- var _this = this;
82
- var autoReportError = this.config.autoReportError;
83
- if (autoReportError) {
84
- addEventListener('error', function (event) {
85
- var message = event.message,
86
- filename = event.filename;
87
- var errorInfo = {
88
- message: message,
89
- fileName: filename
90
- };
91
- _this.errorLog(errorInfo);
92
- console.error('[track:error] catch error', event);
93
- });
94
- }
95
-
96
- //关闭页面时,发送剩余的埋点数据
97
- addEventListener('visibilitychange', function () {
98
- if (document.visibilityState === 'hidden') {
99
- _this.send();
100
- }
101
- });
103
+ key: "isReady",
104
+ value: function isReady() {
105
+ return !!this._instance;
102
106
  }
103
107
 
104
- // 获取系统信息
108
+ /** 获取内部实例(未初始化时抛错) */
105
109
  }, {
106
- key: "getSystemProfile",
107
- value: function getSystemProfile() {
108
- var IMEI = localStorage.getItem('__IMEI__');
109
- if (!IMEI) {
110
- localStorage.setItem('__IMEI__', generateRandomString(16));
111
- }
112
- return {
113
- innerHeight: innerHeight,
114
- innerWidth: innerWidth,
115
- href: location.href,
116
- systemTime: new Date(),
117
- IMEI: localStorage.getItem('__IMEI__')
118
- };
110
+ key: "getInstance",
111
+ value: function getInstance() {
112
+ if (!this._instance) throw new Error('Track 未初始化,请先调用 Track.init(config)');
113
+ return this._instance;
119
114
  }
120
115
 
121
- // 获取当前用户信息,返回格式化后的用户信息
116
+ /** 延迟调用帮助:未 init 时先入队 */
122
117
  }, {
123
- key: "getUserProfile",
124
- value: function getUserProfile() {
125
- var userProfile = this.userProfile;
126
- if (!(userProfile !== null && userProfile !== void 0 && userProfile.userId)) {
127
- userProfile.userId = '';
118
+ key: "invoke",
119
+ value: function invoke(method) {
120
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
121
+ args[_key - 1] = arguments[_key];
128
122
  }
129
- if (!(userProfile !== null && userProfile !== void 0 && userProfile.userName)) {
130
- userProfile.userName = '';
123
+ if (this._instance) {
124
+ var _ref6;
125
+ (_ref6 = this._instance)[method].apply(_ref6, args);
126
+ } else if (this._initPromise) {
127
+ // 初始化进行中,进入队列
128
+ this._queue.push({
129
+ method: method,
130
+ args: args
131
+ });
132
+ } else {
133
+ // 尚未开始 init,仍入队,提示一次
134
+ this._queue.push({
135
+ method: method,
136
+ args: args
137
+ });
138
+ if (!this._warned) {
139
+ console.warn('[track] 在 Track.init 前调用了日志方法,已暂存至初始化后回放');
140
+ this._warned = true;
141
+ }
131
142
  }
132
- return userProfile;
133
143
  }
134
144
 
135
- // 设置当前用户信息
145
+ /**
146
+ * 发送事件日志(通用事件)
147
+ * - 若未初始化:自动排队等待 init 完成后回放
148
+ */
136
149
  }, {
137
- key: "setUserProfile",
138
- value: function setUserProfile(userProfile) {
139
- this.userProfile = userProfile;
140
- }
141
-
142
- // 初始化权限中心数据
143
- }, {
144
- key: "initAuthCenterData",
145
- value: function () {
146
- var _initAuthCenterData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref) {
147
- var getAuth, menuBuild, getDataScopeZonePermissions, menuNameMap, routes, authCenterApi, _yield$Promise$all, _yield$Promise$all2, _yield$Promise$all2$, authInfo, _yield$Promise$all2$2, menuData, dataScopeZonePermissions, _ref2, _ref2$user, user, _ref2$roles, roles, dataScopeRoles, restUser, isAdmin, accessPage, routesMap, authCenterUserProfile;
148
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
149
- while (1) switch (_context2.prev = _context2.next) {
150
- case 0:
151
- getAuth = _ref.getAuth, menuBuild = _ref.menuBuild, getDataScopeZonePermissions = _ref.getDataScopeZonePermissions, menuNameMap = _ref.menuNameMap, routes = _ref.routes;
152
- authCenterApi = []; // 获取用户权限
153
- if (getAuth) {
154
- authCenterApi.push(getAuth);
155
- }
156
-
157
- // 获取权限中心配置的菜单及按钮
158
- if (menuBuild) {
159
- authCenterApi.push(menuBuild);
160
- }
161
-
162
- // 获取权限中心配置的区部数据权限
163
- if (getDataScopeZonePermissions) {
164
- authCenterApi.push(getDataScopeZonePermissions);
165
- }
166
- _context2.next = 7;
167
- return Promise.all(authCenterApi.map(function (v) {
168
- if (v) {
169
- return v();
170
- } else {
171
- return Promise.resolve();
172
- }
173
- }));
174
- case 7:
175
- _yield$Promise$all = _context2.sent;
176
- _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 3);
177
- _yield$Promise$all2$ = _yield$Promise$all2[0];
178
- authInfo = _yield$Promise$all2$ === void 0 ? {} : _yield$Promise$all2$;
179
- _yield$Promise$all2$2 = _yield$Promise$all2[1];
180
- menuData = _yield$Promise$all2$2 === void 0 ? [] : _yield$Promise$all2$2;
181
- dataScopeZonePermissions = _yield$Promise$all2[2];
182
- _ref2 = authInfo || {}, _ref2$user = _ref2.user, user = _ref2$user === void 0 ? {} : _ref2$user, _ref2$roles = _ref2.roles, roles = _ref2$roles === void 0 ? [] : _ref2$roles;
183
- dataScopeRoles = user.roles, restUser = _objectWithoutProperties(user, _excluded); // 权限中心的用户信息
184
- isAdmin = roles.includes('admin'); // 当前用户所拥有的所有页面权限
185
- accessPage = []; // 获取本地菜单信息映射
186
- if (routes) {
187
- routesMap = getRoutesMap(routes, menuNameMap);
188
- routesMap.forEach(function (value) {
189
- var access = value.access;
190
- if (access.length === 0) {
191
- return;
192
- }
193
- if (isAdmin) {
194
- accessPage.push.apply(accessPage, _toConsumableArray(access));
195
- return;
196
- }
197
- access.forEach(function (key) {
198
- if (roles.includes(key)) {
199
- accessPage.push(key);
200
- }
201
- });
202
- });
203
- this.routesMap = routesMap;
204
- }
205
- this.authMap = getAuthMapByAuthCenter(menuData);
206
- authCenterUserProfile = _objectSpread(_objectSpread({}, restUser), {}, {
207
- dataScopeRoles: dataScopeRoles,
208
- roles: roles,
209
- accessPage: accessPage
210
- });
211
- if (dataScopeZonePermissions) {
212
- Object.assign(authCenterUserProfile, {
213
- dataScopeZonePermissions: dataScopeZonePermissions
214
- });
215
- }
216
- this.authCenterUserProfile = authCenterUserProfile;
217
- return _context2.abrupt("return", authCenterUserProfile);
218
- case 24:
219
- case "end":
220
- return _context2.stop();
221
- }
222
- }, _callee2, this);
223
- }));
224
- function initAuthCenterData(_x) {
225
- return _initAuthCenterData.apply(this, arguments);
150
+ key: "eventLog",
151
+ value: function eventLog() {
152
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
153
+ args[_key2] = arguments[_key2];
226
154
  }
227
- return initAuthCenterData;
228
- }() // 挂载初始配置
155
+ this.invoke.apply(this, ['eventLog'].concat(args));
156
+ }
157
+ /**
158
+ * 发送访问/页面曝光日志
159
+ * - 用于记录页面 / 场景进入等行为
160
+ */
229
161
  }, {
230
- key: "init",
231
- value: function () {
232
- var _init = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref3) {
233
- var _this$authCenterUserP2;
234
- var userProfile, menuNameMap, routes, getAuth, menuBuild, getDataScopeZonePermissions, restConfig, currentUserProfile, _this$authCenterUserP;
235
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
236
- while (1) switch (_context3.prev = _context3.next) {
237
- case 0:
238
- userProfile = _ref3.userProfile, menuNameMap = _ref3.menuNameMap, routes = _ref3.routes, getAuth = _ref3.getAuth, menuBuild = _ref3.menuBuild, getDataScopeZonePermissions = _ref3.getDataScopeZonePermissions, restConfig = _objectWithoutProperties(_ref3, _excluded2);
239
- this.checkConfig(restConfig);
240
- this.config = restConfig;
241
- _context3.next = 5;
242
- return this.initAuthCenterData({
243
- getAuth: getAuth,
244
- menuBuild: menuBuild,
245
- getDataScopeZonePermissions: getDataScopeZonePermissions,
246
- menuNameMap: menuNameMap,
247
- routes: routes
248
- });
249
- case 5:
250
- currentUserProfile = {}; // 如果对接了权限中心,取权限中心的用户信息
251
- if (this.authCenterUserProfile.userName) {
252
- Object.assign(currentUserProfile, {
253
- userId: this.authCenterUserProfile.userName,
254
- userName: this.authCenterUserProfile.nickName,
255
- orgCode: this.authCenterUserProfile.orgCode,
256
- orgTitle: this.authCenterUserProfile.orgTitle,
257
- dataScopeRoles: (_this$authCenterUserP = this.authCenterUserProfile.dataScopeRoles) === null || _this$authCenterUserP === void 0 ? void 0 : _this$authCenterUserP.map(function (role) {
258
- return role.name;
259
- }).join(',')
260
- });
261
- }
262
-
263
- // 传入区部数据权限接口时,设置区部权限数据
264
- if (this.authCenterUserProfile.dataScopeZonePermissions && ((_this$authCenterUserP2 = this.authCenterUserProfile.dataScopeZonePermissions) === null || _this$authCenterUserP2 === void 0 || (_this$authCenterUserP2 = _this$authCenterUserP2.list) === null || _this$authCenterUserP2 === void 0 ? void 0 : _this$authCenterUserP2.length) > 0) {
265
- // 提取出所有 zoneId
266
- Object.assign(currentUserProfile, {
267
- dataScopeZonePermissions: this.authCenterUserProfile.dataScopeZonePermissions.list.map(function (item) {
268
- return item.list.map(function (zone) {
269
- return zone.zoneId;
270
- }).join(',');
271
- }).join(',')
272
- });
273
- }
274
- if (userProfile) {
275
- Object.assign(currentUserProfile, userProfile);
276
- }
277
- this.setUserProfile(currentUserProfile);
278
- this.mountAutoTask();
279
-
280
- // 注册应用版本
281
- this.registerAppInfo();
282
- return _context3.abrupt("return", this.authCenterUserProfile);
283
- case 13:
284
- case "end":
285
- return _context3.stop();
286
- }
287
- }, _callee3, this);
288
- }));
289
- function init(_x2) {
290
- return _init.apply(this, arguments);
162
+ key: "visitLog",
163
+ value: function visitLog() {
164
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
165
+ args[_key3] = arguments[_key3];
291
166
  }
292
- return init;
293
- }() // 注册更新应用信息
294
- }, {
295
- key: "registerAppInfo",
296
- value: function registerAppInfo() {
297
- var appId = this.config.appId;
298
- navigator.sendBeacon("".concat(this.config.domain, "/pousheng-guard/api/apps/version/update"), pako.deflate(JSON.stringify({
299
- appId: appId,
300
- version: version
301
- })));
167
+ this.invoke.apply(this, ['visitLog'].concat(args));
302
168
  }
303
-
304
- // 推送埋点信息进入队列
169
+ /**
170
+ * 发送错误日志
171
+ * - 适用于运行时异常、资源加载失败、接口异常包装等
172
+ */
305
173
  }, {
306
- key: "pushQueue",
307
- value: function pushQueue(_ref4) {
308
- var type = _ref4.type,
309
- log = _ref4.log;
310
- var config = this.config;
311
- this.checkConfig(config);
312
- var reqData = _objectSpread(_objectSpread(_objectSpread({}, this.getSystemProfile()), this.getUserProfile()), {}, {
313
- type: type,
314
- appId: config.appId,
315
- log: JSON.stringify(log)
316
- });
317
- this.trackQueue.push(reqData);
318
- if (this.trackQueue.length > 4) {
319
- this.send();
174
+ key: "errorLog",
175
+ value: function errorLog() {
176
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
177
+ args[_key4] = arguments[_key4];
320
178
  }
179
+ this.invoke.apply(this, ['errorLog'].concat(args));
321
180
  }
322
-
323
- // 获取格式化base后的路径
181
+ /**
182
+ * 发送接口调用相关日志
183
+ * - 记录接口耗时 / 结果状态
184
+ */
324
185
  }, {
325
- key: "getFormatBasePath",
326
- value: function getFormatBasePath() {
327
- var _this$config$base = this.config.base,
328
- base = _this$config$base === void 0 ? '/' : _this$config$base;
329
- var _location = location,
330
- pathname = _location.pathname;
331
- return pathname.replace(base, '/');
186
+ key: "apiLog",
187
+ value: function apiLog() {
188
+ for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
189
+ args[_key5] = arguments[_key5];
190
+ }
191
+ this.invoke.apply(this, ['apiLog'].concat(args));
332
192
  }
333
-
334
- // 获取模块名称
193
+ /**
194
+ * 强制立即 flush 已缓冲的日志(若实例策略存在缓冲)
195
+ */
335
196
  }, {
336
- key: "getPageModuleName",
337
- value: function getPageModuleName() {
338
- var routeInfo = this.routesMap.get(this.getFormatBasePath());
339
- return (routeInfo === null || routeInfo === void 0 ? void 0 : routeInfo.module) || [];
197
+ key: "flush",
198
+ value: function flush() {
199
+ if (!this._instance) return;
200
+ this._instance.flush();
340
201
  }
341
-
342
- // 推送错误日志
202
+ /**
203
+ * 销毁当前单例实例
204
+ * - 停止上报 / 释放资源
205
+ * - 再次使用需重新 init
206
+ */
343
207
  }, {
344
- key: "errorLog",
345
- value: function errorLog(_errorLog) {
346
- this.pushQueue({
347
- log: _errorLog,
348
- type: 'error'
349
- });
208
+ key: "destroy",
209
+ value: function destroy() {
210
+ if (!this._instance) return;
211
+ this._instance.destroy();
212
+ this._instance = null;
213
+ this._initPromise = null;
350
214
  }
351
-
352
- // 推送用户触发日志
215
+ /**
216
+ * 设置用户画像 / 用户基础属性
217
+ * - 若在 init 前调用:会延迟到实例 ready 后再真正执行
218
+ */
353
219
  }, {
354
- key: "eventLog",
355
- value: function eventLog(_eventLog) {
356
- var copyEventLog = {
357
- module: '',
358
- content: ''
359
- };
360
- if (typeof _eventLog === 'string') {
361
- var actionLog = this.authMap.get(_eventLog);
362
- if (actionLog) {
363
- copyEventLog.content = '触发: ' + actionLog;
364
- } else {
365
- copyEventLog.content = _eventLog;
220
+ key: "setUserProfile",
221
+ value: function setUserProfile(profile) {
222
+ if (!this._instance) {
223
+ // 允许提前设置,将其转换为 eventLog 之前的一个补丁:加入队列尾部一个函数式调用
224
+ this._queue.push({
225
+ method: 'eventLog',
226
+ args: []
227
+ }); // 占位避免丢失顺序
228
+ // 等 init 后再真正 set(用回放后 hook)
229
+ var prevInit = this._initPromise;
230
+ if (prevInit) {
231
+ prevInit.then(function (ins) {
232
+ return ins.setUserProfile(profile);
233
+ });
366
234
  }
367
- } else {
368
- Object.assign(copyEventLog, _eventLog);
369
- }
370
- if (!copyEventLog.module) {
371
- var routeNames = this.getPageModuleName();
372
- copyEventLog.module = (routeNames === null || routeNames === void 0 ? void 0 : routeNames.join('-')) || '-';
373
- }
374
- this.pushQueue({
375
- log: copyEventLog,
376
- type: 'event'
377
- });
378
- }
379
-
380
- // 推送页面访问日志
381
- }, {
382
- key: "visitLog",
383
- value: function visitLog(_visitLog) {
384
- // 检测当前路由是否为重定向路由,如果是则不记录
385
- var routeInfo = this.routesMap.get(this.getFormatBasePath());
386
- if (routeInfo !== null && routeInfo !== void 0 && routeInfo.isRedirect) {
387
235
  return;
388
236
  }
389
- if (_visitLog === undefined) {
390
- _visitLog = {
391
- module: '',
392
- content: ''
393
- };
394
- var routeNames = this.getPageModuleName();
395
- Object.assign(_visitLog, {
396
- module: routeNames.join('-'),
397
- content: "\u8BBF\u95EE\u9875\u9762: ".concat(_toConsumableArray(routeNames).pop())
398
- });
399
- }
400
- this.pushQueue({
401
- log: _visitLog,
402
- type: 'visit'
403
- });
237
+ this._instance.setUserProfile(profile);
404
238
  }
405
-
406
- // 推送接口访问日志
239
+ /** 获取当前配置(未初始化时返回 undefined) */
407
240
  }, {
408
- key: "apiLog",
409
- value: function apiLog(_apiLog) {
410
- // API 日志无需等待队列,直接发送
411
- var config = this.config;
412
- navigator.sendBeacon("".concat(this.config.domain, "/pousheng-guard/api/track"), pako.deflate(JSON.stringify([_objectSpread(_objectSpread({
413
- appId: config.appId,
414
- log: _apiLog,
415
- type: 'api'
416
- }, this.getSystemProfile()), this.getUserProfile())])));
241
+ key: "getConfig",
242
+ value: function getConfig() {
243
+ var _this$_instance;
244
+ return (_this$_instance = this._instance) === null || _this$_instance === void 0 ? void 0 : _this$_instance.getConfig();
417
245
  }
418
246
  }]);
419
- return Track;
420
- }();
421
- // 配置信息
422
- _defineProperty(Track, "config", {});
423
- // 需要传入到后端的用户信息
424
- _defineProperty(Track, "userProfile", {});
425
- // 权限中心用户信息
426
- _defineProperty(Track, "authCenterUserProfile", {});
427
- // 路径信息映射
428
- _defineProperty(Track, "routesMap", new Map());
429
- // 权限信息映射
430
- _defineProperty(Track, "authMap", new Map());
431
- // 埋点队列
432
- _defineProperty(Track, "trackQueue", []);
433
- export default Track;
247
+ return TrackFacade;
248
+ }(); // 默认导出静态外观,满足 import Track 后直接 Track.eventLog()
249
+ _defineProperty(TrackFacade, "_instance", null);
250
+ _defineProperty(TrackFacade, "_initPromise", null);
251
+ _defineProperty(TrackFacade, "_queue", []);
252
+ _defineProperty(TrackFacade, "_warned", false);
253
+ export default TrackFacade;