@aloma.io/integration-sdk 3.8.70 → 3.8.71
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/README.md +15 -2
- package/build/internal/connector/server/on-connect/make-oauth.mjs +27 -6
- package/build/internal/fetcher/fetcher.d.mts +14 -1
- package/build/internal/fetcher/fetcher.mjs +52 -11
- package/build/internal/fetcher/oauth-fetcher.d.mts +15 -2
- package/build/internal/fetcher/oauth-fetcher.mjs +72 -27
- package/build/internal/util/index.d.mts +8 -0
- package/build/internal/util/index.mjs +13 -1
- package/build/internal/util/jwe/index.mjs +3 -1
- package/package.json +8 -3
- package/.prettierrc.cjs +0 -8
- package/FINDINGS-PLAT-47.md +0 -253
- package/MULTI_RESOURCE_GUIDE.md +0 -220
- package/OPENAPI_TO_CONNECTOR.md +0 -349
- package/examples/hello-world/package.json +0 -25
- package/examples/hello-world/src/controller/index.mts +0 -12
- package/examples/hello-world/src/index.mts +0 -6
- package/examples/hello-world/tsconfig.json +0 -27
- package/examples/sample-api.json +0 -325
- package/examples/sample-api.yaml +0 -222
- package/examples/simple-api.json +0 -39
- package/index.js +0 -4
- package/src/builder/index.mts +0 -274
- package/src/builder/runtime-context.mts +0 -129
- package/src/cli.mts +0 -533
- package/src/controller/index.mts +0 -278
- package/src/index.mts +0 -2
- package/src/internal/connector/config.mts +0 -59
- package/src/internal/connector/index.mts +0 -53
- package/src/internal/connector/metrics.mts +0 -34
- package/src/internal/connector/server/index.mts +0 -51
- package/src/internal/connector/server/on-connect/decrypt-config.mts +0 -27
- package/src/internal/connector/server/on-connect/finish-oauth.mts +0 -109
- package/src/internal/connector/server/on-connect/index.mts +0 -162
- package/src/internal/connector/server/on-connect/make-oauth.mts +0 -97
- package/src/internal/connector/server/on-connect/start-oauth.mts +0 -24
- package/src/internal/connector/server/on-message.mts +0 -13
- package/src/internal/dispatcher/index.mts +0 -231
- package/src/internal/fetcher/fetcher.mts +0 -215
- package/src/internal/fetcher/oauth-fetcher.mts +0 -153
- package/src/internal/index.mts +0 -3
- package/src/internal/util/index.mts +0 -52
- package/src/internal/util/jwe/cli.mts +0 -12
- package/src/internal/util/jwe/index.mts +0 -72
- package/src/internal/websocket/config.mjs +0 -109
- package/src/internal/websocket/connection/constants.mjs +0 -25
- package/src/internal/websocket/connection/index.mjs +0 -71
- package/src/internal/websocket/connection/registration.mjs +0 -42
- package/src/internal/websocket/index.mjs +0 -46
- package/src/internal/websocket/transport/durable.mjs +0 -71
- package/src/internal/websocket/transport/index.mjs +0 -194
- package/src/internal/websocket/transport/packet.mjs +0 -54
- package/src/internal/websocket/transport/processor.mjs +0 -66
- package/src/openapi-to-connector.mts +0 -1648
- package/src/testing/fake-aloma.mts +0 -306
- package/src/testing/harness.mts +0 -172
- package/src/testing/index.mts +0 -15
- package/src/testing/keys.mts +0 -19
- package/src/testing/network-guard.mts +0 -57
- package/src/testing/runtime-connector.mts +0 -50
- package/src/testing/vendor-mock.mts +0 -166
- package/src/transform/index.mts +0 -544
- package/test/MUTATION-entry.md +0 -21
- package/test/MUTATION.md +0 -43
- package/test/dispatcher-ctx-forwarding.test.mjs +0 -161
- package/test/fetcher-query-params.test.mjs +0 -294
- package/test/fixtures/transform/basic/expected.json +0 -9
- package/test/fixtures/transform/basic/src/controller/abstract.mts +0 -5
- package/test/fixtures/transform/basic/src/controller/index.mts +0 -30
- package/test/fixtures/transform/basic/tsconfig.json +0 -1
- package/test/fixtures/transform/interface-param/src/controller/abstract.mts +0 -5
- package/test/fixtures/transform/interface-param/src/controller/index.mts +0 -12
- package/test/fixtures/transform/interface-param/tsconfig.json +0 -1
- package/test/fixtures/transform/overloads/expected.json +0 -6
- package/test/fixtures/transform/overloads/src/controller/abstract.mts +0 -5
- package/test/fixtures/transform/overloads/src/controller/index.mts +0 -11
- package/test/fixtures/transform/overloads/tsconfig.json +0 -1
- package/test/fixtures/transform/tdd-stub/expected.json +0 -8
- package/test/fixtures/transform/tdd-stub/src/controller/abstract.mts +0 -6
- package/test/fixtures/transform/tdd-stub/src/controller/index.mts +0 -204
- package/test/fixtures/transform/tdd-stub/tsconfig.json +0 -1
- package/test/fixtures/transform/two-exports/src/controller/abstract.mts +0 -5
- package/test/fixtures/transform/two-exports/src/controller/index.mts +0 -9
- package/test/fixtures/transform/two-exports/tsconfig.json +0 -1
- package/test/fixtures/transform/type-error/src/controller/abstract.mts +0 -5
- package/test/fixtures/transform/type-error/src/controller/index.mts +0 -7
- package/test/fixtures/transform/type-error/tsconfig.json +0 -1
- package/test/fixtures/transform/typed/expected.json +0 -8
- package/test/fixtures/transform/typed/src/controller/abstract.mts +0 -5
- package/test/fixtures/transform/typed/src/controller/index.mts +0 -13
- package/test/fixtures/transform/typed/tsconfig.json +0 -1
- package/test/fixtures/transform/visibility/expected.json +0 -9
- package/test/fixtures/transform/visibility/src/controller/abstract.mts +0 -5
- package/test/fixtures/transform/visibility/src/controller/index.mts +0 -19
- package/test/fixtures/transform/visibility/tsconfig.json +0 -1
- package/test/harness-connector-smoke.test.mjs +0 -72
- package/test/harness.test.mjs +0 -375
- package/test/nested-resolver.test.mjs +0 -184
- package/test/openapi-generator-bugs.test.mjs +0 -248
- package/test/openapi-identifier-sanitise.test.mjs +0 -69
- package/test/openapi-nested-paths.test.mjs +0 -100
- package/test/openapi-to-connector.test.mts +0 -232
- package/test/openapi-ts-compilation.test.mjs +0 -178
- package/test/scenarios/README.md +0 -148
- package/test/scenarios/complex/expected/controller.mts +0 -271
- package/test/scenarios/complex/expected/orders-resource.mts +0 -262
- package/test/scenarios/complex/expected/products-resource.mts +0 -237
- package/test/scenarios/complex/specs/orders.json +0 -362
- package/test/scenarios/complex/specs/products.json +0 -308
- package/test/scenarios/simple/expected-controller.mts +0 -60
- package/test/scenarios/simple/simple-api.json +0 -39
- package/test/scenarios.test.mts +0 -294
- package/test/transform.test.mjs +0 -68
- package/test/verify-scenarios.mjs +0 -298
- package/tools/mutation-run-entry.mjs +0 -52
- package/tools/mutation-run.mjs +0 -138
- package/tools/run-tests.mjs +0 -64
- package/tsconfig.json +0 -27
|
@@ -1,1648 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
import {Command} from 'commander';
|
|
4
|
-
import fs from 'node:fs';
|
|
5
|
-
import yaml from 'js-yaml';
|
|
6
|
-
import {OpenAPIV3} from 'openapi-types';
|
|
7
|
-
import {z} from 'zod';
|
|
8
|
-
|
|
9
|
-
// OpenAPI 3.x validation schema
|
|
10
|
-
const OpenAPISchema = z.object({
|
|
11
|
-
openapi: z.string().regex(/^3\.\d+\.\d+$/),
|
|
12
|
-
info: z.object({
|
|
13
|
-
title: z.string(),
|
|
14
|
-
version: z.string(),
|
|
15
|
-
description: z.string().optional(),
|
|
16
|
-
}),
|
|
17
|
-
paths: z.record(z.string(), z.any()),
|
|
18
|
-
servers: z
|
|
19
|
-
.array(
|
|
20
|
-
z.object({
|
|
21
|
-
url: z.string(),
|
|
22
|
-
description: z.string().optional(),
|
|
23
|
-
})
|
|
24
|
-
)
|
|
25
|
-
.optional(),
|
|
26
|
-
components: z.any().optional(),
|
|
27
|
-
});
|
|
28
|
-
|
|
29
|
-
interface OperationInfo {
|
|
30
|
-
method: string;
|
|
31
|
-
path: string;
|
|
32
|
-
operationId?: string;
|
|
33
|
-
summary?: string;
|
|
34
|
-
description?: string;
|
|
35
|
-
parameters?: any[];
|
|
36
|
-
requestBody?: any;
|
|
37
|
-
responses?: any;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export interface OpenAPIToConnectorOptions {
|
|
41
|
-
nestedPaths?: boolean;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export class OpenAPIToConnector {
|
|
45
|
-
private spec: OpenAPIV3.Document;
|
|
46
|
-
private connectorName: string;
|
|
47
|
-
private options: OpenAPIToConnectorOptions;
|
|
48
|
-
|
|
49
|
-
constructor(spec: OpenAPIV3.Document, connectorName: string, options?: OpenAPIToConnectorOptions) {
|
|
50
|
-
this.spec = spec;
|
|
51
|
-
this.connectorName = connectorName;
|
|
52
|
-
this.options = options || {};
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* Derive a dotted method path from URL path and operationId.
|
|
57
|
-
* When nestedPaths is enabled, builds a namespace from the URL segments.
|
|
58
|
-
* When disabled (default), falls back to the existing flat method name.
|
|
59
|
-
*/
|
|
60
|
-
deriveMethodPath(httpMethod: string, urlPath: string, operationId: string): string {
|
|
61
|
-
if (!this.options.nestedPaths) {
|
|
62
|
-
return this.generateMethodName({method: httpMethod, path: urlPath, operationId});
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const VERSION_RE = /^v\d+$|^\d{4}-\d{2}$/;
|
|
66
|
-
const STRIP = new Set(['objects', 'items']);
|
|
67
|
-
|
|
68
|
-
// Convert hyphenated segment to camelCase identifier
|
|
69
|
-
const toCamel = (s: string): string =>
|
|
70
|
-
s.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
71
|
-
|
|
72
|
-
// Build namespace parts from the URL path
|
|
73
|
-
const parts = urlPath
|
|
74
|
-
.replace(/\{[^}]+\}/g, '')
|
|
75
|
-
.split('/')
|
|
76
|
-
.filter(Boolean)
|
|
77
|
-
.filter((p) => !VERSION_RE.test(p))
|
|
78
|
-
.filter((p) => !STRIP.has(p))
|
|
79
|
-
.map(toCamel);
|
|
80
|
-
|
|
81
|
-
// Extract the leaf action from operationId suffix
|
|
82
|
-
let suffix = operationId.includes('_')
|
|
83
|
-
? operationId.split('_').pop()!
|
|
84
|
-
: httpMethod.toLowerCase();
|
|
85
|
-
|
|
86
|
-
// Bug 3 fix: If the suffix looks like a raw URL path (contains slashes),
|
|
87
|
-
// clean it by extracting meaningful segments rather than using it literally
|
|
88
|
-
if (suffix.includes('/')) {
|
|
89
|
-
const suffixParts = suffix
|
|
90
|
-
.replace(/\{[^}]+\}/g, '')
|
|
91
|
-
.split('/')
|
|
92
|
-
.filter(Boolean)
|
|
93
|
-
.filter((p) => !VERSION_RE.test(p))
|
|
94
|
-
.filter((p) => !STRIP.has(p))
|
|
95
|
-
.map(toCamel);
|
|
96
|
-
suffix = suffixParts.length > 0 ? suffixParts[suffixParts.length - 1] : httpMethod.toLowerCase();
|
|
97
|
-
} else {
|
|
98
|
-
suffix = toCamel(suffix);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// Dedup: if suffix equals last path segment, don't repeat it
|
|
102
|
-
const last = parts[parts.length - 1];
|
|
103
|
-
if (suffix === last) return parts.join('.');
|
|
104
|
-
return [...parts, suffix].join('.');
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* Parse OpenAPI spec from JSON or YAML string
|
|
109
|
-
*/
|
|
110
|
-
static parseSpec(specString: string): OpenAPIV3.Document {
|
|
111
|
-
let parsed: any;
|
|
112
|
-
|
|
113
|
-
try {
|
|
114
|
-
// Try parsing as JSON first
|
|
115
|
-
parsed = JSON.parse(specString);
|
|
116
|
-
} catch {
|
|
117
|
-
try {
|
|
118
|
-
// If JSON fails, try YAML
|
|
119
|
-
parsed = yaml.load(specString);
|
|
120
|
-
} catch (error) {
|
|
121
|
-
throw new Error(`Failed to parse OpenAPI spec: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// Validate against OpenAPI 3.x schema with lenient validation
|
|
126
|
-
const validationResult = OpenAPISchema.safeParse(parsed);
|
|
127
|
-
if (!validationResult.success) {
|
|
128
|
-
// Check if the errors are just about missing 'type' fields in schemas
|
|
129
|
-
// zod 4 reports .issues (zod 3's .errors is gone), and a missing field is an invalid_type issue whose message no
|
|
130
|
-
// longer reads 'Required'
|
|
131
|
-
const isMissing = (err: any) =>
|
|
132
|
-
err.message.includes('Required') || (err.code === 'invalid_type' && /received undefined/.test(err.message));
|
|
133
|
-
const criticalErrors = validationResult.error.issues.filter((err) => {
|
|
134
|
-
const path = err.path.join('.');
|
|
135
|
-
// Allow missing 'type' in schema definitions as many OpenAPI specs don't include it
|
|
136
|
-
return !path.includes('components.schemas') || !isMissing(err);
|
|
137
|
-
});
|
|
138
|
-
|
|
139
|
-
if (criticalErrors.length > 0) {
|
|
140
|
-
const errors = criticalErrors.map((err) => `${err.path.join('.')}: ${err.message}`).join(', ');
|
|
141
|
-
throw new Error(`Invalid OpenAPI 3.x specification: ${errors}`);
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// Log a warning about lenient validation
|
|
145
|
-
console.warn('⚠️ OpenAPI spec has some validation warnings but proceeding with lenient validation...');
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
return parsed as OpenAPIV3.Document;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Extract all operations from the OpenAPI spec
|
|
153
|
-
*/
|
|
154
|
-
private extractOperations(): OperationInfo[] {
|
|
155
|
-
const operations: OperationInfo[] = [];
|
|
156
|
-
|
|
157
|
-
for (const [path, pathItem] of Object.entries(this.spec.paths)) {
|
|
158
|
-
if (!pathItem) continue;
|
|
159
|
-
|
|
160
|
-
const methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'] as const;
|
|
161
|
-
|
|
162
|
-
for (const method of methods) {
|
|
163
|
-
const operation = pathItem[method];
|
|
164
|
-
if (!operation) continue;
|
|
165
|
-
|
|
166
|
-
operations.push({
|
|
167
|
-
method: method.toUpperCase(),
|
|
168
|
-
path,
|
|
169
|
-
operationId: operation.operationId,
|
|
170
|
-
summary: operation.summary,
|
|
171
|
-
description: operation.description,
|
|
172
|
-
parameters: operation.parameters,
|
|
173
|
-
requestBody: operation.requestBody,
|
|
174
|
-
responses: operation.responses,
|
|
175
|
-
});
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
return operations;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* Generate a valid JavaScript identifier from a string
|
|
184
|
-
*/
|
|
185
|
-
private toValidIdentifier(str: string): string {
|
|
186
|
-
return str
|
|
187
|
-
.replace(/[^a-zA-Z0-9_$]/g, '_')
|
|
188
|
-
.replace(/^[0-9]/, '_$&')
|
|
189
|
-
.replace(/_+/g, '_')
|
|
190
|
-
.replace(/^_|_$/g, '');
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/**
|
|
194
|
-
* Generate method name from operation info
|
|
195
|
-
*/
|
|
196
|
-
private generateMethodName(operation: OperationInfo): string {
|
|
197
|
-
if (operation.operationId) {
|
|
198
|
-
// Clean up HubSpot-style operationIds like "get-/crm/v3/objects/companies_getPage"
|
|
199
|
-
let cleaned = operation.operationId;
|
|
200
|
-
|
|
201
|
-
// Extract the last part after underscore if it exists
|
|
202
|
-
const parts = cleaned.split('_');
|
|
203
|
-
if (parts.length > 1) {
|
|
204
|
-
let lastPart = parts[parts.length - 1];
|
|
205
|
-
// Convert hyphens to camelCase before testing
|
|
206
|
-
lastPart = lastPart.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
207
|
-
// If the last part looks like a method name (camelCase), use it
|
|
208
|
-
if (lastPart && /^[a-z][a-zA-Z0-9]*$/.test(lastPart)) {
|
|
209
|
-
cleaned = lastPart;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
// Remove any remaining special characters and clean up
|
|
214
|
-
cleaned = cleaned
|
|
215
|
-
.replace(/^(get|post|put|patch|delete|head|options)-/i, '') // Remove HTTP method prefix
|
|
216
|
-
.replace(/[^a-zA-Z0-9_]/g, '_')
|
|
217
|
-
.replace(/_+/g, '_')
|
|
218
|
-
.replace(/^_|_$/g, '');
|
|
219
|
-
|
|
220
|
-
// If we still have a valid identifier, use it
|
|
221
|
-
if (cleaned && /^[a-zA-Z]/.test(cleaned)) {
|
|
222
|
-
return cleaned;
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
// Generate from method + path
|
|
227
|
-
const pathParts = operation.path
|
|
228
|
-
.replace(/[{}]/g, '') // Remove path parameters
|
|
229
|
-
.split('/')
|
|
230
|
-
.filter((part) => part.length > 0)
|
|
231
|
-
.map((part) => this.toValidIdentifier(part));
|
|
232
|
-
|
|
233
|
-
const methodPrefix = operation.method.toLowerCase();
|
|
234
|
-
const pathSuffix = pathParts.join('_') || 'root';
|
|
235
|
-
|
|
236
|
-
return `${methodPrefix}_${pathSuffix}`;
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/**
|
|
240
|
-
* Disambiguate a colliding method name by prepending path context.
|
|
241
|
-
* E.g., "archive" from path "/contacts/batch/archive" becomes "batchArchive".
|
|
242
|
-
*/
|
|
243
|
-
private disambiguateMethodName(baseName: string, operation: OperationInfo): string {
|
|
244
|
-
// Extract meaningful path segments excluding parameters and the base name itself
|
|
245
|
-
const pathParts = operation.path
|
|
246
|
-
.replace(/\{[^}]+\}/g, '')
|
|
247
|
-
.split('/')
|
|
248
|
-
.filter(Boolean)
|
|
249
|
-
.filter((p) => p.toLowerCase() !== baseName.toLowerCase());
|
|
250
|
-
|
|
251
|
-
// Use the last path segment before the method name as a distinguishing prefix
|
|
252
|
-
if (pathParts.length > 0) {
|
|
253
|
-
const prefix = pathParts[pathParts.length - 1].replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
254
|
-
const capitalizedBase = baseName.charAt(0).toUpperCase() + baseName.slice(1);
|
|
255
|
-
return `${prefix}${capitalizedBase}`;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// Fallback: prepend the HTTP method
|
|
259
|
-
return `${operation.method.toLowerCase()}${baseName.charAt(0).toUpperCase() + baseName.slice(1)}`;
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
/**
|
|
263
|
-
* Get the number of operations in the OpenAPI spec
|
|
264
|
-
*/
|
|
265
|
-
getOperationsCount(): number {
|
|
266
|
-
return this.extractOperations().length;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
/**
|
|
270
|
-
* Generate method signature with options object
|
|
271
|
-
*/
|
|
272
|
-
private generateMethodSignature(operation: OperationInfo): string {
|
|
273
|
-
const pathParams: Array<{name: string; required: boolean; type: string}> = [];
|
|
274
|
-
const queryParams: Array<{name: string; required: boolean; type: string}> = [];
|
|
275
|
-
const hasBody = !!operation.requestBody;
|
|
276
|
-
|
|
277
|
-
// Identify path and query parameters with their types and required status
|
|
278
|
-
if (operation.parameters) {
|
|
279
|
-
for (const param of operation.parameters) {
|
|
280
|
-
if (typeof param === 'object' && 'name' in param && 'in' in param) {
|
|
281
|
-
const paramInfo = {
|
|
282
|
-
name: param.name,
|
|
283
|
-
required: param.required || false,
|
|
284
|
-
type: this.getParameterType(param),
|
|
285
|
-
};
|
|
286
|
-
|
|
287
|
-
if (param.in === 'path') {
|
|
288
|
-
pathParams.push(paramInfo);
|
|
289
|
-
} else if (param.in === 'query') {
|
|
290
|
-
queryParams.push(paramInfo);
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
// Always extract path parameters as discrete parameters when they exist
|
|
297
|
-
if (pathParams.length > 0) {
|
|
298
|
-
const params: string[] = [];
|
|
299
|
-
for (const paramInfo of pathParams) {
|
|
300
|
-
params.push(`${paramInfo.name}: ${paramInfo.type}`);
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
// Build options object for query params and body
|
|
304
|
-
const optionProps: string[] = [];
|
|
305
|
-
|
|
306
|
-
// Add query parameters to options
|
|
307
|
-
for (const prop of queryParams) {
|
|
308
|
-
const optional = prop.required ? '' : '?';
|
|
309
|
-
optionProps.push(`${prop.name}${optional}: ${prop.type}`);
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
// Add request body properties directly (flattened)
|
|
313
|
-
if (hasBody) {
|
|
314
|
-
this.addRequestBodyProperties(operation.requestBody, optionProps);
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
// Always include headers in options type (generated code references options.headers)
|
|
318
|
-
optionProps.push('headers?: Record<string, string>');
|
|
319
|
-
|
|
320
|
-
// Check if options parameter is required (has required query params or required body)
|
|
321
|
-
const hasRequiredNonPathParams =
|
|
322
|
-
queryParams.some((p) => p.required) || (hasBody && operation.requestBody?.required);
|
|
323
|
-
const optionsRequired = hasRequiredNonPathParams ? '' : '?';
|
|
324
|
-
|
|
325
|
-
// Only add options parameter if there are actual options
|
|
326
|
-
if (optionProps.length > 0) {
|
|
327
|
-
params.push(`options${optionsRequired}: {${optionProps.join(', ')}}`);
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
return `(${params.join(', ')})`;
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// Check if there are any required parameters
|
|
334
|
-
const hasRequiredParams =
|
|
335
|
-
pathParams.some((p) => p.required) ||
|
|
336
|
-
queryParams.some((p) => p.required) ||
|
|
337
|
-
(hasBody && operation.requestBody?.required);
|
|
338
|
-
|
|
339
|
-
// Build detailed options object with proper types
|
|
340
|
-
// Group nested properties into objects (e.g., PrimaryContact.FirstName -> PrimaryContact: {FirstName: string})
|
|
341
|
-
const nestedObjects: Map<string, Array<{name: string; type: string; required: boolean}>> = new Map();
|
|
342
|
-
const flatProps: Array<{name: string; type: string; required: boolean}> = [];
|
|
343
|
-
|
|
344
|
-
// Process all parameters (path + query)
|
|
345
|
-
const allParams = [...pathParams, ...queryParams];
|
|
346
|
-
|
|
347
|
-
for (const paramInfo of allParams) {
|
|
348
|
-
if (paramInfo.name.includes('.')) {
|
|
349
|
-
// This is a nested property like PrimaryContact.FirstName
|
|
350
|
-
const parts = paramInfo.name.split('.');
|
|
351
|
-
const objectName = parts[0];
|
|
352
|
-
const propertyName = parts.slice(1).join('.');
|
|
353
|
-
|
|
354
|
-
if (!nestedObjects.has(objectName)) {
|
|
355
|
-
nestedObjects.set(objectName, []);
|
|
356
|
-
}
|
|
357
|
-
nestedObjects.get(objectName)!.push({
|
|
358
|
-
name: propertyName,
|
|
359
|
-
type: paramInfo.type,
|
|
360
|
-
required: paramInfo.required,
|
|
361
|
-
});
|
|
362
|
-
} else {
|
|
363
|
-
// This is a flat property
|
|
364
|
-
flatProps.push({
|
|
365
|
-
name: paramInfo.name,
|
|
366
|
-
type: paramInfo.type,
|
|
367
|
-
required: paramInfo.required,
|
|
368
|
-
});
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// Build the options properties array
|
|
373
|
-
const optionProps: string[] = [];
|
|
374
|
-
|
|
375
|
-
// Add flat properties
|
|
376
|
-
for (const prop of flatProps) {
|
|
377
|
-
const optional = prop.required ? '' : '?';
|
|
378
|
-
optionProps.push(`${prop.name}${optional}: ${prop.type}`);
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
// Add nested objects
|
|
382
|
-
for (const [objectName, properties] of nestedObjects) {
|
|
383
|
-
const nestedProps = properties
|
|
384
|
-
.map((p) => {
|
|
385
|
-
const optional = p.required ? '' : '?';
|
|
386
|
-
return `${p.name}${optional}: ${p.type}`;
|
|
387
|
-
})
|
|
388
|
-
.join(', ');
|
|
389
|
-
|
|
390
|
-
// Check if all properties are optional
|
|
391
|
-
const allOptional = properties.every((p) => !p.required);
|
|
392
|
-
const optional = allOptional ? '?' : '';
|
|
393
|
-
|
|
394
|
-
optionProps.push(`${objectName}${optional}: {${nestedProps}}`);
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
// Add request body properties directly (flattened)
|
|
398
|
-
if (hasBody) {
|
|
399
|
-
this.addRequestBodyProperties(operation.requestBody, optionProps);
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
// Always include headers in options type (generated code references options.headers)
|
|
403
|
-
optionProps.push('headers?: Record<string, string>');
|
|
404
|
-
|
|
405
|
-
// If there are too many parameters, use simplified signature to avoid parsing issues
|
|
406
|
-
// Also check if any parameter name is too long (over 100 chars) which can cause issues
|
|
407
|
-
const hasLongParamNames = optionProps.some((prop) => prop.length > 100);
|
|
408
|
-
if (optionProps.length > 15 || hasLongParamNames) {
|
|
409
|
-
const required = hasRequiredParams ? '' : '?';
|
|
410
|
-
return `(options${required}: {[key: string]: any})`;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
// Only add options if there are actual options
|
|
414
|
-
if (optionProps.length > 0) {
|
|
415
|
-
const required = hasRequiredParams ? '' : '?';
|
|
416
|
-
return `(options${required}: {${optionProps.join(', ')}})`;
|
|
417
|
-
} else {
|
|
418
|
-
return '()';
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
/**
|
|
423
|
-
* Resolve a schema reference to a TypeScript type name
|
|
424
|
-
*/
|
|
425
|
-
private resolveSchemaRef(ref: string): string {
|
|
426
|
-
const parts = ref.split('/');
|
|
427
|
-
if (parts.length >= 2) {
|
|
428
|
-
const componentName = parts[parts.length - 1];
|
|
429
|
-
if (!this.spec.components?.schemas?.[componentName]) {
|
|
430
|
-
return 'any';
|
|
431
|
-
}
|
|
432
|
-
return this.sanitizeTypeName(componentName);
|
|
433
|
-
}
|
|
434
|
-
return 'any';
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
/**
|
|
438
|
-
* Sanitize a name to be a valid TypeScript identifier
|
|
439
|
-
*/
|
|
440
|
-
private sanitizeTypeName(name: string): string {
|
|
441
|
-
return (
|
|
442
|
-
name
|
|
443
|
-
// Replace dots with underscores
|
|
444
|
-
.replace(/\./g, '_')
|
|
445
|
-
// Replace + with _Plus (common in OpenAPI for enums)
|
|
446
|
-
.replace(/\+/g, '_Plus')
|
|
447
|
-
// Replace other invalid characters with underscores
|
|
448
|
-
.replace(/[^a-zA-Z0-9_$]/g, '_')
|
|
449
|
-
// Ensure it starts with a letter or underscore
|
|
450
|
-
.replace(/^[0-9]/, '_$&')
|
|
451
|
-
// Remove multiple consecutive underscores
|
|
452
|
-
.replace(/_+/g, '_')
|
|
453
|
-
// Remove trailing/leading underscores
|
|
454
|
-
.replace(/^_+|_+$/g, '') ||
|
|
455
|
-
// Ensure it's not empty
|
|
456
|
-
'UnknownType'
|
|
457
|
-
);
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
/**
|
|
461
|
-
* Get TypeScript type from schema object
|
|
462
|
-
*/
|
|
463
|
-
private getTypeFromSchema(schema: any): string {
|
|
464
|
-
if (!schema) return 'any';
|
|
465
|
-
|
|
466
|
-
// Handle $ref
|
|
467
|
-
if (schema.$ref) {
|
|
468
|
-
return this.resolveSchemaRef(schema.$ref);
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
// Handle arrays
|
|
472
|
-
if (schema.type === 'array') {
|
|
473
|
-
if (schema.items) {
|
|
474
|
-
const itemType = this.getTypeFromSchema(schema.items);
|
|
475
|
-
return `${itemType}[]`;
|
|
476
|
-
}
|
|
477
|
-
return 'any[]';
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
// Handle objects with properties
|
|
481
|
-
if (schema.type === 'object' && schema.properties) {
|
|
482
|
-
const propNames = Object.keys(schema.properties);
|
|
483
|
-
|
|
484
|
-
// For response objects, generate inline type definitions
|
|
485
|
-
if (propNames.length <= 5) {
|
|
486
|
-
// Reasonable limit for inline types
|
|
487
|
-
const propTypes = Object.entries(schema.properties).map(([key, prop]: [string, any]) => {
|
|
488
|
-
const propType = this.getTypeFromSchema(prop);
|
|
489
|
-
return `${key}: ${propType}`;
|
|
490
|
-
});
|
|
491
|
-
return `{${propTypes.join('; ')}}`;
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
// For complex objects, return a generic object type
|
|
495
|
-
return 'any';
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
// Handle other primitive types
|
|
499
|
-
if (schema.type) {
|
|
500
|
-
switch (schema.type) {
|
|
501
|
-
case 'string':
|
|
502
|
-
return 'string';
|
|
503
|
-
case 'integer':
|
|
504
|
-
case 'number':
|
|
505
|
-
return 'number';
|
|
506
|
-
case 'boolean':
|
|
507
|
-
return 'boolean';
|
|
508
|
-
case 'object':
|
|
509
|
-
return 'any';
|
|
510
|
-
default:
|
|
511
|
-
return 'any';
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
// Handle enum
|
|
516
|
-
if (schema.enum) {
|
|
517
|
-
return 'string'; // Could be expanded to union types
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
// Handle allOf, oneOf, anyOf
|
|
521
|
-
if (schema.allOf || schema.oneOf || schema.anyOf) {
|
|
522
|
-
return 'any'; // Could be expanded to intersection/union types
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
return 'any';
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
/**
|
|
529
|
-
* Get TypeScript type for request body
|
|
530
|
-
*/
|
|
531
|
-
private getRequestBodyType(requestBody: any): string {
|
|
532
|
-
if (!requestBody) return 'any';
|
|
533
|
-
|
|
534
|
-
// Handle content types
|
|
535
|
-
if (requestBody.content) {
|
|
536
|
-
// Prefer application/json
|
|
537
|
-
if (requestBody.content['application/json']?.schema) {
|
|
538
|
-
return this.getTypeFromSchema(requestBody.content['application/json'].schema);
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
// Fall back to first available content type
|
|
542
|
-
const firstContentType = Object.keys(requestBody.content)[0];
|
|
543
|
-
if (requestBody.content[firstContentType]?.schema) {
|
|
544
|
-
return this.getTypeFromSchema(requestBody.content[firstContentType].schema);
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
return 'any';
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
/**
|
|
552
|
-
* Add request body properties directly to options array (flatten the body)
|
|
553
|
-
*/
|
|
554
|
-
private addRequestBodyProperties(requestBody: any, optionProps: string[]): void {
|
|
555
|
-
if (!requestBody) return;
|
|
556
|
-
|
|
557
|
-
let schema: any = null;
|
|
558
|
-
|
|
559
|
-
// Get the schema from the request body
|
|
560
|
-
if (requestBody.content) {
|
|
561
|
-
// Prefer application/json
|
|
562
|
-
if (requestBody.content['application/json']?.schema) {
|
|
563
|
-
schema = requestBody.content['application/json'].schema;
|
|
564
|
-
} else {
|
|
565
|
-
// Fall back to first available content type
|
|
566
|
-
const firstContentType = Object.keys(requestBody.content)[0];
|
|
567
|
-
if (requestBody.content[firstContentType]?.schema) {
|
|
568
|
-
schema = requestBody.content[firstContentType].schema;
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
if (!schema) return;
|
|
574
|
-
|
|
575
|
-
// Handle $ref in schema
|
|
576
|
-
if (schema.$ref) {
|
|
577
|
-
const refType = this.resolveSchemaRef(schema.$ref);
|
|
578
|
-
const referencedSchema = this.spec.components?.schemas?.[refType];
|
|
579
|
-
if (referencedSchema && !('$ref' in referencedSchema)) {
|
|
580
|
-
schema = referencedSchema;
|
|
581
|
-
} else {
|
|
582
|
-
// If we can't resolve the reference, fall back to the original type
|
|
583
|
-
const bodyType = this.getRequestBodyType(requestBody);
|
|
584
|
-
optionProps.push(`body?: ${bodyType}`);
|
|
585
|
-
return;
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
// If schema has properties, add them individually
|
|
590
|
-
if (schema.properties) {
|
|
591
|
-
for (const [propName, propSchema] of Object.entries(schema.properties)) {
|
|
592
|
-
const propType = this.getTypeFromSchema(propSchema as any);
|
|
593
|
-
const required = (schema.required && schema.required.includes(propName)) || requestBody.required;
|
|
594
|
-
const optional = required ? '' : '?';
|
|
595
|
-
|
|
596
|
-
// Add description as comment if available
|
|
597
|
-
const description = (propSchema as any)?.description;
|
|
598
|
-
if (description) {
|
|
599
|
-
// Clean up description for inline use
|
|
600
|
-
const cleanDesc = description.replace(/\n/g, ' ').replace(/\s+/g, ' ').trim();
|
|
601
|
-
if (cleanDesc.length < 100) {
|
|
602
|
-
// Only add short descriptions inline
|
|
603
|
-
optionProps.push(`${propName}${optional}: ${propType} /** ${cleanDesc} */`);
|
|
604
|
-
} else {
|
|
605
|
-
optionProps.push(`${propName}${optional}: ${propType}`);
|
|
606
|
-
}
|
|
607
|
-
} else {
|
|
608
|
-
optionProps.push(`${propName}${optional}: ${propType}`);
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
} else {
|
|
612
|
-
// If we can't extract individual properties, fall back to body wrapper
|
|
613
|
-
const bodyType = this.getRequestBodyType(requestBody);
|
|
614
|
-
optionProps.push(`body?: ${bodyType}`);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
/**
|
|
619
|
-
* Get TypeScript type for response
|
|
620
|
-
*/
|
|
621
|
-
private getResponseType(operation: OperationInfo): string {
|
|
622
|
-
if (!operation.responses) return 'any';
|
|
623
|
-
|
|
624
|
-
// Try success responses first (200, 201, etc.)
|
|
625
|
-
const successCodes = ['200', '201', '202', '204'];
|
|
626
|
-
for (const code of successCodes) {
|
|
627
|
-
if (operation.responses[code]) {
|
|
628
|
-
const response = operation.responses[code];
|
|
629
|
-
if (response.content) {
|
|
630
|
-
// Prefer application/json
|
|
631
|
-
if (response.content['application/json']?.schema) {
|
|
632
|
-
return this.getTypeFromSchema(response.content['application/json'].schema);
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
// Fall back to first available content type
|
|
636
|
-
const firstContentType = Object.keys(response.content)[0];
|
|
637
|
-
if (response.content[firstContentType]?.schema) {
|
|
638
|
-
return this.getTypeFromSchema(response.content[firstContentType].schema);
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
return 'any';
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
/**
|
|
648
|
-
* Get TypeScript type for a parameter based on its schema
|
|
649
|
-
*/
|
|
650
|
-
private getParameterType(param: any): string {
|
|
651
|
-
if (param.schema) {
|
|
652
|
-
return this.getTypeFromSchema(param.schema);
|
|
653
|
-
}
|
|
654
|
-
return 'any';
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
/**
|
|
658
|
-
* Generate method implementation code for controller methods with discrete path parameters
|
|
659
|
-
*/
|
|
660
|
-
private generateControllerMethodImplementation(operation: OperationInfo): string {
|
|
661
|
-
const lines: string[] = [];
|
|
662
|
-
const url = operation.path;
|
|
663
|
-
const pathParams: string[] = [];
|
|
664
|
-
const queryParams: string[] = [];
|
|
665
|
-
const hasBody = !!operation.requestBody;
|
|
666
|
-
|
|
667
|
-
// Check if method has any options (query params, body, or headers)
|
|
668
|
-
const hasOptions = queryParams.length > 0 || hasBody;
|
|
669
|
-
|
|
670
|
-
// Identify parameters
|
|
671
|
-
if (operation.parameters) {
|
|
672
|
-
operation.parameters.forEach((param: any) => {
|
|
673
|
-
if (param.in === 'path') {
|
|
674
|
-
pathParams.push(param.name);
|
|
675
|
-
} else if (param.in === 'query') {
|
|
676
|
-
queryParams.push(param.name);
|
|
677
|
-
}
|
|
678
|
-
});
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
// Update hasOptions after we know about query params
|
|
682
|
-
const actuallyHasOptions = queryParams.length > 0 || hasBody;
|
|
683
|
-
|
|
684
|
-
// Always extract path parameters as discrete parameters when they exist
|
|
685
|
-
if (pathParams.length > 0) {
|
|
686
|
-
// Handle path parameters as discrete function parameters
|
|
687
|
-
lines.push(` let url = '${url}';`);
|
|
688
|
-
for (const paramName of pathParams) {
|
|
689
|
-
lines.push(` if (${paramName}) {`);
|
|
690
|
-
lines.push(` url = url.replace('{${paramName}}', ${paramName});`);
|
|
691
|
-
lines.push(` }`);
|
|
692
|
-
}
|
|
693
|
-
lines.push('');
|
|
694
|
-
|
|
695
|
-
// Build request body by excluding query parameters and headers (only if we have options)
|
|
696
|
-
if (hasBody && actuallyHasOptions) {
|
|
697
|
-
const excludedParams = ['headers', ...queryParams];
|
|
698
|
-
const destructureList = excludedParams.join(', ');
|
|
699
|
-
lines.push(` const { ${destructureList}, ...bodyData } = options;`);
|
|
700
|
-
lines.push(` const requestBody = Object.keys(bodyData).length > 0 ? bodyData : undefined;`);
|
|
701
|
-
lines.push('');
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
// Build fetch options
|
|
705
|
-
lines.push(` const fetchOptions: any = {`);
|
|
706
|
-
lines.push(` method: '${operation.method}',`);
|
|
707
|
-
|
|
708
|
-
// Add query parameters
|
|
709
|
-
if (queryParams.length > 0) {
|
|
710
|
-
lines.push(` params: {},`);
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
// Add body
|
|
714
|
-
if (hasBody) {
|
|
715
|
-
if (actuallyHasOptions) {
|
|
716
|
-
lines.push(` body: requestBody,`);
|
|
717
|
-
} else {
|
|
718
|
-
lines.push(` body: undefined,`);
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
|
|
722
|
-
// Add headers only if we have options
|
|
723
|
-
if (actuallyHasOptions) {
|
|
724
|
-
lines.push(` headers: options?.headers,`);
|
|
725
|
-
}
|
|
726
|
-
|
|
727
|
-
lines.push(` };`);
|
|
728
|
-
lines.push('');
|
|
729
|
-
|
|
730
|
-
// Add query parameters to options
|
|
731
|
-
if (queryParams.length > 0) {
|
|
732
|
-
lines.push(` // Add query parameters`);
|
|
733
|
-
for (const paramName of queryParams) {
|
|
734
|
-
lines.push(` if (options?.${paramName} !== undefined) {`);
|
|
735
|
-
lines.push(` fetchOptions.params.${paramName} = options.${paramName};`);
|
|
736
|
-
lines.push(` }`);
|
|
737
|
-
}
|
|
738
|
-
lines.push('');
|
|
739
|
-
}
|
|
740
|
-
} else {
|
|
741
|
-
// No path parameters - check if we have options
|
|
742
|
-
if (actuallyHasOptions) {
|
|
743
|
-
lines.push(` options = options || {};`);
|
|
744
|
-
lines.push('');
|
|
745
|
-
}
|
|
746
|
-
lines.push(` const url = '${url}';`);
|
|
747
|
-
lines.push('');
|
|
748
|
-
|
|
749
|
-
// Build request body by excluding query parameters and headers (only if we have options)
|
|
750
|
-
if (hasBody && actuallyHasOptions) {
|
|
751
|
-
const excludedParams = ['headers', ...queryParams];
|
|
752
|
-
const destructureList = excludedParams.join(', ');
|
|
753
|
-
lines.push(` const { ${destructureList}, ...bodyData } = options;`);
|
|
754
|
-
lines.push(` const requestBody = Object.keys(bodyData).length > 0 ? bodyData : undefined;`);
|
|
755
|
-
lines.push('');
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
// Build fetch options
|
|
759
|
-
lines.push(` const fetchOptions: any = {`);
|
|
760
|
-
lines.push(` method: '${operation.method}',`);
|
|
761
|
-
|
|
762
|
-
// Add query parameters
|
|
763
|
-
if (queryParams.length > 0) {
|
|
764
|
-
lines.push(` params: {},`);
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
// Add body
|
|
768
|
-
if (hasBody) {
|
|
769
|
-
if (actuallyHasOptions) {
|
|
770
|
-
lines.push(` body: requestBody,`);
|
|
771
|
-
} else {
|
|
772
|
-
lines.push(` body: undefined,`);
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
// Add headers only if we have options
|
|
777
|
-
if (actuallyHasOptions) {
|
|
778
|
-
lines.push(` headers: options.headers,`);
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
lines.push(` };`);
|
|
782
|
-
lines.push('');
|
|
783
|
-
|
|
784
|
-
// Add query parameters to options
|
|
785
|
-
if (queryParams.length > 0) {
|
|
786
|
-
lines.push(` // Add query parameters`);
|
|
787
|
-
for (const paramName of queryParams) {
|
|
788
|
-
lines.push(` if (options.${paramName} !== undefined) {`);
|
|
789
|
-
lines.push(` fetchOptions.params.${paramName} = options.${paramName};`);
|
|
790
|
-
lines.push(` }`);
|
|
791
|
-
}
|
|
792
|
-
lines.push('');
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
// Make the API call
|
|
796
|
-
lines.push(` return this.api.fetch(url, fetchOptions);`);
|
|
797
|
-
|
|
798
|
-
return lines.join('\n');
|
|
799
|
-
}
|
|
800
|
-
|
|
801
|
-
/**
|
|
802
|
-
* Generate method implementation for resource functions (using this.api instead of this.controller)
|
|
803
|
-
*/
|
|
804
|
-
private generateResourceFunctionImplementation(operation: OperationInfo): string {
|
|
805
|
-
const lines: string[] = [];
|
|
806
|
-
const url = operation.path;
|
|
807
|
-
const pathParams: string[] = [];
|
|
808
|
-
const queryParams: string[] = [];
|
|
809
|
-
const hasBody = !!operation.requestBody;
|
|
810
|
-
|
|
811
|
-
// Identify parameters
|
|
812
|
-
if (operation.parameters) {
|
|
813
|
-
operation.parameters.forEach((param: any) => {
|
|
814
|
-
if (param.in === 'path') {
|
|
815
|
-
pathParams.push(param.name);
|
|
816
|
-
} else if (param.in === 'query') {
|
|
817
|
-
queryParams.push(param.name);
|
|
818
|
-
}
|
|
819
|
-
});
|
|
820
|
-
}
|
|
821
|
-
|
|
822
|
-
// Extract path parameters as discrete parameters when no query params or body
|
|
823
|
-
const isSimple = queryParams.length === 0 && !hasBody;
|
|
824
|
-
|
|
825
|
-
if (isSimple && pathParams.length > 0) {
|
|
826
|
-
// Handle path parameters as discrete function parameters
|
|
827
|
-
lines.push(` let url = '${url}';`);
|
|
828
|
-
for (const paramName of pathParams) {
|
|
829
|
-
lines.push(` if (${paramName}) {`);
|
|
830
|
-
lines.push(` url = url.replace('{${paramName}}', ${paramName});`);
|
|
831
|
-
lines.push(` }`);
|
|
832
|
-
}
|
|
833
|
-
lines.push('');
|
|
834
|
-
lines.push(` return this.api.fetch(url, {`);
|
|
835
|
-
lines.push(` method: '${operation.method}',`);
|
|
836
|
-
lines.push(` });`);
|
|
837
|
-
} else {
|
|
838
|
-
// Options object pattern
|
|
839
|
-
lines.push(` options = options || {};`);
|
|
840
|
-
lines.push('');
|
|
841
|
-
|
|
842
|
-
// Replace path parameters - use discrete parameters, not options
|
|
843
|
-
if (pathParams.length > 0) {
|
|
844
|
-
lines.push(` // Build URL with path parameters`);
|
|
845
|
-
lines.push(` let url = '${url}';`);
|
|
846
|
-
for (const paramName of pathParams) {
|
|
847
|
-
lines.push(` if (${paramName}) {`);
|
|
848
|
-
lines.push(` url = url.replace('{${paramName}}', ${paramName});`);
|
|
849
|
-
lines.push(` }`);
|
|
850
|
-
}
|
|
851
|
-
lines.push('');
|
|
852
|
-
} else {
|
|
853
|
-
lines.push(` const url = '${url}';`);
|
|
854
|
-
lines.push('');
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
// Build request body by excluding query parameters and headers
|
|
858
|
-
if (hasBody) {
|
|
859
|
-
const excludedParams = ['headers', ...queryParams];
|
|
860
|
-
const destructureList = excludedParams.join(', ');
|
|
861
|
-
lines.push(` const { ${destructureList}, ...bodyData } = options;`);
|
|
862
|
-
lines.push(` const requestBody = Object.keys(bodyData).length > 0 ? bodyData : undefined;`);
|
|
863
|
-
lines.push('');
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
// Build fetch options
|
|
867
|
-
lines.push(` const fetchOptions: any = {`);
|
|
868
|
-
lines.push(` method: '${operation.method}',`);
|
|
869
|
-
|
|
870
|
-
// Add query parameters
|
|
871
|
-
if (queryParams.length > 0) {
|
|
872
|
-
lines.push(` params: {},`);
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
// Add body
|
|
876
|
-
if (hasBody) {
|
|
877
|
-
lines.push(` body: requestBody,`);
|
|
878
|
-
}
|
|
879
|
-
|
|
880
|
-
// Add headers
|
|
881
|
-
lines.push(` headers: options.headers,`);
|
|
882
|
-
|
|
883
|
-
lines.push(` };`);
|
|
884
|
-
lines.push('');
|
|
885
|
-
|
|
886
|
-
// Add query parameters to options
|
|
887
|
-
if (queryParams.length > 0) {
|
|
888
|
-
lines.push(` // Add query parameters`);
|
|
889
|
-
for (const paramName of queryParams) {
|
|
890
|
-
lines.push(` if (options.${paramName} !== undefined) {`);
|
|
891
|
-
lines.push(` fetchOptions.params.${paramName} = options.${paramName};`);
|
|
892
|
-
lines.push(` }`);
|
|
893
|
-
}
|
|
894
|
-
lines.push('');
|
|
895
|
-
}
|
|
896
|
-
|
|
897
|
-
// Make the API call
|
|
898
|
-
lines.push(` return this.api.fetch(url, fetchOptions);`);
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
return lines.join('\n');
|
|
902
|
-
}
|
|
903
|
-
|
|
904
|
-
/**
|
|
905
|
-
* Generate exposed resource methods for API introspection
|
|
906
|
-
*/
|
|
907
|
-
generateExposedResourceMethods(
|
|
908
|
-
resources: Array<{className: string; fileName: string}>,
|
|
909
|
-
resourceSpecs?: Array<{fileName: string; spec: OpenAPIV3.Document}>
|
|
910
|
-
): string {
|
|
911
|
-
const methods: string[] = [];
|
|
912
|
-
|
|
913
|
-
for (const resource of resources) {
|
|
914
|
-
const resourceName = resource.fileName;
|
|
915
|
-
|
|
916
|
-
// Find the corresponding spec for this resource
|
|
917
|
-
const resourceSpec = resourceSpecs?.find((rs) => rs.fileName === resourceName);
|
|
918
|
-
|
|
919
|
-
if (resourceSpec) {
|
|
920
|
-
// Create a temporary generator for this resource's spec
|
|
921
|
-
const resourceGenerator = new OpenAPIToConnector(resourceSpec.spec, resourceName, this.options);
|
|
922
|
-
const operations = resourceGenerator.extractOperations();
|
|
923
|
-
|
|
924
|
-
for (const operation of operations) {
|
|
925
|
-
const methodName = resourceGenerator.generateMethodName(operation);
|
|
926
|
-
const jsdoc = resourceGenerator.generateDetailedJSDoc(operation);
|
|
927
|
-
const signature = resourceGenerator.generateMethodSignature(operation);
|
|
928
|
-
|
|
929
|
-
// Generate the exposed method that delegates to the resource
|
|
930
|
-
let exposedMethodName: string;
|
|
931
|
-
if (this.options.nestedPaths && operation.operationId) {
|
|
932
|
-
// Use dotted path for nested method names
|
|
933
|
-
exposedMethodName = resourceGenerator.deriveMethodPath(
|
|
934
|
-
operation.method,
|
|
935
|
-
operation.path,
|
|
936
|
-
operation.operationId
|
|
937
|
-
);
|
|
938
|
-
} else {
|
|
939
|
-
exposedMethodName = `${resourceName}${methodName.charAt(0).toUpperCase() + methodName.slice(1)}`;
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
// Generate parameter call based on operation details
|
|
943
|
-
const parameterCall = this.generateParameterCallForOperation(operation, signature);
|
|
944
|
-
|
|
945
|
-
// Use quoted method name if it contains dots
|
|
946
|
-
const methodDecl = exposedMethodName.includes('.')
|
|
947
|
-
? `'${exposedMethodName}'`
|
|
948
|
-
: exposedMethodName;
|
|
949
|
-
|
|
950
|
-
methods.push(` /**
|
|
951
|
-
${jsdoc}
|
|
952
|
-
*/
|
|
953
|
-
async ${methodDecl}${signature} {
|
|
954
|
-
return this.${resourceName}.${methodName}(${parameterCall});
|
|
955
|
-
}`);
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
}
|
|
959
|
-
|
|
960
|
-
return methods.join('\n\n');
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
/**
|
|
964
|
-
* Generate parameter call for a specific operation based on path parameters
|
|
965
|
-
*/
|
|
966
|
-
private generateParameterCallForOperation(operation: OperationInfo, signature: string): string {
|
|
967
|
-
const pathParams: string[] = [];
|
|
968
|
-
const queryParams: string[] = [];
|
|
969
|
-
const hasBody = !!operation.requestBody;
|
|
970
|
-
|
|
971
|
-
// Identify path and query parameters
|
|
972
|
-
if (operation.parameters) {
|
|
973
|
-
for (const param of operation.parameters) {
|
|
974
|
-
if (typeof param === 'object' && 'name' in param && 'in' in param) {
|
|
975
|
-
if (param.in === 'path') {
|
|
976
|
-
pathParams.push(param.name);
|
|
977
|
-
} else if (param.in === 'query') {
|
|
978
|
-
queryParams.push(param.name);
|
|
979
|
-
}
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
// Extract parameter names from controller signature
|
|
985
|
-
const paramMatch = signature.match(/\(([^)]+)\)/);
|
|
986
|
-
if (!paramMatch || paramMatch[1].trim() === '') return '';
|
|
987
|
-
|
|
988
|
-
const allParams = paramMatch[1]
|
|
989
|
-
.split(',')
|
|
990
|
-
.map((p) => {
|
|
991
|
-
const paramName = p.trim().split(':')[0].trim();
|
|
992
|
-
return paramName.replace(/[?]/g, '');
|
|
993
|
-
})
|
|
994
|
-
.filter((p) => p.length > 0);
|
|
995
|
-
|
|
996
|
-
// Check if signature actually has options parameter
|
|
997
|
-
const hasOptionsParam = allParams.includes('options');
|
|
998
|
-
|
|
999
|
-
// Always extract path parameters as discrete parameters when they exist
|
|
1000
|
-
if (pathParams.length > 0) {
|
|
1001
|
-
// Path parameters are discrete, options is the last parameter (if it exists)
|
|
1002
|
-
const pathParamNames = pathParams;
|
|
1003
|
-
if (hasOptionsParam) {
|
|
1004
|
-
return [...pathParamNames, 'options'].join(', ');
|
|
1005
|
-
} else {
|
|
1006
|
-
return pathParamNames.join(', ');
|
|
1007
|
-
}
|
|
1008
|
-
} else {
|
|
1009
|
-
// No path parameters, everything goes in options object (if options exists)
|
|
1010
|
-
if (hasOptionsParam) {
|
|
1011
|
-
return allParams[0] || 'options';
|
|
1012
|
-
} else {
|
|
1013
|
-
return '';
|
|
1014
|
-
}
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
|
|
1018
|
-
/**
|
|
1019
|
-
* Generate TypeScript interface from OpenAPI schema
|
|
1020
|
-
*/
|
|
1021
|
-
private generateInterfaceFromSchema(name: string, schema: any): string {
|
|
1022
|
-
if (!schema) return '';
|
|
1023
|
-
|
|
1024
|
-
const sanitizedName = this.sanitizeTypeName(name);
|
|
1025
|
-
const lines: string[] = [];
|
|
1026
|
-
lines.push(`export interface ${sanitizedName} {`);
|
|
1027
|
-
|
|
1028
|
-
if (schema.properties) {
|
|
1029
|
-
for (const [propName, propSchema] of Object.entries(schema.properties)) {
|
|
1030
|
-
const propType = this.getTypeFromSchema(propSchema as any);
|
|
1031
|
-
const required = schema.required && schema.required.includes(propName);
|
|
1032
|
-
const optional = required ? '' : '?';
|
|
1033
|
-
|
|
1034
|
-
// Add description as comment if available
|
|
1035
|
-
const description = (propSchema as any)?.description;
|
|
1036
|
-
if (description) {
|
|
1037
|
-
lines.push(` /** ${description} */`);
|
|
1038
|
-
}
|
|
1039
|
-
|
|
1040
|
-
lines.push(` ${propName}${optional}: ${propType};`);
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
|
|
1044
|
-
// Handle allOf, oneOf, anyOf
|
|
1045
|
-
if (schema.allOf) {
|
|
1046
|
-
lines.push(
|
|
1047
|
-
` // Inherits from: ${schema.allOf.map((s: any) => (s.$ref ? this.resolveSchemaRef(s.$ref) : 'unknown')).join(', ')}`
|
|
1048
|
-
);
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1051
|
-
lines.push('}');
|
|
1052
|
-
return lines.join('\n');
|
|
1053
|
-
}
|
|
1054
|
-
|
|
1055
|
-
/**
|
|
1056
|
-
* Generate all TypeScript interfaces from OpenAPI components
|
|
1057
|
-
*/
|
|
1058
|
-
private generateAllInterfaces(): string {
|
|
1059
|
-
if (!this.spec.components?.schemas) {
|
|
1060
|
-
return '';
|
|
1061
|
-
}
|
|
1062
|
-
|
|
1063
|
-
const interfaces: string[] = [];
|
|
1064
|
-
const usedTypes = this.collectUsedSchemaTypes();
|
|
1065
|
-
|
|
1066
|
-
for (const [schemaName, schema] of Object.entries(this.spec.components.schemas)) {
|
|
1067
|
-
const sanitizedSchemaName = this.sanitizeTypeName(schemaName);
|
|
1068
|
-
if (usedTypes.has(sanitizedSchemaName)) {
|
|
1069
|
-
const interfaceCode = this.generateInterfaceFromSchema(schemaName, schema);
|
|
1070
|
-
if (interfaceCode) {
|
|
1071
|
-
interfaces.push(interfaceCode);
|
|
1072
|
-
}
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
|
|
1076
|
-
if (interfaces.length === 0) {
|
|
1077
|
-
return '';
|
|
1078
|
-
}
|
|
1079
|
-
|
|
1080
|
-
return `// Generated TypeScript interfaces from OpenAPI schemas\n\n${interfaces.join('\n\n')}\n`;
|
|
1081
|
-
}
|
|
1082
|
-
|
|
1083
|
-
/**
|
|
1084
|
-
* Generate detailed JSDoc with schema field information
|
|
1085
|
-
*/
|
|
1086
|
-
private generateDetailedJSDoc(operation: OperationInfo): string {
|
|
1087
|
-
const lines: string[] = [];
|
|
1088
|
-
lines.push(` * ${operation.summary || operation.operationId || 'API Operation'}`);
|
|
1089
|
-
|
|
1090
|
-
if (operation.description) {
|
|
1091
|
-
lines.push(' *');
|
|
1092
|
-
// Split long descriptions into multiple lines
|
|
1093
|
-
const descLines = operation.description.split('\n');
|
|
1094
|
-
descLines.forEach((line) => {
|
|
1095
|
-
lines.push(` * ${line}`);
|
|
1096
|
-
});
|
|
1097
|
-
}
|
|
1098
|
-
|
|
1099
|
-
lines.push(' *');
|
|
1100
|
-
|
|
1101
|
-
// Document path parameters with details
|
|
1102
|
-
const pathParams: any[] = [];
|
|
1103
|
-
const queryParams: any[] = [];
|
|
1104
|
-
|
|
1105
|
-
if (operation.parameters) {
|
|
1106
|
-
for (const param of operation.parameters) {
|
|
1107
|
-
if (typeof param === 'object' && 'name' in param && 'in' in param) {
|
|
1108
|
-
if (param.in === 'path') {
|
|
1109
|
-
pathParams.push(param);
|
|
1110
|
-
} else if (param.in === 'query') {
|
|
1111
|
-
queryParams.push(param);
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
|
|
1117
|
-
// Document discrete path parameters
|
|
1118
|
-
pathParams.forEach((param) => {
|
|
1119
|
-
const paramType = this.getParameterType(param);
|
|
1120
|
-
const paramDesc = param.description || '';
|
|
1121
|
-
lines.push(` * @param {${paramType}} ${param.name} ${paramDesc}`);
|
|
1122
|
-
});
|
|
1123
|
-
|
|
1124
|
-
// Document options parameter with detailed schema information
|
|
1125
|
-
if (queryParams.length > 0 || operation.requestBody) {
|
|
1126
|
-
lines.push(' * @param {Object} options - Request options');
|
|
1127
|
-
|
|
1128
|
-
// Document query parameters
|
|
1129
|
-
queryParams.forEach((param) => {
|
|
1130
|
-
const paramType = this.getParameterType(param);
|
|
1131
|
-
const paramDesc = param.description || '';
|
|
1132
|
-
const required = param.required ? '(required)' : '(optional)';
|
|
1133
|
-
lines.push(` * @param {${paramType}} options.${param.name} ${required} - ${paramDesc} [query]`);
|
|
1134
|
-
});
|
|
1135
|
-
|
|
1136
|
-
// Document request body with detailed schema info (now flattened)
|
|
1137
|
-
if (operation.requestBody) {
|
|
1138
|
-
this.addFlattenedBodyDocumentation(lines, operation.requestBody);
|
|
1139
|
-
}
|
|
1140
|
-
} else if (pathParams.length > 0) {
|
|
1141
|
-
lines.push(` * @param {Object} options (optional) - Request options`);
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
// Document response with detailed schema information
|
|
1145
|
-
lines.push(' *');
|
|
1146
|
-
const returnType = this.getResponseType(operation);
|
|
1147
|
-
lines.push(` * @returns {Promise<${returnType}>} ${operation.method.toUpperCase()} ${operation.path} response`);
|
|
1148
|
-
|
|
1149
|
-
// Add detailed schema information for the return type
|
|
1150
|
-
this.addSchemaDetails(lines, returnType, 'response');
|
|
1151
|
-
|
|
1152
|
-
return lines.join('\n');
|
|
1153
|
-
}
|
|
1154
|
-
|
|
1155
|
-
/**
|
|
1156
|
-
* Add flattened request body documentation to JSDoc
|
|
1157
|
-
*/
|
|
1158
|
-
private addFlattenedBodyDocumentation(lines: string[], requestBody: any): void {
|
|
1159
|
-
if (!requestBody) return;
|
|
1160
|
-
|
|
1161
|
-
let schema: any = null;
|
|
1162
|
-
|
|
1163
|
-
// Get the schema from the request body
|
|
1164
|
-
if (requestBody.content) {
|
|
1165
|
-
if (requestBody.content['application/json']?.schema) {
|
|
1166
|
-
schema = requestBody.content['application/json'].schema;
|
|
1167
|
-
} else {
|
|
1168
|
-
const firstContentType = Object.keys(requestBody.content)[0];
|
|
1169
|
-
if (requestBody.content[firstContentType]?.schema) {
|
|
1170
|
-
schema = requestBody.content[firstContentType].schema;
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
1173
|
-
}
|
|
1174
|
-
|
|
1175
|
-
if (!schema) return;
|
|
1176
|
-
|
|
1177
|
-
// Handle $ref in schema
|
|
1178
|
-
if (schema.$ref) {
|
|
1179
|
-
const refType = this.resolveSchemaRef(schema.$ref);
|
|
1180
|
-
const referencedSchema = this.spec.components?.schemas?.[refType];
|
|
1181
|
-
if (referencedSchema && !('$ref' in referencedSchema)) {
|
|
1182
|
-
schema = referencedSchema;
|
|
1183
|
-
} else {
|
|
1184
|
-
// Fallback to original format if we can't resolve
|
|
1185
|
-
const bodyType = this.getRequestBodyType(requestBody);
|
|
1186
|
-
const bodyDesc = requestBody.description || 'Request body';
|
|
1187
|
-
const required = requestBody.required ? '(required)' : '(optional)';
|
|
1188
|
-
lines.push(` * @param {${bodyType}} options.body ${required} - ${bodyDesc}`);
|
|
1189
|
-
return;
|
|
1190
|
-
}
|
|
1191
|
-
}
|
|
1192
|
-
|
|
1193
|
-
// Document individual properties from the body schema
|
|
1194
|
-
if (schema.properties) {
|
|
1195
|
-
for (const [propName, propSchema] of Object.entries(schema.properties)) {
|
|
1196
|
-
const propType = this.getTypeFromSchema(propSchema as any);
|
|
1197
|
-
const propRequired = (schema.required && schema.required.includes(propName)) || requestBody.required;
|
|
1198
|
-
const requiredText = propRequired ? '(required)' : '(optional)';
|
|
1199
|
-
const propDesc = (propSchema as any)?.description || '';
|
|
1200
|
-
|
|
1201
|
-
lines.push(` * @param {${propType}} options.${propName} ${requiredText} - ${propDesc} [body property]`);
|
|
1202
|
-
}
|
|
1203
|
-
} else {
|
|
1204
|
-
// Fallback to original format if no properties
|
|
1205
|
-
const bodyType = this.getRequestBodyType(requestBody);
|
|
1206
|
-
const bodyDesc = requestBody.description || 'Request body';
|
|
1207
|
-
const required = requestBody.required ? '(required)' : '(optional)';
|
|
1208
|
-
lines.push(` * @param {${bodyType}} options.body ${required} - ${bodyDesc}`);
|
|
1209
|
-
}
|
|
1210
|
-
}
|
|
1211
|
-
|
|
1212
|
-
/**
|
|
1213
|
-
* Add detailed schema field information to JSDoc
|
|
1214
|
-
*/
|
|
1215
|
-
private addSchemaDetails(lines: string[], typeName: string, context: string): void {
|
|
1216
|
-
// Remove array notation to get base type
|
|
1217
|
-
const baseType = typeName.replace(/\[\]$/, '');
|
|
1218
|
-
const isArray = typeName.endsWith('[]');
|
|
1219
|
-
|
|
1220
|
-
if (['string', 'number', 'boolean', 'any'].includes(baseType)) {
|
|
1221
|
-
return; // Skip primitive types
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
const schema = this.spec.components?.schemas?.[baseType];
|
|
1225
|
-
if (!schema) {
|
|
1226
|
-
return;
|
|
1227
|
-
}
|
|
1228
|
-
|
|
1229
|
-
// Type guard to check if schema has properties (is not a ReferenceObject)
|
|
1230
|
-
if ('$ref' in schema) {
|
|
1231
|
-
return; // Skip reference objects
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
|
-
if (!schema.properties) {
|
|
1235
|
-
return;
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
lines.push(' *');
|
|
1239
|
-
lines.push(` * ${context}${isArray ? '[]' : ''} fields:`);
|
|
1240
|
-
|
|
1241
|
-
const maxFields = 10; // Limit to avoid too much clutter
|
|
1242
|
-
const properties = Object.entries(schema.properties).slice(0, maxFields);
|
|
1243
|
-
|
|
1244
|
-
for (const [propName, propSchema] of properties) {
|
|
1245
|
-
const propType = this.getTypeFromSchema(propSchema as any);
|
|
1246
|
-
const required = schema.required && schema.required.includes(propName);
|
|
1247
|
-
const requiredText = required ? '' : '?';
|
|
1248
|
-
const description = (propSchema as any)?.description;
|
|
1249
|
-
|
|
1250
|
-
if (description) {
|
|
1251
|
-
lines.push(` * - ${propName}${requiredText}: ${propType} - ${description}`);
|
|
1252
|
-
} else {
|
|
1253
|
-
lines.push(` * - ${propName}${requiredText}: ${propType}`);
|
|
1254
|
-
}
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
const totalFields = Object.keys(schema.properties).length;
|
|
1258
|
-
if (totalFields > maxFields) {
|
|
1259
|
-
lines.push(` * - ... and ${totalFields - maxFields} more fields`);
|
|
1260
|
-
}
|
|
1261
|
-
}
|
|
1262
|
-
|
|
1263
|
-
/**
|
|
1264
|
-
* Collect all schema types used in operations (including nested references)
|
|
1265
|
-
*/
|
|
1266
|
-
private collectUsedSchemaTypes(): Set<string> {
|
|
1267
|
-
const usedTypes = new Set<string>();
|
|
1268
|
-
const visitedSchemas = new Set<string>(); // Track visited schemas to prevent infinite recursion
|
|
1269
|
-
const operations = this.extractOperations();
|
|
1270
|
-
|
|
1271
|
-
for (const operation of operations) {
|
|
1272
|
-
// Collect from request body schemas
|
|
1273
|
-
if (operation.requestBody) {
|
|
1274
|
-
this.collectTypesFromRequestBody(operation.requestBody, usedTypes, visitedSchemas);
|
|
1275
|
-
}
|
|
1276
|
-
|
|
1277
|
-
// Collect from response schemas
|
|
1278
|
-
if (operation.responses) {
|
|
1279
|
-
this.collectTypesFromResponses(operation.responses, usedTypes, visitedSchemas);
|
|
1280
|
-
}
|
|
1281
|
-
|
|
1282
|
-
// Collect from parameter schemas
|
|
1283
|
-
if (operation.parameters) {
|
|
1284
|
-
for (const param of operation.parameters) {
|
|
1285
|
-
if (typeof param === 'object' && 'schema' in param && param.schema) {
|
|
1286
|
-
this.collectTypesFromSchema(param.schema, usedTypes, visitedSchemas);
|
|
1287
|
-
}
|
|
1288
|
-
}
|
|
1289
|
-
}
|
|
1290
|
-
}
|
|
1291
|
-
|
|
1292
|
-
return usedTypes;
|
|
1293
|
-
}
|
|
1294
|
-
|
|
1295
|
-
/**
|
|
1296
|
-
* Collect types from request body schema
|
|
1297
|
-
*/
|
|
1298
|
-
private collectTypesFromRequestBody(requestBody: any, usedTypes: Set<string>, visitedSchemas: Set<string>): void {
|
|
1299
|
-
if (!requestBody || !requestBody.content) return;
|
|
1300
|
-
|
|
1301
|
-
// Check all content types
|
|
1302
|
-
for (const contentType of Object.keys(requestBody.content)) {
|
|
1303
|
-
const content = requestBody.content[contentType];
|
|
1304
|
-
if (content.schema) {
|
|
1305
|
-
this.collectTypesFromSchema(content.schema, usedTypes, visitedSchemas);
|
|
1306
|
-
}
|
|
1307
|
-
}
|
|
1308
|
-
}
|
|
1309
|
-
|
|
1310
|
-
/**
|
|
1311
|
-
* Collect types from response schemas
|
|
1312
|
-
*/
|
|
1313
|
-
private collectTypesFromResponses(responses: any, usedTypes: Set<string>, visitedSchemas: Set<string>): void {
|
|
1314
|
-
if (!responses) return;
|
|
1315
|
-
|
|
1316
|
-
// Check success responses
|
|
1317
|
-
const successCodes = ['200', '201', '202', '204'];
|
|
1318
|
-
for (const code of successCodes) {
|
|
1319
|
-
const response = responses[code];
|
|
1320
|
-
if (response && response.content) {
|
|
1321
|
-
for (const contentType of Object.keys(response.content)) {
|
|
1322
|
-
const content = response.content[contentType];
|
|
1323
|
-
if (content.schema) {
|
|
1324
|
-
this.collectTypesFromSchema(content.schema, usedTypes, visitedSchemas);
|
|
1325
|
-
}
|
|
1326
|
-
}
|
|
1327
|
-
}
|
|
1328
|
-
}
|
|
1329
|
-
}
|
|
1330
|
-
|
|
1331
|
-
/**
|
|
1332
|
-
* Collect types from a schema object
|
|
1333
|
-
*/
|
|
1334
|
-
private collectTypesFromSchema(schema: any, usedTypes: Set<string>, visitedSchemas: Set<string>): void {
|
|
1335
|
-
if (!schema) return;
|
|
1336
|
-
|
|
1337
|
-
// Handle $ref
|
|
1338
|
-
if (schema.$ref) {
|
|
1339
|
-
const parts = schema.$ref.split('/');
|
|
1340
|
-
const originalSchemaName = parts[parts.length - 1];
|
|
1341
|
-
const sanitizedRefType = this.resolveSchemaRef(schema.$ref);
|
|
1342
|
-
|
|
1343
|
-
if (sanitizedRefType !== 'any' && !['string', 'number', 'boolean'].includes(sanitizedRefType)) {
|
|
1344
|
-
// Add the sanitized type name to used types
|
|
1345
|
-
usedTypes.add(sanitizedRefType);
|
|
1346
|
-
|
|
1347
|
-
// Only recurse if we haven't visited this schema before (use original name for lookup)
|
|
1348
|
-
if (!visitedSchemas.has(originalSchemaName)) {
|
|
1349
|
-
visitedSchemas.add(originalSchemaName);
|
|
1350
|
-
const referencedSchema = this.spec.components?.schemas?.[originalSchemaName];
|
|
1351
|
-
if (referencedSchema) {
|
|
1352
|
-
this.collectTypesFromSchema(referencedSchema, usedTypes, visitedSchemas);
|
|
1353
|
-
}
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
return;
|
|
1357
|
-
}
|
|
1358
|
-
|
|
1359
|
-
// Handle arrays
|
|
1360
|
-
if (schema.type === 'array' && schema.items) {
|
|
1361
|
-
this.collectTypesFromSchema(schema.items, usedTypes, visitedSchemas);
|
|
1362
|
-
return;
|
|
1363
|
-
}
|
|
1364
|
-
|
|
1365
|
-
// Handle objects with properties
|
|
1366
|
-
if (schema.type === 'object' && schema.properties) {
|
|
1367
|
-
for (const propSchema of Object.values(schema.properties)) {
|
|
1368
|
-
this.collectTypesFromSchema(propSchema, usedTypes, visitedSchemas);
|
|
1369
|
-
}
|
|
1370
|
-
return;
|
|
1371
|
-
}
|
|
1372
|
-
|
|
1373
|
-
// Handle allOf, oneOf, anyOf
|
|
1374
|
-
if (schema.allOf) {
|
|
1375
|
-
for (const subSchema of schema.allOf) {
|
|
1376
|
-
this.collectTypesFromSchema(subSchema, usedTypes, visitedSchemas);
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
|
|
1380
|
-
if (schema.oneOf) {
|
|
1381
|
-
for (const subSchema of schema.oneOf) {
|
|
1382
|
-
this.collectTypesFromSchema(subSchema, usedTypes, visitedSchemas);
|
|
1383
|
-
}
|
|
1384
|
-
}
|
|
1385
|
-
|
|
1386
|
-
if (schema.anyOf) {
|
|
1387
|
-
for (const subSchema of schema.anyOf) {
|
|
1388
|
-
this.collectTypesFromSchema(subSchema, usedTypes, visitedSchemas);
|
|
1389
|
-
}
|
|
1390
|
-
}
|
|
1391
|
-
}
|
|
1392
|
-
|
|
1393
|
-
/**
|
|
1394
|
-
* Generate type imports for used schema types
|
|
1395
|
-
*/
|
|
1396
|
-
private generateTypeImports(): string {
|
|
1397
|
-
const usedTypes = this.collectUsedSchemaTypes();
|
|
1398
|
-
if (usedTypes.size === 0) {
|
|
1399
|
-
return '';
|
|
1400
|
-
}
|
|
1401
|
-
|
|
1402
|
-
const typeList = Array.from(usedTypes).sort().join(', ');
|
|
1403
|
-
return `// Type imports (you may need to adjust the import path)\n// import type { ${typeList} } from './types';\n\n`;
|
|
1404
|
-
}
|
|
1405
|
-
|
|
1406
|
-
/**
|
|
1407
|
-
* Generate a resource file with exported functions (new pattern for proper introspection)
|
|
1408
|
-
*/
|
|
1409
|
-
generateResourceClass(className: string): string {
|
|
1410
|
-
const operations = this.extractOperations();
|
|
1411
|
-
|
|
1412
|
-
if (operations.length === 0) {
|
|
1413
|
-
throw new Error('No operations found in OpenAPI specification');
|
|
1414
|
-
}
|
|
1415
|
-
|
|
1416
|
-
const resourceName = className.replace('Resource', '').toLowerCase();
|
|
1417
|
-
|
|
1418
|
-
// Bug 1 fix: Track used method names and disambiguate collisions
|
|
1419
|
-
const usedNames = new Map<string, number>();
|
|
1420
|
-
const functions = operations
|
|
1421
|
-
.map((operation) => {
|
|
1422
|
-
let methodName = this.generateMethodName(operation);
|
|
1423
|
-
|
|
1424
|
-
// Disambiguate duplicate names by prepending path context
|
|
1425
|
-
if (usedNames.has(methodName)) {
|
|
1426
|
-
methodName = this.disambiguateMethodName(methodName, operation);
|
|
1427
|
-
// If still colliding after disambiguation, append a numeric suffix
|
|
1428
|
-
if (usedNames.has(methodName)) {
|
|
1429
|
-
const count = (usedNames.get(methodName) || 1) + 1;
|
|
1430
|
-
usedNames.set(methodName, count);
|
|
1431
|
-
methodName = `${methodName}${count}`;
|
|
1432
|
-
}
|
|
1433
|
-
}
|
|
1434
|
-
usedNames.set(methodName, (usedNames.get(methodName) || 0) + 1);
|
|
1435
|
-
|
|
1436
|
-
const jsdoc = this.generateDetailedJSDoc(operation);
|
|
1437
|
-
const signature = this.generateMethodSignature(operation);
|
|
1438
|
-
const implementation = this.generateResourceFunctionImplementation(operation);
|
|
1439
|
-
|
|
1440
|
-
return `/**\n${jsdoc}\n */\nexport function ${methodName}(this: any, ${signature.replace('(', '').replace(')', '')}) {\n${implementation}\n}`;
|
|
1441
|
-
})
|
|
1442
|
-
.join('\n\n');
|
|
1443
|
-
|
|
1444
|
-
// Generate actual TypeScript interfaces
|
|
1445
|
-
const interfaces = this.generateAllInterfaces();
|
|
1446
|
-
|
|
1447
|
-
return `// ${className} resource functions
|
|
1448
|
-
// These functions will be bound to the controller instance and accessible as ${resourceName}.method()
|
|
1449
|
-
|
|
1450
|
-
${interfaces}
|
|
1451
|
-
|
|
1452
|
-
${functions}`;
|
|
1453
|
-
}
|
|
1454
|
-
|
|
1455
|
-
/**
|
|
1456
|
-
* Generate a main controller that composes multiple resources using function binding
|
|
1457
|
-
*/
|
|
1458
|
-
generateMainController(
|
|
1459
|
-
resources: Array<{className: string; fileName: string}>,
|
|
1460
|
-
resourceSpecs?: Array<{fileName: string; spec: OpenAPIV3.Document}>
|
|
1461
|
-
): string {
|
|
1462
|
-
// Get base URL from servers if available
|
|
1463
|
-
const baseUrl =
|
|
1464
|
-
this.spec.servers && this.spec.servers.length > 0 ? this.spec.servers[0].url : 'https://api.example.com';
|
|
1465
|
-
|
|
1466
|
-
const imports = resources
|
|
1467
|
-
.map((resource) => `import * as ${resource.fileName}Functions from '../resources/${resource.fileName}.mjs';`)
|
|
1468
|
-
.join('\n');
|
|
1469
|
-
|
|
1470
|
-
const properties = resources.map((resource) => ` ${resource.fileName}: any = {};`).join('\n');
|
|
1471
|
-
|
|
1472
|
-
const bindings = resources
|
|
1473
|
-
.map((resource) => ` this.bindResourceFunctions('${resource.fileName}', ${resource.fileName}Functions);`)
|
|
1474
|
-
.join('\n');
|
|
1475
|
-
|
|
1476
|
-
// Generate exposed methods for each resource to enable API introspection
|
|
1477
|
-
const exposedMethods = this.generateExposedResourceMethods(resources, resourceSpecs);
|
|
1478
|
-
|
|
1479
|
-
return `import {AbstractController} from '@aloma.io/integration-sdk';
|
|
1480
|
-
${imports}
|
|
1481
|
-
|
|
1482
|
-
export default class Controller extends AbstractController {
|
|
1483
|
-
${properties}
|
|
1484
|
-
|
|
1485
|
-
private api: any;
|
|
1486
|
-
|
|
1487
|
-
protected async start(): Promise<void> {
|
|
1488
|
-
const config = this.config;
|
|
1489
|
-
|
|
1490
|
-
this.api = this.getClient({
|
|
1491
|
-
baseUrl: '${baseUrl}',
|
|
1492
|
-
customize(request) {
|
|
1493
|
-
request.headers ||= {};
|
|
1494
|
-
// Add authentication headers based on your API requirements
|
|
1495
|
-
// Example: request.headers["Authorization"] = \`Bearer \${config.apiToken}\`;
|
|
1496
|
-
},
|
|
1497
|
-
});
|
|
1498
|
-
|
|
1499
|
-
// Bind resource functions to this controller context
|
|
1500
|
-
// This allows using this.resourceName.method() syntax
|
|
1501
|
-
${bindings}
|
|
1502
|
-
}
|
|
1503
|
-
|
|
1504
|
-
private bindResourceFunctions(resourceName: string, functions: any) {
|
|
1505
|
-
for (const [functionName, func] of Object.entries(functions)) {
|
|
1506
|
-
if (typeof func === 'function') {
|
|
1507
|
-
this[resourceName][functionName] = func.bind(this);
|
|
1508
|
-
}
|
|
1509
|
-
}
|
|
1510
|
-
}
|
|
1511
|
-
|
|
1512
|
-
/**
|
|
1513
|
-
* Generic API request method
|
|
1514
|
-
* @param url - API endpoint
|
|
1515
|
-
* @param options - Request options
|
|
1516
|
-
*/
|
|
1517
|
-
async request({ url, options }: { url: string; options?: any }) {
|
|
1518
|
-
return this.api.fetch(url, options);
|
|
1519
|
-
}
|
|
1520
|
-
|
|
1521
|
-
${exposedMethods}
|
|
1522
|
-
}`;
|
|
1523
|
-
}
|
|
1524
|
-
|
|
1525
|
-
/**
|
|
1526
|
-
* Generate the connector controller code with improved pattern
|
|
1527
|
-
*/
|
|
1528
|
-
generateController(): string {
|
|
1529
|
-
const operations = this.extractOperations();
|
|
1530
|
-
|
|
1531
|
-
if (operations.length === 0) {
|
|
1532
|
-
throw new Error('No operations found in OpenAPI specification');
|
|
1533
|
-
}
|
|
1534
|
-
|
|
1535
|
-
// Bug 1 fix: Track used method names and disambiguate collisions
|
|
1536
|
-
const usedNames = new Map<string, number>();
|
|
1537
|
-
const methods = operations
|
|
1538
|
-
.map((operation) => {
|
|
1539
|
-
let methodName: string;
|
|
1540
|
-
if (this.options.nestedPaths && operation.operationId) {
|
|
1541
|
-
methodName = this.deriveMethodPath(operation.method, operation.path, operation.operationId);
|
|
1542
|
-
} else {
|
|
1543
|
-
methodName = this.generateMethodName(operation);
|
|
1544
|
-
}
|
|
1545
|
-
|
|
1546
|
-
// Disambiguate duplicate names
|
|
1547
|
-
if (usedNames.has(methodName)) {
|
|
1548
|
-
methodName = this.disambiguateMethodName(methodName, operation);
|
|
1549
|
-
if (usedNames.has(methodName)) {
|
|
1550
|
-
const count = (usedNames.get(methodName) || 1) + 1;
|
|
1551
|
-
usedNames.set(methodName, count);
|
|
1552
|
-
methodName = `${methodName}${count}`;
|
|
1553
|
-
}
|
|
1554
|
-
}
|
|
1555
|
-
usedNames.set(methodName, (usedNames.get(methodName) || 0) + 1);
|
|
1556
|
-
|
|
1557
|
-
const jsdoc = this.generateDetailedJSDoc(operation); // Use detailed JSDoc like multi-resource
|
|
1558
|
-
const signature = this.generateMethodSignature(operation);
|
|
1559
|
-
const implementation = this.generateControllerMethodImplementation(operation); // Use improved implementation
|
|
1560
|
-
|
|
1561
|
-
// Use quoted method name if it contains dots
|
|
1562
|
-
const methodDecl = methodName.includes('.') ? `'${methodName}'` : methodName;
|
|
1563
|
-
return ` /**\n${jsdoc}\n */\n async ${methodDecl}${signature} {\n${implementation}\n }`;
|
|
1564
|
-
})
|
|
1565
|
-
.join('\n\n');
|
|
1566
|
-
|
|
1567
|
-
// Get base URL from servers if available
|
|
1568
|
-
const baseUrl =
|
|
1569
|
-
this.spec.servers && this.spec.servers.length > 0 ? this.spec.servers[0].url : 'https://api.example.com';
|
|
1570
|
-
|
|
1571
|
-
// Generate TypeScript interfaces
|
|
1572
|
-
const interfaces = this.generateAllInterfaces();
|
|
1573
|
-
|
|
1574
|
-
// Generate type imports
|
|
1575
|
-
const typeImports = this.generateTypeImports();
|
|
1576
|
-
|
|
1577
|
-
const startMethod = ` private api: any;
|
|
1578
|
-
|
|
1579
|
-
protected async start(): Promise<void> {
|
|
1580
|
-
const config = this.config;
|
|
1581
|
-
|
|
1582
|
-
this.api = this.getClient({
|
|
1583
|
-
baseUrl: '${baseUrl}',
|
|
1584
|
-
customize(request) {
|
|
1585
|
-
request.headers ||= {};
|
|
1586
|
-
// Add authentication headers based on your API requirements
|
|
1587
|
-
// Example: request.headers["Authorization"] = \`Bearer \${config.apiToken}\`;
|
|
1588
|
-
},
|
|
1589
|
-
});
|
|
1590
|
-
}`;
|
|
1591
|
-
|
|
1592
|
-
return `import {AbstractController} from '@aloma.io/integration-sdk';
|
|
1593
|
-
|
|
1594
|
-
${typeImports}${interfaces}export default class Controller extends AbstractController {
|
|
1595
|
-
|
|
1596
|
-
${startMethod}
|
|
1597
|
-
|
|
1598
|
-
${methods}
|
|
1599
|
-
}`;
|
|
1600
|
-
}
|
|
1601
|
-
}
|
|
1602
|
-
|
|
1603
|
-
// CLI setup
|
|
1604
|
-
const program = new Command();
|
|
1605
|
-
|
|
1606
|
-
program
|
|
1607
|
-
.name('openapi-to-connector')
|
|
1608
|
-
.description('Generate a connector controller from an OpenAPI specification')
|
|
1609
|
-
.version('1.0.0')
|
|
1610
|
-
.showHelpAfterError();
|
|
1611
|
-
|
|
1612
|
-
program
|
|
1613
|
-
.command('generate')
|
|
1614
|
-
.description('Generate connector controller from OpenAPI spec')
|
|
1615
|
-
.requiredOption('--name <name>', 'Human-readable connector name')
|
|
1616
|
-
.requiredOption('--spec <file>', 'OpenAPI specification file (JSON or YAML)')
|
|
1617
|
-
.option('--out <file>', 'Output file path', 'index.mts')
|
|
1618
|
-
.action(async (options) => {
|
|
1619
|
-
try {
|
|
1620
|
-
// Read and parse the OpenAPI spec
|
|
1621
|
-
const specContent = fs.readFileSync(options.spec, 'utf-8');
|
|
1622
|
-
const spec = OpenAPIToConnector.parseSpec(specContent);
|
|
1623
|
-
|
|
1624
|
-
// Generate the connector controller
|
|
1625
|
-
const generator = new OpenAPIToConnector(spec, options.name);
|
|
1626
|
-
const controllerCode = generator.generateController();
|
|
1627
|
-
|
|
1628
|
-
// Write the output file
|
|
1629
|
-
fs.writeFileSync(options.out, controllerCode);
|
|
1630
|
-
|
|
1631
|
-
console.log(`✅ Successfully generated connector controller: ${options.out}`);
|
|
1632
|
-
console.log(`📝 Connector name: ${options.name}`);
|
|
1633
|
-
console.log(`📊 Found ${generator['extractOperations']().length} operations`);
|
|
1634
|
-
} catch (error) {
|
|
1635
|
-
console.error('❌ Error:', error instanceof Error ? error.message : 'Unknown error');
|
|
1636
|
-
process.exit(1);
|
|
1637
|
-
}
|
|
1638
|
-
});
|
|
1639
|
-
|
|
1640
|
-
// Only run CLI if this file is executed directly
|
|
1641
|
-
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
1642
|
-
// If no command is provided, show help
|
|
1643
|
-
if (process.argv.length <= 2) {
|
|
1644
|
-
program.help();
|
|
1645
|
-
} else {
|
|
1646
|
-
program.parse();
|
|
1647
|
-
}
|
|
1648
|
-
}
|