@yeepay/client-utils 3.1.1 → 4.0.1

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.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import debug from "debug";
2
- import { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from "axios";
2
+ import { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from "axios";
3
3
 
4
4
  //#region src/debug.d.ts
5
5
  declare const logger: Record<string, debug.Debugger> & debug.Debugger;
@@ -13,6 +13,23 @@ declare global {
13
13
  }
14
14
  }
15
15
  //#endregion
16
+ //#region src/is.d.ts
17
+ declare function isMobileDevice(): boolean;
18
+ declare const BREAKPOINTS: {
19
+ MOBILE_MAX: number;
20
+ TABLET_MIN: number;
21
+ TABLET_MAX: number;
22
+ DESKTOP_MIN: number;
23
+ };
24
+ declare const MEDIA_QUERIES: {
25
+ MOBILE: string;
26
+ TABLET: string;
27
+ DESKTOP: string;
28
+ };
29
+ declare function isMobile(): boolean;
30
+ declare function isTablet(): boolean;
31
+ declare function isDesktop(): boolean;
32
+ //#endregion
16
33
  //#region src/request/mock.d.ts
17
34
  /**
18
35
  * A valid `picomatch` glob pattern, or array of patterns.
@@ -76,11 +93,10 @@ interface ServiceFactoryCallbacks {
76
93
  notfoundCallback?: (response: AxiosResponse<any> | any) => any;
77
94
  requestInterceptor?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig;
78
95
  responseInterceptor?: (response: AxiosResponse<any>) => AxiosResponse<any>;
96
+ responseInterceptorFailCallback?: (error: AxiosError) => any;
79
97
  }
80
- type ServiceFactoryCallbacksCompatible = [ServiceFactoryCallbacks['successCallback']?, ServiceFactoryCallbacks['failCallback']?, ServiceFactoryCallbacks['unauthorizedCallback']?, ServiceFactoryCallbacks['forbiddenCallback']?, ServiceFactoryCallbacks['notfoundCallback']?, ServiceFactoryCallbacks['requestInterceptor']?, ServiceFactoryCallbacks['responseInterceptor']?];
81
98
  declare function verifySuccessCode<T extends string | number>(code: T, customCode?: T): boolean;
82
99
  declare function serviceFactory(options: ServiceFactoryOptions, callbacks: ServiceFactoryCallbacks): AxiosInstance;
83
- declare function serviceFactory(options: ServiceFactoryOptions, ...callbacks: ServiceFactoryCallbacksCompatible): AxiosInstance;
84
100
  //#endregion
85
101
  //#region src/request/token.d.ts
86
102
  declare function getToken(): string | undefined;
@@ -93,4 +109,4 @@ declare function removeToken(): void;
93
109
  //#region src/utils.d.ts
94
110
  declare function getQueryObject(url?: string): Record<string, string>;
95
111
  //#endregion
96
- export { logger as debug, getQueryObject, getToken, removeToken, serviceFactory, setTokenFromUrl, verifySuccessCode };
112
+ export { BREAKPOINTS, MEDIA_QUERIES, logger as debug, getQueryObject, getToken, isDesktop, isMobile, isMobileDevice, isTablet, removeToken, serviceFactory, setTokenFromUrl, verifySuccessCode };
package/dist/index.js CHANGED
@@ -54,6 +54,39 @@ try {
54
54
  console.error("Error enabling logger:", error);
55
55
  }
56
56
 
57
+ //#endregion
58
+ //#region src/is.ts
59
+ function isMobileDevice() {
60
+ if (typeof navigator === "undefined" || typeof window === "undefined") return false;
61
+ const ua = navigator.userAgent || "";
62
+ return /android|iphone|ipad|ipod|windows phone|blackberry|mobile/i.test(ua);
63
+ }
64
+ const BREAKPOINTS = {
65
+ MOBILE_MAX: 767,
66
+ TABLET_MIN: 768,
67
+ TABLET_MAX: 1023,
68
+ DESKTOP_MIN: 1024
69
+ };
70
+ const MEDIA_QUERIES = {
71
+ MOBILE: `(max-width: ${BREAKPOINTS.MOBILE_MAX}px)`,
72
+ TABLET: `(min-width: ${BREAKPOINTS.TABLET_MIN}px) and (max-width: ${BREAKPOINTS.TABLET_MAX}px)`,
73
+ DESKTOP: `(min-width: ${BREAKPOINTS.DESKTOP_MIN}px)`
74
+ };
75
+ function isMobile() {
76
+ if (!isMobileDevice()) return false;
77
+ if (typeof window.matchMedia === "function") return window.matchMedia(MEDIA_QUERIES.MOBILE).matches;
78
+ return false;
79
+ }
80
+ function isTablet() {
81
+ if (!isMobileDevice()) return false;
82
+ if (typeof window.matchMedia === "function") return window.matchMedia(MEDIA_QUERIES.TABLET).matches;
83
+ return false;
84
+ }
85
+ function isDesktop() {
86
+ if (typeof navigator === "undefined" || typeof window === "undefined") return false;
87
+ return window.matchMedia(MEDIA_QUERIES.DESKTOP).matches;
88
+ }
89
+
57
90
  //#endregion
58
91
  //#region src/request/mock.ts
59
92
  /**
@@ -123,10 +156,9 @@ async function setupMockAdapter(axiosInstance, mock) {
123
156
  return response;
124
157
  });
125
158
  };
126
- if (typeof modules[path] === "function") interopDefault(modules[path]()).then(registerMock).catch((error) => {
127
- console.error(`@yeepay/client-utils mock trying to loading ${path} failed`, error);
159
+ interopDefault(modules[path]).then((mod) => {
160
+ registerMock(mod);
128
161
  });
129
- else registerMock(modules[path]);
130
162
  });
131
163
  }
132
164
 
@@ -177,26 +209,13 @@ function verifySuccessCode(code, customCode) {
177
209
  if (customCode) return toArray(customCode).includes(code) || !code;
178
210
  return code === 0 || code === "0" || code === "000000" || code === 200 || !code;
179
211
  }
180
- function compatibleCallback(compatibleCallbacks = []) {
181
- if (Array.isArray(compatibleCallbacks) && compatibleCallbacks.length && typeof compatibleCallbacks[0] === "function") return {
182
- successCallback: compatibleCallbacks[0] || (() => ({})),
183
- failCallback: compatibleCallbacks[1] || (() => ({})),
184
- unauthorizedCallback: compatibleCallbacks[2] || (() => ({})),
185
- forbiddenCallback: compatibleCallbacks[3] || (() => ({})),
186
- notfoundCallback: compatibleCallbacks[4] || (() => ({})),
187
- requestInterceptor: compatibleCallbacks[5] || ((c) => c),
188
- responseInterceptor: compatibleCallbacks[6] || ((r) => r)
189
- };
190
- else return compatibleCallbacks[0];
191
- }
192
212
  function blobToJson(blob) {
193
213
  return new Promise((resolve, reject) => {
194
214
  const reader = new FileReader();
195
215
  reader.onload = (event) => {
196
216
  try {
197
217
  const jsonString = event.target?.result;
198
- const jsonObject = JSON.parse(jsonString);
199
- resolve(jsonObject);
218
+ resolve(JSON.parse(jsonString));
200
219
  } catch (error) {
201
220
  reject(error);
202
221
  }
@@ -207,16 +226,13 @@ function blobToJson(blob) {
207
226
  reader.readAsText(blob);
208
227
  });
209
228
  }
210
- function serviceFactory(options, ...callbacks) {
229
+ function serviceFactory(options, callbacks) {
211
230
  const { baseUrl = "/", timeout = 12e5, headers, code, debug: debug$1, mock } = options;
212
- const { successCallback = (_response) => ({}), failCallback = (_error) => ({}), unauthorizedCallback = (_response) => ({}), forbiddenCallback = (_response) => ({}), notfoundCallback = (_response) => ({}), requestInterceptor = (c) => c, responseInterceptor = (r) => r } = compatibleCallback(callbacks);
231
+ const { successCallback = (_response) => ({}), failCallback = (_error) => ({}), unauthorizedCallback = (_response) => ({}), forbiddenCallback = (_response) => ({}), notfoundCallback = (_response) => ({}), requestInterceptor = (c) => c, responseInterceptor = (r) => r, responseInterceptorFailCallback = (error) => Promise.reject(error) } = callbacks;
213
232
  const service = axios.create({
214
233
  baseURL: baseUrl,
215
234
  timeout,
216
- headers,
217
- validateStatus(status) {
218
- return status >= 200 && status < 300 || status === 401 || status === 403 || status === 400 || status === 500;
219
- }
235
+ headers
220
236
  });
221
237
  /**
222
238
  * request拦截器, 先入栈后执行
@@ -248,16 +264,12 @@ function serviceFactory(options, ...callbacks) {
248
264
  }
249
265
  return response;
250
266
  }, async (error) => {
251
- if (error.response.data instanceof Blob && error.response.headers["content-type"]?.split(";")[0]?.trim() === "application/json") error.response.data = await blobToJson(error.response.data);
267
+ try {
268
+ if (error.response.data instanceof Blob && error.response.headers["content-type"]?.split(";")[0]?.trim() === "application/json") error.response.data = await blobToJson(error.response.data);
269
+ } catch (error$1) {}
252
270
  return Promise.reject(error);
253
271
  });
254
272
  service.interceptors.response.use((response) => {
255
- if (response.status && response.status === 401) return unauthorizedCallback(response);
256
- if (response.status && response.status === 403) return forbiddenCallback(response);
257
- if (response.status && (response.status === 400 || response.status === 500)) {
258
- failCallback(response);
259
- return Promise.reject(response);
260
- }
261
273
  if (verifySuccessCode(response.data.code, code)) {
262
274
  successCallback(response);
263
275
  return response;
@@ -267,24 +279,21 @@ function serviceFactory(options, ...callbacks) {
267
279
  }
268
280
  }, (error) => {
269
281
  if (axios.isCancel(error)) return Promise.reject(error);
270
- let status = 0;
271
282
  try {
272
- status = error.response.status || error.response.data.status;
273
- } catch {
274
- if (error.toString().includes("Error: timeout")) return Promise.reject(error);
283
+ const status = error.response.status || error.response.data.status;
284
+ if (status === 401) unauthorizedCallback(error);
285
+ else if (status === 403) forbiddenCallback(error);
286
+ else if (status === 404) notfoundCallback(error);
287
+ else failCallback(error);
288
+ } catch (_) {
289
+ failCallback(error);
275
290
  }
276
- if (status) if (status === 403) forbiddenCallback(error);
277
- else if (status === 404) notfoundCallback(error);
278
- else failCallback(error);
279
- else failCallback(error);
280
- return Promise.reject(error);
281
- });
282
- service.interceptors.response.use(responseInterceptor, (error) => {
283
291
  return Promise.reject(error);
284
292
  });
293
+ service.interceptors.response.use(responseInterceptor, responseInterceptorFailCallback);
285
294
  if (mock) setupMockAdapter(service, mock);
286
295
  return service;
287
296
  }
288
297
 
289
298
  //#endregion
290
- export { logger as debug, getQueryObject, getToken, removeToken, serviceFactory, setTokenFromUrl, verifySuccessCode };
299
+ export { BREAKPOINTS, MEDIA_QUERIES, logger as debug, getQueryObject, getToken, isDesktop, isMobile, isMobileDevice, isTablet, removeToken, serviceFactory, setTokenFromUrl, verifySuccessCode };
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@yeepay/client-utils",
3
3
  "type": "module",
4
- "version": "3.1.1",
4
+ "version": "4.0.1",
5
+ "packageManager": "pnpm@10.17.1",
5
6
  "description": "shared utilities for yeepay client packages",
6
7
  "author": "Yong Yang",
7
8
  "homepage": "http://gitlab.yeepay.com/ued/client-utils#readme",
@@ -19,11 +20,22 @@
19
20
  "files": [
20
21
  "dist"
21
22
  ],
23
+ "scripts": {
24
+ "build": "tsdown",
25
+ "dev": "tsdown --watch",
26
+ "watch": "tsdown --watch",
27
+ "lint": "eslint .",
28
+ "prepack": "nr build",
29
+ "release": "bumpp && pnpm publish",
30
+ "test": "vitest",
31
+ "prepare": "simple-git-hooks",
32
+ "play": "npm -C playground run dev"
33
+ },
22
34
  "dependencies": {
23
35
  "@imyangyong/utils": "^0.8.0",
24
36
  "@yeepay/client-utils": "link:",
25
37
  "ansis": "^4.1.0",
26
- "axios": "^1.7.0",
38
+ "axios": "^1.13.2",
27
39
  "axios-mock-adapter": "^2.1.0",
28
40
  "debug": "^4.4.3",
29
41
  "js-cookie": "^3.0.5",
@@ -50,14 +62,5 @@
50
62
  },
51
63
  "lint-staged": {
52
64
  "*": "eslint --fix"
53
- },
54
- "scripts": {
55
- "build": "tsdown",
56
- "dev": "tsdown --watch",
57
- "watch": "tsdown --watch",
58
- "lint": "eslint .",
59
- "release": "bumpp && pnpm publish",
60
- "test": "vitest",
61
- "play": "npm -C playground run dev"
62
65
  }
63
- }
66
+ }