@be-link/request 1.45.1-beta.2 → 1.45.1-beta.3

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.esm.js CHANGED
@@ -4,7 +4,7 @@ import CryptoJS from 'crypto-js';
4
4
  /**
5
5
  * HTTP 状态码常量
6
6
  */
7
- var HTTP_STATUS = {
7
+ const HTTP_STATUS = {
8
8
  OK: 200,
9
9
  CREATED: 201,
10
10
  NO_CONTENT: 204,
@@ -40,22 +40,26 @@ var ContentType;
40
40
  /**
41
41
  * 默认超时时间
42
42
  */
43
- var DEFAULT_TIMEOUT = 8000;
43
+ const DEFAULT_TIMEOUT = 8000;
44
44
  /**
45
45
  * Token Header 名称
46
46
  */
47
- var TOKEN_HEADER = 'x-belink-authorization';
47
+ const TOKEN_HEADER = 'x-belink-authorization';
48
+ /**
49
+ * UserID Header 名称
50
+ */
51
+ const USERID_HEADER = 'x-belink-userid';
48
52
  /**
49
53
  * 时间同步 Header
50
54
  */
51
- var TIME_SYNC_HEADERS = {
55
+ const TIME_SYNC_HEADERS = {
52
56
  SERVER_TIME: 'x-belink-serverTime',
53
57
  TIME_DIFF: 'x-belink-timeDiff',
54
58
  };
55
59
  /**
56
60
  * LocalStorage 键
57
61
  */
58
- var STORAGE_KEYS = {
62
+ const STORAGE_KEYS = {
59
63
  TOKEN: 'token',
60
64
  SERVER_TIME: 'x-belink-serverTime',
61
65
  TIME_DIFF: 'x-belink-timeDiff',
@@ -67,9 +71,9 @@ var STORAGE_KEYS = {
67
71
  */
68
72
  function request(config) {
69
73
  // 创建独立实例,避免拦截器泄漏
70
- var instance = axios.create();
74
+ const instance = axios.create();
71
75
  // 解析 HTTP 方法
72
- var method = config.method || (config.data ? 'post' : 'get');
76
+ const method = config.method || (config.data ? 'post' : 'get');
73
77
  // 应用临时拦截器
74
78
  if (config.requestInterceptors && typeof config.requestInterceptors === 'function') {
75
79
  instance.interceptors.request.use(config.requestInterceptors);
@@ -77,18 +81,18 @@ function request(config) {
77
81
  if (config.responseInterceptors && typeof config.responseInterceptors === 'function') {
78
82
  instance.interceptors.response.use(config.responseInterceptors);
79
83
  }
80
- var timeout = config.timeout || DEFAULT_TIMEOUT;
81
- return new Promise(function (resolve, reject) {
84
+ const timeout = config.timeout || DEFAULT_TIMEOUT;
85
+ return new Promise((resolve, reject) => {
82
86
  instance
83
87
  .request({
84
- method: method,
88
+ method,
85
89
  url: config.url,
86
90
  headers: config.headers || {},
87
91
  data: config.data,
88
92
  params: config.params,
89
- timeout: timeout,
93
+ timeout,
90
94
  })
91
- .then(function (result) {
95
+ .then((result) => {
92
96
  if (result.status === 200) {
93
97
  resolve(result.data);
94
98
  }
@@ -96,140 +100,15 @@ function request(config) {
96
100
  reject(result.data);
97
101
  }
98
102
  })
99
- .catch(function (reason) {
100
- var _a, _b;
103
+ .catch((reason) => {
101
104
  if (config.catchCallback && typeof config.catchCallback === 'function') {
102
105
  config.catchCallback(reason);
103
106
  }
104
- reject((_b = (_a = reason === null || reason === void 0 ? void 0 : reason.response) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : reason);
107
+ reject(reason?.response?.data ?? reason);
105
108
  });
106
109
  });
107
110
  }
108
111
 
109
- /******************************************************************************
110
- Copyright (c) Microsoft Corporation.
111
-
112
- Permission to use, copy, modify, and/or distribute this software for any
113
- purpose with or without fee is hereby granted.
114
-
115
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
116
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
117
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
118
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
119
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
120
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
121
- PERFORMANCE OF THIS SOFTWARE.
122
- ***************************************************************************** */
123
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
124
-
125
- var extendStatics = function(d, b) {
126
- extendStatics = Object.setPrototypeOf ||
127
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
128
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
129
- return extendStatics(d, b);
130
- };
131
-
132
- function __extends$1(d, b) {
133
- if (typeof b !== "function" && b !== null)
134
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
135
- extendStatics(d, b);
136
- function __() { this.constructor = d; }
137
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
138
- }
139
-
140
- var __assign$4 = function() {
141
- __assign$4 = Object.assign || function __assign(t) {
142
- for (var s, i = 1, n = arguments.length; i < n; i++) {
143
- s = arguments[i];
144
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
145
- }
146
- return t;
147
- };
148
- return __assign$4.apply(this, arguments);
149
- };
150
-
151
- function __awaiter$3(thisArg, _arguments, P, generator) {
152
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
153
- return new (P || (P = Promise))(function (resolve, reject) {
154
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
155
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
156
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
157
- step((generator = generator.apply(thisArg, _arguments || [])).next());
158
- });
159
- }
160
-
161
- function __generator$3(thisArg, body) {
162
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
163
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
164
- function verb(n) { return function (v) { return step([n, v]); }; }
165
- function step(op) {
166
- if (f) throw new TypeError("Generator is already executing.");
167
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
168
- 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;
169
- if (y = 0, t) op = [op[0] & 2, t.value];
170
- switch (op[0]) {
171
- case 0: case 1: t = op; break;
172
- case 4: _.label++; return { value: op[1], done: false };
173
- case 5: _.label++; y = op[1]; op = [0]; continue;
174
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
175
- default:
176
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
177
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
178
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
179
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
180
- if (t[2]) _.ops.pop();
181
- _.trys.pop(); continue;
182
- }
183
- op = body.call(thisArg, _);
184
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
185
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
186
- }
187
- }
188
-
189
- function __values(o) {
190
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
191
- if (m) return m.call(o);
192
- if (o && typeof o.length === "number") return {
193
- next: function () {
194
- if (o && i >= o.length) o = void 0;
195
- return { value: o && o[i++], done: !o };
196
- }
197
- };
198
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
199
- }
200
-
201
- function __read(o, n) {
202
- var m = typeof Symbol === "function" && o[Symbol.iterator];
203
- if (!m) return o;
204
- var i = m.call(o), r, ar = [], e;
205
- try {
206
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
207
- }
208
- catch (error) { e = { error: error }; }
209
- finally {
210
- try {
211
- if (r && !r.done && (m = i["return"])) m.call(i);
212
- }
213
- finally { if (e) throw e.error; }
214
- }
215
- return ar;
216
- }
217
-
218
- function __spreadArray$1(to, from, pack) {
219
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
220
- if (ar || !(i in from)) {
221
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
222
- ar[i] = from[i];
223
- }
224
- }
225
- return to.concat(ar || Array.prototype.slice.call(from));
226
- }
227
-
228
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
229
- var e = new Error(message);
230
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
231
- };
232
-
233
112
  /**
234
113
  * HTTP 方法枚举
235
114
  */
@@ -245,660 +124,376 @@ var HttpMethod;
245
124
  /**
246
125
  * 基础错误类
247
126
  */
248
- var BaseError = /** @class */ (function (_super) {
249
- __extends$1(BaseError, _super);
250
- function BaseError(message, code, originalError) {
251
- var _this = _super.call(this, message) || this;
252
- Object.defineProperty(_this, "code", {
253
- enumerable: true,
254
- configurable: true,
255
- writable: true,
256
- value: void 0
257
- });
258
- Object.defineProperty(_this, "originalError", {
259
- enumerable: true,
260
- configurable: true,
261
- writable: true,
262
- value: void 0
263
- });
264
- _this.name = _this.constructor.name;
265
- _this.code = code;
266
- _this.originalError = originalError;
267
- Error.captureStackTrace(_this, _this.constructor);
268
- return _this;
127
+ class BaseError extends Error {
128
+ constructor(message, code, originalError) {
129
+ super(message);
130
+ this.name = this.constructor.name;
131
+ this.code = code;
132
+ this.originalError = originalError;
133
+ Error.captureStackTrace(this, this.constructor);
269
134
  }
270
- return BaseError;
271
- }(Error));
135
+ }
272
136
  /**
273
137
  * HTTP 错误
274
138
  */
275
- var HttpError = /** @class */ (function (_super) {
276
- __extends$1(HttpError, _super);
277
- function HttpError(message, status, data, originalError) {
278
- var _this = _super.call(this, message, 'HTTP_ERROR', originalError) || this;
279
- Object.defineProperty(_this, "status", {
280
- enumerable: true,
281
- configurable: true,
282
- writable: true,
283
- value: void 0
284
- });
285
- Object.defineProperty(_this, "data", {
286
- enumerable: true,
287
- configurable: true,
288
- writable: true,
289
- value: void 0
290
- });
291
- _this.status = status;
292
- _this.data = data;
293
- return _this;
139
+ class HttpError extends BaseError {
140
+ constructor(message, status, data, originalError) {
141
+ super(message, 'HTTP_ERROR', originalError);
142
+ this.status = status;
143
+ this.data = data;
294
144
  }
295
- return HttpError;
296
- }(BaseError));
145
+ }
297
146
  /**
298
147
  * 认证错误
299
148
  */
300
- var AuthError = /** @class */ (function (_super) {
301
- __extends$1(AuthError, _super);
302
- function AuthError(message, originalError) {
303
- if (message === void 0) { message = 'Unauthorized'; }
304
- return _super.call(this, message, 'AUTH_ERROR', originalError) || this;
305
- }
306
- return AuthError;
307
- }(BaseError));
149
+ class AuthError extends BaseError {
150
+ constructor(message = 'Unauthorized', originalError) {
151
+ super(message, 'AUTH_ERROR', originalError);
152
+ }
153
+ }
308
154
  /**
309
155
  * 超时错误
310
156
  */
311
- var TimeoutError = /** @class */ (function (_super) {
312
- __extends$1(TimeoutError, _super);
313
- function TimeoutError(message, timeout, originalError) {
314
- var _this = _super.call(this, message, 'TIMEOUT_ERROR', originalError) || this;
315
- Object.defineProperty(_this, "timeout", {
316
- enumerable: true,
317
- configurable: true,
318
- writable: true,
319
- value: void 0
320
- });
321
- _this.timeout = timeout;
322
- return _this;
157
+ class TimeoutError extends BaseError {
158
+ constructor(message, timeout, originalError) {
159
+ super(message, 'TIMEOUT_ERROR', originalError);
160
+ this.timeout = timeout;
323
161
  }
324
- return TimeoutError;
325
- }(BaseError));
162
+ }
326
163
  /**
327
164
  * 配置错误
328
165
  */
329
- var ConfigError = /** @class */ (function (_super) {
330
- __extends$1(ConfigError, _super);
331
- function ConfigError(message, originalError) {
332
- return _super.call(this, message, 'CONFIG_ERROR', originalError) || this;
166
+ class ConfigError extends BaseError {
167
+ constructor(message, originalError) {
168
+ super(message, 'CONFIG_ERROR', originalError);
333
169
  }
334
- return ConfigError;
335
- }(BaseError));
170
+ }
336
171
  /**
337
172
  * 网络错误
338
173
  */
339
- var NetworkError = /** @class */ (function (_super) {
340
- __extends$1(NetworkError, _super);
341
- function NetworkError(message, originalError) {
342
- if (message === void 0) { message = 'Network error'; }
343
- return _super.call(this, message, 'NETWORK_ERROR', originalError) || this;
174
+ class NetworkError extends BaseError {
175
+ constructor(message = 'Network error', originalError) {
176
+ super(message, 'NETWORK_ERROR', originalError);
344
177
  }
345
- return NetworkError;
346
- }(BaseError));
178
+ }
347
179
 
348
180
  /**
349
181
  * Axios 适配器
350
182
  * 封装 Axios 实例,提供统一的请求接口
351
183
  */
352
- var AxiosAdapter = /** @class */ (function () {
353
- function AxiosAdapter(baseURL, timeout) {
354
- Object.defineProperty(this, "instance", {
355
- enumerable: true,
356
- configurable: true,
357
- writable: true,
358
- value: void 0
359
- });
360
- Object.defineProperty(this, "interceptorIds", {
361
- enumerable: true,
362
- configurable: true,
363
- writable: true,
364
- value: {
365
- request: [],
366
- response: [],
367
- }
368
- });
184
+ class AxiosAdapter {
185
+ constructor(baseURL, timeout) {
186
+ this.interceptorIds = {
187
+ request: [],
188
+ response: [],
189
+ };
369
190
  this.instance = axios.create({
370
- baseURL: baseURL,
191
+ baseURL,
371
192
  timeout: timeout || DEFAULT_TIMEOUT,
372
193
  });
373
194
  }
374
195
  /**
375
196
  * 发起请求
376
197
  */
377
- Object.defineProperty(AxiosAdapter.prototype, "request", {
378
- enumerable: false,
379
- configurable: true,
380
- writable: true,
381
- value: function (config) {
382
- return __awaiter$3(this, void 0, void 0, function () {
383
- var headers, axiosConfig, response, error_1;
384
- return __generator$3(this, function (_a) {
385
- switch (_a.label) {
386
- case 0:
387
- headers = __assign$4({}, config.headers);
388
- // 当有请求体时,默认设置 Content-Type 为 application/json
389
- if (config.data && !headers['Content-Type'] && !headers['content-type']) {
390
- headers['Content-Type'] = ContentType.JSON;
391
- }
392
- axiosConfig = __assign$4({ method: config.method || (config.data ? HttpMethod.POST : HttpMethod.GET), url: config.url, headers: headers, data: config.data, params: config.params, timeout: config.timeout || DEFAULT_TIMEOUT }, config.axiosConfig);
393
- _a.label = 1;
394
- case 1:
395
- _a.trys.push([1, 3, , 4]);
396
- return [4 /*yield*/, this.instance.request(axiosConfig)];
397
- case 2:
398
- response = _a.sent();
399
- if (response.status === 200) {
400
- return [2 /*return*/, response.data];
401
- }
402
- throw new HttpError("Request failed with status ".concat(response.status), response.status, response.data);
403
- case 3:
404
- error_1 = _a.sent();
405
- throw this.handleError(error_1);
406
- case 4: return [2 /*return*/];
407
- }
408
- });
409
- });
198
+ async request(config) {
199
+ const headers = { ...config.headers };
200
+ // 当有请求体时,默认设置 Content-Type 为 application/json
201
+ if (config.data && !headers['Content-Type'] && !headers['content-type']) {
202
+ headers['Content-Type'] = ContentType.JSON;
410
203
  }
411
- });
204
+ const axiosConfig = {
205
+ method: config.method || (config.data ? HttpMethod.POST : HttpMethod.GET),
206
+ url: config.url,
207
+ headers,
208
+ data: config.data,
209
+ params: config.params,
210
+ timeout: config.timeout || DEFAULT_TIMEOUT,
211
+ ...config.axiosConfig,
212
+ };
213
+ try {
214
+ const response = await this.instance.request(axiosConfig);
215
+ if (response.status === 200) {
216
+ return response.data;
217
+ }
218
+ throw new HttpError(`Request failed with status ${response.status}`, response.status, response.data);
219
+ }
220
+ catch (error) {
221
+ throw this.handleError(error);
222
+ }
223
+ }
412
224
  /**
413
225
  * 添加请求拦截器
414
226
  * @returns 拦截器 ID
415
227
  */
416
- Object.defineProperty(AxiosAdapter.prototype, "addRequestInterceptor", {
417
- enumerable: false,
418
- configurable: true,
419
- writable: true,
420
- value: function (onFulfilled, onRejected) {
421
- var id = this.instance.interceptors.request.use(onFulfilled, onRejected);
422
- this.interceptorIds.request.push(id);
423
- return id;
424
- }
425
- });
228
+ addRequestInterceptor(onFulfilled, onRejected) {
229
+ const id = this.instance.interceptors.request.use(onFulfilled, onRejected);
230
+ this.interceptorIds.request.push(id);
231
+ return id;
232
+ }
426
233
  /**
427
234
  * 添加响应拦截器
428
235
  * @returns 拦截器 ID
429
236
  */
430
- Object.defineProperty(AxiosAdapter.prototype, "addResponseInterceptor", {
431
- enumerable: false,
432
- configurable: true,
433
- writable: true,
434
- value: function (onFulfilled, onRejected) {
435
- var id = this.instance.interceptors.response.use(onFulfilled, onRejected);
436
- this.interceptorIds.response.push(id);
437
- return id;
438
- }
439
- });
237
+ addResponseInterceptor(onFulfilled, onRejected) {
238
+ const id = this.instance.interceptors.response.use(onFulfilled, onRejected);
239
+ this.interceptorIds.response.push(id);
240
+ return id;
241
+ }
440
242
  /**
441
243
  * 移除请求拦截器
442
244
  */
443
- Object.defineProperty(AxiosAdapter.prototype, "removeRequestInterceptor", {
444
- enumerable: false,
445
- configurable: true,
446
- writable: true,
447
- value: function (id) {
448
- this.instance.interceptors.request.eject(id);
449
- var index = this.interceptorIds.request.indexOf(id);
450
- if (index > -1) {
451
- this.interceptorIds.request.splice(index, 1);
452
- }
245
+ removeRequestInterceptor(id) {
246
+ this.instance.interceptors.request.eject(id);
247
+ const index = this.interceptorIds.request.indexOf(id);
248
+ if (index > -1) {
249
+ this.interceptorIds.request.splice(index, 1);
453
250
  }
454
- });
251
+ }
455
252
  /**
456
253
  * 移除响应拦截器
457
254
  */
458
- Object.defineProperty(AxiosAdapter.prototype, "removeResponseInterceptor", {
459
- enumerable: false,
460
- configurable: true,
461
- writable: true,
462
- value: function (id) {
463
- this.instance.interceptors.response.eject(id);
464
- var index = this.interceptorIds.response.indexOf(id);
465
- if (index > -1) {
466
- this.interceptorIds.response.splice(index, 1);
467
- }
255
+ removeResponseInterceptor(id) {
256
+ this.instance.interceptors.response.eject(id);
257
+ const index = this.interceptorIds.response.indexOf(id);
258
+ if (index > -1) {
259
+ this.interceptorIds.response.splice(index, 1);
468
260
  }
469
- });
261
+ }
470
262
  /**
471
263
  * 清理所有拦截器
472
264
  */
473
- Object.defineProperty(AxiosAdapter.prototype, "clearAllInterceptors", {
474
- enumerable: false,
475
- configurable: true,
476
- writable: true,
477
- value: function () {
478
- var _this = this;
479
- this.interceptorIds.request.forEach(function (id) {
480
- _this.instance.interceptors.request.eject(id);
481
- });
482
- this.interceptorIds.response.forEach(function (id) {
483
- _this.instance.interceptors.response.eject(id);
484
- });
485
- this.interceptorIds = { request: [], response: [] };
486
- }
487
- });
265
+ clearAllInterceptors() {
266
+ this.interceptorIds.request.forEach((id) => {
267
+ this.instance.interceptors.request.eject(id);
268
+ });
269
+ this.interceptorIds.response.forEach((id) => {
270
+ this.instance.interceptors.response.eject(id);
271
+ });
272
+ this.interceptorIds = { request: [], response: [] };
273
+ }
488
274
  /**
489
275
  * 获取 Axios 实例
490
276
  */
491
- Object.defineProperty(AxiosAdapter.prototype, "getInstance", {
492
- enumerable: false,
493
- configurable: true,
494
- writable: true,
495
- value: function () {
496
- return this.instance;
497
- }
498
- });
277
+ getInstance() {
278
+ return this.instance;
279
+ }
499
280
  /**
500
281
  * 设置 BaseURL
501
282
  */
502
- Object.defineProperty(AxiosAdapter.prototype, "setBaseUrl", {
503
- enumerable: false,
504
- configurable: true,
505
- writable: true,
506
- value: function (baseUrl) {
507
- this.instance.defaults.baseURL = baseUrl;
508
- }
509
- });
283
+ setBaseUrl(baseUrl) {
284
+ this.instance.defaults.baseURL = baseUrl;
285
+ }
510
286
  /**
511
287
  * 处理错误
512
288
  */
513
- Object.defineProperty(AxiosAdapter.prototype, "handleError", {
514
- enumerable: false,
515
- configurable: true,
516
- writable: true,
517
- value: function (error) {
518
- var _a, _b;
519
- if (isAxiosError(error)) {
520
- var axiosError = error;
521
- if (axiosError.code === 'ECONNABORTED') {
522
- return new TimeoutError("Request timeout after ".concat((_a = axiosError.config) === null || _a === void 0 ? void 0 : _a.timeout, "ms"), ((_b = axiosError.config) === null || _b === void 0 ? void 0 : _b.timeout) || DEFAULT_TIMEOUT, axiosError);
523
- }
524
- if (!axiosError.response) {
525
- return new NetworkError('Network error: Unable to reach server', axiosError);
526
- }
527
- return new HttpError(axiosError.message, axiosError.response.status, axiosError.response.data, axiosError);
289
+ handleError(error) {
290
+ if (isAxiosError(error)) {
291
+ const axiosError = error;
292
+ if (axiosError.code === 'ECONNABORTED') {
293
+ return new TimeoutError(`Request timeout after ${axiosError.config?.timeout}ms`, axiosError.config?.timeout || DEFAULT_TIMEOUT, axiosError);
528
294
  }
529
- if (error instanceof Error) {
530
- return error;
295
+ if (!axiosError.response) {
296
+ return new NetworkError('Network error: Unable to reach server', axiosError);
531
297
  }
532
- return new Error(String(error));
298
+ return new HttpError(axiosError.message, axiosError.response.status, axiosError.response.data, axiosError);
533
299
  }
534
- });
535
- return AxiosAdapter;
536
- }());
300
+ if (error instanceof Error) {
301
+ return error;
302
+ }
303
+ return new Error(String(error));
304
+ }
305
+ }
537
306
 
538
307
  /**
539
308
  * 生成请求 ID
540
309
  */
541
310
  function generateRequestId() {
542
- return "req_".concat(Date.now(), "_").concat(Math.random().toString(36).substring(2, 11));
311
+ return `req_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
543
312
  }
544
313
  /**
545
314
  * HTTP 客户端实现
546
315
  * 提供基础的 HTTP 请求功能
547
316
  */
548
- var HttpClient = /** @class */ (function () {
549
- function HttpClient(adapter) {
550
- Object.defineProperty(this, "adapter", {
551
- enumerable: true,
552
- configurable: true,
553
- writable: true,
554
- value: void 0
555
- });
556
- Object.defineProperty(this, "requestInterceptors", {
557
- enumerable: true,
558
- configurable: true,
559
- writable: true,
560
- value: []
561
- });
562
- Object.defineProperty(this, "responseInterceptors", {
563
- enumerable: true,
564
- configurable: true,
565
- writable: true,
566
- value: []
567
- });
317
+ class HttpClient {
318
+ constructor(adapter) {
319
+ this.requestInterceptors = [];
320
+ this.responseInterceptors = [];
568
321
  this.adapter = adapter || new AxiosAdapter();
569
322
  }
570
323
  /**
571
324
  * GET 请求
572
325
  */
573
- Object.defineProperty(HttpClient.prototype, "get", {
574
- enumerable: false,
575
- configurable: true,
576
- writable: true,
577
- value: function (url, config) {
578
- return __awaiter$3(this, void 0, void 0, function () {
579
- return __generator$3(this, function (_a) {
580
- return [2 /*return*/, this.request(__assign$4(__assign$4({}, config), { url: url, method: HttpMethod.GET }))];
581
- });
582
- });
583
- }
584
- });
326
+ async get(url, config) {
327
+ return this.request({ ...config, url, method: HttpMethod.GET });
328
+ }
585
329
  /**
586
330
  * POST 请求
587
331
  */
588
- Object.defineProperty(HttpClient.prototype, "post", {
589
- enumerable: false,
590
- configurable: true,
591
- writable: true,
592
- value: function (url, data, config) {
593
- return __awaiter$3(this, void 0, void 0, function () {
594
- return __generator$3(this, function (_a) {
595
- return [2 /*return*/, this.request(__assign$4(__assign$4({}, config), { url: url, data: data, method: HttpMethod.POST }))];
596
- });
597
- });
598
- }
599
- });
332
+ async post(url, data, config) {
333
+ return this.request({ ...config, url, data, method: HttpMethod.POST });
334
+ }
600
335
  /**
601
336
  * PUT 请求
602
337
  */
603
- Object.defineProperty(HttpClient.prototype, "put", {
604
- enumerable: false,
605
- configurable: true,
606
- writable: true,
607
- value: function (url, data, config) {
608
- return __awaiter$3(this, void 0, void 0, function () {
609
- return __generator$3(this, function (_a) {
610
- return [2 /*return*/, this.request(__assign$4(__assign$4({}, config), { url: url, data: data, method: HttpMethod.PUT }))];
611
- });
612
- });
613
- }
614
- });
338
+ async put(url, data, config) {
339
+ return this.request({ ...config, url, data, method: HttpMethod.PUT });
340
+ }
615
341
  /**
616
342
  * DELETE 请求
617
343
  */
618
- Object.defineProperty(HttpClient.prototype, "delete", {
619
- enumerable: false,
620
- configurable: true,
621
- writable: true,
622
- value: function (url, config) {
623
- return __awaiter$3(this, void 0, void 0, function () {
624
- return __generator$3(this, function (_a) {
625
- return [2 /*return*/, this.request(__assign$4(__assign$4({}, config), { url: url, method: HttpMethod.DELETE }))];
626
- });
627
- });
628
- }
629
- });
344
+ async delete(url, config) {
345
+ return this.request({ ...config, url, method: HttpMethod.DELETE });
346
+ }
630
347
  /**
631
348
  * 通用请求方法
632
349
  */
633
- Object.defineProperty(HttpClient.prototype, "request", {
634
- enumerable: false,
635
- configurable: true,
636
- writable: true,
637
- value: function (config) {
638
- return __awaiter$3(this, void 0, void 0, function () {
639
- var context, processedContext, _a, _b, interceptor, e_1_1, response, responseContext, _c, _d, interceptor, e_2_1, error_1, processedError, _e, _f, interceptor, interceptorError_1, e_3_1;
640
- var e_1, _g, e_2, _h, e_3, _j;
641
- return __generator$3(this, function (_k) {
642
- switch (_k.label) {
643
- case 0:
644
- context = {
645
- config: this.normalizeConfig(config),
646
- startTime: Date.now(),
647
- requestId: generateRequestId(),
648
- metadata: new Map(),
649
- };
650
- _k.label = 1;
651
- case 1:
652
- _k.trys.push([1, 19, , 30]);
653
- processedContext = context;
654
- _k.label = 2;
655
- case 2:
656
- _k.trys.push([2, 7, 8, 9]);
657
- _a = __values(this.requestInterceptors), _b = _a.next();
658
- _k.label = 3;
659
- case 3:
660
- if (!!_b.done) return [3 /*break*/, 6];
661
- interceptor = _b.value;
662
- return [4 /*yield*/, interceptor.onRequest(processedContext)];
663
- case 4:
664
- processedContext = (_k.sent());
665
- _k.label = 5;
666
- case 5:
667
- _b = _a.next();
668
- return [3 /*break*/, 3];
669
- case 6: return [3 /*break*/, 9];
670
- case 7:
671
- e_1_1 = _k.sent();
672
- e_1 = { error: e_1_1 };
673
- return [3 /*break*/, 9];
674
- case 8:
675
- try {
676
- if (_b && !_b.done && (_g = _a.return)) _g.call(_a);
677
- }
678
- finally { if (e_1) throw e_1.error; }
679
- return [7 /*endfinally*/];
680
- case 9: return [4 /*yield*/, this.adapter.request(processedContext.config)];
681
- case 10:
682
- response = _k.sent();
683
- responseContext = {
684
- response: response,
685
- status: 200,
686
- headers: {},
687
- duration: Date.now() - context.startTime,
688
- requestId: context.requestId,
689
- };
690
- _k.label = 11;
691
- case 11:
692
- _k.trys.push([11, 16, 17, 18]);
693
- _c = __values(this.responseInterceptors), _d = _c.next();
694
- _k.label = 12;
695
- case 12:
696
- if (!!_d.done) return [3 /*break*/, 15];
697
- interceptor = _d.value;
698
- return [4 /*yield*/, interceptor.onResponse(responseContext)];
699
- case 13:
700
- responseContext = _k.sent();
701
- _k.label = 14;
702
- case 14:
703
- _d = _c.next();
704
- return [3 /*break*/, 12];
705
- case 15: return [3 /*break*/, 18];
706
- case 16:
707
- e_2_1 = _k.sent();
708
- e_2 = { error: e_2_1 };
709
- return [3 /*break*/, 18];
710
- case 17:
711
- try {
712
- if (_d && !_d.done && (_h = _c.return)) _h.call(_c);
713
- }
714
- finally { if (e_2) throw e_2.error; }
715
- return [7 /*endfinally*/];
716
- case 18: return [2 /*return*/, responseContext.response];
717
- case 19:
718
- error_1 = _k.sent();
719
- processedError = error_1;
720
- _k.label = 20;
721
- case 20:
722
- _k.trys.push([20, 27, 28, 29]);
723
- _e = __values(this.responseInterceptors), _f = _e.next();
724
- _k.label = 21;
725
- case 21:
726
- if (!!_f.done) return [3 /*break*/, 26];
727
- interceptor = _f.value;
728
- if (!interceptor.onResponseError) return [3 /*break*/, 25];
729
- _k.label = 22;
730
- case 22:
731
- _k.trys.push([22, 24, , 25]);
732
- return [4 /*yield*/, interceptor.onResponseError(processedError)];
733
- case 23:
734
- processedError = _k.sent();
735
- return [3 /*break*/, 25];
736
- case 24:
737
- interceptorError_1 = _k.sent();
738
- processedError = interceptorError_1;
739
- return [3 /*break*/, 25];
740
- case 25:
741
- _f = _e.next();
742
- return [3 /*break*/, 21];
743
- case 26: return [3 /*break*/, 29];
744
- case 27:
745
- e_3_1 = _k.sent();
746
- e_3 = { error: e_3_1 };
747
- return [3 /*break*/, 29];
748
- case 28:
749
- try {
750
- if (_f && !_f.done && (_j = _e.return)) _j.call(_e);
751
- }
752
- finally { if (e_3) throw e_3.error; }
753
- return [7 /*endfinally*/];
754
- case 29: throw processedError;
755
- case 30: return [2 /*return*/];
350
+ async request(config) {
351
+ // 创建请求上下文
352
+ const context = {
353
+ config: this.normalizeConfig(config),
354
+ startTime: Date.now(),
355
+ requestId: generateRequestId(),
356
+ metadata: new Map(),
357
+ };
358
+ try {
359
+ // 执行请求拦截器
360
+ let processedContext = context;
361
+ for (const interceptor of this.requestInterceptors) {
362
+ processedContext = (await interceptor.onRequest(processedContext));
363
+ }
364
+ // 发起请求
365
+ const response = await this.adapter.request(processedContext.config);
366
+ // 创建响应上下文
367
+ let responseContext = {
368
+ response,
369
+ status: 200,
370
+ headers: {},
371
+ duration: Date.now() - context.startTime,
372
+ requestId: context.requestId,
373
+ };
374
+ // 执行响应拦截器
375
+ for (const interceptor of this.responseInterceptors) {
376
+ responseContext = await interceptor.onResponse(responseContext);
377
+ }
378
+ return responseContext.response;
379
+ }
380
+ catch (error) {
381
+ // 执行错误拦截器
382
+ let processedError = error;
383
+ for (const interceptor of this.responseInterceptors) {
384
+ if (interceptor.onResponseError) {
385
+ try {
386
+ processedError = await interceptor.onResponseError(processedError);
756
387
  }
757
- });
758
- });
388
+ catch (interceptorError) {
389
+ processedError = interceptorError;
390
+ }
391
+ }
392
+ }
393
+ throw processedError;
759
394
  }
760
- });
395
+ }
761
396
  /**
762
397
  * 添加请求拦截器
763
398
  */
764
- Object.defineProperty(HttpClient.prototype, "addRequestInterceptor", {
765
- enumerable: false,
766
- configurable: true,
767
- writable: true,
768
- value: function (interceptor) {
769
- var _this = this;
770
- this.requestInterceptors.push(interceptor);
771
- this.requestInterceptors.sort(function (a, b) { return (a.priority || 0) - (b.priority || 0); });
772
- return function () {
773
- var index = _this.requestInterceptors.indexOf(interceptor);
774
- if (index > -1) {
775
- _this.requestInterceptors.splice(index, 1);
776
- }
777
- };
778
- }
779
- });
399
+ addRequestInterceptor(interceptor) {
400
+ this.requestInterceptors.push(interceptor);
401
+ this.requestInterceptors.sort((a, b) => (a.priority || 0) - (b.priority || 0));
402
+ return () => {
403
+ const index = this.requestInterceptors.indexOf(interceptor);
404
+ if (index > -1) {
405
+ this.requestInterceptors.splice(index, 1);
406
+ }
407
+ };
408
+ }
780
409
  /**
781
410
  * 添加响应拦截器
782
411
  */
783
- Object.defineProperty(HttpClient.prototype, "addResponseInterceptor", {
784
- enumerable: false,
785
- configurable: true,
786
- writable: true,
787
- value: function (interceptor) {
788
- var _this = this;
789
- this.responseInterceptors.push(interceptor);
790
- this.responseInterceptors.sort(function (a, b) { return (a.priority || 0) - (b.priority || 0); });
791
- return function () {
792
- var index = _this.responseInterceptors.indexOf(interceptor);
793
- if (index > -1) {
794
- _this.responseInterceptors.splice(index, 1);
795
- }
796
- };
797
- }
798
- });
412
+ addResponseInterceptor(interceptor) {
413
+ this.responseInterceptors.push(interceptor);
414
+ this.responseInterceptors.sort((a, b) => (a.priority || 0) - (b.priority || 0));
415
+ return () => {
416
+ const index = this.responseInterceptors.indexOf(interceptor);
417
+ if (index > -1) {
418
+ this.responseInterceptors.splice(index, 1);
419
+ }
420
+ };
421
+ }
799
422
  /**
800
423
  * 克隆客户端
801
424
  * 注意:克隆会创建新的拦截器数组,但共享同一个适配器实例
802
425
  * 如需独立的适配器,请使用 new HttpClient() 创建新实例
803
426
  */
804
- Object.defineProperty(HttpClient.prototype, "clone", {
805
- enumerable: false,
806
- configurable: true,
807
- writable: true,
808
- value: function () {
809
- var cloned = new HttpClient(this.adapter);
810
- cloned.requestInterceptors = __spreadArray$1([], __read(this.requestInterceptors), false);
811
- cloned.responseInterceptors = __spreadArray$1([], __read(this.responseInterceptors), false);
812
- return cloned;
813
- }
814
- });
427
+ clone() {
428
+ const cloned = new HttpClient(this.adapter);
429
+ cloned.requestInterceptors = [...this.requestInterceptors];
430
+ cloned.responseInterceptors = [...this.responseInterceptors];
431
+ return cloned;
432
+ }
815
433
  /**
816
434
  * 规范化配置
817
435
  */
818
- Object.defineProperty(HttpClient.prototype, "normalizeConfig", {
819
- enumerable: false,
820
- configurable: true,
821
- writable: true,
822
- value: function (config) {
823
- return __assign$4({ method: config.method || (config.data ? HttpMethod.POST : HttpMethod.GET), timeout: config.timeout || DEFAULT_TIMEOUT, headers: config.headers || {} }, config);
824
- }
825
- });
436
+ normalizeConfig(config) {
437
+ return {
438
+ method: config.method || (config.data ? HttpMethod.POST : HttpMethod.GET),
439
+ timeout: config.timeout || DEFAULT_TIMEOUT,
440
+ headers: config.headers || {},
441
+ ...config,
442
+ };
443
+ }
826
444
  /**
827
445
  * 获取适配器
828
446
  */
829
- Object.defineProperty(HttpClient.prototype, "getAdapter", {
830
- enumerable: false,
831
- configurable: true,
832
- writable: true,
833
- value: function () {
834
- return this.adapter;
835
- }
836
- });
447
+ getAdapter() {
448
+ return this.adapter;
449
+ }
837
450
  /**
838
451
  * 处理旧版拦截器的请求(向后兼容)
839
452
  * 此方法被 BeLinkClient 和 LiveClient 共享
840
453
  * @protected 允许子类调用
841
454
  */
842
- Object.defineProperty(HttpClient.prototype, "requestWithLegacyInterceptors", {
843
- enumerable: false,
844
- configurable: true,
845
- writable: true,
846
- value: function (config) {
847
- return __awaiter$3(this, void 0, void 0, function () {
848
- var removeRequestInterceptor, removeResponseInterceptor, response, error_2, err;
849
- var _a;
850
- return __generator$3(this, function (_b) {
851
- switch (_b.label) {
852
- case 0:
853
- removeRequestInterceptor = config.requestInterceptors
854
- ? this.addRequestInterceptor({
855
- name: 'LegacyRequest',
856
- priority: 100,
857
- onRequest: function (ctx) {
858
- var newConfig = config.requestInterceptors(ctx.config);
859
- return __assign$4(__assign$4({}, ctx), { config: newConfig });
860
- },
861
- })
862
- : null;
863
- removeResponseInterceptor = config.responseInterceptors
864
- ? this.addResponseInterceptor({
865
- name: 'LegacyResponse',
866
- priority: 100,
867
- onResponse: function (ctx) { return ctx; },
868
- })
869
- : null;
870
- _b.label = 1;
871
- case 1:
872
- _b.trys.push([1, 3, 4, 5]);
873
- return [4 /*yield*/, this.request(config)];
874
- case 2:
875
- response = _b.sent();
876
- return [2 /*return*/, response];
877
- case 3:
878
- error_2 = _b.sent();
879
- if (config.catchCallback) {
880
- config.catchCallback(error_2);
881
- }
882
- err = error_2;
883
- throw ((_a = err === null || err === void 0 ? void 0 : err.response) === null || _a === void 0 ? void 0 : _a.data) || error_2;
884
- case 4:
885
- // 清理临时拦截器
886
- removeRequestInterceptor === null || removeRequestInterceptor === void 0 ? void 0 : removeRequestInterceptor();
887
- removeResponseInterceptor === null || removeResponseInterceptor === void 0 ? void 0 : removeResponseInterceptor();
888
- return [7 /*endfinally*/];
889
- case 5: return [2 /*return*/];
890
- }
891
- });
892
- });
455
+ async requestWithLegacyInterceptors(config) {
456
+ // 注册临时拦截器
457
+ const removeRequestInterceptor = config.requestInterceptors
458
+ ? this.addRequestInterceptor({
459
+ name: 'LegacyRequest',
460
+ priority: 100,
461
+ onRequest: (ctx) => {
462
+ const newConfig = config.requestInterceptors(ctx.config);
463
+ return { ...ctx, config: newConfig };
464
+ },
465
+ })
466
+ : null;
467
+ const removeResponseInterceptor = config.responseInterceptors
468
+ ? this.addResponseInterceptor({
469
+ name: 'LegacyResponse',
470
+ priority: 100,
471
+ onResponse: (ctx) => ctx,
472
+ })
473
+ : null;
474
+ try {
475
+ const response = await this.request(config);
476
+ return response;
893
477
  }
894
- });
895
- return HttpClient;
896
- }());
478
+ catch (error) {
479
+ if (config.catchCallback) {
480
+ config.catchCallback(error);
481
+ }
482
+ const err = error;
483
+ throw err?.response?.data || error;
484
+ }
485
+ finally {
486
+ // 清理临时拦截器
487
+ removeRequestInterceptor?.();
488
+ removeResponseInterceptor?.();
489
+ }
490
+ }
491
+ }
897
492
 
898
493
  /**
899
494
  * 默认配置值
900
495
  */
901
- var DEFAULT_CONFIG = {
496
+ const DEFAULT_CONFIG = {
902
497
  mode: 'development',
903
498
  timeout: 8000,
904
499
  encryption: {
@@ -923,151 +518,100 @@ var DEFAULT_CONFIG = {
923
518
  * 配置管理器实现
924
519
  * 单例模式,集中管理所有配置
925
520
  */
926
- var ConfigManager = /** @class */ (function () {
927
- function ConfigManager() {
928
- Object.defineProperty(this, "config", {
929
- enumerable: true,
930
- configurable: true,
931
- writable: true,
932
- value: void 0
933
- });
934
- this.config = __assign$4({}, DEFAULT_CONFIG);
521
+ class ConfigManager {
522
+ constructor() {
523
+ this.config = { ...DEFAULT_CONFIG };
935
524
  this.loadFromEnvironment();
936
525
  }
937
526
  /**
938
527
  * 获取单例实例
939
528
  */
940
- Object.defineProperty(ConfigManager, "getInstance", {
941
- enumerable: false,
942
- configurable: true,
943
- writable: true,
944
- value: function () {
945
- if (!ConfigManager.instance) {
946
- ConfigManager.instance = new ConfigManager();
947
- }
948
- return ConfigManager.instance;
529
+ static getInstance() {
530
+ if (!ConfigManager.instance) {
531
+ ConfigManager.instance = new ConfigManager();
949
532
  }
950
- });
533
+ return ConfigManager.instance;
534
+ }
951
535
  /**
952
536
  * 初始化配置
953
537
  */
954
- Object.defineProperty(ConfigManager.prototype, "init", {
955
- enumerable: false,
956
- configurable: true,
957
- writable: true,
958
- value: function (config) {
959
- this.config = this.mergeConfig(this.config, config);
960
- if (!this.validate()) {
961
- console.warn('[ConfigManager] Configuration validation failed');
962
- }
538
+ init(config) {
539
+ this.config = this.mergeConfig(this.config, config);
540
+ if (!this.validate()) {
541
+ console.warn('[ConfigManager] Configuration validation failed');
963
542
  }
964
- });
543
+ }
965
544
  /**
966
545
  * 获取配置项
967
546
  */
968
- Object.defineProperty(ConfigManager.prototype, "get", {
969
- enumerable: false,
970
- configurable: true,
971
- writable: true,
972
- value: function (key) {
973
- return this.config[key];
974
- }
975
- });
547
+ get(key) {
548
+ return this.config[key];
549
+ }
976
550
  /**
977
551
  * 设置配置项
978
552
  */
979
- Object.defineProperty(ConfigManager.prototype, "set", {
980
- enumerable: false,
981
- configurable: true,
982
- writable: true,
983
- value: function (key, value) {
984
- this.config[key] = value;
985
- }
986
- });
553
+ set(key, value) {
554
+ this.config[key] = value;
555
+ }
987
556
  /**
988
557
  * 获取完整配置
989
558
  */
990
- Object.defineProperty(ConfigManager.prototype, "getAll", {
991
- enumerable: false,
992
- configurable: true,
993
- writable: true,
994
- value: function () {
995
- return Object.freeze(__assign$4({}, this.config));
996
- }
997
- });
559
+ getAll() {
560
+ return Object.freeze({ ...this.config });
561
+ }
998
562
  /**
999
563
  * 验证配置
1000
564
  */
1001
- Object.defineProperty(ConfigManager.prototype, "validate", {
1002
- enumerable: false,
1003
- configurable: true,
1004
- writable: true,
1005
- value: function () {
1006
- if (!this.config.mode) {
1007
- console.error('[ConfigManager] Mode is required');
1008
- return false;
1009
- }
1010
- return true;
565
+ validate() {
566
+ if (!this.config.mode) {
567
+ console.error('[ConfigManager] Mode is required');
568
+ return false;
1011
569
  }
1012
- });
570
+ return true;
571
+ }
1013
572
  /**
1014
573
  * 重置配置
1015
574
  */
1016
- Object.defineProperty(ConfigManager.prototype, "reset", {
1017
- enumerable: false,
1018
- configurable: true,
1019
- writable: true,
1020
- value: function () {
1021
- this.config = __assign$4({}, DEFAULT_CONFIG);
1022
- }
1023
- });
575
+ reset() {
576
+ this.config = { ...DEFAULT_CONFIG };
577
+ }
1024
578
  /**
1025
579
  * 从环境变量加载配置
1026
580
  */
1027
- Object.defineProperty(ConfigManager.prototype, "loadFromEnvironment", {
1028
- enumerable: false,
1029
- configurable: true,
1030
- writable: true,
1031
- value: function () {
1032
- var key = this.getEnvVar('BELINK_ENCRYPTION_KEY');
1033
- var iv = this.getEnvVar('BELINK_ENCRYPTION_IV');
1034
- if (key && iv) {
1035
- this.config.encryption = { key: key, iv: iv };
1036
- }
581
+ loadFromEnvironment() {
582
+ const key = this.getEnvVar('BELINK_ENCRYPTION_KEY');
583
+ const iv = this.getEnvVar('BELINK_ENCRYPTION_IV');
584
+ if (key && iv) {
585
+ this.config.encryption = { key, iv };
1037
586
  }
1038
- });
587
+ }
1039
588
  /**
1040
589
  * 深度合并配置
1041
590
  */
1042
- Object.defineProperty(ConfigManager.prototype, "mergeConfig", {
1043
- enumerable: false,
1044
- configurable: true,
1045
- writable: true,
1046
- value: function (target, source) {
1047
- return __assign$4(__assign$4(__assign$4({}, target), source), { encryption: source.encryption ? __assign$4(__assign$4({}, target.encryption), source.encryption) : target.encryption, timeSync: source.timeSync ? __assign$4(__assign$4({}, target.timeSync), source.timeSync) : target.timeSync, cloudbase: source.cloudbase ? __assign$4(__assign$4({}, target.cloudbase), source.cloudbase) : target.cloudbase });
1048
- }
1049
- });
591
+ mergeConfig(target, source) {
592
+ return {
593
+ ...target,
594
+ ...source,
595
+ encryption: source.encryption ? { ...target.encryption, ...source.encryption } : target.encryption,
596
+ timeSync: source.timeSync ? { ...target.timeSync, ...source.timeSync } : target.timeSync,
597
+ cloudbase: source.cloudbase ? { ...target.cloudbase, ...source.cloudbase } : target.cloudbase,
598
+ };
599
+ }
1050
600
  /**
1051
601
  * 获取环境变量
1052
602
  */
1053
- Object.defineProperty(ConfigManager.prototype, "getEnvVar", {
1054
- enumerable: false,
1055
- configurable: true,
1056
- writable: true,
1057
- value: function (key) {
1058
- // Vite 环境
1059
- if (typeof import.meta !== 'undefined' && import.meta.env) {
1060
- return import.meta.env[key];
1061
- }
1062
- // Webpack/Node 环境
1063
- if (typeof process !== 'undefined' && process.env) {
1064
- return process.env[key];
1065
- }
1066
- return undefined;
603
+ getEnvVar(key) {
604
+ // Vite 环境
605
+ if (typeof import.meta !== 'undefined' && import.meta.env) {
606
+ return import.meta.env[key];
1067
607
  }
1068
- });
1069
- return ConfigManager;
1070
- }());
608
+ // Webpack/Node 环境
609
+ if (typeof process !== 'undefined' && process.env) {
610
+ return process.env[key];
611
+ }
612
+ return undefined;
613
+ }
614
+ }
1071
615
 
1072
616
  /**
1073
617
  * 检测当前环境
@@ -1075,12 +619,12 @@ var ConfigManager = /** @class */ (function () {
1075
619
  function detectEnvironment() {
1076
620
  // Vite 环境
1077
621
  if (typeof import.meta !== 'undefined' && import.meta.env) {
1078
- var env = import.meta.env.VITE_API_ENV || import.meta.env.MODE;
622
+ const env = import.meta.env.VITE_API_ENV || import.meta.env.MODE;
1079
623
  return normalizeEnv(env);
1080
624
  }
1081
625
  // Webpack/Node 环境
1082
626
  if (typeof process !== 'undefined' && process.env) {
1083
- var env = process.env.API_ENV || process.env.NODE_ENV;
627
+ const env = process.env.API_ENV || process.env.NODE_ENV;
1084
628
  return normalizeEnv(env);
1085
629
  }
1086
630
  console.warn('[EnvUtils] Cannot detect environment, defaulting to "development"');
@@ -1092,7 +636,7 @@ function detectEnvironment() {
1092
636
  function normalizeEnv(env) {
1093
637
  if (!env)
1094
638
  return 'development';
1095
- var normalized = env.toLowerCase();
639
+ const normalized = env.toLowerCase();
1096
640
  if (normalized === 'production' || normalized === 'prod') {
1097
641
  return 'production';
1098
642
  }
@@ -1118,950 +662,658 @@ function isNode() {
1118
662
  * 加密服务实现
1119
663
  * 提供 Token 加密/解密功能
1120
664
  */
1121
- var EncryptionService = /** @class */ (function () {
1122
- function EncryptionService(config, timeSyncService) {
1123
- Object.defineProperty(this, "config", {
1124
- enumerable: true,
1125
- configurable: true,
1126
- writable: true,
1127
- value: void 0
1128
- });
1129
- Object.defineProperty(this, "timeSyncService", {
1130
- enumerable: true,
1131
- configurable: true,
1132
- writable: true,
1133
- value: void 0
1134
- });
1135
- this.config = __assign$4({}, config);
665
+ class EncryptionService {
666
+ constructor(config, timeSyncService) {
667
+ this.config = { ...config };
1136
668
  this.timeSyncService = timeSyncService;
1137
669
  }
1138
670
  /**
1139
671
  * 加密 Token
1140
672
  * 格式: AES(token + "|+|" + timestamp)
1141
673
  */
1142
- Object.defineProperty(EncryptionService.prototype, "encryptToken", {
1143
- enumerable: false,
1144
- configurable: true,
1145
- writable: true,
1146
- value: function (token, timestamp) {
1147
- if (!token) {
1148
- return '';
1149
- }
1150
- var time = timestamp !== null && timestamp !== void 0 ? timestamp : this.getAdjustedTime();
1151
- var data = "".concat(token, "|+|").concat(time);
1152
- var encrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(this.config.key), {
1153
- iv: CryptoJS.enc.Utf8.parse(this.config.iv),
1154
- mode: CryptoJS.mode.CBC,
1155
- }).toString();
1156
- return encrypted;
674
+ encryptToken(token, timestamp) {
675
+ if (!token) {
676
+ return '';
1157
677
  }
1158
- });
678
+ const time = timestamp ?? this.getAdjustedTime();
679
+ const data = `${token}|+|${time}`;
680
+ const encrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(this.config.key), {
681
+ iv: CryptoJS.enc.Utf8.parse(this.config.iv),
682
+ mode: CryptoJS.mode.CBC,
683
+ }).toString();
684
+ return encrypted;
685
+ }
1159
686
  /**
1160
687
  * 解密 Token
1161
688
  */
1162
- Object.defineProperty(EncryptionService.prototype, "decryptToken", {
1163
- enumerable: false,
1164
- configurable: true,
1165
- writable: true,
1166
- value: function (encryptedToken) {
1167
- var decrypted = CryptoJS.AES.decrypt(encryptedToken, CryptoJS.enc.Utf8.parse(this.config.key), {
1168
- iv: CryptoJS.enc.Utf8.parse(this.config.iv),
1169
- mode: CryptoJS.mode.CBC,
1170
- }).toString(CryptoJS.enc.Utf8);
1171
- var parts = decrypted.split('|+|');
1172
- return {
1173
- token: parts[0],
1174
- timestamp: parseInt(parts[1], 10),
1175
- };
1176
- }
1177
- });
689
+ decryptToken(encryptedToken) {
690
+ const decrypted = CryptoJS.AES.decrypt(encryptedToken, CryptoJS.enc.Utf8.parse(this.config.key), {
691
+ iv: CryptoJS.enc.Utf8.parse(this.config.iv),
692
+ mode: CryptoJS.mode.CBC,
693
+ }).toString(CryptoJS.enc.Utf8);
694
+ const parts = decrypted.split('|+|');
695
+ return {
696
+ token: parts[0],
697
+ timestamp: parseInt(parts[1], 10),
698
+ };
699
+ }
1178
700
  /**
1179
701
  * 更新加密配置
1180
702
  */
1181
- Object.defineProperty(EncryptionService.prototype, "updateConfig", {
1182
- enumerable: false,
1183
- configurable: true,
1184
- writable: true,
1185
- value: function (config) {
1186
- this.config = __assign$4(__assign$4({}, this.config), config);
1187
- }
1188
- });
703
+ updateConfig(config) {
704
+ this.config = { ...this.config, ...config };
705
+ }
1189
706
  /**
1190
707
  * 获取调整后的时间戳(考虑服务器时间差)
1191
708
  * 优先使用注入的 TimeSyncService
1192
709
  */
1193
- Object.defineProperty(EncryptionService.prototype, "getAdjustedTime", {
1194
- enumerable: false,
1195
- configurable: true,
1196
- writable: true,
1197
- value: function () {
1198
- var currentTime = Date.now();
1199
- // 优先使用注入的 TimeSyncService
1200
- if (this.timeSyncService) {
1201
- var timeDiff = this.timeSyncService.getTimeDiff();
1202
- return timeDiff !== null ? currentTime + timeDiff : currentTime;
1203
- }
1204
- // 降级方案:直接读取 localStorage(向后兼容)
1205
- // 需要环境检查,防止 Node.js 环境崩溃
1206
- if (isBrowser()) {
1207
- var timeDiff = localStorage.getItem(STORAGE_KEYS.TIME_DIFF);
1208
- return timeDiff ? currentTime + Number(timeDiff) : currentTime;
1209
- }
1210
- return currentTime;
710
+ getAdjustedTime() {
711
+ const currentTime = Date.now();
712
+ // 优先使用注入的 TimeSyncService
713
+ if (this.timeSyncService) {
714
+ const timeDiff = this.timeSyncService.getTimeDiff();
715
+ return timeDiff !== null ? currentTime + timeDiff : currentTime;
1211
716
  }
1212
- });
1213
- return EncryptionService;
1214
- }());
717
+ // 降级方案:直接读取 localStorage(向后兼容)
718
+ // 需要环境检查,防止 Node.js 环境崩溃
719
+ if (isBrowser()) {
720
+ const timeDiff = localStorage.getItem(STORAGE_KEYS.TIME_DIFF);
721
+ return timeDiff ? currentTime + Number(timeDiff) : currentTime;
722
+ }
723
+ return currentTime;
724
+ }
725
+ }
1215
726
 
1216
727
  /**
1217
728
  * 时间同步服务
1218
729
  * 负责同步客户端和服务器时间
1219
730
  */
1220
- var TimeSyncService = /** @class */ (function () {
1221
- function TimeSyncService(config, mode) {
1222
- if (mode === void 0) { mode = 'development'; }
1223
- Object.defineProperty(this, "config", {
1224
- enumerable: true,
1225
- configurable: true,
1226
- writable: true,
1227
- value: void 0
1228
- });
1229
- Object.defineProperty(this, "mode", {
1230
- enumerable: true,
1231
- configurable: true,
1232
- writable: true,
1233
- value: void 0
1234
- });
1235
- Object.defineProperty(this, "synced", {
1236
- enumerable: true,
1237
- configurable: true,
1238
- writable: true,
1239
- value: false
1240
- });
731
+ class TimeSyncService {
732
+ constructor(config, mode = 'development') {
733
+ this.synced = false;
1241
734
  this.config = config;
1242
735
  this.mode = mode;
1243
736
  }
1244
737
  /**
1245
738
  * 确保时间已同步
1246
739
  */
1247
- Object.defineProperty(TimeSyncService.prototype, "ensureSync", {
1248
- enumerable: false,
1249
- configurable: true,
1250
- writable: true,
1251
- value: function () {
1252
- return __awaiter$3(this, void 0, void 0, function () {
1253
- var serverTime;
1254
- return __generator$3(this, function (_a) {
1255
- switch (_a.label) {
1256
- case 0:
1257
- if (!this.config.enabled) {
1258
- return [2 /*return*/];
1259
- }
1260
- if (this.synced) {
1261
- return [2 /*return*/];
1262
- }
1263
- if (!isBrowser()) {
1264
- return [2 /*return*/];
1265
- }
1266
- serverTime = localStorage.getItem(STORAGE_KEYS.SERVER_TIME);
1267
- if (serverTime && serverTime !== 'undefined') {
1268
- this.synced = true;
1269
- return [2 /*return*/];
1270
- }
1271
- return [4 /*yield*/, this.sync()];
1272
- case 1:
1273
- _a.sent();
1274
- return [2 /*return*/];
1275
- }
1276
- });
1277
- });
740
+ async ensureSync() {
741
+ if (!this.config.enabled) {
742
+ return;
1278
743
  }
1279
- });
744
+ if (this.synced) {
745
+ return;
746
+ }
747
+ if (!isBrowser()) {
748
+ return;
749
+ }
750
+ const serverTime = localStorage.getItem(STORAGE_KEYS.SERVER_TIME);
751
+ if (serverTime && serverTime !== 'undefined') {
752
+ this.synced = true;
753
+ return;
754
+ }
755
+ await this.sync();
756
+ }
1280
757
  /**
1281
758
  * 执行时间同步
1282
759
  */
1283
- Object.defineProperty(TimeSyncService.prototype, "sync", {
1284
- enumerable: false,
1285
- configurable: true,
1286
- writable: true,
1287
- value: function () {
1288
- return __awaiter$3(this, void 0, void 0, function () {
1289
- var url, response, res, serverTime, currentTime, timeDiff, error_1;
1290
- return __generator$3(this, function (_a) {
1291
- switch (_a.label) {
1292
- case 0:
1293
- if (!isBrowser()) {
1294
- return [2 /*return*/];
1295
- }
1296
- _a.label = 1;
1297
- case 1:
1298
- _a.trys.push([1, 4, , 5]);
1299
- url = this.getSyncUrl();
1300
- if (!url) {
1301
- console.warn('[TimeSyncService] Sync URL not configured');
1302
- return [2 /*return*/];
1303
- }
1304
- return [4 /*yield*/, fetch(url, { method: 'POST' })];
1305
- case 2:
1306
- response = _a.sent();
1307
- // 检查响应状态
1308
- if (!response.ok) {
1309
- console.error('[TimeSyncService] Sync failed with status:', response.status);
1310
- this.clear();
1311
- return [2 /*return*/];
1312
- }
1313
- return [4 /*yield*/, response.json()];
1314
- case 3:
1315
- res = _a.sent();
1316
- serverTime = res.data;
1317
- if (!serverTime) {
1318
- this.clear();
1319
- return [2 /*return*/];
1320
- }
1321
- currentTime = Date.now();
1322
- timeDiff = serverTime - currentTime;
1323
- localStorage.setItem(STORAGE_KEYS.SERVER_TIME, String(serverTime));
1324
- localStorage.setItem(STORAGE_KEYS.TIME_DIFF, String(timeDiff));
1325
- this.synced = true;
1326
- return [3 /*break*/, 5];
1327
- case 4:
1328
- error_1 = _a.sent();
1329
- console.error('[TimeSyncService] Failed to sync time:', error_1);
1330
- this.clear();
1331
- return [3 /*break*/, 5];
1332
- case 5: return [2 /*return*/];
1333
- }
1334
- });
1335
- });
760
+ async sync() {
761
+ if (!isBrowser()) {
762
+ return;
1336
763
  }
1337
- });
764
+ try {
765
+ const url = this.getSyncUrl();
766
+ if (!url) {
767
+ console.warn('[TimeSyncService] Sync URL not configured');
768
+ return;
769
+ }
770
+ const response = await fetch(url, { method: 'POST' });
771
+ // 检查响应状态
772
+ if (!response.ok) {
773
+ console.error('[TimeSyncService] Sync failed with status:', response.status);
774
+ this.clear();
775
+ return;
776
+ }
777
+ const res = await response.json();
778
+ const serverTime = res.data;
779
+ if (!serverTime) {
780
+ this.clear();
781
+ return;
782
+ }
783
+ // const currentTime = Date.now();
784
+ // const timeDiff = serverTime - currentTime;
785
+ localStorage.setItem(STORAGE_KEYS.SERVER_TIME, String(serverTime));
786
+ // localStorage.setItem(STORAGE_KEYS.TIME_DIFF, String(timeDiff));
787
+ this.synced = true;
788
+ }
789
+ catch (error) {
790
+ console.error('[TimeSyncService] Failed to sync time:', error);
791
+ this.clear();
792
+ }
793
+ }
1338
794
  /**
1339
795
  * 获取服务器时间
1340
796
  */
1341
- Object.defineProperty(TimeSyncService.prototype, "getServerTime", {
1342
- enumerable: false,
1343
- configurable: true,
1344
- writable: true,
1345
- value: function () {
1346
- if (!isBrowser()) {
1347
- return null;
1348
- }
1349
- var serverTime = localStorage.getItem(STORAGE_KEYS.SERVER_TIME);
1350
- return serverTime ? Number(serverTime) : null;
797
+ getServerTime() {
798
+ if (!isBrowser()) {
799
+ return null;
1351
800
  }
1352
- });
801
+ const serverTime = localStorage.getItem(STORAGE_KEYS.SERVER_TIME);
802
+ return serverTime ? Number(serverTime) : null;
803
+ }
1353
804
  /**
1354
805
  * 获取时间差
1355
806
  */
1356
- Object.defineProperty(TimeSyncService.prototype, "getTimeDiff", {
1357
- enumerable: false,
1358
- configurable: true,
1359
- writable: true,
1360
- value: function () {
1361
- if (!isBrowser()) {
1362
- return null;
1363
- }
1364
- var timeDiff = localStorage.getItem(STORAGE_KEYS.TIME_DIFF);
1365
- return timeDiff ? Number(timeDiff) : null;
807
+ getTimeDiff() {
808
+ if (!isBrowser()) {
809
+ return null;
1366
810
  }
1367
- });
811
+ const serverTime = this.getServerTime();
812
+ return serverTime ? serverTime - Date.now() : null;
813
+ }
1368
814
  /**
1369
815
  * 获取时间同步请求头
1370
816
  */
1371
- Object.defineProperty(TimeSyncService.prototype, "getTimeSyncHeaders", {
1372
- enumerable: false,
1373
- configurable: true,
1374
- writable: true,
1375
- value: function () {
1376
- var headers = {};
1377
- var serverTime = this.getServerTime();
1378
- var timeDiff = this.getTimeDiff();
1379
- if (serverTime) {
1380
- headers['x-belink-serverTime'] = String(serverTime);
1381
- }
1382
- if (timeDiff !== null) {
1383
- headers['x-belink-timeDiff'] = String(timeDiff);
1384
- }
1385
- return headers;
817
+ getTimeSyncHeaders() {
818
+ const headers = {};
819
+ const serverTime = this.getServerTime();
820
+ const timeDiff = this.getTimeDiff();
821
+ if (serverTime) {
822
+ headers['x-belink-serverTime'] = String(serverTime);
1386
823
  }
1387
- });
824
+ if (timeDiff !== null) {
825
+ headers['x-belink-timeDiff'] = String(timeDiff);
826
+ }
827
+ return headers;
828
+ }
1388
829
  /**
1389
830
  * 清理时间同步数据
1390
831
  */
1391
- Object.defineProperty(TimeSyncService.prototype, "clear", {
1392
- enumerable: false,
1393
- configurable: true,
1394
- writable: true,
1395
- value: function () {
1396
- if (isBrowser()) {
1397
- localStorage.removeItem(STORAGE_KEYS.SERVER_TIME);
1398
- localStorage.removeItem(STORAGE_KEYS.TIME_DIFF);
1399
- }
1400
- this.synced = false;
832
+ clear() {
833
+ if (isBrowser()) {
834
+ localStorage.removeItem(STORAGE_KEYS.SERVER_TIME);
835
+ localStorage.removeItem(STORAGE_KEYS.TIME_DIFF);
1401
836
  }
1402
- });
837
+ this.synced = false;
838
+ }
1403
839
  /**
1404
840
  * 更新模式
1405
841
  */
1406
- Object.defineProperty(TimeSyncService.prototype, "setMode", {
1407
- enumerable: false,
1408
- configurable: true,
1409
- writable: true,
1410
- value: function (mode) {
1411
- this.mode = mode;
1412
- }
1413
- });
842
+ setMode(mode) {
843
+ this.mode = mode;
844
+ }
1414
845
  /**
1415
846
  * 获取同步 URL
1416
847
  */
1417
- Object.defineProperty(TimeSyncService.prototype, "getSyncUrl", {
1418
- enumerable: false,
1419
- configurable: true,
1420
- writable: true,
1421
- value: function () {
1422
- if (this.mode === 'production') {
1423
- return this.config.productionUrl || '';
1424
- }
1425
- return this.config.developmentUrl || '';
848
+ getSyncUrl() {
849
+ if (this.mode === 'production') {
850
+ return this.config.productionUrl || '';
1426
851
  }
1427
- });
1428
- return TimeSyncService;
1429
- }());
852
+ return this.config.developmentUrl || '';
853
+ }
854
+ }
1430
855
 
1431
856
  /**
1432
857
  * Token 拦截器
1433
858
  * 负责将 Token 加密后注入请求头
1434
859
  */
1435
- var TokenInterceptor = /** @class */ (function () {
1436
- function TokenInterceptor(tokenProvider, encryptionService, options) {
1437
- Object.defineProperty(this, "name", {
1438
- enumerable: true,
1439
- configurable: true,
1440
- writable: true,
1441
- value: 'TokenInterceptor'
1442
- });
1443
- Object.defineProperty(this, "priority", {
1444
- enumerable: true,
1445
- configurable: true,
1446
- writable: true,
1447
- value: void 0
1448
- });
1449
- Object.defineProperty(this, "tokenProvider", {
1450
- enumerable: true,
1451
- configurable: true,
1452
- writable: true,
1453
- value: void 0
1454
- });
1455
- Object.defineProperty(this, "encryptionService", {
1456
- enumerable: true,
1457
- configurable: true,
1458
- writable: true,
1459
- value: void 0
1460
- });
1461
- Object.defineProperty(this, "headerName", {
1462
- enumerable: true,
1463
- configurable: true,
1464
- writable: true,
1465
- value: void 0
1466
- });
860
+ class TokenInterceptor {
861
+ constructor(tokenProvider, encryptionService, options) {
862
+ this.name = 'TokenInterceptor';
1467
863
  this.tokenProvider = tokenProvider;
1468
864
  this.encryptionService = encryptionService;
1469
- this.priority = (options === null || options === void 0 ? void 0 : options.priority) || 0;
1470
- this.headerName = (options === null || options === void 0 ? void 0 : options.headerName) || TOKEN_HEADER;
865
+ this.priority = options?.priority || 0;
866
+ this.headerName = options?.headerName || TOKEN_HEADER;
867
+ this.userId = options?.userId || '';
1471
868
  }
1472
- Object.defineProperty(TokenInterceptor.prototype, "onRequest", {
1473
- enumerable: false,
1474
- configurable: true,
1475
- writable: true,
1476
- value: function (context) {
1477
- return __awaiter$3(this, void 0, void 0, function () {
1478
- var token, encryptedToken;
1479
- return __generator$3(this, function (_a) {
1480
- token = this.tokenProvider();
1481
- if (token) {
1482
- encryptedToken = this.encryptionService.encryptToken(token);
1483
- if (!context.config.headers) {
1484
- context.config.headers = {};
1485
- }
1486
- context.config.headers[this.headerName] = encryptedToken;
1487
- }
1488
- return [2 /*return*/, context];
1489
- });
1490
- });
1491
- }
1492
- });
1493
- Object.defineProperty(TokenInterceptor.prototype, "onRequestError", {
1494
- enumerable: false,
1495
- configurable: true,
1496
- writable: true,
1497
- value: function (error) {
1498
- return __awaiter$3(this, void 0, void 0, function () {
1499
- return __generator$3(this, function (_a) {
1500
- throw error;
1501
- });
1502
- });
869
+ async onRequest(context) {
870
+ const token = this.tokenProvider();
871
+ if (token) {
872
+ const encryptedToken = this.encryptionService.encryptToken(token);
873
+ if (!context.config.headers) {
874
+ context.config.headers = {};
875
+ }
876
+ context.config.headers[this.headerName] = encryptedToken;
877
+ context.config.headers[USERID_HEADER] = this.userId || '';
1503
878
  }
1504
- });
1505
- return TokenInterceptor;
1506
- }());
1507
-
1508
- /**
1509
- * 时间同步拦截器
1510
- * 负责同步服务器时间并注入请求头
1511
- */
1512
- var TimeInterceptor = /** @class */ (function () {
1513
- function TimeInterceptor(timeSyncService, options) {
1514
- Object.defineProperty(this, "name", {
1515
- enumerable: true,
1516
- configurable: true,
1517
- writable: true,
1518
- value: 'TimeInterceptor'
1519
- });
1520
- Object.defineProperty(this, "priority", {
1521
- enumerable: true,
1522
- configurable: true,
1523
- writable: true,
1524
- value: void 0
1525
- });
1526
- Object.defineProperty(this, "timeSyncService", {
1527
- enumerable: true,
1528
- configurable: true,
1529
- writable: true,
1530
- value: void 0
1531
- });
1532
- this.timeSyncService = timeSyncService;
1533
- this.priority = (options === null || options === void 0 ? void 0 : options.priority) || 0;
879
+ return context;
1534
880
  }
1535
- Object.defineProperty(TimeInterceptor.prototype, "onRequest", {
1536
- enumerable: false,
1537
- configurable: true,
1538
- writable: true,
1539
- value: function (context) {
1540
- return __awaiter$3(this, void 0, void 0, function () {
1541
- var timeSyncHeaders;
1542
- return __generator$3(this, function (_a) {
1543
- switch (_a.label) {
1544
- case 0:
1545
- // 确保时间已同步
1546
- return [4 /*yield*/, this.timeSyncService.ensureSync()];
1547
- case 1:
1548
- // 确保时间已同步
1549
- _a.sent();
1550
- timeSyncHeaders = this.timeSyncService.getTimeSyncHeaders();
1551
- if (!context.config.headers) {
1552
- context.config.headers = {};
1553
- }
1554
- Object.assign(context.config.headers, timeSyncHeaders);
1555
- return [2 /*return*/, context];
1556
- }
1557
- });
1558
- });
1559
- }
1560
- });
1561
- Object.defineProperty(TimeInterceptor.prototype, "onRequestError", {
1562
- enumerable: false,
1563
- configurable: true,
1564
- writable: true,
1565
- value: function (error) {
1566
- return __awaiter$3(this, void 0, void 0, function () {
1567
- return __generator$3(this, function (_a) {
1568
- throw error;
1569
- });
1570
- });
881
+ async onRequestError(error) {
882
+ throw error;
883
+ }
884
+ }
885
+
886
+ /**
887
+ * 时间同步拦截器
888
+ * 负责同步服务器时间并注入请求头
889
+ */
890
+ class TimeInterceptor {
891
+ constructor(timeSyncService, options) {
892
+ this.name = 'TimeInterceptor';
893
+ this.timeSyncService = timeSyncService;
894
+ this.priority = options?.priority || 0;
895
+ }
896
+ async onRequest(context) {
897
+ // 确保时间已同步
898
+ await this.timeSyncService.ensureSync();
899
+ // 获取时间同步头
900
+ const timeSyncHeaders = this.timeSyncService.getTimeSyncHeaders();
901
+ if (!context.config.headers) {
902
+ context.config.headers = {};
1571
903
  }
1572
- });
1573
- return TimeInterceptor;
1574
- }());
904
+ Object.assign(context.config.headers, timeSyncHeaders);
905
+ return context;
906
+ }
907
+ async onRequestError(error) {
908
+ throw error;
909
+ }
910
+ }
1575
911
 
1576
912
  /**
1577
913
  * 认证拦截器
1578
914
  * 负责处理 401 未授权响应
1579
915
  */
1580
- var AuthInterceptor = /** @class */ (function () {
1581
- function AuthInterceptor(configManager, timeSyncService, options) {
1582
- Object.defineProperty(this, "name", {
1583
- enumerable: true,
1584
- configurable: true,
1585
- writable: true,
1586
- value: 'AuthInterceptor'
1587
- });
1588
- Object.defineProperty(this, "priority", {
1589
- enumerable: true,
1590
- configurable: true,
1591
- writable: true,
1592
- value: void 0
1593
- });
1594
- Object.defineProperty(this, "configManager", {
1595
- enumerable: true,
1596
- configurable: true,
1597
- writable: true,
1598
- value: void 0
1599
- });
1600
- Object.defineProperty(this, "timeSyncService", {
1601
- enumerable: true,
1602
- configurable: true,
1603
- writable: true,
1604
- value: void 0
1605
- });
916
+ class AuthInterceptor {
917
+ constructor(configManager, timeSyncService, options) {
918
+ this.name = 'AuthInterceptor';
1606
919
  this.configManager = configManager;
1607
920
  this.timeSyncService = timeSyncService;
1608
- this.priority = (options === null || options === void 0 ? void 0 : options.priority) || 0;
921
+ this.priority = options?.priority || 0;
1609
922
  }
1610
- Object.defineProperty(AuthInterceptor.prototype, "onResponse", {
1611
- enumerable: false,
1612
- configurable: true,
1613
- writable: true,
1614
- value: function (context) {
1615
- return __awaiter$3(this, void 0, void 0, function () {
1616
- return __generator$3(this, function (_a) {
1617
- return [2 /*return*/, context];
1618
- });
1619
- });
1620
- }
1621
- });
1622
- Object.defineProperty(AuthInterceptor.prototype, "onResponseError", {
1623
- enumerable: false,
1624
- configurable: true,
1625
- writable: true,
1626
- value: function (error) {
1627
- return __awaiter$3(this, void 0, void 0, function () {
1628
- var status, loginPath;
1629
- return __generator$3(this, function (_a) {
1630
- status = error.status;
1631
- if (status === 401) {
1632
- // 清理时间同步数据
1633
- this.timeSyncService.clear();
1634
- loginPath = this.configManager.get('loginPath');
1635
- if (typeof loginPath === 'string') {
1636
- if (typeof window !== 'undefined') {
1637
- window.location.replace(loginPath);
1638
- }
1639
- }
1640
- else if (typeof loginPath === 'function') {
1641
- loginPath();
1642
- }
1643
- throw new AuthError('Unauthorized', error instanceof Error ? error : undefined);
1644
- }
1645
- throw error;
1646
- });
1647
- });
923
+ async onResponse(context) {
924
+ return context;
925
+ }
926
+ async onResponseError(error) {
927
+ const status = error.status;
928
+ if (status === 401) {
929
+ // 清理时间同步数据
930
+ this.timeSyncService.clear();
931
+ const loginPath = this.configManager.get('loginPath');
932
+ if (typeof loginPath === 'string') {
933
+ if (typeof window !== 'undefined') {
934
+ window.location.replace(loginPath);
935
+ }
936
+ }
937
+ else if (typeof loginPath === 'function') {
938
+ loginPath();
939
+ }
940
+ throw new AuthError('Unauthorized', error instanceof Error ? error : undefined);
1648
941
  }
1649
- });
1650
- return AuthInterceptor;
1651
- }());
942
+ throw error;
943
+ }
944
+ }
1652
945
 
1653
946
  /**
1654
947
  * BeLink 业务请求客户端
1655
948
  * 提供完整的认证、加密、时间同步等企业级功能
1656
949
  */
1657
- var BeLinkClient = /** @class */ (function (_super) {
1658
- __extends$1(BeLinkClient, _super);
1659
- function BeLinkClient() {
1660
- var _this = _super.call(this) || this;
1661
- Object.defineProperty(_this, "configManager", {
1662
- enumerable: true,
1663
- configurable: true,
1664
- writable: true,
1665
- value: void 0
1666
- });
1667
- Object.defineProperty(_this, "encryptionService", {
1668
- enumerable: true,
1669
- configurable: true,
1670
- writable: true,
1671
- value: void 0
1672
- });
1673
- Object.defineProperty(_this, "timeSyncService", {
1674
- enumerable: true,
1675
- configurable: true,
1676
- writable: true,
1677
- value: void 0
1678
- });
1679
- Object.defineProperty(_this, "token", {
1680
- enumerable: true,
1681
- configurable: true,
1682
- writable: true,
1683
- value: null
1684
- });
1685
- Object.defineProperty(_this, "initialized", {
1686
- enumerable: true,
1687
- configurable: true,
1688
- writable: true,
1689
- value: false
1690
- });
1691
- Object.defineProperty(_this, "tokenListenerCleanup", {
1692
- enumerable: true,
1693
- configurable: true,
1694
- writable: true,
1695
- value: null
1696
- });
1697
- Object.defineProperty(_this, "tokenHeaderName", {
1698
- enumerable: true,
1699
- configurable: true,
1700
- writable: true,
1701
- value: TOKEN_HEADER
1702
- });
1703
- Object.defineProperty(_this, "tokenStorageKey", {
1704
- enumerable: true,
1705
- configurable: true,
1706
- writable: true,
1707
- value: STORAGE_KEYS.TOKEN
1708
- });
1709
- _this.configManager = ConfigManager.getInstance();
950
+ class BeLinkClient extends HttpClient {
951
+ constructor() {
952
+ super();
953
+ this.token = null;
954
+ this.initialized = false;
955
+ this.tokenListenerCleanup = null;
956
+ this.tokenHeaderName = TOKEN_HEADER;
957
+ this.tokenStorageKey = STORAGE_KEYS.TOKEN;
958
+ this.configManager = ConfigManager.getInstance();
1710
959
  // 先初始化 timeSyncService
1711
- _this.timeSyncService = new TimeSyncService(_this.configManager.get('timeSync') || { enabled: true }, _this.configManager.get('mode'));
960
+ this.timeSyncService = new TimeSyncService(this.configManager.get('timeSync') || { enabled: true }, this.configManager.get('mode'));
1712
961
  // 再初始化 encryptionService,注入 timeSyncService
1713
- _this.encryptionService = new EncryptionService(_this.configManager.get('encryption') || { key: '214c!dsf1214c!ds', iv: 'icalqai23cfhgj!s' }, _this.timeSyncService);
1714
- return _this;
962
+ this.encryptionService = new EncryptionService(this.configManager.get('encryption') || { key: '214c!dsf1214c!ds', iv: 'icalqai23cfhgj!s' }, this.timeSyncService);
1715
963
  }
1716
964
  /**
1717
965
  * 初始化客户端
1718
966
  */
1719
- Object.defineProperty(BeLinkClient.prototype, "init", {
1720
- enumerable: false,
1721
- configurable: true,
1722
- writable: true,
1723
- value: function (config) {
1724
- this.configManager.init({
1725
- mode: config.mode,
1726
- loginPath: config.loginPath,
1727
- baseUrl: config.baseUrl,
1728
- tokenHeaderName: config.tokenHeaderName,
1729
- tokenStorageKey: config.tokenStorageKey,
1730
- });
1731
- // 更新时间同步服务的模式
1732
- this.timeSyncService.setMode(config.mode);
1733
- // 设置 baseUrl
1734
- if (config.baseUrl) {
1735
- this.adapter.setBaseUrl(config.baseUrl);
1736
- }
1737
- // 设置 tokenHeaderName(请求头名称)
1738
- if (config.tokenHeaderName) {
1739
- this.tokenHeaderName = config.tokenHeaderName;
1740
- }
1741
- // 设置 tokenStorageKey(localStorage 存储键名)
1742
- if (config.tokenStorageKey) {
1743
- this.tokenStorageKey = config.tokenStorageKey;
1744
- }
1745
- // 设置默认拦截器
1746
- if (!this.initialized) {
1747
- this.setupDefaultInterceptors();
1748
- this.initialized = true;
1749
- }
967
+ init(config) {
968
+ this.configManager.init({
969
+ mode: config.mode,
970
+ loginPath: config.loginPath,
971
+ baseUrl: config.baseUrl,
972
+ tokenHeaderName: config.tokenHeaderName,
973
+ tokenStorageKey: config.tokenStorageKey,
974
+ });
975
+ // 更新时间同步服务的模式
976
+ this.timeSyncService.setMode(config.mode);
977
+ // 设置 baseUrl
978
+ if (config.baseUrl) {
979
+ this.adapter.setBaseUrl(config.baseUrl);
1750
980
  }
1751
- });
981
+ // 设置 tokenHeaderName(请求头名称)
982
+ if (config.tokenHeaderName) {
983
+ this.tokenHeaderName = config.tokenHeaderName;
984
+ }
985
+ // 设置 tokenStorageKey(localStorage 存储键名)
986
+ if (config.tokenStorageKey) {
987
+ this.tokenStorageKey = config.tokenStorageKey;
988
+ }
989
+ // 设置默认拦截器
990
+ if (!this.initialized) {
991
+ this.setupDefaultInterceptors();
992
+ this.initialized = true;
993
+ }
994
+ }
1752
995
  /**
1753
996
  * 设置 Token
1754
997
  */
1755
- Object.defineProperty(BeLinkClient.prototype, "setToken", {
1756
- enumerable: false,
1757
- configurable: true,
1758
- writable: true,
1759
- value: function (token) {
1760
- this.token = token;
1761
- }
1762
- });
998
+ setToken(token) {
999
+ this.token = token;
1000
+ }
1763
1001
  /**
1764
1002
  * 获取当前 Token
1765
1003
  */
1766
- Object.defineProperty(BeLinkClient.prototype, "getToken", {
1767
- enumerable: false,
1768
- configurable: true,
1769
- writable: true,
1770
- value: function () {
1771
- return this.token;
1772
- }
1773
- });
1004
+ getToken() {
1005
+ return this.token;
1006
+ }
1774
1007
  /**
1775
1008
  * 设置 Token 监听器
1776
1009
  * @returns 清理函数,用于移除监听器
1777
1010
  */
1778
- Object.defineProperty(BeLinkClient.prototype, "setupTokenListener", {
1779
- enumerable: false,
1780
- configurable: true,
1781
- writable: true,
1782
- value: function (tokenKey) {
1783
- var _this = this;
1784
- // 清理之前的监听器
1785
- if (this.tokenListenerCleanup) {
1786
- this.tokenListenerCleanup();
1787
- this.tokenListenerCleanup = null;
1011
+ setupTokenListener(tokenKey) {
1012
+ // 清理之前的监听器
1013
+ if (this.tokenListenerCleanup) {
1014
+ this.tokenListenerCleanup();
1015
+ this.tokenListenerCleanup = null;
1016
+ }
1017
+ // 非浏览器环境返回空操作
1018
+ if (!isBrowser()) {
1019
+ return () => { };
1020
+ }
1021
+ const getToken = () => {
1022
+ if (typeof tokenKey === 'string') {
1023
+ return window.localStorage.getItem(tokenKey);
1788
1024
  }
1789
- // 非浏览器环境返回空操作
1790
- if (!isBrowser()) {
1791
- return function () { };
1025
+ else if (typeof tokenKey === 'function') {
1026
+ return tokenKey();
1792
1027
  }
1793
- var getToken = function () {
1794
- if (typeof tokenKey === 'string') {
1795
- return window.localStorage.getItem(tokenKey);
1796
- }
1797
- else if (typeof tokenKey === 'function') {
1798
- return tokenKey();
1799
- }
1800
- return null;
1801
- };
1802
- var storageHandler = function (event) {
1803
- if (typeof tokenKey === 'string' && event.key === tokenKey) {
1804
- if (event.newValue) {
1805
- _this.setToken(event.newValue);
1806
- }
1028
+ return null;
1029
+ };
1030
+ const storageHandler = (event) => {
1031
+ if (typeof tokenKey === 'string' && event.key === tokenKey) {
1032
+ if (event.newValue) {
1033
+ this.setToken(event.newValue);
1807
1034
  }
1808
- if (typeof tokenKey === 'function') {
1809
- var token_1 = tokenKey();
1810
- if (token_1) {
1811
- _this.setToken(token_1);
1812
- }
1035
+ }
1036
+ if (typeof tokenKey === 'function') {
1037
+ const token = tokenKey();
1038
+ if (token) {
1039
+ this.setToken(token);
1813
1040
  }
1814
- };
1815
- window.addEventListener('storage', storageHandler);
1816
- // 初始化时获取 token
1817
- var token = getToken();
1818
- if (token) {
1819
- this.setToken(token);
1820
1041
  }
1821
- // 创建并存储清理函数
1822
- var cleanup = function () {
1823
- window.removeEventListener('storage', storageHandler);
1824
- };
1825
- this.tokenListenerCleanup = cleanup;
1826
- return cleanup;
1042
+ };
1043
+ window.addEventListener('storage', storageHandler);
1044
+ // 初始化时获取 token
1045
+ const token = getToken();
1046
+ if (token) {
1047
+ this.setToken(token);
1827
1048
  }
1828
- });
1049
+ // 创建并存储清理函数
1050
+ const cleanup = () => {
1051
+ window.removeEventListener('storage', storageHandler);
1052
+ };
1053
+ this.tokenListenerCleanup = cleanup;
1054
+ return cleanup;
1055
+ }
1829
1056
  /**
1830
1057
  * 设置全局拦截器(向后兼容)
1831
1058
  */
1832
- Object.defineProperty(BeLinkClient.prototype, "setupInterceptors", {
1833
- enumerable: false,
1834
- configurable: true,
1835
- writable: true,
1836
- value: function () {
1837
- // 已在 init 中自动设置
1838
- }
1839
- });
1059
+ setupInterceptors() {
1060
+ // 已在 init 中自动设置
1061
+ }
1840
1062
  /**
1841
1063
  * 设置认证回调(向后兼容)
1842
1064
  */
1843
- Object.defineProperty(BeLinkClient.prototype, "setupAuthorizationCallback", {
1844
- enumerable: false,
1845
- configurable: true,
1846
- writable: true,
1847
- value: function (path) {
1848
- this.configManager.set('loginPath', path);
1849
- }
1850
- });
1065
+ setupAuthorizationCallback(path) {
1066
+ this.configManager.set('loginPath', path);
1067
+ }
1851
1068
  /**
1852
1069
  * 清除请求时间
1853
1070
  */
1854
- Object.defineProperty(BeLinkClient.prototype, "removeRequestTime", {
1855
- enumerable: false,
1856
- configurable: true,
1857
- writable: true,
1858
- value: function () {
1859
- return __awaiter$3(this, void 0, void 0, function () {
1860
- return __generator$3(this, function (_a) {
1861
- this.timeSyncService.clear();
1862
- return [2 /*return*/];
1863
- });
1864
- });
1865
- }
1866
- });
1071
+ async removeRequestTime() {
1072
+ this.timeSyncService.clear();
1073
+ }
1867
1074
  /**
1868
1075
  * @deprecated 请使用 removeRequestTime(修正拼写后的版本)
1869
1076
  * 清除请求时间(向后兼容)
1870
1077
  */
1871
- Object.defineProperty(BeLinkClient.prototype, "removeReqeustTime", {
1872
- enumerable: false,
1873
- configurable: true,
1874
- writable: true,
1875
- value: function () {
1876
- return __awaiter$3(this, void 0, void 0, function () {
1877
- return __generator$3(this, function (_a) {
1878
- return [2 /*return*/, this.removeRequestTime()];
1879
- });
1880
- });
1881
- }
1882
- });
1078
+ async removeReqeustTime() {
1079
+ return this.removeRequestTime();
1080
+ }
1883
1081
  /**
1884
1082
  * 设置请求时间
1885
1083
  */
1886
- Object.defineProperty(BeLinkClient.prototype, "setupRequestTime", {
1887
- enumerable: false,
1888
- configurable: true,
1889
- writable: true,
1890
- value: function (config) {
1891
- return __awaiter$3(this, void 0, void 0, function () {
1892
- var headers;
1893
- return __generator$3(this, function (_a) {
1894
- switch (_a.label) {
1895
- case 0: return [4 /*yield*/, this.timeSyncService.ensureSync()];
1896
- case 1:
1897
- _a.sent();
1898
- headers = this.timeSyncService.getTimeSyncHeaders();
1899
- if (!config.headers) {
1900
- config.headers = {};
1901
- }
1902
- Object.assign(config.headers, headers);
1903
- return [2 /*return*/];
1904
- }
1905
- });
1906
- });
1084
+ async setupRequestTime(config) {
1085
+ await this.timeSyncService.ensureSync();
1086
+ const headers = this.timeSyncService.getTimeSyncHeaders();
1087
+ if (!config.headers) {
1088
+ config.headers = {};
1907
1089
  }
1908
- });
1090
+ Object.assign(config.headers, headers);
1091
+ }
1909
1092
  /**
1910
1093
  * @deprecated 请使用 setupRequestTime(修正拼写后的版本)
1911
1094
  * 设置请求时间(向后兼容)
1912
1095
  */
1913
- Object.defineProperty(BeLinkClient.prototype, "setupReqeustTime", {
1914
- enumerable: false,
1915
- configurable: true,
1916
- writable: true,
1917
- value: function (config) {
1918
- return __awaiter$3(this, void 0, void 0, function () {
1919
- return __generator$3(this, function (_a) {
1920
- return [2 /*return*/, this.setupRequestTime(config)];
1921
- });
1922
- });
1923
- }
1924
- });
1096
+ async setupReqeustTime(config) {
1097
+ return this.setupRequestTime(config);
1098
+ }
1925
1099
  /**
1926
1100
  * 设置 Token(向后兼容)
1927
1101
  */
1928
- Object.defineProperty(BeLinkClient.prototype, "setupToken", {
1929
- enumerable: false,
1930
- configurable: true,
1931
- writable: true,
1932
- value: function (config) {
1933
- if (!isBrowser()) {
1934
- return;
1935
- }
1936
- var token = localStorage.getItem(this.tokenStorageKey);
1937
- if (token) {
1938
- if (!config.headers) {
1939
- config.headers = {};
1940
- }
1941
- config.headers[this.tokenHeaderName] = this.encryptionService.encryptToken(token);
1102
+ setupToken(config) {
1103
+ if (!isBrowser()) {
1104
+ return;
1105
+ }
1106
+ const token = localStorage.getItem(this.tokenStorageKey);
1107
+ if (token) {
1108
+ if (!config.headers) {
1109
+ config.headers = {};
1942
1110
  }
1111
+ config.headers[this.tokenHeaderName] = this.encryptionService.encryptToken(token);
1943
1112
  }
1944
- });
1113
+ }
1945
1114
  /**
1946
1115
  * 重写请求方法(向后兼容旧版 API)
1947
1116
  */
1948
- Object.defineProperty(BeLinkClient.prototype, "request", {
1949
- enumerable: false,
1950
- configurable: true,
1951
- writable: true,
1952
- value: function (config) {
1953
- return __awaiter$3(this, void 0, void 0, function () {
1954
- return __generator$3(this, function (_a) {
1955
- // 处理 customToken
1956
- if (config.customToken) {
1957
- this.setToken(config.customToken);
1958
- }
1959
- // 处理旧版拦截器配置(使用基类的共享方法)
1960
- if (config.requestInterceptors || config.responseInterceptors) {
1961
- return [2 /*return*/, this.requestWithLegacyInterceptors(config)];
1962
- }
1963
- return [2 /*return*/, _super.prototype.request.call(this, config)];
1964
- });
1965
- });
1117
+ async request(config) {
1118
+ // 处理 customToken
1119
+ if (config.customToken) {
1120
+ this.setToken(config.customToken);
1966
1121
  }
1967
- });
1122
+ // 处理旧版拦截器配置(使用基类的共享方法)
1123
+ if (config.requestInterceptors || config.responseInterceptors) {
1124
+ return this.requestWithLegacyInterceptors(config);
1125
+ }
1126
+ return super.request(config);
1127
+ }
1968
1128
  /**
1969
1129
  * 设置默认拦截器
1970
1130
  */
1971
- Object.defineProperty(BeLinkClient.prototype, "setupDefaultInterceptors", {
1972
- enumerable: false,
1973
- configurable: true,
1974
- writable: true,
1975
- value: function () {
1976
- var _this = this;
1977
- // 时间同步拦截器
1978
- this.addRequestInterceptor(new TimeInterceptor(this.timeSyncService, {
1979
- priority: 1,
1980
- }));
1981
- // Token 拦截器
1982
- this.addRequestInterceptor(new TokenInterceptor(function () { return _this.token || localStorage.getItem(_this.tokenStorageKey); }, this.encryptionService, {
1983
- priority: 2,
1984
- headerName: this.tokenHeaderName,
1985
- }));
1986
- // 认证拦截器(处理 401)
1987
- this.addResponseInterceptor(new AuthInterceptor(this.configManager, this.timeSyncService, {
1988
- priority: 1,
1989
- }));
1990
- }
1991
- });
1992
- return BeLinkClient;
1993
- }(HttpClient));
1131
+ setupDefaultInterceptors() {
1132
+ // 时间同步拦截器
1133
+ this.addRequestInterceptor(new TimeInterceptor(this.timeSyncService, {
1134
+ priority: 1,
1135
+ }));
1136
+ // Token 拦截器
1137
+ this.addRequestInterceptor(new TokenInterceptor(() => this.token || localStorage.getItem(this.tokenStorageKey), this.encryptionService, {
1138
+ priority: 2,
1139
+ headerName: this.tokenHeaderName,
1140
+ }));
1141
+ // 认证拦截器(处理 401)
1142
+ this.addResponseInterceptor(new AuthInterceptor(this.configManager, this.timeSyncService, {
1143
+ priority: 1,
1144
+ }));
1145
+ }
1146
+ }
1994
1147
 
1995
1148
  // 创建并导出单例实例
1996
- var beLinkRequest = new BeLinkClient();
1149
+ const beLinkRequest = new BeLinkClient();
1997
1150
 
1998
1151
  /**
1999
- * BeLink 直播请求客户端
2000
- * 简化版客户端,无认证逻辑
1152
+ * LiveClient 业务请求客户端
1153
+ * 提供完整的认证、加密、时间同步等企业级功能
2001
1154
  */
2002
- var LiveClient = /** @class */ (function (_super) {
2003
- __extends$1(LiveClient, _super);
2004
- function LiveClient() {
2005
- var _this = _super.call(this) || this;
2006
- Object.defineProperty(_this, "tokenHeaderName", {
2007
- enumerable: true,
2008
- configurable: true,
2009
- writable: true,
2010
- value: TOKEN_HEADER
2011
- });
2012
- return _this;
1155
+ class LiveClient extends HttpClient {
1156
+ constructor() {
1157
+ super();
1158
+ this.token = null;
1159
+ this.userId = null;
1160
+ this.initialized = false;
1161
+ this.tokenListenerCleanup = null;
1162
+ this.tokenHeaderName = TOKEN_HEADER;
1163
+ this.tokenStorageKey = STORAGE_KEYS.TOKEN;
1164
+ this.configManager = ConfigManager.getInstance();
1165
+ // 先初始化 timeSyncService
1166
+ this.timeSyncService = new TimeSyncService(this.configManager.get('timeSync') || { enabled: true }, this.configManager.get('mode'));
1167
+ // 再初始化 encryptionService,注入 timeSyncService
1168
+ this.encryptionService = new EncryptionService(this.configManager.get('encryption') || { key: '214c!dsf1214c!ds', iv: 'icalqai23cfhgj!s' }, this.timeSyncService);
2013
1169
  }
2014
1170
  /**
2015
1171
  * 初始化客户端
2016
1172
  */
2017
- Object.defineProperty(LiveClient.prototype, "init", {
2018
- enumerable: false,
2019
- configurable: true,
2020
- writable: true,
2021
- value: function (config) {
2022
- if (config.baseUrl) {
2023
- this.adapter.setBaseUrl(config.baseUrl);
1173
+ init(config) {
1174
+ this.configManager.init({
1175
+ mode: config.mode,
1176
+ baseUrl: config.baseUrl,
1177
+ timeSync: config.timeSyncConfig,
1178
+ encryption: config.encryption,
1179
+ tokenHeaderName: config.tokenHeaderName,
1180
+ tokenStorageKey: config.tokenStorageKey,
1181
+ });
1182
+ // 更新时间同步服务的模式
1183
+ this.timeSyncService.setMode(config.mode);
1184
+ // 设置 baseUrl
1185
+ if (config.baseUrl) {
1186
+ this.adapter.setBaseUrl(config.baseUrl);
1187
+ }
1188
+ // 设置 tokenHeaderName(请求头名称)
1189
+ if (config.tokenHeaderName) {
1190
+ this.tokenHeaderName = config.tokenHeaderName;
1191
+ }
1192
+ // 设置 tokenStorageKey(localStorage 存储键名)
1193
+ if (config.tokenStorageKey) {
1194
+ this.tokenStorageKey = config.tokenStorageKey;
1195
+ }
1196
+ // 设置默认拦截器
1197
+ if (!this.initialized) {
1198
+ this.setupDefaultInterceptors();
1199
+ this.initialized = true;
1200
+ }
1201
+ }
1202
+ setUserId(userId) {
1203
+ this.userId = userId;
1204
+ }
1205
+ /**
1206
+ * 设置 Token
1207
+ */
1208
+ setToken(token) {
1209
+ this.token = token;
1210
+ }
1211
+ /**
1212
+ * 获取当前 Token
1213
+ */
1214
+ getToken() {
1215
+ return this.token;
1216
+ }
1217
+ /**
1218
+ * 设置 Token 监听器
1219
+ * @returns 清理函数,用于移除监听器
1220
+ */
1221
+ setupTokenListener(tokenKey) {
1222
+ // 清理之前的监听器
1223
+ if (this.tokenListenerCleanup) {
1224
+ this.tokenListenerCleanup();
1225
+ this.tokenListenerCleanup = null;
1226
+ }
1227
+ // 非浏览器环境返回空操作
1228
+ if (!isBrowser()) {
1229
+ return () => { };
1230
+ }
1231
+ const getToken = () => {
1232
+ if (typeof tokenKey === 'string') {
1233
+ return window.localStorage.getItem(tokenKey);
1234
+ }
1235
+ else if (typeof tokenKey === 'function') {
1236
+ return tokenKey();
1237
+ }
1238
+ return null;
1239
+ };
1240
+ const storageHandler = (event) => {
1241
+ if (typeof tokenKey === 'string' && event.key === tokenKey) {
1242
+ if (event.newValue) {
1243
+ this.setToken(event.newValue);
1244
+ }
2024
1245
  }
2025
- if (config.tokenHeaderName) {
2026
- this.tokenHeaderName = config.tokenHeaderName;
1246
+ if (typeof tokenKey === 'function') {
1247
+ const token = tokenKey();
1248
+ if (token) {
1249
+ this.setToken(token);
1250
+ }
2027
1251
  }
1252
+ };
1253
+ window.addEventListener('storage', storageHandler);
1254
+ // 初始化时获取 token
1255
+ const token = getToken();
1256
+ if (token) {
1257
+ this.setToken(token);
2028
1258
  }
2029
- });
1259
+ // 创建并存储清理函数
1260
+ const cleanup = () => {
1261
+ window.removeEventListener('storage', storageHandler);
1262
+ };
1263
+ this.tokenListenerCleanup = cleanup;
1264
+ return cleanup;
1265
+ }
1266
+ /**
1267
+ * 清除请求时间
1268
+ */
1269
+ async removeRequestTime() {
1270
+ this.timeSyncService.clear();
1271
+ }
2030
1272
  /**
2031
- * 获取 Token 请求头名称
1273
+ * 设置请求时间
2032
1274
  */
2033
- Object.defineProperty(LiveClient.prototype, "getTokenHeaderName", {
2034
- enumerable: false,
2035
- configurable: true,
2036
- writable: true,
2037
- value: function () {
2038
- return this.tokenHeaderName;
1275
+ async setupRequestTime(config) {
1276
+ await this.timeSyncService.ensureSync();
1277
+ const headers = this.timeSyncService.getTimeSyncHeaders();
1278
+ if (!config.headers) {
1279
+ config.headers = {};
2039
1280
  }
2040
- });
1281
+ Object.assign(config.headers, headers);
1282
+ }
1283
+ /**
1284
+ * 设置默认拦截器
1285
+ */
1286
+ setupDefaultInterceptors() {
1287
+ // 时间同步拦截器
1288
+ this.addRequestInterceptor(new TimeInterceptor(this.timeSyncService, { priority: 1 }));
1289
+ // Token 拦截器
1290
+ if (this.encryptionService) {
1291
+ this.addRequestInterceptor(new TokenInterceptor(() => this.token || localStorage.getItem(this.tokenStorageKey), this.encryptionService, {
1292
+ priority: 2,
1293
+ headerName: this.tokenHeaderName,
1294
+ userId: this.userId,
1295
+ }));
1296
+ }
1297
+ // 认证拦截器(处理 401)
1298
+ this.addResponseInterceptor(new AuthInterceptor(this.configManager, this.timeSyncService, { priority: 1 }));
1299
+ }
2041
1300
  /**
2042
1301
  * 重写请求方法(向后兼容旧版 API)
2043
1302
  */
2044
- Object.defineProperty(LiveClient.prototype, "request", {
2045
- enumerable: false,
2046
- configurable: true,
2047
- writable: true,
2048
- value: function (config) {
2049
- return __awaiter$3(this, void 0, void 0, function () {
2050
- return __generator$3(this, function (_a) {
2051
- // 处理旧版拦截器配置(使用基类的共享方法)
2052
- if (config.requestInterceptors || config.responseInterceptors) {
2053
- return [2 /*return*/, this.requestWithLegacyInterceptors(config)];
2054
- }
2055
- return [2 /*return*/, _super.prototype.request.call(this, config)];
2056
- });
2057
- });
1303
+ async request(config) {
1304
+ if (config.customToken) {
1305
+ this.setToken(config.customToken);
2058
1306
  }
2059
- });
2060
- return LiveClient;
2061
- }(HttpClient));
1307
+ // 处理旧版拦截器配置(使用基类的共享方法)
1308
+ if (config.requestInterceptors || config.responseInterceptors) {
1309
+ return this.requestWithLegacyInterceptors(config);
1310
+ }
1311
+ return super.request(config);
1312
+ }
1313
+ }
2062
1314
 
2063
1315
  // 创建并导出单例实例
2064
- var beLinkLiveRequest = new LiveClient();
1316
+ const beLinkLiveRequest = new LiveClient();
2065
1317
 
2066
1318
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2067
1319
 
@@ -6141,167 +5393,111 @@ catch (e) { }
6141
5393
  * 用户信息服务
6142
5394
  * 单例模式,用于存储和获取当前用户信息
6143
5395
  */
6144
- var UserInfoService = /** @class */ (function () {
6145
- function UserInfoService() {
6146
- Object.defineProperty(this, "userInfo", {
6147
- enumerable: true,
6148
- configurable: true,
6149
- writable: true,
6150
- value: {
6151
- name: '',
6152
- }
6153
- });
5396
+ class UserInfoService {
5397
+ constructor() {
5398
+ this.userInfo = {
5399
+ name: '',
5400
+ };
6154
5401
  }
6155
5402
  /**
6156
5403
  * 初始化用户信息
6157
5404
  */
6158
- Object.defineProperty(UserInfoService.prototype, "init", {
6159
- enumerable: false,
6160
- configurable: true,
6161
- writable: true,
6162
- value: function (userInfo) {
6163
- this.userInfo = userInfo || { name: '' };
6164
- }
6165
- });
5405
+ init(userInfo) {
5406
+ this.userInfo = userInfo || { name: '' };
5407
+ }
6166
5408
  /**
6167
5409
  * 获取用户信息
6168
5410
  */
6169
- Object.defineProperty(UserInfoService.prototype, "getParams", {
6170
- enumerable: false,
6171
- configurable: true,
6172
- writable: true,
6173
- value: function () {
6174
- return this.userInfo;
6175
- }
6176
- });
5411
+ getParams() {
5412
+ return this.userInfo;
5413
+ }
6177
5414
  /**
6178
5415
  * 更新用户信息
6179
5416
  */
6180
- Object.defineProperty(UserInfoService.prototype, "update", {
6181
- enumerable: false,
6182
- configurable: true,
6183
- writable: true,
6184
- value: function (userInfo) {
6185
- this.userInfo = __assign$4(__assign$4({}, this.userInfo), userInfo);
6186
- }
6187
- });
5417
+ update(userInfo) {
5418
+ this.userInfo = { ...this.userInfo, ...userInfo };
5419
+ }
6188
5420
  /**
6189
5421
  * 清除用户信息
6190
5422
  */
6191
- Object.defineProperty(UserInfoService.prototype, "clear", {
6192
- enumerable: false,
6193
- configurable: true,
6194
- writable: true,
6195
- value: function () {
6196
- this.userInfo = { name: '' };
6197
- }
6198
- });
6199
- return UserInfoService;
6200
- }());
5423
+ clear() {
5424
+ this.userInfo = { name: '' };
5425
+ }
5426
+ }
6201
5427
  // 导出单例实例
6202
- var beLinkUserInfo = new UserInfoService();
5428
+ const beLinkUserInfo = new UserInfoService();
6203
5429
 
6204
5430
  /**
6205
5431
  * 云函数客户端
6206
5432
  * 封装腾讯云 CloudBase SDK
6207
5433
  */
6208
- var CloudFunctionClient = /** @class */ (function () {
6209
- function CloudFunctionClient() {
6210
- Object.defineProperty(this, "app", {
6211
- enumerable: true,
6212
- configurable: true,
6213
- writable: true,
6214
- value: null
6215
- });
5434
+ class CloudFunctionClient {
5435
+ constructor() {
5436
+ this.app = null;
6216
5437
  }
6217
5438
  /**
6218
5439
  * 初始化 CloudBase App
6219
5440
  */
6220
- Object.defineProperty(CloudFunctionClient.prototype, "initApp", {
6221
- enumerable: false,
6222
- configurable: true,
6223
- writable: true,
6224
- value: function () {
6225
- if (this.app) {
6226
- return this.app;
6227
- }
6228
- var configManager = ConfigManager.getInstance();
6229
- var cloudbaseConfig = configManager.get('cloudbase');
6230
- var env = detectEnvironment();
6231
- var envId = (cloudbaseConfig === null || cloudbaseConfig === void 0 ? void 0 : cloudbaseConfig[env]) || 'dev-1gpp53ju3ceb46c7';
6232
- var region = (cloudbaseConfig === null || cloudbaseConfig === void 0 ? void 0 : cloudbaseConfig.region) || 'ap-shanghai';
6233
- var timeout = (cloudbaseConfig === null || cloudbaseConfig === void 0 ? void 0 : cloudbaseConfig.timeout) || 60000;
6234
- var options = {
6235
- region: region,
6236
- env: envId,
6237
- timeout: timeout,
6238
- };
6239
- this.app = cloudbase.init(options);
5441
+ initApp() {
5442
+ if (this.app) {
6240
5443
  return this.app;
6241
5444
  }
6242
- });
5445
+ const configManager = ConfigManager.getInstance();
5446
+ const cloudbaseConfig = configManager.get('cloudbase');
5447
+ const env = detectEnvironment();
5448
+ const envId = cloudbaseConfig?.[env] || 'dev-1gpp53ju3ceb46c7';
5449
+ const region = cloudbaseConfig?.region || 'ap-shanghai';
5450
+ const timeout = cloudbaseConfig?.timeout || 60000;
5451
+ const options = {
5452
+ region,
5453
+ env: envId,
5454
+ timeout,
5455
+ };
5456
+ this.app = cloudbase.init(options);
5457
+ return this.app;
5458
+ }
6243
5459
  /**
6244
5460
  * 调用云函数
6245
5461
  */
6246
- Object.defineProperty(CloudFunctionClient.prototype, "call", {
6247
- enumerable: false,
6248
- configurable: true,
6249
- writable: true,
6250
- value: function (params) {
6251
- return __awaiter$3(this, void 0, void 0, function () {
6252
- var app, data, callParams, result;
6253
- return __generator$3(this, function (_a) {
6254
- switch (_a.label) {
6255
- case 0:
6256
- app = this.initApp();
6257
- data = __assign$4({}, params.data);
6258
- // 请求拦截:自动注入用户信息
6259
- if (!data.operateUser) {
6260
- data.operateUser = __assign$4({}, beLinkUserInfo.getParams());
6261
- }
6262
- callParams = __assign$4(__assign$4({}, params), { data: data });
6263
- return [4 /*yield*/, app.callFunction(callParams)];
6264
- case 1:
6265
- result = _a.sent();
6266
- // 响应拦截
6267
- return [2 /*return*/, new Promise(function (resolve, reject) {
6268
- var _a;
6269
- if (!((_a = result.result) === null || _a === void 0 ? void 0 : _a.success)) {
6270
- reject(result.result);
6271
- }
6272
- else {
6273
- resolve(result.result.data);
6274
- }
6275
- })];
6276
- }
6277
- });
6278
- });
5462
+ async call(params) {
5463
+ const app = this.initApp();
5464
+ // 创建数据副本,避免修改原始参数
5465
+ const data = { ...params.data };
5466
+ // 请求拦截:自动注入用户信息
5467
+ if (!data.operateUser) {
5468
+ data.operateUser = {
5469
+ ...beLinkUserInfo.getParams(),
5470
+ };
6279
5471
  }
6280
- });
5472
+ const callParams = {
5473
+ ...params,
5474
+ data,
5475
+ };
5476
+ const result = await app.callFunction(callParams);
5477
+ // 响应拦截
5478
+ return new Promise((resolve, reject) => {
5479
+ if (!result.result?.success) {
5480
+ reject(result.result);
5481
+ }
5482
+ else {
5483
+ resolve(result.result.data);
5484
+ }
5485
+ });
5486
+ }
6281
5487
  /**
6282
5488
  * 重置 App 实例
6283
5489
  */
6284
- Object.defineProperty(CloudFunctionClient.prototype, "reset", {
6285
- enumerable: false,
6286
- configurable: true,
6287
- writable: true,
6288
- value: function () {
6289
- this.app = null;
6290
- }
6291
- });
6292
- return CloudFunctionClient;
6293
- }());
5490
+ reset() {
5491
+ this.app = null;
5492
+ }
5493
+ }
6294
5494
  // 创建单例
6295
- var cloudFunctionClient = new CloudFunctionClient();
5495
+ const cloudFunctionClient = new CloudFunctionClient();
6296
5496
  /**
6297
5497
  * 云函数调用函数(保持原 API 兼容)
6298
5498
  */
6299
- function callFunction(params) {
6300
- return __awaiter$3(this, void 0, void 0, function () {
6301
- return __generator$3(this, function (_a) {
6302
- return [2 /*return*/, cloudFunctionClient.call(params)];
6303
- });
6304
- });
5499
+ async function callFunction(params) {
5500
+ return cloudFunctionClient.call(params);
6305
5501
  }
6306
5502
 
6307
5503
  export { AuthError, AuthInterceptor, AxiosAdapter, BaseError, BeLinkClient, ConfigError, ConfigManager, ContentType, DEFAULT_TIMEOUT, EncryptionService, HTTP_STATUS, HttpClient, HttpError, HttpMethod, LiveClient, NetworkError, STORAGE_KEYS, TIME_SYNC_HEADERS, TOKEN_HEADER, TimeInterceptor, TimeSyncService, TimeoutError, TokenInterceptor, beLinkLiveRequest, beLinkRequest, beLinkUserInfo, callFunction, detectEnvironment, isBrowser, isNode, request };