import fs from 'fs-extra'; import fg from 'fast-glob'; import path from 'path'; import { pascalCase } from 'change-case'; import { getSchemaModule, getSchemaName, getSchemaRegistry, processSchemaGlob, } from '@kickstartds/jsonschema-utils'; import { createTypes as createTypings } from '@kickstartds/jsonschema2types'; const renderImportName = (schemaId: string): string => `${pascalCase(getSchemaName(schemaId))}Props`; const renderImportStatement = (schemaId: string): string => schemaId.includes('schema.kickstartds.com') ? `import type { ${pascalCase( getSchemaName(schemaId) )}Props } from '@kickstartds/${getSchemaModule( schemaId )}/lib/${getSchemaName(schemaId)}/typing'` : `import type { ${pascalCase( getSchemaName(schemaId) )}Props } from '../${getSchemaName(schemaId)}/${pascalCase( getSchemaName(schemaId) )}Props'`; const createTypes = async (schemaId: string, schemaGlob: string) => { const schemaPaths: string[] = await fg(schemaGlob); const ajv = getSchemaRegistry(); const schemaIds = await processSchemaGlob(schemaGlob, ajv, { typeResolution: false, modules: ['base', 'blog', 'form'], mergeAllOf: false, }); // TODO `style` should be loaded from `${root}/.prettierrc` again // https://github.com/kickstartDS/schema/issues/15 const types: Record = await createTypings( schemaIds, renderImportName, renderImportStatement, ajv, { bannerComment: '/* eslint-disable */\n/**\n* This file was automatically generated by json-schema-to-typescript.\n* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,\n* and run `yarn run schema` to regenerate this file.\n*/', style: { singleQuote: true, printWidth: 80, }, } ); const module = getSchemaModule(schemaId); const moduleSchemaIds = Object.keys(types).filter((schemaId) => schemaId.startsWith(`http://schema.kickstartds.com/${module}/`) ); for (const schemaId of moduleSchemaIds) { const directPath: string | undefined = schemaPaths.find((schemaPath) => schemaPath.endsWith(`/${schemaId.split('/').pop()}` || 'NO MATCH') ); const indirectPath: string | undefined = schemaPaths.find((schemaPath) => schemaId.includes(`/${module}/${schemaPath.split('/')[1]}/`) ); if (!directPath && !indirectPath) { throw new Error( `Couldn't find matching schema path for schema $id: ${schemaId}` ); } const base = directPath ? path.basename(directPath, '.json') : getSchemaName(schemaId); const dir = path.dirname(directPath || indirectPath); fs.writeFile( `${dir}/${pascalCase( base.replace(/\.(schema|definitions|interface)$/, '') )}Props.ts`, types[schemaId] ); } }; export { createTypes };