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