-
Notifications
You must be signed in to change notification settings - Fork 431
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(codegen): add CLI to generate types given a codegen config
- Loading branch information
Showing
14 changed files
with
409 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import {readFile} from 'fs/promises' | ||
import * as json5 from 'json5' | ||
import * as z from 'zod' | ||
|
||
export const configDefintion = z.object({ | ||
path: z.string().or(z.array(z.string())).default('./src/**/*.{ts,tsx,js,jsx}'), | ||
schema: z.string().default('./schema.json'), | ||
generates: z.string().default('./sanity.types.ts'), | ||
}) | ||
|
||
export type CodegenConfig = z.infer<typeof configDefintion> | ||
|
||
export async function readConfig(path: string): Promise<CodegenConfig> { | ||
try { | ||
const content = await readFile(path, 'utf-8') | ||
const json = json5.parse(content) | ||
return configDefintion.parseAsync(json) | ||
} catch (error) { | ||
if (error instanceof z.ZodError) { | ||
throw new Error(`Error in config file\n ${error.errors.map((err) => err.message).join('\n')}`) | ||
} | ||
if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') { | ||
return configDefintion.parse({}) | ||
} | ||
|
||
throw error | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
16 changes: 16 additions & 0 deletions
16
packages/sanity/src/_internal/cli/actions/codegen/generateTypes.telemetry.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import {defineTrace} from '@sanity/telemetry' | ||
|
||
interface TypesGeneratedTraceAttrubutes { | ||
outputSize: number | ||
queryTypes: number | ||
schemaTypes: number | ||
files: number | ||
filesWithErrors: number | ||
unknownTypes: number | ||
} | ||
|
||
export const TypesGeneratedTrace = defineTrace<TypesGeneratedTraceAttrubutes>({ | ||
name: 'Types Generated', | ||
version: 0, | ||
description: 'Trace emitted when generating TypeScript types for queries', | ||
}) |
137 changes: 137 additions & 0 deletions
137
packages/sanity/src/_internal/cli/actions/codegen/generateTypesAction.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
import {constants, open} from 'node:fs/promises' | ||
import {dirname, join} from 'node:path' | ||
|
||
import {type CliCommandArguments, type CliCommandContext} from '@sanity/cli' | ||
import {readConfig} from '@sanity/codegen' | ||
import readPkgUp from 'read-pkg-up' | ||
import {Worker} from 'worker_threads' | ||
|
||
import { | ||
type CodegenGenerateTypesWorkerData, | ||
type CodegenGenerateTypesWorkerMessage, | ||
} from '../../threads/codegenGenerateTypes' | ||
import {TypesGeneratedTrace} from './generateTypes.telemetry' | ||
|
||
export interface CodegenGenerateTypesCommandFlags { | ||
configPath?: string | ||
} | ||
|
||
export default async function codegenGenerateAction( | ||
args: CliCommandArguments<CodegenGenerateTypesCommandFlags>, | ||
context: CliCommandContext, | ||
): Promise<void> { | ||
const flags = args.extOptions | ||
const {output, workDir, telemetry} = context | ||
|
||
const trace = telemetry.trace(TypesGeneratedTrace) | ||
trace.start() | ||
|
||
const codegenConfig = await readConfig(flags.configPath || 'sanity-codegen.json') | ||
|
||
const rootPkgPath = readPkgUp.sync({cwd: __dirname})?.path | ||
if (!rootPkgPath) { | ||
throw new Error('Could not find root directory for `sanity` package') | ||
} | ||
|
||
const workerPath = join( | ||
dirname(rootPkgPath), | ||
'lib', | ||
'_internal', | ||
'cli', | ||
'threads', | ||
'codegenGenerateTypes.js', | ||
) | ||
|
||
const spinner = output.spinner({}).start('Generating types') | ||
|
||
const worker = new Worker(workerPath, { | ||
workerData: { | ||
workDir, | ||
schemaPath: codegenConfig.schema, | ||
searchPath: codegenConfig.path, | ||
} satisfies CodegenGenerateTypesWorkerData, | ||
// eslint-disable-next-line no-process-env | ||
env: process.env, | ||
}) | ||
|
||
const typeFile = await open( | ||
join(process.cwd(), codegenConfig.generates), | ||
// eslint-disable-next-line no-bitwise | ||
constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY, | ||
) | ||
|
||
typeFile.write('// This file is generated by `sanity codegen generate`\n') | ||
|
||
const stats = { | ||
files: 0, | ||
errors: 0, | ||
queries: 0, | ||
schemas: 0, | ||
unknownTypes: 0, | ||
size: 0, | ||
} | ||
|
||
await new Promise<void>((resolve, reject) => { | ||
worker.addListener('message', (msg: CodegenGenerateTypesWorkerMessage) => { | ||
if (msg.type === 'error') { | ||
trace.error(msg.error) | ||
|
||
if (msg.fatal) { | ||
reject(msg.error) | ||
return | ||
} | ||
const errorMessage = msg.filename | ||
? `${msg.error.message} in "${msg.filename}"` | ||
: msg.error.message | ||
spinner.fail(errorMessage) | ||
stats.errors++ | ||
return | ||
} | ||
if (msg.type === 'complete') { | ||
resolve() | ||
return | ||
} | ||
|
||
let fileTypeString = `// ${msg.filename}\n` | ||
|
||
if (msg.type === 'schema') { | ||
stats.schemas += msg.length | ||
fileTypeString += `${msg.schema}\n\n` | ||
typeFile.write(fileTypeString) | ||
return | ||
} | ||
|
||
stats.files++ | ||
for (const {queryName, query, type, unknownTypes} of msg.types) { | ||
fileTypeString += `// ${queryName}\n` | ||
fileTypeString += `// ${query.replace(/(\r\n|\n|\r)/gm, '')}\n` | ||
fileTypeString += `${type}\n` | ||
stats.queries++ | ||
stats.unknownTypes += unknownTypes | ||
} | ||
typeFile.write(`${fileTypeString}\n`) | ||
stats.size += Buffer.byteLength(fileTypeString) | ||
}) | ||
worker.addListener('error', reject) | ||
}) | ||
|
||
typeFile.close() | ||
|
||
trace.log({ | ||
outputSize: stats.size, | ||
queryTypes: stats.queries, | ||
schemaTypes: stats.schemas, | ||
files: stats.files, | ||
filesWithErrors: stats.errors, | ||
unknownTypes: stats.unknownTypes, | ||
}) | ||
|
||
trace.complete() | ||
if (stats.errors > 0) { | ||
spinner.warn(`Encountered errors in ${stats.errors} files while generating types`) | ||
} | ||
|
||
spinner.succeed( | ||
`Generated TypeScript types for ${stats.schemas} schema types and ${stats.queries} queries in ${stats.files} files into: ${codegenConfig.generates}`, | ||
) | ||
} |
41 changes: 41 additions & 0 deletions
41
packages/sanity/src/_internal/cli/commands/codegen/generateTypesCommand.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import {type CliCommandDefinition} from '@sanity/cli' | ||
|
||
const description = 'Generates codegen' | ||
|
||
const helpText = ` | ||
**Note**: This command is experimental and subject to change. | ||
Options | ||
--help, -h | ||
Show this help text. | ||
Examples | ||
# Generate types from a schema, generate schema with "sanity schema extract" first. | ||
sanity codegen generate-types | ||
Configuration | ||
The codegen command uses the following configuration properties from sanity-codegen.json: | ||
{ | ||
"path": "'./src/**/*.{ts,tsx,js,jsx}'" // glob pattern to your typescript files | ||
"schema": "schema.json", // path to your schema file, generated with 'sanity schema extract' command | ||
"generates": "./sanity.types.ts" // path to the file where the types will be generated | ||
} | ||
The listed properties are the default values, and can be overridden in the configuration file. | ||
` | ||
|
||
const generateTypesCodegenCommand: CliCommandDefinition = { | ||
name: 'generate-types', | ||
group: 'codegen', | ||
signature: '', | ||
description, | ||
helpText, | ||
hideFromHelp: true, | ||
action: async (args, context) => { | ||
const mod = await import('../../actions/codegen/generateTypesAction') | ||
|
||
return mod.default(args, context) | ||
}, | ||
} satisfies CliCommandDefinition | ||
|
||
export default generateTypesCodegenCommand |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.