@pluve/logger-sdk 0.0.11 → 0.0.13

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 (47) hide show
  1. package/dist/esm/capture/jsError.js +3 -24
  2. package/dist/esm/capture/promiseError.js +3 -24
  3. package/dist/esm/capture/wechatError.js +9 -31
  4. package/dist/esm/compress/compression.js +47 -51
  5. package/dist/esm/core/httpClient.js +53 -76
  6. package/dist/esm/core/loggerSDK.js +202 -233
  7. package/dist/esm/core/queueManager.js +59 -99
  8. package/dist/esm/core/retryManager.js +44 -70
  9. package/dist/esm/stack/stacktrace.js +8 -31
  10. package/dist/esm/transport/beaconTransport.js +20 -61
  11. package/dist/esm/transport/pixelImageTransport.js +55 -79
  12. package/dist/esm/transport/transportAdapter.js +11 -13
  13. package/dist/esm/transport/wechatTransport.js +53 -94
  14. package/dist/esm/utils/tools.js +12 -35
  15. package/dist/types/compress/compression.d.ts +2 -0
  16. package/dist/types/transport/transportAdapter.d.ts +3 -5
  17. package/package.json +1 -2
  18. package/dist/cjs/capture/jsError.js +0 -48
  19. package/dist/cjs/capture/promiseError.js +0 -49
  20. package/dist/cjs/capture/resourceError.js +0 -48
  21. package/dist/cjs/capture/wechatError.js +0 -95
  22. package/dist/cjs/compress/compression.js +0 -84
  23. package/dist/cjs/config/index.js +0 -55
  24. package/dist/cjs/core/fingerprint.js +0 -36
  25. package/dist/cjs/core/httpClient.js +0 -96
  26. package/dist/cjs/core/loggerSDK.js +0 -641
  27. package/dist/cjs/core/queueManager.js +0 -249
  28. package/dist/cjs/core/retryManager.js +0 -127
  29. package/dist/cjs/index.js +0 -34
  30. package/dist/cjs/stack/stacktrace.js +0 -48
  31. package/dist/cjs/transport/beaconTransport.js +0 -64
  32. package/dist/cjs/transport/pixelImageTransport.js +0 -100
  33. package/dist/cjs/transport/transport.js +0 -17
  34. package/dist/cjs/transport/transportAdapter.js +0 -56
  35. package/dist/cjs/transport/wechatTransport.js +0 -103
  36. package/dist/cjs/types/api.js +0 -17
  37. package/dist/cjs/types/env.js +0 -17
  38. package/dist/cjs/types/external.d.ts +0 -21
  39. package/dist/cjs/types/logEvent.js +0 -17
  40. package/dist/cjs/types/logEventLevel.js +0 -17
  41. package/dist/cjs/types/sdkOptions.js +0 -17
  42. package/dist/cjs/types/trackOptions.js +0 -17
  43. package/dist/cjs/utils/environment.js +0 -183
  44. package/dist/cjs/utils/session.js +0 -31
  45. package/dist/cjs/utils/tools.js +0 -82
  46. package/dist/cjs/utils/uuid.js +0 -35
  47. package/dist/umd/logger-sdk.min.js +0 -1
@@ -1,53 +1,3 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
- }) : x)(function(x) {
10
- if (typeof require !== "undefined")
11
- return require.apply(this, arguments);
12
- throw new Error('Dynamic require of "' + x + '" is not supported');
13
- });
14
- var __copyProps = (to, from, except, desc) => {
15
- if (from && typeof from === "object" || typeof from === "function") {
16
- for (let key of __getOwnPropNames(from))
17
- if (!__hasOwnProp.call(to, key) && key !== except)
18
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
- // If the importer is in node compatibility mode or this is not an ESM
24
- // file that has been converted to a CommonJS file using a Babel-
25
- // compatible transform (i.e. "__esModule" has not been set), then set
26
- // "default" to the CommonJS "module.exports" for node compatibility.
27
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
- mod
29
- ));
30
- var __async = (__this, __arguments, generator) => {
31
- return new Promise((resolve, reject) => {
32
- var fulfilled = (value) => {
33
- try {
34
- step(generator.next(value));
35
- } catch (e) {
36
- reject(e);
37
- }
38
- };
39
- var rejected = (value) => {
40
- try {
41
- step(generator.throw(value));
42
- } catch (e) {
43
- reject(e);
44
- }
45
- };
46
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
47
- step((generator = generator.apply(__this, __arguments)).next());
48
- });
49
- };
50
-
51
1
  // src/core/queueManager.ts
