@opra/cli 1.0.0-alpha.12 → 1.0.0-alpha.14
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/cjs/ts-generator/generators/clean-directory.js +35 -0
- package/cjs/ts-generator/generators/generate-data-type.js +258 -0
- package/cjs/ts-generator/generators/generate-document.js +60 -0
- package/cjs/ts-generator/generators/generate-http-api.js +45 -0
- package/cjs/ts-generator/generators/generate-http-controller.js +224 -0
- package/cjs/ts-generator/ts-generator.js +16 -17
- package/esm/ts-generator/generators/clean-directory.js +30 -0
- package/esm/ts-generator/generators/generate-data-type.js +247 -0
- package/esm/ts-generator/generators/generate-document.js +55 -0
- package/esm/ts-generator/generators/generate-http-api.js +40 -0
- package/esm/ts-generator/generators/generate-http-controller.js +219 -0
- package/esm/ts-generator/ts-generator.js +16 -17
- package/package.json +4 -3
- package/types/ts-generator/generators/clean-directory.d.ts +2 -0
- package/types/ts-generator/generators/generate-data-type.d.ts +41 -0
- package/types/ts-generator/generators/generate-document.d.ts +8 -0
- package/types/ts-generator/generators/generate-http-api.d.ts +3 -0
- package/types/ts-generator/generators/generate-http-controller.d.ts +3 -0
- package/types/ts-generator/ts-generator.d.ts +15 -15
|
@@ -8,11 +8,11 @@ const node_path_1 = tslib_1.__importDefault(require("node:path"));
|
|
|
8
8
|
const node_process_1 = tslib_1.__importDefault(require("node:process"));
|
|
9
9
|
const chalk_1 = tslib_1.__importDefault(require("chalk"));
|
|
10
10
|
const file_writer_js_1 = require("../file-writer.js");
|
|
11
|
-
const clean_directory_js_1 = require("./
|
|
12
|
-
const
|
|
13
|
-
const
|
|
14
|
-
const
|
|
15
|
-
const
|
|
11
|
+
const clean_directory_js_1 = require("./generators/clean-directory.js");
|
|
12
|
+
const generate_data_type_js_1 = require("./generators/generate-data-type.js");
|
|
13
|
+
const generate_document_js_1 = require("./generators/generate-document.js");
|
|
14
|
+
const generate_http_api_js_1 = require("./generators/generate-http-api.js");
|
|
15
|
+
const generate_http_controller_js_1 = require("./generators/generate-http-controller.js");
|
|
16
16
|
const ts_file_js_1 = require("./ts-file.js");
|
|
17
17
|
/**
|
|
18
18
|
* @class TsGenerator
|
|
@@ -49,7 +49,7 @@ class TsGenerator extends node_events_1.EventEmitter {
|
|
|
49
49
|
this.emit('log', chalk_1.default.cyan('Removing old files..'));
|
|
50
50
|
this.cleanDirectory(this.outDir);
|
|
51
51
|
this._apiPath = '/api';
|
|
52
|
-
await this.
|
|
52
|
+
await this.generateDocument();
|
|
53
53
|
const { importExt } = this.options;
|
|
54
54
|
// Write files
|
|
55
55
|
for (const file of Object.values(this._files)) {
|
|
@@ -95,15 +95,14 @@ class TsGenerator extends node_events_1.EventEmitter {
|
|
|
95
95
|
exports.TsGenerator = TsGenerator;
|
|
96
96
|
(() => {
|
|
97
97
|
TsGenerator.prototype.cleanDirectory = clean_directory_js_1.cleanDirectory;
|
|
98
|
-
TsGenerator.prototype.
|
|
99
|
-
TsGenerator.prototype.
|
|
100
|
-
TsGenerator.prototype.
|
|
101
|
-
TsGenerator.prototype.
|
|
102
|
-
TsGenerator.prototype.
|
|
103
|
-
TsGenerator.prototype.
|
|
104
|
-
TsGenerator.prototype.
|
|
105
|
-
TsGenerator.prototype.
|
|
106
|
-
TsGenerator.prototype.
|
|
107
|
-
TsGenerator.prototype.
|
|
108
|
-
// TsGenerator.prototype.resolveTypeNameOrDef = resolveTypeNameOrDef;
|
|
98
|
+
TsGenerator.prototype.generateDocument = generate_document_js_1.generateDocument;
|
|
99
|
+
TsGenerator.prototype.generateDataType = generate_data_type_js_1.generateDataType;
|
|
100
|
+
TsGenerator.prototype._generateTypeCode = generate_data_type_js_1._generateTypeCode;
|
|
101
|
+
TsGenerator.prototype._generateEnumTypeCode = generate_data_type_js_1._generateEnumTypeCode;
|
|
102
|
+
TsGenerator.prototype._generateComplexTypeCode = generate_data_type_js_1._generateComplexTypeCode;
|
|
103
|
+
TsGenerator.prototype._generateSimpleTypeCode = generate_data_type_js_1._generateSimpleTypeCode;
|
|
104
|
+
TsGenerator.prototype._generateMappedTypeCode = generate_data_type_js_1._generateMappedTypeCode;
|
|
105
|
+
TsGenerator.prototype._generateMixinTypeCode = generate_data_type_js_1._generateMixinTypeCode;
|
|
106
|
+
TsGenerator.prototype.generateHttpApi = generate_http_api_js_1.generateHttpApi;
|
|
107
|
+
TsGenerator.prototype.generateHttpController = generate_http_controller_js_1.generateHttpController;
|
|
109
108
|
})();
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import chalk from 'chalk';
|
|
4
|
+
export function cleanDirectory(dirname) {
|
|
5
|
+
const rootDir = dirname;
|
|
6
|
+
const _cleanDirectory = (targetDir) => {
|
|
7
|
+
if (!fs.existsSync(targetDir))
|
|
8
|
+
return;
|
|
9
|
+
const files = fs.readdirSync(targetDir);
|
|
10
|
+
for (const f of files) {
|
|
11
|
+
const absolutePath = path.join(targetDir, f);
|
|
12
|
+
if (fs.statSync(absolutePath).isDirectory()) {
|
|
13
|
+
_cleanDirectory(absolutePath);
|
|
14
|
+
if (!fs.readdirSync(absolutePath).length) {
|
|
15
|
+
this.emit('verbose', chalk.cyan(`Removing directory ${path.relative(absolutePath, rootDir)}`));
|
|
16
|
+
fs.rmdirSync(absolutePath);
|
|
17
|
+
}
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
if (path.extname(f) === '.ts') {
|
|
21
|
+
const contents = fs.readFileSync(absolutePath, 'utf-8');
|
|
22
|
+
if (contents.includes('#!oprimp_auto_generated!#')) {
|
|
23
|
+
this.emit('verbose', chalk.cyan(`Removing file ${path.relative(absolutePath, rootDir)}`));
|
|
24
|
+
fs.unlinkSync(absolutePath);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
_cleanDirectory(dirname);
|
|
30
|
+
}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { ComplexType, EnumType, MappedType, MixinType, SimpleType } from '@opra/common';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { CodeBlock } from '../../code-block.js';
|
|
4
|
+
import { wrapJSDocString } from '../utils/string-utils.js';
|
|
5
|
+
const internalTypeNames = ['any', 'boolean', 'bigint', 'number', 'null', 'string', 'object'];
|
|
6
|
+
export async function generateDataType(dataType, intent, currentFile) {
|
|
7
|
+
const doc = dataType.node.getDocument();
|
|
8
|
+
if (doc.id !== this._document?.id) {
|
|
9
|
+
const { generator } = await this.generateDocument(doc);
|
|
10
|
+
return await generator.generateDataType(dataType, intent, currentFile);
|
|
11
|
+
}
|
|
12
|
+
const typeName = dataType.name;
|
|
13
|
+
if (typeName) {
|
|
14
|
+
if (internalTypeNames.includes(typeName))
|
|
15
|
+
return { kind: 'internal', typeName: dataType.name };
|
|
16
|
+
let file = this._filesMap.get(dataType);
|
|
17
|
+
if (file) {
|
|
18
|
+
if (currentFile)
|
|
19
|
+
currentFile.addImport(file.filename, [typeName]);
|
|
20
|
+
return { kind: 'named', file, typeName: dataType.name };
|
|
21
|
+
}
|
|
22
|
+
if (dataType instanceof SimpleType)
|
|
23
|
+
file = this.addFile(path.join(this._documentRoot, '/simple-types.ts'), true);
|
|
24
|
+
else if (dataType instanceof EnumType)
|
|
25
|
+
file = this.addFile(path.join(this._typesRoot, 'enums', typeName + '.ts'));
|
|
26
|
+
else
|
|
27
|
+
file = this.addFile(path.join(this._typesRoot, 'types', typeName + '.ts'));
|
|
28
|
+
this._filesMap.set(dataType, file);
|
|
29
|
+
if (file.exportTypes.includes(typeName)) {
|
|
30
|
+
if (currentFile)
|
|
31
|
+
currentFile.addImport(file.filename, [typeName]);
|
|
32
|
+
return { kind: 'named', file, typeName: dataType.name };
|
|
33
|
+
}
|
|
34
|
+
file.exportTypes.push(typeName);
|
|
35
|
+
const typesIndexTs = this.addFile(path.join(this._typesRoot, 'index.ts'), true);
|
|
36
|
+
const indexTs = this.addFile('/index.ts', true);
|
|
37
|
+
indexTs.addExport(typesIndexTs.filename);
|
|
38
|
+
const codeBlock = (file.code['type_' + typeName] = new CodeBlock());
|
|
39
|
+
codeBlock.head = `/**\n * ${wrapJSDocString(dataType.description || '')}\n *`;
|
|
40
|
+
codeBlock.head += `
|
|
41
|
+
* @url ${path.posix.join(doc.url || this.serviceUrl, '$schema', '#types/' + typeName)}
|
|
42
|
+
*/
|
|
43
|
+
export `;
|
|
44
|
+
codeBlock.typeDef = (await this._generateTypeCode(file, dataType, 'root')) + '\n\n';
|
|
45
|
+
typesIndexTs.addExport(file.filename);
|
|
46
|
+
if (currentFile)
|
|
47
|
+
currentFile.addImport(file.filename, [typeName]);
|
|
48
|
+
return { kind: 'named', file, typeName };
|
|
49
|
+
}
|
|
50
|
+
if (!currentFile)
|
|
51
|
+
throw new TypeError(`You must provide currentFile to generate data type`);
|
|
52
|
+
const code = await this._generateTypeCode(currentFile, dataType, intent);
|
|
53
|
+
return { kind: 'embedded', code };
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
*
|
|
57
|
+
*/
|
|
58
|
+
export async function _generateTypeCode(currentFile, dataType, intent) {
|
|
59
|
+
if (intent === 'root' && !dataType.name) {
|
|
60
|
+
throw new TypeError(`Name required to generate data type code to root intent`);
|
|
61
|
+
}
|
|
62
|
+
if (dataType instanceof EnumType) {
|
|
63
|
+
return await this._generateEnumTypeCode(currentFile, dataType, intent);
|
|
64
|
+
}
|
|
65
|
+
if (dataType instanceof ComplexType) {
|
|
66
|
+
return await this._generateComplexTypeCode(currentFile, dataType, intent);
|
|
67
|
+
}
|
|
68
|
+
if (dataType instanceof SimpleType) {
|
|
69
|
+
return await this._generateSimpleTypeCode(currentFile, dataType, intent);
|
|
70
|
+
}
|
|
71
|
+
if (dataType instanceof MappedType) {
|
|
72
|
+
return await this._generateMappedTypeCode(currentFile, dataType, intent);
|
|
73
|
+
}
|
|
74
|
+
if (dataType instanceof MixinType) {
|
|
75
|
+
return await this._generateMixinTypeCode(currentFile, dataType, intent);
|
|
76
|
+
}
|
|
77
|
+
/* istanbul ignore next */
|
|
78
|
+
throw new TypeError(`${dataType.kind} data types can not be directly exported`);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
*
|
|
82
|
+
*/
|
|
83
|
+
export async function _generateEnumTypeCode(currentFile, dataType, intent) {
|
|
84
|
+
if (intent === 'root') {
|
|
85
|
+
let out = `enum ${dataType.name} {\n\t`;
|
|
86
|
+
for (const [value, info] of Object.entries(dataType.attributes)) {
|
|
87
|
+
// Print JSDoc
|
|
88
|
+
let jsDoc = '';
|
|
89
|
+
if (dataType.attributes[value].description)
|
|
90
|
+
jsDoc += ` * ${dataType.attributes[value].description}\n`;
|
|
91
|
+
if (jsDoc)
|
|
92
|
+
out += `/**\n${jsDoc} */\n`;
|
|
93
|
+
out +=
|
|
94
|
+
`${info.alias || value} = ` +
|
|
95
|
+
(typeof value === 'number' ? value : "'" + String(value).replace("'", "\\'") + "'");
|
|
96
|
+
out += ',\n\n';
|
|
97
|
+
}
|
|
98
|
+
return out + '\b}';
|
|
99
|
+
}
|
|
100
|
+
return ('(' +
|
|
101
|
+
Object.keys(dataType.attributes)
|
|
102
|
+
.map(t => `'${t}'`)
|
|
103
|
+
.join(' | ') +
|
|
104
|
+
')');
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
*
|
|
108
|
+
*/
|
|
109
|
+
export async function _generateComplexTypeCode(currentFile, dataType, intent) {
|
|
110
|
+
let out = intent === 'root' ? `interface ${dataType.name} ` : '';
|
|
111
|
+
const ownFields = [...dataType.fields.values()].filter(f => f.origin === dataType);
|
|
112
|
+
if (dataType.base) {
|
|
113
|
+
const base = await this.generateDataType(dataType.base, 'extends', currentFile);
|
|
114
|
+
let baseDef = base.kind === 'embedded' ? base.code : base.typeName;
|
|
115
|
+
const omitBaseFields = ownFields.filter(f => dataType.base.fields.has(f.name));
|
|
116
|
+
if (omitBaseFields.length)
|
|
117
|
+
baseDef = `Omit<${baseDef}, ${omitBaseFields.map(x => "'" + x.name + "'").join(' | ')}>`;
|
|
118
|
+
if (intent === 'root')
|
|
119
|
+
out += `extends ${baseDef} `;
|
|
120
|
+
else {
|
|
121
|
+
out += baseDef;
|
|
122
|
+
if (!ownFields.length)
|
|
123
|
+
return out;
|
|
124
|
+
out += ' & ';
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
out += '{\n\t';
|
|
128
|
+
let i = 0;
|
|
129
|
+
for (const field of ownFields) {
|
|
130
|
+
if (i++)
|
|
131
|
+
out += '\n';
|
|
132
|
+
// Print JSDoc
|
|
133
|
+
out += `/**\n * ${field.description || ''}\n`;
|
|
134
|
+
if (field.default)
|
|
135
|
+
out += ` * @default ` + field.default + '\n';
|
|
136
|
+
// if (field.format)
|
|
137
|
+
// jsDoc += ` * @format ` + field.format + '\n';
|
|
138
|
+
if (field.exclusive)
|
|
139
|
+
out += ` * @exclusive\n`;
|
|
140
|
+
if (field.readonly)
|
|
141
|
+
out += ` * @readonly\n`;
|
|
142
|
+
if (field.writeonly)
|
|
143
|
+
out += ` * @writeonly\n`;
|
|
144
|
+
if (field.deprecated) {
|
|
145
|
+
out += ` * @deprecated ` + (typeof field.deprecated === 'string' ? field.deprecated : '') + '\n';
|
|
146
|
+
}
|
|
147
|
+
out += ' */\n';
|
|
148
|
+
// Print field name
|
|
149
|
+
if (field.readonly)
|
|
150
|
+
out += 'readonly ';
|
|
151
|
+
out += `${field.name}${field.required ? '' : '?'}: `;
|
|
152
|
+
if (field.fixed) {
|
|
153
|
+
const t = typeof field.fixed;
|
|
154
|
+
out += `${t === 'number' || t === 'boolean' || t === 'bigint' ? field.fixed : "'" + field.fixed + "'"}\n`;
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
const x = await this.generateDataType(field.type, 'typeDef', currentFile);
|
|
158
|
+
out += (x.kind === 'embedded' ? x.code : x.typeName) + `${field.isArray ? '[]' : ''};\n`;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (dataType.additionalFields)
|
|
162
|
+
out += '[key: string]: any;\n';
|
|
163
|
+
return out + '\b}';
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
*
|
|
167
|
+
*/
|
|
168
|
+
export async function _generateSimpleTypeCode(currentFile, dataType, intent) {
|
|
169
|
+
let out = intent === 'root' ? `type ${dataType.name} = ` : '';
|
|
170
|
+
out += dataType.nameMappings.js || 'any';
|
|
171
|
+
return intent === 'root' ? out + ';' : out;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
*
|
|
175
|
+
*/
|
|
176
|
+
export async function _generateMixinTypeCode(currentFile, dataType, intent) {
|
|
177
|
+
const outArray = [];
|
|
178
|
+
for (const t of dataType.types) {
|
|
179
|
+
const x = await this.generateDataType(t, 'typeDef', currentFile);
|
|
180
|
+
if (x.kind === 'embedded') {
|
|
181
|
+
outArray.push(x.code.includes('|') ? '(' + x.code + ')' : x.code);
|
|
182
|
+
}
|
|
183
|
+
else
|
|
184
|
+
outArray.push(x.typeName);
|
|
185
|
+
}
|
|
186
|
+
if (intent === 'root')
|
|
187
|
+
return `type ${dataType.name} = ${outArray.join(' & ')}`;
|
|
188
|
+
if (intent === 'extends')
|
|
189
|
+
return outArray.join(', ');
|
|
190
|
+
return outArray.join(' & ');
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
*
|
|
194
|
+
*/
|
|
195
|
+
export async function _generateMappedTypeCode(currentFile, dataType, intent) {
|
|
196
|
+
let out = intent === 'root' ? `type ${dataType.name} = ` : '';
|
|
197
|
+
const base = await this.generateDataType(dataType.base, 'typeDef', currentFile);
|
|
198
|
+
const typeDef = base.kind === 'embedded' ? base.code : base.typeName;
|
|
199
|
+
const pick = dataType.pick?.length ? dataType.pick : undefined;
|
|
200
|
+
const omit = !pick && dataType.omit?.length ? dataType.omit : undefined;
|
|
201
|
+
const partial = dataType.partial === true || (Array.isArray(dataType.partial) && dataType.partial.length > 0)
|
|
202
|
+
? dataType.partial
|
|
203
|
+
: undefined;
|
|
204
|
+
const required = dataType.required === true || (Array.isArray(dataType.required) && dataType.required.length > 0)
|
|
205
|
+
? dataType.required
|
|
206
|
+
: undefined;
|
|
207
|
+
if (!(pick || omit || partial || required))
|
|
208
|
+
return typeDef;
|
|
209
|
+
if (partial === true)
|
|
210
|
+
out += 'Partial<';
|
|
211
|
+
else if (partial) {
|
|
212
|
+
out += 'PartialSome<';
|
|
213
|
+
currentFile.addExport('ts-gems', ['PartialSome']);
|
|
214
|
+
}
|
|
215
|
+
if (required === true)
|
|
216
|
+
out += 'Partial<';
|
|
217
|
+
else if (required) {
|
|
218
|
+
out += 'RequiredSome<';
|
|
219
|
+
currentFile.addExport('ts-gems', ['RequiredSome']);
|
|
220
|
+
}
|
|
221
|
+
if (pick)
|
|
222
|
+
out += 'Pick<';
|
|
223
|
+
else if (omit)
|
|
224
|
+
out += 'Omit<';
|
|
225
|
+
out += typeDef;
|
|
226
|
+
if (omit || pick) {
|
|
227
|
+
out +=
|
|
228
|
+
', ' +
|
|
229
|
+
(omit || pick)
|
|
230
|
+
.filter(x => !!x)
|
|
231
|
+
.map(x => `'${x}'`)
|
|
232
|
+
.join(' | ') +
|
|
233
|
+
'>';
|
|
234
|
+
}
|
|
235
|
+
if (partial) {
|
|
236
|
+
if (Array.isArray(partial)) {
|
|
237
|
+
out +=
|
|
238
|
+
', ' +
|
|
239
|
+
partial
|
|
240
|
+
.filter(x => !!x)
|
|
241
|
+
.map(x => `'${x}'`)
|
|
242
|
+
.join(' | ');
|
|
243
|
+
}
|
|
244
|
+
out += '>';
|
|
245
|
+
}
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { OpraHttpClient } from '@opra/client';
|
|
2
|
+
import { HttpApi } from '@opra/common';
|
|
3
|
+
import chalk from 'chalk';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import { pascalCase } from 'putil-varhelpers';
|
|
6
|
+
export async function generateDocument(document, options) {
|
|
7
|
+
if (!document || typeof document === 'string') {
|
|
8
|
+
if (document) {
|
|
9
|
+
const out = this._documentsMap.get(document);
|
|
10
|
+
if (out)
|
|
11
|
+
return out;
|
|
12
|
+
}
|
|
13
|
+
this.emit('log', chalk.cyan('Fetching document schema from ') + chalk.blueBright(this.serviceUrl));
|
|
14
|
+
const client = new OpraHttpClient(this.serviceUrl);
|
|
15
|
+
document = await client.fetchDocument({ documentId: document });
|
|
16
|
+
}
|
|
17
|
+
this._document = document;
|
|
18
|
+
let out = this._documentsMap.get(document.id);
|
|
19
|
+
if (out)
|
|
20
|
+
return out;
|
|
21
|
+
out = {
|
|
22
|
+
document,
|
|
23
|
+
generator: this,
|
|
24
|
+
};
|
|
25
|
+
this._documentsMap.set(document.id, out);
|
|
26
|
+
this.emit('log', chalk.white('[' + document.id + '] ') + chalk.cyan('Processing document ') + chalk.magenta(document.info.title));
|
|
27
|
+
if (document.references.size) {
|
|
28
|
+
this.emit('log', chalk.white('[' + document.id + '] ') + chalk.cyan(`Processing references`));
|
|
29
|
+
for (const ref of document.references.values()) {
|
|
30
|
+
const generator = this.extend();
|
|
31
|
+
generator._document = ref;
|
|
32
|
+
generator._documentRoot = '/references/' + (ref.info.title ? pascalCase(ref.info.title) : ref.id);
|
|
33
|
+
generator._typesRoot = path.join(generator._documentRoot, 'models');
|
|
34
|
+
await generator.generateDocument(ref, { typesOnly: true });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
this._fileHeaderDocInfo = `/*
|
|
38
|
+
* ${document.info.title}
|
|
39
|
+
* Id: ${document.id}
|
|
40
|
+
* Version: ${document.info.version}
|
|
41
|
+
* ${this.serviceUrl}
|
|
42
|
+
*/`;
|
|
43
|
+
if (document.types.size) {
|
|
44
|
+
this.emit('log', chalk.white('[' + document.id + ']'), chalk.cyan(`Processing data types`));
|
|
45
|
+
for (const t of document.types.values()) {
|
|
46
|
+
await this.generateDataType(t, 'root');
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (options?.typesOnly)
|
|
50
|
+
return out;
|
|
51
|
+
if (document.api instanceof HttpApi) {
|
|
52
|
+
await this.generateHttpApi(document.api);
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { camelCase, pascalCase } from 'putil-varhelpers';
|
|
3
|
+
import { CodeBlock } from '../../code-block.js';
|
|
4
|
+
import { httpControllerNodeScript } from '../http-controller-node.js';
|
|
5
|
+
import { wrapJSDocString } from '../utils/string-utils.js';
|
|
6
|
+
export async function generateHttpApi(api) {
|
|
7
|
+
let file = this._filesMap.get(api);
|
|
8
|
+
if (file)
|
|
9
|
+
return file;
|
|
10
|
+
const className = api.name ? pascalCase(api.name) : 'Api';
|
|
11
|
+
file = this.addFile(className + '.ts');
|
|
12
|
+
file.addImport('@opra/client', ['kClient', 'OpraHttpClient']);
|
|
13
|
+
const indexTs = this.addFile('/index.ts', true);
|
|
14
|
+
indexTs.addExport('.' + file.filename);
|
|
15
|
+
const httpApiNodeFile = this.addFile('./http-controller-node.ts');
|
|
16
|
+
httpApiNodeFile.code.content = httpControllerNodeScript;
|
|
17
|
+
const classBlock = (file.code[className] = new CodeBlock());
|
|
18
|
+
classBlock.doc = `/**
|
|
19
|
+
* ${wrapJSDocString(api.description || '')}
|
|
20
|
+
* @class ${className}
|
|
21
|
+
* @url ${path.posix.join(this.serviceUrl, '$schema')}
|
|
22
|
+
*/`;
|
|
23
|
+
classBlock.head = `\nexport class ${className} {\n\t`;
|
|
24
|
+
classBlock.properties = 'readonly [kClient]: OpraHttpClient;';
|
|
25
|
+
const classConstBlock = (classBlock.classConstBlock = new CodeBlock());
|
|
26
|
+
classConstBlock.head = `\n\nconstructor(client: OpraHttpClient) {`;
|
|
27
|
+
classConstBlock.body = `\n\tthis[kClient] = client;`;
|
|
28
|
+
classConstBlock.tail = `\b\n}\n`;
|
|
29
|
+
for (const controller of api.controllers.values()) {
|
|
30
|
+
const generator = this.extend();
|
|
31
|
+
const f = await generator.generateHttpController(controller);
|
|
32
|
+
const childClassName = pascalCase(controller.name) + 'Controller';
|
|
33
|
+
file.addImport('.' + f.filename, [childClassName]);
|
|
34
|
+
const property = '$' + controller.name.charAt(0).toLowerCase() + camelCase(controller.name.substring(1));
|
|
35
|
+
classBlock.properties += `\nreadonly ${property}: ${childClassName};`;
|
|
36
|
+
classConstBlock.body += `\nthis.${property} = new ${childClassName}(client);`;
|
|
37
|
+
}
|
|
38
|
+
classBlock.tail = `\b}`;
|
|
39
|
+
return file;
|
|
40
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import typeIs from '@browsery/type-is';
|
|
3
|
+
import { MimeTypes } from '@opra/common';
|
|
4
|
+
import { camelCase, pascalCase } from 'putil-varhelpers';
|
|
5
|
+
import { CodeBlock } from '../../code-block.js';
|
|
6
|
+
import { locateNamedType } from '../utils/locate-named-type.js';
|
|
7
|
+
import { wrapJSDocString } from '../utils/string-utils.js';
|
|
8
|
+
export async function generateHttpController(controller) {
|
|
9
|
+
let file = this._filesMap.get(controller);
|
|
10
|
+
if (file)
|
|
11
|
+
return file;
|
|
12
|
+
const className = pascalCase(controller.name) + 'Controller';
|
|
13
|
+
file = this.addFile(path.join(this._apiPath, className + '.ts'));
|
|
14
|
+
file.addImport('@opra/client', ['HttpRequestObservable', 'kClient', 'OpraHttpClient']);
|
|
15
|
+
file.addImport(path.relative(file.dirname, '/http-controller-node.ts'), ['HttpControllerNode']);
|
|
16
|
+
const classBlock = (file.code[className] = new CodeBlock());
|
|
17
|
+
classBlock.doc = `/**
|
|
18
|
+
* ${wrapJSDocString(controller.description || '')}
|
|
19
|
+
* @class ${className}
|
|
20
|
+
* @url ${path.posix.join(this.serviceUrl, '$schema', '#resources/' + className)}
|
|
21
|
+
*/`;
|
|
22
|
+
classBlock.head = `\nexport class ${className} extends HttpControllerNode {\n\t`;
|
|
23
|
+
classBlock.properties = '';
|
|
24
|
+
const classConstBlock = (classBlock.classConstBlock = new CodeBlock());
|
|
25
|
+
classConstBlock.head = `\n\nconstructor(client: OpraHttpClient) {`;
|
|
26
|
+
classConstBlock.body = `\n\tsuper(client);`;
|
|
27
|
+
classConstBlock.tail = `\b\n}\n`;
|
|
28
|
+
if (controller.controllers.size) {
|
|
29
|
+
for (const child of controller.controllers.values()) {
|
|
30
|
+
const generator = this.extend();
|
|
31
|
+
generator._apiPath = path.join(this._apiPath, className);
|
|
32
|
+
const f = await generator.generateHttpController(child);
|
|
33
|
+
const childClassName = pascalCase(child.name) + 'Controller';
|
|
34
|
+
file.addImport(f.filename, [childClassName]);
|
|
35
|
+
const property = '$' + child.name.charAt(0).toLowerCase() + camelCase(child.name.substring(1));
|
|
36
|
+
classBlock.properties += `\nreadonly ${property}: ${childClassName};`;
|
|
37
|
+
classConstBlock.body += `\nthis.${property} = new ${childClassName}(client);`;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Process operations */
|
|
41
|
+
for (const operation of controller.operations.values()) {
|
|
42
|
+
const operationBlock = (classBlock['operation_' + operation.name] = new CodeBlock());
|
|
43
|
+
operationBlock.doc = `
|
|
44
|
+
/**
|
|
45
|
+
* ${wrapJSDocString(operation.description || operation.name + ' operation')}`;
|
|
46
|
+
if (operation.parameters.length) {
|
|
47
|
+
const block = new CodeBlock();
|
|
48
|
+
block.doc = '\n *\n * RegExp parameters:';
|
|
49
|
+
let i = 0;
|
|
50
|
+
for (const prm of operation.parameters) {
|
|
51
|
+
if (!(prm.name instanceof RegExp))
|
|
52
|
+
continue;
|
|
53
|
+
i++;
|
|
54
|
+
block.doc +=
|
|
55
|
+
`\n * > ${String(prm.name)} - ${prm.description || ''}` +
|
|
56
|
+
`\n * - location: ${prm.location}` +
|
|
57
|
+
`\n * - type: ${locateNamedType(prm.type)?.name || 'any'}${prm.isArray ? '[' + prm.arraySeparator + ']' : ''}` +
|
|
58
|
+
(prm.required ? `\n * required: ${prm.required}` : '') +
|
|
59
|
+
(prm.deprecated ? `\n * deprecated: ${prm.deprecated}` : '');
|
|
60
|
+
}
|
|
61
|
+
if (i)
|
|
62
|
+
operationBlock.doc += block;
|
|
63
|
+
}
|
|
64
|
+
operationBlock.doc += `\n */\n`;
|
|
65
|
+
operationBlock.head = `${operation.name}(`;
|
|
66
|
+
/** Process operation parameters */
|
|
67
|
+
const mergedParams = [...controller.parameters, ...operation.parameters];
|
|
68
|
+
const pathParams = [];
|
|
69
|
+
const queryParams = [];
|
|
70
|
+
const headerParams = [];
|
|
71
|
+
if (mergedParams.length) {
|
|
72
|
+
const pathParamsMap = {};
|
|
73
|
+
const queryParamsMap = {};
|
|
74
|
+
const headerParamsMap = {};
|
|
75
|
+
for (const prm of mergedParams) {
|
|
76
|
+
if (typeof prm.name !== 'string')
|
|
77
|
+
continue;
|
|
78
|
+
if (prm.location === 'path')
|
|
79
|
+
pathParamsMap[prm.name] = prm;
|
|
80
|
+
if (prm.location === 'query')
|
|
81
|
+
queryParamsMap[prm.name] = prm;
|
|
82
|
+
if (prm.location === 'header')
|
|
83
|
+
headerParamsMap[prm.name] = prm;
|
|
84
|
+
}
|
|
85
|
+
pathParams.push(...Object.values(pathParamsMap));
|
|
86
|
+
queryParams.push(...Object.values(queryParamsMap));
|
|
87
|
+
headerParams.push(...Object.values(headerParamsMap));
|
|
88
|
+
}
|
|
89
|
+
let argIndex = 0;
|
|
90
|
+
for (const prm of pathParams) {
|
|
91
|
+
let typeName;
|
|
92
|
+
if (prm.type) {
|
|
93
|
+
const xt = await this.generateDataType(prm.type, 'typeDef', file);
|
|
94
|
+
typeName = xt.kind === 'embedded' ? xt.code : xt.typeName;
|
|
95
|
+
}
|
|
96
|
+
else
|
|
97
|
+
typeName = `any`;
|
|
98
|
+
if (argIndex++ > 0)
|
|
99
|
+
operationBlock.head += ', ';
|
|
100
|
+
operationBlock.head += `${prm.name}: ${typeName}`;
|
|
101
|
+
}
|
|
102
|
+
let hasBody = false;
|
|
103
|
+
if (operation.requestBody?.content.length) {
|
|
104
|
+
if (argIndex++ > 0)
|
|
105
|
+
operationBlock.head += ', ';
|
|
106
|
+
let typeArr = [];
|
|
107
|
+
for (const content of operation.requestBody.content) {
|
|
108
|
+
if (content.type) {
|
|
109
|
+
const xt = await this.generateDataType(content.type, 'typeDef', file);
|
|
110
|
+
let typeDef = xt.kind === 'embedded' ? xt.code : xt.typeName;
|
|
111
|
+
if (typeDef === 'any') {
|
|
112
|
+
typeArr = [];
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
if (typeDef) {
|
|
116
|
+
if (operation.requestBody.partial) {
|
|
117
|
+
file.addImport('ts-gems', ['PartialDTO']);
|
|
118
|
+
typeDef = `PartialDTO<${typeDef}>`;
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
file.addImport('ts-gems', ['DTO']);
|
|
122
|
+
typeDef = `DTO<${typeDef}>`;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
typeDef = typeDef || 'undefined';
|
|
126
|
+
if (!typeArr.includes(typeDef))
|
|
127
|
+
typeArr.push(typeDef);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
typeArr = [];
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
operationBlock.head += `$body: ${typeArr.join(' | ') || 'any'}`;
|
|
134
|
+
hasBody = true;
|
|
135
|
+
}
|
|
136
|
+
/** process query params */
|
|
137
|
+
const isQueryRequired = queryParams.find(p => p.required);
|
|
138
|
+
const isHeadersRequired = queryParams.find(p => p.required);
|
|
139
|
+
if (queryParams.length) {
|
|
140
|
+
if (argIndex++ > 0)
|
|
141
|
+
operationBlock.head += ', ';
|
|
142
|
+
operationBlock.head += '\n\t$params' + (isHeadersRequired || isQueryRequired ? '' : '?') + ': {\n\t';
|
|
143
|
+
for (const prm of queryParams) {
|
|
144
|
+
operationBlock.head += `/**\n * ${prm.description || ''}\n */\n`;
|
|
145
|
+
operationBlock.head += `${prm.name}${prm.required ? '' : '?'}: `;
|
|
146
|
+
if (prm.type) {
|
|
147
|
+
const xt = await this.generateDataType(prm.type, 'typeDef', file);
|
|
148
|
+
const typeDef = xt.kind === 'embedded' ? xt.code : xt.typeName;
|
|
149
|
+
operationBlock.head += `${typeDef};\n`;
|
|
150
|
+
}
|
|
151
|
+
else
|
|
152
|
+
operationBlock.head += `any;\n`;
|
|
153
|
+
}
|
|
154
|
+
operationBlock.head += '\b}\b';
|
|
155
|
+
}
|
|
156
|
+
/** process header params */
|
|
157
|
+
if (headerParams.length) {
|
|
158
|
+
if (argIndex++ > 0)
|
|
159
|
+
operationBlock.head += ', \n';
|
|
160
|
+
operationBlock.head += '\t$headers' + (isHeadersRequired ? '' : '?') + ': {\n\t';
|
|
161
|
+
for (const prm of headerParams) {
|
|
162
|
+
operationBlock.head += `/**\n * ${prm.description || ''}\n */\n`;
|
|
163
|
+
operationBlock.head += `${prm.name}${prm.required ? '' : '?'}: `;
|
|
164
|
+
if (prm.type) {
|
|
165
|
+
const xt = await this.generateDataType(prm.type, 'typeDef', file);
|
|
166
|
+
const typeDef = xt.kind === 'embedded' ? xt.code : xt.typeName;
|
|
167
|
+
operationBlock.head += `${typeDef};\n`;
|
|
168
|
+
}
|
|
169
|
+
else
|
|
170
|
+
operationBlock.head += `any;\n`;
|
|
171
|
+
}
|
|
172
|
+
operationBlock.head += '\b}\b';
|
|
173
|
+
}
|
|
174
|
+
/* Determine return type */
|
|
175
|
+
const returnTypes = [];
|
|
176
|
+
let typeDef = '';
|
|
177
|
+
for (const resp of operation.responses) {
|
|
178
|
+
if (!resp.statusCode.find(r => r.intersects(200, 299)))
|
|
179
|
+
continue;
|
|
180
|
+
typeDef = '';
|
|
181
|
+
if (resp.type) {
|
|
182
|
+
const xt = await this.generateDataType(resp.type, 'typeDef', file);
|
|
183
|
+
typeDef = xt.kind === 'embedded' ? xt.code : xt.typeName;
|
|
184
|
+
}
|
|
185
|
+
if (typeDef) {
|
|
186
|
+
if (typeDef !== 'OperationResult') {
|
|
187
|
+
if (resp.partial) {
|
|
188
|
+
file.addImport('ts-gems', ['PartialDTO']);
|
|
189
|
+
typeDef = `PartialDTO<${typeDef}>`;
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
file.addImport('ts-gems', ['DTO']);
|
|
193
|
+
typeDef = `DTO<${typeDef}>`;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (resp.contentType && typeIs.is(String(resp.contentType), [MimeTypes.opra_response_json])) {
|
|
198
|
+
file.addImport('@opra/common', ['OperationResult']);
|
|
199
|
+
typeDef = typeDef ? `OperationResult<${typeDef}>` : 'OperationResult';
|
|
200
|
+
}
|
|
201
|
+
typeDef = typeDef || 'undefined';
|
|
202
|
+
if (!returnTypes.includes(typeDef))
|
|
203
|
+
returnTypes.push(typeDef);
|
|
204
|
+
}
|
|
205
|
+
operationBlock.head += `\n): HttpRequestObservable<${returnTypes.join(' | ') || 'any'}>{`;
|
|
206
|
+
operationBlock.body = `\n\t`;
|
|
207
|
+
operationBlock.body +=
|
|
208
|
+
`const url = this._prepareUrl('${operation.getFullUrl()}', {` + pathParams.map(p => p.name).join(', ') + '});';
|
|
209
|
+
operationBlock.body +=
|
|
210
|
+
`\nreturn this[kClient].request(url, { method: '${operation.method}'` +
|
|
211
|
+
(hasBody ? ', body: $body' : '') +
|
|
212
|
+
(queryParams.length ? ', params: $params as any' : '') +
|
|
213
|
+
(headerParams.length ? ', headers: $headers as any' : '') +
|
|
214
|
+
'});';
|
|
215
|
+
operationBlock.tail = `\b\n};\n`;
|
|
216
|
+
}
|
|
217
|
+
classBlock.tail = `\b}`;
|
|
218
|
+
return file;
|
|
219
|
+
}
|