chronocat/packages/shell/scripts/codegen.cts

103 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-03-03 17:43:15 +00:00
import { dump, load } from 'js-yaml'
2024-03-03 18:28:51 +00:00
import { mkdir, readFile, writeFile } from 'node:fs/promises'
2024-03-03 17:43:15 +00:00
import { resolve } from 'node:path'
import type { Definition, PartialArgs } from 'typescript-json-schema'
import { buildGenerator, programFromConfig } from 'typescript-json-schema'
const settings: PartialArgs = {
aliasRef: true,
titles: false,
defaultProps: true,
noExtraProps: true,
propOrder: false,
required: true,
strictNullChecks: true,
skipLibCheck: true,
}
void (async () => {
console.log('Building generator...')
const generator = buildGenerator(
programFromConfig(resolve(__dirname, 'tsconfig.entity.json')),
settings,
)!
2024-03-03 18:11:06 +00:00
console.log('Generating config schema...')
const configSchema = generator.getSchemaForSymbol('ChronocatConfig')
console.log('Modifying config schema...')
configSchema.$id = 'https://chronocat.vercel.app/config-v0.schema.json'
configSchema.title = 'Chronocat 配置'
configSchema.description = 'Chronocat 配置chronocat.yml'
const schemaString = JSON.stringify(configSchema).replaceAll(
'"anyOf"',
'"type":"object","discriminator":{"propertyName":"type"},"oneOf"',
)
console.log('Writing config schema...')
void writeFile(
resolve(__dirname, '../../docs/static/config-v0.schema.json'),
schemaString,
)
console.log('Generating schemas for codegen...')
2024-03-03 17:43:15 +00:00
const schemas = generator.getUserSymbols().map((x) => ({
$id: x,
...generator.getSchemaForSymbol(x),
}))
2024-03-03 18:11:06 +00:00
console.log('Writing schemas for codegen...')
2024-03-03 18:28:51 +00:00
await mkdir(resolve(__dirname, '../generated'), {
recursive: true,
})
2024-03-03 17:43:15 +00:00
await writeFile(
resolve(__dirname, '../generated/schemas.json'),
2024-03-05 05:14:22 +00:00
JSON.stringify(schemas, null, 2).replaceAll(
'"anyOf"',
'"type":"object","discriminator":{"propertyName":"type"},"oneOf"',
),
2024-03-03 17:43:15 +00:00
)
console.log('Generating schemas for openapi...')
let oapiDefinitions = generator.getSchemaForSymbols(
generator.getUserSymbols(),
)
console.log('Modifying schemas for openapi...')
oapiDefinitions = JSON.parse(
JSON.stringify(oapiDefinitions)
.replaceAll(
'"anyOf"',
'"type":"object","discriminator":{"propertyName":"type"},"oneOf"',
)
.replaceAll('#/definitions/', '#/components/schemas/'),
) as Definition
console.log('Writing ChronocatConfig for openapi...')
const openapiSource = load(
await readFile(resolve(__dirname, '../static/openapi.yaml'), 'utf-8'),
) as {
components: {
schemas: unknown
}
}
openapiSource.components.schemas = oapiDefinitions.definitions
await writeFile(
resolve(__dirname, '../../docs/static/openapi.yaml'),
dump(openapiSource),
)
})()