nuxt-openapi-hyperfetch 0.1.6-alpha.1 → 0.2.7-alpha.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.
Files changed (97) hide show
  1. package/CONTRIBUTING.md +291 -292
  2. package/INSTRUCTIONS.md +327 -327
  3. package/LICENSE +202 -202
  4. package/README.md +231 -227
  5. package/dist/cli/logger.d.ts +26 -0
  6. package/dist/cli/logger.js +36 -0
  7. package/dist/cli/logo.js +6 -6
  8. package/dist/generators/components/connector-generator/generator.d.ts +12 -0
  9. package/dist/generators/components/connector-generator/generator.js +116 -0
  10. package/dist/generators/components/connector-generator/templates.d.ts +18 -0
  11. package/dist/generators/components/connector-generator/templates.js +222 -0
  12. package/dist/generators/components/connector-generator/types.d.ts +32 -0
  13. package/dist/generators/components/connector-generator/types.js +7 -0
  14. package/dist/generators/components/schema-analyzer/index.d.ts +17 -0
  15. package/dist/generators/components/schema-analyzer/index.js +20 -0
  16. package/dist/generators/components/schema-analyzer/intent-detector.d.ts +17 -0
  17. package/dist/generators/components/schema-analyzer/intent-detector.js +143 -0
  18. package/dist/generators/components/schema-analyzer/openapi-reader.d.ts +11 -0
  19. package/dist/generators/components/schema-analyzer/openapi-reader.js +76 -0
  20. package/dist/generators/components/schema-analyzer/resource-grouper.d.ts +6 -0
  21. package/dist/generators/components/schema-analyzer/resource-grouper.js +132 -0
  22. package/dist/generators/components/schema-analyzer/schema-field-mapper.d.ts +35 -0
  23. package/dist/generators/components/schema-analyzer/schema-field-mapper.js +220 -0
  24. package/dist/generators/components/schema-analyzer/types.d.ts +156 -0
  25. package/dist/generators/components/schema-analyzer/types.js +7 -0
  26. package/dist/generators/nuxt-server/generator.d.ts +2 -1
  27. package/dist/generators/nuxt-server/generator.js +21 -21
  28. package/dist/generators/shared/runtime/apiHelpers.d.ts +98 -41
  29. package/dist/generators/shared/runtime/apiHelpers.js +97 -104
  30. package/dist/generators/shared/runtime/pagination.d.ts +168 -0
  31. package/dist/generators/shared/runtime/pagination.js +179 -0
  32. package/dist/generators/shared/runtime/useDeleteConnector.d.ts +16 -0
  33. package/dist/generators/shared/runtime/useDeleteConnector.js +93 -0
  34. package/dist/generators/shared/runtime/useDetailConnector.d.ts +14 -0
  35. package/dist/generators/shared/runtime/useDetailConnector.js +50 -0
  36. package/dist/generators/shared/runtime/useFormConnector.d.ts +19 -0
  37. package/dist/generators/shared/runtime/useFormConnector.js +113 -0
  38. package/dist/generators/shared/runtime/useListConnector.d.ts +25 -0
  39. package/dist/generators/shared/runtime/useListConnector.js +125 -0
  40. package/dist/generators/shared/runtime/zod-error-merger.d.ts +23 -0
  41. package/dist/generators/shared/runtime/zod-error-merger.js +106 -0
  42. package/dist/generators/shared/templates/api-callbacks-plugin.js +54 -11
  43. package/dist/generators/shared/templates/api-pagination-plugin.d.ts +51 -0
  44. package/dist/generators/shared/templates/api-pagination-plugin.js +152 -0
  45. package/dist/generators/use-async-data/generator.d.ts +2 -1
  46. package/dist/generators/use-async-data/generator.js +14 -14
  47. package/dist/generators/use-async-data/runtime/useApiAsyncData.js +130 -17
  48. package/dist/generators/use-async-data/runtime/useApiAsyncDataRaw.js +103 -13
  49. package/dist/generators/use-async-data/templates.js +20 -14
  50. package/dist/generators/use-fetch/generator.d.ts +2 -1
  51. package/dist/generators/use-fetch/generator.js +12 -12
  52. package/dist/generators/use-fetch/runtime/useApiRequest.js +149 -40
  53. package/dist/generators/use-fetch/templates.js +14 -14
  54. package/dist/index.js +25 -0
  55. package/dist/module/index.d.ts +4 -0
  56. package/dist/module/index.js +93 -0
  57. package/dist/module/types.d.ts +27 -0
  58. package/dist/module/types.js +1 -0
  59. package/docs/API-REFERENCE.md +886 -887
  60. package/docs/generated-components.md +615 -0
  61. package/docs/headless-composables-ui.md +569 -0
  62. package/eslint.config.js +13 -0
  63. package/package.json +29 -2
  64. package/src/cli/config.ts +140 -140
  65. package/src/cli/logger.ts +124 -66
  66. package/src/cli/logo.ts +25 -25
  67. package/src/cli/types.ts +50 -50
  68. package/src/generators/components/connector-generator/generator.ts +138 -0
  69. package/src/generators/components/connector-generator/templates.ts +254 -0
  70. package/src/generators/components/connector-generator/types.ts +34 -0
  71. package/src/generators/components/schema-analyzer/index.ts +44 -0
  72. package/src/generators/components/schema-analyzer/intent-detector.ts +187 -0
  73. package/src/generators/components/schema-analyzer/openapi-reader.ts +96 -0
  74. package/src/generators/components/schema-analyzer/resource-grouper.ts +166 -0
  75. package/src/generators/components/schema-analyzer/schema-field-mapper.ts +268 -0
  76. package/src/generators/components/schema-analyzer/types.ts +177 -0
  77. package/src/generators/nuxt-server/generator.ts +272 -270
  78. package/src/generators/shared/runtime/apiHelpers.ts +535 -481
  79. package/src/generators/shared/runtime/pagination.ts +323 -0
  80. package/src/generators/shared/runtime/useDeleteConnector.ts +109 -0
  81. package/src/generators/shared/runtime/useDetailConnector.ts +64 -0
  82. package/src/generators/shared/runtime/useFormConnector.ts +139 -0
  83. package/src/generators/shared/runtime/useListConnector.ts +148 -0
  84. package/src/generators/shared/runtime/zod-error-merger.ts +119 -0
  85. package/src/generators/shared/templates/api-callbacks-plugin.ts +399 -352
  86. package/src/generators/shared/templates/api-pagination-plugin.ts +158 -0
  87. package/src/generators/use-async-data/generator.ts +205 -204
  88. package/src/generators/use-async-data/runtime/useApiAsyncData.ts +329 -214
  89. package/src/generators/use-async-data/runtime/useApiAsyncDataRaw.ts +324 -230
  90. package/src/generators/use-async-data/templates.ts +257 -250
  91. package/src/generators/use-fetch/generator.ts +170 -169
  92. package/src/generators/use-fetch/runtime/useApiRequest.ts +354 -234
  93. package/src/generators/use-fetch/templates.ts +214 -214
  94. package/src/index.ts +303 -265
  95. package/src/module/index.ts +133 -0
  96. package/src/module/types.ts +31 -0
  97. package/src/generators/tanstack-query/generator.ts +0 -11
