zod-codegen 1.2.2 → 1.4.0

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 (84) hide show
  1. package/.claude/settings.local.json +43 -0
  2. package/.github/workflows/ci.yml +4 -4
  3. package/.github/workflows/release.yml +1 -1
  4. package/CHANGELOG.md +17 -0
  5. package/README.md +61 -9
  6. package/dist/scripts/update-manifest.d.ts +14 -0
  7. package/dist/scripts/update-manifest.d.ts.map +1 -0
  8. package/dist/src/cli.d.ts +3 -0
  9. package/dist/src/cli.d.ts.map +1 -0
  10. package/dist/src/cli.js +31 -2
  11. package/dist/src/generator.d.ts +23 -0
  12. package/dist/src/generator.d.ts.map +1 -0
  13. package/dist/src/generator.js +3 -2
  14. package/dist/src/http/fetch-client.d.ts +15 -0
  15. package/dist/src/http/fetch-client.d.ts.map +1 -0
  16. package/dist/src/interfaces/code-generator.d.ts +20 -0
  17. package/dist/src/interfaces/code-generator.d.ts.map +1 -0
  18. package/dist/src/interfaces/file-reader.d.ts +13 -0
  19. package/dist/src/interfaces/file-reader.d.ts.map +1 -0
  20. package/dist/src/polyfills/fetch.d.ts +5 -0
  21. package/dist/src/polyfills/fetch.d.ts.map +1 -0
  22. package/dist/src/services/code-generator.service.d.ts +57 -0
  23. package/dist/src/services/code-generator.service.d.ts.map +1 -0
  24. package/dist/src/services/code-generator.service.js +43 -6
  25. package/dist/src/services/file-reader.service.d.ts +9 -0
  26. package/dist/src/services/file-reader.service.d.ts.map +1 -0
  27. package/dist/src/services/file-writer.service.d.ts +10 -0
  28. package/dist/src/services/file-writer.service.d.ts.map +1 -0
  29. package/dist/src/services/import-builder.service.d.ts +14 -0
  30. package/dist/src/services/import-builder.service.d.ts.map +1 -0
  31. package/dist/src/services/type-builder.service.d.ts +12 -0
  32. package/dist/src/services/type-builder.service.d.ts.map +1 -0
  33. package/dist/src/types/generator-options.d.ts +59 -0
  34. package/dist/src/types/generator-options.d.ts.map +1 -0
  35. package/dist/src/types/generator-options.js +1 -0
  36. package/dist/src/types/http.d.ts +25 -0
  37. package/dist/src/types/http.d.ts.map +1 -0
  38. package/dist/src/types/openapi.d.ts +1120 -0
  39. package/dist/src/types/openapi.d.ts.map +1 -0
  40. package/dist/src/utils/error-handler.d.ts +3 -0
  41. package/dist/src/utils/error-handler.d.ts.map +1 -0
  42. package/dist/src/utils/error-handler.js +2 -2
  43. package/dist/src/utils/execution-time.d.ts +2 -0
  44. package/dist/src/utils/execution-time.d.ts.map +1 -0
  45. package/dist/src/utils/manifest.d.ts +8 -0
  46. package/dist/src/utils/manifest.d.ts.map +1 -0
  47. package/dist/src/utils/naming-convention.d.ts +80 -0
  48. package/dist/src/utils/naming-convention.d.ts.map +1 -0
  49. package/dist/src/utils/naming-convention.js +135 -0
  50. package/dist/src/utils/reporter.d.ts +7 -0
  51. package/dist/src/utils/reporter.d.ts.map +1 -0
  52. package/dist/src/utils/signal-handler.d.ts +3 -0
  53. package/dist/src/utils/signal-handler.d.ts.map +1 -0
  54. package/dist/src/utils/signal-handler.js +2 -2
  55. package/dist/src/utils/tty.d.ts +2 -0
  56. package/dist/src/utils/tty.d.ts.map +1 -0
  57. package/dist/tests/integration/cli.test.d.ts +2 -0
  58. package/dist/tests/integration/cli.test.d.ts.map +1 -0
  59. package/dist/tests/integration/cli.test.js +2 -2
  60. package/dist/tests/unit/code-generator.test.d.ts +2 -0
  61. package/dist/tests/unit/code-generator.test.d.ts.map +1 -0
  62. package/dist/tests/unit/code-generator.test.js +170 -1
  63. package/dist/tests/unit/file-reader.test.d.ts +2 -0
  64. package/dist/tests/unit/file-reader.test.d.ts.map +1 -0
  65. package/dist/tests/unit/generator.test.d.ts +2 -0
  66. package/dist/tests/unit/generator.test.d.ts.map +1 -0
  67. package/dist/tests/unit/naming-convention.test.d.ts +2 -0
  68. package/dist/tests/unit/naming-convention.test.d.ts.map +1 -0
  69. package/dist/tests/unit/naming-convention.test.js +231 -0
  70. package/dist/vitest.config.d.ts +3 -0
  71. package/dist/vitest.config.d.ts.map +1 -0
  72. package/package.json +12 -7
  73. package/scripts/republish-versions.sh +94 -0
  74. package/src/cli.ts +34 -3
  75. package/src/generator.ts +8 -1
  76. package/src/services/code-generator.service.ts +74 -7
  77. package/src/types/generator-options.ts +60 -0
  78. package/src/utils/error-handler.ts +2 -2
  79. package/src/utils/naming-convention.ts +214 -0
  80. package/src/utils/signal-handler.ts +2 -2
  81. package/tests/integration/cli.test.ts +2 -2
  82. package/tests/unit/code-generator.test.ts +189 -1
  83. package/tests/unit/naming-convention.test.ts +263 -0
  84. package/tsconfig.json +2 -0
