-
Notifications
You must be signed in to change notification settings - Fork 542
/
transpileSchemaTypes.js
61 lines (56 loc) · 1.99 KB
/
transpileSchemaTypes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const { writeFileSync } = require('fs');
const path = require('path');
const { Transpiler } = require('@json-schema-tools/transpiler');
const snapManifestSchema = require('../src/json-schemas/snap-manifest.schema.json');
const npmSnapPackageJsonSchema = require('../src/json-schemas/npm-snap-package-json.schema.json');
// A comment warning against modifying generated files.
const FILE_PREFIX =
'// THIS IS A PROGRAMMATICALLY GENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n\n';
main();
/**
* Main function of the script.
*/
function main() {
[
[snapManifestSchema, 'SnapManifest'],
[npmSnapPackageJsonSchema, 'NpmSnapPackageJson'],
].forEach(([schema, primaryExportName]) => {
writeSchema(transpileSchema(schema, primaryExportName), primaryExportName);
});
}
/**
* Transpiles a given JSON schema to TypeScript.
*
* @param {object} schema - The schema JSON.
* @param {string} primaryExportName - The name of the primary export for the schema.
* @returns {string} The TypeScript source code transpiled from the schema.
*/
function transpileSchema(schema, primaryExportName) {
return FILE_PREFIX.concat(
new Transpiler(schema)
.toTypescript()
// Get rid of all export statements
.replace(/^export /gmu, '')
// Convert all interfaces to object types for Json type compatibility
.replace(/^interface (\w+) \{/gmu, 'type $1 = {')
// Export the primary schema type only
.replace(
new RegExp(`^type ${primaryExportName}`, 'mu'),
`export type ${primaryExportName}`,
)
// Add a newline because we like it better
.concat('\n'),
);
}
/**
* Writes a transpiled schema to disk.
*
* @param {string} typeSource - The TypeScript source code resulting from the transpilation.
* @param {string} primaryExportName - The name of the primary export for the schema.
*/
function writeSchema(typeSource, primaryExportName) {
writeFileSync(
path.resolve(__dirname, `../src/json-schemas/${primaryExportName}.ts`),
typeSource,
);
}