nuxt-openapi-hyperfetch 0.1.0-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.
- package/.editorconfig +26 -0
- package/.prettierignore +17 -0
- package/.prettierrc.json +12 -0
- package/CONTRIBUTING.md +292 -0
- package/INSTRUCTIONS.md +327 -0
- package/LICENSE +202 -0
- package/README.md +202 -0
- package/dist/cli/config.d.ts +57 -0
- package/dist/cli/config.js +85 -0
- package/dist/cli/logger.d.ts +44 -0
- package/dist/cli/logger.js +58 -0
- package/dist/cli/logo.d.ts +6 -0
- package/dist/cli/logo.js +21 -0
- package/dist/cli/messages.d.ts +65 -0
- package/dist/cli/messages.js +86 -0
- package/dist/cli/prompts.d.ts +30 -0
- package/dist/cli/prompts.js +118 -0
- package/dist/cli/types.d.ts +43 -0
- package/dist/cli/types.js +4 -0
- package/dist/cli/utils.d.ts +26 -0
- package/dist/cli/utils.js +45 -0
- package/dist/generate.d.ts +6 -0
- package/dist/generate.js +48 -0
- package/dist/generators/nuxt-server/bff-templates.d.ts +25 -0
- package/dist/generators/nuxt-server/bff-templates.js +737 -0
- package/dist/generators/nuxt-server/generator.d.ts +7 -0
- package/dist/generators/nuxt-server/generator.js +206 -0
- package/dist/generators/nuxt-server/parser.d.ts +5 -0
- package/dist/generators/nuxt-server/parser.js +5 -0
- package/dist/generators/nuxt-server/templates.d.ts +35 -0
- package/dist/generators/nuxt-server/templates.js +412 -0
- package/dist/generators/nuxt-server/types.d.ts +5 -0
- package/dist/generators/nuxt-server/types.js +5 -0
- package/dist/generators/shared/parsers/heyapi-parser.d.ts +11 -0
- package/dist/generators/shared/parsers/heyapi-parser.js +248 -0
- package/dist/generators/shared/parsers/official-parser.d.ts +5 -0
- package/dist/generators/shared/parsers/official-parser.js +5 -0
- package/dist/generators/shared/runtime/apiHelpers.d.ts +183 -0
- package/dist/generators/shared/runtime/apiHelpers.js +268 -0
- package/dist/generators/shared/templates/api-callbacks-plugin.d.ts +178 -0
- package/dist/generators/shared/templates/api-callbacks-plugin.js +338 -0
- package/dist/generators/shared/types.d.ts +25 -0
- package/dist/generators/shared/types.js +4 -0
- package/dist/generators/tanstack-query/generator.d.ts +5 -0
- package/dist/generators/tanstack-query/generator.js +11 -0
- package/dist/generators/use-async-data/generator.d.ts +5 -0
- package/dist/generators/use-async-data/generator.js +156 -0
- package/dist/generators/use-async-data/parser.d.ts +5 -0
- package/dist/generators/use-async-data/parser.js +5 -0
- package/dist/generators/use-async-data/runtime/useApiAsyncData.d.ts +38 -0
- package/dist/generators/use-async-data/runtime/useApiAsyncData.js +122 -0
- package/dist/generators/use-async-data/runtime/useApiAsyncDataRaw.d.ts +54 -0
- package/dist/generators/use-async-data/runtime/useApiAsyncDataRaw.js +126 -0
- package/dist/generators/use-async-data/templates.d.ts +20 -0
- package/dist/generators/use-async-data/templates.js +191 -0
- package/dist/generators/use-async-data/types.d.ts +4 -0
- package/dist/generators/use-async-data/types.js +4 -0
- package/dist/generators/use-fetch/generator.d.ts +5 -0
- package/dist/generators/use-fetch/generator.js +131 -0
- package/dist/generators/use-fetch/parser.d.ts +9 -0
- package/dist/generators/use-fetch/parser.js +282 -0
- package/dist/generators/use-fetch/runtime/useApiRequest.d.ts +46 -0
- package/dist/generators/use-fetch/runtime/useApiRequest.js +158 -0
- package/dist/generators/use-fetch/templates.d.ts +16 -0
- package/dist/generators/use-fetch/templates.js +169 -0
- package/dist/generators/use-fetch/types.d.ts +5 -0
- package/dist/generators/use-fetch/types.js +5 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +213 -0
- package/docs/API-REFERENCE.md +887 -0
- package/docs/ARCHITECTURE.md +649 -0
- package/docs/DEVELOPMENT.md +918 -0
- package/docs/QUICK-START.md +323 -0
- package/docs/README.md +155 -0
- package/docs/TROUBLESHOOTING.md +881 -0
- package/eslint.config.js +72 -0
- package/package.json +65 -0
- package/src/cli/config.ts +140 -0
- package/src/cli/logger.ts +66 -0
- package/src/cli/logo.ts +25 -0
- package/src/cli/messages.ts +97 -0
- package/src/cli/prompts.ts +143 -0
- package/src/cli/types.ts +50 -0
- package/src/cli/utils.ts +49 -0
- package/src/generate.ts +57 -0
- package/src/generators/nuxt-server/bff-templates.ts +754 -0
- package/src/generators/nuxt-server/generator.ts +270 -0
- package/src/generators/nuxt-server/parser.ts +5 -0
- package/src/generators/nuxt-server/templates.ts +483 -0
- package/src/generators/nuxt-server/types.ts +5 -0
- package/src/generators/shared/parsers/heyapi-parser.ts +307 -0
- package/src/generators/shared/parsers/official-parser.ts +5 -0
- package/src/generators/shared/runtime/apiHelpers.ts +466 -0
- package/src/generators/shared/templates/api-callbacks-plugin.ts +352 -0
- package/src/generators/shared/types.ts +27 -0
- package/src/generators/tanstack-query/generator.ts +11 -0
- package/src/generators/use-async-data/generator.ts +204 -0
- package/src/generators/use-async-data/parser.ts +5 -0
- package/src/generators/use-async-data/runtime/useApiAsyncData.ts +220 -0
- package/src/generators/use-async-data/runtime/useApiAsyncDataRaw.ts +236 -0
- package/src/generators/use-async-data/templates.ts +250 -0
- package/src/generators/use-async-data/types.ts +4 -0
- package/src/generators/use-fetch/generator.ts +169 -0
- package/src/generators/use-fetch/parser.ts +341 -0
- package/src/generators/use-fetch/runtime/useApiRequest.ts +223 -0
- package/src/generators/use-fetch/templates.ts +214 -0
- package/src/generators/use-fetch/types.ts +5 -0
- package/src/index.ts +265 -0
- package/tsconfig.json +15 -0
|
@@ -0,0 +1,169 @@
|
|
|
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 { generateComposableFile, generateIndexFile, type GenerateOptions } from './templates.js';
|
|
14
|
+
import type { MethodInfo } from './types.js';
|
|
15
|
+
import { p, logSuccess, logError } from '../../cli/logger.js';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Main function to generate useFetch composables
|
|
19
|
+
*/
|
|
20
|
+
export async function generateUseFetchComposables(
|
|
21
|
+
inputDir: string,
|
|
22
|
+
outputDir: string,
|
|
23
|
+
options?: GenerateOptions
|
|
24
|
+
): Promise<void> {
|
|
25
|
+
const mainSpinner = p.spinner();
|
|
26
|
+
|
|
27
|
+
// Select parser based on chosen backend
|
|
28
|
+
const getApiFiles = options?.backend === 'heyapi' ? getApiFilesHeyApi : getApiFilesOfficial;
|
|
29
|
+
const parseApiFile = options?.backend === 'heyapi' ? parseApiFileHeyApi : parseApiFileOfficial;
|
|
30
|
+
|
|
31
|
+
// 1. Get all API files
|
|
32
|
+
mainSpinner.start('Scanning API files');
|
|
33
|
+
const apiFiles = getApiFiles(inputDir);
|
|
34
|
+
mainSpinner.stop(`Found ${apiFiles.length} API file(s)`);
|
|
35
|
+
|
|
36
|
+
if (apiFiles.length === 0) {
|
|
37
|
+
throw new Error('No API files found in the input directory');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// 2. Parse each API file
|
|
41
|
+
mainSpinner.start('Parsing API files');
|
|
42
|
+
const allMethods: MethodInfo[] = [];
|
|
43
|
+
|
|
44
|
+
for (const file of apiFiles) {
|
|
45
|
+
const fileName = path.basename(file);
|
|
46
|
+
try {
|
|
47
|
+
const apiInfo = parseApiFile(file);
|
|
48
|
+
allMethods.push(...apiInfo.methods);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
logError(`Error parsing ${fileName}: ${String(error)}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
mainSpinner.stop(`Found ${allMethods.length} methods to generate`);
|
|
55
|
+
|
|
56
|
+
if (allMethods.length === 0) {
|
|
57
|
+
p.log.warn('No methods found to generate');
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// 3. Clean and create output directories
|
|
62
|
+
mainSpinner.start('Preparing output directories');
|
|
63
|
+
const composablesDir = path.join(outputDir, 'composables');
|
|
64
|
+
const runtimeDir = path.join(outputDir, 'runtime');
|
|
65
|
+
const sharedRuntimeDir = path.join(outputDir, 'shared', 'runtime');
|
|
66
|
+
await fs.emptyDir(composablesDir);
|
|
67
|
+
await fs.ensureDir(runtimeDir);
|
|
68
|
+
await fs.ensureDir(sharedRuntimeDir);
|
|
69
|
+
mainSpinner.stop('Output directories ready');
|
|
70
|
+
|
|
71
|
+
// 4. Copy runtime helpers
|
|
72
|
+
mainSpinner.start('Copying runtime files');
|
|
73
|
+
// Derive __dirname equivalent for ESM
|
|
74
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
75
|
+
// When compiled, __dirname points to dist/generators/use-fetch/
|
|
76
|
+
// We need to go back to src/ to get the original .ts files
|
|
77
|
+
|
|
78
|
+
// Copy useApiRequest.ts
|
|
79
|
+
const runtimeSource = path.resolve(
|
|
80
|
+
__dirname,
|
|
81
|
+
'../../../src/generators/use-fetch/runtime/useApiRequest.ts'
|
|
82
|
+
);
|
|
83
|
+
const runtimeDest = path.join(runtimeDir, 'useApiRequest.ts');
|
|
84
|
+
await fs.copyFile(runtimeSource, runtimeDest);
|
|
85
|
+
|
|
86
|
+
// Copy shared apiHelpers.ts
|
|
87
|
+
const sharedHelpersSource = path.resolve(
|
|
88
|
+
__dirname,
|
|
89
|
+
'../../../src/generators/shared/runtime/apiHelpers.ts'
|
|
90
|
+
);
|
|
91
|
+
const sharedHelpersDest = path.join(sharedRuntimeDir, 'apiHelpers.ts');
|
|
92
|
+
await fs.copyFile(sharedHelpersSource, sharedHelpersDest);
|
|
93
|
+
mainSpinner.stop('Runtime files copied');
|
|
94
|
+
|
|
95
|
+
// 5. Calculate relative import path from composables to APIs
|
|
96
|
+
const relativePath = calculateRelativeImportPath(composablesDir, inputDir);
|
|
97
|
+
|
|
98
|
+
// 6. Generate each composable
|
|
99
|
+
mainSpinner.start('Generating composables');
|
|
100
|
+
let successCount = 0;
|
|
101
|
+
let errorCount = 0;
|
|
102
|
+
|
|
103
|
+
for (const method of allMethods) {
|
|
104
|
+
try {
|
|
105
|
+
const code = generateComposableFile(method, relativePath, options);
|
|
106
|
+
const formattedCode = await formatCode(code);
|
|
107
|
+
const fileName = `${method.composableName}.ts`;
|
|
108
|
+
const filePath = path.join(composablesDir, fileName);
|
|
109
|
+
|
|
110
|
+
await fs.writeFile(filePath, formattedCode, 'utf-8');
|
|
111
|
+
successCount++;
|
|
112
|
+
} catch (error) {
|
|
113
|
+
logError(`Error generating ${method.composableName}: ${String(error)}`);
|
|
114
|
+
errorCount++;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// 7. Generate index.ts
|
|
119
|
+
const indexCode = generateIndexFile(allMethods.map((m) => m.composableName));
|
|
120
|
+
const formattedIndex = await formatCode(indexCode);
|
|
121
|
+
await fs.writeFile(path.join(outputDir, 'index.ts'), formattedIndex, 'utf-8');
|
|
122
|
+
mainSpinner.stop(`Generated ${successCount} composables`);
|
|
123
|
+
|
|
124
|
+
// 8. Summary
|
|
125
|
+
if (errorCount > 0) {
|
|
126
|
+
p.log.warn(`Completed with ${errorCount} error(s)`);
|
|
127
|
+
}
|
|
128
|
+
logSuccess(`Generated ${successCount} useFetch composable(s) in ${outputDir}`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Calculate relative import path from composables to APIs
|
|
133
|
+
*/
|
|
134
|
+
function calculateRelativeImportPath(composablesDir: string, inputDir: string): string {
|
|
135
|
+
// Import from the root index.ts which exports apis, models, and runtime
|
|
136
|
+
let relativePath = path.relative(composablesDir, inputDir);
|
|
137
|
+
|
|
138
|
+
// Convert Windows paths to Unix-style
|
|
139
|
+
relativePath = relativePath.replace(/\\/g, '/');
|
|
140
|
+
|
|
141
|
+
// Ensure it starts with './' or '../'
|
|
142
|
+
if (!relativePath.startsWith('.')) {
|
|
143
|
+
relativePath = './' + relativePath;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Remove .ts extension and trailing /
|
|
147
|
+
relativePath = relativePath.replace(/\.ts$/, '').replace(/\/$/, '');
|
|
148
|
+
|
|
149
|
+
return relativePath;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Format code with Prettier
|
|
154
|
+
*/
|
|
155
|
+
async function formatCode(code: string): Promise<string> {
|
|
156
|
+
try {
|
|
157
|
+
return await format(code, {
|
|
158
|
+
parser: 'typescript',
|
|
159
|
+
semi: true,
|
|
160
|
+
singleQuote: true,
|
|
161
|
+
trailingComma: 'es5',
|
|
162
|
+
printWidth: 80,
|
|
163
|
+
tabWidth: 2,
|
|
164
|
+
});
|
|
165
|
+
} catch {
|
|
166
|
+
p.log.warn('Could not format code with Prettier');
|
|
167
|
+
return code;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { Project, SourceFile, MethodDeclaration, SyntaxKind, Node } from 'ts-morph';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { existsSync, readdirSync } from 'node:fs';
|
|
4
|
+
import type { ApiClassInfo, MethodInfo } from './types.js';
|
|
5
|
+
import { pascalCase } from 'change-case';
|
|
6
|
+
import { p } from '../../cli/logger.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Get all API files from the input directory
|
|
10
|
+
*/
|
|
11
|
+
export function getApiFiles(inputDir: string): string[] {
|
|
12
|
+
const apisDir = path.join(inputDir, 'apis');
|
|
13
|
+
|
|
14
|
+
if (!existsSync(apisDir)) {
|
|
15
|
+
throw new Error(`APIs directory not found: ${apisDir}`);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const files = readdirSync(apisDir);
|
|
19
|
+
return files
|
|
20
|
+
.filter((file: string) => file.endsWith('.ts') && file !== 'index.ts')
|
|
21
|
+
.map((file: string) => path.join(apisDir, file));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Parse an API file and extract all methods
|
|
26
|
+
*/
|
|
27
|
+
export function parseApiFile(filePath: string): ApiClassInfo {
|
|
28
|
+
const project = new Project();
|
|
29
|
+
const sourceFile = project.addSourceFileAtPath(filePath);
|
|
30
|
+
|
|
31
|
+
// Find the API class (e.g., PetApi, StoreApi)
|
|
32
|
+
const classes = sourceFile.getClasses();
|
|
33
|
+
if (classes.length === 0) {
|
|
34
|
+
throw new Error(`No class found in ${filePath}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const apiClass = classes[0];
|
|
38
|
+
const className = apiClass.getName() || '';
|
|
39
|
+
|
|
40
|
+
// Get all public methods (excluding Raw and RequestOpts)
|
|
41
|
+
const methods = getPublicMethods(apiClass.getMethods());
|
|
42
|
+
|
|
43
|
+
const methodInfos: MethodInfo[] = [];
|
|
44
|
+
|
|
45
|
+
for (const method of methods) {
|
|
46
|
+
try {
|
|
47
|
+
const methodInfo = extractMethodInfo(method, sourceFile);
|
|
48
|
+
if (methodInfo) {
|
|
49
|
+
methodInfos.push(methodInfo);
|
|
50
|
+
}
|
|
51
|
+
} catch (error) {
|
|
52
|
+
p.log.warn(`Could not parse method ${method.getName()}: ${String(error)}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
className,
|
|
58
|
+
methods: methodInfos,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Filter to get only public methods (not Raw, not RequestOpts)
|
|
64
|
+
*/
|
|
65
|
+
function getPublicMethods(methods: MethodDeclaration[]): MethodDeclaration[] {
|
|
66
|
+
return methods.filter((method) => {
|
|
67
|
+
const name = method.getName();
|
|
68
|
+
const isAsync = method.isAsync();
|
|
69
|
+
const isPublic =
|
|
70
|
+
!method.hasModifier(SyntaxKind.PrivateKeyword) &&
|
|
71
|
+
!method.hasModifier(SyntaxKind.ProtectedKeyword);
|
|
72
|
+
|
|
73
|
+
return isPublic && isAsync && !name.endsWith('Raw') && !name.endsWith('RequestOpts');
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Extract method information
|
|
79
|
+
*/
|
|
80
|
+
function extractMethodInfo(method: MethodDeclaration, sourceFile: SourceFile): MethodInfo | null {
|
|
81
|
+
const methodName = method.getName();
|
|
82
|
+
const composableName = `useFetch${pascalCase(methodName)}`;
|
|
83
|
+
|
|
84
|
+
// Get parameters
|
|
85
|
+
const params = method.getParameters();
|
|
86
|
+
let requestType = params.length > 0 ? params[0].getType().getText() : undefined;
|
|
87
|
+
|
|
88
|
+
// Clean up type text: remove import() expressions and fix formatting
|
|
89
|
+
if (requestType) {
|
|
90
|
+
// Remove all import("path") expressions
|
|
91
|
+
requestType = requestType.replace(/import\([^)]+\)\./g, '');
|
|
92
|
+
|
|
93
|
+
// If it's the default RequestInit | InitOverrideFunction, treat as no params
|
|
94
|
+
if (requestType === 'RequestInit | InitOverrideFunction') {
|
|
95
|
+
requestType = undefined;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Get return type
|
|
100
|
+
const returnType = method.getReturnType();
|
|
101
|
+
const responseType = extractResponseType(returnType.getText());
|
|
102
|
+
|
|
103
|
+
// Find corresponding RequestOpts method
|
|
104
|
+
const requestOptsMethodName = `${methodName}RequestOpts`;
|
|
105
|
+
const requestOptsMethod = sourceFile.getClasses()[0].getMethod(requestOptsMethodName);
|
|
106
|
+
|
|
107
|
+
if (!requestOptsMethod) {
|
|
108
|
+
p.log.warn(`Could not find ${requestOptsMethodName} method`);
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Parse request options
|
|
113
|
+
const requestOpts = parseRequestOptions(requestOptsMethod);
|
|
114
|
+
|
|
115
|
+
// Get description from JSDoc
|
|
116
|
+
const jsDocs = method.getJsDocs();
|
|
117
|
+
const description = jsDocs.length > 0 ? jsDocs[0].getDescription().trim() : undefined;
|
|
118
|
+
|
|
119
|
+
// Detect if Raw method exists
|
|
120
|
+
const rawMethodName = `${methodName}Raw`;
|
|
121
|
+
const classDeclaration = sourceFile.getClasses()[0];
|
|
122
|
+
const hasRawMethod = classDeclaration.getMethod(rawMethodName) !== undefined;
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
name: methodName,
|
|
126
|
+
composableName,
|
|
127
|
+
requestType,
|
|
128
|
+
responseType,
|
|
129
|
+
httpMethod: requestOpts.method,
|
|
130
|
+
path: requestOpts.path,
|
|
131
|
+
hasBody: requestOpts.hasBody,
|
|
132
|
+
bodyField: requestOpts.bodyField,
|
|
133
|
+
hasQueryParams: requestOpts.queryParams.length > 0,
|
|
134
|
+
queryParams: requestOpts.queryParams,
|
|
135
|
+
pathParams: extractPathParams(requestOpts.path),
|
|
136
|
+
headers: requestOpts.headers,
|
|
137
|
+
description,
|
|
138
|
+
hasRawMethod,
|
|
139
|
+
rawMethodName: hasRawMethod ? rawMethodName : undefined,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Extract response type from Promise<Type>
|
|
145
|
+
*/
|
|
146
|
+
function extractResponseType(returnTypeText: string): string {
|
|
147
|
+
// Match Promise<Type>
|
|
148
|
+
const match = returnTypeText.match(/Promise<(.+)>$/);
|
|
149
|
+
if (match) {
|
|
150
|
+
// Remove all import("path") expressions
|
|
151
|
+
return match[1].replace(/import\([^)]+\)\./g, '');
|
|
152
|
+
}
|
|
153
|
+
return 'void';
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Parse the RequestOpts method to extract request details
|
|
158
|
+
*/
|
|
159
|
+
function parseRequestOptions(method: MethodDeclaration): {
|
|
160
|
+
path: string;
|
|
161
|
+
method: string;
|
|
162
|
+
headers: Record<string, string>;
|
|
163
|
+
hasBody: boolean;
|
|
164
|
+
bodyField?: string;
|
|
165
|
+
queryParams: string[];
|
|
166
|
+
} {
|
|
167
|
+
const result = {
|
|
168
|
+
path: '',
|
|
169
|
+
method: 'GET',
|
|
170
|
+
headers: {} as Record<string, string>,
|
|
171
|
+
hasBody: false,
|
|
172
|
+
bodyField: undefined as string | undefined,
|
|
173
|
+
queryParams: [] as string[],
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// Find the return statement
|
|
177
|
+
const returnStatements = method.getDescendantsOfKind(SyntaxKind.ReturnStatement);
|
|
178
|
+
if (returnStatements.length === 0) {
|
|
179
|
+
return result;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const returnStmt = returnStatements[0];
|
|
183
|
+
const objectLiteral = returnStmt.getFirstDescendantByKind(SyntaxKind.ObjectLiteralExpression);
|
|
184
|
+
|
|
185
|
+
if (!objectLiteral) {
|
|
186
|
+
return result;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Parse each property
|
|
190
|
+
for (const prop of objectLiteral.getProperties()) {
|
|
191
|
+
if (prop.getKind() !== SyntaxKind.PropertyAssignment) {
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const propAssignment = prop.asKind(SyntaxKind.PropertyAssignment);
|
|
196
|
+
if (!propAssignment) {
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const propName = propAssignment.getName();
|
|
201
|
+
const initializer = propAssignment.getInitializer();
|
|
202
|
+
|
|
203
|
+
if (!initializer) {
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
switch (propName) {
|
|
208
|
+
case 'path': {
|
|
209
|
+
// Extract path from variable assignment
|
|
210
|
+
const pathValue = extractStringValue(initializer, method);
|
|
211
|
+
if (pathValue) {
|
|
212
|
+
result.path = pathValue;
|
|
213
|
+
}
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
case 'method': {
|
|
217
|
+
const methodValue = extractStringValue(initializer, method);
|
|
218
|
+
if (methodValue) {
|
|
219
|
+
result.method = methodValue;
|
|
220
|
+
}
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
case 'body': {
|
|
224
|
+
result.hasBody = true;
|
|
225
|
+
// Try to extract body field (e.g., params['pet'] or params.pet)
|
|
226
|
+
const bodyText = initializer.getText();
|
|
227
|
+
const bodyMatch = bodyText.match(/requestParameters(?:\['(\w+)'\]|\.(\w+))/);
|
|
228
|
+
if (bodyMatch) {
|
|
229
|
+
result.bodyField = bodyMatch[1] || bodyMatch[2];
|
|
230
|
+
}
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
case 'headers': {
|
|
234
|
+
// Extract headers if it's an object literal
|
|
235
|
+
if (initializer.getKind() === SyntaxKind.ObjectLiteralExpression) {
|
|
236
|
+
const headersObj = initializer.asKind(SyntaxKind.ObjectLiteralExpression);
|
|
237
|
+
if (headersObj) {
|
|
238
|
+
for (const headerProp of headersObj.getProperties()) {
|
|
239
|
+
if (headerProp.getKind() === SyntaxKind.PropertyAssignment) {
|
|
240
|
+
const headerAssignment = headerProp.asKind(SyntaxKind.PropertyAssignment);
|
|
241
|
+
if (headerAssignment) {
|
|
242
|
+
const headerName = headerAssignment.getName();
|
|
243
|
+
const headerValue = headerAssignment.getInitializer();
|
|
244
|
+
if (headerValue && headerValue.getKind() === SyntaxKind.StringLiteral) {
|
|
245
|
+
result.headers[headerName] = headerValue.getText().slice(1, -1);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
break;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Extract query parameters from the method body
|
|
258
|
+
result.queryParams = extractQueryParams(method);
|
|
259
|
+
|
|
260
|
+
return result;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Extract string value from expression
|
|
265
|
+
*/
|
|
266
|
+
function extractStringValue(node: Node, method: MethodDeclaration): string | null {
|
|
267
|
+
// Direct string literal
|
|
268
|
+
if (node.getKind() === SyntaxKind.StringLiteral) {
|
|
269
|
+
return node.getText().slice(1, -1); // Remove quotes
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Template literal
|
|
273
|
+
if (
|
|
274
|
+
node.getKind() === SyntaxKind.TemplateExpression ||
|
|
275
|
+
node.getKind() === SyntaxKind.NoSubstitutionTemplateLiteral
|
|
276
|
+
) {
|
|
277
|
+
return node.getText().slice(1, -1); // Remove backticks
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// Variable reference - try to find its value
|
|
281
|
+
if (node.getKind() === SyntaxKind.Identifier) {
|
|
282
|
+
const varName = node.getText();
|
|
283
|
+
|
|
284
|
+
// Find variable declarations in the method body
|
|
285
|
+
const varDeclarations = method.getDescendantsOfKind(SyntaxKind.VariableDeclaration);
|
|
286
|
+
for (const varDecl of varDeclarations) {
|
|
287
|
+
if (varDecl.getName() === varName) {
|
|
288
|
+
const initializer = varDecl.getInitializer();
|
|
289
|
+
if (initializer) {
|
|
290
|
+
if (initializer.getKind() === SyntaxKind.StringLiteral) {
|
|
291
|
+
return initializer.getText().slice(1, -1);
|
|
292
|
+
}
|
|
293
|
+
if (
|
|
294
|
+
initializer.getKind() === SyntaxKind.TemplateExpression ||
|
|
295
|
+
initializer.getKind() === SyntaxKind.NoSubstitutionTemplateLiteral
|
|
296
|
+
) {
|
|
297
|
+
return initializer.getText().slice(1, -1);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Extract query parameters from method body
|
|
309
|
+
*/
|
|
310
|
+
function extractQueryParams(method: MethodDeclaration): string[] {
|
|
311
|
+
const params: string[] = [];
|
|
312
|
+
const methodText = method.getText();
|
|
313
|
+
|
|
314
|
+
// Look for queryParameters['paramName'] or queryParameters.paramName
|
|
315
|
+
const regex = /queryParameters(?:\['(\w+)'\]|\.(\w+))/g;
|
|
316
|
+
let match;
|
|
317
|
+
|
|
318
|
+
while ((match = regex.exec(methodText)) !== null) {
|
|
319
|
+
const paramName = match[1] || match[2];
|
|
320
|
+
if (paramName && !params.includes(paramName)) {
|
|
321
|
+
params.push(paramName);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
return params;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Extract path parameters from path string (e.g., /pet/{petId} -> ['petId'])
|
|
330
|
+
*/
|
|
331
|
+
function extractPathParams(path: string): string[] {
|
|
332
|
+
const regex = /\{(\w+)\}/g;
|
|
333
|
+
const params: string[] = [];
|
|
334
|
+
let match;
|
|
335
|
+
|
|
336
|
+
while ((match = regex.exec(path)) !== null) {
|
|
337
|
+
params.push(match[1]);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return params;
|
|
341
|
+
}
|