@paulpugovkin/api-docs-axios-ts-generator 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@paulpugovkin/api-docs-axios-ts-generator",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "description": "Generate TypeScript interfaces and axios classes from OpenAPI documentation",
5
- "main": "src/index.min.js",
5
+ "main": "src/index.js",
6
6
  "bin": {
7
- "api-docs-generator": "./src/index.min.js"
7
+ "api-docs-generator": "./bin/cli.js"
8
8
  },
9
9
  "types": "src/types/index.d.ts",
10
10
  "scripts": {
@@ -37,7 +37,22 @@
37
37
  "node": ">=14.0.0"
38
38
  },
39
39
  "files": [
40
- "src",
40
+ "src/index.min.js",
41
+ "src/clean-generated-folder",
42
+ "src/collect-genereted-files",
43
+ "src/generate-class",
44
+ "src/generate-index-file-with-public-api",
45
+ "src/generate-interface",
46
+ "src/generate-js-doc",
47
+ "src/generate-main-index-file",
48
+ "src/generate-method",
49
+ "src/generators",
50
+ "src/map-type",
51
+ "src/parse-and-generate",
52
+ "src/resolve-type",
53
+ "src/scripts",
54
+ "src/templates",
55
+ "src/update-api-docs-json",
41
56
  "bin",
42
57
  "README.md",
43
58
  "LICENSE"
@@ -1,33 +0,0 @@
1
- /**
2
- * Конфигурация по умолчанию для генератора
3
- */
4
- import { GeneratorConfig } from '../types/config.types';
5
-
6
- export const defaultConfig: Partial<GeneratorConfig> = {
7
- outputDir: './generated',
8
- interfacesDir: './generated/interfaces',
9
- classesDir: './generated/classes',
10
- groupBy: 'tag',
11
- classMode: 'multiple',
12
- tags: {
13
- prefix: 'api_tag_',
14
- },
15
- imports: {
16
- axiosPath: 'axios',
17
- baseUrlPath: './config/axios/axios',
18
- },
19
- options: {
20
- generateJSDoc: true,
21
- generateIndexFiles: true,
22
- cleanOutputDir: true,
23
- generateAxiosConfig: true,
24
- allowAxiosConfigSpread: true,
25
- },
26
- axios: {
27
- baseURL: '',
28
- timeout: 30000,
29
- headers: {
30
- 'Content-Type': 'application/json',
31
- },
32
- },
33
- };
@@ -1,112 +0,0 @@
1
- /**
2
- * Загрузка конфигурации генератора
3
- */
4
- // @ts-ignore - Node.js types
5
- import fs from 'fs';
6
- // @ts-ignore - Node.js types
7
- import path from 'path';
8
- import { GeneratorConfig } from '../types/config.types';
9
- import { defaultConfig } from './defaultConfig';
10
- import { validateConfig } from './validateConfig';
11
-
12
- /**
13
- * Загружает конфигурацию из файла
14
- * @param configPath - Путь к файлу конфигурации
15
- * @returns Объект конфигурации
16
- */
17
- async function loadConfigFile(configPath: string): Promise<Partial<GeneratorConfig>> {
18
- const resolvedPath = path.resolve(configPath);
19
-
20
- if (!fs.existsSync(resolvedPath)) {
21
- throw new Error(`Configuration file not found: ${resolvedPath}`);
22
- }
23
-
24
- // Удаляем кэш для поддержки горячей перезагрузки
25
- // @ts-ignore
26
- delete require.cache[require.resolve(resolvedPath)];
27
-
28
- try {
29
- // @ts-ignore
30
- const userConfig = require(resolvedPath);
31
- return userConfig.default || userConfig;
32
- } catch (error) {
33
- throw new Error(`Failed to load configuration from ${resolvedPath}: ${error}`);
34
- }
35
- }
36
-
37
- /**
38
- * Объединяет конфигурации (пользовательская перекрывает дефолтную)
39
- * @param defaults - Конфигурация по умолчанию
40
- * @param userConfig - Пользовательская конфигурация
41
- * @returns Объединённая конфигурация
42
- */
43
- function mergeConfigs(
44
- defaults: Partial<GeneratorConfig>,
45
- userConfig: Partial<GeneratorConfig>
46
- ): GeneratorConfig {
47
- const merged: any = {
48
- ...defaults,
49
- ...userConfig,
50
- };
51
-
52
- // Глубокое слияние для вложенных объектов
53
- if (defaults.tags && userConfig.tags) {
54
- merged.tags = { ...defaults.tags, ...userConfig.tags };
55
- }
56
-
57
- if (defaults.naming && userConfig.naming) {
58
- merged.naming = { ...defaults.naming, ...userConfig.naming };
59
- }
60
-
61
- if (defaults.imports && userConfig.imports) {
62
- merged.imports = { ...defaults.imports, ...userConfig.imports };
63
- }
64
-
65
- if (defaults.options && userConfig.options) {
66
- merged.options = { ...defaults.options, ...userConfig.options };
67
- }
68
-
69
- if (defaults.axios && userConfig.axios) {
70
- merged.axios = { ...defaults.axios, ...userConfig.axios };
71
- // Глубокое слияние для headers
72
- if (defaults.axios.headers && userConfig.axios.headers) {
73
- merged.axios.headers = { ...defaults.axios.headers, ...userConfig.axios.headers };
74
- }
75
- }
76
-
77
- return merged as GeneratorConfig;
78
- }
79
-
80
- /**
81
- * Загружает конфигурацию генератора
82
- * @param configPath - Путь к файлу конфигурации (опционально)
83
- * @param cliOverrides - Переопределения из CLI аргументов
84
- * @returns Полная конфигурация генератора
85
- */
86
- export async function loadConfig(
87
- configPath?: string,
88
- cliOverrides?: Partial<GeneratorConfig>
89
- ): Promise<GeneratorConfig> {
90
- let userConfig: Partial<GeneratorConfig> = {};
91
-
92
- // Загрузка из файла, если указан
93
- if (configPath) {
94
- console.log(`Loading configuration from: ${configPath}`);
95
- userConfig = await loadConfigFile(configPath);
96
- } else {
97
- console.log('No configuration file specified, using default configuration');
98
- }
99
-
100
- // Слияние с конфигурацией по умолчанию
101
- let mergedConfig = mergeConfigs(defaultConfig, userConfig);
102
-
103
- // Применение переопределений из CLI
104
- if (cliOverrides) {
105
- mergedConfig = mergeConfigs(mergedConfig, cliOverrides);
106
- }
107
-
108
- // Валидация конфигурации
109
- validateConfig(mergedConfig);
110
-
111
- return mergedConfig;
112
- }
@@ -1,58 +0,0 @@
1
- /**
2
- * Валидация конфигурации генератора
3
- */
4
- import { GeneratorConfig } from '../types/config.types';
5
-
6
- export function validateConfig(config: GeneratorConfig): void {
7
- // Проверка обязательного поля outputDir
8
- if (!config.outputDir) {
9
- throw new Error('Configuration error: outputDir is required');
10
- }
11
-
12
- // Проверка, что указан либо apiDocsUrl, либо apiDocsPath
13
- if (!config.apiDocsUrl && !config.apiDocsPath) {
14
- throw new Error('Configuration error: either apiDocsUrl or apiDocsPath must be specified');
15
- }
16
-
17
- // Проверка groupBy
18
- if (config.groupBy && !['tag', 'all', 'path'].includes(config.groupBy)) {
19
- throw new Error(`Configuration error: invalid groupBy value "${config.groupBy}". Must be one of: tag, all, path`);
20
- }
21
-
22
- // Проверка classMode
23
- if (config.classMode && !['single', 'multiple'].includes(config.classMode)) {
24
- throw new Error(`Configuration error: invalid classMode value "${config.classMode}". Must be one of: single, multiple`);
25
- }
26
-
27
- // Проверка фильтрации по тегам
28
- if (config.tags) {
29
- if (config.tags.include && config.tags.exclude) {
30
- console.warn('Warning: Both include and exclude tags are specified. Include will take precedence.');
31
- }
32
-
33
- if (config.tags.include && config.tags.include.length === 0) {
34
- console.warn('Warning: tags.include is empty. No tags will be filtered.');
35
- }
36
- }
37
-
38
- // Проверка совместимости groupBy и classMode
39
- if (config.groupBy === 'all' && config.classMode === 'multiple') {
40
- console.warn('Warning: groupBy="all" with classMode="multiple" will generate only one class. Consider using classMode="single".');
41
- }
42
-
43
- // Проверка настроек axios
44
- if (config.axios) {
45
- if (config.axios.timeout !== undefined && config.axios.timeout < 0) {
46
- throw new Error('Configuration error: axios.timeout must be a positive number');
47
- }
48
- }
49
-
50
- // Проверка опций генерации
51
- if (config.options) {
52
- if (config.options.generateAxiosConfig && !config.axios) {
53
- console.warn('Warning: generateAxiosConfig is true but no axios config provided. Using default values.');
54
- }
55
- }
56
-
57
- console.log('Configuration validated successfully.');
58
- }
package/src/index.min.js DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- const fs=require('fs'),path=require('path'),{program}=require('commander'),{loadConfig}=require('./config/loadConfig'),{parseAndGenerate}=require('./parse-and-generate/parseAndGenerate'),{cleanGeneratedFolder}=require('./clean-generated-folder/cleanGeneratedFolder'),{collectGeneratedFiles}=require('./collect-genereted-files/collectGeneratedFiles'),{generateInterface}=require('./generate-interface/generateInterface'),{generateClass}=require('./generate-class/generateClass'),{generateMethod}=require('./generate-method/generateMethod'),{generateJSDoc}=require('./generate-js-doc/generateJSDoc'),{generateIndexFileWithPublicApi}=require('./generate-index-file-with-public-api/generateIndexFileWithPublicApi'),{generateMainIndexFile}=require('./generate-main-index-file/generateMainIndexFile'),{generateAxiosConfig}=require('./generators/axiosConfigGenerator'),{mapType}=require('./map-type/mapType'),{resolveType}=require('./resolve-type/resolveType'),{updateApiDocsJson}=require('./update-api-docs-json/updateApiDocsJson');program.name('api-docs-generator').description('Generate TypeScript interfaces and axios classes from OpenAPI documentation').version('1.0.0').option('-c, --config <path>','Path to configuration file').option('--api-docs-url <url>','URL to fetch OpenAPI documentation').option('--api-docs-path <path>','Local path to OpenAPI documentation file').option('--output-dir <dir>','Output directory for generated files').option('--clean','Clean output directory before generation');program.parse(process.argv);async function main(){let config;const options=program.opts();if(options.config){try{const configPath=path.resolve(options.config);if(!fs.existsSync(configPath)){console.error(`Configuration file not found: ${configPath}`);process.exit(1);}const configContent=fs.readFileSync(configPath,'utf8');const ext=path.extname(configPath);if(ext==='.js'){const modulePath=path.resolve(configPath);config=eval(`require('${modulePath.replace(/\\/g,'\\\\')}')`);}else if(ext==='.json'){config=JSON.parse(configContent);}else if(ext==='.ts'){const ts=require('typescript');const result=ts.transpileModule(configContent,{compilerOptions:{module:1,target:99,esModuleInterop:!0}});const modulePath=path.resolve(configPath.replace('.ts','.js'));fs.writeFileSync(modulePath,result);config=eval(`require('${modulePath.replace(/\\/g,'\\\\')}')`);}else{console.error('Unsupported configuration file format. Use .js, .json, or .ts');process.exit(1);}}catch(error){console.error(`Failed to load configuration: ${error.message}`);process.exit(1);}}else{const apiDocsUrl=options.apiDocsUrl;if(!apiDocsUrl){console.error('Error: API documentation URL is required.');console.error('Please specify --api-docs-url or --api-docs-path, or create a configuration file.');console.error('Run "api-docs-generator --help" for more information.');process.exit(1);}const outputDir=options.outputDir||path.resolve(__dirname,"../generated");config={apiDocsUrl:apiDocsUrl,outputDir:outputDir,interfacesDir:path.join(outputDir,"interfaces"),classesDir:path.join(outputDir,"classes"),groupBy:"tag",classMode:"multiple",options:{cleanOutputDir:options.clean!==undefined?options.clean:!0,generateAxiosConfig:!1,allowAxiosConfigSpread:!0}};}await cleanGeneratedFolder(config);const apiDocs=await updateApiDocsJson(config);const schemaData=apiDocs.paths?apiDocs.paths:apiDocs.components?.schemas||{};const generatedFiles=await collectGeneratedFiles(config);const interfaces=generatedFiles.filter(f=>f.endsWith('.ts')&&!f.includes('index'));const classes=generatedFiles.filter(f=>f.endsWith('.ts')&&!f.includes('index'));await generateInterface(schemaData,interfaces,config);await generateClass(schemaData,classes,config);await generateJSDoc(schemaData,classes,config);await generateMethod(schemaData,classes,config);await generateIndexFileWithPublicApi(config);await generateMainIndexFile(config);await generateAxiosConfig(config);console.log('✓ API client generated successfully!');console.log(` Output directory: ${config.outputDir}`);}main().catch(error=>{console.error('Error:',error.message);process.exit(1);});
@@ -1,183 +0,0 @@
1
- /**
2
- * Типы конфигурации для генератора API клиента
3
- */
4
-
5
- /**
6
- * Основная конфигурация генератора
7
- */
8
- export interface GeneratorConfig {
9
- /**
10
- * URL для загрузки OpenAPI спецификации
11
- */
12
- apiDocsUrl?: string;
13
-
14
- /**
15
- * Локальный путь к файлу OpenAPI спецификации
16
- */
17
- apiDocsPath?: string;
18
-
19
- /**
20
- * Директория для вывода сгенерированных файлов
21
- */
22
- outputDir: string;
23
-
24
- /**
25
- * Директория для интерфейсов (опционально, по умолчанию outputDir/interfaces)
26
- */
27
- interfacesDir?: string;
28
-
29
- /**
30
- * Директория для классов (опционально, по умолчанию outputDir/classes)
31
- */
32
- classesDir?: string;
33
-
34
- /**
35
- * Настройки фильтрации по тегам
36
- */
37
- tags?: TagFilter;
38
-
39
- /**
40
- * Режим группировки методов
41
- * - 'tag' - группировка по тегам (несколько классов)
42
- * - 'all' - все методы в одном классе
43
- * - 'path' - группировка по путям API
44
- */
45
- groupBy: 'tag' | 'all' | 'path';
46
-
47
- /**
48
- * Режим генерации классов
49
- * - 'single' - один класс для всех методов
50
- * - 'multiple' - несколько классов по группировке
51
- */
52
- classMode: 'single' | 'multiple';
53
-
54
- /**
55
- * Настройки именования
56
- */
57
- naming?: NamingOptions;
58
-
59
- /**
60
- * Настройки импортов
61
- */
62
- imports?: ImportOptions;
63
-
64
- /**
65
- * Дополнительные опции генерации
66
- */
67
- options?: GeneratorOptions;
68
-
69
- /**
70
- * Настройки axios
71
- */
72
- axios?: AxiosConfig;
73
- }
74
-
75
- /**
76
- * Настройки фильтрации по тегам
77
- */
78
- export interface TagFilter {
79
- /**
80
- * Список тегов для включения в генерацию
81
- */
82
- include?: string[];
83
-
84
- /**
85
- * Список тегов для исключения из генерации
86
- */
87
- exclude?: string[];
88
-
89
- /**
90
- * Префикс тегов для фильтрации (например, "api_tag_")
91
- */
92
- prefix?: string;
93
- }
94
-
95
- /**
96
- * Настройки именования
97
- */
98
- export interface NamingOptions {
99
- /**
100
- * Функция для генерации имени класса из тега
101
- */
102
- className?: (tag: string) => string;
103
-
104
- /**
105
- * Функция для генерации имени интерфейса из схемы
106
- */
107
- interfaceName?: (name: string) => string;
108
-
109
- /**
110
- * Функция для генерации имени метода из operationId
111
- */
112
- methodName?: (operationId: string) => string;
113
- }
114
-
115
- /**
116
- * Настройки импортов
117
- */
118
- export interface ImportOptions {
119
- /**
120
- * Путь для импорта axios
121
- */
122
- axiosPath?: string;
123
-
124
- /**
125
- * Путь для импорта BASE_URL
126
- */
127
- baseUrlPath?: string;
128
- }
129
-
130
- /**
131
- * Опции генерации
132
- */
133
- export interface GeneratorOptions {
134
- /**
135
- * Генерировать JSDoc комментарии
136
- */
137
- generateJSDoc?: boolean;
138
-
139
- /**
140
- * Генерировать index файлы
141
- */
142
- generateIndexFiles?: boolean;
143
-
144
- /**
145
- * Очищать директорию вывода перед генерацией
146
- */
147
- cleanOutputDir?: boolean;
148
-
149
- /**
150
- * Генерировать конфигурацию axios
151
- */
152
- generateAxiosConfig?: boolean;
153
-
154
- /**
155
- * Разрешить распыление пользовательских конфигураций axios
156
- */
157
- allowAxiosConfigSpread?: boolean;
158
- }
159
-
160
- /**
161
- * Настройки axios
162
- */
163
- export interface AxiosConfig {
164
- /**
165
- * Базовый URL для всех запросов
166
- */
167
- baseURL?: string;
168
-
169
- /**
170
- * Таймаут запроса в миллисекундах
171
- */
172
- timeout?: number;
173
-
174
- /**
175
- * Заголовки по умолчанию
176
- */
177
- headers?: Record<string, string>;
178
-
179
- /**
180
- * Отправлять куки с кросс-доменными запросами
181
- */
182
- withCredentials?: boolean;
183
- }
@@ -1,22 +0,0 @@
1
- /**
2
- * TypeScript declaration files for the generator
3
- */
4
-
5
- declare module './config/loadConfig' {
6
- export function loadConfig(
7
- configPath?: string,
8
- cliOverrides?: import('./config.types').GeneratorConfig
9
- ): Promise<import('./config.types').GeneratorConfig>;
10
- }
11
-
12
- declare module './config/defaultConfig' {
13
- export const defaultConfig: Partial<import('./config.types').GeneratorConfig>;
14
- }
15
-
16
- declare module './config/validateConfig' {
17
- export function validateConfig(config: import('./config.types').GeneratorConfig): void;
18
- }
19
-
20
- declare module './generators/axiosConfigGenerator' {
21
- export function generateAxiosConfig(config: any, outputDir: string): void;
22
- }