52
2
  import { isBrowser, isWeChatMiniProgram } from "../utils/environment";
53
3
  import { logDebug, safeStringify } from "../utils/tools";
@@ -63,20 +13,32 @@ var QueueManager = class {
63
13
  }
64
14
  });
65
15
  }
66
- loadLocalForage() {
67
- return __async(this, null, function* () {
16
+ async loadLocalForage() {
17
+ if (!isBrowser())
18
+ return null;
19
+ try {
20
+ const g = globalThis;
21
+ if (g && g.localforage && typeof g.localforage.getItem === "function") {
22
+ this.localforage = g.localforage;
23
+ return this.localforage;
24
+ }
68
25
  try {
69
- if (isBrowser()) {
70
- Promise.resolve().then(() => __toESM(__require("localforage"))).then((res) => {
71
- this.localforage = res;
72
- logDebug(!!this.opts.debug, res);
73
- });
74
- }
26
+ const mod = await import(
27
+ /* @vite-ignore */
28
+ "localforage"
29
+ );
30
+ this.localforage = mod;
31
+ return this.localforage;
75
32
  } catch (e) {
76
- logDebug(!!this.opts.debug, "localforage load error", e);
33
+ logDebug(!!this.opts.debug, "localforage dynamic import failed, fallback to localStorage", e);
34
+ this.localforage = null;
35
+ return null;
77
36
  }
37
+ } catch (e) {
38
+ logDebug(!!this.opts.debug, "localforage load error", e);
39
+ this.localforage = null;
78
40
  return null;
79
- });
41
+ }
80
42
  }
81
43
  /**
82
44
  * 添加日志到队列
@@ -129,52 +91,50 @@ var QueueManager = class {
129
91
  /**
130
92
  * 从持久化存储加载队列
131
93
  */
132
- loadFromStorage() {
133
- return __async(this, null, function* () {
134
- try {
135
- let stored = null;
136
- if (isWeChatMiniProgram()) {
137
- stored = wx.getStorageSync(this.storageKey);
138
- } else if (isBrowser()) {
139
- if (!this.localforage) {
140
- yield this.loadLocalForage();
141
- }
142
- try {
143
- const items = this.localforage ? yield this.localforage.getItem(this.storageKey) : null;
144
- if (Array.isArray(items)) {
145
- this.queue = items.slice(0, this.opts.maxSize);
146
- logDebug(!!this.opts.debug, `Loaded ${this.queue.length} events from IndexedDB`);
147
- return;
148
- }
149
- } catch (err) {
150
- logDebug(!!this.opts.debug, "IndexedDB load error, falling back to localStorage", err);
94
+ async loadFromStorage() {
95
+ try {
96
+ let stored = null;
97
+ if (isWeChatMiniProgram()) {
98
+ stored = wx.getStorageSync(this.storageKey);
99
+ } else if (isBrowser()) {
100
+ if (!this.localforage) {
101
+ await this.loadLocalForage();
102
+ }
103
+ try {
104
+ const items = this.localforage ? await this.localforage.getItem(this.storageKey) : null;
105
+ if (Array.isArray(items)) {
106
+ this.queue = items.slice(0, this.opts.maxSize);
107
+ logDebug(!!this.opts.debug, `Loaded ${this.queue.length} events from IndexedDB`);
108
+ return;
151
109
  }
152
- if (typeof localStorage !== "undefined") {
153
- const ls = localStorage.getItem(this.storageKey);
154
- if (ls) {
155
- try {
156
- const parsed = JSON.parse(ls);
157
- if (Array.isArray(parsed)) {
158
- this.queue = parsed.slice(0, this.opts.maxSize);
159
- logDebug(!!this.opts.debug, `Loaded ${this.queue.length} events from localStorage`);
160
- }
161
- } catch (e) {
110
+ } catch (err) {
111
+ logDebug(!!this.opts.debug, "IndexedDB load error, falling back to localStorage", err);
112
+ }
113
+ if (typeof localStorage !== "undefined") {
114
+ const ls = localStorage.getItem(this.storageKey);
115
+ if (ls) {
116
+ try {
117
+ const parsed = JSON.parse(ls);
118
+ if (Array.isArray(parsed)) {
119
+ this.queue = parsed.slice(0, this.opts.maxSize);
120
+ logDebug(!!this.opts.debug, `Loaded ${this.queue.length} events from localStorage`);
162
121
  }
122
+ } catch {
163
123
  }
164
124
  }
165
- return;
166
125
  }
167
- if (stored) {
168
- const parsed = JSON.parse(stored);
169
- if (Array.isArray(parsed)) {
170
- this.queue = parsed.slice(0, this.opts.maxSize);
171
- logDebug(!!this.opts.debug, `Loaded ${this.queue.length} events from storage`);
172
- }
126
+ return;
127
+ }
128
+ if (stored) {
129
+ const parsed = JSON.parse(stored);
130
+ if (Array.isArray(parsed)) {
131
+ this.queue = parsed.slice(0, this.opts.maxSize);
132
+ logDebug(!!this.opts.debug, `Loaded ${this.queue.length} events from storage`);
173
133
  }
174
- } catch (error) {
175
- logDebug(!!this.opts.debug, "Failed to load queue from storage", error);
176
134
  }
177
- });
135
+ } catch (error) {
136
+ logDebug(!!this.opts.debug, "Failed to load queue from storage", error);
137
+ }
178
138
  }
179
139
  /**
180
140
  * 保存队列到持久化存储
@@ -1,25 +1,3 @@
1
- var __pow = Math.pow;
2
- var __async = (__this, __arguments, generator) => {
3
- return new Promise((resolve, reject) => {
4
- var fulfilled = (value) => {
5
- try {
6
- step(generator.next(value));
7
- } catch (e) {
8
- reject(e);
9
- }
10
- };
11
- var rejected = (value) => {
12
- try {
13
- step(generator.throw(value));
14
- } catch (e) {
15
- reject(e);
16
- }
17
- };
18
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
19
- step((generator = generator.apply(__this, __arguments)).next());
20
- });
21
- };
22
-
23
1
  // src/core/retryManager.ts
24
2
  import { logDebug } from "../utils/tools";
25
3
  var RetryManager = class {
@@ -33,59 +11,55 @@ var RetryManager = class {
33
11
  * @param fn - 要执行的异步函数
34
12
  * @returns Promise
35
13
  */
36
- executeWithRetry(taskId, fn) {
37
- return __async(this, null, function* () {
38
- if (this.retryingTasks.has(taskId)) {
39
- logDebug(!!this.opts.debug, `Task ${taskId} already retrying, skipped`);
40
- throw new Error(`Task ${taskId} already retrying`);
41
- }
42
- const task = {
43
- id: taskId,
44
- fn,
45
- retries: 0,
46
- maxRetries: this.opts.maxRetries,
47
- baseDelay: this.opts.baseDelay,
48
- useBackoff: this.opts.useBackoff
49
- };
50
- this.retryingTasks.set(taskId, task);
51
- try {
52
- const result = yield this.executeTask(task);
53
- this.retryingTasks.delete(taskId);
54
- return result;
55
- } catch (error) {
56
- this.retryingTasks.delete(taskId);
57
- throw error;
58
- }
59
- });
14
+ async executeWithRetry(taskId, fn) {
15
+ if (this.retryingTasks.has(taskId)) {
16
+ logDebug(!!this.opts.debug, `Task ${taskId} already retrying, skipped`);
17
+ throw new Error(`Task ${taskId} already retrying`);
18
+ }
19
+ const task = {
20
+ id: taskId,
21
+ fn,
22
+ retries: 0,
23
+ maxRetries: this.opts.maxRetries,
24
+ baseDelay: this.opts.baseDelay,
25
+ useBackoff: this.opts.useBackoff
26
+ };
27
+ this.retryingTasks.set(taskId, task);
28
+ try {
29
+ const result = await this.executeTask(task);
30
+ this.retryingTasks.delete(taskId);
31
+ return result;
32
+ } catch (error) {
33
+ this.retryingTasks.delete(taskId);
34
+ throw error;
35
+ }
60
36
  }
61
37
  /**
62
38
  * 执行任务(带重试逻辑)
63
39
  */
64
- executeTask(task) {
65
- return __async(this, null, function* () {
66
- while (task.retries <= task.maxRetries) {
67
- try {
68
- const result = yield task.fn();
69
- if (task.retries > 0) {
70
- logDebug(!!this.opts.debug, `Task ${task.id} succeeded after ${task.retries} retries`);
71
- }
72
- return result;
73
- } catch (error) {
74
- task.retries += 1;
75
- if (task.retries > task.maxRetries) {
76
- logDebug(!!this.opts.debug, `Task ${task.id} failed after ${task.maxRetries} retries`);
77
- throw error;
78
- }
79
- const delay = RetryManager.calculateDelay(task.retries, task.baseDelay, task.useBackoff);
80
- logDebug(
81
- !!this.opts.debug,
82
- `Task ${task.id} failed (attempt ${task.retries}/${task.maxRetries}), retrying in ${delay}ms`
83
- );
84
- yield RetryManager.sleep(delay);
40
+ async executeTask(task) {
41
+ while (task.retries <= task.maxRetries) {
42
+ try {
43
+ const result = await task.fn();
44
+ if (task.retries > 0) {
45
+ logDebug(!!this.opts.debug, `Task ${task.id} succeeded after ${task.retries} retries`);
85
46
  }
47
+ return result;
48
+ } catch (error) {
49
+ task.retries += 1;
50
+ if (task.retries > task.maxRetries) {
51
+ logDebug(!!this.opts.debug, `Task ${task.id} failed after ${task.maxRetries} retries`);
52
+ throw error;
53
+ }
54
+ const delay = RetryManager.calculateDelay(task.retries, task.baseDelay, task.useBackoff);
55
+ logDebug(
56
+ !!this.opts.debug,
57
+ `Task ${task.id} failed (attempt ${task.retries}/${task.maxRetries}), retrying in ${delay}ms`
58
+ );
59
+ await RetryManager.sleep(delay);
86
60
  }
87
- throw new Error(`Task ${task.id} exceeded max retries`);
88
- });
61
+ }
62
+ throw new Error(`Task ${task.id} exceeded max retries`);
89
63
  }
90
64
  /**
91
65
  * 计算延迟时间
@@ -98,7 +72,7 @@ var RetryManager = class {
98
72
  if (!useBackoff) {
99
73
  return baseDelay;
100
74
  }
101
- const factor = __pow(2, attempt - 1);
75
+ const factor = 2 ** (attempt - 1);
102
76
  const delay = baseDelay * factor;
103
77
  const jitterRatio = 0.3;
104
78
  const maxDelay = 3e4;
@@ -1,36 +1,13 @@
1
- var __async = (__this, __arguments, generator) => {
2
- return new Promise((resolve, reject) => {
3
- var fulfilled = (value) => {
4
- try {
5
- step(generator.next(value));
6
- } catch (e) {
7
- reject(e);
8
- }
9
- };
10
- var rejected = (value) => {
11
- try {
12
- step(generator.throw(value));
13
- } catch (e) {
14
- reject(e);
15
- }
16
- };
17
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
- step((generator = generator.apply(__this, __arguments)).next());
19
- });
20
- };
21
-
22
1
  // src/stack/stacktrace.ts
23
2
  import StackTrace from "stacktrace-js";
24
- function parseStack(error) {
25
- return __async(this, null, function* () {
26
- const frames = yield StackTrace.fromError(error);
27
- return frames.slice(0, 5).map((f) => ({
28
- file: f.fileName || "",
29
- line: f.lineNumber || 0,
30
- column: f.columnNumber || 0,
31
- function: f.functionName || void 0
32
- }));
33
- });
3
+ async function parseStack(error) {
4
+ const frames = await StackTrace.fromError(error);
5
+ return frames.slice(0, 5).map((f) => ({
6
+ file: f.fileName || "",
7
+ line: f.lineNumber || 0,
8
+ column: f.columnNumber || 0,
9
+ function: f.functionName || void 0
10
+ }));
34
11
  }
35
12
  export {
36
13
  parseStack
@@ -1,43 +1,3 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __async = (__this, __arguments, generator) => {
21
- return new Promise((resolve, reject) => {
22
- var fulfilled = (value) => {
23
- try {
24
- step(generator.next(value));
25
- } catch (e) {
26
- reject(e);
27
- }
28
- };
29
- var rejected = (value) => {
30
- try {
31
- step(generator.throw(value));
32
- } catch (e) {
33
- reject(e);
34
- }
35
- };
36
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
- step((generator = generator.apply(__this, __arguments)).next());
38
- });
39
- };
40
-
41
1
  // src/transport/beaconTransport.ts
42
2
  import { gzipCompress } from "../compress/compression";
43
3
  import { getReportApi } from "../config";
@@ -53,27 +13,26 @@ var BeaconTransport = class {
53
13
  isSupported() {
54
14
  return isBrowser() && typeof navigator !== "undefined" && navigator.sendBeacon && typeof navigator.sendBeacon === "function";
55
15
  }
56
- send(payload) {
57
- return __async(this, null, function* () {
58
- var _a, _b, _c, _d, _e;
59
- let body = typeof payload === "string" ? payload : safeStringify(payload);
60
- const endpoint = getReportApi(((_a = this.opts) == null ? void 0 : _a.env) || "develop");
61
- let contentType = "application/json";
62
- if (((_b = this.opts) == null ? void 0 : _b.enableGzip) && (!((_c = this.opts) == null ? void 0 : _c.gzipOnlyInBatchMode) || payload.items.length > 0)) {
63
- const compressedItems = yield gzipCompress(safeStringify(payload.items));
64
- body = safeStringify(__spreadProps(__spreadValues({}, payload), {
65
- items: compressedItems
66
- }));
67
- contentType = "application/json; charset=utf-8";
68
- }
69
- const blob = new Blob([body], { type: contentType });
70
- const success = navigator.sendBeacon(endpoint, blob);
71
- logDebug(!!((_d = this.opts) == null ? void 0 : _d.debug), "sendBeacon result", success);
72
- if (!success) {
73
- logDebug(!!((_e = this.opts) == null ? void 0 : _e.debug), "sendBeacon failed (queue full or other error)");
74
- }
75
- return Promise.resolve();
76
- });
16
+ async send(payload) {
17
+ var _a, _b, _c, _d, _e;
18
+ let body = typeof payload === "string" ? payload : safeStringify(payload);
19
+ const endpoint = getReportApi(((_a = this.opts) == null ? void 0 : _a.env) || "develop");
20
+ let contentType = "application/json";
21
+ if (((_b = this.opts) == null ? void 0 : _b.enableGzip) && (!((_c = this.opts) == null ? void 0 : _c.gzipOnlyInBatchMode) || payload.items.length > 0)) {
22
+ const compressedItems = await gzipCompress(safeStringify(payload.items));
23
+ body = safeStringify({
24
+ ...payload,
25
+ items: compressedItems
26
+ });
27
+ contentType = "application/json; charset=utf-8";
28
+ }
29
+ const blob = new Blob([body], { type: contentType });
30
+ const success = navigator.sendBeacon(endpoint, blob);
31
+ logDebug(!!((_d = this.opts) == null ? void 0 : _d.debug), "sendBeacon result", success);
32
+ if (!success) {
33
+ logDebug(!!((_e = this.opts) == null ? void 0 : _e.debug), "sendBeacon failed (queue full or other error)");
34
+ }
35
+ return Promise.resolve();
77
36
  }
78
37
  };
79
38
  export {
@@ -1,30 +1,8 @@
1
- var __async = (__this, __arguments, generator) => {
2
- return new Promise((resolve, reject) => {
3
- var fulfilled = (value) => {
4
- try {
5
- step(generator.next(value));
6
- } catch (e) {
7
- reject(e);
8
- }
9
- };
10
- var rejected = (value) => {
11
- try {
12
- step(generator.throw(value));
13
- } catch (e) {
14
- reject(e);
15
- }
16
- };
17
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
- step((generator = generator.apply(__this, __arguments)).next());
19
- });
20
- };
21
-
22
1
  // src/transport/pixelImageTransport.ts
23
- import { Base64 } from "js-base64";
24
2
  import { isBrowser } from "../utils/environment";
25
3
  import { logDebug, now, safeStringify } from "../utils/tools";
26
4
  import { getPixelBatchApi } from "../config";
27
- import { gzipCompress } from "../compress/compression";
5
+ import { convert2Base64, gzipCompress } from "../compress/compression";
28
6
  var PixelImageTransport = class {
29
7
  constructor(opts) {
30
8
  /** 传输器名称 */
@@ -35,62 +13,60 @@ var PixelImageTransport = class {
35
13
  isSupported() {
36
14
  return isBrowser() && typeof Image !== "undefined";
37
15
  }
38
- send(payload) {
39
- return __async(this, null, function* () {
40
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
41
- const body = safeStringify(payload.items);
42
- const endpoint = getPixelBatchApi(((_a = this.opts) == null ? void 0 : _a.env) || "develop");
43
- const param = "items";
44
- const maxLen = ((_b = this.opts) == null ? void 0 : _b.maxPixelUrlLen) || 8192;
45
- let compressedBody;
46
- if (((_c = this.opts) == null ? void 0 : _c.enableGzip) && (!((_d = this.opts) == null ? void 0 : _d.gzipOnlyInBatchMode) || payload.items.length > 0)) {
47
- const t = now();
48
- logDebug(!!((_e = this.opts) == null ? void 0 : _e.debug), "PixelImage request gzip compress body: ", body);
49
- compressedBody = yield gzipCompress(body);
50
- logDebug(!!((_f = this.opts) == null ? void 0 : _f.debug), "PixelImage request gzip compress cost: ", now() - t);
51
- logDebug(!!((_g = this.opts) == null ? void 0 : _g.debug), `original body size: ${body.length}, compressed body size: ${compressedBody.length}`);
52
- logDebug(!!((_h = this.opts) == null ? void 0 : _h.debug), "PixelImage request gzip compress body: ", compressedBody);
53
- } else {
54
- compressedBody = Base64.encode(body, false);
55
- }
56
- const cacheBuster = `_=${Date.now()}`;
57
- const qs = `appId=${((_i = this.opts) == null ? void 0 : _i.appId) || ""}&appStage=${((_j = this.opts) == null ? void 0 : _j.logStage) || ""}&${param}=${encodeURIComponent(compressedBody)}&gzip=${((_k = this.opts) == null ? void 0 : _k.enableGzip) ? 1 : 0}&${cacheBuster}`;
58
- const url = endpoint.includes("?") ? `${endpoint}&${qs}` : `${endpoint}?${qs}`;
59
- if (url.length > maxLen) {
60
- logDebug(!!((_l = this.opts) == null ? void 0 : _l.debug), `URL too long (${url.length} > ${maxLen})`);
61
- }
62
- return new Promise((resolve, reject) => {
63
- const img = new Image();
64
- let timeoutId = null;
65
- let settled = false;
66
- timeoutId = setTimeout(() => {
67
- if (!settled) {
68
- settled = true;
69
- img.src = "";
70
- reject(new Error("Image request timeout after 5000ms"));
71
- }
72
- }, 5e3);
73
- img.onload = () => {
74
- if (timeoutId)
75
- clearTimeout(timeoutId);
76
- if (!settled) {
77
- settled = true;
78
- resolve();
79
- }
80
- };
81
- img.onerror = (event, source, lineno, colno, error) => {
82
- var _a2, _b2;
83
- logDebug(!!((_a2 = this.opts) == null ? void 0 : _a2.debug), "Image request failed", event, source, lineno, colno, error);
84
- if (timeoutId)
85
- clearTimeout(timeoutId);
86
- if (!settled) {
87
- settled = true;
88
- logDebug(!!((_b2 = this.opts) == null ? void 0 : _b2.debug), "Image request failed", event, source, lineno, colno, error);
89
- resolve();
90
- }
91
- };
92
- img.src = url;
93
- });
16
+ async send(payload) {
17
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
18
+ const body = safeStringify(payload.items);
19
+ const endpoint = getPixelBatchApi(((_a = this.opts) == null ? void 0 : _a.env) || "develop");
20
+ const param = "items";
21
+ const maxLen = ((_b = this.opts) == null ? void 0 : _b.maxPixelUrlLen) || 8192;
22
+ let compressedBody;
23
+ if (((_c = this.opts) == null ? void 0 : _c.enableGzip) && (!((_d = this.opts) == null ? void 0 : _d.gzipOnlyInBatchMode) || payload.items.length > 0)) {
24
+ const t = now();
25
+ logDebug(!!((_e = this.opts) == null ? void 0 : _e.debug), "PixelImage request gzip compress body: ", body);
26
+ compressedBody = await gzipCompress(body);
27
+ logDebug(!!((_f = this.opts) == null ? void 0 : _f.debug), "PixelImage request gzip compress cost: ", now() - t);
28
+ logDebug(!!((_g = this.opts) == null ? void 0 : _g.debug), `original body size: ${body.length}, compressed body size: ${compressedBody.length}`);
29
+ logDebug(!!((_h = this.opts) == null ? void 0 : _h.debug), "PixelImage request gzip compress body: ", compressedBody);
30
+ } else {
31
+ compressedBody = convert2Base64(body);
32
+ }
33
+ const cacheBuster = `_=${Date.now()}`;
34
+ const qs = `appId=${((_i = this.opts) == null ? void 0 : _i.appId) || ""}&appStage=${((_j = this.opts) == null ? void 0 : _j.logStage) || ""}&${param}=${encodeURIComponent(compressedBody)}&gzip=${((_k = this.opts) == null ? void 0 : _k.enableGzip) ? 1 : 0}&${cacheBuster}`;
35
+ const url = endpoint.includes("?") ? `${endpoint}&${qs}` : `${endpoint}?${qs}`;
36
+ if (url.length > maxLen) {
37
+ logDebug(!!((_l = this.opts) == null ? void 0 : _l.debug), `URL too long (${url.length} > ${maxLen})`);
38
+ }
39
+ return new Promise((resolve, reject) => {
40
+ const img = new Image();
41
+ let timeoutId = null;
42
+ let settled = false;
43
+ timeoutId = setTimeout(() => {
44
+ if (!settled) {
45
+ settled = true;
46
+ img.src = "";
47
+ reject(new Error("Image request timeout after 5000ms"));
48
+ }
49
+ }, 5e3);
50
+ img.onload = () => {
51
+ if (timeoutId)
52
+ clearTimeout(timeoutId);
53
+ if (!settled) {
54
+ settled = true;
55
+ resolve();
56
+ }
57
+ };
58
+ img.onerror = (event, source, lineno, colno, error) => {
59
+ var _a2, _b2;
60
+ logDebug(!!((_a2 = this.opts) == null ? void 0 : _a2.debug), "Image request failed", event, source, lineno, colno, error);
61
+ if (timeoutId)
62
+ clearTimeout(timeoutId);
63
+ if (!settled) {
64
+ settled = true;
65
+ logDebug(!!((_b2 = this.opts) == null ? void 0 : _b2.debug), "Image request failed", event, source, lineno, colno, error);
66
+ resolve();
67
+ }
68
+ };
69
+ img.src = url;
94
70
  });
95
71
  }
96
72
  };
@@ -1,13 +1,8 @@
1
1
  // src/transport/transportAdapter.ts
2
2
  import { isWeChatMiniProgram } from "../utils/environment";
3
- import { BeaconTransport } from "./beaconTransport";
4
- import { PixelImageTransport } from "./pixelImageTransport";
5
- import { WechatTransport } from "./wechatTransport";
6
3
  var TransportAdapter = class {
7
4
  constructor(opts) {
8
- this.beaconTransport = new BeaconTransport(opts);
9
- this.pixelImageTransport = new PixelImageTransport(opts);
10
- this.wechatTransport = new WechatTransport(opts);
5
+ this.opts = opts;
11
6
  }
12
7
  static getInstance(opts) {
13
8
  if (!TransportAdapter.instance) {
@@ -15,16 +10,19 @@ var TransportAdapter = class {
15
10
  }
16
11
  return TransportAdapter.instance;
17
12
  }
18
- getTransporter() {
13
+ async getTransporter() {
19
14
  if (isWeChatMiniProgram()) {
20
- return this.wechatTransport;
15
+ const mod = await import("./wechatTransport");
16
+ return new mod.WechatTransport(this.opts);
21
17
  }
22
- const transports = [this.beaconTransport, this.pixelImageTransport];
23
- const transporter = transports.find((t) => t.isSupported());
24
- if (!transporter) {
25
- return this.pixelImageTransport;
18
+ const beaconMod = await import("./beaconTransport");
19
+ const pixelMod = await import("./pixelImageTransport");
20
+ const beacon = new beaconMod.BeaconTransport(this.opts);
21
+ const pixel = new pixelMod.PixelImageTransport(this.opts);
22
+ if (beacon.isSupported()) {
23
+ return beacon;
26
24
  }
27
- return transporter;
25
+ return pixel;
28
26
  }
29
27
  };
30
28
  export {