@relia-fe/core 0.0.1 → 0.0.2

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 CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,19 +17,43 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = 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(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var src_exports = {};
22
32
  __export(src_exports, {
33
+ AuthError: () => AuthError,
34
+ AuthProvider: () => AuthProvider,
35
+ AuthService: () => AuthService,
36
+ TokenStorageService: () => TokenStorageService,
23
37
  cloneDeep: () => import_lodash_es.cloneDeep,
38
+ configureBaseRequest: () => configureBaseRequest,
24
39
  copyToClipboard: () => copyToClipboard,
40
+ createAuthRequest: () => createAuthRequest,
41
+ createBaseRequest: () => createBaseRequest,
42
+ createFetcherInterceptor: () => createFetcherInterceptor,
43
+ createFetcherMutation: () => createFetcherMutation,
25
44
  debounce: () => import_radash.debounce,
45
+ defaultTokenStorageService: () => defaultTokenStorageService,
46
+ defineFetch: () => defineFetch,
47
+ defineMutation: () => defineMutation,
48
+ defineResource: () => defineResource,
49
+ defineResourceList: () => defineResourceList,
26
50
  formatCurrency: () => formatCurrency,
27
51
  formatDate: () => formatDate,
28
52
  generateId: () => generateId,
29
53
  get: () => import_lodash_es.get,
54
+ getBaseRequest: () => getBaseRequest,
30
55
  groupBy: () => import_lodash_es.groupBy,
56
+ isBrowser: () => isBrowser,
31
57
  isEmpty: () => import_lodash_es.isEmpty,
32
58
  isEqual: () => import_lodash_es.isEqual,
33
59
  merge: () => import_lodash_es.merge,
@@ -39,10 +65,683 @@ __export(src_exports, {
39
65
  sortBy: () => import_lodash_es.sortBy,
40
66
  throttle: () => import_radash.throttle,
41
67
  uniq: () => import_lodash_es.uniq,
42
- uniqBy: () => import_lodash_es.uniqBy
68
+ uniqBy: () => import_lodash_es.uniqBy,
69
+ useAuth: () => useAuth,
70
+ useAuthChange: () => useAuthChange,
71
+ useAuthRequest: () => useAuthRequest,
72
+ useMutation: () => useMutation,
73
+ useResource: () => useResource,
74
+ useResourceList: () => useResourceList
43
75
  });
44
76
  module.exports = __toCommonJS(src_exports);
45
77
 
78
+ // src/api/base/request.ts
79
+ var import_axios = __toESM(require("axios"));
80
+ var isBrowser = typeof window !== "undefined";
81
+ var shouldRemoveBaseURL = (url) => {
82
+ if (!url) return false;
83
+ return url.startsWith("http") || url.startsWith("/api/");
84
+ };
85
+ var setAuthorizationHeader = (headers, token) => {
86
+ if (headers instanceof import_axios.AxiosHeaders) {
87
+ const newHeaders = new import_axios.AxiosHeaders(headers);
88
+ newHeaders.set("Authorization", `TOKEN ${token}`);
89
+ return newHeaders;
90
+ } else {
91
+ return {
92
+ ...headers,
93
+ Authorization: `TOKEN ${token}`
94
+ };
95
+ }
96
+ };
97
+ var applyAuthorizationToConfig = (requestConfig, token) => {
98
+ return {
99
+ ...requestConfig,
100
+ headers: setAuthorizationHeader(
101
+ requestConfig.headers ?? {},
102
+ token
103
+ )
104
+ };
105
+ };
106
+ var is401Error = (error) => {
107
+ return !!error && typeof error === "object" && "response" in error && error.response?.status === 401;
108
+ };
109
+ var createBaseRequest = (config) => {
110
+ return import_axios.default.create({
111
+ baseURL: config.baseURL,
112
+ headers: {
113
+ "Content-Type": "application/json",
114
+ ...config.headers
115
+ }
116
+ });
117
+ };
118
+ var _baseRequest = null;
119
+ var getBaseRequest = () => {
120
+ if (!_baseRequest) {
121
+ _baseRequest = createBaseRequest({ baseURL: "" });
122
+ }
123
+ return _baseRequest;
124
+ };
125
+ var configureBaseRequest = (config) => {
126
+ _baseRequest = createBaseRequest(config);
127
+ };
128
+ var createAuthRequest = (config) => {
129
+ const { authService, axiosConfig } = config;
130
+ const requestInterceptor = async (reqConfig) => {
131
+ let token = authService.getToken();
132
+ if (!token && isBrowser) {
133
+ const result = await authService.authenticate("request-init");
134
+ if (result.success && result.token) {
135
+ token = result.token;
136
+ } else {
137
+ throw new Error("Authentication required");
138
+ }
139
+ }
140
+ if (!token) {
141
+ throw new Error("Authentication required");
142
+ }
143
+ let newConfig = applyAuthorizationToConfig(reqConfig, token);
144
+ if (shouldRemoveBaseURL(newConfig.url)) {
145
+ newConfig = { ...newConfig, baseURL: void 0 };
146
+ }
147
+ return newConfig;
148
+ };
149
+ const clearAuthAndRedirect = () => {
150
+ authService.logout();
151
+ if (isBrowser) {
152
+ window.location.replace("/");
153
+ }
154
+ };
155
+ const handle401Retry = async (error, retryFn) => {
156
+ const originalConfig = error.config;
157
+ if (originalConfig._retry) {
158
+ console.warn("[Fetcher] Re-authentication retry failed");
159
+ clearAuthAndRedirect();
160
+ return Promise.reject(error);
161
+ }
162
+ originalConfig._retry = true;
163
+ const authResult = await authService.authenticate("token-refresh");
164
+ if (authResult.success && authResult.token) {
165
+ const newConfig = applyAuthorizationToConfig(
166
+ originalConfig,
167
+ authResult.token
168
+ );
169
+ console.log("[Fetcher] Re-authentication successful, retrying request");
170
+ return retryFn(newConfig);
171
+ }
172
+ console.warn("[Fetcher] Re-authentication failed, redirecting to home");
173
+ clearAuthAndRedirect();
174
+ return Promise.reject(error);
175
+ };
176
+ const responseErrorHandler = async (error, retryFn) => {
177
+ console.error(error);
178
+ if (!isBrowser) {
179
+ return Promise.reject(error);
180
+ }
181
+ if (is401Error(error)) {
182
+ return handle401Retry(error, retryFn);
183
+ }
184
+ return Promise.reject(error);
185
+ };
186
+ const baseReq = getBaseRequest();
187
+ const instance = axiosConfig ? baseReq.create(axiosConfig) : baseReq.create();
188
+ instance.interceptors.request.use(
189
+ requestInterceptor,
190
+ (error) => Promise.reject(error)
191
+ );
192
+ instance.interceptors.response.use(
193
+ (response) => response,
194
+ (error) => responseErrorHandler(error, (cfg) => instance.request(cfg))
195
+ );
196
+ return instance;
197
+ };
198
+
199
+ // src/api/base/definition.ts
200
+ function defineFetch(uri, method, option) {
201
+ return {
202
+ uri,
203
+ method,
204
+ host: option?.host,
205
+ // absoluteUri: `${option?.host ?? HOST_PREFIX}${uri}`,
206
+ noAuth: option?.noAuth
207
+ };
208
+ }
209
+ function defineResource(uri, option) {
210
+ return {
211
+ uri,
212
+ method: "get",
213
+ host: option?.host,
214
+ // absoluteUri: `${option?.host ?? HOST_PREFIX}${uri}`,
215
+ noAuth: option?.noAuth
216
+ };
217
+ }
218
+ function defineResourceList(uri, option) {
219
+ return {
220
+ uri,
221
+ method: "get",
222
+ host: option?.host,
223
+ // absoluteUri: `${option?.host ?? HOST_PREFIX}${uri}`,
224
+ noAuth: option?.noAuth
225
+ };
226
+ }
227
+ function defineMutation(uri, option) {
228
+ return {
229
+ uri,
230
+ method: option?.method ?? "post",
231
+ host: option?.host,
232
+ // absoluteUri: `${option?.host ?? HOST_PREFIX}${uri}`,
233
+ noAuth: option?.noAuth
234
+ };
235
+ }
236
+
237
+ // src/api/base/TokenStorageService.ts
238
+ var isBrowser2 = typeof window !== "undefined";
239
+ var STORAGE_KEY = "auth_tokens";
240
+ var TokenStorageService = class {
241
+ constructor() {
242
+ this.listeners = /* @__PURE__ */ new Set();
243
+ this.boundHandleStorage = null;
244
+ }
245
+ setToken(token, address) {
246
+ if (!isBrowser2) return;
247
+ const key = address?.toLowerCase() ?? "_default";
248
+ const map = this.getMap();
249
+ if (token === void 0) {
250
+ delete map[key];
251
+ } else {
252
+ map[key] = token;
253
+ }
254
+ this.saveMap(map);
255
+ }
256
+ getToken(address) {
257
+ const key = address?.toLowerCase() ?? "_default";
258
+ return this.getMap()[key] ?? null;
259
+ }
260
+ getMap() {
261
+ if (!isBrowser2) return {};
262
+ try {
263
+ const data = localStorage.getItem(STORAGE_KEY);
264
+ return data ? JSON.parse(data) : {};
265
+ } catch {
266
+ return {};
267
+ }
268
+ }
269
+ saveMap(map) {
270
+ if (!isBrowser2) return;
271
+ try {
272
+ if (Object.keys(map).length === 0) {
273
+ localStorage.removeItem(STORAGE_KEY);
274
+ } else {
275
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(map));
276
+ }
277
+ } catch (e) {
278
+ console.error("Failed to persist auth tokens", e);
279
+ }
280
+ }
281
+ subscribe(listener) {
282
+ this.listeners.add(listener);
283
+ if (isBrowser2 && this.listeners.size === 1) {
284
+ this.boundHandleStorage = (e) => {
285
+ if (e.key === STORAGE_KEY) {
286
+ this.listeners.forEach((l) => l());
287
+ }
288
+ };
289
+ window.addEventListener("storage", this.boundHandleStorage);
290
+ }
291
+ return () => {
292
+ this.listeners.delete(listener);
293
+ if (isBrowser2 && this.listeners.size === 0 && this.boundHandleStorage) {
294
+ window.removeEventListener("storage", this.boundHandleStorage);
295
+ this.boundHandleStorage = null;
296
+ }
297
+ };
298
+ }
299
+ };
300
+ var defaultTokenStorageService = new TokenStorageService();
301
+
302
+ // src/api/base/AuthError.ts
303
+ var AuthError = class _AuthError extends Error {
304
+ constructor(message, errorType) {
305
+ super(message);
306
+ this.name = "AuthError";
307
+ this.errorType = errorType;
308
+ Object.setPrototypeOf(this, _AuthError.prototype);
309
+ }
310
+ };
311
+
312
+ // src/api/base/AuthService.ts
313
+ var AuthService = class {
314
+ constructor(config) {
315
+ this.authPromise = null;
316
+ // 用于并发控制
317
+ // 状态管理
318
+ this.state = { status: "idle" };
319
+ this.listeners = /* @__PURE__ */ new Set();
320
+ this.refreshToken = config.refreshToken;
321
+ this.tokenStorageService = config.tokenStorageService ?? defaultTokenStorageService;
322
+ this.tokenStorageService.subscribe(() => this.handleStorageChange());
323
+ }
324
+ /**
325
+ * Authenticate with concurrency control
326
+ * Multiple concurrent calls will share the same Promise
327
+ * Stores token on success
328
+ */
329
+ async authenticate(context) {
330
+ if (this.state.status === "authenticating" && this.authPromise) {
331
+ console.log(
332
+ `[AuthService] Authentication already in progress, reusing Promise`
333
+ );
334
+ return this.authPromise;
335
+ }
336
+ const startAddress = this.state.address;
337
+ this.setState({
338
+ status: "authenticating",
339
+ address: startAddress
340
+ });
341
+ this.authPromise = this.refreshToken(context);
342
+ try {
343
+ const result = await this.authPromise;
344
+ const currentAddress = this.state.address;
345
+ if (this.state.status !== "authenticating") {
346
+ console.log(
347
+ `[AuthService] Authentication was cancelled, ignoring result`
348
+ );
349
+ throw new AuthError("Authentication was cancelled", "cancelled" /* CANCELLED */);
350
+ }
351
+ if (currentAddress !== startAddress) {
352
+ console.log(
353
+ `[AuthService] Address changed during auth, ignoring result`
354
+ );
355
+ throw new AuthError(
356
+ "Address changed during authentication",
357
+ "address_changed" /* ADDRESS_CHANGED */
358
+ );
359
+ }
360
+ this.tokenStorageService.setToken(
361
+ result.token,
362
+ currentAddress ?? void 0
363
+ );
364
+ this.setState({
365
+ status: "authenticated",
366
+ address: currentAddress
367
+ });
368
+ console.log(`[AuthService] Token stored successfully`);
369
+ return result;
370
+ } catch (error) {
371
+ const currentAddress = this.state.address;
372
+ if (error instanceof AuthError) {
373
+ this.setState({
374
+ status: "unauthenticated",
375
+ address: currentAddress,
376
+ error
377
+ });
378
+ throw error;
379
+ }
380
+ const authError = new AuthError(
381
+ error instanceof Error ? error.message : "Unknown error",
382
+ "unknown" /* UNKNOWN */
383
+ );
384
+ this.setState({
385
+ status: "unauthenticated",
386
+ address: currentAddress,
387
+ error: authError
388
+ });
389
+ throw authError;
390
+ } finally {
391
+ this.authPromise = null;
392
+ }
393
+ }
394
+ /**
395
+ * 重置内部认证状态(私有方法)
396
+ */
397
+ reset() {
398
+ this.authPromise = null;
399
+ }
400
+ /**
401
+ * Get current token for the current wallet address
402
+ */
403
+ getToken() {
404
+ return this.tokenStorageService.getToken(this.state.address ?? void 0);
405
+ }
406
+ /**
407
+ * 检查地址是否有有效 token(私有方法)
408
+ */
409
+ isAddressAuthenticated(address) {
410
+ if (!address) return false;
411
+ return this.tokenStorageService.getToken(address) !== null;
412
+ }
413
+ /**
414
+ * Logout: clear token for current address and update state
415
+ */
416
+ logout() {
417
+ const address = this.state.address;
418
+ this.tokenStorageService.setToken(void 0, address ?? void 0);
419
+ this.reset();
420
+ this.setState({ status: "unauthenticated", address });
421
+ }
422
+ /**
423
+ * Get current authentication state
424
+ */
425
+ getState() {
426
+ return { ...this.state };
427
+ }
428
+ /**
429
+ * Subscribe to state changes
430
+ */
431
+ subscribe(listener) {
432
+ this.listeners.add(listener);
433
+ return () => this.listeners.delete(listener);
434
+ }
435
+ /**
436
+ * Handle wallet address changes
437
+ * Note: Wallet disconnection should be handled externally by calling logout()
438
+ */
439
+ handleWalletChange(address) {
440
+ const isAuthenticating = this.state.status === "authenticating";
441
+ if (isAuthenticating && this.state.address !== address) {
442
+ this.reset();
443
+ this.setState({ status: "idle", address });
444
+ }
445
+ if (this.isAddressAuthenticated(address)) {
446
+ if (this.state.status !== "authenticated" || this.state.address !== address) {
447
+ this.setState({ status: "authenticated", address });
448
+ }
449
+ return;
450
+ }
451
+ const isAlreadyAuthForThisAddress = this.state.status === "authenticated" && this.state.address === address;
452
+ if (!isAuthenticating && !isAlreadyAuthForThisAddress) {
453
+ this.setState({ status: "idle", address });
454
+ this.authenticate("wallet-connect").catch(() => {
455
+ });
456
+ }
457
+ }
458
+ /**
459
+ * 处理 StorageChange 事件(用于多选项卡同步)
460
+ * 当 localStorage 在另一个选项卡中发生更改时调用
461
+ */
462
+ handleStorageChange() {
463
+ const address = this.state.address;
464
+ if (!address) return;
465
+ const hasToken = this.isAddressAuthenticated(address);
466
+ const currentStatus = this.state.status;
467
+ if (!hasToken && currentStatus === "authenticated") {
468
+ this.setState({ status: "unauthenticated", address });
469
+ } else if (hasToken && currentStatus !== "authenticated") {
470
+ this.setState({ status: "authenticated", address });
471
+ }
472
+ }
473
+ /**
474
+ * 更新状态并通知监听者
475
+ */
476
+ setState(newState) {
477
+ this.state = newState;
478
+ this.listeners.forEach((listener) => listener(newState));
479
+ }
480
+ };
481
+
482
+ // src/api/provider/AuthProvider.tsx
483
+ var import_react = require("react");
484
+ var import_swr = require("swr");
485
+ var import_jsx_runtime = require("react/jsx-runtime");
486
+ function isInstanceConfig(config) {
487
+ return "authService" in config && "authRequest" in config;
488
+ }
489
+ var AuthContext = (0, import_react.createContext)(null);
490
+ var AuthRequestContext = (0, import_react.createContext)(null);
491
+ var useAuthInternal = ({
492
+ authService,
493
+ address
494
+ }) => {
495
+ const { mutate: globalMutate } = (0, import_swr.useSWRConfig)();
496
+ const [authState, setAuthState] = (0, import_react.useState)(() => authService.getState());
497
+ (0, import_react.useEffect)(() => {
498
+ return authService.subscribe(setAuthState);
499
+ }, [authService]);
500
+ (0, import_react.useEffect)(() => {
501
+ authService.handleWalletChange(address);
502
+ }, [address, authService]);
503
+ const prevStatusRef = (0, import_react.useRef)(void 0);
504
+ const prevAddressRef = (0, import_react.useRef)(void 0);
505
+ (0, import_react.useEffect)(() => {
506
+ const prevStatus = prevStatusRef.current;
507
+ const prevAddress = prevAddressRef.current;
508
+ const currentStatus = authState.status;
509
+ const currentAddress = authState.address;
510
+ prevStatusRef.current = currentStatus;
511
+ prevAddressRef.current = currentAddress;
512
+ if (currentStatus === "authenticated" && prevStatus !== "authenticated" || currentStatus === "authenticated" && currentAddress !== prevAddress) {
513
+ globalMutate(() => true, void 0, { revalidate: true });
514
+ }
515
+ }, [authState.status, authState.address, globalMutate]);
516
+ const authenticate = (0, import_react.useCallback)(async () => {
517
+ if (!address) {
518
+ console.warn("[Auth] Cannot authenticate without address");
519
+ return;
520
+ }
521
+ if (authState.status === "authenticating") {
522
+ console.log("[Auth] Authentication already in progress");
523
+ return;
524
+ }
525
+ try {
526
+ await authService.authenticate("wallet-connect");
527
+ } catch (error) {
528
+ console.error("[Auth] Authentication failed:", error);
529
+ }
530
+ }, [authService, address, authState.status]);
531
+ const logout = (0, import_react.useCallback)(() => {
532
+ authService.logout();
533
+ }, [authService]);
534
+ return {
535
+ status: authState.status,
536
+ error: authState.error,
537
+ address: authState.address,
538
+ isAuthenticated: authState.status === "authenticated",
539
+ isAuthenticating: authState.status === "authenticating",
540
+ authenticate,
541
+ logout
542
+ };
543
+ };
544
+ var AuthProvider = ({
545
+ children,
546
+ ...config
547
+ }) => {
548
+ const { authService, authRequest, address } = (0, import_react.useMemo)(() => {
549
+ if (isInstanceConfig(config)) {
550
+ return {
551
+ authService: config.authService,
552
+ authRequest: config.authRequest,
553
+ address: config.address
554
+ };
555
+ }
556
+ const { refreshTokenFn, axiosConfig, tokenStorageService, address: address2 } = config;
557
+ const service = new AuthService({
558
+ refreshToken: refreshTokenFn,
559
+ tokenStorageService
560
+ });
561
+ const request = createAuthRequest({
562
+ authService: service,
563
+ axiosConfig
564
+ });
565
+ return { authService: service, authRequest: request, address: address2 };
566
+ }, [config]);
567
+ const auth = useAuthInternal({ authService, address });
568
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AuthContext.Provider, { value: auth, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AuthRequestContext.Provider, { value: authRequest, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
569
+ import_swr.SWRConfig,
570
+ {
571
+ value: {
572
+ revalidateOnFocus: false,
573
+ shouldRetryOnError: false,
574
+ dedupingInterval: 2e3,
575
+ revalidateOnReconnect: false
576
+ },
577
+ children
578
+ }
579
+ ) }) });
580
+ };
581
+
582
+ // src/api/hooks/useAuth.ts
583
+ var import_react2 = require("react");
584
+ var useAuth = () => {
585
+ const context = (0, import_react2.useContext)(AuthContext);
586
+ if (!context) {
587
+ throw new Error("useAuth must be used within AuthProvider");
588
+ }
589
+ return context;
590
+ };
591
+
592
+ // src/api/hooks/useAuthChange.ts
593
+ var import_react3 = require("react");
594
+ function useAuthChange(onChange) {
595
+ const { status, error, address } = useAuth();
596
+ const prevStatusRef = (0, import_react3.useRef)(void 0);
597
+ const prevAddressRef = (0, import_react3.useRef)(void 0);
598
+ (0, import_react3.useEffect)(() => {
599
+ const prevStatus = prevStatusRef.current;
600
+ const prevAddress = prevAddressRef.current;
601
+ prevStatusRef.current = status;
602
+ prevAddressRef.current = address;
603
+ if (status === "authenticated" && prevStatus !== "authenticated" || status === "authenticated" && address !== prevAddress) {
604
+ onChange({ type: "authenticated" });
605
+ } else if (error && status !== prevStatus) {
606
+ onChange({ type: "error", error });
607
+ } else if (status === "unauthenticated" && prevStatus && prevStatus !== "idle") {
608
+ onChange({ type: "unauthenticated", error });
609
+ }
610
+ }, [status, error, address, onChange]);
611
+ }
612
+
613
+ // src/api/hooks/useAuthRequest.ts
614
+ var import_react4 = require("react");
615
+ var useAuthRequest = () => {
616
+ const context = (0, import_react4.useContext)(AuthRequestContext);
617
+ if (!context) {
618
+ throw new Error("useAuthRequest must be used within AuthProvider");
619
+ }
620
+ return context;
621
+ };
622
+
623
+ // src/api/hooks/useResource.ts
624
+ var import_swr2 = __toESM(require("swr"));
625
+ var import_react5 = require("react");
626
+
627
+ // src/api/hooks/fetcherFactory.ts
628
+ var createFetchFn = (authRequest) => {
629
+ return async (requestIdentity, payload) => {
630
+ const { method, uri, noAuth } = requestIdentity;
631
+ const instance = noAuth ? getBaseRequest() : authRequest;
632
+ if (!method || method === "get") {
633
+ const { data: data2 } = await instance.get(uri, {
634
+ params: payload
635
+ });
636
+ return data2;
637
+ }
638
+ if (method === "delete") {
639
+ const { data: data2 } = await instance.delete(uri, {
640
+ data: payload
641
+ });
642
+ return data2;
643
+ }
644
+ const { data } = await instance.post(uri, payload);
645
+ return data;
646
+ };
647
+ };
648
+ var createFetcherInterceptor = (authRequest) => {
649
+ const fetchFn = createFetchFn(authRequest);
650
+ async function fetcherInterceptor(params) {
651
+ if (Array.isArray(params[0])) {
652
+ const multiParams = params;
653
+ return await Promise.all(
654
+ multiParams.map(([identity2, payload2]) => fetchFn(identity2, payload2))
655
+ );
656
+ }
657
+ const [identity, payload] = params;
658
+ return await fetchFn(identity, payload);
659
+ }
660
+ return fetcherInterceptor;
661
+ };
662
+ var createFetcherMutation = (authRequest) => {
663
+ const fetchFn = createFetchFn(authRequest);
664
+ return async (requestIdentity, { arg }) => {
665
+ const res = await fetchFn(requestIdentity, arg);
666
+ if (!res.success || res.code !== 0 && res.code !== 10001) {
667
+ throw Error(res.message);
668
+ }
669
+ return res;
670
+ };
671
+ };
672
+
673
+ // src/api/hooks/useResource.ts
674
+ var useResource = (requestIdentity, params, option) => {
675
+ const authRequest = useAuthRequest();
676
+ const fetcher = (0, import_react5.useMemo)(
677
+ () => createFetcherInterceptor(authRequest),
678
+ [authRequest]
679
+ );
680
+ const { data, ...query } = (0, import_swr2.default)(
681
+ requestIdentity && [requestIdentity, params],
682
+ fetcher,
683
+ option
684
+ );
685
+ return {
686
+ ...query,
687
+ response: data,
688
+ data: data?.data
689
+ };
690
+ };
691
+
692
+ // src/api/hooks/useResourceList.ts
693
+ var import_swr3 = __toESM(require("swr"));
694
+ var import_react6 = require("react");
695
+ var useResourceList = (requestIdentity, params, option) => {
696
+ const authRequest = useAuthRequest();
697
+ const fetcher = (0, import_react6.useMemo)(
698
+ () => createFetcherInterceptor(authRequest),
699
+ [authRequest]
700
+ );
701
+ const [page, setPage] = (0, import_react6.useState)(option?.page ?? 1);
702
+ const [size, setSize] = (0, import_react6.useState)(option?.size ?? 10);
703
+ const pageMapping = option?.pageMapping || ((pageInfo) => pageInfo);
704
+ const keyWithPage = requestIdentity && [
705
+ requestIdentity,
706
+ { ...pageMapping({ page, size }), ...params }
707
+ ];
708
+ const { data, ...query } = (0, import_swr3.default)(
709
+ keyWithPage,
710
+ fetcher,
711
+ option
712
+ );
713
+ return {
714
+ ...query,
715
+ response: data,
716
+ list: data?.data?.items,
717
+ pagination: {
718
+ count: (data?.data?.total ?? 0) / size,
719
+ page,
720
+ size,
721
+ setPage,
722
+ setSize
723
+ }
724
+ };
725
+ };
726
+
727
+ // src/api/hooks/useMutation.ts
728
+ var import_mutation = __toESM(require("swr/mutation"));
729
+ var import_react7 = require("react");
730
+ var useMutation = (key, option) => {
731
+ const authRequest = useAuthRequest();
732
+ const fetcher = (0, import_react7.useMemo)(
733
+ () => createFetcherMutation(authRequest),
734
+ [authRequest]
735
+ );
736
+ const { data, error, ...query } = (0, import_mutation.default)(key, fetcher, option);
737
+ return {
738
+ ...query,
739
+ error,
740
+ response: data,
741
+ data: data?.data
742
+ };
743
+ };
744
+
46
745
  // src/utils/index.ts
