ts-openapi-codegen 2.0.0-beta.4 → 2.0.0-beta.5
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/dist/cli/index.js +6 -4
- package/dist/cli/initOpenApiConfig/Types.d.ts +5 -0
- package/dist/cli/initOpenApiConfig/Types.d.ts.map +1 -1
- package/dist/cli/initOpenApiConfig/init.d.ts +6 -0
- package/dist/cli/initOpenApiConfig/init.d.ts.map +1 -0
- package/dist/cli/initOpenApiConfig/init.js +61 -0
- package/dist/cli/initOpenApiConfig/initConfig.d.ts +11 -0
- package/dist/cli/initOpenApiConfig/initConfig.d.ts.map +1 -0
- package/dist/cli/initOpenApiConfig/initConfig.js +102 -0
- package/dist/cli/initOpenApiConfig/initCustomRequest.d.ts +3 -0
- package/dist/cli/initOpenApiConfig/initCustomRequest.d.ts.map +1 -0
- package/dist/cli/initOpenApiConfig/initCustomRequest.js +23 -0
- package/dist/cli/initOpenApiConfig/utils/buildConfig.d.ts +21 -0
- package/dist/cli/initOpenApiConfig/utils/buildConfig.d.ts.map +1 -0
- package/dist/cli/initOpenApiConfig/utils/buildConfig.js +107 -0
- package/dist/cli/initOpenApiConfig/utils/findSpecFiles.d.ts +8 -0
- package/dist/cli/initOpenApiConfig/utils/findSpecFiles.d.ts.map +1 -0
- package/dist/cli/initOpenApiConfig/utils/findSpecFiles.js +40 -0
- package/dist/cli/initOpenApiConfig/utils/registerHandlebarTemplates.d.ts +3 -0
- package/dist/cli/initOpenApiConfig/utils/registerHandlebarTemplates.d.ts.map +1 -0
- package/dist/cli/initOpenApiConfig/utils/registerHandlebarTemplates.js +53 -0
- package/dist/cli/initOpenApiConfig/utils/validateSpecFile.d.ts +7 -0
- package/dist/cli/initOpenApiConfig/utils/validateSpecFile.d.ts.map +1 -0
- package/dist/cli/initOpenApiConfig/utils/validateSpecFile.js +23 -0
- package/dist/cli/initOpenApiConfig/utils/validateSpecFiles.d.ts +11 -0
- package/dist/cli/initOpenApiConfig/utils/validateSpecFiles.d.ts.map +1 -0
- package/dist/cli/initOpenApiConfig/utils/validateSpecFiles.js +24 -0
- package/dist/cli/initOpenApiConfig/utils/writeConfigFile.d.ts +11 -0
- package/dist/cli/initOpenApiConfig/utils/writeConfigFile.d.ts.map +1 -0
- package/dist/cli/initOpenApiConfig/utils/writeConfigFile.js +31 -0
- package/dist/cli/schemas/init.d.ts +4 -2
- package/dist/cli/schemas/init.d.ts.map +1 -1
- package/dist/cli/schemas/init.js +5 -2
- package/dist/common/Consts.d.ts +3 -0
- package/dist/common/Consts.d.ts.map +1 -1
- package/dist/common/Consts.js +4 -1
- package/dist/core/utils/__tests__/resolveRefToImportPath.test.js +9 -0
- package/dist/core/utils/resolveRefToImportPath.d.ts.map +1 -1
- package/dist/core/utils/resolveRefToImportPath.js +13 -7
- package/dist/templatesCompiled/cli/customRequest.d.ts +11 -0
- package/dist/templatesCompiled/cli/customRequest.d.ts.map +1 -0
- package/dist/templatesCompiled/cli/customRequest.js +27 -0
- package/dist/templatesCompiled/cli/customRequestExecutor.d.ts +11 -0
- package/dist/templatesCompiled/cli/customRequestExecutor.d.ts.map +1 -0
- package/dist/templatesCompiled/cli/customRequestExecutor.js +27 -0
- package/dist/templatesCompiled/cli/openApiConfig.d.ts +2 -1
- package/dist/templatesCompiled/cli/openApiConfig.d.ts.map +1 -1
- package/dist/templatesCompiled/cli/openApiConfig.js +76 -4
- package/package.json +1 -1
- package/dist/cli/initOpenApiConfig/runInitOpenapiConfig.d.ts +0 -3
- package/dist/cli/initOpenApiConfig/runInitOpenapiConfig.d.ts.map +0 -1
- package/dist/cli/initOpenApiConfig/runInitOpenapiConfig.js +0 -70
package/dist/cli/index.js
CHANGED
|
@@ -15,8 +15,7 @@ const ValidationLibrary_enum_1 = require("../core/types/enums/ValidationLibrary.
|
|
|
15
15
|
const checkConfig_1 = require("./checkAndUpdateConfig/checkConfig");
|
|
16
16
|
const updateConfig_1 = require("./checkAndUpdateConfig/updateConfig");
|
|
17
17
|
const generateOpenApiClient_1 = require("./generateOpenApiClient/generateOpenApiClient");
|
|
18
|
-
const
|
|
19
|
-
const runInitOpenapiConfig_1 = require("./initOpenApiConfig/runInitOpenapiConfig");
|
|
18
|
+
const init_1 = require("./initOpenApiConfig/init");
|
|
20
19
|
const previewChanges_1 = require("./previewChanges/previewChanges");
|
|
21
20
|
const utils_1 = require("./utils");
|
|
22
21
|
const packageDetails = JSON.parse(fs_1.default.readFileSync((0, pathHelpers_1.joinHelper)(__dirname, '../../package.json'), 'utf-8'));
|
|
@@ -100,12 +99,15 @@ program
|
|
|
100
99
|
.description('Generates a configuration file template for a set of single or multiple options')
|
|
101
100
|
.addHelpText('before', (0, utils_1.getCLIName)(APP_NAME))
|
|
102
101
|
.option('-ocn, --openapi-config <value>', 'The path to the configuration file, listing the options', Consts_1.DEFAULT_OPENAPI_CONFIG_FILENAME)
|
|
103
|
-
.
|
|
102
|
+
.option('-sd, --specs-dir <value>', 'Путь до директории с файлами спецификации', './openapi')
|
|
103
|
+
.option('--request <value>', 'Path to custom request file')
|
|
104
|
+
.option('--useCancelableRequest', 'Use cancelled promise as returned data type in request (default: false)')
|
|
105
|
+
.option('--useInteractiveMode', 'Использовать интерактивный режим команды. В терминале будут задаваться вопросы (default: false)')
|
|
104
106
|
.hook('preAction', async () => {
|
|
105
107
|
await updateNotifier.checkAndNotify();
|
|
106
108
|
})
|
|
107
109
|
.action(async (options) => {
|
|
108
|
-
await (0,
|
|
110
|
+
await (0, init_1.init)(options);
|
|
109
111
|
});
|
|
110
112
|
/**
|
|
111
113
|
* preview-changes - Команда для предпросмотра изменений перед генерацией
|
|
@@ -3,4 +3,9 @@ export type TInitOpenApiConfigParams = {
|
|
|
3
3
|
type: EOptionType;
|
|
4
4
|
openapiConfig?: string;
|
|
5
5
|
};
|
|
6
|
+
export type CLITemplates = {
|
|
7
|
+
config: Handlebars.TemplateDelegate;
|
|
8
|
+
request: Handlebars.TemplateDelegate;
|
|
9
|
+
requestExecutor: Handlebars.TemplateDelegate;
|
|
10
|
+
};
|
|
6
11
|
//# sourceMappingURL=Types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Types.d.ts","sourceRoot":"","sources":["../../../src/cli/initOpenApiConfig/Types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAEtC,MAAM,MAAM,wBAAwB,GAAG;IACnC,IAAI,EAAE,WAAW,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAA"}
|
|
1
|
+
{"version":3,"file":"Types.d.ts","sourceRoot":"","sources":["../../../src/cli/initOpenApiConfig/Types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAEtC,MAAM,MAAM,wBAAwB,GAAG;IACnC,IAAI,EAAE,WAAW,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAA;AAED,MAAM,MAAM,YAAY,GAAG;IACvB,MAAM,EAAE,UAAU,CAAC,gBAAgB,CAAC;IACpC,OAAO,EAAE,UAAU,CAAC,gBAAgB,CAAC;IACrC,eAAe,EAAE,UAAU,CAAC,gBAAgB,CAAC;CAChD,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../src/cli/initOpenApiConfig/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAUzC;;GAEG;AACH,wBAAsB,IAAI,CAAC,OAAO,EAAE,YAAY,iBAmD/C"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.init = init;
|
|
4
|
+
const Consts_1 = require("../../common/Consts");
|
|
5
|
+
const confirmDialog_1 = require("../interactive/confirmDialog");
|
|
6
|
+
const schemas_1 = require("../schemas");
|
|
7
|
+
const validation_1 = require("../validation");
|
|
8
|
+
const initConfig_1 = require("./initConfig");
|
|
9
|
+
const initCustomRequest_1 = require("./initCustomRequest");
|
|
10
|
+
const registerHandlebarTemplates_1 = require("./utils/registerHandlebarTemplates");
|
|
11
|
+
/**
|
|
12
|
+
* Фнукция изначальной настройки файлов конфигурации для последующего запуска генератора
|
|
13
|
+
*/
|
|
14
|
+
async function init(options) {
|
|
15
|
+
let validatedOptions;
|
|
16
|
+
try {
|
|
17
|
+
// Валидация опций через Zod
|
|
18
|
+
const validationResult = (0, validation_1.validateCLIOptions)(schemas_1.initOptionsSchema, options);
|
|
19
|
+
if (!validationResult.success) {
|
|
20
|
+
Consts_1.APP_LOGGER.error(validationResult.error);
|
|
21
|
+
process.exit(1);
|
|
22
|
+
}
|
|
23
|
+
validatedOptions = validationResult.data;
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
Consts_1.APP_LOGGER.error(error.message);
|
|
27
|
+
process.exit(1);
|
|
28
|
+
}
|
|
29
|
+
const templates = (0, registerHandlebarTemplates_1.registerHandlebarTemplates)();
|
|
30
|
+
if (validatedOptions.useInteractiveMode) {
|
|
31
|
+
const shouldInitConfig = await (0, confirmDialog_1.confirmDialog)({
|
|
32
|
+
message: 'Желаете сформировать конфигурационный файл для быстрого запуска генератора?',
|
|
33
|
+
initial: false,
|
|
34
|
+
});
|
|
35
|
+
if (shouldInitConfig) {
|
|
36
|
+
// TODO: генерация по шаблону!
|
|
37
|
+
await (0, initConfig_1.initConfig)({
|
|
38
|
+
openapiConfig: validatedOptions.openapiConfig,
|
|
39
|
+
request: validatedOptions.request,
|
|
40
|
+
specsDir: validatedOptions.specsDir,
|
|
41
|
+
templates,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
const shouldInitCustomRequest = await (0, confirmDialog_1.confirmDialog)({
|
|
45
|
+
message: 'Желаете сформировать файл с пользовательским вариантом обработки запросов?',
|
|
46
|
+
initial: false,
|
|
47
|
+
});
|
|
48
|
+
if (shouldInitCustomRequest) {
|
|
49
|
+
await (0, initCustomRequest_1.initCustomRequest)(templates, validatedOptions?.useCancelableRequest);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
await (0, initConfig_1.initConfig)({
|
|
54
|
+
openapiConfig: validatedOptions.openapiConfig,
|
|
55
|
+
request: validatedOptions.request,
|
|
56
|
+
specsDir: validatedOptions.specsDir,
|
|
57
|
+
templates,
|
|
58
|
+
});
|
|
59
|
+
await (0, initCustomRequest_1.initCustomRequest)(templates, validatedOptions?.useCancelableRequest);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { InitOptions } from '../schemas';
|
|
2
|
+
import { CLITemplates } from './Types';
|
|
3
|
+
type InitConfigParams = Pick<InitOptions, 'openapiConfig' | 'specsDir' | 'request'> & {
|
|
4
|
+
templates: CLITemplates;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Инициализирует файл конфигурации OpenAPI
|
|
8
|
+
*/
|
|
9
|
+
export declare function initConfig(params: InitConfigParams): Promise<void>;
|
|
10
|
+
export {};
|
|
11
|
+
//# sourceMappingURL=initConfig.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"initConfig.d.ts","sourceRoot":"","sources":["../../../src/cli/initOpenApiConfig/initConfig.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAMvC,KAAK,gBAAgB,GAAG,IAAI,CAAC,WAAW,EAAE,eAAe,GAAG,UAAU,GAAG,SAAS,CAAC,GAAG;IAClF,SAAS,EAAE,YAAY,CAAC;CAC3B,CAAA;AAED;;GAEG;AACH,wBAAsB,UAAU,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAoGxE"}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.initConfig = initConfig;
|
|
4
|
+
const Consts_1 = require("../../common/Consts");
|
|
5
|
+
const fileSystemHelpers_1 = require("../../common/utils/fileSystemHelpers");
|
|
6
|
+
const pathHelpers_1 = require("../../common/utils/pathHelpers");
|
|
7
|
+
const confirmDialog_1 = require("../interactive/confirmDialog");
|
|
8
|
+
const constants_1 = require("../interactive/constants");
|
|
9
|
+
const selectDialog_1 = require("../interactive/selectDialog");
|
|
10
|
+
const types_1 = require("../interactive/types");
|
|
11
|
+
const buildConfig_1 = require("./utils/buildConfig");
|
|
12
|
+
const findSpecFiles_1 = require("./utils/findSpecFiles");
|
|
13
|
+
const validateSpecFiles_1 = require("./utils/validateSpecFiles");
|
|
14
|
+
const writeConfigFile_1 = require("./utils/writeConfigFile");
|
|
15
|
+
/**
|
|
16
|
+
* Инициализирует файл конфигурации OpenAPI
|
|
17
|
+
*/
|
|
18
|
+
async function initConfig(params) {
|
|
19
|
+
const configPath = (0, pathHelpers_1.resolveHelper)(process.cwd(), params.openapiConfig);
|
|
20
|
+
const configExists = await fileSystemHelpers_1.fileSystemHelpers.exists(configPath);
|
|
21
|
+
// Шаг 3: Проверка существования файла конфигурации
|
|
22
|
+
if (configExists) {
|
|
23
|
+
const shouldRegenerate = await (0, confirmDialog_1.confirmDialog)({
|
|
24
|
+
message: 'Configuration file already exists. Do you want to regenerate it?',
|
|
25
|
+
initial: false,
|
|
26
|
+
});
|
|
27
|
+
if (!shouldRegenerate) {
|
|
28
|
+
Consts_1.APP_LOGGER.info('Configuration file left unchanged.');
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const currentSpecsDir = params.specsDir;
|
|
33
|
+
// Шаг 4: Формирование файла конфигурации
|
|
34
|
+
// Поиск файлов спецификаций
|
|
35
|
+
let specFiles = [];
|
|
36
|
+
try {
|
|
37
|
+
specFiles = await (0, findSpecFiles_1.findSpecFiles)(currentSpecsDir);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
Consts_1.APP_LOGGER.warn(`Error finding spec files: ${error instanceof Error ? error.message : String(error)}`);
|
|
41
|
+
}
|
|
42
|
+
if (specFiles.length === 0) {
|
|
43
|
+
Consts_1.APP_LOGGER.warn(`No spec files found in directory: ${currentSpecsDir}`);
|
|
44
|
+
}
|
|
45
|
+
// Валидация файлов
|
|
46
|
+
const validatedSpecs = await (0, validateSpecFiles_1.validateSpecFiles)(specFiles);
|
|
47
|
+
let config;
|
|
48
|
+
let useMultiOption = false;
|
|
49
|
+
let customRequest;
|
|
50
|
+
let perSpecRequest = false;
|
|
51
|
+
if (validatedSpecs.length > 0) {
|
|
52
|
+
// Если найдены валидные спецификации, спрашиваем о типе конфигурации
|
|
53
|
+
useMultiOption = validatedSpecs.length > 1;
|
|
54
|
+
// Спрашиваем про пользовательскую реализацию request
|
|
55
|
+
const hasCustomRequest = await (0, confirmDialog_1.confirmDialog)({
|
|
56
|
+
message: 'Do you want to use a custom request implementation?',
|
|
57
|
+
initial: false,
|
|
58
|
+
});
|
|
59
|
+
if (hasCustomRequest) {
|
|
60
|
+
if (useMultiOption) {
|
|
61
|
+
perSpecRequest = await (0, confirmDialog_1.confirmDialog)({
|
|
62
|
+
message: 'Will each specification have its own request?',
|
|
63
|
+
initial: false,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
customRequest = params.request;
|
|
67
|
+
}
|
|
68
|
+
config = await (0, buildConfig_1.buildConfig)(validatedSpecs, useMultiOption, customRequest, perSpecRequest);
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
// Если валидных спецификаций нет, предлагаем создать пример
|
|
72
|
+
Consts_1.APP_LOGGER.warn('No valid OpenAPI specification files found.');
|
|
73
|
+
const action = await (0, selectDialog_1.selectDialog)({
|
|
74
|
+
message: 'What would you like to do?',
|
|
75
|
+
choices: constants_1.OPEN_API_CONFIG_SELECT_OPTIONS,
|
|
76
|
+
initial: 0,
|
|
77
|
+
});
|
|
78
|
+
if (action === types_1.EConfigType.NONE) {
|
|
79
|
+
Consts_1.APP_LOGGER.info('Configuration file generation cancelled.');
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
useMultiOption = action === types_1.EConfigType.MULTI;
|
|
83
|
+
// Спрашиваем про пользовательскую реализацию request
|
|
84
|
+
const hasCustomRequest = await (0, confirmDialog_1.confirmDialog)({
|
|
85
|
+
message: 'Do you want to use a custom request implementation?',
|
|
86
|
+
initial: false,
|
|
87
|
+
});
|
|
88
|
+
if (hasCustomRequest) {
|
|
89
|
+
if (useMultiOption) {
|
|
90
|
+
perSpecRequest = await (0, confirmDialog_1.confirmDialog)({
|
|
91
|
+
message: 'Will each specification have its own request?',
|
|
92
|
+
initial: false,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
customRequest = './custom-request.ts';
|
|
96
|
+
}
|
|
97
|
+
// Создаем пример конфигурации
|
|
98
|
+
config = (0, buildConfig_1.buildExampleConfig)(useMultiOption, customRequest, perSpecRequest);
|
|
99
|
+
}
|
|
100
|
+
// Записываем конфигурацию на диск
|
|
101
|
+
await (0, writeConfigFile_1.writeConfigFile)(params.openapiConfig, config, params.templates);
|
|
102
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"initCustomRequest.d.ts","sourceRoot":"","sources":["../../../src/cli/initOpenApiConfig/initCustomRequest.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEvC,wBAAsB,iBAAiB,CAAC,SAAS,EAAE,YAAY,EAAE,oBAAoB,CAAC,EAAE,OAAO,iBAkB9F"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.initCustomRequest = initCustomRequest;
|
|
4
|
+
const fileSystemHelpers_1 = require("../../common/utils/fileSystemHelpers");
|
|
5
|
+
const format_1 = require("../../common/utils/format");
|
|
6
|
+
const pathHelpers_1 = require("../../common/utils/pathHelpers");
|
|
7
|
+
const confirmDialog_1 = require("../interactive/confirmDialog");
|
|
8
|
+
async function initCustomRequest(templates, useCancelableRequest) {
|
|
9
|
+
// TODO: Подумать над правильной постановкой вопроса!
|
|
10
|
+
const shouldRequestExecutor = await (0, confirmDialog_1.confirmDialog)({
|
|
11
|
+
message: 'Желаете сформировать пользовательский обработчик request в новом формате?',
|
|
12
|
+
initial: false,
|
|
13
|
+
});
|
|
14
|
+
const artifacts = {
|
|
15
|
+
useCancelableRequest,
|
|
16
|
+
};
|
|
17
|
+
const customRequestPath = './src/custom/request.ts';
|
|
18
|
+
const file = (0, pathHelpers_1.resolveHelper)(process.cwd(), customRequestPath);
|
|
19
|
+
const templateResult = shouldRequestExecutor ? templates.requestExecutor(artifacts) : templates.request(artifacts);
|
|
20
|
+
const formattedValue = await (0, format_1.format)(templateResult);
|
|
21
|
+
await fileSystemHelpers_1.fileSystemHelpers.writeFile(file, formattedValue);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { TRawOptions } from '../../../common/TRawOptions';
|
|
2
|
+
import { ValidatedSpec } from './validateSpecFiles';
|
|
3
|
+
/**
|
|
4
|
+
* Формирует конфигурацию на основе валидированных спецификаций
|
|
5
|
+
* @param validatedSpecs - Массив валидированных спецификаций
|
|
6
|
+
* @param useMultiOption - Использовать множественный формат (items)
|
|
7
|
+
* @param customRequest - Путь к кастомной реализации request (опционально)
|
|
8
|
+
* @param perSpecRequest - Использовать отдельный request для каждой спецификации (только для MULTI)
|
|
9
|
+
* @returns Объект конфигурации
|
|
10
|
+
* @throws {Error} Если нет валидированных спецификаций для плоского формата
|
|
11
|
+
*/
|
|
12
|
+
export declare function buildConfig(validatedSpecs: ValidatedSpec[], useMultiOption: boolean, customRequest?: string, perSpecRequest?: boolean): Promise<TRawOptions>;
|
|
13
|
+
/**
|
|
14
|
+
* Создает пример конфигурации, когда нет валидированных спецификаций
|
|
15
|
+
* @param useMultiOption - Использовать множественный формат (items)
|
|
16
|
+
* @param customRequest - Путь к кастомной реализации request (опционально)
|
|
17
|
+
* @param perSpecRequest - Использовать отдельный request для каждой спецификации (только для MULTI)
|
|
18
|
+
* @returns Объект конфигурации-примера
|
|
19
|
+
*/
|
|
20
|
+
export declare function buildExampleConfig(useMultiOption: boolean, customRequest?: string, perSpecRequest?: boolean): TRawOptions;
|
|
21
|
+
//# sourceMappingURL=buildConfig.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buildConfig.d.ts","sourceRoot":"","sources":["../../../../src/cli/initOpenApiConfig/utils/buildConfig.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD;;;;;;;;GAQG;AACH,wBAAsB,WAAW,CAAC,cAAc,EAAE,aAAa,EAAE,EAAE,cAAc,EAAE,OAAO,EAAE,aAAa,CAAC,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,CAAC,CA8ClK;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,cAAc,EAAE,OAAO,EAAE,aAAa,CAAC,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,OAAO,GAAG,WAAW,CAuCzH"}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildConfig = buildConfig;
|
|
4
|
+
exports.buildExampleConfig = buildExampleConfig;
|
|
5
|
+
const Consts_1 = require("../../../common/Consts");
|
|
6
|
+
/**
|
|
7
|
+
* Формирует конфигурацию на основе валидированных спецификаций
|
|
8
|
+
* @param validatedSpecs - Массив валидированных спецификаций
|
|
9
|
+
* @param useMultiOption - Использовать множественный формат (items)
|
|
10
|
+
* @param customRequest - Путь к кастомной реализации request (опционально)
|
|
11
|
+
* @param perSpecRequest - Использовать отдельный request для каждой спецификации (только для MULTI)
|
|
12
|
+
* @returns Объект конфигурации
|
|
13
|
+
* @throws {Error} Если нет валидированных спецификаций для плоского формата
|
|
14
|
+
*/
|
|
15
|
+
async function buildConfig(validatedSpecs, useMultiOption, customRequest, perSpecRequest) {
|
|
16
|
+
if (useMultiOption) {
|
|
17
|
+
const items = validatedSpecs.map(spec => ({
|
|
18
|
+
input: spec.relativePath,
|
|
19
|
+
output: Consts_1.DEFAULT_OUTPUT_API_DIR,
|
|
20
|
+
...(perSpecRequest && customRequest ? { request: customRequest } : {}),
|
|
21
|
+
}));
|
|
22
|
+
return {
|
|
23
|
+
items,
|
|
24
|
+
httpClient: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.httpClient,
|
|
25
|
+
sortByRequired: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.sortByRequired,
|
|
26
|
+
enumPrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.enumPrefix,
|
|
27
|
+
excludeCoreServiceFiles: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.excludeCoreServiceFiles,
|
|
28
|
+
interfacePrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.interfacePrefix,
|
|
29
|
+
typePrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.typePrefix,
|
|
30
|
+
useCancelableRequest: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useCancelableRequest,
|
|
31
|
+
useOptions: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useOptions,
|
|
32
|
+
useSeparatedIndexes: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useSeparatedIndexes,
|
|
33
|
+
useUnionTypes: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useUnionTypes,
|
|
34
|
+
...(!perSpecRequest && customRequest ? { request: customRequest } : {}),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
if (validatedSpecs.length === 0) {
|
|
39
|
+
throw new Error('No validated spec files found');
|
|
40
|
+
}
|
|
41
|
+
// Для плоского варианта используем первую спецификацию
|
|
42
|
+
const firstSpec = validatedSpecs[0];
|
|
43
|
+
return {
|
|
44
|
+
input: firstSpec.relativePath,
|
|
45
|
+
output: Consts_1.DEFAULT_OUTPUT_API_DIR,
|
|
46
|
+
httpClient: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.httpClient,
|
|
47
|
+
sortByRequired: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.sortByRequired,
|
|
48
|
+
enumPrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.enumPrefix,
|
|
49
|
+
excludeCoreServiceFiles: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.excludeCoreServiceFiles,
|
|
50
|
+
interfacePrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.interfacePrefix,
|
|
51
|
+
typePrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.typePrefix,
|
|
52
|
+
useCancelableRequest: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useCancelableRequest,
|
|
53
|
+
useOptions: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useOptions,
|
|
54
|
+
useSeparatedIndexes: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useSeparatedIndexes,
|
|
55
|
+
useUnionTypes: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useUnionTypes,
|
|
56
|
+
...(customRequest ? { request: customRequest } : {}),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Создает пример конфигурации, когда нет валидированных спецификаций
|
|
62
|
+
* @param useMultiOption - Использовать множественный формат (items)
|
|
63
|
+
* @param customRequest - Путь к кастомной реализации request (опционально)
|
|
64
|
+
* @param perSpecRequest - Использовать отдельный request для каждой спецификации (только для MULTI)
|
|
65
|
+
* @returns Объект конфигурации-примера
|
|
66
|
+
*/
|
|
67
|
+
function buildExampleConfig(useMultiOption, customRequest, perSpecRequest) {
|
|
68
|
+
if (useMultiOption) {
|
|
69
|
+
return {
|
|
70
|
+
items: [
|
|
71
|
+
{
|
|
72
|
+
input: './openapi/spec.yml',
|
|
73
|
+
output: Consts_1.DEFAULT_OUTPUT_API_DIR,
|
|
74
|
+
...(perSpecRequest && customRequest ? { request: customRequest } : {}),
|
|
75
|
+
},
|
|
76
|
+
],
|
|
77
|
+
httpClient: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.httpClient,
|
|
78
|
+
sortByRequired: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.sortByRequired,
|
|
79
|
+
enumPrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.enumPrefix,
|
|
80
|
+
excludeCoreServiceFiles: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.excludeCoreServiceFiles,
|
|
81
|
+
interfacePrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.interfacePrefix,
|
|
82
|
+
typePrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.typePrefix,
|
|
83
|
+
useCancelableRequest: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useCancelableRequest,
|
|
84
|
+
useOptions: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useOptions,
|
|
85
|
+
useSeparatedIndexes: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useSeparatedIndexes,
|
|
86
|
+
useUnionTypes: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useUnionTypes,
|
|
87
|
+
...(!perSpecRequest && customRequest ? { request: customRequest } : {}),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
return {
|
|
92
|
+
input: './openapi/spec.yml',
|
|
93
|
+
output: Consts_1.DEFAULT_OUTPUT_API_DIR,
|
|
94
|
+
httpClient: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.httpClient,
|
|
95
|
+
sortByRequired: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.sortByRequired,
|
|
96
|
+
enumPrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.enumPrefix,
|
|
97
|
+
excludeCoreServiceFiles: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.excludeCoreServiceFiles,
|
|
98
|
+
interfacePrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.interfacePrefix,
|
|
99
|
+
typePrefix: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.typePrefix,
|
|
100
|
+
useCancelableRequest: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useCancelableRequest,
|
|
101
|
+
useOptions: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useOptions,
|
|
102
|
+
useSeparatedIndexes: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useSeparatedIndexes,
|
|
103
|
+
useUnionTypes: Consts_1.COMMON_DEFAULT_OPTIONS_VALUES.useUnionTypes,
|
|
104
|
+
...(customRequest ? { request: customRequest } : {}),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Находит все файлы спецификаций в директории
|
|
3
|
+
* @param specsDir - Путь к директории со спецификациями
|
|
4
|
+
* @returns Массив путей к файлам спецификаций
|
|
5
|
+
* @throws {Error} Если директория не существует или не является директорией
|
|
6
|
+
*/
|
|
7
|
+
export declare function findSpecFiles(specsDir: string): Promise<string[]>;
|
|
8
|
+
//# sourceMappingURL=findSpecFiles.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"findSpecFiles.d.ts","sourceRoot":"","sources":["../../../../src/cli/initOpenApiConfig/utils/findSpecFiles.ts"],"names":[],"mappings":"AAOA;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CA6BvE"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.findSpecFiles = findSpecFiles;
|
|
7
|
+
const path_1 = __importDefault(require("path"));
|
|
8
|
+
const fileSystemHelpers_1 = require("../../../common/utils/fileSystemHelpers");
|
|
9
|
+
const pathHelpers_1 = require("../../../common/utils/pathHelpers");
|
|
10
|
+
const SPEC_EXTENSIONS = ['.json', '.yaml', '.yml'];
|
|
11
|
+
/**
|
|
12
|
+
* Находит все файлы спецификаций в директории
|
|
13
|
+
* @param specsDir - Путь к директории со спецификациями
|
|
14
|
+
* @returns Массив путей к файлам спецификаций
|
|
15
|
+
* @throws {Error} Если директория не существует или не является директорией
|
|
16
|
+
*/
|
|
17
|
+
async function findSpecFiles(specsDir) {
|
|
18
|
+
const resolvedDir = (0, pathHelpers_1.resolveHelper)(process.cwd(), specsDir);
|
|
19
|
+
const dirExists = await fileSystemHelpers_1.fileSystemHelpers.exists(resolvedDir);
|
|
20
|
+
if (!dirExists) {
|
|
21
|
+
throw new Error(`Directory does not exist: ${specsDir}`);
|
|
22
|
+
}
|
|
23
|
+
const isDir = fileSystemHelpers_1.fileSystemHelpers.isDirectory(resolvedDir);
|
|
24
|
+
if (!isDir) {
|
|
25
|
+
throw new Error(`Path is not a directory: ${specsDir}`);
|
|
26
|
+
}
|
|
27
|
+
const files = await fileSystemHelpers_1.fileSystemHelpers.readdir(resolvedDir);
|
|
28
|
+
const specFiles = [];
|
|
29
|
+
for (const file of files) {
|
|
30
|
+
const filePath = (0, pathHelpers_1.joinHelper)(resolvedDir, file);
|
|
31
|
+
const isFile = fileSystemHelpers_1.fileSystemHelpers.isPathToFile(filePath);
|
|
32
|
+
if (isFile) {
|
|
33
|
+
const ext = path_1.default.extname(file).toLowerCase();
|
|
34
|
+
if (SPEC_EXTENSIONS.includes(ext)) {
|
|
35
|
+
specFiles.push(filePath);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return specFiles;
|
|
40
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registerHandlebarTemplates.d.ts","sourceRoot":"","sources":["../../../../src/cli/initOpenApiConfig/utils/registerHandlebarTemplates.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAGxC,wBAAgB,0BAA0B,IAAI,YAAY,CAUzD"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.registerHandlebarTemplates = registerHandlebarTemplates;
|
|
40
|
+
const Handlebars = __importStar(require("handlebars/runtime"));
|
|
41
|
+
const customRequest_1 = __importDefault(require("../../../templatesCompiled/cli/customRequest"));
|
|
42
|
+
const customRequestExecutor_1 = __importDefault(require("../../../templatesCompiled/cli/customRequestExecutor"));
|
|
43
|
+
const openApiConfig_1 = __importDefault(require("../../../templatesCompiled/cli/openApiConfig"));
|
|
44
|
+
const header_1 = __importDefault(require("../../../templatesCompiled/client/partials/header"));
|
|
45
|
+
function registerHandlebarTemplates() {
|
|
46
|
+
const templates = {
|
|
47
|
+
config: Handlebars.template(openApiConfig_1.default),
|
|
48
|
+
request: Handlebars.template(customRequest_1.default),
|
|
49
|
+
requestExecutor: Handlebars.template(customRequestExecutor_1.default),
|
|
50
|
+
};
|
|
51
|
+
Handlebars.registerPartial('header', Handlebars.template(header_1.default));
|
|
52
|
+
return templates;
|
|
53
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Валидирует файл спецификации через SwaggerParser
|
|
3
|
+
* @param filePath - Путь к файлу спецификации
|
|
4
|
+
* @returns true, если файл валиден, false в противном случае
|
|
5
|
+
*/
|
|
6
|
+
export declare function validateSpecFile(filePath: string): Promise<boolean>;
|
|
7
|
+
//# sourceMappingURL=validateSpecFile.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validateSpecFile.d.ts","sourceRoot":"","sources":["../../../../src/cli/initOpenApiConfig/utils/validateSpecFile.ts"],"names":[],"mappings":"AAIA;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAQzE"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.validateSpecFile = validateSpecFile;
|
|
7
|
+
const swagger_parser_1 = __importDefault(require("@apidevtools/swagger-parser"));
|
|
8
|
+
const Consts_1 = require("../../../common/Consts");
|
|
9
|
+
/**
|
|
10
|
+
* Валидирует файл спецификации через SwaggerParser
|
|
11
|
+
* @param filePath - Путь к файлу спецификации
|
|
12
|
+
* @returns true, если файл валиден, false в противном случае
|
|
13
|
+
*/
|
|
14
|
+
async function validateSpecFile(filePath) {
|
|
15
|
+
try {
|
|
16
|
+
await swagger_parser_1.default.validate(filePath);
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
Consts_1.APP_LOGGER.warn(`Skipping invalid spec file: ${filePath}`);
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface ValidatedSpec {
|
|
2
|
+
path: string;
|
|
3
|
+
relativePath: string;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Валидирует все файлы спецификаций
|
|
7
|
+
* @param specFiles - Массив путей к файлам спецификаций
|
|
8
|
+
* @returns Массив валидированных спецификаций с относительными путями
|
|
9
|
+
*/
|
|
10
|
+
export declare function validateSpecFiles(specFiles: string[]): Promise<ValidatedSpec[]>;
|
|
11
|
+
//# sourceMappingURL=validateSpecFiles.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validateSpecFiles.d.ts","sourceRoot":"","sources":["../../../../src/cli/initOpenApiConfig/utils/validateSpecFiles.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,aAAa;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,CAAC;CACxB;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAerF"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateSpecFiles = validateSpecFiles;
|
|
4
|
+
const pathHelpers_1 = require("../../../common/utils/pathHelpers");
|
|
5
|
+
const validateSpecFile_1 = require("./validateSpecFile");
|
|
6
|
+
/**
|
|
7
|
+
* Валидирует все файлы спецификаций
|
|
8
|
+
* @param specFiles - Массив путей к файлам спецификаций
|
|
9
|
+
* @returns Массив валидированных спецификаций с относительными путями
|
|
10
|
+
*/
|
|
11
|
+
async function validateSpecFiles(specFiles) {
|
|
12
|
+
const validatedSpecs = [];
|
|
13
|
+
for (const specFile of specFiles) {
|
|
14
|
+
const isValid = await (0, validateSpecFile_1.validateSpecFile)(specFile);
|
|
15
|
+
if (isValid) {
|
|
16
|
+
const relativePath = (0, pathHelpers_1.relativeHelper)(process.cwd(), specFile);
|
|
17
|
+
validatedSpecs.push({
|
|
18
|
+
path: specFile,
|
|
19
|
+
relativePath,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return validatedSpecs;
|
|
24
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { TRawOptions } from '../../../common/TRawOptions';
|
|
2
|
+
import { CLITemplates } from '../Types';
|
|
3
|
+
/**
|
|
4
|
+
* Записывает конфигурацию в файл
|
|
5
|
+
* @param configPath - Путь к файлу конфигурации
|
|
6
|
+
* @param config - Объект конфигурации для записи
|
|
7
|
+
* @param templates
|
|
8
|
+
* @throws {Error} Если не удалось записать файл
|
|
9
|
+
*/
|
|
10
|
+
export declare function writeConfigFile(configPath: string, config: TRawOptions, templates: CLITemplates): Promise<void>;
|
|
11
|
+
//# sourceMappingURL=writeConfigFile.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"writeConfigFile.d.ts","sourceRoot":"","sources":["../../../../src/cli/initOpenApiConfig/utils/writeConfigFile.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAI1D,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC;;;;;;GAMG;AACH,wBAAsB,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAerH"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.writeConfigFile = writeConfigFile;
|
|
7
|
+
const path_1 = __importDefault(require("path"));
|
|
8
|
+
const Consts_1 = require("../../../common/Consts");
|
|
9
|
+
const fileSystemHelpers_1 = require("../../../common/utils/fileSystemHelpers");
|
|
10
|
+
const format_1 = require("../../../common/utils/format");
|
|
11
|
+
const pathHelpers_1 = require("../../../common/utils/pathHelpers");
|
|
12
|
+
/**
|
|
13
|
+
* Записывает конфигурацию в файл
|
|
14
|
+
* @param configPath - Путь к файлу конфигурации
|
|
15
|
+
* @param config - Объект конфигурации для записи
|
|
16
|
+
* @param templates
|
|
17
|
+
* @throws {Error} Если не удалось записать файл
|
|
18
|
+
*/
|
|
19
|
+
async function writeConfigFile(configPath, config, templates) {
|
|
20
|
+
const resolvedPath = (0, pathHelpers_1.resolveHelper)(process.cwd(), configPath);
|
|
21
|
+
const configDir = path_1.default.dirname(resolvedPath);
|
|
22
|
+
// Создаем директорию, если она не существует
|
|
23
|
+
const dirExists = await fileSystemHelpers_1.fileSystemHelpers.exists(configDir);
|
|
24
|
+
if (!dirExists) {
|
|
25
|
+
await fileSystemHelpers_1.fileSystemHelpers.mkdir(configDir);
|
|
26
|
+
}
|
|
27
|
+
const templateResult = templates.config(config);
|
|
28
|
+
const formattedValue = await (0, format_1.format)(templateResult, 'json');
|
|
29
|
+
await fileSystemHelpers_1.fileSystemHelpers.writeFile(resolvedPath, formattedValue);
|
|
30
|
+
Consts_1.APP_LOGGER.info(`Configuration file created: ${resolvedPath}`);
|
|
31
|
+
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { EOptionType } from '../initOpenApiConfig/Enums';
|
|
3
2
|
export declare const initOptionsSchema: z.ZodObject<{
|
|
4
3
|
openapiConfig: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
|
5
|
-
|
|
4
|
+
specsDir: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
|
5
|
+
request: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
|
6
|
+
useCancelableRequest: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
7
|
+
useInteractiveMode: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
6
8
|
}, z.core.$strip>;
|
|
7
9
|
export type InitOptions = z.infer<typeof initOptionsSchema>;
|
|
8
10
|
//# sourceMappingURL=init.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../src/cli/schemas/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../src/cli/schemas/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAKxB,eAAO,MAAM,iBAAiB;;;;;;iBAK5B,CAAC;AAEH,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC"}
|
package/dist/cli/schemas/init.js
CHANGED
|
@@ -2,8 +2,11 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.initOptionsSchema = void 0;
|
|
4
4
|
const zod_1 = require("zod");
|
|
5
|
-
const
|
|
5
|
+
const Consts_1 = require("../../common/Consts");
|
|
6
6
|
const base_1 = require("./base");
|
|
7
7
|
exports.initOptionsSchema = base_1.baseCLIOptionsSchema.extend({
|
|
8
|
-
|
|
8
|
+
specsDir: zod_1.z.string().min(1).optional().default(Consts_1.DEFAULT_SPECS_DIR),
|
|
9
|
+
request: zod_1.z.string().min(1).optional().default(Consts_1.DEFAULT_CUSTOM_REQUEST_PATH),
|
|
10
|
+
useCancelableRequest: zod_1.z.boolean().optional().default(false),
|
|
11
|
+
useInteractiveMode: zod_1.z.boolean().optional().default(false),
|
|
9
12
|
});
|
package/dist/common/Consts.d.ts
CHANGED
|
@@ -3,4 +3,7 @@ import { TStrictFlatOptions } from './TRawOptions';
|
|
|
3
3
|
export declare const DEFAULT_OPENAPI_CONFIG_FILENAME = "openapi.config.json";
|
|
4
4
|
export declare const COMMON_DEFAULT_OPTIONS_VALUES: TStrictFlatOptions;
|
|
5
5
|
export declare const APP_LOGGER: Logger;
|
|
6
|
+
export declare const DEFAULT_SPECS_DIR = "openapi/";
|
|
7
|
+
export declare const DEFAULT_CUSTOM_REQUEST_PATH = "./src/custom/request.ts";
|
|
8
|
+
export declare const DEFAULT_OUTPUT_API_DIR = "./generated";
|
|
6
9
|
//# sourceMappingURL=Consts.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Consts.d.ts","sourceRoot":"","sources":["../../src/common/Consts.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEnD,eAAO,MAAM,+BAA+B,wBAAwB,CAAC;AAErE,eAAO,MAAM,6BAA6B,EAAE,kBAqB3C,CAAC;AAEF,eAAO,MAAM,UAAU,QAIrB,CAAC"}
|
|
1
|
+
{"version":3,"file":"Consts.d.ts","sourceRoot":"","sources":["../../src/common/Consts.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEnD,eAAO,MAAM,+BAA+B,wBAAwB,CAAC;AAErE,eAAO,MAAM,6BAA6B,EAAE,kBAqB3C,CAAC;AAEF,eAAO,MAAM,UAAU,QAIrB,CAAC;AAEH,eAAO,MAAM,iBAAiB,aAAa,CAAC;AAE5C,eAAO,MAAM,2BAA2B,4BAA4B,CAAA;AAEpE,eAAO,MAAM,sBAAsB,gBAAgB,CAAC"}
|
package/dist/common/Consts.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.APP_LOGGER = exports.COMMON_DEFAULT_OPTIONS_VALUES = exports.DEFAULT_OPENAPI_CONFIG_FILENAME = void 0;
|
|
3
|
+
exports.DEFAULT_OUTPUT_API_DIR = exports.DEFAULT_CUSTOM_REQUEST_PATH = exports.DEFAULT_SPECS_DIR = exports.APP_LOGGER = exports.COMMON_DEFAULT_OPTIONS_VALUES = exports.DEFAULT_OPENAPI_CONFIG_FILENAME = void 0;
|
|
4
4
|
const HttpClient_enum_1 = require("../core/types/enums/HttpClient.enum");
|
|
5
5
|
const ValidationLibrary_enum_1 = require("../core/types/enums/ValidationLibrary.enum");
|
|
6
6
|
const Enums_1 = require("./Enums");
|
|
@@ -33,3 +33,6 @@ exports.APP_LOGGER = new Logger_1.Logger({
|
|
|
33
33
|
instanceId: 'cli',
|
|
34
34
|
logOutput: Enums_1.ELogOutput.CONSOLE,
|
|
35
35
|
});
|
|
36
|
+
exports.DEFAULT_SPECS_DIR = 'openapi/';
|
|
37
|
+
exports.DEFAULT_CUSTOM_REQUEST_PATH = './src/custom/request.ts';
|
|
38
|
+
exports.DEFAULT_OUTPUT_API_DIR = './generated';
|
|
@@ -246,6 +246,15 @@ const normalizePath = (p) => p.replace(Consts_1.REGEX_BACKSLASH, '/');
|
|
|
246
246
|
const normalized = normalizePath(result);
|
|
247
247
|
node_assert_1.strict.ok(normalized.includes('User') || normalized === './User');
|
|
248
248
|
});
|
|
249
|
+
(0, node_test_1.test)('external file reference with parentFilePath as directory', () => {
|
|
250
|
+
const result = (0, resolveRefToImportPath_1.resolveRefToImportPath)({
|
|
251
|
+
mainSpecPath: '/Developer/my-app/api/openapi_spec.yaml',
|
|
252
|
+
parentFilePath: '/Developer/my-app/api/ui/components/dir/some.yaml',
|
|
253
|
+
refValuePath: '../components/dir/file_name.yaml',
|
|
254
|
+
outputModelsPath: '/generated/models',
|
|
255
|
+
});
|
|
256
|
+
node_assert_1.strict.equal(normalizePath(result), './ui/components/dir/FileName');
|
|
257
|
+
});
|
|
249
258
|
});
|
|
250
259
|
(0, node_test_1.describe)('ABSOLUTE_PATH (default case)', () => {
|
|
251
260
|
(0, node_test_1.test)('absolute path to file → resolves correctly', () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveRefToImportPath.d.ts","sourceRoot":"","sources":["../../../src/core/utils/resolveRefToImportPath.ts"],"names":[],"mappings":"AAQA,UAAU,OAAO;IACb,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;CAC5B;
|
|
1
|
+
{"version":3,"file":"resolveRefToImportPath.d.ts","sourceRoot":"","sources":["../../../src/core/utils/resolveRefToImportPath.ts"],"names":[],"mappings":"AAQA,UAAU,OAAO;IACb,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;CAC5B;AAoED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,EAAE,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,gBAAgB,EAAE,EAAE,OAAO,UAyD/G"}
|
|
@@ -60,9 +60,7 @@ function prepareParentDirForResolve(parentFilePath, mainSpecPath, sourceRoot) {
|
|
|
60
60
|
function removeParentBasenamePrefix(refValueClean, parentDirForResolveWithSep) {
|
|
61
61
|
const baseNameParent = (0, path_1.basename)(parentDirForResolveWithSep);
|
|
62
62
|
const baseNameParentWithSep = baseNameParent.endsWith('/') ? baseNameParent : baseNameParent + '/';
|
|
63
|
-
return refValueClean.startsWith(baseNameParentWithSep)
|
|
64
|
-
? refValueClean.replace(baseNameParentWithSep, '')
|
|
65
|
-
: refValueClean;
|
|
63
|
+
return refValueClean.startsWith(baseNameParentWithSep) ? refValueClean.replace(baseNameParentWithSep, '') : refValueClean;
|
|
66
64
|
}
|
|
67
65
|
/**
|
|
68
66
|
* Resolves $ref reference to import path for generated code.
|
|
@@ -94,12 +92,20 @@ function resolveRefToImportPath({ mainSpecPath, parentFilePath, refValuePath, ou
|
|
|
94
92
|
const currentRefValue = removeParentBasenamePrefix(refValueClean, parentDirForResolveWithSep);
|
|
95
93
|
// EXTERNAL_FILE: reference to external file (e.g., ./file.yaml)
|
|
96
94
|
if (parsed.type === parseRef_1.RefType.EXTERNAL_FILE) {
|
|
97
|
-
const
|
|
95
|
+
const adjustedRefSegments = currentRefValue.split('/');
|
|
96
|
+
let adjustedParentDir = parentDirForResolveWithSep;
|
|
97
|
+
while (adjustedRefSegments[0] === '..') {
|
|
98
|
+
adjustedParentDir = (0, pathHelpers_1.dirNameHelper)(adjustedParentDir);
|
|
99
|
+
adjustedRefSegments.shift();
|
|
100
|
+
}
|
|
101
|
+
const parentBase = (0, path_1.basename)(adjustedParentDir);
|
|
102
|
+
if (adjustedRefSegments[0] === parentBase) {
|
|
103
|
+
adjustedRefSegments.shift();
|
|
104
|
+
}
|
|
105
|
+
const targetFileAbs = (0, pathHelpers_1.resolveHelper)(adjustedParentDir, ...adjustedRefSegments);
|
|
98
106
|
return resolveExternalFileOrAbsolutePath(targetFileAbs, sourceRoot, outputModelsPath, absOutputModelsPath);
|
|
99
107
|
}
|
|
100
108
|
// ABSOLUTE_PATH (default case): absolute path reference
|
|
101
|
-
const targetFileAbs = fileSystemHelpers_1.fileSystemHelpers.isPathToFile(refValueClean)
|
|
102
|
-
? (0, pathHelpers_1.joinHelper)(parentDirForResolveWithSep, refValueClean)
|
|
103
|
-
: (0, pathHelpers_1.resolveHelper)(parentDirForResolveWithSep, refValueClean);
|
|
109
|
+
const targetFileAbs = fileSystemHelpers_1.fileSystemHelpers.isPathToFile(refValueClean) ? (0, pathHelpers_1.joinHelper)(parentDirForResolveWithSep, refValueClean) : (0, pathHelpers_1.resolveHelper)(parentDirForResolveWithSep, refValueClean);
|
|
104
110
|
return resolveExternalFileOrAbsolutePath(targetFileAbs, sourceRoot, outputModelsPath, absOutputModelsPath);
|
|
105
111
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
declare const _default: {
|
|
2
|
+
"1": (container: any, depth0: any, helpers: any, partials: any, data: any) => string;
|
|
3
|
+
"3": (container: any, depth0: any, helpers: any, partials: any, data: any) => string;
|
|
4
|
+
"5": (container: any, depth0: any, helpers: any, partials: any, data: any) => string;
|
|
5
|
+
compiler: (string | number)[];
|
|
6
|
+
main: (container: any, depth0: any, helpers: any, partials: any, data: any) => string;
|
|
7
|
+
usePartial: boolean;
|
|
8
|
+
useData: boolean;
|
|
9
|
+
};
|
|
10
|
+
export default _default;
|
|
11
|
+
//# sourceMappingURL=customRequest.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"customRequest.d.ts","sourceRoot":"","sources":["../../../src/templatesCompiled/cli/customRequest.ts"],"names":[],"mappings":";;;;;;;;;AAMA,wBAmBmC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
// This is an automatically generated file for the hbs template.
|
|
4
|
+
// You don't need to change it, run npm run build:hbs to update it.
|
|
5
|
+
/* istanbul ignore file */
|
|
6
|
+
/* tslint: disable */
|
|
7
|
+
/* eslint: disable */
|
|
8
|
+
// @ts-nocheck
|
|
9
|
+
exports.default = { "1": function (container, depth0, helpers, partials, data) {
|
|
10
|
+
return "import type { CancelablePromise } from './CancelablePromise';\n";
|
|
11
|
+
}, "3": function (container, depth0, helpers, partials, data) {
|
|
12
|
+
return "export function request<T>(options: ApiRequestOptions, config: TOpenAPIConfig): CancelablePromise<T> {\n return new CancelablePromise(async (resolve, reject, onCancel) => {\n try {\n const abortController = new AbortController();\n \n if (options?.timeout) {\n const timeoutId = setTimeout(() => abortController.abort(), options.timeout);\n onCancel(() => clearTimeout(timeoutId));\n }\n \n onCancel(() => abortController.abort());\n \n if (onCancel.isCancelled) {\n return;\n }\n \n // Ваша пользовательская логика запросов здесь\n const response = await fetch(config.url, {\n method: config.method,\n headers: config.headers,\n body: config.body ? JSON.stringify(config.body) : undefined,\n signal: abortController.signal,\n });\n \n if (!response.ok) {\n throw new Error(`Request failed: ${response.statusText}`);\n }\n \n const data = await response.json();\n resolve(data);\n } catch (error) {\n reject(error);\n }\n });\n};\n";
|
|
13
|
+
}, "5": function (container, depth0, helpers, partials, data) {
|
|
14
|
+
return "export async function request<T>(options: ApiRequestOptions, config: TOpenAPIConfig): Promise<T> {\n return new Promise(async (resolve, reject) => {\n try {\n const url = getUrl(options, config);\n const response = await sendRequest(options, url, config);\n const responseBody = getResponseBody(response);\n const responseHeader = getResponseHeader(response, options.responseHeader);\n\n const result: ApiResult = {\n url,\n ok: isSuccess(response.status),\n status: response.status,\n statusText: response.statusText,\n body: responseHeader || responseBody,\n };\n\n catchErrors(options, result);\n resolve(result.body);\n } catch (error) {\n reject(error);\n }\n });\n}\n";
|
|
15
|
+
}, "compiler": [8, ">= 4.3.0"], "main": function (container, depth0, helpers, partials, data) {
|
|
16
|
+
var stack1, alias1 = depth0 != null ? depth0 : (container.nullContext || {}), lookupProperty = container.lookupProperty || function (parent, propertyName) {
|
|
17
|
+
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
|
|
18
|
+
return parent[propertyName];
|
|
19
|
+
}
|
|
20
|
+
return undefined;
|
|
21
|
+
};
|
|
22
|
+
return ((stack1 = container.invokePartial(lookupProperty(partials, "header"), depth0, { "name": "header", "data": data, "helpers": helpers, "partials": partials, "decorators": container.decorators })) != null ? stack1 : "")
|
|
23
|
+
+ "\nimport type { RequestExecutor, RequestConfig } from './request-executor';\n"
|
|
24
|
+
+ ((stack1 = lookupProperty(helpers, "if").call(alias1, lookupProperty(depth0, "useCancelableRequest"), { "name": "if", "hash": {}, "fn": container.program(1, data, 0), "inverse": container.noop, "data": data, "loc": { "start": { "line": 4, "column": 0 }, "end": { "line": 6, "column": 7 } } })) != null ? stack1 : "")
|
|
25
|
+
+ "\n/**\n * Определите свой тип опций (опционально)\n * Измените этот интерфейс в соответствии с вашими потребностями\n */\ninterface MyCustomOptions {\n timeout?: number;\n retries?: number;\n}\n\n/**\n * Создайте пользовательский executor\n * Реализуйте свою логику запросов здесь\n *\n * @example Пример использования:\n * \n * import { createLegacyExecutor } from './generated/core/legacy-request-adapter';\n * import { SimpleService } from './generated/services/SimpleService';\n *\n * const executorWithOptions = createLegacyExecutor<MyCustomOptions>(OpenAPI, (options) => {\n * // Мапьте ваши пользовательские опции в ApiRequestOptions при необходимости\n * return {\n * // Добавьте любые поля ApiRequestOptions на основе options\n * };\n * });\n * \n * const simpleService = new SimpleService(executorWithOptions);\n * await simpleService.getCallWithoutParametersAndResponse();\n */\n"
|
|
26
|
+
+ ((stack1 = lookupProperty(helpers, "if").call(alias1, lookupProperty(depth0, "useCancelableRequest"), { "name": "if", "hash": {}, "fn": container.program(3, data, 0), "inverse": container.program(5, data, 0), "data": data, "loc": { "start": { "line": 36, "column": 0 }, "end": { "line": 96, "column": 7 } } })) != null ? stack1 : "");
|
|
27
|
+
}, "usePartial": true, "useData": true };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
declare const _default: {
|
|
2
|
+
"1": (container: any, depth0: any, helpers: any, partials: any, data: any) => string;
|
|
3
|
+
"3": (container: any, depth0: any, helpers: any, partials: any, data: any) => string;
|
|
4
|
+
"5": (container: any, depth0: any, helpers: any, partials: any, data: any) => string;
|
|
5
|
+
compiler: (string | number)[];
|
|
6
|
+
main: (container: any, depth0: any, helpers: any, partials: any, data: any) => string;
|
|
7
|
+
usePartial: boolean;
|
|
8
|
+
useData: boolean;
|
|
9
|
+
};
|
|
10
|
+
export default _default;
|
|
11
|
+
//# sourceMappingURL=customRequestExecutor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"customRequestExecutor.d.ts","sourceRoot":"","sources":["../../../src/templatesCompiled/cli/customRequestExecutor.ts"],"names":[],"mappings":";;;;;;;;;AAMA,wBAmBmC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
// This is an automatically generated file for the hbs template.
|
|
4
|
+
// You don't need to change it, run npm run build:hbs to update it.
|
|
5
|
+
/* istanbul ignore file */
|
|
6
|
+
/* tslint: disable */
|
|
7
|
+
/* eslint: disable */
|
|
8
|
+
// @ts-nocheck
|
|
9
|
+
exports.default = { "1": function (container, depth0, helpers, partials, data) {
|
|
10
|
+
return "import type { CancelablePromise } from './CancelablePromise';\n";
|
|
11
|
+
}, "3": function (container, depth0, helpers, partials, data) {
|
|
12
|
+
return "export const customExecutor: RequestExecutor<MyCustomOptions> = {\n async request<TResponse>(config: RequestConfig, options?: MyCustomOptions): CancelablePromise<TResponse> {\n return new CancelablePromise(async (resolve, reject, onCancel) => {\n try {\n const abortController = new AbortController();\n \n if (options?.timeout) {\n const timeoutId = setTimeout(() => abortController.abort(), options.timeout);\n onCancel(() => clearTimeout(timeoutId));\n }\n \n onCancel(() => abortController.abort());\n \n if (onCancel.isCancelled) {\n return;\n }\n \n // Ваша пользовательская логика запросов здесь\n const response = await fetch(config.url, {\n method: config.method,\n headers: config.headers,\n body: config.body ? JSON.stringify(config.body) : undefined,\n signal: abortController.signal,\n });\n \n if (!response.ok) {\n throw new Error(`Request failed: ${response.statusText}`);\n }\n \n const data = await response.json();\n resolve(data);\n } catch (error) {\n reject(error);\n }\n });\n },\n};\n";
|
|
13
|
+
}, "5": function (container, depth0, helpers, partials, data) {
|
|
14
|
+
return "export const customExecutor: RequestExecutor<MyCustomOptions> = {\n async request<TResponse>(config: RequestConfig, options?: MyCustomOptions): Promise<TResponse> {\n // Ваша пользовательская логика запросов здесь\n const response = await fetch(config.url, {\n method: config.method,\n headers: config.headers,\n body: config.body ? JSON.stringify(config.body) : undefined,\n signal: options?.timeout ? AbortSignal.timeout(options.timeout) : undefined,\n });\n \n if (!response.ok) {\n throw new Error(`Request failed: ${response.statusText}`);\n }\n \n return response.json();\n },\n};\n";
|
|
15
|
+
}, "compiler": [8, ">= 4.3.0"], "main": function (container, depth0, helpers, partials, data) {
|
|
16
|
+
var stack1, alias1 = depth0 != null ? depth0 : (container.nullContext || {}), lookupProperty = container.lookupProperty || function (parent, propertyName) {
|
|
17
|
+
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
|
|
18
|
+
return parent[propertyName];
|
|
19
|
+
}
|
|
20
|
+
return undefined;
|
|
21
|
+
};
|
|
22
|
+
return ((stack1 = container.invokePartial(lookupProperty(partials, "header"), depth0, { "name": "header", "data": data, "helpers": helpers, "partials": partials, "decorators": container.decorators })) != null ? stack1 : "")
|
|
23
|
+
+ "\nimport type { RequestExecutor, RequestConfig } from './request-executor';\n"
|
|
24
|
+
+ ((stack1 = lookupProperty(helpers, "if").call(alias1, lookupProperty(depth0, "useCancelableRequest"), { "name": "if", "hash": {}, "fn": container.program(1, data, 0), "inverse": container.noop, "data": data, "loc": { "start": { "line": 4, "column": 0 }, "end": { "line": 6, "column": 7 } } })) != null ? stack1 : "")
|
|
25
|
+
+ "\n/**\n * Определите свой тип опций (опционально)\n * Измените этот интерфейс в соответствии с вашими потребностями\n */\ninterface MyCustomOptions {\n timeout?: number;\n retries?: number;\n}\n\n/**\n * Создайте пользовательский executor\n * Реализуйте свою логику запросов здесь\n *\n * @example Пример использования:\n * \n * import { SimpleService } from './generated/services/SimpleService';\n * \n * const simpleService = new SimpleService<MyCustomOptions>(customExecutor);\n * await simpleService.getCallWithoutParametersAndResponse({ timeout: 5000, retries: 3 });\n */\n"
|
|
26
|
+
+ ((stack1 = lookupProperty(helpers, "if").call(alias1, lookupProperty(depth0, "useCancelableRequest"), { "name": "if", "hash": {}, "fn": container.program(3, data, 0), "inverse": container.program(5, data, 0), "data": data, "loc": { "start": { "line": 28, "column": 0 }, "end": { "line": 84, "column": 7 } } })) != null ? stack1 : "");
|
|
27
|
+
}, "usePartial": true, "useData": true };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
declare const _default: {
|
|
2
2
|
"1": (container: any, depth0: any, helpers: any, partials: any, data: any) => string;
|
|
3
|
-
"
|
|
3
|
+
"2": (container: any, depth0: any, helpers: any, partials: any, data: any) => string;
|
|
4
|
+
"4": (container: any, depth0: any, helpers: any, partials: any, data: any) => string;
|
|
4
5
|
compiler: (string | number)[];
|
|
5
6
|
main: (container: any, depth0: any, helpers: any, partials: any, data: any) => any;
|
|
6
7
|
useData: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openApiConfig.d.ts","sourceRoot":"","sources":["../../../src/templatesCompiled/cli/openApiConfig.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"openApiConfig.d.ts","sourceRoot":"","sources":["../../../src/templatesCompiled/cli/openApiConfig.ts"],"names":[],"mappings":";;;;;;;;AAMA,wBAwFiB"}
|
|
@@ -7,9 +7,81 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
7
7
|
/* eslint: disable */
|
|
8
8
|
// @ts-nocheck
|
|
9
9
|
exports.default = { "1": function (container, depth0, helpers, partials, data) {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
var stack1, alias1 = container.strict, alias2 = container.lambda, lookupProperty = container.lookupProperty || function (parent, propertyName) {
|
|
11
|
+
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
|
|
12
|
+
return parent[propertyName];
|
|
13
|
+
}
|
|
14
|
+
return undefined;
|
|
15
|
+
};
|
|
16
|
+
return "{\n \"items\": "
|
|
17
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "items", { "start": { "line": 3, "column": 15 }, "end": { "line": 3, "column": 26 } }), depth0)) != null ? stack1 : "")
|
|
18
|
+
+ ",\n \"httpClient\": \""
|
|
19
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "httpClient", { "start": { "line": 4, "column": 21 }, "end": { "line": 4, "column": 37 } }), depth0)) != null ? stack1 : "")
|
|
20
|
+
+ "\",\n \"sortByRequired\": "
|
|
21
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "sortByRequired", { "start": { "line": 5, "column": 24 }, "end": { "line": 5, "column": 44 } }), depth0)) != null ? stack1 : "")
|
|
22
|
+
+ ",\n \"enumPrefix\": \""
|
|
23
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "enumPrefix", { "start": { "line": 6, "column": 21 }, "end": { "line": 6, "column": 37 } }), depth0)) != null ? stack1 : "")
|
|
24
|
+
+ "\",\n \"excludeCoreServiceFiles\": "
|
|
25
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "excludeCoreServiceFiles", { "start": { "line": 7, "column": 33 }, "end": { "line": 7, "column": 62 } }), depth0)) != null ? stack1 : "")
|
|
26
|
+
+ ",\n \"interfacePrefix\": \""
|
|
27
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "interfacePrefix", { "start": { "line": 8, "column": 26 }, "end": { "line": 8, "column": 47 } }), depth0)) != null ? stack1 : "")
|
|
28
|
+
+ "\",\n \"typePrefix\": \""
|
|
29
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "typePrefix", { "start": { "line": 9, "column": 21 }, "end": { "line": 9, "column": 37 } }), depth0)) != null ? stack1 : "")
|
|
30
|
+
+ "\",\n \"useCancelableRequest\": "
|
|
31
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "useCancelableRequest", { "start": { "line": 10, "column": 30 }, "end": { "line": 10, "column": 56 } }), depth0)) != null ? stack1 : "")
|
|
32
|
+
+ ",\n \"useOptions\": "
|
|
33
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "useOptions", { "start": { "line": 11, "column": 20 }, "end": { "line": 11, "column": 36 } }), depth0)) != null ? stack1 : "")
|
|
34
|
+
+ ",\n \"useSeparatedIndexes\": "
|
|
35
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "useSeparatedIndexes", { "start": { "line": 12, "column": 29 }, "end": { "line": 12, "column": 54 } }), depth0)) != null ? stack1 : "")
|
|
36
|
+
+ ",\n \"useUnionTypes\": "
|
|
37
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "useUnionTypes", { "start": { "line": 13, "column": 23 }, "end": { "line": 13, "column": 42 } }), depth0)) != null ? stack1 : "")
|
|
38
|
+
+ ",\n "
|
|
39
|
+
+ ((stack1 = lookupProperty(helpers, "if").call(depth0 != null ? depth0 : (container.nullContext || {}), lookupProperty(lookupProperty(data, "root"), "request"), { "name": "if", "hash": {}, "fn": container.program(2, data, 0), "inverse": container.noop, "data": data, "loc": { "start": { "line": 14, "column": 4 }, "end": { "line": 14, "column": 62 } } })) != null ? stack1 : "")
|
|
40
|
+
+ "\n}\n";
|
|
41
|
+
}, "2": function (container, depth0, helpers, partials, data) {
|
|
42
|
+
var stack1, lookupProperty = container.lookupProperty || function (parent, propertyName) {
|
|
43
|
+
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
|
|
44
|
+
return parent[propertyName];
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
};
|
|
48
|
+
return "\"request\": \""
|
|
49
|
+
+ ((stack1 = container.lambda(container.strict(lookupProperty(data, "root"), "request", { "start": { "line": 14, "column": 39 }, "end": { "line": 14, "column": 52 } }), depth0)) != null ? stack1 : "")
|
|
50
|
+
+ "\"";
|
|
51
|
+
}, "4": function (container, depth0, helpers, partials, data) {
|
|
52
|
+
var stack1, alias1 = container.strict, alias2 = container.lambda, lookupProperty = container.lookupProperty || function (parent, propertyName) {
|
|
53
|
+
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
|
|
54
|
+
return parent[propertyName];
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
};
|
|
58
|
+
return "{\n \"input\": \""
|
|
59
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "input", { "start": { "line": 18, "column": 16 }, "end": { "line": 18, "column": 27 } }), depth0)) != null ? stack1 : "")
|
|
60
|
+
+ "\",\n \"output\": \""
|
|
61
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "output", { "start": { "line": 19, "column": 17 }, "end": { "line": 19, "column": 29 } }), depth0)) != null ? stack1 : "")
|
|
62
|
+
+ "\",\n \"httpClient\": \""
|
|
63
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "httpClient", { "start": { "line": 20, "column": 21 }, "end": { "line": 20, "column": 37 } }), depth0)) != null ? stack1 : "")
|
|
64
|
+
+ "\",\n \"sortByRequired\": "
|
|
65
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "sortByRequired", { "start": { "line": 21, "column": 24 }, "end": { "line": 21, "column": 44 } }), depth0)) != null ? stack1 : "")
|
|
66
|
+
+ ",\n \"enumPrefix\": \""
|
|
67
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "enumPrefix", { "start": { "line": 22, "column": 21 }, "end": { "line": 22, "column": 37 } }), depth0)) != null ? stack1 : "")
|
|
68
|
+
+ "\",\n \"excludeCoreServiceFiles\": "
|
|
69
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "excludeCoreServiceFiles", { "start": { "line": 23, "column": 33 }, "end": { "line": 23, "column": 62 } }), depth0)) != null ? stack1 : "")
|
|
70
|
+
+ ",\n \"interfacePrefix\": \""
|
|
71
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "interfacePrefix", { "start": { "line": 24, "column": 26 }, "end": { "line": 24, "column": 47 } }), depth0)) != null ? stack1 : "")
|
|
72
|
+
+ "\",\n \"typePrefix\": \""
|
|
73
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "typePrefix", { "start": { "line": 25, "column": 21 }, "end": { "line": 25, "column": 37 } }), depth0)) != null ? stack1 : "")
|
|
74
|
+
+ "\",\n \"useCancelableRequest\": "
|
|
75
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "useCancelableRequest", { "start": { "line": 26, "column": 30 }, "end": { "line": 26, "column": 56 } }), depth0)) != null ? stack1 : "")
|
|
76
|
+
+ ",\n \"useOptions\": "
|
|
77
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "useOptions", { "start": { "line": 27, "column": 20 }, "end": { "line": 27, "column": 36 } }), depth0)) != null ? stack1 : "")
|
|
78
|
+
+ ",\n \"useSeparatedIndexes\": "
|
|
79
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "useSeparatedIndexes", { "start": { "line": 28, "column": 29 }, "end": { "line": 28, "column": 54 } }), depth0)) != null ? stack1 : "")
|
|
80
|
+
+ ",\n \"useUnionTypes\": "
|
|
81
|
+
+ ((stack1 = alias2(alias1(lookupProperty(data, "root"), "useUnionTypes", { "start": { "line": 29, "column": 23 }, "end": { "line": 29, "column": 42 } }), depth0)) != null ? stack1 : "")
|
|
82
|
+
+ ",\n "
|
|
83
|
+
+ ((stack1 = lookupProperty(helpers, "if").call(depth0 != null ? depth0 : (container.nullContext || {}), lookupProperty(lookupProperty(data, "root"), "request"), { "name": "if", "hash": {}, "fn": container.program(2, data, 0), "inverse": container.noop, "data": data, "loc": { "start": { "line": 30, "column": 4 }, "end": { "line": 30, "column": 62 } } })) != null ? stack1 : "")
|
|
84
|
+
+ "\n}\n";
|
|
13
85
|
}, "compiler": [8, ">= 4.3.0"], "main": function (container, depth0, helpers, partials, data) {
|
|
14
86
|
var stack1, lookupProperty = container.lookupProperty || function (parent, propertyName) {
|
|
15
87
|
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
|
|
@@ -17,5 +89,5 @@ exports.default = { "1": function (container, depth0, helpers, partials, data) {
|
|
|
17
89
|
}
|
|
18
90
|
return undefined;
|
|
19
91
|
};
|
|
20
|
-
return ((stack1 = lookupProperty(helpers, "if").call(depth0 != null ? depth0 : (container.nullContext || {}), lookupProperty(
|
|
92
|
+
return ((stack1 = lookupProperty(helpers, "if").call(depth0 != null ? depth0 : (container.nullContext || {}), lookupProperty(lookupProperty(data, "root"), "useMultyOptions"), { "name": "if", "hash": {}, "fn": container.program(1, data, 0), "inverse": container.program(4, data, 0), "data": data, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 32, "column": 7 } } })) != null ? stack1 : "");
|
|
21
93
|
}, "useData": true };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ts-openapi-codegen",
|
|
3
|
-
"version": "2.0.0-beta.
|
|
3
|
+
"version": "2.0.0-beta.5",
|
|
4
4
|
"description": "Library that generates Typescript clients based on the OpenAPI specification. It bases on openapi-typescript-codegen",
|
|
5
5
|
"author": "Alexey Zverev",
|
|
6
6
|
"homepage": "https://github.com/ozonophore/openapi-codegen.git",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"runInitOpenapiConfig.d.ts","sourceRoot":"","sources":["../../../src/cli/initOpenApiConfig/runInitOpenapiConfig.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAazC,wBAAsB,oBAAoB,CAAC,MAAM,EAAE,YAAY,iBAoB9D"}
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
-
};
|
|
38
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
-
exports.runInitOpenapiConfig = runInitOpenapiConfig;
|
|
40
|
-
const Handlebars = __importStar(require("handlebars/runtime"));
|
|
41
|
-
const prettier_1 = require("prettier");
|
|
42
|
-
const Consts_1 = require("../../common/Consts");
|
|
43
|
-
const fileSystemHelpers_1 = require("../../common/utils/fileSystemHelpers");
|
|
44
|
-
const loadConfigIfExists_1 = require("../../common/utils/loadConfigIfExists");
|
|
45
|
-
const pathHelpers_1 = require("../../common/utils/pathHelpers");
|
|
46
|
-
const getFileName_1 = require("../../core/utils/getFileName");
|
|
47
|
-
const openApiConfig_1 = __importDefault(require("../../templatesCompiled/cli/openApiConfig"));
|
|
48
|
-
const Enums_1 = require("./Enums");
|
|
49
|
-
async function runInitOpenapiConfig(params) {
|
|
50
|
-
const { openapiConfig, type: optionType } = params;
|
|
51
|
-
try {
|
|
52
|
-
const configData = (0, loadConfigIfExists_1.loadConfigIfExists)(openapiConfig);
|
|
53
|
-
if (!configData) {
|
|
54
|
-
const configFilePath = openapiConfig ?? Consts_1.DEFAULT_OPENAPI_CONFIG_FILENAME;
|
|
55
|
-
const file = (0, pathHelpers_1.resolveHelper)(process.cwd(), configFilePath);
|
|
56
|
-
const configTemplate = Handlebars.template(openApiConfig_1.default);
|
|
57
|
-
const templateResult = configTemplate({ useMultyOptions: optionType === Enums_1.EOptionType.MULTIOPTION });
|
|
58
|
-
const formattedValue = await (0, prettier_1.format)(templateResult, { parser: 'json' });
|
|
59
|
-
await fileSystemHelpers_1.fileSystemHelpers.writeFile(file, formattedValue);
|
|
60
|
-
Consts_1.APP_LOGGER.info(`File recording completed: ${file}`);
|
|
61
|
-
}
|
|
62
|
-
else {
|
|
63
|
-
const fileName = (0, getFileName_1.getFileName)(openapiConfig);
|
|
64
|
-
Consts_1.APP_LOGGER.info(`The configuration file already exists: ${fileName}`);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
catch (error) {
|
|
68
|
-
Consts_1.APP_LOGGER.error(error.message);
|
|
69
|
-
}
|
|
70
|
-
}
|