@oxog/requestkit 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.
@@ -0,0 +1,460 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import * as react from 'react';
3
+ import { ReactNode } from 'react';
4
+
5
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
6
+ type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream' | 'raw';
7
+ type ErrorCode = 'ERR_NETWORK' | 'ERR_TIMEOUT' | 'ERR_CANCELED' | 'ERR_BAD_REQUEST' | 'ERR_BAD_RESPONSE';
8
+ interface Progress {
9
+ loaded: number;
10
+ total: number;
11
+ percent: number;
12
+ }
13
+ type ProgressCallback = (progress: Progress) => void;
14
+ interface ParamsSerializer {
15
+ encode?: (params: Record<string, unknown>) => string;
16
+ arrayFormat?: 'indices' | 'brackets' | 'repeat' | 'comma';
17
+ }
18
+ type TransformFn = (data: unknown, headers?: Headers) => unknown;
19
+ type RequestHook = (config: InternalRequestConfig) => InternalRequestConfig | Promise<InternalRequestConfig>;
20
+ type ResponseHook = (response: Response) => Response | Promise<Response>;
21
+ type ErrorHook = (error: RequestError) => unknown;
22
+ interface RetryConfig {
23
+ /** Max retry attempts */
24
+ limit: number;
25
+ /** Methods to retry (default: GET, HEAD, OPTIONS, PUT, DELETE) */
26
+ methods?: HttpMethod[];
27
+ /** Status codes to retry (default: 408, 429, 500, 502, 503, 504) */
28
+ statusCodes?: number[];
29
+ /** Initial delay in ms (default: 1000) */
30
+ delay?: number;
31
+ /** Backoff strategy (default: exponential) */
32
+ backoff?: 'linear' | 'exponential';
33
+ /** Max delay in ms (default: 30000) */
34
+ maxDelay?: number;
35
+ /** Custom retry condition */
36
+ retryCondition?: (error: RequestError) => boolean;
37
+ /** Retry callback */
38
+ onRetry?: (attempt: number, error: RequestError, config: InternalRequestConfig) => void;
39
+ }
40
+ interface ClientConfig {
41
+ /** Base URL for all requests */
42
+ baseURL?: string;
43
+ /** Default headers */
44
+ headers?: HeadersInit | Record<string, string>;
45
+ /** Timeout in ms (0 = no timeout) */
46
+ timeout?: number;
47
+ /** Retry config or number of retries */
48
+ retry?: number | RetryConfig;
49
+ /** Response type (default: json) */
50
+ responseType?: ResponseType;
51
+ /** Credentials mode */
52
+ credentials?: RequestCredentials;
53
+ /** Cache mode */
54
+ cache?: RequestCache;
55
+ /** Request mode */
56
+ mode?: RequestMode;
57
+ /** Query params serialization */
58
+ paramsSerializer?: ParamsSerializer;
59
+ /** Status validation (default: 200-299) */
60
+ validateStatus?: (status: number) => boolean;
61
+ /** Transform request data */
62
+ transformRequest?: TransformFn | TransformFn[];
63
+ /** Transform response data */
64
+ transformResponse?: TransformFn | TransformFn[];
65
+ /** Request hook */
66
+ onRequest?: RequestHook;
67
+ /** Response hook */
68
+ onResponse?: ResponseHook;
69
+ /** Error hook */
70
+ onError?: ErrorHook;
71
+ }
72
+ interface RequestOptions extends Omit<ClientConfig, 'baseURL'> {
73
+ /** HTTP method */
74
+ method?: HttpMethod;
75
+ /** URL params (query string) */
76
+ params?: Record<string, unknown> | URLSearchParams;
77
+ /** Request body */
78
+ body?: BodyInit | Record<string, unknown>;
79
+ /** JSON body (auto-serialized) */
80
+ json?: Record<string, unknown>;
81
+ /** Form body (FormData or URLSearchParams) */
82
+ form?: Record<string, unknown> | FormData;
83
+ /** Abort signal */
84
+ signal?: AbortSignal;
85
+ /** Upload progress callback */
86
+ onUploadProgress?: ProgressCallback;
87
+ /** Download progress callback */
88
+ onDownloadProgress?: ProgressCallback;
89
+ /** Return cancelable request */
90
+ cancelable?: boolean;
91
+ /** Return raw response with metadata */
92
+ raw?: boolean;
93
+ }
94
+ interface InternalRequestConfig extends RequestOptions {
95
+ url: string;
96
+ method: HttpMethod;
97
+ headers: Headers;
98
+ baseURL?: string;
99
+ /** Internal: retry attempt tracking */
100
+ _retry?: boolean;
101
+ /** Internal: current retry count */
102
+ _retryCount?: number;
103
+ }
104
+ interface RequestError extends Error {
105
+ name: 'RequestError';
106
+ message: string;
107
+ status?: number;
108
+ statusText?: string;
109
+ data?: unknown;
110
+ config: InternalRequestConfig;
111
+ request?: Request;
112
+ response?: Response;
113
+ code?: ErrorCode;
114
+ }
115
+ interface InterceptorManager<T> {
116
+ /**
117
+ * Add an interceptor
118
+ * @returns Interceptor ID for removal
119
+ */
120
+ use(onFulfilled?: (value: T) => T | Promise<T>, onRejected?: (error: RequestError) => unknown): number;
121
+ /**
122
+ * Remove an interceptor by ID
123
+ */
124
+ eject(id: number): void;
125
+ /**
126
+ * Clear all interceptors
127
+ */
128
+ clear(): void;
129
+ }
130
+ interface Interceptors {
131
+ request: InterceptorManager<InternalRequestConfig>;
132
+ response: InterceptorManager<Response>;
133
+ }
134
+ interface RequestClient {
135
+ get<T = unknown>(url: string, options?: RequestOptions): Promise<T>;
136
+ post<T = unknown>(url: string, body?: unknown, options?: RequestOptions): Promise<T>;
137
+ put<T = unknown>(url: string, body?: unknown, options?: RequestOptions): Promise<T>;
138
+ patch<T = unknown>(url: string, body?: unknown, options?: RequestOptions): Promise<T>;
139
+ delete<T = unknown>(url: string, options?: RequestOptions): Promise<T>;
140
+ head(url: string, options?: RequestOptions): Promise<void>;
141
+ options(url: string, options?: RequestOptions): Promise<void>;
142
+ request<T = unknown>(url: string, options?: RequestOptions): Promise<T>;
143
+ request<T = unknown>(options: RequestOptions & {
144
+ url: string;
145
+ }): Promise<T>;
146
+ interceptors: Interceptors;
147
+ defaults: ClientConfig;
148
+ extend(config: ClientConfig): RequestClient;
149
+ clone(): RequestClient;
150
+ }
151
+ interface UseRequestOptions<T> {
152
+ /** Don't fetch on mount */
153
+ manual?: boolean;
154
+ /** Success callback */
155
+ onSuccess?: (data: T) => void;
156
+ /** Error callback */
157
+ onError?: (error: RequestError) => void;
158
+ }
159
+ interface UseRequestResult<T> {
160
+ data: T | undefined;
161
+ loading: boolean;
162
+ error: RequestError | null;
163
+ execute: (options?: RequestOptions) => Promise<T>;
164
+ reset: () => void;
165
+ }
166
+ interface UseQueryOptions<T> {
167
+ /** Enable/disable query */
168
+ enabled?: boolean;
169
+ /** Time until data is stale (ms) */
170
+ staleTime?: number;
171
+ /** Time to keep in cache (ms) */
172
+ cacheTime?: number;
173
+ /** Refetch on window focus */
174
+ refetchOnWindowFocus?: boolean;
175
+ /** Refetch on reconnect */
176
+ refetchOnReconnect?: boolean;
177
+ /** Polling interval (ms) */
178
+ refetchInterval?: number;
179
+ /** Retry failed requests */
180
+ retry?: number | boolean;
181
+ /** Success callback */
182
+ onSuccess?: (data: T) => void;
183
+ /** Error callback */
184
+ onError?: (error: RequestError) => void;
185
+ }
186
+ interface UseQueryResult<T> {
187
+ data: T | undefined;
188
+ loading: boolean;
189
+ error: RequestError | null;
190
+ isStale: boolean;
191
+ isFetching: boolean;
192
+ refetch: () => Promise<void>;
193
+ }
194
+ interface UseMutationOptions<T, V> {
195
+ /** Success callback */
196
+ onSuccess?: (data: T, variables: V) => void;
197
+ /** Error callback */
198
+ onError?: (error: RequestError, variables: V) => void;
199
+ /** Settled callback (always called) */
200
+ onSettled?: (data: T | undefined, error: RequestError | null, variables: V) => void;
201
+ }
202
+ interface UseMutationResult<T, V> {
203
+ data: T | undefined;
204
+ loading: boolean;
205
+ error: RequestError | null;
206
+ mutate: (variables: V) => void;
207
+ mutateAsync: (variables: V) => Promise<T>;
208
+ reset: () => void;
209
+ }
210
+ interface UseInfiniteQueryOptions<T> {
211
+ /** Get next page param from last page */
212
+ getNextPageParam: (lastPage: T, pages: T[]) => unknown | undefined;
213
+ /** Get previous page param from first page */
214
+ getPreviousPageParam?: (firstPage: T, pages: T[]) => unknown | undefined;
215
+ /** Enable/disable query */
216
+ enabled?: boolean;
217
+ /** Time until data is stale (ms) */
218
+ staleTime?: number;
219
+ /** Success callback */
220
+ onSuccess?: (data: T[]) => void;
221
+ /** Error callback */
222
+ onError?: (error: RequestError) => void;
223
+ }
224
+ interface UseInfiniteQueryResult<T> {
225
+ data: T[] | undefined;
226
+ loading: boolean;
227
+ error: RequestError | null;
228
+ isFetchingNextPage: boolean;
229
+ isFetchingPreviousPage: boolean;
230
+ hasNextPage: boolean;
231
+ hasPreviousPage: boolean;
232
+ fetchNextPage: () => Promise<void>;
233
+ fetchPreviousPage: () => Promise<void>;
234
+ refetch: () => Promise<void>;
235
+ }
236
+
237
+ interface RequestProviderProps {
238
+ /**
239
+ * The RequestKit client instance
240
+ */
241
+ client: RequestClient;
242
+ /**
243
+ * Children components
244
+ */
245
+ children: ReactNode;
246
+ }
247
+ /**
248
+ * Provider component for RequestKit
249
+ * Wrap your app with this to use the hooks
250
+ *
251
+ * @example
252
+ * ```tsx
253
+ * import { createClient } from '@oxog/requestkit'
254
+ * import { RequestProvider } from '@oxog/requestkit/react'
255
+ *
256
+ * const client = createClient({ baseURL: 'https://api.example.com' })
257
+ *
258
+ * function App() {
259
+ * return (
260
+ * <RequestProvider client={client}>
261
+ * <MyApp />
262
+ * </RequestProvider>
263
+ * )
264
+ * }
265
+ * ```
266
+ */
267
+ declare function RequestProvider({ client, children }: RequestProviderProps): react_jsx_runtime.JSX.Element;
268
+
269
+ /**
270
+ * Context for the RequestKit client
271
+ * Use RequestProvider to provide the client
272
+ */
273
+ declare const RequestContext: react.Context<RequestClient | null>;
274
+
275
+ /**
276
+ * useClient Hook
277
+ * Returns the RequestKit client from context
278
+ */
279
+
280
+ /**
281
+ * Get the RequestKit client from context
282
+ * Must be used within a RequestProvider
283
+ *
284
+ * @example
285
+ * ```tsx
286
+ * function MyComponent() {
287
+ * const client = useClient()
288
+ *
289
+ * const handleClick = async () => {
290
+ * const data = await client.get('/endpoint')
291
+ * console.log(data)
292
+ * }
293
+ *
294
+ * return <button onClick={handleClick}>Fetch</button>
295
+ * }
296
+ * ```
297
+ */
298
+ declare function useClient(): RequestClient;
299
+
300
+ /**
301
+ * useRequest Hook
302
+ * Manual request execution with state management
303
+ */
304
+
305
+ /**
306
+ * Hook for manual request execution
307
+ * Use this when you need to trigger requests manually (e.g., on button click)
308
+ *
309
+ * @example
310
+ * ```tsx
311
+ * function DeleteButton({ id }: { id: string }) {
312
+ * const { loading, error, execute } = useRequest<void>(
313
+ * `/items/${id}`,
314
+ * {
315
+ * manual: true,
316
+ * method: 'DELETE',
317
+ * onSuccess: () => toast.success('Deleted!'),
318
+ * }
319
+ * )
320
+ *
321
+ * return (
322
+ * <button onClick={() => execute()} disabled={loading}>
323
+ * {loading ? 'Deleting...' : 'Delete'}
324
+ * </button>
325
+ * )
326
+ * }
327
+ * ```
328
+ */
329
+ declare function useRequest<T = unknown>(url: string, options?: RequestOptions & UseRequestOptions<T>): UseRequestResult<T>;
330
+
331
+ /**
332
+ * useQuery Hook
333
+ * Auto-fetching data with caching and refetch support
334
+ */
335
+
336
+ /**
337
+ * Hook for data fetching with automatic execution
338
+ * Best for GET requests that should load on mount
339
+ *
340
+ * @example
341
+ * ```tsx
342
+ * function UserProfile({ userId }: { userId: string }) {
343
+ * const { data, loading, error, refetch } = useQuery<User>(
344
+ * `/users/${userId}`,
345
+ * {
346
+ * enabled: !!userId,
347
+ * staleTime: 60000,
348
+ * retry: 3,
349
+ * }
350
+ * )
351
+ *
352
+ * if (loading) return <Spinner />
353
+ * if (error) return <Error error={error} />
354
+ *
355
+ * return (
356
+ * <div>
357
+ * <h1>{data?.name}</h1>
358
+ * <button onClick={refetch}>Refresh</button>
359
+ * </div>
360
+ * )
361
+ * }
362
+ * ```
363
+ */
364
+ declare function useQuery<T = unknown>(url: string | (() => string | null), options?: RequestOptions & UseQueryOptions<T>): UseQueryResult<T>;
365
+
366
+ /**
367
+ * useMutation Hook
368
+ * For creating, updating, or deleting data
369
+ */
370
+
371
+ /**
372
+ * Hook for mutations (POST, PUT, PATCH, DELETE)
373
+ * Best for data modifications that need to be triggered by user actions
374
+ *
375
+ * @example
376
+ * ```tsx
377
+ * interface CreateUserInput {
378
+ * name: string
379
+ * email: string
380
+ * }
381
+ *
382
+ * function CreateUserForm() {
383
+ * const { mutate, loading, error } = useMutation<User, CreateUserInput>(
384
+ * (input) => client.post('/users', input),
385
+ * {
386
+ * onSuccess: (user) => {
387
+ * toast.success(`Created ${user.name}`)
388
+ * router.push(`/users/${user.id}`)
389
+ * },
390
+ * onError: (error) => {
391
+ * toast.error(error.message)
392
+ * },
393
+ * }
394
+ * )
395
+ *
396
+ * const handleSubmit = (e: FormEvent) => {
397
+ * e.preventDefault()
398
+ * mutate({ name: 'John', email: 'john@example.com' })
399
+ * }
400
+ *
401
+ * return (
402
+ * <form onSubmit={handleSubmit}>
403
+ * <button type="submit" disabled={loading}>
404
+ * {loading ? 'Creating...' : 'Create User'}
405
+ * </button>
406
+ * </form>
407
+ * )
408
+ * }
409
+ * ```
410
+ */
411
+ declare function useMutation<T = unknown, V = void>(mutationFn: (variables: V) => Promise<T>, options?: UseMutationOptions<T, V>): UseMutationResult<T, V>;
412
+
413
+ /**
414
+ * useInfiniteQuery Hook
415
+ * For paginated/infinite scroll data fetching
416
+ */
417
+
418
+ /**
419
+ * Hook for infinite/paginated queries
420
+ * Best for lists with load more or infinite scroll
421
+ *
422
+ * @example
423
+ * ```tsx
424
+ * interface UsersPage {
425
+ * users: User[]
426
+ * nextCursor?: string
427
+ * }
428
+ *
429
+ * function UserList() {
430
+ * const {
431
+ * data,
432
+ * loading,
433
+ * hasNextPage,
434
+ * isFetchingNextPage,
435
+ * fetchNextPage,
436
+ * } = useInfiniteQuery<UsersPage>(
437
+ * (pageParam) => `/users?cursor=${pageParam || ''}`,
438
+ * {
439
+ * getNextPageParam: (lastPage) => lastPage.nextCursor,
440
+ * }
441
+ * )
442
+ *
443
+ * const allUsers = data?.flatMap(page => page.users) || []
444
+ *
445
+ * return (
446
+ * <div>
447
+ * {allUsers.map(user => <UserCard key={user.id} user={user} />)}
448
+ * {hasNextPage && (
449
+ * <button onClick={fetchNextPage} disabled={isFetchingNextPage}>
450
+ * {isFetchingNextPage ? 'Loading...' : 'Load More'}
451
+ * </button>
452
+ * )}
453
+ * </div>
454
+ * )
455
+ * }
456
+ * ```
457
+ */
458
+ declare function useInfiniteQuery<T = unknown>(getUrl: (pageParam: unknown) => string, options: RequestOptions & UseInfiniteQueryOptions<T>): UseInfiniteQueryResult<T>;
459
+
460
+ export { RequestContext, RequestProvider, type RequestProviderProps, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutationOptions, type UseMutationResult, type UseQueryOptions, type UseQueryResult, type UseRequestOptions, type UseRequestResult, useClient, useInfiniteQuery, useMutation, useQuery, useRequest };