@@ -0,0 +1,60 @@
1
+ import type {NamingConvention, OperationNameTransformer} from '../utils/naming-convention.js';
2
+
3
+ /**
4
+ * Configuration options for the Generator class.
5
+ *
6
+ * These options control how operation IDs are transformed during code generation.
7
+ * You can either use a predefined naming convention or provide a custom transformer function.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * // Using a naming convention
12
+ * const generator = new Generator(..., {
13
+ * namingConvention: 'camelCase'
14
+ * });
15
+ *
16
+ * // Using a custom transformer
17
+ * const generator = new Generator(..., {
18
+ * operationNameTransformer: (details) => {
19
+ * return `${details.method}_${details.operationId}`;
20
+ * }
21
+ * });
22
+ * ```
23
+ */
24
+ export interface GeneratorOptions {
25
+ /**
26
+ * Naming convention to apply to operation IDs.
27
+ *
28
+ * If provided, all operation IDs will be transformed according to the specified convention.
29
+ * This is useful when OpenAPI specs have inconsistent or poorly named operation IDs.
30
+ *
31
+ * **Note:** If `operationNameTransformer` is also provided, it takes precedence.
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * { namingConvention: 'camelCase' } // Transforms 'get_user_by_id' → 'getUserById'
36
+ * ```
37
+ */
38
+ namingConvention?: NamingConvention;
39
+
40
+ /**
41
+ * Custom transformer function for operation names.
42
+ *
43
+ * If provided, this function will be called for each operation with full operation details.
44
+ * This allows for advanced customization based on HTTP method, path, tags, etc.
45
+ *
46
+ * **Note:** This takes precedence over `namingConvention` if both are provided.
47
+ * The returned name will be sanitized to ensure it's a valid TypeScript identifier.
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * {
52
+ * operationNameTransformer: (details) => {
53
+ * const tag = details.tags?.[0] || 'default';
54
+ * return `${details.method.toUpperCase()}_${tag}_${details.operationId}`;
55
+ * }
56
+ * }
57
+ * ```
58
+ */
59
+ operationNameTransformer?: OperationNameTransformer;
60
+ }
@@ -7,7 +7,7 @@ export const errorReceived = (process: NodeJS.Process, startTime: bigint) => ():
7
7
 
