Files
openstapps/packages/core-tools/src/schema.ts

86 lines
2.8 KiB
TypeScript

/*
* Copyright (C) 2018, 2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import Ajv, {JSONSchemaType} from 'ajv';
import {
Config,
DEFAULT_CONFIG,
SchemaGenerator,
createParser,
createFormatter,
createProgram,
} from 'ts-json-schema-generator';
import {getTsconfigPath} from './common.js';
import {definitionsOf, lightweightProjectFromPath} from '@openstapps/easy-ast';
import path from 'path';
/**
* StAppsCore converter
*
* Converts TypeScript source files to JSON schema files
*/
export class Converter {
private readonly generator: SchemaGenerator;
private readonly schemaValidator: Ajv.default;
/**
* @param projectPath Path to the project
* @param sourcePath Path to optionally point to a different directory of / or single source file
*/
constructor(projectPath: string, sourcePath?: string) {
const config: Config = {
...DEFAULT_CONFIG,
path: sourcePath,
tsconfig: path.join(getTsconfigPath(projectPath), 'tsconfig.json'),
};
const program = createProgram(config);
this.generator = new SchemaGenerator(program, createParser(program, config), createFormatter(config));
this.schemaValidator = new Ajv.default();
}
/**
* Get schema for specific StAppsCore type
* @param type Type to get the schema for
* @param _version Version to set for the schema
* @returns Generated schema
*/
getSchema(type: string, _version: string): JSONSchemaType<unknown> {
const schema = this.generator.createSchema(type) as JSONSchemaType<unknown>;
this.schemaValidator.validateSchema(schema, true);
return schema;
}
}
/**
* Get a list of validatable types from an API extractor file
*/
export function getValidatableTypesInPath(path: string): string[] {
return Object.values(definitionsOf(lightweightProjectFromPath(path)))
.filter(type => !!type.comment?.tags?.find(it => it.name === 'validatable'))
.map(type => type.name);
}
/**
* Merge multiple schemas
*/
export function mergeSchemas(schemas: JSONSchemaType<unknown>[]): JSONSchemaType<unknown> {
const completeSchema = {definitions: {}} as JSONSchemaType<unknown>;
for (const schema of schemas) {
Object.assign(completeSchema.definitions!, schema.definitions);
}
return completeSchema;
}