@hlw-uni-mp/request 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,717 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target2, all) => {
9
+ for (var name in all)
10
+ __defProp(target2, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ InterceptorManager: () => InterceptorManager,
34
+ UniHttpClient: () => UniHttpClient,
35
+ calculateSign: () => calculateSign,
36
+ client: () => client,
37
+ default: () => index_default,
38
+ del: () => del,
39
+ doUpload: () => doUpload,
40
+ encryptRsa: () => encryptRsa,
41
+ get: () => get,
42
+ getClient: () => getClient,
43
+ getDevice: () => getDevice,
44
+ getHttpOptions: () => getHttpOptions,
45
+ http: () => http,
46
+ post: () => post,
47
+ postUploadSign: () => postUploadSign,
48
+ put: () => put,
49
+ request: () => request,
50
+ setupHttp: () => setupHttp,
51
+ sha256: () => sha256,
52
+ sortString: () => sortString,
53
+ uploadFile: () => uploadFile,
54
+ uploadOss: () => uploadOss
55
+ });
56
+ module.exports = __toCommonJS(index_exports);
57
+
58
+ // src/device/index.ts
59
+ var deviceCache = null;
60
+ var currentNetworkType = "";
61
+ try {
62
+ if (typeof uni !== "undefined" && uni.getNetworkType) {
63
+ uni.getNetworkType({
64
+ success(res) {
65
+ currentNetworkType = res.networkType || "";
66
+ if (deviceCache) {
67
+ deviceCache.networkType = currentNetworkType;
68
+ }
69
+ }
70
+ });
71
+ if (uni.onNetworkStatusChange) {
72
+ uni.onNetworkStatusChange((res) => {
73
+ currentNetworkType = res.networkType || "";
74
+ if (deviceCache) {
75
+ deviceCache.networkType = currentNetworkType;
76
+ }
77
+ });
78
+ }
79
+ }
80
+ } catch {
81
+ }
82
+ function getDevice() {
83
+ if (deviceCache) return deviceCache;
84
+ const deviceRaw = uni.getDeviceInfo?.() || {};
85
+ const windowRaw = uni.getWindowInfo?.() || {};
86
+ const appRaw = uni.getAppBaseInfo?.() || {};
87
+ const system = deviceRaw.system || "";
88
+ deviceCache = {
89
+ appid: uni.getAccountInfoSync?.().miniProgram?.appId || "",
90
+ appName: appRaw.appName || "",
91
+ version: appRaw.appVersion || "",
92
+ versionCode: appRaw.appVersionCode || "",
93
+ channel: appRaw.appChannel || "",
94
+ deviceId: deviceRaw.deviceId || "",
95
+ deviceType: deviceRaw.deviceType || "",
96
+ deviceOrientation: windowRaw.deviceOrientation || "portrait",
97
+ brand: deviceRaw.brand || "",
98
+ model: deviceRaw.model || "",
99
+ system,
100
+ os: system.split(" ")[0] || "",
101
+ pixelRatio: windowRaw.pixelRatio || 0,
102
+ screenWidth: windowRaw.screenWidth || 0,
103
+ screenHeight: windowRaw.screenHeight || 0,
104
+ windowWidth: windowRaw.windowWidth || 0,
105
+ windowHeight: windowRaw.windowHeight || 0,
106
+ statusBarHeight: windowRaw.statusBarHeight || 0,
107
+ sdkVersion: appRaw.SDKVersion || "",
108
+ hostName: appRaw.hostName || "",
109
+ hostVersion: appRaw.hostVersion || "",
110
+ hostLanguage: appRaw.hostLanguage || "",
111
+ hostTheme: appRaw.hostTheme || "",
112
+ platform: deviceRaw.platform || "",
113
+ language: appRaw.appLanguage || "",
114
+ networkType: currentNetworkType,
115
+ benchmarkLevel: deviceRaw.benchmarkLevel || 0,
116
+ theme: appRaw.theme || "light",
117
+ fontSizeSetting: appRaw.fontSizeSetting || 16
118
+ };
119
+ return deviceCache;
120
+ }
121
+
122
+ // src/crypto/rsa.ts
123
+ function base64ToBytes(b64) {
124
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
125
+ const str = b64.replace(/[\r\n\s=]/g, "");
126
+ const bytes = [];
127
+ for (let i = 0; i < str.length; i += 4) {
128
+ const b0 = chars.indexOf(str[i]);
129
+ const b1 = chars.indexOf(str[i + 1]);
130
+ const b2 = i + 2 < str.length ? chars.indexOf(str[i + 2]) : 64;
131
+ const b3 = i + 3 < str.length ? chars.indexOf(str[i + 3]) : 64;
132
+ bytes.push(b0 << 2 | b1 >> 4);
133
+ if (b2 !== 64 && b2 !== -1) {
134
+ bytes.push((b1 & 15) << 4 | b2 >> 2);
135
+ }
136
+ if (b3 !== 64 && b3 !== -1) {
137
+ bytes.push((b2 & 3) << 6 | b3);
138
+ }
139
+ }
140
+ return new Uint8Array(bytes);
141
+ }
142
+ function bytesToBase64(bytes) {
143
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
144
+ let res = "";
145
+ for (let i = 0; i < bytes.length; i += 3) {
146
+ const b0 = bytes[i];
147
+ const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
148
+ const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
149
+ res += chars[b0 >> 2];
150
+ res += chars[(b0 & 3) << 4 | b1 >> 4];
151
+ res += i + 1 < bytes.length ? chars[(b1 & 15) << 2 | b2 >> 6] : "=";
152
+ res += i + 2 < bytes.length ? chars[b2 & 63] : "=";
153
+ }
154
+ return res;
155
+ }
156
+ function stringToUtf8(str) {
157
+ if (typeof TextEncoder !== "undefined") {
158
+ return new TextEncoder().encode(str);
159
+ }
160
+ const code = unescape(encodeURIComponent(str));
161
+ const bytes = new Uint8Array(code.length);
162
+ for (let i = 0; i < code.length; i++) {
163
+ bytes[i] = code.charCodeAt(i);
164
+ }
165
+ return bytes;
166
+ }
167
+ function modPow(base, exp, mod) {
168
+ let res = 1n;
169
+ base = base % mod;
170
+ while (exp > 0n) {
171
+ if (exp & 1n) res = res * base % mod;
172
+ base = base * base % mod;
173
+ exp >>= 1n;
174
+ }
175
+ return res;
176
+ }
177
+ function parseDerInt(bytes, offset) {
178
+ if (bytes[offset] !== 2) {
179
+ throw new Error("ASN.1 \u89E3\u6790\u9519\u8BEF: \u975E INTEGER \u6807\u8BC6");
180
+ }
181
+ let len = bytes[offset + 1];
182
+ let lenBytes = 1;
183
+ if (len & 128) {
184
+ const count = len & 127;
185
+ len = 0;
186
+ for (let i = 0; i < count; i++) {
187
+ len = len << 8 | bytes[offset + 2 + i];
188
+ }
189
+ lenBytes = 1 + count;
190
+ }
191
+ const start = offset + 1 + lenBytes;
192
+ let val = 0n;
193
+ for (let i = start; i < start + len; i++) {
194
+ val = val << 8n | BigInt(bytes[i]);
195
+ }
196
+ return { val, nextOffset: start + len };
197
+ }
198
+ function parseSpki(der) {
199
+ let bitStringStart = -1;
200
+ for (let i = 0; i < der.length - 1; i++) {
201
+ if (der[i] === 3) {
202
+ let len = der[i + 1];
203
+ let contentOffset = i + 2;
204
+ if (len & 128) {
205
+ const count = len & 127;
206
+ contentOffset = i + 2 + count;
207
+ }
208
+ if (der[contentOffset] === 0 && der[contentOffset + 1] === 48) {
209
+ bitStringStart = contentOffset + 1;
210
+ break;
211
+ }
212
+ }
213
+ }
214
+ const rsaSeqOffset = bitStringStart !== -1 ? bitStringStart : 0;
215
+ let offset = rsaSeqOffset;
216
+ if (der[offset] === 48) {
217
+ let len = der[offset + 1];
218
+ let headerLen = 2;
219
+ if (len & 128) {
220
+ headerLen = 2 + (len & 127);
221
+ }
222
+ offset += headerLen;
223
+ }
224
+ const mod = parseDerInt(der, offset);
225
+ const exp = parseDerInt(der, mod.nextOffset);
226
+ return { n: mod.val, e: exp.val };
227
+ }
228
+ function parsePublicKey(pemOrBase64) {
229
+ const clean = pemOrBase64.replace(/-----BEGIN[A-Z\s]+-----/g, "").replace(/-----END[A-Z\s]+-----/g, "").replace(/[\r\n\s]/g, "");
230
+ const der = base64ToBytes(clean);
231
+ const { n, e } = parseSpki(der);
232
+ let hex = n.toString(16);
233
+ if (hex.length % 2 !== 0) hex = "0" + hex;
234
+ const keyBytes = hex.length / 2;
235
+ return { n, e, keyBytes };
236
+ }
237
+ function getRandomNonZeroByte() {
238
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
239
+ const buf = new Uint8Array(1);
240
+ while (true) {
241
+ crypto.getRandomValues(buf);
242
+ if (buf[0] !== 0) return buf[0];
243
+ }
244
+ }
245
+ while (true) {
246
+ const val = Math.floor(Math.random() * 256);
247
+ if (val !== 0) return val;
248
+ }
249
+ }
250
+ function encryptBlock(block, key) {
251
+ const k = key.keyBytes;
252
+ const mLen = block.length;
253
+ if (mLen > k - 11) {
254
+ throw new Error(`\u660E\u6587\u5206\u5757\u5927\u5C0F (${mLen}) \u8D85\u51FA RSA-${k * 8} \u6700\u5927\u9650\u5236 (${k - 11})`);
255
+ }
256
+ const em = new Uint8Array(k);
257
+ em[0] = 0;
258
+ em[1] = 2;
259
+ const psLen = k - mLen - 3;
260
+ for (let i = 0; i < psLen; i++) {
261
+ em[2 + i] = getRandomNonZeroByte();
262
+ }
263
+ em[2 + psLen] = 0;
264
+ em.set(block, 2 + psLen + 1);
265
+ let m = 0n;
266
+ for (let i = 0; i < em.length; i++) {
267
+ m = m << 8n | BigInt(em[i]);
268
+ }
269
+ const c = modPow(m, key.e, key.n);
270
+ const cBytes = new Uint8Array(k);
271
+ let temp = c;
272
+ for (let i = k - 1; i >= 0; i--) {
273
+ cBytes[i] = Number(temp & 0xffn);
274
+ temp >>= 8n;
275
+ }
276
+ return cBytes;
277
+ }
278
+ function encryptRsa(plaintext, publicKey) {
279
+ if (!plaintext || !publicKey) return "";
280
+ const key = parsePublicKey(publicKey);
281
+ const maxBlockSize = key.keyBytes - 11;
282
+ const dataBytes = stringToUtf8(plaintext);
283
+ const totalBlocks = Math.ceil(dataBytes.length / maxBlockSize) || 1;
284
+ const result = new Uint8Array(totalBlocks * key.keyBytes);
285
+ for (let i = 0; i < totalBlocks; i++) {
286
+ const start = i * maxBlockSize;
287
+ const end = Math.min(start + maxBlockSize, dataBytes.length);
288
+ const chunk = dataBytes.slice(start, end);
289
+ const encryptedChunk = encryptBlock(chunk, key);
290
+ result.set(encryptedChunk, i * key.keyBytes);
291
+ }
292
+ return bytesToBase64(result);
293
+ }
294
+
295
+ // src/crypto/sign.ts
296
+ var import_crypto_js = __toESM(require("crypto-js"));
297
+ function sha256(rawInput) {
298
+ return import_crypto_js.default.SHA256(rawInput).toString();
299
+ }
300
+ function sortString(data) {
301
+ if (data === null || data === void 0 || data === "") return "";
302
+ if (typeof data === "boolean") return data ? "true" : "false";
303
+ if (typeof data !== "object") return String(data);
304
+ if (Array.isArray(data)) {
305
+ return "[" + data.map((item) => sortString(item)).join(",") + "]";
306
+ }
307
+ const keys = Object.keys(data).sort();
308
+ const parts = [];
309
+ for (const key of keys) {
310
+ const val = data[key];
311
+ if (val !== null && val !== void 0) {
312
+ parts.push(`${key}=${sortString(val)}`);
313
+ }
314
+ }
315
+ return parts.join("&");
316
+ }
317
+ function calculateSign(options) {
318
+ const ts = String(options.timestamp);
319
+ const nonce = options.nonce;
320
+ const context = options.context;
321
+ const secret = options.secret || "";
322
+ const dataStr = sortString(options.data);
323
+ const raw = `ts=${ts}&nonce=${nonce}&context=${context}&data=${dataStr}&key=${secret}`;
324
+ return sha256(raw);
325
+ }
326
+
327
+ // src/oss.ts
328
+ async function uploadOss(oss, source) {
329
+ const filePath = typeof source === "string" ? source : source?.path || source?.tempFilePath || "";
330
+ const name = oss.filename || filePath?.split("/").pop() || "file";
331
+ const formData = {
332
+ key: String(oss.key || ""),
333
+ success_action_status: "200"
334
+ };
335
+ if (oss.policy) formData.policy = String(oss.policy);
336
+ if (oss.OSSAccessKeyId) formData.OSSAccessKeyId = String(oss.OSSAccessKeyId);
337
+ if (oss.signature) formData.signature = String(oss.signature);
338
+ if (oss["x-oss-security-token"]) formData["x-oss-security-token"] = String(oss["x-oss-security-token"]);
339
+ const target2 = String(oss.host || "");
340
+ return new Promise((resolve, reject) => {
341
+ uni.uploadFile({
342
+ url: target2,
343
+ filePath,
344
+ name: "file",
345
+ formData,
346
+ header: {
347
+ "Content-Disposition": `inline;filename=${encodeURIComponent(name || "file")}`
348
+ },
349
+ success: (res) => {
350
+ if (res.statusCode === 200 || res.statusCode === 204) {
351
+ resolve(String(oss.url || ""));
352
+ } else {
353
+ reject(new Error(`\u4E0A\u4F20\u963F\u91CC\u4E91\u5931\u8D25 (${res.statusCode}): ${res.data || ""}`));
354
+ }
355
+ },
356
+ fail: (error) => reject(new Error(error.errMsg || "\u4E0A\u4F20\u963F\u91CC\u4E91\u5931\u8D25"))
357
+ });
358
+ });
359
+ }
360
+
361
+ // src/upload.ts
362
+ function getFileExt(filePath) {
363
+ const ext = filePath.split("?")[0].split(".").pop()?.toLowerCase() || "";
364
+ return ["jpg", "jpeg", "png", "webp", "mp4", "mp3", "gif"].includes(ext) ? ext : "jpg";
365
+ }
366
+ function buildFormData(cred) {
367
+ if (cred.type === "local") {
368
+ return { key: cred.key };
369
+ }
370
+ if (cred.type === "alioss") {
371
+ const anyCred = cred;
372
+ return {
373
+ key: cred.key,
374
+ policy: cred.policy,
375
+ OSSAccessKeyId: cred.OSSAccessKeyId || anyCred.oSSAccessKeyId || anyCred.ossAccessKeyId || "",
376
+ Signature: cred.Signature || anyCred.signature || "",
377
+ success_action_status: cred.success_action_status || anyCred.successActionStatus || "200"
378
+ };
379
+ }
380
+ return {
381
+ key: cred.key,
382
+ token: cred.token
383
+ };
384
+ }
385
+ function decodeUtf8(value) {
386
+ if (!value) return value;
387
+ try {
388
+ return decodeURIComponent(escape(value));
389
+ } catch {
390
+ return value;
391
+ }
392
+ }
393
+ function buildHeader(cred, customHeader) {
394
+ if (cred.type !== "local" && !customHeader) {
395
+ return void 0;
396
+ }
397
+ const opts = getHttpOptions();
398
+ const devInfo = opts.getDevice?.() || getDevice();
399
+ const token = opts.getToken?.() || "";
400
+ const appid = devInfo?.appid || "";
401
+ const headers = { ...customHeader };
402
+ if (cred.type === "local") {
403
+ if (appid) headers["X-Appid"] = String(appid);
404
+ if (token) headers["X-Token"] = String(token);
405
+ }
406
+ return headers;
407
+ }
408
+ function postUploadSign(data, signUrl = "/api/v1.upload/sign") {
409
+ return post(signUrl, data);
410
+ }
411
+ function doUpload(cred, filePath, customHeader) {
412
+ return new Promise((resolve, reject) => {
413
+ uni.uploadFile({
414
+ url: cred.server,
415
+ filePath,
416
+ name: "file",
417
+ formData: buildFormData(cred),
418
+ header: buildHeader(cred, customHeader),
419
+ success: (res) => {
420
+ if (res.statusCode < 200 || res.statusCode >= 300) {
421
+ reject(new Error(`\u4E0A\u4F20\u5931\u8D25 (${res.statusCode})`));
422
+ return;
423
+ }
424
+ if (cred.type !== "local") {
425
+ resolve();
426
+ return;
427
+ }
428
+ try {
429
+ const body = JSON.parse(decodeUtf8(res.data));
430
+ body.code === 1 ? resolve() : reject(new Error(body.msg || "\u4E0A\u4F20\u5931\u8D25"));
431
+ } catch {
432
+ reject(new Error("\u54CD\u5E94\u89E3\u6790\u5931\u8D25"));
433
+ }
434
+ },
435
+ fail: (error) => reject(new Error(error?.errMsg || "\u4E0A\u4F20\u5931\u8D25"))
436
+ });
437
+ });
438
+ }
439
+ async function uploadFile(params) {
440
+ const ext = params.ext || getFileExt(params.filePath);
441
+ const signUrl = params.signUrl || "/api/v1.upload/sign";
442
+ const signRes = await postUploadSign({ biz: params.biz, ext, size: params.size }, signUrl);
443
+ if (signRes.code !== 1 || !signRes.data) {
444
+ throw new Error(signRes.msg || "\u83B7\u53D6\u4E0A\u4F20\u51ED\u8BC1\u5931\u8D25");
445
+ }
446
+ const cred = signRes.data;
447
+ await doUpload(cred, params.filePath, params.header);
448
+ return cred.url;
449
+ }
450
+
451
+ // src/index.ts
452
+ var InterceptorManager = class {
453
+ constructor() {
454
+ this.handlers = [];
455
+ }
456
+ use(fulfilled, rejected) {
457
+ this.handlers.push({ fulfilled, rejected });
458
+ return this.handlers.length - 1;
459
+ }
460
+ eject(id) {
461
+ if (this.handlers[id]) {
462
+ this.handlers[id] = null;
463
+ }
464
+ }
465
+ forEach(fn) {
466
+ for (const h of this.handlers) {
467
+ if (h !== null) fn(h);
468
+ }
469
+ }
470
+ };
471
+ var UniHttpClient = class {
472
+ constructor(options = {}) {
473
+ this.defaults = {
474
+ baseURL: "",
475
+ timeout: 15e3,
476
+ headers: {
477
+ "Content-Type": "application/json",
478
+ Accept: "application/json"
479
+ }
480
+ };
481
+ this.interceptors = {
482
+ request: new InterceptorManager(),
483
+ response: new InterceptorManager()
484
+ };
485
+ if (options.baseURL) this.defaults.baseURL = options.baseURL.replace(/\/+$/, "");
486
+ if (options.timeout) this.defaults.timeout = options.timeout;
487
+ if (options.headers) this.defaults.headers = { ...this.defaults.headers, ...options.headers };
488
+ }
489
+ async request(config) {
490
+ const cfg = {
491
+ method: "GET",
492
+ ...config,
493
+ baseURL: config.baseURL ?? this.defaults.baseURL,
494
+ headers: { ...this.defaults.headers, ...config.headers },
495
+ timeout: config.timeout ?? this.defaults.timeout
496
+ };
497
+ const requestChain = [];
498
+ this.interceptors.request.forEach((h) => {
499
+ requestChain.push(h.fulfilled, h.rejected);
500
+ });
501
+ let promise = Promise.resolve(cfg);
502
+ while (requestChain.length) {
503
+ promise = promise.then(requestChain.shift(), requestChain.shift());
504
+ }
505
+ let responsePromise = promise.then(async (finalConfig) => {
506
+ const fullUrl = this.resolveUrl(finalConfig.url, finalConfig.baseURL);
507
+ return this.send(fullUrl, finalConfig);
508
+ });
509
+ const responseChain = [];
510
+ this.interceptors.response.forEach((h) => {
511
+ responseChain.push(h.fulfilled, h.rejected);
512
+ });
513
+ while (responseChain.length) {
514
+ responsePromise = responsePromise.then(responseChain.shift(), responseChain.shift());
515
+ }
516
+ return responsePromise;
517
+ }
518
+ get(url, config) {
519
+ return this.request({ ...config, url, method: "GET" });
520
+ }
521
+ post(url, data, config) {
522
+ return this.request({ ...config, url, method: "POST", data });
523
+ }
524
+ put(url, data, config) {
525
+ return this.request({ ...config, url, method: "PUT", data });
526
+ }
527
+ delete(url, config) {
528
+ return this.request({ ...config, url, method: "DELETE" });
529
+ }
530
+ resolveUrl(url, baseURL) {
531
+ if (/^(https?:)?\/\//.test(url) || url.startsWith("file://")) return url;
532
+ const base = (baseURL || this.defaults.baseURL || "").replace(/\/+$/, "");
533
+ const path = url.startsWith("/") ? url : `/${url}`;
534
+ return base ? `${base}${path}` : path;
535
+ }
536
+ send(url, cfg) {
537
+ return new Promise((resolve, reject) => {
538
+ const isGet = (cfg.method || "GET").toUpperCase() === "GET";
539
+ const requestData = isGet ? cfg.params ?? cfg.data : cfg.data ?? cfg.params;
540
+ uni.request({
541
+ url,
542
+ method: cfg.method?.toUpperCase() || "GET",
543
+ data: requestData,
544
+ header: cfg.headers,
545
+ timeout: cfg.timeout,
546
+ success: (res) => {
547
+ const response = {
548
+ data: res.data,
549
+ status: res.statusCode,
550
+ statusText: String(res.statusCode),
551
+ headers: res.header || {},
552
+ config: cfg
553
+ };
554
+ if (res.statusCode >= 200 && res.statusCode < 300) {
555
+ resolve(response);
556
+ } else {
557
+ const body = res.data;
558
+ const error = new Error(String(body?.msg || `\u8BF7\u6C42\u5931\u8D25: ${res.statusCode}`));
559
+ error.response = response;
560
+ error.status = res.statusCode;
561
+ reject(error);
562
+ }
563
+ },
564
+ fail: (errorResult) => {
565
+ const error = new Error(errorResult.errMsg || "\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25");
566
+ error.config = cfg;
567
+ reject(error);
568
+ }
569
+ });
570
+ });
571
+ }
572
+ };
573
+ var target = null;
574
+ var currentOptions = {};
575
+ var lastToastTime = 0;
576
+ function handleUnauthorized(message, callback) {
577
+ const now = Date.now();
578
+ if (now - lastToastTime > 3e3) {
579
+ lastToastTime = now;
580
+ if (typeof uni !== "undefined" && uni.showToast) {
581
+ uni.showToast({ title: message, icon: "none" });
582
+ }
583
+ }
584
+ if (callback) {
585
+ callback(message);
586
+ }
587
+ }
588
+ function getClient() {
589
+ if (target) {
590
+ if (currentOptions.baseURL && !target.defaults.baseURL) {
591
+ target.defaults.baseURL = currentOptions.baseURL;
592
+ }
593
+ return target;
594
+ }
595
+ const base = currentOptions.baseURL || "";
596
+ const inst = new UniHttpClient({
597
+ baseURL: base,
598
+ timeout: currentOptions.timeout || 15e3
599
+ });
600
+ inst.interceptors.request.use(
601
+ async (config) => {
602
+ const devInfo = currentOptions.getDevice?.() || getDevice();
603
+ const token = currentOptions.getToken?.() || "";
604
+ const time = Date.now();
605
+ const nonce = Math.random().toString(36).substring(2, 12);
606
+ const payload = {
607
+ ...devInfo,
608
+ token
609
+ };
610
+ const jsonStr = JSON.stringify(payload);
611
+ const pubKey = currentOptions.publicKey || "";
612
+ const secret = currentOptions.secret || "";
613
+ let cipher = "";
614
+ if (pubKey) {
615
+ cipher = encryptRsa(jsonStr, pubKey);
616
+ } else {
617
+ cipher = encodeURIComponent(jsonStr);
618
+ }
619
+ const signData = config.data || config.params || {};
620
+ const sign = calculateSign({
621
+ timestamp: time,
622
+ nonce,
623
+ context: cipher,
624
+ secret,
625
+ data: signData
626
+ });
627
+ config.headers = config.headers || {};
628
+ config.headers["X-Client-Timestamp"] = String(time);
629
+ config.headers["X-Client-Nonce"] = nonce;
630
+ config.headers["X-Client-Sign"] = sign;
631
+ config.headers["X-Client-Context"] = cipher;
632
+ if (devInfo.appid) {
633
+ config.headers["x-appid"] = String(devInfo.appid);
634
+ }
635
+ return config;
636
+ },
637
+ (error) => Promise.reject(error)
638
+ );
639
+ inst.interceptors.response.use(
640
+ async (response) => {
641
+ const res = response.data;
642
+ if (res && (res.code === 401 || res.code === 403)) {
643
+ const message = res.msg || "\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55";
644
+ handleUnauthorized(message, currentOptions.onUnauthorized);
645
+ }
646
+ return response;
647
+ },
648
+ (error) => {
649
+ const status = error.response?.status;
650
+ const message = error.response?.data?.msg || error.message || "\u7F51\u7EDC\u8FDE\u63A5\u5F02\u5E38";
651
+ if (status === 401 || status === 403) {
652
+ handleUnauthorized(message, currentOptions.onUnauthorized);
653
+ }
654
+ return Promise.reject(error);
655
+ }
656
+ );
657
+ target = inst;
658
+ return inst;
659
+ }
660
+ function setupHttp(options = {}) {
661
+ currentOptions = { ...currentOptions, ...options };
662
+ if (target && options.baseURL) {
663
+ target.defaults.baseURL = options.baseURL;
664
+ }
665
+ return getClient();
666
+ }
667
+ function request(config) {
668
+ return getClient().request(config).then((res) => res.data);
669
+ }
670
+ function get(url, params) {
671
+ return request({ url, method: "GET", params });
672
+ }
673
+ function post(url, data) {
674
+ return request({ url, method: "POST", data });
675
+ }
676
+ function put(url, data) {
677
+ return request({ url, method: "PUT", data });
678
+ }
679
+ function del(url, params) {
680
+ return request({ url, method: "DELETE", params });
681
+ }
682
+ function getHttpOptions() {
683
+ return currentOptions;
684
+ }
685
+ var client = new Proxy({}, {
686
+ get(_, prop) {
687
+ const inst = getClient();
688
+ const val = inst[prop];
689
+ return typeof val === "function" ? val.bind(inst) : val;
690
+ }
691
+ });
692
+ var http = client;
693
+ var index_default = request;
694
+ // Annotate the CommonJS export names for ESM import in node:
695
+ 0 && (module.exports = {
696
+ InterceptorManager,
697
+ UniHttpClient,
698
+ calculateSign,
699
+ client,
700
+ del,
701
+ doUpload,
702
+ encryptRsa,
703
+ get,
704
+ getClient,
705
+ getDevice,
706
+ getHttpOptions,
707
+ http,
708
+ post,
709
+ postUploadSign,
710
+ put,
711
+ request,
712
+ setupHttp,
713
+ sha256,
714
+ sortString,
715
+ uploadFile,
716
+ uploadOss
717
+ });