zod-codegen 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/.github/workflows/ci.yml +17 -17
  2. package/.github/workflows/release.yml +8 -8
  3. package/CHANGELOG.md +17 -0
  4. package/README.md +61 -9
  5. package/dist/src/cli.d.ts +3 -0
  6. package/dist/src/cli.d.ts.map +1 -0
  7. package/dist/src/cli.js +31 -2
  8. package/dist/src/generator.d.ts +23 -0
  9. package/dist/src/generator.d.ts.map +1 -0
  10. package/dist/src/generator.js +3 -2
  11. package/dist/src/http/fetch-client.d.ts +15 -0
  12. package/dist/src/http/fetch-client.d.ts.map +1 -0
  13. package/dist/src/interfaces/code-generator.d.ts +20 -0
  14. package/dist/src/interfaces/code-generator.d.ts.map +1 -0
  15. package/dist/src/interfaces/file-reader.d.ts +13 -0
  16. package/dist/src/interfaces/file-reader.d.ts.map +1 -0
  17. package/dist/src/polyfills/fetch.d.ts +5 -0
  18. package/dist/src/polyfills/fetch.d.ts.map +1 -0
  19. package/dist/src/services/code-generator.service.d.ts +57 -0
  20. package/dist/src/services/code-generator.service.d.ts.map +1 -0
  21. package/dist/src/services/code-generator.service.js +41 -4
  22. package/dist/src/services/file-reader.service.d.ts +9 -0
  23. package/dist/src/services/file-reader.service.d.ts.map +1 -0
  24. package/dist/src/services/file-writer.service.d.ts +10 -0
  25. package/dist/src/services/file-writer.service.d.ts.map +1 -0
  26. package/dist/src/services/import-builder.service.d.ts +14 -0
  27. package/dist/src/services/import-builder.service.d.ts.map +1 -0
  28. package/dist/src/services/type-builder.service.d.ts +12 -0
  29. package/dist/src/services/type-builder.service.d.ts.map +1 -0
  30. package/dist/src/types/generator-options.d.ts +59 -0
  31. package/dist/src/types/generator-options.d.ts.map +1 -0
  32. package/dist/src/types/generator-options.js +1 -0
  33. package/dist/src/types/http.d.ts +25 -0
  34. package/dist/src/types/http.d.ts.map +1 -0
  35. package/dist/src/types/openapi.d.ts +1120 -0
  36. package/dist/src/types/openapi.d.ts.map +1 -0
  37. package/dist/src/utils/error-handler.d.ts +3 -0
  38. package/dist/src/utils/error-handler.d.ts.map +1 -0
  39. package/dist/src/utils/error-handler.js +2 -2
  40. package/dist/src/utils/execution-time.d.ts +2 -0
  41. package/dist/src/utils/execution-time.d.ts.map +1 -0
  42. package/dist/src/utils/manifest.d.ts +8 -0
  43. package/dist/src/utils/manifest.d.ts.map +1 -0
  44. package/dist/src/utils/naming-convention.d.ts +80 -0
  45. package/dist/src/utils/naming-convention.d.ts.map +1 -0
  46. package/dist/src/utils/naming-convention.js +135 -0
  47. package/dist/src/utils/reporter.d.ts +7 -0
  48. package/dist/src/utils/reporter.d.ts.map +1 -0
  49. package/dist/src/utils/signal-handler.d.ts +3 -0
  50. package/dist/src/utils/signal-handler.d.ts.map +1 -0
  51. package/dist/src/utils/signal-handler.js +2 -2
  52. package/dist/src/utils/tty.d.ts +2 -0
  53. package/dist/src/utils/tty.d.ts.map +1 -0
  54. package/dist/vitest.config.d.ts +3 -0
  55. package/dist/vitest.config.d.ts.map +1 -0
  56. package/package.json +15 -15
  57. package/src/cli.ts +34 -3
  58. package/src/generator.ts +8 -1
  59. package/src/services/code-generator.service.ts +51 -8
  60. package/src/types/generator-options.ts +60 -0
  61. package/src/utils/error-handler.ts +2 -2
  62. package/src/utils/naming-convention.ts +214 -0
  63. package/src/utils/signal-handler.ts +2 -2
  64. package/tests/integration/cli.test.ts +2 -2
  65. package/tests/unit/code-generator.test.ts +192 -4
  66. package/tests/unit/generator.test.ts +2 -2
  67. package/tests/unit/naming-convention.test.ts +263 -0
  68. package/tsconfig.json +3 -1
  69. package/.claude/settings.local.json +0 -43
  70. package/dist/scripts/update-manifest.js +0 -31
  71. package/dist/tests/integration/cli.test.js +0 -25
  72. package/dist/tests/unit/code-generator.test.js +0 -290
  73. package/dist/tests/unit/file-reader.test.js +0 -110
  74. package/dist/tests/unit/generator.test.js +0 -100
  75. package/scripts/republish-versions.sh +0 -94
@@ -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 = {
@@ -24,7 +212,7 @@ describe('TypeScriptCodeGeneratorService', () => {
24
212
  expect(code).toBeTruthy();
25
213
  expect(typeof code).toBe('string');
26
214
  expect(code).toMatch(/import\s*{\s*z\s*}\s*from\s*['"]zod['"]/);
27
- expect(code).toContain('export class');
215
+ expect(code).toContain('export default class');
28
216
  });
29
217
 
30
218
  it('should generate schemas for component schemas', () => {
@@ -87,7 +275,7 @@ describe('TypeScriptCodeGeneratorService', () => {
87
275
 
88
276
  const code = generator.generate(spec);
89
277
  expect(code).toContain('async getUsers');
90
- expect(code).toContain('#makeRequest');
278
+ expect(code).toContain('makeRequest');
91
279
  });
92
280
 
93
281
  it('should generate getBaseRequestOptions method', () => {
@@ -220,7 +408,7 @@ describe('TypeScriptCodeGeneratorService', () => {
220
408
  expect(code).not.toContain('ExecutionMode: z.enum');
221
409
  });
222
410
 
223
- it('should merge baseOptions with request-specific options in #makeRequest', () => {
411
+ it('should merge baseOptions with request-specific options in makeRequest', () => {
224
412
  const spec: OpenApiSpecType = {
225
413
  openapi: '3.0.0',
226
414
  info: {
@@ -68,7 +68,7 @@ describe('Generator', () => {
68
68
  // Verify file contains expected content
69
69
  const content = readFileSync(outputFile, 'utf-8');
70
70
  expect(content).toMatch(/import\s*{\s*z\s*}\s*from\s*['"]zod['"]/);
71
- expect(content).toContain('export class');
71
+ expect(content).toContain('export default class');
72
72
  expect(content).toContain('getBaseRequestOptions');
73
73
  });
74
74
 
@@ -109,7 +109,7 @@ describe('Generator', () => {
109
109
  expect(content).toMatch(/import\s*{\s*z\s*}\s*from\s*['"]zod['"]/);
110
110
  expect(content).toContain('export const');
111
111
  expect(content).toContain('protected getBaseRequestOptions');
112
- expect(content).toContain('async #makeRequest');
112
+ expect(content).toContain('protected async makeRequest');
113
113
  });
114
114
 
115
115
  it('should include header comments in generated file', async () => {