@@ -1,481 +1,535 @@
1
- // @ts-nocheck - This file runs in user's Nuxt project with different TypeScript config
2
- /**
3
- * Shared API Helpers - Used by both useFetch and useAsyncData wrappers
4
- * This file contains common logic for callbacks, transforms, and global configuration
5
- */
6
-
7
- /**
8
- * Context provided to onRequest interceptor
9
- */
10
- export interface RequestContext {
11
- /** Request URL */
12
- url: string;
13
- /** HTTP method */
14
- method: string;
15
- /** Request body (if any) */
16
- body?: any;
17
- /** Request headers */
18
- headers?: Record<string, string>;
19
- /** Query parameters */
20
- query?: Record<string, any>;
21
- }
22
-
23
- /**
24
- * Modified context that can be returned from onRequest
25
- */
26
- export interface ModifiedRequestContext {
27
- /** Modified request body */
28
- body?: any;
29
- /** Modified request headers */
30
- headers?: Record<string, string>;
31
- /** Modified query parameters */
32
- query?: Record<string, any>;
33
- }
34
-
35
- /**
36
- * Result context provided to onFinish callback
37
- */
38
- export interface FinishContext<T> {
39
- /** Response data (if successful) */
40
- data?: T;
41
- /** Error (if failed) */
42
- error?: any;
43
- /** Whether the request was successful */
44
- success: boolean;
45
- }
46
-
47
- /**
48
- * Global callbacks configuration
49
- * Can be provided via Nuxt plugin: $getGlobalApiCallbacks
50
- */
51
- export interface GlobalCallbacksConfig {
52
- /**
53
- * Optional URL patterns to match (Opción 3)
54
- * Only apply global callbacks to URLs matching these patterns
55
- * Supports wildcards: '/api/**', '/api/public/*', etc.
56
- * If omitted, callbacks apply to all requests
57
- */
58
- patterns?: string[];
59
-
60
- /**
61
- * Called before every request matching patterns
62
- * Return false to prevent local callback execution (Opción 2)
63
- * Return modified context to change request
64
- */
65
- onRequest?: (
66
- context: RequestContext
67
- ) =>
68
- | void
69
- | Promise<void>
70
- | ModifiedRequestContext
71
- | Promise<ModifiedRequestContext>
72
- | boolean
73
- | Promise<boolean>;
74
-
75
- /**
76
- * Called when request succeeds
77
- * Return false to prevent local callback execution (Opción 2)
78
- */
79
- onSuccess?: (data: any, context?: any) => void | Promise<void> | boolean | Promise<boolean>;
80
-
81
- /**
82
- * Called when request fails
83
- * Return false to prevent local callback execution (Opción 2)
84
- */
85
- onError?: (error: any, context?: any) => void | Promise<void> | boolean | Promise<boolean>;
86
-
87
- /**
88
- * Called when request finishes (success or error)
89
- * Return false to prevent local callback execution (Opción 2)
90
- */
91
- onFinish?: (context: FinishContext<any>) => void | Promise<void> | boolean | Promise<boolean>;
92
- }
93
-
94
- /**
95
- * Type for skipGlobalCallbacks option (Opción 1)
96
- * - true: skip all global callbacks
97
- * - array: skip specific callbacks by name
98
- */
99
- export type SkipGlobalCallbacks =
100
- | boolean
101
- | Array<'onRequest' | 'onSuccess' | 'onError' | 'onFinish'>;
102
-
103
- /**
104
- * Base options for API requests with lifecycle callbacks
105
- * This is extended by specific wrapper options (useFetch, useAsyncData)
106
- */
107
- export interface ApiRequestOptions<T = any> {
108
- /**
109
- * Called before the request is sent - can be used as an interceptor
110
- * Return modified body/headers to transform the request
111
- */
112
- onRequest?: (
113
- context: RequestContext
114
- ) => void | Promise<void> | ModifiedRequestContext | Promise<ModifiedRequestContext>;
115
-
116
- /** Called when the request succeeds with data (after transform/pick if provided) */
117
- onSuccess?: (data: any) => void | Promise<void>;
118
-
119
- /** Called when the request fails with an error */
120
- onError?: (error: any) => void | Promise<void>;
121
-
122
- /** Called when the request finishes (success or error) with result context */
123
- onFinish?: (context: FinishContext<any>) => void | Promise<void>;
124
-
125
- /**
126
- * Skip global callbacks for this specific request (Opción 1)
127
- * - true: skip all global callbacks
128
- * - ['onSuccess', 'onError']: skip specific callbacks
129
- * - false/undefined: use global callbacks (default)
130
- * @example
131
- * skipGlobalCallbacks: true // Skip all global callbacks
132
- * skipGlobalCallbacks: ['onSuccess'] // Skip only global onSuccess
133
- */
134
- skipGlobalCallbacks?: SkipGlobalCallbacks;
135
-
136
- /**
137
- * Transform the response data
138
- * @example
139
- * transform: (pet) => ({ displayName: pet.name, isAvailable: pet.status === 'available' })
140
- */
141
- transform?: (data: T) => any;
142
-
143
- /**
144
- * Pick specific keys from the response (applied before transform)
145
- * Supports dot notation for nested paths
146
- * @example
147
- * pick: ['id', 'name'] as const
148
- * pick: ['person.name', 'person.email', 'status']
149
- */
150
- pick?: ReadonlyArray<string>;
151
- }
152
-
153
- /**
154
- * Helper function to apply request modifications from onRequest interceptor
155
- */
156
- export function applyRequestModifications(
157
- options: Record<string, any>,
158
- modifications: ModifiedRequestContext
159
- ): void {
160
- if (modifications.body !== undefined) {
161
- options.body = modifications.body;
162
- }
163
- if (modifications.headers !== undefined) {
164
- options.headers = {
165
- ...options.headers,
166
- ...modifications.headers,
167
- };
168
- }
169
- if (modifications.query !== undefined) {
170
- options.query = {
171
- ...options.query,
172
- ...modifications.query,
173
- };
174
- }
175
- }
176
-
177
- /**
178
- * Helper function to pick specific keys from an object
179
- * Supports dot notation for nested paths (e.g., 'person.name')
180
- */
181
- export function applyPick<T>(data: T, paths: ReadonlyArray<string>): any {
182
- const result: any = {};
183
-
184
- for (const path of paths) {
185
- const keys = path.split('.');
186
-
187
- // Navigate to the nested value
188
- let value: any = data;
189
- let exists = true;
190
-
191
- for (const key of keys) {
192
- if (value && typeof value === 'object' && key in value) {
193
- value = value[key];
194
- } else {
195
- exists = false;
196
- break;
197
- }
198
- }
199
-
200
- // Set the value in the result, maintaining nested structure
201
- if (exists) {
202
- let current = result;
203
- for (let i = 0; i < keys.length - 1; i++) {
204
- const key = keys[i];
205
- if (!(key in current)) {
206
- current[key] = {};
207
- }
208
- current = current[key];
209
- }
210
- current[keys[keys.length - 1]] = value;
211
- }
212
- }
213
-
214
- return result;
215
- }
216
-
217
- /**
218
- * Helper function to get global headers from user configuration
219
- * Supports two methods:
220
- * 1. Auto-imported composable: composables/useApiHeaders.ts
221
- * 2. Nuxt plugin provide: plugins/api-config.ts with $getApiHeaders
222
- */
223
- export function getGlobalHeaders(): Record<string, string> {
224
- let headers: Record<string, string> = {};
225
-
226
- // Method 1: Try to use auto-imported composable (useApiHeaders)
227
- try {
228
- // @ts-ignore - useApiHeaders may or may not exist (user-defined)
229
- if (typeof useApiHeaders !== 'undefined') {
230
- // @ts-ignore
231
- const getHeaders = useApiHeaders();
232
- if (getHeaders) {
233
- const h = typeof getHeaders === 'function' ? getHeaders() : getHeaders;
234
- if (h && typeof h === 'object') {
235
- headers = { ...headers, ...h };
236
- }
237
- }
238
- }
239
- } catch (e) {
240
- // useApiHeaders doesn't exist or failed, that's OK
241
- }
242
-
243
- // Method 2: Try to use Nuxt App plugin ($getApiHeaders)
244
- try {
245
- const nuxtApp = useNuxtApp();
246
- // @ts-ignore - $getApiHeaders may or may not exist (user-defined)
247
- if (nuxtApp.$getApiHeaders) {
248
- // @ts-ignore
249
- const h = nuxtApp.$getApiHeaders();
250
- if (h && typeof h === 'object') {
251
- headers = { ...headers, ...h };
252
- }
253
- }
254
- } catch (e) {
255
- // useNuxtApp not available or plugin not configured, that's OK
256
- }
257
-
258
- return headers;
259
- }
260
-
261
- /**
262
- * Helper function to get global callbacks from user configuration
263
- * Uses Nuxt plugin provide: plugins/api-callbacks.ts with $getGlobalApiCallbacks
264
- */
265
- export function getGlobalCallbacks(): GlobalCallbacksConfig {
266
- try {
267
- const nuxtApp = useNuxtApp();
268
- // @ts-ignore - $getGlobalApiCallbacks may or may not exist (user-defined)
269
- if (nuxtApp.$getGlobalApiCallbacks) {
270
- // @ts-ignore
271
- const callbacks = nuxtApp.$getGlobalApiCallbacks();
272
- if (callbacks && typeof callbacks === 'object') {
273
- return callbacks;
274
- }
275
- }
276
- } catch (e) {
277
- // useNuxtApp not available or plugin not configured, that's OK
278
- }
279
-
280
- return {};
281
- }
282
-
283
- /**
284
- * Helper function to get the global base URL from runtimeConfig.public.apiBaseUrl
285
- * Returns the configured URL or undefined if not set or not in a Nuxt context.
286
- */
287
- export function getGlobalBaseUrl(): string | undefined {
288
- try {
289
- const runtimeConfig = useRuntimeConfig();
290
- const url = runtimeConfig?.public?.apiBaseUrl as string | undefined;
291
- return url || undefined;
292
- } catch {
293
- // useRuntimeConfig not available outside Nuxt context, that's OK
294
- return undefined;
295
- }
296
- }
297
-
298
- /**
299
- * Check if a global callback should be applied to a specific request
300
- * Implements Opción 1 (skipGlobalCallbacks) and Opción 3 (pattern matching)
301
- */
302
- export function shouldApplyGlobalCallback(
303
- url: string,
304
- callbackName: 'onRequest' | 'onSuccess' | 'onError' | 'onFinish',
305
- patterns?: string[],
306
- skipConfig?: SkipGlobalCallbacks
307
- ): boolean {
308
- // Opción 1: Check if callback is skipped via skipGlobalCallbacks
309
- if (skipConfig === true) {
310
- return false; // Skip all global callbacks
311
- }
312
-
313
- if (Array.isArray(skipConfig) && skipConfig.includes(callbackName)) {
314
- return false; // Skip this specific callback
315
- }
316
-
317
- // Opción 3: Check pattern matching
318
- if (patterns && patterns.length > 0) {
319
- return patterns.some((pattern) => {
320
- // Convert glob pattern to regex
321
- // ** matches any characters including /
322
- // * matches any characters except /
323
- const regexPattern = pattern
324
- .replace(/\*\*/g, '@@DOUBLE_STAR@@')
325
- .replace(/\*/g, '[^/]*')
326
- .replace(/@@DOUBLE_STAR@@/g, '.*');
327
-
328
- const regex = new RegExp('^' + regexPattern + '$');
329
- return regex.test(url);
330
- });
331
- }
332
-
333
- // By default, apply global callback
334
- return true;
335
- }
336
-
337
- /**
338
- * Merge local and global callbacks with proper execution order
339
- * Implements all 3 options:
340
- * - Opción 1: skipGlobalCallbacks to disable global callbacks
341
- * - Opción 2: global callbacks can return false to prevent local execution
342
- * - Opción 3: pattern matching to apply callbacks only to matching URLs
343
- */
344
- export function mergeCallbacks(
345
- url: string,
346
- localCallbacks: {
347
- onRequest?: Function;
348
- onSuccess?: Function;
349
- onError?: Function;
350
- onFinish?: Function;
351
- },
352
- skipConfig?: SkipGlobalCallbacks
353
- ) {
354
- const global = getGlobalCallbacks();
355
-
356
- return {
357
- /**
358
- * Merged onRequest callback
359
- * Executes global first, then local
360
- * Global can return modifications or false to cancel local
361
- */
362
- onRequest: async (ctx: RequestContext) => {
363
- // Execute global onRequest
364
- if (
365
- shouldApplyGlobalCallback(url, 'onRequest', global.patterns, skipConfig) &&
366
- global.onRequest
367
- ) {
368
- try {
369
- const result = await global.onRequest(ctx);
370
-
371
- // Opción 2: If global returns false, don't execute local
372
- if (result === false) {
373
- return;
374
- }
375
-
376
- // If global returns modified context, use it
377
- if (result && typeof result === 'object' && !('then' in result)) {
378
- return result;
379
- }
380
- } catch (error) {
381
- console.error('Error in global onRequest callback:', error);
382
- }
383
- }
384
-
385
- // Execute local onRequest
386
- if (localCallbacks.onRequest) {
387
- return await localCallbacks.onRequest(ctx);
388
- }
389
- },
390
-
391
- /**
392
- * Merged onSuccess callback
393
- * Executes global first, then local (if global doesn't return false)
394
- */
395
- onSuccess: async (data: any, context?: any) => {
396
- let continueLocal = true;
397
-
398
- // Execute global onSuccess
399
- if (
400
- shouldApplyGlobalCallback(url, 'onSuccess', global.patterns, skipConfig) &&
401
- global.onSuccess
402
- ) {
403
- try {
404
- const result = await global.onSuccess(data, context);
405
-
406
- // Opción 2: If global returns false, don't execute local
407
- if (result === false) {
408
- continueLocal = false;
409
- }
410
- } catch (error) {
411
- console.error('Error in global onSuccess callback:', error);
412
- }
413
- }
414
-
415
- // Execute local onSuccess (if not cancelled)
416
- if (continueLocal && localCallbacks.onSuccess) {
417
- await localCallbacks.onSuccess(data, context);
418
- }
419
- },
420
-
421
- /**
422
- * Merged onError callback
423
- * Executes global first, then local (if global doesn't return false)
424
- */
425
- onError: async (error: any, context?: any) => {
426
- let continueLocal = true;
427
-
428
- // Execute global onError
429
- if (
430
- shouldApplyGlobalCallback(url, 'onError', global.patterns, skipConfig) &&
431
- global.onError
432
- ) {
433
- try {
434
- const result = await global.onError(error, context);
435
-
436
- // Opción 2: If global returns false, don't execute local
437
- if (result === false) {
438
- continueLocal = false;
439
- }
440
- } catch (error) {
441
- console.error('Error in global onError callback:', error);
442
- }
443
- }
444
-
445
- // Execute local onError (if not cancelled)
446
- if (continueLocal && localCallbacks.onError) {
447
- await localCallbacks.onError(error, context);
448
- }
449
- },
450
-
451
- /**
452
- * Merged onFinish callback
453
- * Executes global first, then local (if global doesn't return false)
454
- */
455
- onFinish: async (context: any) => {
456
- let continueLocal = true;
457
-
458
- // Execute global onFinish
459
- if (
460
- shouldApplyGlobalCallback(url, 'onFinish', global.patterns, skipConfig) &&
461
- global.onFinish
462
- ) {
463
- try {
464
- const result = await global.onFinish(context);
465
-
466
- // Opción 2: If global returns false, don't execute local
467
- if (result === false) {
468
- continueLocal = false;
469
- }
470
- } catch (error) {
471
- console.error('Error in global onFinish callback:', error);
472
- }
473
- }
474
-
475
- // Execute local onFinish (if not cancelled)
476
- if (continueLocal && localCallbacks.onFinish) {
477
- await localCallbacks.onFinish(context);
478
- }
479
- },
480
- };
481
- }
1
+ // @ts-nocheck - This file runs in user's Nuxt project with different TypeScript config
2
+ /**
3
+ * Shared API Helpers - Used by both useFetch and useAsyncData wrappers
4
+ * This file contains common logic for callbacks, transforms, and global configuration
5
+ */
6
+
7
+ /**
8
+ * Context provided to onRequest interceptor
9
+ */
10
+ export interface RequestContext {
11
+ /** Request URL */
12
+ url: string;
13
+ /** HTTP method */
14
+ method: string;
15
+ /** Request body (if any) */
16
+ body?: any;
17
+ /** Request headers */
18
+ headers?: Record<string, string>;
19
+ /** Query parameters */
20
+ query?: Record<string, any>;
21
+ }
22
+
23
+ /**
24
+ * Modified context that can be returned from onRequest
25
+ */
26
+ export interface ModifiedRequestContext {
27
+ /** Modified request body */
28
+ body?: any;
29
+ /** Modified request headers */
30
+ headers?: Record<string, string>;
31
+ /** Modified query parameters */
32
+ query?: Record<string, any>;
33
+ }
34
+
35
+ /**
36
+ * Result context provided to onFinish callback
37
+ */
38
+ export interface FinishContext<T> {
39
+ /** Response data (if successful) */
40
+ data?: T;
41
+ /** Error (if failed) */
42
+ error?: any;
43
+ /** Whether the request was successful */
44
+ success: boolean;
45
+ }
46
+
47
+ /**
48
+ * A single rule in the global callbacks configuration.
49
+ * Each rule independently targets specific URL patterns and/or HTTP methods.
50
+ * Rules are executed in order; any rule may return false to suppress the local callback.
51
+ */
52
+ export interface GlobalCallbacksRule {
53
+ /**
54
+ * URL glob patterns — only apply this rule to matching URLs.
55
+ * Supports wildcards: '/api/**', '/api/public/*', etc.
56
+ * If omitted, the rule applies to all URLs.
57
+ */
58
+ patterns?: string[];
59
+
60
+ /**
61
+ * HTTP methods only apply this rule to matching methods (case-insensitive).
62
+ * Example: ['DELETE', 'POST']
63
+ * If omitted, the rule applies to all methods.
64
+ */
65
+ methods?: string[];
66
+
67
+ /**
68
+ * Called before the request is sent.
69
+ * Return modified context (headers/body/query) to alter the request.
70
+ * Return false to prevent local onRequest execution (Opción 2).
71
+ */
72
+ onRequest?: (
73
+ context: RequestContext
74
+ ) =>
75
+ | void
76
+ | Promise<void>
77
+ | ModifiedRequestContext
78
+ | Promise<ModifiedRequestContext>
79
+ | boolean
80
+ | Promise<boolean>;
81
+
82
+ /**
83
+ * Called when the request succeeds.
84
+ * Return false to prevent local onSuccess execution (Opción 2).
85
+ */
86
+ onSuccess?: (data: any, context?: any) => void | Promise<void> | boolean | Promise<boolean>;
87
+
88
+ /**
89
+ * Called when the request fails.
90
+ * Return false to prevent local onError execution (Opción 2).
91
+ */
92
+ onError?: (error: any, context?: any) => void | Promise<void> | boolean | Promise<boolean>;
93
+
94
+ /**
95
+ * Called when the request finishes (success or error).
96
+ * Return false to prevent local onFinish execution (Opción 2).
97
+ */
98
+ onFinish?: (context: FinishContext<any>) => void | Promise<void> | boolean | Promise<boolean>;
99
+ }
100
+
101
+ /**
102
+ * Global callbacks configuration.
103
+ * Accepts a single rule (backward-compatible) or an array of rules.
104
+ * Each rule can independently target URLs and HTTP methods.
105
+ * Provided via Nuxt plugin: $getGlobalApiCallbacks
106
+ *
107
+ * @example Single rule (backward-compatible)
108
+ * getGlobalApiCallbacks: () => ({ onError: (e) => console.error(e) })
109
+ *
110
+ * @example Multiple rules with method/pattern targeting
111
+ * getGlobalApiCallbacks: () => [
112
+ * { onRequest: (ctx) => console.log(ctx.url) },
113
+ * { methods: ['DELETE'], onSuccess: () => toast.success('Deleted!') },
114
+ * { patterns: ['/api/private/**'], onRequest: () => ({ headers: { Authorization: '...' } }) },
115
+ * ]
116
+ */
117
+ export type GlobalCallbacksConfig = GlobalCallbacksRule | GlobalCallbacksRule[];
118
+
119
+ /**
120
+ * Type for skipGlobalCallbacks option (Opción 1)
121
+ * - true: skip all global callbacks
122
+ * - array: skip specific callbacks by name
123
+ */
124
+ export type SkipGlobalCallbacks =
125
+ | boolean
126
+ | Array<'onRequest' | 'onSuccess' | 'onError' | 'onFinish'>;
127
+
128
+ /**
129
+ * Base options for API requests with lifecycle callbacks
130
+ * This is extended by specific wrapper options (useFetch, useAsyncData)
131
+ */
132
+ export interface ApiRequestOptions<T = any> {
133
+ /**
134
+ * Called before the request is sent - can be used as an interceptor
135
+ * Return modified body/headers to transform the request
136
+ */
137
+ onRequest?: (
138
+ context: RequestContext
139
+ ) => void | Promise<void> | ModifiedRequestContext | Promise<ModifiedRequestContext>;
140
+
141
+ /** Called when the request succeeds with data (after transform/pick if provided) */
142
+ onSuccess?: (data: any) => void | Promise<void>;
143
+
144
+ /** Called when the request fails with an error */
145
+ onError?: (error: any) => void | Promise<void>;
146
+
147
+ /** Called when the request finishes (success or error) with result context */
148
+ onFinish?: (context: FinishContext<any>) => void | Promise<void>;
149
+
150
+ /**
151
+ * Skip global callbacks for this specific request (Opción 1)
152
+ * - true: skip all global callbacks
153
+ * - ['onSuccess', 'onError']: skip specific callbacks
154
+ * - false/undefined: use global callbacks (default)
155
+ * @example
156
+ * skipGlobalCallbacks: true // Skip all global callbacks
157
+ * skipGlobalCallbacks: ['onSuccess'] // Skip only global onSuccess
158
+ */
159
+ skipGlobalCallbacks?: SkipGlobalCallbacks;
160
+
161
+ /**
162
+ * Transform the response data
163
+ * @example
164
+ * transform: (pet) => ({ displayName: pet.name, isAvailable: pet.status === 'available' })
165
+ */
166
+ transform?: (data: T) => any;
167
+
168
+ /**
169
+ * Pick specific keys from the response (applied before transform)
170
+ * Supports dot notation for nested paths
171
+ * @example
172
+ * pick: ['id', 'name'] as const
173
+ * pick: ['person.name', 'person.email', 'status']
174
+ */
175
+ pick?: ReadonlyArray<string>;
176
+
177
+ /**
178
+ * Custom cache key for useAsyncData. If provided, used as-is instead of the auto-generated key.
179
+ * Useful for manual cache control or sharing cache between components.
180
+ */
181
+ cacheKey?: string;
182
+
183
+ // --- Pagination options ---
184
+
185
+ /**
186
+ * Enable pagination for this request.
187
+ * When true, the composable injects page/perPage params and exposes `pagination` state + helpers.
188
+ * Uses global pagination config by default (set via plugins/api-pagination.ts).
189
+ * @example
190
+ * const { data, pagination, goToPage, nextPage, prevPage, setPerPage } = useGetPets(params, { paginated: true })
191
+ */
192
+ paginated?: boolean;
193
+
194
+ /**
195
+ * Initial page number. Defaults to global config default (usually 1).
196
+ */
197
+ initialPage?: number;
198
+
199
+ /**
200
+ * Initial page size. Defaults to global config default (usually 20).
201
+ */
202
+ initialPerPage?: number;
203
+
204
+ /**
205
+ * Per-request pagination config override.
206
+ * Takes priority over the global pagination config set in plugins/api-pagination.ts.
207
+ * Useful when one specific endpoint has a different pagination convention.
208
+ */
209
+ paginationConfig?: import('./pagination.js').PaginationConfig;
210
+
211
+ // --- Common fetch options (available in all composables) ---
212
+
213
+ /** Base URL prepended to every request URL. Overrides runtimeConfig.public.apiBaseUrl. */
214
+ baseURL?: string;
215
+
216
+ /** HTTP method (GET, POST, PUT, PATCH, DELETE, etc.) */
217
+ method?: string;
218
+
219
+ /** Request body */
220
+ body?: any;
221
+
222
+ /** Request headers */
223
+ headers?: Record<string, string> | HeadersInit;
224
+
225
+ /** URL query parameters */
226
+ query?: Record<string, any>;
227
+
228
+ /** Alias for query */
229
+ params?: Record<string, any>;
230
+ }
231
+
232
+ /**
233
+ * Helper function to apply request modifications from onRequest interceptor
234
+ */
235
+ export function applyRequestModifications(
236
+ options: Record<string, any>,
237
+ modifications: ModifiedRequestContext
238
+ ): void {
239
+ if (modifications.body !== undefined) {
240
+ options.body = modifications.body;
241
+ }
242
+ if (modifications.headers !== undefined) {
243
+ options.headers = {
244
+ ...options.headers,
245
+ ...modifications.headers,
246
+ };
247
+ }
248
+ if (modifications.query !== undefined) {
249
+ options.query = {
250
+ ...options.query,
251
+ ...modifications.query,
252
+ };
253
+ }
254
+ }
255
+
256
+ /**
257
+ * Helper function to pick specific keys from an object
258
+ * Supports dot notation for nested paths (e.g., 'person.name')
259
+ */
260
+ export function applyPick<T>(data: T, paths: ReadonlyArray<string>): any {
261
+ const result: any = {};
262
+
263
+ for (const path of paths) {
264
+ const keys = path.split('.');
265
+
266
+ // Navigate to the nested value
267
+ let value: any = data;
268
+ let exists = true;
269
+
270
+ for (const key of keys) {
271
+ if (value && typeof value === 'object' && key in value) {
272
+ value = value[key];
273
+ } else {
274
+ exists = false;
275
+ break;
276
+ }
277
+ }
278
+
279
+ // Set the value in the result, maintaining nested structure
280
+ if (exists) {
281
+ let current = result;
282
+ for (let i = 0; i < keys.length - 1; i++) {
283
+ const key = keys[i];
284
+ if (!(key in current)) {
285
+ current[key] = {};
286
+ }
287
+ current = current[key];
288
+ }
289
+ current[keys[keys.length - 1]] = value;
290
+ }
291
+ }
292
+
293
+ return result;
294
+ }
295
+
296
+ /**
297
+ * Helper function to get global headers from user configuration
298
+ * Supports two methods:
299
+ * 1. Auto-imported composable: composables/useApiHeaders.ts
300
+ * 2. Nuxt plugin provide: plugins/api-config.ts with $getApiHeaders
301
+ */
302
+ export function getGlobalHeaders(): Record<string, string> {
303
+ let headers: Record<string, string> = {};
304
+
305
+ // Method 1: Try to use auto-imported composable (useApiHeaders)
306
+ try {
307
+ // @ts-ignore - useApiHeaders may or may not exist (user-defined)
308
+ if (typeof useApiHeaders !== 'undefined') {
309
+ // @ts-ignore
310
+ const getHeaders = useApiHeaders();
311
+ if (getHeaders) {
312
+ const h = typeof getHeaders === 'function' ? getHeaders() : getHeaders;
313
+ if (h && typeof h === 'object') {
314
+ headers = { ...headers, ...h };
315
+ }
316
+ }
317
+ }
318
+ } catch (e) {
319
+ // useApiHeaders doesn't exist or failed, that's OK
320
+ }
321
+
322
+ // Method 2: Try to use Nuxt App plugin ($getApiHeaders)
323
+ try {
324
+ const nuxtApp = useNuxtApp();
325
+ // @ts-ignore - $getApiHeaders may or may not exist (user-defined)
326
+ if (nuxtApp.$getApiHeaders) {
327
+ // @ts-ignore
328
+ const h = nuxtApp.$getApiHeaders();
329
+ if (h && typeof h === 'object') {
330
+ headers = { ...headers, ...h };
331
+ }
332
+ }
333
+ } catch (e) {
334
+ // useNuxtApp not available or plugin not configured, that's OK
335
+ }
336
+
337
+ return headers;
338
+ }
339
+
340
+ /**
341
+ * Helper function to get global callback rules from user configuration.
342
+ * Always returns a normalized array wraps legacy single-object config automatically for
343
+ * full backward compatibility.
344
+ * Uses Nuxt plugin provide: plugins/api-callbacks.ts with $getGlobalApiCallbacks
345
+ */
346
+ export function getGlobalCallbacks(): GlobalCallbacksRule[] {
347
+ try {
348
+ const nuxtApp = useNuxtApp();
349
+ // @ts-ignore - $getGlobalApiCallbacks may or may not exist (user-defined)
350
+ if (nuxtApp.$getGlobalApiCallbacks) {
351
+ // @ts-ignore
352
+ const config: GlobalCallbacksConfig = nuxtApp.$getGlobalApiCallbacks();
353
+ if (config && typeof config === 'object') {
354
+ // Normalize: wrap single-rule object in array for backward compatibility
355
+ return Array.isArray(config) ? config : [config];
356
+ }
357
+ }
358
+ } catch (e) {
359
+ // useNuxtApp not available or plugin not configured, that's OK
360
+ }
361
+
362
+ return [];
363
+ }
364
+
365
+ /**
366
+ * Helper function to get the global base URL from runtimeConfig.public.apiBaseUrl
367
+ * Returns the configured URL or undefined if not set or not in a Nuxt context.
368
+ */
369
+ export function getGlobalBaseUrl(): string | undefined {
370
+ try {
371
+ const runtimeConfig = useRuntimeConfig();
372
+ const url = runtimeConfig?.public?.apiBaseUrl as string | undefined;
373
+ return url || undefined;
374
+ } catch {
375
+ // useRuntimeConfig not available outside Nuxt context, that's OK
376
+ return undefined;
377
+ }
378
+ }
379
+
380
+ /**
381
+ * Check if a global rule should be applied to a specific request.
382
+ * Implements Opción 1 (skipGlobalCallbacks), URL pattern matching, and HTTP method matching.
383
+ */
384
+ export function shouldApplyGlobalCallback(
385
+ url: string,
386
+ method: string,
387
+ callbackName: 'onRequest' | 'onSuccess' | 'onError' | 'onFinish',
388
+ rule: GlobalCallbacksRule,
389
+ skipConfig?: SkipGlobalCallbacks
390
+ ): boolean {
391
+ // Opción 1: Check if callback is skipped via skipGlobalCallbacks
392
+ if (skipConfig === true) return false;
393
+ if (Array.isArray(skipConfig) && skipConfig.includes(callbackName)) return false;
394
+
395
+ // URL pattern matching — if patterns defined, URL must match at least one
396
+ if (rule.patterns && rule.patterns.length > 0) {
397
+ const matchesUrl = rule.patterns.some((pattern) => {
398
+ // Convert glob pattern to regex: ** = any path, * = single segment
399
+ const regexPattern = pattern
400
+ .replace(/\*\*/g, '@@DOUBLE_STAR@@')
401
+ .replace(/\*/g, '[^/]*')
402
+ .replace(/@@DOUBLE_STAR@@/g, '.*');
403
+ return new RegExp('^' + regexPattern + '$').test(url);
404
+ });
405
+ if (!matchesUrl) return false;
406
+ }
407
+
408
+ // Method matching — if methods defined, request method must match at least one
409
+ if (rule.methods && rule.methods.length > 0) {
410
+ if (!rule.methods.map((m) => m.toUpperCase()).includes(method.toUpperCase())) return false;
411
+ }
412
+
413
+ return true;
414
+ }
415
+
416
+ /**
417
+ * Merge local and global callback rules with proper execution order.
418
+ * Global rules are iterated in definition order. Any rule returning false suppresses the local callback.
419
+ * Implements all 3 options:
420
+ * - Opción 1: skipGlobalCallbacks to disable all global rules per request
421
+ * - Opción 2: a rule callback can return false to prevent local callback execution
422
+ * - Opción 3: per-rule URL pattern matching and HTTP method filtering
423
+ */
424
+ export function mergeCallbacks(
425
+ url: string,
426
+ method: string,
427
+ localCallbacks: {
428
+ onRequest?: Function;
429
+ onSuccess?: Function;
430
+ onError?: Function;
431
+ onFinish?: Function;
432
+ },
433
+ skipConfig?: SkipGlobalCallbacks
434
+ ) {
435
+ const rules = getGlobalCallbacks();
436
+
437
+ /**
438
+ * Iterate all applicable global rules for onSuccess, onError, or onFinish.
439
+ * Returns true if the local callback should still execute.
440
+ */
441
+ async function runGlobalRules(
442
+ callbackName: 'onSuccess' | 'onError' | 'onFinish',
443
+ ...args: any[]
444
+ ): Promise<boolean> {
445
+ let continueLocal = true;
446
+ for (const rule of rules) {
447
+ const cb = rule[callbackName];
448
+ if (!cb || !shouldApplyGlobalCallback(url, method, callbackName, rule, skipConfig)) continue;
449
+ try {
450
+ const result = await (cb as Function)(...args);
451
+ // Opción 2: returning false from any rule suppresses the local callback
452
+ if (result === false) continueLocal = false;
453
+ } catch (error) {
454
+ console.error(`Error in global ${callbackName} callback:`, error);
455
+ }
456
+ }
457
+ return continueLocal;
458
+ }
459
+
460
+ return {
461
+ /**
462
+ * Merged onRequest: runs all applicable global rules collecting and deep-merging
463
+ * modifications (headers and query are merged; body is last-write-wins).
464
+ * Local onRequest runs after all rules unless any returns false, and its
465
+ * modifications take highest priority.
466
+ */
467
+ onRequest: async (ctx: RequestContext) => {
468
+ let mergedMods: ModifiedRequestContext | undefined;
469
+ let continueLocal = true;
470
+
471
+ for (const rule of rules) {
472
+ if (!rule.onRequest || !shouldApplyGlobalCallback(url, method, 'onRequest', rule, skipConfig)) continue;
473
+ try {
474
+ const result = await rule.onRequest(ctx);
475
+ if (result === false) {
476
+ continueLocal = false;
477
+ } else if (result && typeof result === 'object') {
478
+ const mod = result as ModifiedRequestContext;
479
+ // Deep-merge headers and query; body is last-write-wins
480
+ mergedMods = {
481
+ ...(mergedMods ?? {}),
482
+ ...mod,
483
+ headers: { ...(mergedMods?.headers ?? {}), ...(mod.headers ?? {}) },
484
+ query: { ...(mergedMods?.query ?? {}), ...(mod.query ?? {}) },
485
+ };
486
+ }
487
+ } catch (error) {
488
+ console.error('Error in global onRequest callback:', error);
489
+ }
490
+ }
491
+
492
+ // Execute local onRequest — its modifications take highest priority
493
+ if (continueLocal && localCallbacks.onRequest) {
494
+ const localResult = await localCallbacks.onRequest(ctx);
495
+ if (localResult && typeof localResult === 'object') {
496
+ const localMod = localResult as ModifiedRequestContext;
497
+ return mergedMods
498
+ ? {
499
+ ...mergedMods,
500
+ ...localMod,
501
+ headers: { ...(mergedMods.headers ?? {}), ...(localMod.headers ?? {}) },
502
+ query: { ...(mergedMods.query ?? {}), ...(localMod.query ?? {}) },
503
+ }
504
+ : localMod;
505
+ }
506
+ }
507
+
508
+ return mergedMods;
509
+ },
510
+
511
+ /** Merged onSuccess: global rules first in order, then local (unless suppressed). */
512
+ onSuccess: async (data: any, context?: any) => {
513
+ const continueLocal = await runGlobalRules('onSuccess', data, context);
514
+ if (continueLocal && localCallbacks.onSuccess) {
515
+ await localCallbacks.onSuccess(data, context);
516
+ }
517
+ },
518
+
519
+ /** Merged onError: global rules first in order, then local (unless suppressed). */
520
+ onError: async (error: any, context?: any) => {
521
+ const continueLocal = await runGlobalRules('onError', error, context);
522
+ if (continueLocal && localCallbacks.onError) {
523
+ await localCallbacks.onError(error, context);
524
+ }
525
+ },
526
+
527
+ /** Merged onFinish: global rules first in order, then local (unless suppressed). */
528
+ onFinish: async (context: any) => {
529
+ const continueLocal = await runGlobalRules('onFinish', context);
530
+ if (continueLocal && localCallbacks.onFinish) {
531
+ await localCallbacks.onFinish(context);
532
+ }
533
+ },
534
+ };
535
+ }