47
746
  var import_radash = require("radash");
48
747
  var import_lodash_es = require("lodash-es");
@@ -70,14 +769,30 @@ var copyToClipboard = async (text) => {
70
769
  };
71
770
  // Annotate the CommonJS export names for ESM import in node:
72
771
  0 && (module.exports = {
772
+ AuthError,
773
+ AuthProvider,
774
+ AuthService,
775
+ TokenStorageService,
73
776
  cloneDeep,
777
+ configureBaseRequest,
74
778
  copyToClipboard,
779
+ createAuthRequest,
780
+ createBaseRequest,
781
+ createFetcherInterceptor,
782
+ createFetcherMutation,
75
783
  debounce,
784
+ defaultTokenStorageService,
785
+ defineFetch,
786
+ defineMutation,
787
+ defineResource,
788
+ defineResourceList,
76
789
  formatCurrency,
77
790
  formatDate,
78
791
  generateId,
79
792
  get,
793
+ getBaseRequest,
80
794
  groupBy,
795
+ isBrowser,
81
796
  isEmpty,
82
797
  isEqual,
83
798
  merge,
@@ -89,6 +804,12 @@ var copyToClipboard = async (text) => {
89
804
  sortBy,
90
805
  throttle,
91
806
  uniq,
92
- uniqBy
807
+ uniqBy,
808
+ useAuth,
809
+ useAuthChange,
810
+ useAuthRequest,
811
+ useMutation,
812
+ useResource,
813
+ useResourceList
93
814
  });
94
815
  //# sourceMappingURL=index.js.map