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