nuxt-openapi-hyperfetch 0.1.7-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 +5 -5
  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 +81 -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 +114 -13
  48. package/dist/generators/use-async-data/runtime/useApiAsyncDataRaw.js +88 -10
  49. package/dist/generators/use-async-data/templates.js +17 -17
  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 -507
  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 -229
  89. package/src/generators/use-async-data/runtime/useApiAsyncDataRaw.ts +324 -245
  90. package/src/generators/use-async-data/templates.ts +257 -257
  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
@@ -0,0 +1,158 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Global API Pagination Plugin
4
+ *
5
+ * ⚠️ IMPORTANT: This file is NEVER regenerated - your changes are safe!
6
+ *
7
+ * Configure the global pagination convention for all paginated API requests.
8
+ * Each composable can override this config locally via `paginationConfig` option.
9
+ *
10
+ * ── HOW IT WORKS ──────────────────────────────────────────────────────────────
11
+ *
12
+ * When you call a composable with `paginated: true`, the wrapper will:
13
+ * 1. Inject page/perPage params into the request (query, body, or headers)
14
+ * 2. After the response, read total/totalPages/currentPage/perPage from the
15
+ * response headers or JSON body, according to `metaSource`
16
+ * 3. Expose `pagination`, `goToPage()`, `nextPage()`, `prevPage()`, `setPerPage()`
17
+ *
18
+ * ── USAGE ─────────────────────────────────────────────────────────────────────
19
+ *
20
+ * // In your page/component:
21
+ * const { data, pagination, goToPage, nextPage, prevPage, setPerPage } =
22
+ * useGetPets(params, { paginated: true })
23
+ *
24
+ * // pagination is a computed ref:
25
+ * pagination.value.currentPage // current page
26
+ * pagination.value.totalPages // total pages
27
+ * pagination.value.total // total items
28
+ * pagination.value.perPage // items per page
29
+ * pagination.value.hasNextPage // boolean
30
+ * pagination.value.hasPrevPage // boolean
31
+ *
32
+ * // Navigation helpers — automatically trigger re-fetch:
33
+ * goToPage(3)
34
+ * nextPage()
35
+ * prevPage()
36
+ * setPerPage(50)
37
+ *
38
+ * ── PRIORITY ──────────────────────────────────────────────────────────────────
39
+ *
40
+ * Per-call paginationConfig > this plugin's global config > built-in defaults
41
+ *
42
+ * Example of per-call override:
43
+ * useGetPets(params, {
44
+ * paginated: true,
45
+ * paginationConfig: {
46
+ * meta: { metaSource: 'headers', fields: { ... } },
47
+ * request: { sendAs: 'query', params: { page: 'p', perPage: 'size' }, defaults: { page: 1, perPage: 10 } }
48
+ * }
49
+ * })
50
+ */
51
+
52
+ export default defineNuxtPlugin(() => {
53
+ // Uncomment and configure ONE of the examples below that matches your backend.
54
+
55
+ // ============================================================================
56
+ // EXAMPLE 1 — Query params + response body (most common REST pattern)
57
+ //
58
+ // Request: GET /pets?page=1&limit=20
59
+ // Response: { data: [...], total: 100, totalPages: 5, currentPage: 1, perPage: 20 }
60
+ // ============================================================================
61
+ // const paginationConfig = {
62
+ // meta: {
63
+ // metaSource: 'body',
64
+ // fields: {
65
+ // total: 'total',
66
+ // totalPages: 'totalPages',
67
+ // currentPage: 'currentPage',
68
+ // perPage: 'perPage',
69
+ // dataKey: 'data', // response.data contains the actual array
70
+ // },
71
+ // },
72
+ // request: {
73
+ // sendAs: 'query',
74
+ // params: { page: 'page', perPage: 'limit' },
75
+ // defaults: { page: 1, perPage: 20 },
76
+ // },
77
+ // };
78
+
79
+ // ============================================================================
80
+ // EXAMPLE 2 — Laravel paginate() convention
81
+ //
82
+ // Request: GET /pets?page=1&per_page=15
83
+ // Response: { data: [...], meta: { total: 100, last_page: 7, current_page: 1, per_page: 15 } }
84
+ // ============================================================================
85
+ // const paginationConfig = {
86
+ // meta: {
87
+ // metaSource: 'body',
88
+ // fields: {
89
+ // total: 'meta.total',
90
+ // totalPages: 'meta.last_page',
91
+ // currentPage: 'meta.current_page',
92
+ // perPage: 'meta.per_page',
93
+ // dataKey: 'data',
94
+ // },
95
+ // },
96
+ // request: {
97
+ // sendAs: 'query',
98
+ // params: { page: 'page', perPage: 'per_page' },
99
+ // defaults: { page: 1, perPage: 15 },
100
+ // },
101
+ // };
102
+
103
+ // ============================================================================
104
+ // EXAMPLE 3 — HTTP response headers convention
105
+ //
106
+ // Request: GET /pets?page=1&limit=20
107
+ // Response headers: X-Total-Count: 100, X-Total-Pages: 5, X-Page: 1, X-Per-Page: 20
108
+ // ============================================================================
109
+ // const paginationConfig = {
110
+ // meta: {
111
+ // metaSource: 'headers',
112
+ // fields: {
113
+ // total: 'X-Total-Count',
114
+ // totalPages: 'X-Total-Pages',
115
+ // currentPage: 'X-Page',
116
+ // perPage: 'X-Per-Page',
117
+ // // No dataKey needed — response body is the array directly
118
+ // },
119
+ // },
120
+ // request: {
121
+ // sendAs: 'query',
122
+ // params: { page: 'page', perPage: 'limit' },
123
+ // defaults: { page: 1, perPage: 20 },
124
+ // },
125
+ // };
126
+
127
+ // ============================================================================
128
+ // EXAMPLE 4 — POST-as-search (body pagination)
129
+ //
130
+ // Request: POST /pets/search body: { filters: {...}, page: 1, pageSize: 20 }
131
+ // Response: { items: [...], total: 100, pages: 5 }
132
+ // ============================================================================
133
+ // const paginationConfig = {
134
+ // meta: {
135
+ // metaSource: 'body',
136
+ // fields: {
137
+ // total: 'total',
138
+ // totalPages: 'pages',
139
+ // currentPage: 'page',
140
+ // perPage: 'pageSize',
141
+ // dataKey: 'items',
142
+ // },
143
+ // },
144
+ // request: {
145
+ // sendAs: 'body',
146
+ // params: { page: 'page', perPage: 'pageSize' },
147
+ // defaults: { page: 1, perPage: 20 },
148
+ // },
149
+ // };
150
+
151
+ return {
152
+ provide: {
153
+ // Expose the config so the runtime wrappers can read it.
154
+ // Uncomment this line once you've configured paginationConfig above:
155
+ // getGlobalApiPagination: () => paginationConfig,
156
+ },
157
+ };
158
+ });
@@ -1,204 +1,205 @@
1
- import * as path from 'path';
2
- import fs from 'fs-extra';
3
- import { fileURLToPath } from 'url';
4
- import { format } from 'prettier';
5
- import {
6
- getApiFiles as getApiFilesOfficial,
7
- parseApiFile as parseApiFileOfficial,
8
- } from './parser.js';
9
- import {
10
- getApiFiles as getApiFilesHeyApi,
11
- parseApiFile as parseApiFileHeyApi,
12
- } from '../shared/parsers/heyapi-parser.js';
13
- import {
14
- generateComposableFile,
15
- generateRawComposableFile,
16
- generateIndexFile,
17
- type GenerateOptions,
18
- } from './templates.js';
19
- import type { MethodInfo } from './types.js';
20
- import { p, logSuccess, logError } from '../../cli/logger.js';
21
-
22
- /**
23
- * Main function to generate useAsyncData composables
24
- */
25
- export async function generateUseAsyncDataComposables(
26
- inputDir: string,
27
- outputDir: string,
28
- options?: GenerateOptions
29
- ): Promise<void> {
30
- const mainSpinner = p.spinner();
31
-
32
- // Select parser based on chosen backend
33
- const getApiFiles = options?.backend === 'heyapi' ? getApiFilesHeyApi : getApiFilesOfficial;
34
- const parseApiFile = options?.backend === 'heyapi' ? parseApiFileHeyApi : parseApiFileOfficial;
35
-
36
- // 1. Get all API files
37
- mainSpinner.start('Scanning API files');
38
- const apiFiles = getApiFiles(inputDir);
39
- mainSpinner.stop(`Found ${apiFiles.length} API file(s)`);
40
-
41
- if (apiFiles.length === 0) {
42
- throw new Error('No API files found in the input directory');
43
- }
44
-
45
- // 2. Parse each API file
46
- mainSpinner.start('Parsing API files');
47
- const allMethods: MethodInfo[] = [];
48
-
49
- for (const file of apiFiles) {
50
- const fileName = path.basename(file);
51
- try {
52
- const apiInfo = parseApiFile(file);
53
- allMethods.push(...apiInfo.methods);
54
- } catch (error) {
55
- logError(`Error parsing ${fileName}: ${error}`);
56
- }
57
- }
58
-
59
- mainSpinner.stop(`Found ${allMethods.length} methods to generate`);
60
-
61
- if (allMethods.length === 0) {
62
- p.log.warn('No methods found to generate');
63
- return;
64
- }
65
-
66
- // 3. Clean and create output directories
67
- mainSpinner.start('Preparing output directories');
68
- const composablesDir = path.join(outputDir, 'composables');
69
- const runtimeDir = path.join(outputDir, 'runtime');
70
- const sharedRuntimeDir = path.join(path.dirname(outputDir), 'shared', 'runtime');
71
- await fs.emptyDir(composablesDir);
72
- await fs.ensureDir(runtimeDir);
73
- await fs.ensureDir(sharedRuntimeDir);
74
- mainSpinner.stop('Output directories ready');
75
-
76
- // 4. Copy runtime helpers
77
- mainSpinner.start('Copying runtime files');
78
- // Derive __dirname equivalent for ESM
79
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
80
- // When compiled, __dirname points to dist/generators/use-async-data/
81
- // We need to go back to src/ to get the original .ts files
82
-
83
- // Copy useApiAsyncData.ts
84
- const runtimeSource = path.resolve(
85
- __dirname,
86
- '../../../src/generators/use-async-data/runtime/useApiAsyncData.ts'
87
- );
88
- const runtimeDest = path.join(runtimeDir, 'useApiAsyncData.ts');
89
- await fs.copyFile(runtimeSource, runtimeDest);
90
-
91
- // Copy useApiAsyncDataRaw.ts
92
- const runtimeRawSource = path.resolve(
93
- __dirname,
94
- '../../../src/generators/use-async-data/runtime/useApiAsyncDataRaw.ts'
95
- );
96
- const runtimeRawDest = path.join(runtimeDir, 'useApiAsyncDataRaw.ts');
97
- await fs.copyFile(runtimeRawSource, runtimeRawDest);
98
-
99
- // Copy shared apiHelpers.ts
100
- const sharedHelpersSource = path.resolve(
101
- __dirname,
102
- '../../../src/generators/shared/runtime/apiHelpers.ts'
103
- );
104
- const sharedHelpersDest = path.join(sharedRuntimeDir, 'apiHelpers.ts');
105
- await fs.copyFile(sharedHelpersSource, sharedHelpersDest);
106
- mainSpinner.stop('Runtime files copied');
107
-
108
- // 5. Calculate relative import path from composables to APIs
109
- const relativePath = calculateRelativeImportPath(composablesDir, inputDir);
110
-
111
- // 6. Generate each composable (normal + Raw if available)
112
- mainSpinner.start('Generating composables');
113
- let successCount = 0;
114
- let errorCount = 0;
115
- const generatedComposableNames: string[] = [];
116
-
117
- for (const method of allMethods) {
118
- // Generate normal version
119
- try {
120
- const code = generateComposableFile(method, relativePath, options);
121
- const formattedCode = await formatCode(code);
122
- const composableName = method.composableName.replace(/^useFetch/, 'useAsyncData');
123
- const fileName = `${composableName}.ts`;
124
- const filePath = path.join(composablesDir, fileName);
125
-
126
- await fs.writeFile(filePath, formattedCode, 'utf-8');
127
- generatedComposableNames.push(composableName);
128
- successCount++;
129
- } catch (error) {
130
- logError(`Error generating ${method.composableName}: ${error}`);
131
- errorCount++;
132
- }
133
-
134
- // Generate Raw version if available
135
- if (method.hasRawMethod && method.rawMethodName) {
136
- try {
137
- const code = generateRawComposableFile(method, relativePath, options);
138
- const formattedCode = await formatCode(code);
139
- const composableName = `useAsyncData${method.rawMethodName.replace(/Raw$/, '')}Raw`;
140
- const fileName = `${composableName}.ts`;
141
- const filePath = path.join(composablesDir, fileName);
142
-
143
- await fs.writeFile(filePath, formattedCode, 'utf-8');
144
- generatedComposableNames.push(composableName);
145
- successCount++;
146
- } catch (error) {
147
- logError(`Error generating ${method.composableName} (Raw): ${error}`);
148
- errorCount++;
149
- }
150
- }
151
- }
152
-
153
- // 7. Generate index.ts
154
- const indexCode = generateIndexFile(generatedComposableNames);
155
- const formattedIndex = await formatCode(indexCode);
156
- await fs.writeFile(path.join(outputDir, 'index.ts'), formattedIndex, 'utf-8');
157
- mainSpinner.stop(`Generated ${successCount} composables`);
158
-
159
- // 8. Summary
160
- if (errorCount > 0) {
161
- p.log.warn(`Completed with ${errorCount} error(s)`);
162
- }
163
- logSuccess(`Generated ${successCount} useAsyncData composable(s) in ${outputDir}`);
164
- }
165
-
166
- /**
167
- * Calculate relative import path from composables to APIs
168
- */
169
- function calculateRelativeImportPath(composablesDir: string, inputDir: string): string {
170
- // Import from the root index.ts which exports apis, models, and runtime
171
- let relativePath = path.relative(composablesDir, inputDir);
172
-
173
- // Convert Windows paths to Unix-style
174
- relativePath = relativePath.replace(/\\/g, '/');
175
-
176
- // Ensure it starts with './' or '../'
177
- if (!relativePath.startsWith('.')) {
178
- relativePath = './' + relativePath;
179
- }
180
-
181
- // Remove .ts extension and trailing /
182
- relativePath = relativePath.replace(/\.ts$/, '').replace(/\/$/, '');
183
-
184
- return relativePath;
185
- }
186
-
187
- /**
188
- * Format code with Prettier
189
- */
190
- async function formatCode(code: string): Promise<string> {
191
- try {
192
- return await format(code, {
193
- parser: 'typescript',
194
- semi: true,
195
- singleQuote: true,
196
- trailingComma: 'es5',
197
- printWidth: 80,
198
- tabWidth: 2,
199
- });
200
- } catch {
201
- p.log.warn('Could not format code with Prettier');
202
- return code;
203
- }
204
- }
1
+ import * as path from 'path';
2
+ import fs from 'fs-extra';
3
+ import { fileURLToPath } from 'url';
4
+ import { format } from 'prettier';
5
+ import {
6
+ getApiFiles as getApiFilesOfficial,
7
+ parseApiFile as parseApiFileOfficial,
8
+ } from './parser.js';
9
+ import {
10
+ getApiFiles as getApiFilesHeyApi,
11
+ parseApiFile as parseApiFileHeyApi,
12
+ } from '../shared/parsers/heyapi-parser.js';
13
+ import {
14
+ generateComposableFile,
15
+ generateRawComposableFile,
16
+ generateIndexFile,
17
+ type GenerateOptions,
18
+ } from './templates.js';
19
+ import type { MethodInfo } from './types.js';
20
+ import { type Logger, createClackLogger } from '../../cli/logger.js';
21
+
22
+ /**
23
+ * Main function to generate useAsyncData composables
24
+ */
25
+ export async function generateUseAsyncDataComposables(
26
+ inputDir: string,
27
+ outputDir: string,
28
+ options?: GenerateOptions,
29
+ logger: Logger = createClackLogger()
30
+ ): Promise<void> {
31
+ const mainSpinner = logger.spinner();
32
+
33
+ // Select parser based on chosen backend
34
+ const getApiFiles = options?.backend === 'heyapi' ? getApiFilesHeyApi : getApiFilesOfficial;
35
+ const parseApiFile = options?.backend === 'heyapi' ? parseApiFileHeyApi : parseApiFileOfficial;
36
+
37
+ // 1. Get all API files
38
+ mainSpinner.start('Scanning API files');
39
+ const apiFiles = getApiFiles(inputDir);
40
+ mainSpinner.stop(`Found ${apiFiles.length} API file(s)`);
41
+
42
+ if (apiFiles.length === 0) {
43
+ throw new Error('No API files found in the input directory');
44
+ }
45
+
46
+ // 2. Parse each API file
47
+ mainSpinner.start('Parsing API files');
48
+ const allMethods: MethodInfo[] = [];
49
+
50
+ for (const file of apiFiles) {
51
+ const fileName = path.basename(file);
52
+ try {
53
+ const apiInfo = parseApiFile(file);
54
+ allMethods.push(...apiInfo.methods);
55
+ } catch (error) {
56
+ logger.log.error(`Error parsing ${fileName}: ${String(error)}`);
57
+ }
58
+ }
59
+
60
+ mainSpinner.stop(`Found ${allMethods.length} methods to generate`);
61
+
62
+ if (allMethods.length === 0) {
63
+ logger.log.warn('No methods found to generate');
64
+ return;
65
+ }
66
+
67
+ // 3. Clean and create output directories
68
+ mainSpinner.start('Preparing output directories');
69
+ const composablesDir = path.join(outputDir, 'composables');
70
+ const runtimeDir = path.join(outputDir, 'runtime');
71
+ const sharedRuntimeDir = path.join(path.dirname(outputDir), 'shared', 'runtime');
72
+ await fs.emptyDir(composablesDir);
73
+ await fs.ensureDir(runtimeDir);
74
+ await fs.ensureDir(sharedRuntimeDir);
75
+ mainSpinner.stop('Output directories ready');
76
+
77
+ // 4. Copy runtime helpers
78
+ mainSpinner.start('Copying runtime files');
79
+ // Derive __dirname equivalent for ESM
80
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
81
+ // When compiled, __dirname points to dist/generators/use-async-data/
82
+ // We need to go back to src/ to get the original .ts files
83
+
84
+ // Copy useApiAsyncData.ts
85
+ const runtimeSource = path.resolve(
86
+ __dirname,
87
+ '../../../src/generators/use-async-data/runtime/useApiAsyncData.ts'
88
+ );
89
+ const runtimeDest = path.join(runtimeDir, 'useApiAsyncData.ts');
90
+ await fs.copyFile(runtimeSource, runtimeDest);
91
+
92
+ // Copy useApiAsyncDataRaw.ts
93
+ const runtimeRawSource = path.resolve(
94
+ __dirname,
95
+ '../../../src/generators/use-async-data/runtime/useApiAsyncDataRaw.ts'
96
+ );
97
+ const runtimeRawDest = path.join(runtimeDir, 'useApiAsyncDataRaw.ts');
98
+ await fs.copyFile(runtimeRawSource, runtimeRawDest);
99
+
100
+ // Copy shared apiHelpers.ts
101
+ const sharedHelpersSource = path.resolve(
102
+ __dirname,
103
+ '../../../src/generators/shared/runtime/apiHelpers.ts'
104
+ );
105
+ const sharedHelpersDest = path.join(sharedRuntimeDir, 'apiHelpers.ts');
106
+ await fs.copyFile(sharedHelpersSource, sharedHelpersDest);
107
+ mainSpinner.stop('Runtime files copied');
108
+
109
+ // 5. Calculate relative import path from composables to APIs
110
+ const relativePath = calculateRelativeImportPath(composablesDir, inputDir);
111
+
112
+ // 6. Generate each composable (normal + Raw if available)
113
+ mainSpinner.start('Generating composables');
114
+ let successCount = 0;
115
+ let errorCount = 0;
116
+ const generatedComposableNames: string[] = [];
117
+
118
+ for (const method of allMethods) {
119
+ // Generate normal version
120
+ try {
121
+ const code = generateComposableFile(method, relativePath, options);
122
+ const formattedCode = await formatCode(code, logger);
123
+ const composableName = method.composableName.replace(/^useFetch/, 'useAsyncData');
124
+ const fileName = `${composableName}.ts`;
125
+ const filePath = path.join(composablesDir, fileName);
126
+
127
+ await fs.writeFile(filePath, formattedCode, 'utf-8');
128
+ generatedComposableNames.push(composableName);
129
+ successCount++;
130
+ } catch (error) {
131
+ logger.log.error(`Error generating ${method.composableName}: ${String(error)}`);
132
+ errorCount++;
133
+ }
134
+
135
+ // Generate Raw version if available
136
+ if (method.hasRawMethod && method.rawMethodName) {
137
+ try {
138
+ const code = generateRawComposableFile(method, relativePath, options);
139
+ const formattedCode = await formatCode(code, logger);
140
+ const composableName = `useAsyncData${method.rawMethodName.replace(/Raw$/, '')}Raw`;
141
+ const fileName = `${composableName}.ts`;
142
+ const filePath = path.join(composablesDir, fileName);
143
+
144
+ await fs.writeFile(filePath, formattedCode, 'utf-8');
145
+ generatedComposableNames.push(composableName);
146
+ successCount++;
147
+ } catch (error) {
148
+ logger.log.error(`Error generating ${method.composableName} (Raw): ${String(error)}`);
149
+ errorCount++;
150
+ }
151
+ }
152
+ }
153
+
154
+ // 7. Generate index.ts
155
+ const indexCode = generateIndexFile(generatedComposableNames);
156
+ const formattedIndex = await formatCode(indexCode, logger);
157
+ await fs.writeFile(path.join(outputDir, 'index.ts'), formattedIndex, 'utf-8');
158
+ mainSpinner.stop(`Generated ${successCount} composables`);
159
+
160
+ // 8. Summary
161
+ if (errorCount > 0) {
162
+ logger.log.warn(`Completed with ${errorCount} error(s)`);
163
+ }
164
+ logger.log.success(`Generated ${successCount} useAsyncData composable(s) in ${outputDir}`);
165
+ }
166
+
167
+ /**
168
+ * Calculate relative import path from composables to APIs
169
+ */
170
+ function calculateRelativeImportPath(composablesDir: string, inputDir: string): string {
171
+ // Import from the root index.ts which exports apis, models, and runtime
172
+ let relativePath = path.relative(composablesDir, inputDir);
173
+
174
+ // Convert Windows paths to Unix-style
175
+ relativePath = relativePath.replace(/\\/g, '/');
176
+
177
+ // Ensure it starts with './' or '../'
178
+ if (!relativePath.startsWith('.')) {
179
+ relativePath = './' + relativePath;
180
+ }
181
+
182
+ // Remove .ts extension and trailing /
183
+ relativePath = relativePath.replace(/\.ts$/, '').replace(/\/$/, '');
184
+
185
+ return relativePath;
186
+ }
187
+
188
+ /**
189
+ * Format code with Prettier
190
+ */
191
+ async function formatCode(code: string, logger: Logger): Promise<string> {
192
+ try {
193
+ return await format(code, {
194
+ parser: 'typescript',
195
+ semi: true,
196
+ singleQuote: true,
197
+ trailingComma: 'es5',
198
+ printWidth: 80,
199
+ tabWidth: 2,
200
+ });
201
+ } catch {
202
+ logger.log.warn('Could not format code with Prettier');
203
+ return code;
204
+ }
205
+ }