@sanity/codegen 5.7.0 → 5.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_exports/index.js +1 -0
- package/dist/_exports/index.js.map +1 -1
- package/dist/commands/typegen/generate.js +3 -1
- package/dist/commands/typegen/generate.js.map +1 -1
- package/dist/index.d.ts +21 -14
- package/dist/readConfig.js +1 -1
- package/dist/readConfig.js.map +1 -1
- package/oclif.config.js +12 -0
- package/oclif.manifest.json +1 -1
- package/package.json +3 -2
package/dist/_exports/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/_exports/index.ts"],"sourcesContent":["export {\n type CodegenConfig,\n configDefinition,\n readConfig,\n type TypeGenConfig,\n} from '../readConfig.js'\nexport {readSchema} from '../readSchema.js'\nexport {safeParseQuery} from '../safeParseQuery.js'\nexport {findQueriesInPath} from '../typescript/findQueriesInPath.js'\nexport {findQueriesInSource} from '../typescript/findQueriesInSource.js'\nexport {getResolver} from '../typescript/moduleResolver.js'\nexport {registerBabel} from '../typescript/registerBabel.js'\nexport {\n type GenerateTypesOptions,\n TypeGenerator,\n type TypegenWorkerChannel,\n} from '../typescript/typeGenerator.js'\nexport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n type ExtractedQuery,\n QueryExtractionError,\n} from '../typescript/types.js'\nexport {type FilterByType, type Get} from '../typeUtils.js'\n"],"names":["configDefinition","readConfig","readSchema","safeParseQuery","findQueriesInPath","findQueriesInSource","getResolver","registerBabel","TypeGenerator","QueryExtractionError"],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"sources":["../../src/_exports/index.ts"],"sourcesContent":["export {TypegenGenerateCommand} from '../commands/typegen/generate.js'\nexport {\n type CodegenConfig,\n configDefinition,\n readConfig,\n type TypeGenConfig,\n} from '../readConfig.js'\nexport {readSchema} from '../readSchema.js'\nexport {safeParseQuery} from '../safeParseQuery.js'\nexport {findQueriesInPath} from '../typescript/findQueriesInPath.js'\nexport {findQueriesInSource} from '../typescript/findQueriesInSource.js'\nexport {getResolver} from '../typescript/moduleResolver.js'\nexport {registerBabel} from '../typescript/registerBabel.js'\nexport {\n type GenerateTypesOptions,\n TypeGenerator,\n type TypegenWorkerChannel,\n} from '../typescript/typeGenerator.js'\nexport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n type ExtractedQuery,\n QueryExtractionError,\n} from '../typescript/types.js'\nexport {type FilterByType, type Get} from '../typeUtils.js'\n"],"names":["TypegenGenerateCommand","configDefinition","readConfig","readSchema","safeParseQuery","findQueriesInPath","findQueriesInSource","getResolver","registerBabel","TypeGenerator","QueryExtractionError"],"mappings":"AAAA,SAAQA,sBAAsB,QAAO,kCAAiC;AACtE,SAEEC,gBAAgB,EAChBC,UAAU,QAEL,mBAAkB;AACzB,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,iBAAiB,QAAO,qCAAoC;AACpE,SAAQC,mBAAmB,QAAO,uCAAsC;AACxE,SAAQC,WAAW,QAAO,kCAAiC;AAC3D,SAAQC,aAAa,QAAO,iCAAgC;AAC5D,SAEEC,aAAa,QAER,iCAAgC;AACvC,SAKEC,oBAAoB,QACf,yBAAwB"}
|
|
@@ -33,7 +33,9 @@ ${chalk.bold('Note:')}
|
|
|
33
33
|
- The \`sanity schema extract\` command is a prerequisite for extracting your Sanity Studio schema into a \`schema.json\` file, which is then used by the \`sanity typegen generate\` command to generate type definitions.
|
|
34
34
|
- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.`.trim();
|
|
35
35
|
const debug = subdebug('typegen:generate');
|
|
36
|
-
|
|
36
|
+
/**
|
|
37
|
+
* @internal
|
|
38
|
+
*/ export class TypegenGenerateCommand extends SanityCommand {
|
|
37
39
|
static description = description;
|
|
38
40
|
static examples = [
|
|
39
41
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/typegen/generate.ts"],"sourcesContent":["import {mkdir, stat, writeFile} from 'node:fs/promises'\nimport {dirname, isAbsolute, join} from 'node:path'\nimport {env} from 'node:process'\nimport {Worker} from 'node:worker_threads'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand, subdebug} from '@sanity/cli-core'\nimport {chalk, spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {generatedFileWarning} from '../../actions/generatedFileWarning.js'\nimport {\n type TypegenGenerateTypesWorkerData,\n type TypegenWorkerChannel,\n} from '../../actions/types.js'\nimport {configDefinition, readConfig, type TypeGenConfig} from '../../readConfig.js'\nimport {count} from '../../utils/count.js'\nimport {formatPath} from '../../utils/formatPath.js'\nimport {getMessage} from '../../utils/getMessage.js'\nimport {percent} from '../../utils/percent.js'\n\nconst description = `Sanity TypeGen (Beta)\nThis command is currently in beta and may undergo significant changes. Feedback is welcome!\n\n${chalk.bold('Configuration:')}\nThis command can utilize configuration settings defined in a \\`sanity-typegen.json\\` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the \\`sanity schema extract\\` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your \\`sanity-typegen.json\\` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\n${chalk.bold('Note:')}\n- The \\`sanity schema extract\\` command is a prerequisite for extracting your Sanity Studio schema into a \\`schema.json\\` file, which is then used by the \\`sanity typegen generate\\` command to generate type definitions.\n- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.`.trim()\n\nconst debug = subdebug('typegen:generate')\n\nexport class TypegenGenerateCommand extends SanityCommand<typeof TypegenGenerateCommand> {\n static override description = description\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: `Generate TypeScript type definitions from a Sanity Studio schema extracted using the \\`sanity schema extract\\` command.`,\n },\n ]\n\n static override flags = {\n 'config-path': Flags.string({\n description:\n '[Default: sanity-typegen.json] Specifies the path to the typegen configuration file. This file should be a JSON file that contains settings for the type generation process.',\n }),\n }\n\n public async run() {\n const {flags} = await this.parse(TypegenGenerateCommand)\n const workDir = (await this.getProjectRoot()).directory\n\n // TODO: Add telemetry\n // const trace = telemetry.trace(TypesGeneratedTrace)\n // trace.start()\n\n const spin = spinner({}).start('Loading config…')\n\n let typegenConfig: TypeGenConfig\n let configPath: string | undefined\n let typegenConfigMethod: 'cli' | 'legacy'\n\n try {\n const result = await this.getConfig(spin, flags['config-path'])\n typegenConfig = result.config\n configPath = result.path\n typegenConfigMethod = result.type\n\n spin.succeed(`Config loaded from ${formatPath(configPath?.replace(workDir, '.') ?? '')}`)\n } catch (error) {\n debug('error loading config', error)\n spin.fail()\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n\n const {\n formatGeneratedCode,\n generates,\n overloadClientMethods,\n path: searchPath,\n schema: schemaPath,\n } = typegenConfig\n\n const outputPath = isAbsolute(typegenConfig.generates)\n ? typegenConfig.generates\n : join(workDir, typegenConfig.generates)\n\n const outputDir = dirname(outputPath)\n await mkdir(outputDir, {recursive: true})\n\n const workerPath = new URL('../../actions/typegenGenerate.worker.js', import.meta.url)\n const workerData: TypegenGenerateTypesWorkerData = {\n overloadClientMethods,\n schemaPath,\n searchPath,\n workDir,\n }\n\n const worker = new Worker(workerPath, {env, workerData})\n const receiver = WorkerChannelReceiver.from<TypegenWorkerChannel>(worker)\n\n try {\n spin.start(`Loading schema…`)\n await receiver.event.loadedSchema()\n spin.succeed(`Schema loaded from ${formatPath(schemaPath ?? '')}`)\n\n spin.start('Generating schema types…')\n const {expectedFileCount} = await receiver.event.typegenStarted()\n const {schemaTypeDeclarations} = await receiver.event.generatedSchemaTypes()\n const schemaTypesCount = schemaTypeDeclarations.length\n spin.succeed(`Generated ${count(schemaTypesCount, 'schema types')}`)\n\n spin.start('Generating query types…')\n let queriesCount = 0\n let evaluatedFiles = 0\n let filesWithErrors = 0\n let queryFilesCount = 0\n let typeNodesGenerated = 0\n let unknownTypeNodesGenerated = 0\n let emptyUnionTypeNodesGenerated = 0\n\n for await (const {errors, queries} of receiver.stream.evaluatedModules()) {\n evaluatedFiles++\n queriesCount += queries.length\n queryFilesCount += queries.length > 0 ? 1 : 0\n filesWithErrors += errors.length > 0 ? 1 : 0\n\n for (const {stats} of queries) {\n typeNodesGenerated += stats.allTypes\n unknownTypeNodesGenerated += stats.unknownTypes\n emptyUnionTypeNodesGenerated += stats.emptyUnions\n }\n\n for (const error of errors) {\n spin.fail(getMessage(error))\n }\n\n spin.text =\n `Generating query types… (${percent(evaluatedFiles / expectedFileCount)})\\n` +\n ` └─ Processed ${count(evaluatedFiles)} of ${count(expectedFileCount, 'files')}. ` +\n `Found ${count(queriesCount, 'queries', 'query')} from ${count(queryFilesCount, 'files')}.`\n }\n\n const result = await receiver.event.typegenComplete()\n const code = `${generatedFileWarning}${result.code}`\n await writeFile(outputPath, code)\n\n spin.succeed(\n `Generated ${count(queriesCount, 'query types')} from ${count(queryFilesCount, 'files')} out of ${count(evaluatedFiles, 'scanned files')}`,\n )\n\n if (formatGeneratedCode) {\n spin.start(`Formatting generated types with prettier…`)\n\n try {\n const prettier = await import('prettier')\n const prettierConfig = await prettier.resolveConfig(outputPath)\n const formattedCode = await prettier.format(code, {\n ...prettierConfig,\n parser: 'typescript' as const,\n })\n await writeFile(outputPath, formattedCode)\n\n spin.succeed('Formatted generated types with prettier')\n } catch (err) {\n spin.warn(`Failed to format generated types with prettier: ${getMessage(err)}`)\n }\n }\n\n debug('trace', {\n configMethod: typegenConfigMethod,\n configOverloadClientMethods: overloadClientMethods,\n emptyUnionTypeNodesGenerated,\n filesWithErrors,\n outputSize: Buffer.byteLength(result.code),\n queriesCount,\n queryFilesCount,\n schemaTypesCount,\n typeNodesGenerated,\n unknownTypeNodesGenerated,\n unknownTypeNodesRatio:\n typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n })\n // trace.log({\n // configMethod: typegenConfigMethod,\n // configOverloadClientMethods: overloadClientMethods,\n // emptyUnionTypeNodesGenerated,\n // filesWithErrors,\n // outputSize: Buffer.byteLength(result.code),\n // queriesCount,\n // queryFilesCount,\n // schemaTypesCount,\n // typeNodesGenerated,\n // unknownTypeNodesGenerated,\n // unknownTypeNodesRatio:\n // typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n // })\n\n if (filesWithErrors > 0) {\n spin.warn(`Encountered errors in ${count(filesWithErrors, 'files')} while generating types`)\n }\n\n spin.succeed(`Successfully generated types to ${formatPath(generates)}`)\n } catch (err) {\n // trace.error(err)\n debug('error generating types', err)\n this.error(err instanceof Error ? err.message : 'Unknown error', {exit: 1})\n } finally {\n receiver.unsubscribe()\n // trace.complete()\n await worker.terminate()\n }\n }\n\n private async getConfig(\n spin: ReturnType<typeof spinner>,\n configPath?: string,\n ): Promise<{config: TypeGenConfig; path?: string; type: 'cli' | 'legacy'}> {\n const rootDir = await this.getProjectRoot()\n const config = await this.getCliConfig()\n\n // check if the legacy config exist\n const legacyConfigPath = configPath || 'sanity-typegen.json'\n let hasLegacyConfig = false\n try {\n const file = await stat(legacyConfigPath)\n hasLegacyConfig = file.isFile()\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {\n throw new Error(`Typegen config file not found: ${configPath}`, {cause: err})\n }\n\n if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {\n throw new Error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {\n cause: err,\n })\n }\n }\n\n // we have both legacy and cli config with typegen\n if (config?.typegen && hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `You've specified typegen in your Sanity CLI config, but also have a typegen config.\n\n The config from the Sanity CLI config is used.\n `,\n ),\n )\n\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n }\n }\n\n // we only have legacy typegen config\n if (hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `The separate typegen config has been deprecated. Use \\`typegen\\` in the sanity CLI config instead.\n\n See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`,\n ),\n )\n return {\n config: await readConfig(legacyConfigPath),\n path: legacyConfigPath,\n type: 'legacy',\n }\n }\n\n // we only have cli config\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n }\n }\n}\n"],"names":["mkdir","stat","writeFile","dirname","isAbsolute","join","env","Worker","Flags","SanityCommand","subdebug","chalk","spinner","WorkerChannelReceiver","generatedFileWarning","configDefinition","readConfig","count","formatPath","getMessage","percent","description","bold","trim","debug","TypegenGenerateCommand","examples","command","flags","string","run","parse","workDir","getProjectRoot","directory","spin","start","typegenConfig","configPath","typegenConfigMethod","result","getConfig","config","path","type","succeed","replace","error","fail","Error","message","exit","formatGeneratedCode","generates","overloadClientMethods","searchPath","schema","schemaPath","outputPath","outputDir","recursive","workerPath","URL","url","workerData","worker","receiver","from","event","loadedSchema","expectedFileCount","typegenStarted","schemaTypeDeclarations","generatedSchemaTypes","schemaTypesCount","length","queriesCount","evaluatedFiles","filesWithErrors","queryFilesCount","typeNodesGenerated","unknownTypeNodesGenerated","emptyUnionTypeNodesGenerated","errors","queries","stream","evaluatedModules","stats","allTypes","unknownTypes","emptyUnions","text","typegenComplete","code","prettier","prettierConfig","resolveConfig","formattedCode","format","parser","err","warn","configMethod","configOverloadClientMethods","outputSize","Buffer","byteLength","unknownTypeNodesRatio","unsubscribe","terminate","rootDir","getCliConfig","legacyConfigPath","hasLegacyConfig","file","isFile","cause","typegen","yellow"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,IAAI,EAAEC,SAAS,QAAO,mBAAkB;AACvD,SAAQC,O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AAC;;+EAEoE,CAAC;YAG1E,OAAO;gBACL5E,QAAQ,MAAM1B,WAAWgG;gBACzBrE,MAAMqE;gBACNpE,MAAM;YACR;QACF;QAEA,0BAA0B;QAC1B,OAAO;YACLF,QAAQ3B,iBAAiBgB,KAAK,CAACW,OAAO2E,OAAO,IAAI,CAAC;YAClD1E,MAAMmE,QAAQnE,IAAI;YAClBC,MAAM;QACR;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/typegen/generate.ts"],"sourcesContent":["import {mkdir, stat, writeFile} from 'node:fs/promises'\nimport {dirname, isAbsolute, join} from 'node:path'\nimport {env} from 'node:process'\nimport {Worker} from 'node:worker_threads'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand, subdebug} from '@sanity/cli-core'\nimport {chalk, spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {generatedFileWarning} from '../../actions/generatedFileWarning.js'\nimport {\n type TypegenGenerateTypesWorkerData,\n type TypegenWorkerChannel,\n} from '../../actions/types.js'\nimport {configDefinition, readConfig, type TypeGenConfig} from '../../readConfig.js'\nimport {count} from '../../utils/count.js'\nimport {formatPath} from '../../utils/formatPath.js'\nimport {getMessage} from '../../utils/getMessage.js'\nimport {percent} from '../../utils/percent.js'\n\nconst description = `Sanity TypeGen (Beta)\nThis command is currently in beta and may undergo significant changes. Feedback is welcome!\n\n${chalk.bold('Configuration:')}\nThis command can utilize configuration settings defined in a \\`sanity-typegen.json\\` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the \\`sanity schema extract\\` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your \\`sanity-typegen.json\\` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\n${chalk.bold('Note:')}\n- The \\`sanity schema extract\\` command is a prerequisite for extracting your Sanity Studio schema into a \\`schema.json\\` file, which is then used by the \\`sanity typegen generate\\` command to generate type definitions.\n- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.`.trim()\n\nconst debug = subdebug('typegen:generate')\n\n/**\n * @internal\n */\nexport class TypegenGenerateCommand extends SanityCommand<typeof TypegenGenerateCommand> {\n static override description = description\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: `Generate TypeScript type definitions from a Sanity Studio schema extracted using the \\`sanity schema extract\\` command.`,\n },\n ]\n\n static override flags = {\n 'config-path': Flags.string({\n description:\n '[Default: sanity-typegen.json] Specifies the path to the typegen configuration file. This file should be a JSON file that contains settings for the type generation process.',\n }),\n }\n\n public async run() {\n const {flags} = await this.parse(TypegenGenerateCommand)\n const workDir = (await this.getProjectRoot()).directory\n\n // TODO: Add telemetry\n // const trace = telemetry.trace(TypesGeneratedTrace)\n // trace.start()\n\n const spin = spinner({}).start('Loading config…')\n\n let typegenConfig: TypeGenConfig\n let configPath: string | undefined\n let typegenConfigMethod: 'cli' | 'legacy'\n\n try {\n const result = await this.getConfig(spin, flags['config-path'])\n typegenConfig = result.config\n configPath = result.path\n typegenConfigMethod = result.type\n\n spin.succeed(`Config loaded from ${formatPath(configPath?.replace(workDir, '.') ?? '')}`)\n } catch (error) {\n debug('error loading config', error)\n spin.fail()\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n\n const {\n formatGeneratedCode,\n generates,\n overloadClientMethods,\n path: searchPath,\n schema: schemaPath,\n } = typegenConfig\n\n const outputPath = isAbsolute(typegenConfig.generates)\n ? typegenConfig.generates\n : join(workDir, typegenConfig.generates)\n\n const outputDir = dirname(outputPath)\n await mkdir(outputDir, {recursive: true})\n\n const workerPath = new URL('../../actions/typegenGenerate.worker.js', import.meta.url)\n const workerData: TypegenGenerateTypesWorkerData = {\n overloadClientMethods,\n schemaPath,\n searchPath,\n workDir,\n }\n\n const worker = new Worker(workerPath, {env, workerData})\n const receiver = WorkerChannelReceiver.from<TypegenWorkerChannel>(worker)\n\n try {\n spin.start(`Loading schema…`)\n await receiver.event.loadedSchema()\n spin.succeed(`Schema loaded from ${formatPath(schemaPath ?? '')}`)\n\n spin.start('Generating schema types…')\n const {expectedFileCount} = await receiver.event.typegenStarted()\n const {schemaTypeDeclarations} = await receiver.event.generatedSchemaTypes()\n const schemaTypesCount = schemaTypeDeclarations.length\n spin.succeed(`Generated ${count(schemaTypesCount, 'schema types')}`)\n\n spin.start('Generating query types…')\n let queriesCount = 0\n let evaluatedFiles = 0\n let filesWithErrors = 0\n let queryFilesCount = 0\n let typeNodesGenerated = 0\n let unknownTypeNodesGenerated = 0\n let emptyUnionTypeNodesGenerated = 0\n\n for await (const {errors, queries} of receiver.stream.evaluatedModules()) {\n evaluatedFiles++\n queriesCount += queries.length\n queryFilesCount += queries.length > 0 ? 1 : 0\n filesWithErrors += errors.length > 0 ? 1 : 0\n\n for (const {stats} of queries) {\n typeNodesGenerated += stats.allTypes\n unknownTypeNodesGenerated += stats.unknownTypes\n emptyUnionTypeNodesGenerated += stats.emptyUnions\n }\n\n for (const error of errors) {\n spin.fail(getMessage(error))\n }\n\n spin.text =\n `Generating query types… (${percent(evaluatedFiles / expectedFileCount)})\\n` +\n ` └─ Processed ${count(evaluatedFiles)} of ${count(expectedFileCount, 'files')}. ` +\n `Found ${count(queriesCount, 'queries', 'query')} from ${count(queryFilesCount, 'files')}.`\n }\n\n const result = await receiver.event.typegenComplete()\n const code = `${generatedFileWarning}${result.code}`\n await writeFile(outputPath, code)\n\n spin.succeed(\n `Generated ${count(queriesCount, 'query types')} from ${count(queryFilesCount, 'files')} out of ${count(evaluatedFiles, 'scanned files')}`,\n )\n\n if (formatGeneratedCode) {\n spin.start(`Formatting generated types with prettier…`)\n\n try {\n const prettier = await import('prettier')\n const prettierConfig = await prettier.resolveConfig(outputPath)\n const formattedCode = await prettier.format(code, {\n ...prettierConfig,\n parser: 'typescript' as const,\n })\n await writeFile(outputPath, formattedCode)\n\n spin.succeed('Formatted generated types with prettier')\n } catch (err) {\n spin.warn(`Failed to format generated types with prettier: ${getMessage(err)}`)\n }\n }\n\n debug('trace', {\n configMethod: typegenConfigMethod,\n configOverloadClientMethods: overloadClientMethods,\n emptyUnionTypeNodesGenerated,\n filesWithErrors,\n outputSize: Buffer.byteLength(result.code),\n queriesCount,\n queryFilesCount,\n schemaTypesCount,\n typeNodesGenerated,\n unknownTypeNodesGenerated,\n unknownTypeNodesRatio:\n typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n })\n // trace.log({\n // configMethod: typegenConfigMethod,\n // configOverloadClientMethods: overloadClientMethods,\n // emptyUnionTypeNodesGenerated,\n // filesWithErrors,\n // outputSize: Buffer.byteLength(result.code),\n // queriesCount,\n // queryFilesCount,\n // schemaTypesCount,\n // typeNodesGenerated,\n // unknownTypeNodesGenerated,\n // unknownTypeNodesRatio:\n // typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n // })\n\n if (filesWithErrors > 0) {\n spin.warn(`Encountered errors in ${count(filesWithErrors, 'files')} while generating types`)\n }\n\n spin.succeed(`Successfully generated types to ${formatPath(generates)}`)\n } catch (err) {\n // trace.error(err)\n debug('error generating types', err)\n this.error(err instanceof Error ? err.message : 'Unknown error', {exit: 1})\n } finally {\n receiver.unsubscribe()\n // trace.complete()\n await worker.terminate()\n }\n }\n\n private async getConfig(\n spin: ReturnType<typeof spinner>,\n configPath?: string,\n ): Promise<{config: TypeGenConfig; path?: string; type: 'cli' | 'legacy'}> {\n const rootDir = await this.getProjectRoot()\n const config = await this.getCliConfig()\n\n // check if the legacy config exist\n const legacyConfigPath = configPath || 'sanity-typegen.json'\n let hasLegacyConfig = false\n try {\n const file = await stat(legacyConfigPath)\n hasLegacyConfig = file.isFile()\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {\n throw new Error(`Typegen config file not found: ${configPath}`, {cause: err})\n }\n\n if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {\n throw new Error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {\n cause: err,\n })\n }\n }\n\n // we have both legacy and cli config with typegen\n if (config?.typegen && hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `You've specified typegen in your Sanity CLI config, but also have a typegen config.\n\n The config from the Sanity CLI config is used.\n `,\n ),\n )\n\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n }\n }\n\n // we only have legacy typegen config\n if (hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `The separate typegen config has been deprecated. Use \\`typegen\\` in the sanity CLI config instead.\n\n See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`,\n ),\n )\n return {\n config: await readConfig(legacyConfigPath),\n path: legacyConfigPath,\n type: 'legacy',\n }\n }\n\n // we only have cli config\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n }\n }\n}\n"],"names":["mkdir","stat","writeFile","dirname","isAbsolute","join","env","Worker","Flags","SanityCommand","subdebug","chalk","spinner","WorkerChannelReceiver","generatedFileWarning","configDefinition","readConfig","count","formatPath","getMessage","percent","description","bold","trim","debug","TypegenGenerateCommand","examples","command","flags","string","run","parse","workDir","getProjectRoot","directory","spin","start","typegenConfig","configPath","typegenConfigMethod","result","getConfig","config","path","type","succeed","replace","error","fail","Error","message","exit","formatGeneratedCode","generates","overloadClientMethods","searchPath","schema","schemaPath","outputPath","outputDir","recursive","workerPath","URL","url","workerData","worker","receiver","from","event","loadedSchema","expectedFileCount","typegenStarted","schemaTypeDeclarations","generatedSchemaTypes","schemaTypesCount","length","queriesCount","evaluatedFiles","filesWithErrors","queryFilesCount","typeNodesGenerated","unknownTypeNodesGenerated","emptyUnionTypeNodesGenerated","errors","queries","stream","evaluatedModules","stats","allTypes","unknownTypes","emptyUnions","text","typegenComplete","code","prettier","prettierConfig","resolveConfig","formattedCode","format","parser","err","warn","configMethod","configOverloadClientMethods","outputSize","Buffer","byteLength","unknownTypeNodesRatio","unsubscribe","terminate","rootDir","getCliConfig","legacyConfigPath","hasLegacyConfig","file","isFile","cause","typegen","yellow"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,IAAI,EAAEC,SAAS,QAAO,mBAAkB;AACvD,SAAQC,OAAO,EAAEC,UAAU,EAAEC,IAAI,QAAO,YAAW;AACnD,SAAQC,GAAG,QAAO,eAAc;AAChC,SAAQC,MAAM,QAAO,sBAAqB;AAE1C,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACxD,SAAQC,KAAK,EAAEC,OAAO,QAAO,sBAAqB;AAClD,SAAQC,qBAAqB,QAAO,0BAAyB;AAE7D,SAAQC,oBAAoB,QAAO,wCAAuC;AAK1E,SAAQC,gBAAgB,EAAEC,UAAU,QAA2B,sBAAqB;AACpF,SAAQC,KAAK,QAAO,uBAAsB;AAC1C,SAAQC,UAAU,QAAO,4BAA2B;AACpD,SAAQC,UAAU,QAAO,4BAA2B;AACpD,SAAQC,OAAO,QAAO,yBAAwB;AAE9C,MAAMC,cAAc,CAAC;;;AAGrB,EAAEV,MAAMW,IAAI,CAAC,kBAAkB;;;;;;;;;;;;;;AAc/B,EAAEX,MAAMW,IAAI,CAAC,SAAS;;4JAEsI,CAAC,CAACC,IAAI;AAElK,MAAMC,QAAQd,SAAS;AAEvB;;CAEC,GACD,OAAO,MAAMe,+BAA+BhB;IAC1C,OAAgBY,cAAcA,YAAW;IAEzC,OAAgBK,WAAW;QACzB;YACEC,SAAS;YACTN,aAAa,CAAC,uHAAuH,CAAC;QACxI;KACD,CAAA;IAED,OAAgBO,QAAQ;QACtB,eAAepB,MAAMqB,MAAM,CAAC;YAC1BR,aACE;QACJ;IACF,EAAC;IAED,MAAaS,MAAM;Q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iBAAiB;YACtC9E,KAAKkE,IAAI,CACP1F,MAAM2G,MAAM,CACV,CAAC;;;EAGT,CAAC;YAIG,OAAO;gBACL5E,QAAQ3B,iBAAiBgB,KAAK,CAACW,OAAO2E,OAAO,IAAI,CAAC;gBAClD1E,MAAMmE,QAAQnE,IAAI;gBAClBC,MAAM;YACR;QACF;QAEA,qCAAqC;QACrC,IAAIqE,iBAAiB;YACnB9E,KAAKkE,IAAI,CACP1F,MAAM2G,MAAM,CACV,CAAC;;+EAEoE,CAAC;YAG1E,OAAO;gBACL5E,QAAQ,MAAM1B,WAAWgG;gBACzBrE,MAAMqE;gBACNpE,MAAM;YACR;QACF;QAEA,0BAA0B;QAC1B,OAAO;YACLF,QAAQ3B,iBAAiBgB,KAAK,CAACW,OAAO2E,OAAO,IAAI,CAAC;YAClD1E,MAAMmE,QAAQnE,IAAI;YAClBC,MAAM;QACR;IACF;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { CustomOptions } from '@oclif/core/interfaces';
|
|
1
2
|
import { ExprNode } from 'groq-js';
|
|
3
|
+
import { OptionFlag } from '@oclif/core/interfaces';
|
|
4
|
+
import { SanityCommand } from '@sanity/cli-core';
|
|
2
5
|
import { SchemaType } from 'groq-js';
|
|
3
6
|
import * as t from '@babel/types';
|
|
4
7
|
import { TransformOptions } from '@babel/core';
|
|
@@ -18,21 +21,9 @@ export declare const configDefinition: z.ZodObject<{
|
|
|
18
21
|
formatGeneratedCode: z.ZodDefault<z.ZodBoolean>;
|
|
19
22
|
generates: z.ZodDefault<z.ZodString>;
|
|
20
23
|
overloadClientMethods: z.ZodDefault<z.ZodBoolean>;
|
|
21
|
-
path: z.ZodDefault<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString
|
|
24
|
+
path: z.ZodDefault<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString>]>>;
|
|
22
25
|
schema: z.ZodDefault<z.ZodString>;
|
|
23
|
-
},
|
|
24
|
-
formatGeneratedCode: boolean;
|
|
25
|
-
generates: string;
|
|
26
|
-
overloadClientMethods: boolean;
|
|
27
|
-
path: string | string[];
|
|
28
|
-
schema: string;
|
|
29
|
-
}, {
|
|
30
|
-
formatGeneratedCode?: boolean | undefined;
|
|
31
|
-
generates?: string | undefined;
|
|
32
|
-
overloadClientMethods?: boolean | undefined;
|
|
33
|
-
path?: string | string[] | undefined;
|
|
34
|
-
schema?: string | undefined;
|
|
35
|
-
}>;
|
|
26
|
+
}, z.core.$strip>;
|
|
36
27
|
|
|
37
28
|
/**
|
|
38
29
|
* A module containing queries that have been evaluated.
|
|
@@ -427,6 +418,22 @@ export declare class TypeGenerator {
|
|
|
427
418
|
}>;
|
|
428
419
|
}
|
|
429
420
|
|
|
421
|
+
/**
|
|
422
|
+
* @internal
|
|
423
|
+
*/
|
|
424
|
+
export declare class TypegenGenerateCommand extends SanityCommand<typeof TypegenGenerateCommand> {
|
|
425
|
+
static description: string;
|
|
426
|
+
static examples: {
|
|
427
|
+
command: string;
|
|
428
|
+
description: string;
|
|
429
|
+
}[];
|
|
430
|
+
static flags: {
|
|
431
|
+
'config-path': OptionFlag<string | undefined, CustomOptions>;
|
|
432
|
+
};
|
|
433
|
+
run(): Promise<void>;
|
|
434
|
+
private getConfig;
|
|
435
|
+
}
|
|
436
|
+
|
|
430
437
|
export declare type TypegenWorkerChannel = WorkerChannel.Definition<{
|
|
431
438
|
evaluatedModules: WorkerChannel.Stream<EvaluatedModule>;
|
|
432
439
|
generatedQueryTypes: WorkerChannel.Event<{
|
package/dist/readConfig.js
CHANGED
|
@@ -24,7 +24,7 @@ import * as z from 'zod';
|
|
|
24
24
|
return configDefinition.parseAsync(json);
|
|
25
25
|
} catch (error) {
|
|
26
26
|
if (error instanceof z.ZodError) {
|
|
27
|
-
throw new Error(`Error in config file\n ${error.
|
|
27
|
+
throw new Error(`Error in config file\n ${error.issues.map((err)=>err.message).join('\n')}`, {
|
|
28
28
|
cause: error
|
|
29
29
|
});
|
|
30
30
|
}
|
package/dist/readConfig.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as z from 'zod'\n\n/**\n * @internal\n */\nexport const configDefinition = z.object({\n formatGeneratedCode: z.boolean().default(true),\n generates: z.string().default('./sanity.types.ts'),\n overloadClientMethods: z.boolean().default(true),\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n})\n\nexport type TypeGenConfig = z.infer<typeof configDefinition>\n\n/**\n * @deprecated use TypeGenConfig\n */\nexport type CodegenConfig = TypeGenConfig\n\n/**\n * Read, parse and process a config file\n * @internal\n */\nexport async function readConfig(path: string): Promise<TypeGenConfig> {\n try {\n const content = await readFile(path, 'utf8')\n const json = json5.parse(content)\n return configDefinition.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(\n `Error in config file\\n ${error.
|
|
1
|
+
{"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as z from 'zod'\n\n/**\n * @internal\n */\nexport const configDefinition = z.object({\n formatGeneratedCode: z.boolean().default(true),\n generates: z.string().default('./sanity.types.ts'),\n overloadClientMethods: z.boolean().default(true),\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n})\n\nexport type TypeGenConfig = z.infer<typeof configDefinition>\n\n/**\n * @deprecated use TypeGenConfig\n */\nexport type CodegenConfig = TypeGenConfig\n\n/**\n * Read, parse and process a config file\n * @internal\n */\nexport async function readConfig(path: string): Promise<TypeGenConfig> {\n try {\n const content = await readFile(path, 'utf8')\n const json = json5.parse(content)\n return configDefinition.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(\n `Error in config file\\n ${error.issues.map((err) => err.message).join('\\n')}`,\n {cause: error},\n )\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefinition.parse({})\n }\n\n throw error\n }\n}\n"],"names":["readFile","json5","z","configDefinition","object","formatGeneratedCode","boolean","default","generates","string","overloadClientMethods","path","or","array","schema","readConfig","content","json","parse","parseAsync","error","ZodError","Error","issues","map","err","message","join","cause","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,OAAOC,WAAW,QAAO;AACzB,YAAYC,OAAO,MAAK;AAExB;;CAEC,GACD,OAAO,MAAMC,mBAAmBD,EAAEE,MAAM,CAAC;IACvCC,qBAAqBH,EAAEI,OAAO,GAAGC,OAAO,CAAC;IACzCC,WAAWN,EAAEO,MAAM,GAAGF,OAAO,CAAC;IAC9BG,uBAAuBR,EAAEI,OAAO,GAAGC,OAAO,CAAC;IAC3CI,MAAMT,EACHO,MAAM,GACNG,EAAE,CAACV,EAAEW,KAAK,CAACX,EAAEO,MAAM,KACnBF,OAAO,CAAC;QACP;QACA;QACA;KACD;IACHO,QAAQZ,EAAEO,MAAM,GAAGF,OAAO,CAAC;AAC7B,GAAE;AASF;;;CAGC,GACD,OAAO,eAAeQ,WAAWJ,IAAY;IAC3C,IAAI;QACF,MAAMK,UAAU,MAAMhB,SAASW,MAAM;QACrC,MAAMM,OAAOhB,MAAMiB,KAAK,CAACF;QACzB,OAAOb,iBAAiBgB,UAAU,CAACF;IACrC,EAAE,OAAOG,OAAO;QACd,IAAIA,iBAAiBlB,EAAEmB,QAAQ,EAAE;YAC/B,MAAM,IAAIC,MACR,CAAC,uBAAuB,EAAEF,MAAMG,MAAM,CAACC,GAAG,CAAC,CAACC,MAAQA,IAAIC,OAAO,EAAEC,IAAI,CAAC,OAAO,EAC7E;gBAACC,OAAOR;YAAK;QAEjB;QACA,IAAI,OAAOA,UAAU,YAAYA,UAAU,QAAQ,UAAUA,SAASA,MAAMS,IAAI,KAAK,UAAU;YAC7F,OAAO1B,iBAAiBe,KAAK,CAAC,CAAC;QACjC;QAEA,MAAME;IACR;AACF"}
|
package/oclif.config.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export default {
|
|
2
|
+
bin: 'sanity',
|
|
3
|
+
commands: './dist/commands',
|
|
4
|
+
dirname: 'sanity-typegen',
|
|
5
|
+
plugins: ['@oclif/plugin-help'],
|
|
6
|
+
topics: {
|
|
7
|
+
typegen: {
|
|
8
|
+
description: 'Beta: Generate TypeScript types for schema and GROQ',
|
|
9
|
+
},
|
|
10
|
+
},
|
|
11
|
+
topicSeparator: ' ',
|
|
12
|
+
}
|
package/oclif.manifest.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/codegen",
|
|
3
|
-
"version": "5.7.
|
|
3
|
+
"version": "5.7.2",
|
|
4
4
|
"description": "Codegen toolkit for Sanity.io",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
"dist",
|
|
39
39
|
"bin",
|
|
40
40
|
"oclif.manifest.json",
|
|
41
|
+
"oclif.config.js",
|
|
41
42
|
"babel.config.json"
|
|
42
43
|
],
|
|
43
44
|
"dependencies": {
|
|
@@ -61,7 +62,7 @@
|
|
|
61
62
|
"prettier": "^3.7.4",
|
|
62
63
|
"reselect": "^5.1.1",
|
|
63
64
|
"tsconfig-paths": "^4.2.0",
|
|
64
|
-
"zod": "^3.
|
|
65
|
+
"zod": "^4.3.6"
|
|
65
66
|
},
|
|
66
67
|
"devDependencies": {
|
|
67
68
|
"@eslint/compat": "^2.0.1",
|