8
8
  export const handleErrors = (process: NodeJS.Process, startTime: bigint): void => {
9
9
  const catchErrors: string[] = ['unhandledRejection', 'uncaughtException'];
10
- catchErrors.map((event): NodeJS.EventEmitter => {
11
- return process.on(event, errorReceived(process, startTime));
10
+ catchErrors.forEach((event) => {
11
+ process.on(event, errorReceived(process, startTime));
12
12
  });
13
13
  };
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Supported naming conventions for operation IDs.
3
+ * These conventions transform operation IDs to match common programming language styles.
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * transformNamingConvention('get_user_by_id', 'camelCase') // 'getUserById'
8
+ * transformNamingConvention('getUserById', 'snake_case') // 'get_user_by_id'
9
+ * ```
10
+ */
11
+ export type NamingConvention =
12
+ | 'camelCase'
13
+ | 'PascalCase'
14
+ | 'snake_case'
15
+ | 'kebab-case'
16
+ | 'SCREAMING_SNAKE_CASE'
17
+ | 'SCREAMING-KEBAB-CASE';
18
+
19
+ /**
20
+ * Operation details provided to custom transformers.
21
+ * Contains all available information about an OpenAPI operation.
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * const transformer: OperationNameTransformer = (details) => {
26
+ * return `${details.method.toUpperCase()}_${details.operationId}`;
27
+ * };
28
+ * ```
29
+ */
30
+ export interface OperationDetails {
31
+ /** Original operationId from OpenAPI spec */
32
+ operationId: string;
33
+ /** HTTP method (get, post, put, patch, delete, head, options) */
34
+ method: string;
35
+ /** API path (e.g., /users/{id}) */
36
+ path: string;
37
+ /** Tags associated with the operation */
38
+ tags?: string[];
39
+ /** Summary of the operation */
40
+ summary?: string;
41
+ /** Description of the operation */
42
+ description?: string;
43
+ }
44
+
45
+ /**
46
+ * Custom transformer function for operation names.
47
+ * Receives operation details and returns the transformed name.
48
+ *
49
+ * **Note:** The returned name will be sanitized to ensure it's a valid TypeScript identifier.
50
+ * Invalid characters will be replaced with underscores, and names starting with digits will be prefixed.
51
+ *
52
+ * @param details - Complete operation details from OpenAPI spec
53
+ * @returns The transformed operation name
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * const transformer: OperationNameTransformer = (details) => {
58
+ * const tag = details.tags?.[0] || 'default';
59
+ * return `${details.method}_${tag}_${details.operationId}`;
60
+ * };
61
+ * ```
62
+ */
63
+ export type OperationNameTransformer = (details: OperationDetails) => string;
64
+
65
+ /**
66
+ * Capitalizes the first letter of a word
67
+ */
68
+ function capitalize(word: string): string {
69
+ if (word.length === 0) return word;
70
+ return word.charAt(0).toUpperCase() + word.slice(1);
71
+ }
72
+
73
+ /**
74
+ * Splits camelCase or PascalCase strings into words
75
+ */
76
+ function splitCamelCase(input: string): string[] {
77
+ const words: string[] = [];
78
+ let currentWord = '';
79
+
80
+ for (const char of input) {
81
+ const isUpperCase = char === char.toUpperCase() && char !== char.toLowerCase();
82
+ const isDigit = /\d/.test(char);
83
+ const lastChar = currentWord[currentWord.length - 1];
84
+
85
+ // Start a new word if:
86
+ // 1. Current char is uppercase and we have a previous word
87
+ // 2. Current char is a digit and previous was not
88
+ if (currentWord.length > 0 && (isUpperCase || (isDigit && lastChar && !/\d/.test(lastChar)))) {
89
+ words.push(currentWord);
90
+ currentWord = '';
91
+ }
92
+
93
+ currentWord += char;
94
+ }
95
+
96
+ if (currentWord.length > 0) {
97
+ words.push(currentWord);
98
+ }
99
+
100
+ return words.length > 0 ? words : [input];
101
+ }
102
+
103
+ /**
104
+ * Normalizes input string into an array of words
105
+ * Handles camelCase, PascalCase, snake_case, kebab-case, SCREAMING_SNAKE_CASE, etc.
106
+ */
107
+ function normalizeToWords(input: string): string[] {
108
+ // Handle empty or single character
109
+ if (input.length <= 1) {
110
+ return [input.toLowerCase()];
111
+ }
112
+
113
+ // Split by common delimiters: underscore, hyphen, space, dot
114
+ let words = input.split(/[-_\s.]+/).filter((w) => w.length > 0);
115
+
116
+ // If no delimiters found, try to split camelCase/PascalCase
117
+ if (words.length === 1) {
118
+ words = splitCamelCase(input);
119
+ }
120
+
121
+ // Normalize all words to lowercase
122
+ return words.map((w) => w.toLowerCase());
123
+ }
124
+
125
+ /**
126
+ * Converts words array to camelCase
127
+ */
128
+ function toCamelCase(words: string[]): string {
129
+ if (words.length === 0) return '';
130
+ const [first, ...rest] = words;
131
+ if (!first) return '';
132
+ return first + rest.map((w) => capitalize(w)).join('');
133
+ }
134
+
135
+ /**
136
+ * Converts words array to PascalCase
137
+ */
138
+ function toPascalCase(words: string[]): string {
139
+ return words.map((w) => capitalize(w)).join('');
140
+ }
141
+
142
+ /**
143
+ * Converts words array to snake_case
144
+ */
145
+ function toSnakeCase(words: string[]): string {
146
+ return words.join('_');
147
+ }
148
+
149
+ /**
150
+ * Converts words array to kebab-case
151
+ */
152
+ function toKebabCase(words: string[]): string {
153
+ return words.join('-');
154
+ }
155
+
156
+ /**
157
+ * Converts words array to SCREAMING_SNAKE_CASE
158
+ */
159
+ function toScreamingSnakeCase(words: string[]): string {
160
+ return words.map((w) => w.toUpperCase()).join('_');
161
+ }
162
+
163
+ /**
164
+ * Converts words array to SCREAMING-KEBAB-CASE
165
+ */
166
+ function toScreamingKebabCase(words: string[]): string {
167
+ return words.map((w) => w.toUpperCase()).join('-');
168
+ }
169
+ /**
170
+ * Transforms a string to the specified naming convention.
171
+ *
172
+ * Handles various input formats including camelCase, PascalCase, snake_case, kebab-case,
173
+ * and mixed delimiters. The function normalizes the input by splitting on common delimiters
174
+ * (underscores, hyphens, spaces, dots) and then applies the target convention.
175
+ *
176
+ * **Note:** This function does not sanitize the output. The caller should ensure the result
177
+ * is a valid identifier for the target language (e.g., using `sanitizeIdentifier`).
178
+ *
179
+ * @param input - The input string to transform (can be in any naming convention)
180
+ * @param convention - The target naming convention to apply
181
+ * @returns The transformed string in the target convention
182
+ *
183
+ * @example
184
+ * ```typescript
185
+ * transformNamingConvention('get_user_by_id', 'camelCase') // 'getUserById'
186
+ * transformNamingConvention('getUserById', 'snake_case') // 'get_user_by_id'
187
+ * transformNamingConvention('get-user-by-id', 'PascalCase') // 'GetUserById'
188
+ * ```
189
+ *
190
+ * @throws Will return empty string if input is empty (preserves empty input)
191
+ */
192
+ export function transformNamingConvention(input: string, convention: NamingConvention): string {
193
+ if (!input || input.length === 0) {
194
+ return input;
195
+ }
196
+
197
+ // Normalize input: split by common delimiters and convert to words
198
+ const words = normalizeToWords(input);
199
+
200
+ switch (convention) {
201
+ case 'camelCase':
202
+ return toCamelCase(words);
203
+ case 'PascalCase':
204
+ return toPascalCase(words);
205
+ case 'snake_case':
206
+ return toSnakeCase(words);
207
+ case 'kebab-case':
208
+ return toKebabCase(words);
209
+ case 'SCREAMING_SNAKE_CASE':
210
+ return toScreamingSnakeCase(words);
211
+ case 'SCREAMING-KEBAB-CASE':
212
+ return toScreamingKebabCase(words);
213
+ }
214
+ }
@@ -8,7 +8,7 @@ export const signalReceived = (process: NodeJS.Process, startTime: bigint, event
8
8
 
9
9
  export const handleSignals = (process: NodeJS.Process, startTime: bigint): void => {
10
10
  const catchSignals: NodeJS.Signals[] = ['SIGTERM', 'SIGINT', 'SIGUSR2'];
11
- catchSignals.map((event): NodeJS.EventEmitter => {
12
- return process.once(event, signalReceived(process, startTime, event));
11
+ catchSignals.forEach((event) => {
12
+ process.once(event, signalReceived(process, startTime, event));
13
13
  });
14
14
  };
@@ -5,7 +5,7 @@ import {resolve} from 'node:path';
5
5
  describe('CLI Integration', () => {
6
6
  describe('--help', () => {
7
7
  it('should display help information', () => {
8
- const result = execSync('yarn build && node ./dist/src/cli.js --help', {
8
+ const result = execSync('npm run build && node ./dist/src/cli.js --help', {
9
9
  encoding: 'utf-8',
10
10
  cwd: resolve(__dirname, '../..'),
11
11
  });
@@ -18,7 +18,7 @@ describe('CLI Integration', () => {
18
18
 
19
19
  describe('--version', () => {
20
20
  it('should display version information', () => {
21
- const result = execSync('yarn build && node ./dist/src/cli.js --version', {
21
+ const result = execSync('npm run build && node ./dist/src/cli.js --version', {
22
22
  encoding: 'utf-8',
23
23
  cwd: resolve(__dirname, '../..'),
24
24
  });
@@ -1,4 +1,4 @@
1
- import {describe, expect, it} from 'vitest';
1
+ import {beforeEach, describe, expect, it} from 'vitest';
2
2
  import {TypeScriptCodeGeneratorService} from '../../src/services/code-generator.service.js';
3
3
  import type {OpenApiSpecType} from '../../src/types/openapi.js';
4
4
 
@@ -9,6 +9,194 @@ describe('TypeScriptCodeGeneratorService', () => {
9
9
  generator = new TypeScriptCodeGeneratorService();
10
10
  });
11
11
 
12
+ describe('naming conventions', () => {
13
+ it('should apply camelCase naming convention', () => {
14
+ const spec: OpenApiSpecType = {
15
+ openapi: '3.0.0',
16
+ info: {
17
+ title: 'Test API',
18
+ version: '1.0.0',
19
+ },
20
+ paths: {
21
+ '/users': {
22
+ get: {
23
+ operationId: 'get_user_by_id',
24
+ responses: {
25
+ '200': {
26
+ description: 'Success',
27
+ content: {
28
+ 'application/json': {
29
+ schema: {type: 'string'},
30
+ },
31
+ },
32
+ },
33
+ },
34
+ },
35
+ },
36
+ },
37
+ };
38
+
39
+ const generatorWithConvention = new TypeScriptCodeGeneratorService({
40
+ namingConvention: 'camelCase',
41
+ });
42
+ const code = generatorWithConvention.generate(spec);
43
+ expect(code).toContain('async getUserById');
44
+ expect(code).not.toContain('async get_user_by_id');
45
+ });
46
+
47
+ it('should apply PascalCase naming convention', () => {
48
+ const spec: OpenApiSpecType = {
49
+ openapi: '3.0.0',
50
+ info: {
51
+ title: 'Test API',
52
+ version: '1.0.0',
53
+ },
54
+ paths: {
55
+ '/users': {
56
+ get: {
57
+ operationId: 'get_user_by_id',
58
+ responses: {
59
+ '200': {
60
+ description: 'Success',
61
+ content: {
62
+ 'application/json': {
63
+ schema: {type: 'string'},
64
+ },
65
+ },
66
+ },
67
+ },
68
+ },
69
+ },
70
+ },
71
+ };
72
+
73
+ const generatorWithConvention = new TypeScriptCodeGeneratorService({
74
+ namingConvention: 'PascalCase',
75
+ });
76
+ const code = generatorWithConvention.generate(spec);
77
+ expect(code).toContain('async GetUserById');
78
+ expect(code).not.toContain('async get_user_by_id');
79
+ });
80
+
81
+ it('should apply snake_case naming convention', () => {
82
+ const spec: OpenApiSpecType = {
83
+ openapi: '3.0.0',
84
+ info: {
85
+ title: 'Test API',
86
+ version: '1.0.0',
87
+ },
88
+ paths: {
89
+ '/users': {
90
+ get: {
91
+ operationId: 'getUserById',
92
+ responses: {
93
+ '200': {
94
+ description: 'Success',
95
+ content: {
96
+ 'application/json': {
97
+ schema: {type: 'string'},
98
+ },
99
+ },
100
+ },
101
+ },
102
+ },
103
+ },
104
+ },
105
+ };
106
+
107
+ const generatorWithConvention = new TypeScriptCodeGeneratorService({
108
+ namingConvention: 'snake_case',
109
+ });
110
+ const code = generatorWithConvention.generate(spec);
111
+ expect(code).toContain('async get_user_by_id');
112
+ expect(code).not.toContain('async getUserById');
113
+ });
114
+
115
+ it('should use custom transformer when provided', () => {
116
+ const spec: OpenApiSpecType = {
117
+ openapi: '3.0.0',
118
+ info: {
119
+ title: 'Test API',
120
+ version: '1.0.0',
121
+ },
122
+ paths: {
123
+ '/users/{id}': {
124
+ get: {
125
+ operationId: 'getUserById',
126
+ tags: ['users'],
127
+ summary: 'Get user',
128
+ responses: {
129
+ '200': {
130
+ description: 'Success',
131
+ content: {
132
+ 'application/json': {
133
+ schema: {type: 'string'},
134
+ },
135
+ },
136
+ },
137
+ },
138
+ },
139
+ },
140
+ },
141
+ };
142
+
143
+ const customTransformer = (details: {
144
+ operationId: string;
145
+ method: string;
146
+ path: string;
147
+ tags?: string[];
148
+ summary?: string;
149
+ description?: string;
150
+ }) => {
151
+ return `${details.method.toUpperCase()}_${details.tags?.[0] || 'default'}_${details.operationId}`;
152
+ };
153
+
154
+ const generatorWithTransformer = new TypeScriptCodeGeneratorService({
155
+ operationNameTransformer: customTransformer,
156
+ });
157
+ const code = generatorWithTransformer.generate(spec);
158
+ expect(code).toContain('async GET_users_getUserById');
159
+ });
160
+
161
+ it('should prioritize custom transformer over naming convention', () => {
162
+ const spec: OpenApiSpecType = {
163
+ openapi: '3.0.0',
164
+ info: {
165
+ title: 'Test API',
166
+ version: '1.0.0',
167
+ },
168
+ paths: {
169
+ '/users': {
170
+ get: {
171
+ operationId: 'get_user_by_id',
172
+ responses: {
173
+ '200': {
174
+ description: 'Success',
175
+ content: {
176
+ 'application/json': {
177
+ schema: {type: 'string'},
178
+ },
179
+ },
180
+ },
181
+ },
182
+ },
183
+ },
184
+ },
185
+ };
186
+
187
+ const customTransformer = () => 'customName';
188
+
189
+ const generatorWithBoth = new TypeScriptCodeGeneratorService({
190
+ namingConvention: 'PascalCase',
191
+ operationNameTransformer: customTransformer,
192
+ });
193
+ const code = generatorWithBoth.generate(spec);
194
+ expect(code).toContain('async customName');
195
+ expect(code).not.toContain('GetUserById');
196
+ expect(code).not.toContain('get_user_by_id');
197
+ });
198
+ });
199
+
12
200
  describe('generate', () => {
13
201
  it('should generate code for a minimal OpenAPI spec', () => {
14
202
  const spec: OpenApiSpecType = {