api-core-lib 16.2.0 → 16.12.133

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.
@@ -0,0 +1,631 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }"use client";
2
+
3
+
4
+
5
+
6
+
7
+
8
+ var _chunkJAMEOM7Tcjs = require('./chunk-JAMEOM7T.cjs');
9
+
10
+ // src/hooks/useApi.ts
11
+ var _react = require('react');
12
+ function buildDynamicPath(template, params) {
13
+ if (!params) return template;
14
+ let path = template;
15
+ for (const key in params) {
16
+ path = path.replace(new RegExp(`{${key}}`, "g"), String(params[key]));
17
+ }
18
+ return path;
19
+ }
20
+ function useApi(axiosInstance, config) {
21
+ const {
22
+ endpoint,
23
+ pathParams,
24
+ initialData,
25
+ initialQuery = {},
26
+ enabled = true,
27
+ refetchAfterChange = true,
28
+ requestConfig,
29
+ onSuccess,
30
+ onError
31
+ } = config;
32
+ const finalEndpoint = _react.useMemo.call(void 0,
33
+ () => buildDynamicPath(endpoint, pathParams),
34
+ [endpoint, pathParams]
35
+ );
36
+ const [state, setState] = _react.useState.call(void 0, {
37
+ data: _nullishCoalesce(initialData, () => ( null)),
38
+ rawResponse: null,
39
+ loading: enabled,
40
+ error: null,
41
+ success: false,
42
+ message: void 0,
43
+ validationErrors: void 0
44
+ });
45
+ const [queryOptions, setQueryOptions] = _react.useState.call(void 0, initialQuery);
46
+ const apiServices = _react.useMemo.call(void 0,
47
+ () => _chunkJAMEOM7Tcjs.createApiServices.call(void 0, axiosInstance, finalEndpoint),
48
+ [axiosInstance, finalEndpoint]
49
+ );
50
+ const savedOnSuccess = _react.useRef.call(void 0, onSuccess);
51
+ const savedOnError = _react.useRef.call(void 0, onError);
52
+ _react.useEffect.call(void 0, () => {
53
+ savedOnSuccess.current = onSuccess;
54
+ savedOnError.current = onError;
55
+ }, [onSuccess, onError]);
56
+ const fetchData = _react.useCallback.call(void 0, async (currentQueryOptions) => {
57
+ setState((prev) => ({ ...prev, loading: true, error: null }));
58
+ try {
59
+ const finalQuery = currentQueryOptions || queryOptions;
60
+ const hasQueryParams = Object.keys(finalQuery).length > 0;
61
+ const queryString = _chunkJAMEOM7Tcjs.buildPaginateQuery.call(void 0, finalQuery);
62
+ const result = hasQueryParams ? await apiServices.getWithQuery(queryString, requestConfig) : await apiServices.get(void 0, requestConfig);
63
+ setState(result);
64
+ if (result.success && savedOnSuccess.current) {
65
+ savedOnSuccess.current(result.message || "Fetch successful!", _nullishCoalesce(result.data, () => ( void 0)));
66
+ } else if (!result.success && savedOnError.current) {
67
+ savedOnError.current(result.message || "Fetch failed", _nullishCoalesce(result.error, () => ( void 0)));
68
+ }
69
+ } catch (e) {
70
+ const apiError = { status: 500, message: e.message || "An unexpected client-side error occurred." };
71
+ setState((prev) => ({ ...prev, loading: false, error: apiError, success: false }));
72
+ if (savedOnError.current) {
73
+ savedOnError.current(apiError.message, apiError);
74
+ }
75
+ }
76
+ }, [apiServices, queryOptions, requestConfig]);
77
+ _react.useEffect.call(void 0, () => {
78
+ if (enabled) {
79
+ fetchData();
80
+ }
81
+ }, [enabled, fetchData]);
82
+ const handleActionResult = _react.useCallback.call(void 0, async (actionPromise) => {
83
+ setState((prev) => ({ ...prev, loading: true }));
84
+ try {
85
+ const result = await actionPromise;
86
+ if (result.success) {
87
+ if (savedOnSuccess.current) {
88
+ savedOnSuccess.current(result.message || "Action successful!", _nullishCoalesce(result.data, () => ( void 0)));
89
+ }
90
+ if (refetchAfterChange) {
91
+ await fetchData(queryOptions);
92
+ } else {
93
+ setState((prev) => ({ ...prev, ...result, loading: false }));
94
+ }
95
+ } else {
96
+ if (savedOnError.current) {
97
+ savedOnError.current(result.message || "Action failed", _nullishCoalesce(result.error, () => ( void 0)));
98
+ }
99
+ setState((prev) => ({ ...prev, loading: false, error: result.error, success: false }));
100
+ }
101
+ return result;
102
+ } catch (e) {
103
+ const apiError = { status: 500, message: e.message || "An unexpected error occurred during action." };
104
+ setState((prev) => ({ ...prev, loading: false, error: apiError, success: false }));
105
+ if (savedOnError.current) {
106
+ savedOnError.current(apiError.message, apiError);
107
+ }
108
+ return { data: null, error: apiError, loading: false, success: false, rawResponse: e };
109
+ }
110
+ }, [refetchAfterChange, fetchData, queryOptions]);
111
+ const refetch = _react.useCallback.call(void 0, () => {
112
+ fetchData();
113
+ }, [fetchData]);
114
+ const actions = {
115
+ fetch: fetchData,
116
+ create: (newItem, options) => handleActionResult(apiServices.post(newItem, options)),
117
+ put: (id, item, options) => handleActionResult(apiServices.put(id, item, options)),
118
+ update: (id, updatedItem, options) => handleActionResult(apiServices.patch(id, updatedItem, options)),
119
+ remove: (id, options) => handleActionResult(apiServices.remove(id, options)),
120
+ bulkRemove: (ids, options) => handleActionResult(apiServices.bulkDelete(ids, options))
121
+ };
122
+ const query = {
123
+ options: queryOptions,
124
+ refetch,
125
+ setOptions: setQueryOptions,
126
+ setPage: (page) => setQueryOptions((prev) => ({ ...prev, page })),
127
+ setLimit: (limit) => setQueryOptions((prev) => ({ ...prev, page: 1, limit })),
128
+ setSearchTerm: (search) => setQueryOptions((prev) => ({ ...prev, page: 1, search })),
129
+ setSorting: (sortBy) => setQueryOptions((prev) => ({ ...prev, sortBy })),
130
+ setFilters: (filter) => setQueryOptions((prev) => ({ ...prev, page: 1, filter })),
131
+ setQueryParam: (key, value) => setQueryOptions((prev) => ({ ...prev, [key]: value, page: key !== "page" ? 1 : value })),
132
+ reset: () => setQueryOptions(initialQuery)
133
+ };
134
+ return { state, setState, actions, query };
135
+ }
136
+
137
+ // src/hooks/useApiRecord/index.ts
138
+
139
+ function buildDynamicPath2(template, params) {
140
+ if (!params) return template;
141
+ let path = template;
142
+ for (const key in params) {
143
+ path = path.replace(new RegExp(`{${key}}`, "g"), String(params[key]));
144
+ }
145
+ return path;
146
+ }
147
+ function useApiRecord(axiosInstance, config) {
148
+ const {
149
+ endpoint,
150
+ pathParams,
151
+ recordId,
152
+ initialData,
153
+ enabled = true,
154
+ refetchAfterChange = true,
155
+ requestConfig,
156
+ onSuccess,
157
+ onError
158
+ } = config;
159
+ const finalEndpoint = _react.useMemo.call(void 0,
160
+ () => buildDynamicPath2(endpoint, pathParams),
161
+ [endpoint, pathParams]
162
+ );
163
+ const initialState = _react.useMemo.call(void 0, () => ({
164
+ data: _nullishCoalesce(initialData, () => ( null)),
165
+ rawResponse: null,
166
+ error: null,
167
+ loading: enabled && !!recordId,
168
+ success: false,
169
+ message: void 0,
170
+ validationErrors: void 0
171
+ }), [initialData, enabled, recordId]);
172
+ const [state, setState] = _react.useState.call(void 0, initialState);
173
+ const savedOnSuccess = _react.useRef.call(void 0, onSuccess);
174
+ const savedOnError = _react.useRef.call(void 0, onError);
175
+ _react.useEffect.call(void 0, () => {
176
+ savedOnSuccess.current = onSuccess;
177
+ savedOnError.current = onError;
178
+ }, [onSuccess, onError]);
179
+ const apiServices = _react.useMemo.call(void 0,
180
+ () => _chunkJAMEOM7Tcjs.createApiServices.call(void 0, axiosInstance, finalEndpoint),
181
+ [axiosInstance, finalEndpoint]
182
+ );
183
+ const fetchRecord = _react.useCallback.call(void 0, async () => {
184
+ if (!recordId) {
185
+ setState(initialState);
186
+ return;
187
+ }
188
+ setState((prev) => ({ ...prev, loading: true, error: null, success: false }));
189
+ try {
190
+ const result = await apiServices.get(recordId, requestConfig);
191
+ setState(result);
192
+ if (result.success && savedOnSuccess.current) {
193
+ savedOnSuccess.current(result.message || "Record fetched successfully!", _nullishCoalesce(result.data, () => ( void 0)));
194
+ } else if (!result.success && savedOnError.current) {
195
+ savedOnError.current(result.message || "Fetch failed", _nullishCoalesce(result.error, () => ( void 0)));
196
+ }
197
+ } catch (e) {
198
+ console.error("[useApiRecord Fetch Error]", e);
199
+ const apiError = {
200
+ status: _optionalChain([e, 'access', _ => _.response, 'optionalAccess', _2 => _2.status]) || 500,
201
+ message: e.message || "An unexpected client-side error occurred.",
202
+ code: e.code
203
+ };
204
+ setState((prev) => ({ ...prev, loading: false, success: false, error: apiError }));
205
+ if (savedOnError.current) {
206
+ savedOnError.current(apiError.message, apiError);
207
+ }
208
+ }
209
+ }, [apiServices, recordId, requestConfig, initialState]);
210
+ _react.useEffect.call(void 0, () => {
211
+ if (enabled) {
212
+ fetchRecord();
213
+ }
214
+ }, [enabled, fetchRecord]);
215
+ const handleActionResult = _react.useCallback.call(void 0,
216
+ async (actionPromise, options) => {
217
+ setState((prev) => ({ ...prev, loading: true }));
218
+ try {
219
+ const result = await actionPromise;
220
+ if (result.success) {
221
+ if (savedOnSuccess.current) {
222
+ savedOnSuccess.current(result.message || "Action successful!", result.data);
223
+ }
224
+ const shouldRefetch = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _3 => _3.refetch]), () => ( refetchAfterChange));
225
+ if (shouldRefetch) {
226
+ await fetchRecord();
227
+ } else {
228
+ setState({ ...result, loading: false, data: result.data });
229
+ }
230
+ } else {
231
+ if (savedOnError.current) {
232
+ savedOnError.current(result.message || "Action failed", _nullishCoalesce(result.error, () => ( void 0)));
233
+ }
234
+ setState((prev) => ({ ...prev, ...result, loading: false }));
235
+ }
236
+ return result;
237
+ } catch (e) {
238
+ console.error("[useApiRecord Action Error]", e);
239
+ const apiError = {
240
+ status: _optionalChain([e, 'access', _4 => _4.response, 'optionalAccess', _5 => _5.status]) || 500,
241
+ message: e.message || "An unexpected error occurred during the action.",
242
+ code: e.code
243
+ };
244
+ const errorResponse = { ...initialState, loading: false, success: false, error: apiError, rawResponse: e, data: null };
245
+ setState(errorResponse);
246
+ if (savedOnError.current) {
247
+ savedOnError.current(apiError.message, apiError);
248
+ }
249
+ return errorResponse;
250
+ }
251
+ },
252
+ [refetchAfterChange, fetchRecord, initialState]
253
+ );
254
+ const actions = {
255
+ fetch: fetchRecord,
256
+ update: (updatedItem, options) => handleActionResult(apiServices.patch(recordId, updatedItem, { ...requestConfig, ...options }), options),
257
+ put: (item, options) => handleActionResult(apiServices.put(recordId, item, { ...requestConfig, ...options }), options),
258
+ remove: (options) => handleActionResult(apiServices.remove(recordId, { ...requestConfig, ...options }), options),
259
+ resetState: () => setState(initialState)
260
+ };
261
+ return { state, setState, actions };
262
+ }
263
+
264
+ // src/hooks/useDeepCompareEffect/index.ts
265
+
266
+ var _fastdeepequal = require('fast-deep-equal'); var _fastdeepequal2 = _interopRequireDefault(_fastdeepequal);
267
+ function useDeepCompareEffect(callback, dependencies) {
268
+ const currentDependenciesRef = _react.useRef.call(void 0, );
269
+ if (!_fastdeepequal2.default.call(void 0, currentDependenciesRef.current, dependencies)) {
270
+ currentDependenciesRef.current = dependencies;
271
+ }
272
+ _react.useEffect.call(void 0, callback, [currentDependenciesRef.current]);
273
+ }
274
+
275
+ // src/hooks/useApiModule/useApiModule.ts
276
+
277
+ var ApiModuleContext = _react.createContext.call(void 0, null);
278
+ var ApiModuleProvider = ApiModuleContext.Provider;
279
+ var createInitialState = () => ({
280
+ data: null,
281
+ lastSuccessAt: void 0,
282
+ meta: void 0,
283
+ links: void 0,
284
+ validationErrors: [],
285
+ error: null,
286
+ loading: false,
287
+ success: false,
288
+ called: false,
289
+ isStale: false,
290
+ rawResponse: null
291
+ });
292
+ function useApiActionState(actionConfig, cacheKey, execute, input, enabled) {
293
+ const getClientSnapshot = () => _chunkJAMEOM7Tcjs.globalStateManager.getSnapshot(cacheKey);
294
+ const getServerSnapshot = () => _chunkJAMEOM7Tcjs.globalStateManager.getSnapshot(cacheKey);
295
+ const state = _react.useSyncExternalStore.call(void 0,
296
+ (callback) => _chunkJAMEOM7Tcjs.globalStateManager.subscribe(cacheKey, callback),
297
+ getClientSnapshot,
298
+ getServerSnapshot
299
+ );
300
+ const inputRef = _react.useRef.call(void 0, input);
301
+ _react.useEffect.call(void 0, () => {
302
+ inputRef.current = input;
303
+ }, [input]);
304
+ const refetch = _react.useCallback.call(void 0, () => {
305
+ execute(inputRef.current);
306
+ }, [execute]);
307
+ const prevCacheKeyRef = _react.useRef.call(void 0, cacheKey);
308
+ _react.useEffect.call(void 0, () => {
309
+ if (prevCacheKeyRef.current !== cacheKey && enabled && state.called) {
310
+ refetch();
311
+ } else if (enabled && actionConfig.autoFetch && !state.called && !state.loading) {
312
+ refetch();
313
+ } else if (enabled && state.isStale && !state.loading) {
314
+ refetch();
315
+ }
316
+ prevCacheKeyRef.current = cacheKey;
317
+ }, [cacheKey, enabled, state.isStale, state.loading, state.called, actionConfig.autoFetch, refetch]);
318
+ return state;
319
+ }
320
+ function useApiModule(axiosInstance, moduleConfig, options = {}) {
321
+ const {
322
+ refetchOnWindowFocus = true,
323
+ onSuccess,
324
+ onError,
325
+ pathParams: globalPathParams,
326
+ enabled = true,
327
+ hydratedState,
328
+ extraContextData,
329
+ urlSync,
330
+ defaultQueryOptions,
331
+ initialActionsToExecute
332
+ } = options;
333
+ const pathParamsString = _react.useMemo.call(void 0, () => JSON.stringify(globalPathParams || {}), [globalPathParams]);
334
+ const [queryOptions, setQueryOptions] = _react.useState.call(void 0, () => {
335
+ const initialOptions = {};
336
+ for (const actionName in moduleConfig.actions) {
337
+ const actionConfig = moduleConfig.actions[actionName];
338
+ if (actionConfig._input) {
339
+ initialOptions[actionName] = { ...actionConfig._input };
340
+ }
341
+ }
342
+ if (defaultQueryOptions) {
343
+ for (const actionName in defaultQueryOptions) {
344
+ initialOptions[actionName] = {
345
+ ...initialOptions[actionName],
346
+ ...defaultQueryOptions[actionName]
347
+ };
348
+ }
349
+ }
350
+ return initialOptions;
351
+ });
352
+ const lastCallRef = _react.useRef.call(void 0, {});
353
+ const initialFetchRef = _react.useRef.call(void 0, false);
354
+ const stableActionsRef = _react.useRef.call(void 0, {});
355
+ const savedCallbacks = _react.useRef.call(void 0, { onSuccess, onError });
356
+ _react.useEffect.call(void 0, () => {
357
+ savedCallbacks.current = { onSuccess, onError };
358
+ }, [onSuccess, onError]);
359
+ _react.useEffect.call(void 0, () => {
360
+ if (hydratedState) {
361
+ _chunkJAMEOM7Tcjs.globalStateManager.rehydrate(hydratedState);
362
+ }
363
+ }, [hydratedState]);
364
+ _react.useEffect.call(void 0, () => {
365
+ if (!urlSync) return;
366
+ const { searchParams, actionsToSync, defaultSyncAction } = urlSync;
367
+ const params = new URLSearchParams(searchParams);
368
+ const queryFromUrl = {};
369
+ params.forEach((value, key) => {
370
+ const parts = key.split(".");
371
+ const hasPrefix = parts.length > 1;
372
+ const actionName = hasPrefix ? parts[0] : defaultSyncAction;
373
+ const paramKey = hasPrefix ? parts[1] : parts[0];
374
+ if (actionName && paramKey && actionsToSync.some((a) => a === actionName)) {
375
+ if (!queryFromUrl[actionName]) queryFromUrl[actionName] = {};
376
+ const isNum = !isNaN(Number(value)) && value.trim() !== "";
377
+ queryFromUrl[actionName][paramKey] = isNum ? Number(value) : value;
378
+ }
379
+ });
380
+ if (Object.keys(queryFromUrl).length > 0) {
381
+ setQueryOptions((prev) => {
382
+ const newState = { ...prev };
383
+ for (const actionName in queryFromUrl) {
384
+ newState[actionName] = { ...newState[actionName], ...queryFromUrl[actionName] };
385
+ }
386
+ return newState;
387
+ });
388
+ }
389
+ }, [urlSync]);
390
+ _react.useEffect.call(void 0, () => {
391
+ if (!urlSync) return;
392
+ const { searchParams, updateUrl, actionsToSync, defaultSyncAction } = urlSync;
393
+ const currentParams = new URLSearchParams(searchParams);
394
+ let hasChanged = false;
395
+ for (const actionName in queryOptions) {
396
+ if (actionsToSync.some((a) => a === actionName)) {
397
+ const params = queryOptions[actionName];
398
+ const isDefaultAction = actionName === defaultSyncAction;
399
+ for (const key in params) {
400
+ const fullKey = isDefaultAction ? key : `${actionName}.${key}`;
401
+ const value = params[key];
402
+ const stringValue = value !== void 0 && value !== null ? String(value) : "";
403
+ if (currentParams.get(fullKey) !== stringValue) {
404
+ if (stringValue) currentParams.set(fullKey, stringValue);
405
+ else currentParams.delete(fullKey);
406
+ hasChanged = true;
407
+ }
408
+ }
409
+ }
410
+ }
411
+ if (hasChanged) {
412
+ updateUrl(currentParams.toString());
413
+ }
414
+ }, [queryOptions, urlSync]);
415
+ _react.useMemo.call(void 0, () => {
416
+ for (const actionName in moduleConfig.actions) {
417
+ const actionConfig = moduleConfig.actions[actionName];
418
+ const shouldCache = actionConfig.cacheResponse !== false;
419
+ const execute = async (input, options2 = {}) => {
420
+ lastCallRef.current[actionName] = { input, options: options2 };
421
+ const finalPathParams = { ...JSON.parse(pathParamsString), ...options2.pathParams };
422
+ let bodyForCall = input;
423
+ let requestConfig = options2.config || {};
424
+ if (actionConfig.method === "GET") {
425
+ const currentQueryOptions = queryOptions[actionName];
426
+ bodyForCall = { ...actionConfig._input, ...currentQueryOptions, ..._optionalChain([options2, 'access', _6 => _6.config, 'optionalAccess', _7 => _7.params]), ...input };
427
+ } else if (actionConfig.upload && input) {
428
+ bodyForCall = new FormData();
429
+ for (const key in input) {
430
+ bodyForCall.append(key, input[key]);
431
+ }
432
+ }
433
+ const cacheKey = shouldCache ? _chunkJAMEOM7Tcjs.generateCacheKey.call(void 0, moduleConfig.baseEndpoint, actionName, bodyForCall, { pathParams: finalPathParams }) : "";
434
+ let mutationContext;
435
+ try {
436
+ if (options2.onMutate && shouldCache) {
437
+ mutationContext = await options2.onMutate(input);
438
+ }
439
+ if (shouldCache) {
440
+ _chunkJAMEOM7Tcjs.globalStateManager.setState(cacheKey, (prev) => ({ ...prev, loading: true, called: true, error: null, isStale: false }));
441
+ }
442
+ const result = await _chunkJAMEOM7Tcjs.callDynamicApi.call(void 0, axiosInstance, moduleConfig.baseEndpoint, actionConfig, {
443
+ pathParams: finalPathParams,
444
+ body: bodyForCall,
445
+ config: requestConfig
446
+ });
447
+ if (shouldCache) {
448
+ _chunkJAMEOM7Tcjs.globalStateManager.setState(cacheKey, (prev) => ({
449
+ ...prev,
450
+ loading: false,
451
+ success: result.success,
452
+ error: result.success ? null : result.error || prev.error,
453
+ data: result.data,
454
+ meta: result.meta,
455
+ links: result.links,
456
+ message: result.message,
457
+ validationErrors: result.validationErrors || [],
458
+ rawResponse: result.rawResponse,
459
+ lastSuccessAt: result.success ? Date.now() : prev.lastSuccessAt
460
+ }));
461
+ }
462
+ if (result.success) {
463
+ _optionalChain([savedCallbacks, 'access', _8 => _8.current, 'access', _9 => _9.onSuccess, 'optionalCall', _10 => _10(actionName, result.message || "Action successful", result.data)]);
464
+ _optionalChain([options2, 'access', _11 => _11.onSuccess, 'optionalCall', _12 => _12(result.data, mutationContext)]);
465
+ _optionalChain([actionConfig, 'access', _13 => _13.invalidates, 'optionalAccess', _14 => _14.forEach, 'call', _15 => _15((keyToInvalidate) => {
466
+ const prefix = `${moduleConfig.baseEndpoint}/${keyToInvalidate}::`;
467
+ _chunkJAMEOM7Tcjs.globalStateManager.invalidateByPrefix(prefix);
468
+ })]);
469
+ } else {
470
+ _optionalChain([savedCallbacks, 'access', _16 => _16.current, 'access', _17 => _17.onError, 'optionalCall', _18 => _18(actionName, result.message || "Action failed", _nullishCoalesce(result.error, () => ( void 0)))]);
471
+ _optionalChain([options2, 'access', _19 => _19.onError, 'optionalCall', _20 => _20(result.error, mutationContext)]);
472
+ }
473
+ return result;
474
+ } catch (error) {
475
+ const apiError = _optionalChain([error, 'access', _21 => _21.response, 'optionalAccess', _22 => _22.data]) || { status: 500, message: error.message };
476
+ if (shouldCache) {
477
+ _chunkJAMEOM7Tcjs.globalStateManager.setState(cacheKey, (prev) => ({ ...prev, error: apiError, loading: false, success: false }));
478
+ }
479
+ _optionalChain([savedCallbacks, 'access', _23 => _23.current, 'access', _24 => _24.onError, 'optionalCall', _25 => _25(actionName, apiError.message, apiError)]);
480
+ _optionalChain([options2, 'access', _26 => _26.onError, 'optionalCall', _27 => _27(apiError, mutationContext)]);
481
+ throw error;
482
+ } finally {
483
+ if (options2.onSettled) {
484
+ options2.onSettled();
485
+ }
486
+ }
487
+ };
488
+ const reset = (input, options2 = {}) => {
489
+ if (shouldCache) {
490
+ const finalPathParams = { ...JSON.parse(pathParamsString), ...options2.pathParams };
491
+ const cacheKey = _chunkJAMEOM7Tcjs.generateCacheKey.call(void 0, moduleConfig.baseEndpoint, actionName, input, { pathParams: finalPathParams });
492
+ _chunkJAMEOM7Tcjs.globalStateManager.setState(cacheKey, () => createInitialState());
493
+ }
494
+ };
495
+ stableActionsRef.current[actionName] = { execute, reset };
496
+ }
497
+ }, [axiosInstance, moduleConfig, pathParamsString]);
498
+ const actions = _react.useMemo.call(void 0, () => stableActionsRef.current, []);
499
+ _react.useEffect.call(void 0, () => {
500
+ if (typeof window === "undefined" || initialFetchRef.current || !enabled) return;
501
+ const actionsToRun = initialActionsToExecute ? initialActionsToExecute.map(String) : Object.keys(moduleConfig.actions).filter(
502
+ (actionName) => moduleConfig.actions[actionName].autoFetch
503
+ );
504
+ actionsToRun.forEach((actionName) => {
505
+ const key = actionName;
506
+ const hydratedData = hydratedState ? JSON.parse(hydratedState) : {};
507
+ if (_optionalChain([hydratedData, 'access', _28 => _28[actionName], 'optionalAccess', _29 => _29.data])) {
508
+ return;
509
+ }
510
+ const actionConfig = moduleConfig.actions[key];
511
+ const executeAction = _optionalChain([actions, 'access', _30 => _30[key], 'optionalAccess', _31 => _31.execute]);
512
+ if (typeof executeAction === "function") {
513
+ const input = actionConfig.hasQuery ? queryOptions[actionName] : void 0;
514
+ executeAction(input);
515
+ }
516
+ });
517
+ initialFetchRef.current = true;
518
+ }, [actions, initialActionsToExecute, moduleConfig.actions, hydratedState, queryOptions, enabled]);
519
+ const queries = _react.useMemo.call(void 0, () => {
520
+ return Object.keys(moduleConfig.actions).reduce((acc, actionName) => {
521
+ const actionConfig = moduleConfig.actions[actionName];
522
+ if (_optionalChain([actionConfig, 'optionalAccess', _32 => _32.hasQuery])) {
523
+ const setActionQueryOptions = (updater) => {
524
+ const key = actionName;
525
+ setQueryOptions((prev) => ({ ...prev, [key]: typeof updater === "function" ? updater(prev[key] || {}) : updater }));
526
+ };
527
+ const refetch = () => {
528
+ const execute = actions[actionName].execute;
529
+ execute(queryOptions[actionName] || {});
530
+ };
531
+ acc[actionName] = {
532
+ options: queryOptions[actionName] || {},
533
+ refetch,
534
+ setOptions: setActionQueryOptions,
535
+ setPage: (page) => setActionQueryOptions((p) => ({ ...p, page })),
536
+ setLimit: (limit) => setActionQueryOptions((p) => ({ ...p, limit, page: 1 })),
537
+ setSearchTerm: (search) => setActionQueryOptions((p) => ({ ...p, search, page: 1 })),
538
+ setFilters: (filter) => setActionQueryOptions((p) => ({ ...p, filter, page: 1 })),
539
+ setSorting: (sortBy) => setActionQueryOptions((p) => ({ ...p, sortBy })),
540
+ setQueryParam: (key, value) => setActionQueryOptions((p) => ({ ...p, [key]: value, page: key !== "page" ? value : p.page })),
541
+ reset: () => setActionQueryOptions(actionConfig._input || {})
542
+ };
543
+ }
544
+ return acc;
545
+ }, {});
546
+ }, [actions, queryOptions, moduleConfig.actions]);
547
+ const states = {};
548
+ function isActionWithQuery(key, actions2) {
549
+ return _optionalChain([actions2, 'access', _33 => _33[key], 'optionalAccess', _34 => _34.hasQuery]) === true;
550
+ }
551
+ for (const actionName in moduleConfig.actions) {
552
+ if (Object.prototype.hasOwnProperty.call(moduleConfig.actions, actionName)) {
553
+ const key = actionName;
554
+ const actionConfig = moduleConfig.actions[key];
555
+ if (actionConfig.cacheResponse !== false) {
556
+ let currentQueryOptions;
557
+ if (isActionWithQuery(key, moduleConfig.actions)) {
558
+ currentQueryOptions = _optionalChain([queries, 'access', _35 => _35[key], 'optionalAccess', _36 => _36.options]);
559
+ }
560
+ const input = currentQueryOptions;
561
+ const pathParams = JSON.parse(pathParamsString);
562
+ const cacheKey = _chunkJAMEOM7Tcjs.generateCacheKey.call(void 0, moduleConfig.baseEndpoint, actionName, input, { pathParams });
563
+ states[actionName] = useApiActionState(actionConfig, cacheKey, actions[key].execute, input, enabled);
564
+ } else {
565
+ states[actionName] = createInitialState();
566
+ }
567
+ }
568
+ }
569
+ const lastBlurTimestamp = _react.useRef.call(void 0, Date.now());
570
+ _react.useEffect.call(void 0, () => {
571
+ if (!enabled || !refetchOnWindowFocus) return;
572
+ const onFocus = () => {
573
+ if (Date.now() - lastBlurTimestamp.current > 1e4) {
574
+ for (const actionName of Object.keys(moduleConfig.actions)) {
575
+ const state = states[actionName];
576
+ if (state && state.called && !state.loading) {
577
+ _chunkJAMEOM7Tcjs.globalStateManager.invalidateByPrefix(`${moduleConfig.baseEndpoint}/${actionName}::`);
578
+ }
579
+ }
580
+ }
581
+ };
582
+ const onBlur = () => {
583
+ lastBlurTimestamp.current = Date.now();
584
+ };
585
+ window.addEventListener("focus", onFocus);
586
+ window.addEventListener("blur", onBlur);
587
+ return () => {
588
+ window.removeEventListener("focus", onFocus);
589
+ window.removeEventListener("blur", onBlur);
590
+ };
591
+ }, [enabled, refetchOnWindowFocus, moduleConfig, states]);
592
+ const dehydrate = _react.useCallback.call(void 0, () => _chunkJAMEOM7Tcjs.globalStateManager.dehydrate(), []);
593
+ const finalApiReturn = _react.useMemo.call(void 0, () => ({
594
+ actions,
595
+ states,
596
+ queries,
597
+ dehydrate,
598
+ ...extraContextData || {}
599
+ }), [actions, states, queries, dehydrate, extraContextData]);
600
+ return finalApiReturn;
601
+ }
602
+
603
+ // src/hooks/useApiModule/apiModuleContext.ts
604
+
605
+ function createApiModuleContext() {
606
+ const Context = _react.createContext.call(void 0, null);
607
+ Context.displayName = "ApiModuleContext";
608
+ const Provider = ({ value, children }) => {
609
+ return _react.createElement.call(void 0, Context.Provider, { value }, children);
610
+ };
611
+ const useConsumer = () => {
612
+ const context = _react.useContext.call(void 0, Context);
613
+ if (!context) {
614
+ throw new Error("This component must be used within its corresponding ApiModuleProvider.");
615
+ }
616
+ return context;
617
+ };
618
+ return {
619
+ Context,
620
+ Provider,
621
+ useContext: useConsumer
622
+ };
623
+ }
624
+
625
+
626
+
627
+
628
+
629
+
630
+
631
+ exports.ApiModuleProvider = ApiModuleProvider; exports.createApiModuleContext = createApiModuleContext; exports.useApi = useApi; exports.useApiModule = useApiModule; exports.useApiRecord = useApiRecord; exports.useDeepCompareEffect = useDeepCompareEffect;
@@ -0,0 +1,50 @@
1
+ import { AxiosInstance } from 'axios';
2
+ import { U as UseApiConfig, A as ApiModuleConfig, a as UseApiModuleOptions, b as UseApiModuleReturn, M as ModuleStates, c as ModuleActions, d as ModuleQueries } from './apiModule.types-DEskFzOY.cjs';
3
+ import { U as UseApiRecordConfig, a as UseApiRecordReturn } from './useApiRecord.types-mpeiDoxm.cjs';
4
+ import * as react from 'react';
5
+ import { ReactNode } from 'react';
6
+
7
+ declare function useApi<T>(axiosInstance: AxiosInstance, config: UseApiConfig<T>): any;
8
+
9
+ /**
10
+ * A React hook for managing the lifecycle of a single API resource (a record).
11
+ * It handles fetching, updating, replacing, and deleting a record, while managing
12
+ * loading, error, and data states. It supports dynamic path parameters for flexible API routing.
13
+ *
14
+ * @template T The data type of the record being managed.
15
+ * @param {AxiosInstance} axiosInstance - The configured Axios instance for making API calls.
16
+ * @param {UseApiRecordConfig<T>} config - Configuration options for the hook.
17
+ * @returns {UseApiRecordReturn<T>} An object containing the state, actions, and setState function.
18
+ */
19
+ declare function useApiRecord<T>(axiosInstance: AxiosInstance, config: UseApiRecordConfig<T>): UseApiRecordReturn<T>;
20
+
21
+ type EffectCallback = () => (void | (() => void));
22
+ type DependencyList = readonly any[];
23
+ declare function useDeepCompareEffect(callback: EffectCallback, dependencies: DependencyList): void;
24
+
25
+ declare const ApiModuleProvider: react.Provider<{
26
+ states: ModuleStates<any>;
27
+ actions: ModuleActions<any>;
28
+ queries: ModuleQueries<any>;
29
+ dehydrate: () => string;
30
+ } | null>;
31
+ declare function useApiModule<TModule extends ApiModuleConfig<any>, TExtra extends object = {}>(axiosInstance: AxiosInstance, moduleConfig: TModule, options?: UseApiModuleOptions<TModule, TExtra>): UseApiModuleReturn<TModule['actions'], TExtra>;
32
+
33
+ /**
34
+ * Creates a strongly-typed React Context, Provider, and consumer hook for a specific API module.
35
+ * This pattern avoids the need for manual type assertions in consuming components.
36
+ *
37
+ * @template TActions - The shape of the actions in the API module.
38
+ * @template TExtra - The shape of any extra data passed via `extraContextData`.
39
+ * @returns An object containing the typed Context, Provider, and a `useContext` hook.
40
+ */
41
+ declare function createApiModuleContext<TActions extends Record<string, any>, TExtra extends object = {}>(): {
42
+ Context: react.Context<UseApiModuleReturn<TActions, TExtra> | null>;
43
+ Provider: ({ value, children }: {
44
+ value: UseApiModuleReturn<TActions, TExtra>;
45
+ children: ReactNode;
46
+ }) => react.FunctionComponentElement<react.ProviderProps<UseApiModuleReturn<TActions, TExtra> | null>>;
47
+ useContext: () => UseApiModuleReturn<TActions, TExtra>;
48
+ };
49
+
50
+ export { ApiModuleProvider, createApiModuleContext, useApi, useApiModule, useApiRecord, useDeepCompareEffect };