@ps-aux/api-client-gen 0.0.7-rc1 → 0.0.7-rc2
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/bin.esm.js +1 -1
- package/dist/bin.js +1 -1
- package/dist/generateApiClient-BHDOH9mh.js +188 -0
- package/dist/generateApiClient-DUCQclNI.js +168 -0
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +5 -5
package/dist/bin.esm.js
CHANGED
package/dist/bin.js
CHANGED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var Path = require('path');
|
|
4
|
+
var fs$1 = require('fs');
|
|
5
|
+
var axios = require('axios');
|
|
6
|
+
var fs = require('fs/promises');
|
|
7
|
+
var swaggerTypescriptApi = require('swagger-typescript-api');
|
|
8
|
+
var tsToZod = require('ts-to-zod');
|
|
9
|
+
|
|
10
|
+
function _interopNamespaceDefault(e) {
|
|
11
|
+
var n = Object.create(null);
|
|
12
|
+
if (e) {
|
|
13
|
+
Object.keys(e).forEach(function (k) {
|
|
14
|
+
if (k !== 'default') {
|
|
15
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
16
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
17
|
+
enumerable: true,
|
|
18
|
+
get: function () { return e[k]; }
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
n.default = e;
|
|
24
|
+
return Object.freeze(n);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs$1);
|
|
28
|
+
|
|
29
|
+
const downloadSpec = async (path, url) => {
|
|
30
|
+
const res = await axios({
|
|
31
|
+
url,
|
|
32
|
+
method: 'GET',
|
|
33
|
+
responseType: 'arraybuffer',
|
|
34
|
+
}).catch(err => {
|
|
35
|
+
throw err.toString();
|
|
36
|
+
});
|
|
37
|
+
const content = res.data.toString();
|
|
38
|
+
await fs.writeFile(path, format(content));
|
|
39
|
+
};
|
|
40
|
+
const format = (content) => JSON.stringify(JSON.parse(content), null, 4);
|
|
41
|
+
|
|
42
|
+
const generateOpenApiModel = async ({ input, isNode, responseWrapper, name, outputDir }, log) => {
|
|
43
|
+
log(`Will generate API client name=${name} to ${outputDir}, node=${isNode}`);
|
|
44
|
+
const specialMapping = isNode
|
|
45
|
+
? {
|
|
46
|
+
File: '{file: Buffer | stream.Readable, name: string}',
|
|
47
|
+
}
|
|
48
|
+
: {};
|
|
49
|
+
const fileName = 'index';
|
|
50
|
+
const dstFile = Path.join(outputDir, `${fileName}.ts`);
|
|
51
|
+
await swaggerTypescriptApi.generateApi({
|
|
52
|
+
name: 'index',
|
|
53
|
+
output: outputDir,
|
|
54
|
+
input: input,
|
|
55
|
+
// modular: true,
|
|
56
|
+
httpClientType: 'axios',
|
|
57
|
+
templates: Path.resolve(getThisScriptDirname(), '../templates'),
|
|
58
|
+
defaultResponseAsSuccess: true,
|
|
59
|
+
// generateRouteTypes: true,
|
|
60
|
+
singleHttpClient: true,
|
|
61
|
+
// extractRequestBody: true,
|
|
62
|
+
cleanOutput: true,
|
|
63
|
+
moduleNameFirstTag: true,
|
|
64
|
+
apiClassName: capitalize(name) + 'Api',
|
|
65
|
+
// @ts-ignore
|
|
66
|
+
codeGenConstructs: (struct) => ({
|
|
67
|
+
// @ts-ignore
|
|
68
|
+
Keyword: specialMapping,
|
|
69
|
+
}),
|
|
70
|
+
// extractRequestParams: true,
|
|
71
|
+
});
|
|
72
|
+
const addImports = [];
|
|
73
|
+
const replaces = [];
|
|
74
|
+
if (isNode) {
|
|
75
|
+
addImports.push('import stream from \'node:stream\'');
|
|
76
|
+
}
|
|
77
|
+
if (responseWrapper) {
|
|
78
|
+
log(`Will use response wrapper '${JSON.stringify(responseWrapper)}'`);
|
|
79
|
+
if (responseWrapper.import)
|
|
80
|
+
addImports.push(responseWrapper.import);
|
|
81
|
+
replaces.push(['Promise', responseWrapper.symbol]);
|
|
82
|
+
}
|
|
83
|
+
// Remove unnecessary generics
|
|
84
|
+
replaces.push(['<SecurityDataType extends unknown>', '']);
|
|
85
|
+
replaces.push(['<SecurityDataType>', '']);
|
|
86
|
+
log(`Will modify the outputs ${JSON.stringify({
|
|
87
|
+
addImports,
|
|
88
|
+
replaces,
|
|
89
|
+
})}`);
|
|
90
|
+
await modifyOutput(dstFile, {
|
|
91
|
+
addImports,
|
|
92
|
+
replaces,
|
|
93
|
+
});
|
|
94
|
+
return dstFile;
|
|
95
|
+
};
|
|
96
|
+
const modifyOutput = async (path, cmd) => {
|
|
97
|
+
let content = await fs.readFile(path).then((r) => r.toString());
|
|
98
|
+
if (cmd.addImports.length) {
|
|
99
|
+
content = cmd.addImports.join('\n') + '\n' + content;
|
|
100
|
+
}
|
|
101
|
+
cmd.replaces.forEach(([from, to]) => {
|
|
102
|
+
content = content.replaceAll(from, to);
|
|
103
|
+
});
|
|
104
|
+
await fs.writeFile(path, content);
|
|
105
|
+
};
|
|
106
|
+
const getThisScriptDirname = () => {
|
|
107
|
+
// Might be problem in ESM mode
|
|
108
|
+
return __dirname;
|
|
109
|
+
};
|
|
110
|
+
const capitalize = (str) => {
|
|
111
|
+
return str[0].toUpperCase() + str.substring(1);
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
// TODO needed?
|
|
115
|
+
const removeGenericTypes = (code) => {
|
|
116
|
+
const regex = /export (interface|enum|type) [^<]* \{\n(.*\n)*?}/mg;
|
|
117
|
+
const matches = code.matchAll(regex);
|
|
118
|
+
const types = Array.from(matches).map(m => m[0]);
|
|
119
|
+
return types.join('\n');
|
|
120
|
+
};
|
|
121
|
+
const generateSchemas = (inputFile, outputFile, opts = {}) => {
|
|
122
|
+
const code = fs$1.readFileSync(inputFile).toString();
|
|
123
|
+
const { getZodSchemasFile } = tsToZod.generate({
|
|
124
|
+
sourceText: removeGenericTypes(code),
|
|
125
|
+
// inputOutputMappings: {
|
|
126
|
+
//
|
|
127
|
+
// },
|
|
128
|
+
customJSDocFormatTypes: {
|
|
129
|
+
// Custom mapping
|
|
130
|
+
// 'date-time': 'blablaj' - regex
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
const fileName = Path.basename(inputFile);
|
|
134
|
+
let f = getZodSchemasFile(`./${fileName.replace('.ts', '')}`);
|
|
135
|
+
// Add import from the api model - TODO find a way how to define on generate
|
|
136
|
+
f = f.replaceAll('"./index";', '"./client"');
|
|
137
|
+
// Backend sends nulls not undefined - should be properly set in the OpenAPI TS types generation!
|
|
138
|
+
f = f.replaceAll('.optional()', '.nullable()');
|
|
139
|
+
if (opts.localDateTimes) {
|
|
140
|
+
f = f.replaceAll('z.string().datetime()', 'z.string().datetime({local: true})');
|
|
141
|
+
}
|
|
142
|
+
fs$1.writeFileSync(outputFile, f);
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const generateApiClient = async ({ dstDir, apiName, env, srcSpec, responseWrapper, zodSchemas, }, log = console.log) => {
|
|
146
|
+
if (!srcSpec)
|
|
147
|
+
throw new Error(`Url or path ('srcSpec' not specified`);
|
|
148
|
+
if (!apiName)
|
|
149
|
+
throw new Error('apiName not specified');
|
|
150
|
+
if (!dstDir)
|
|
151
|
+
throw new Error('dstDir not specified');
|
|
152
|
+
if (!env)
|
|
153
|
+
throw new Error('env not specified');
|
|
154
|
+
const dir = Path.resolve(dstDir, apiName);
|
|
155
|
+
if (!fs__namespace.existsSync(dir)) {
|
|
156
|
+
log(`Creating dir ${dir}`);
|
|
157
|
+
fs__namespace.mkdirSync(dir, {
|
|
158
|
+
recursive: true,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
const clientDir = Path.resolve(dir, 'client');
|
|
162
|
+
const specPath = await getSpecPath(srcSpec, dir, log);
|
|
163
|
+
const clientFile = await generateOpenApiModel({
|
|
164
|
+
name: apiName,
|
|
165
|
+
input: specPath,
|
|
166
|
+
outputDir: clientDir,
|
|
167
|
+
isNode: env === 'node',
|
|
168
|
+
responseWrapper,
|
|
169
|
+
}, log);
|
|
170
|
+
console.log('client file', clientFile);
|
|
171
|
+
if (zodSchemas?.enabled === false)
|
|
172
|
+
return;
|
|
173
|
+
log('Generating Zod schemas');
|
|
174
|
+
generateSchemas(Path.resolve(dir, clientFile), Path.resolve(dir, './zod.ts'), zodSchemas);
|
|
175
|
+
};
|
|
176
|
+
const getSpecPath = async (urlOrPath, dir, log) => {
|
|
177
|
+
if (!urlOrPath.startsWith('http')) {
|
|
178
|
+
if (!fs__namespace.existsSync(urlOrPath))
|
|
179
|
+
throw new Error(`Spec file ${urlOrPath} does not exists`);
|
|
180
|
+
return urlOrPath;
|
|
181
|
+
}
|
|
182
|
+
const specPath = Path.resolve(dir, `spec.json`);
|
|
183
|
+
log(`Will download the API spec from ${urlOrPath} to ${specPath}`);
|
|
184
|
+
await downloadSpec(specPath, urlOrPath);
|
|
185
|
+
return specPath;
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
exports.generateApiClient = generateApiClient;
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import Path from 'path';
|
|
2
|
+
import * as fs from 'fs';
|
|
3
|
+
import fs__default from 'fs';
|
|
4
|
+
import axios from 'axios';
|
|
5
|
+
import fs$1 from 'fs/promises';
|
|
6
|
+
import { generateApi } from 'swagger-typescript-api';
|
|
7
|
+
import { generate } from 'ts-to-zod';
|
|
8
|
+
|
|
9
|
+
const downloadSpec = async (path, url) => {
|
|
10
|
+
const res = await axios({
|
|
11
|
+
url,
|
|
12
|
+
method: 'GET',
|
|
13
|
+
responseType: 'arraybuffer',
|
|
14
|
+
}).catch(err => {
|
|
15
|
+
throw err.toString();
|
|
16
|
+
});
|
|
17
|
+
const content = res.data.toString();
|
|
18
|
+
await fs$1.writeFile(path, format(content));
|
|
19
|
+
};
|
|
20
|
+
const format = (content) => JSON.stringify(JSON.parse(content), null, 4);
|
|
21
|
+
|
|
22
|
+
const generateOpenApiModel = async ({ input, isNode, responseWrapper, name, outputDir }, log) => {
|
|
23
|
+
log(`Will generate API client name=${name} to ${outputDir}, node=${isNode}`);
|
|
24
|
+
const specialMapping = isNode
|
|
25
|
+
? {
|
|
26
|
+
File: '{file: Buffer | stream.Readable, name: string}',
|
|
27
|
+
}
|
|
28
|
+
: {};
|
|
29
|
+
const fileName = 'index';
|
|
30
|
+
const dstFile = Path.join(outputDir, `${fileName}.ts`);
|
|
31
|
+
await generateApi({
|
|
32
|
+
name: 'index',
|
|
33
|
+
output: outputDir,
|
|
34
|
+
input: input,
|
|
35
|
+
// modular: true,
|
|
36
|
+
httpClientType: 'axios',
|
|
37
|
+
templates: Path.resolve(getThisScriptDirname(), '../templates'),
|
|
38
|
+
defaultResponseAsSuccess: true,
|
|
39
|
+
// generateRouteTypes: true,
|
|
40
|
+
singleHttpClient: true,
|
|
41
|
+
// extractRequestBody: true,
|
|
42
|
+
cleanOutput: true,
|
|
43
|
+
moduleNameFirstTag: true,
|
|
44
|
+
apiClassName: capitalize(name) + 'Api',
|
|
45
|
+
// @ts-ignore
|
|
46
|
+
codeGenConstructs: (struct) => ({
|
|
47
|
+
// @ts-ignore
|
|
48
|
+
Keyword: specialMapping,
|
|
49
|
+
}),
|
|
50
|
+
// extractRequestParams: true,
|
|
51
|
+
});
|
|
52
|
+
const addImports = [];
|
|
53
|
+
const replaces = [];
|
|
54
|
+
if (isNode) {
|
|
55
|
+
addImports.push('import stream from \'node:stream\'');
|
|
56
|
+
}
|
|
57
|
+
if (responseWrapper) {
|
|
58
|
+
log(`Will use response wrapper '${JSON.stringify(responseWrapper)}'`);
|
|
59
|
+
if (responseWrapper.import)
|
|
60
|
+
addImports.push(responseWrapper.import);
|
|
61
|
+
replaces.push(['Promise', responseWrapper.symbol]);
|
|
62
|
+
}
|
|
63
|
+
// Remove unnecessary generics
|
|
64
|
+
replaces.push(['<SecurityDataType extends unknown>', '']);
|
|
65
|
+
replaces.push(['<SecurityDataType>', '']);
|
|
66
|
+
log(`Will modify the outputs ${JSON.stringify({
|
|
67
|
+
addImports,
|
|
68
|
+
replaces,
|
|
69
|
+
})}`);
|
|
70
|
+
await modifyOutput(dstFile, {
|
|
71
|
+
addImports,
|
|
72
|
+
replaces,
|
|
73
|
+
});
|
|
74
|
+
return dstFile;
|
|
75
|
+
};
|
|
76
|
+
const modifyOutput = async (path, cmd) => {
|
|
77
|
+
let content = await fs$1.readFile(path).then((r) => r.toString());
|
|
78
|
+
if (cmd.addImports.length) {
|
|
79
|
+
content = cmd.addImports.join('\n') + '\n' + content;
|
|
80
|
+
}
|
|
81
|
+
cmd.replaces.forEach(([from, to]) => {
|
|
82
|
+
content = content.replaceAll(from, to);
|
|
83
|
+
});
|
|
84
|
+
await fs$1.writeFile(path, content);
|
|
85
|
+
};
|
|
86
|
+
const getThisScriptDirname = () => {
|
|
87
|
+
// Might be problem in ESM mode
|
|
88
|
+
return __dirname;
|
|
89
|
+
};
|
|
90
|
+
const capitalize = (str) => {
|
|
91
|
+
return str[0].toUpperCase() + str.substring(1);
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// TODO needed?
|
|
95
|
+
const removeGenericTypes = (code) => {
|
|
96
|
+
const regex = /export (interface|enum|type) [^<]* \{\n(.*\n)*?}/mg;
|
|
97
|
+
const matches = code.matchAll(regex);
|
|
98
|
+
const types = Array.from(matches).map(m => m[0]);
|
|
99
|
+
return types.join('\n');
|
|
100
|
+
};
|
|
101
|
+
const generateSchemas = (inputFile, outputFile, opts = {}) => {
|
|
102
|
+
const code = fs__default.readFileSync(inputFile).toString();
|
|
103
|
+
const { getZodSchemasFile } = generate({
|
|
104
|
+
sourceText: removeGenericTypes(code),
|
|
105
|
+
// inputOutputMappings: {
|
|
106
|
+
//
|
|
107
|
+
// },
|
|
108
|
+
customJSDocFormatTypes: {
|
|
109
|
+
// Custom mapping
|
|
110
|
+
// 'date-time': 'blablaj' - regex
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
const fileName = Path.basename(inputFile);
|
|
114
|
+
let f = getZodSchemasFile(`./${fileName.replace('.ts', '')}`);
|
|
115
|
+
// Add import from the api model - TODO find a way how to define on generate
|
|
116
|
+
f = f.replaceAll('"./index";', '"./client"');
|
|
117
|
+
// Backend sends nulls not undefined - should be properly set in the OpenAPI TS types generation!
|
|
118
|
+
f = f.replaceAll('.optional()', '.nullable()');
|
|
119
|
+
if (opts.localDateTimes) {
|
|
120
|
+
f = f.replaceAll('z.string().datetime()', 'z.string().datetime({local: true})');
|
|
121
|
+
}
|
|
122
|
+
fs__default.writeFileSync(outputFile, f);
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const generateApiClient = async ({ dstDir, apiName, env, srcSpec, responseWrapper, zodSchemas, }, log = console.log) => {
|
|
126
|
+
if (!srcSpec)
|
|
127
|
+
throw new Error(`Url or path ('srcSpec' not specified`);
|
|
128
|
+
if (!apiName)
|
|
129
|
+
throw new Error('apiName not specified');
|
|
130
|
+
if (!dstDir)
|
|
131
|
+
throw new Error('dstDir not specified');
|
|
132
|
+
if (!env)
|
|
133
|
+
throw new Error('env not specified');
|
|
134
|
+
const dir = Path.resolve(dstDir, apiName);
|
|
135
|
+
if (!fs.existsSync(dir)) {
|
|
136
|
+
log(`Creating dir ${dir}`);
|
|
137
|
+
fs.mkdirSync(dir, {
|
|
138
|
+
recursive: true,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
const clientDir = Path.resolve(dir, 'client');
|
|
142
|
+
const specPath = await getSpecPath(srcSpec, dir, log);
|
|
143
|
+
const clientFile = await generateOpenApiModel({
|
|
144
|
+
name: apiName,
|
|
145
|
+
input: specPath,
|
|
146
|
+
outputDir: clientDir,
|
|
147
|
+
isNode: env === 'node',
|
|
148
|
+
responseWrapper,
|
|
149
|
+
}, log);
|
|
150
|
+
console.log('client file', clientFile);
|
|
151
|
+
if (zodSchemas?.enabled === false)
|
|
152
|
+
return;
|
|
153
|
+
log('Generating Zod schemas');
|
|
154
|
+
generateSchemas(Path.resolve(dir, clientFile), Path.resolve(dir, './zod.ts'), zodSchemas);
|
|
155
|
+
};
|
|
156
|
+
const getSpecPath = async (urlOrPath, dir, log) => {
|
|
157
|
+
if (!urlOrPath.startsWith('http')) {
|
|
158
|
+
if (!fs.existsSync(urlOrPath))
|
|
159
|
+
throw new Error(`Spec file ${urlOrPath} does not exists`);
|
|
160
|
+
return urlOrPath;
|
|
161
|
+
}
|
|
162
|
+
const specPath = Path.resolve(dir, `spec.json`);
|
|
163
|
+
log(`Will download the API spec from ${urlOrPath} to ${specPath}`);
|
|
164
|
+
await downloadSpec(specPath, urlOrPath);
|
|
165
|
+
return specPath;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
export { generateApiClient as g };
|
package/dist/index.esm.js
CHANGED
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ps-aux/api-client-gen",
|
|
3
|
-
"version": "0.0.7-
|
|
3
|
+
"version": "0.0.7-rc2",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"module": "dist/index.esm.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -18,10 +18,10 @@
|
|
|
18
18
|
"author": "",
|
|
19
19
|
"license": "ISC",
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"axios": "
|
|
22
|
-
"cosmiconfig": "
|
|
23
|
-
"swagger-typescript-api": "
|
|
24
|
-
"ts-to-zod": "
|
|
21
|
+
"axios": "1.5.0",
|
|
22
|
+
"cosmiconfig": "8.3.6",
|
|
23
|
+
"swagger-typescript-api": "13.0.23",
|
|
24
|
+
"ts-to-zod": "3.15.0"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"vitest": "^3.1.1"
|