@sanity/codegen 5.10.1 → 6.0.0
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.d.ts +555 -0
- package/dist/actions/typegenGenerate.js +1 -0
- package/dist/actions/typegenGenerate.js.map +1 -1
- package/dist/actions/typegenWatch.js +3 -1
- package/dist/actions/typegenWatch.js.map +1 -1
- package/dist/actions/types.js +1 -1
- package/dist/actions/types.js.map +1 -1
- package/dist/commands/typegen/generate.js +2 -1
- package/dist/commands/typegen/generate.js.map +1 -1
- package/dist/readConfig.js +1 -1
- package/dist/readConfig.js.map +1 -1
- package/dist/typeUtils.js +1 -0
- package/dist/typeUtils.js.map +1 -1
- package/dist/typegen.telemetry.js +2 -2
- package/dist/typegen.telemetry.js.map +1 -1
- package/dist/typescript/typeGenerator.js.map +1 -1
- package/dist/utils/test/testLongRunning.js +1 -1
- package/dist/utils/test/testLongRunning.js.map +1 -1
- package/oclif.config.js +0 -1
- package/oclif.manifest.json +1 -1
- package/package.json +20 -27
- package/bin/run.js +0 -51
- package/dist/index.d.ts +0 -562
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/typegen/generate.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {omit, once} from 'lodash-es'\n\nimport {runTypegenGenerate} from '../../actions/typegenGenerate.js'\nimport {runTypegenWatcher} from '../../actions/typegenWatch.js'\nimport {configDefinition, readConfig, type TypeGenConfig} from '../../readConfig.js'\nimport {TypegenWatchModeTrace, TypesGeneratedTrace} from '../../typegen.telemetry.js'\nimport {debug} from '../../utils/debug.js'\nimport {promiseWithResolvers} from '../../utils/promiseWithResolvers.js'\n\nconst description = `Sanity TypeGen\n\n${styleText('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${styleText('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.`.trim()\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 watch: Flags.boolean({\n default: false,\n description: '[Default: false] Run the typegen in watch mode',\n }),\n }\n\n public async run() {\n const {flags} = await this.parse(TypegenGenerateCommand)\n\n if (flags.watch) {\n await this.runWatcher()\n return\n }\n\n await this.runSingle()\n }\n\n private async getConfig(): Promise<{\n config: TypeGenConfig\n path?: string\n type: 'cli' | 'legacy'\n workDir: string\n }> {\n const spin = spinner({}).start('Loading config…')\n\n try {\n const {flags} = await this.parse(TypegenGenerateCommand)\n const rootDir = await this.getProjectRoot()\n const config = await this.getCliConfig()\n\n const configPath = flags['config-path']\n const workDir = rootDir.directory\n\n // check if the legacy config exist\n const legacyConfigPath = configPath || 'sanity-typegen.json'\n let hasLegacyConfig = false\n\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 spin.fail()\n this.error(`Typegen config file not found: ${configPath}`, {exit: 1})\n }\n\n if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {\n spin.fail()\n this.error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {\n exit: 1,\n })\n }\n }\n\n // we have both legacy and cli config with typegen\n if (config?.typegen && hasLegacyConfig) {\n spin.warn(\n styleText(\n '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 workDir,\n }\n }\n\n // we only have legacy typegen config\n if (hasLegacyConfig) {\n spin.warn(\n styleText(\n '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 workDir,\n }\n }\n\n spin.succeed(`Config loaded from sanity.cli.ts`)\n\n // we only have cli config\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n workDir,\n }\n } catch (err) {\n spin.fail()\n this.error(`An error occured during config loading ${err}`, {exit: 1})\n }\n }\n\n private async runSingle() {\n const trace = this.telemetry.trace(TypesGeneratedTrace)\n\n try {\n const {config: typegenConfig, type: typegenConfigMethod, workDir} = await this.getConfig()\n trace.start()\n\n const result = await runTypegenGenerate({\n config: typegenConfig,\n workDir,\n })\n\n const traceStats = omit(result, 'code', 'duration')\n\n trace.log({\n configMethod: typegenConfigMethod,\n configOverloadClientMethods: typegenConfig.overloadClientMethods,\n ...traceStats,\n })\n trace.complete()\n } catch (error) {\n debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n\n private async runWatcher() {\n const trace = this.telemetry.trace(TypegenWatchModeTrace)\n\n try {\n const {config: typegenConfig, workDir} = await this.getConfig()\n trace.start()\n\n const {promise, resolve} = promiseWithResolvers()\n\n const typegenWatcher = runTypegenWatcher({\n config: typegenConfig,\n workDir,\n })\n\n const stop = once(async () => {\n process.off('SIGINT', stop)\n process.off('SIGTERM', stop)\n\n trace.log({\n step: 'stopped',\n ...typegenWatcher.getStats(),\n })\n trace.complete()\n\n await typegenWatcher.stop()\n resolve()\n })\n\n process.on('SIGINT', stop)\n process.on('SIGTERM', stop)\n\n await promise\n } catch (error) {\n debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n}\n"],"names":["stat","styleText","Flags","SanityCommand","spinner","omit","once","runTypegenGenerate","runTypegenWatcher","configDefinition","readConfig","TypegenWatchModeTrace","TypesGeneratedTrace","debug","promiseWithResolvers","description","trim","TypegenGenerateCommand","examples","command","flags","string","watch","boolean","default","run","parse","runWatcher","runSingle","getConfig","spin","start","rootDir","getProjectRoot","config","getCliConfig","configPath","workDir","directory","legacyConfigPath","hasLegacyConfig","file","isFile","err","Error","code","fail","error","exit","typegen","warn","path","type","succeed","trace","telemetry","typegenConfig","typegenConfigMethod","result","traceStats","log","configMethod","configOverloadClientMethods","overloadClientMethods","complete","message","promise","resolve","typegenWatcher","stop","process","off","step","getStats","on"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,IAAI,EAAEC,IAAI,QAAO,YAAW;AAEpC,SAAQC,kBAAkB,QAAO,mCAAkC;AACnE,SAAQC,iBAAiB,QAAO,gCAA+B;AAC/D,SAAQC,gBAAgB,EAAEC,UAAU,QAA2B,sBAAqB;AACp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MH;QACR,EAAE,OAAOnB,OAAO;YACdlC,MAAMkC;YACNO,MAAMP,KAAK,CAACA;YACZ,IAAI,CAACA,KAAK,CAAC,GAAGA,iBAAiBH,QAAQG,MAAMkB,OAAO,GAAG,iBAAiB,EAAE;gBACxEjB,MAAM;YACR;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/typegen/generate.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\nimport omit from 'lodash-es/omit.js'\nimport once from 'lodash-es/once.js'\n\nimport {runTypegenGenerate} from '../../actions/typegenGenerate.js'\nimport {runTypegenWatcher} from '../../actions/typegenWatch.js'\nimport {configDefinition, readConfig, type TypeGenConfig} from '../../readConfig.js'\nimport {TypegenWatchModeTrace, TypesGeneratedTrace} from '../../typegen.telemetry.js'\nimport {debug} from '../../utils/debug.js'\nimport {promiseWithResolvers} from '../../utils/promiseWithResolvers.js'\n\nconst description = `Sanity TypeGen\n\n${styleText('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${styleText('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.`.trim()\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 watch: Flags.boolean({\n default: false,\n description: '[Default: false] Run the typegen in watch mode',\n }),\n }\n\n public async run() {\n const {flags} = await this.parse(TypegenGenerateCommand)\n\n if (flags.watch) {\n await this.runWatcher()\n return\n }\n\n await this.runSingle()\n }\n\n private async getConfig(): Promise<{\n config: TypeGenConfig\n path?: string\n type: 'cli' | 'legacy'\n workDir: string\n }> {\n const spin = spinner({}).start('Loading config…')\n\n try {\n const {flags} = await this.parse(TypegenGenerateCommand)\n const rootDir = await this.getProjectRoot()\n const config = await this.getCliConfig()\n\n const configPath = flags['config-path']\n const workDir = rootDir.directory\n\n // check if the legacy config exist\n const legacyConfigPath = configPath || 'sanity-typegen.json'\n let hasLegacyConfig = false\n\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 spin.fail()\n this.error(`Typegen config file not found: ${configPath}`, {exit: 1})\n }\n\n if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {\n spin.fail()\n this.error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {\n exit: 1,\n })\n }\n }\n\n // we have both legacy and cli config with typegen\n if (config?.typegen && hasLegacyConfig) {\n spin.warn(\n styleText(\n '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 workDir,\n }\n }\n\n // we only have legacy typegen config\n if (hasLegacyConfig) {\n spin.warn(\n styleText(\n '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 workDir,\n }\n }\n\n spin.succeed(`Config loaded from sanity.cli.ts`)\n\n // we only have cli config\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n workDir,\n }\n } catch (err) {\n spin.fail()\n this.error(`An error occured during config loading ${err}`, {exit: 1})\n }\n }\n\n private async runSingle() {\n const trace = this.telemetry.trace(TypesGeneratedTrace)\n\n try {\n const {config: typegenConfig, type: typegenConfigMethod, workDir} = await this.getConfig()\n trace.start()\n\n const result = await runTypegenGenerate({\n config: typegenConfig,\n workDir,\n })\n\n const traceStats = omit(result, 'code', 'duration')\n\n trace.log({\n configMethod: typegenConfigMethod,\n configOverloadClientMethods: typegenConfig.overloadClientMethods,\n ...traceStats,\n })\n trace.complete()\n } catch (error) {\n debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n\n private async runWatcher() {\n const trace = this.telemetry.trace(TypegenWatchModeTrace)\n\n try {\n const {config: typegenConfig, workDir} = await this.getConfig()\n trace.start()\n\n const {promise, resolve} = promiseWithResolvers()\n\n const typegenWatcher = runTypegenWatcher({\n config: typegenConfig,\n workDir,\n })\n\n const stop = once(async () => {\n process.off('SIGINT', stop)\n process.off('SIGTERM', stop)\n\n trace.log({\n step: 'stopped',\n ...typegenWatcher.getStats(),\n })\n trace.complete()\n\n await typegenWatcher.stop()\n resolve()\n })\n\n process.on('SIGINT', stop)\n process.on('SIGTERM', stop)\n\n await promise\n } catch (error) {\n debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n}\n"],"names":["stat","styleText","Flags","SanityCommand","spinner","omit","once","runTypegenGenerate","runTypegenWatcher","configDefinition","readConfig","TypegenWatchModeTrace","TypesGeneratedTrace","debug","promiseWithResolvers","description","trim","TypegenGenerateCommand","examples","command","flags","string","watch","boolean","default","run","parse","runWatcher","runSingle","getConfig","spin","start","rootDir","getProjectRoot","config","getCliConfig","configPath","workDir","directory","legacyConfigPath","hasLegacyConfig","file","isFile","err","Error","code","fail","error","exit","typegen","warn","path","type","succeed","trace","telemetry","typegenConfig","typegenConfigMethod","result","traceStats","log","configMethod","configOverloadClientMethods","overloadClientMethods","complete","message","promise","resolve","typegenWatcher","stop","process","off","step","getStats","on"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,OAAOC,UAAU,oBAAmB;AACpC,OAAOC,UAAU,oBAAmB;AAEpC,SAAQC,kBAAkB,QAAO,mCAAkC;AACnE,SAAQC,iBAAiB,QAAO,gCAA+B;AAC/D,SAAQC,gBAAgB,EAAEC,UAAU,QAA2B,sBAAqB;AACpF,SAAQC,qBAAqB,EAAEC,mBAAmB,QAAO,6BAA4B;AACrF,SAAQC,KAAK,QAAO,uBAAsB;AAC1C,SAAQC,oBAAoB,QAAO,sCAAqC;AAExE,MAAMC,cAAc,CAAC;;AAErB,EAAEd,UAAU,QAAQ,kBAAkB;;;;;;;;;;;;;;AActC,EAAEA,UAAU,QAAQ,SAAS;2NAC8L,CAAC,CAACe,IAAI;AAEjO;;CAEC,GACD,OAAO,MAAMC,+BAA+Bd;IAC1C,OAAgBY,cAAcA,YAAW;IAEzC,OAAgBG,WAAW;QACzB;YACEC,SAAS;YACTJ,aAAa,CAAC,uHAAuH,CAAC;QACxI;KACD,CAAA;IAED,OAAgBK,QAAQ;QACtB,eAAelB,MAAMmB,MAAM,CAAC;YAC1BN,aACE;QAC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AK,CAAC,GAAGA,iBAAiBH,QAAQG,MAAMkB,OAAO,GAAG,iBAAiB,EAAE;gBACxEjB,MAAM;YACR;QACF;IACF;IAEA,MAAcrB,aAAa;QACzB,MAAM2B,QAAQ,IAAI,CAACC,SAAS,CAACD,KAAK,CAAC3C;QAEnC,IAAI;YACF,MAAM,EAACuB,QAAQsB,aAAa,EAAEnB,OAAO,EAAC,GAAG,MAAM,IAAI,CAACR,SAAS;YAC7DyB,MAAMvB,KAAK;YAEX,MAAM,EAACmC,OAAO,EAAEC,OAAO,EAAC,GAAGrD;YAE3B,MAAMsD,iBAAiB5D,kBAAkB;gBACvC0B,QAAQsB;gBACRnB;YACF;YAEA,MAAMgC,OAAO/D,KAAK;gBAChBgE,QAAQC,GAAG,CAAC,UAAUF;gBACtBC,QAAQC,GAAG,CAAC,WAAWF;gBAEvBf,MAAMM,GAAG,CAAC;oBACRY,MAAM;oBACN,GAAGJ,eAAeK,QAAQ,EAAE;gBAC9B;gBACAnB,MAAMU,QAAQ;gBAEd,MAAMI,eAAeC,IAAI;gBACzBF;YACF;YAEAG,QAAQI,EAAE,CAAC,UAAUL;YACrBC,QAAQI,EAAE,CAAC,WAAWL;YAEtB,MAAMH;QACR,EAAE,OAAOnB,OAAO;YACdlC,MAAMkC;YACNO,MAAMP,KAAK,CAACA;YACZ,IAAI,CAACA,KAAK,CAAC,GAAGA,iBAAiBH,QAAQG,MAAMkB,OAAO,GAAG,iBAAiB,EAAE;gBACxEjB,MAAM;YACR;QACF;IACF;AACF"}
|
package/dist/readConfig.js
CHANGED
|
@@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises';
|
|
|
2
2
|
import json5 from 'json5';
|
|
3
3
|
import * as z from 'zod';
|
|
4
4
|
/**
|
|
5
|
-
* @
|
|
5
|
+
* @public
|
|
6
6
|
*/ export const configDefinition = z.object({
|
|
7
7
|
formatGeneratedCode: z.boolean().default(true),
|
|
8
8
|
generates: z.string().default('./sanity.types.ts'),
|
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 * @
|
|
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 * @public\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\n/** @public */\nexport type TypeGenConfig = z.infer<typeof configDefinition>\n\n/**\n * @deprecated use TypeGenConfig\n * @public\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;AAWF;;;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/dist/typeUtils.js
CHANGED
package/dist/typeUtils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/typeUtils.ts"],"sourcesContent":["/** Excludes `null` and `undefined` from a type. */\ntype NonNullish<T> = T extends null | undefined ? never : T\n\n/** Builds a tuple from elements, stopping at the first `never`. */\ntype TakeUntilNever<T extends unknown[]> = T extends [infer H, ...infer Rest]\n ? [H] extends [never]\n ? []\n : [H, ...TakeUntilNever<Rest>]\n : []\n\n/** Recursively navigates through a path, stripping nullability for key lookup. */\ntype NavigatePath<T, Path extends unknown[]> = Path extends []\n ? NonNullish<T>\n : Path extends [infer K, ...infer Rest]\n ? K extends keyof NonNullish<T>\n ? NavigatePath<NonNullish<T>[K], Rest>\n : never\n : never\n\n/** Recursively gets value at path, preserving nullability at final access. */\ntype GetAtPath<T, Path extends unknown[]> = Path extends []\n ? T\n : Path extends [infer K]\n ? K extends keyof NonNullish<T>\n ? NonNullish<T>[K]\n : never\n : Path extends [infer K, ...infer Rest]\n ? K extends keyof NonNullish<T>\n ? GetAtPath<NonNullish<T>[K], Rest>\n : never\n : never\n\n/**\n * Get a deeply nested property type from a complex type structure. Safely navigates\n * through nullable types (`T | null | undefined`) at each level, preserving the\n * nullability of the final accessed property.\n *\n * Supports up to 20 levels of nesting.\n *\n * @example\n * ```ts\n * type POST_QUERY_RESULT = {\n * _id: string\n * author: {\n * profile: {\n * name: string;\n * } | null;\n * } | null;\n * links: Array<{\n * _key: string\n * type: 'link'\n * label: string\n * url: string\n * }> | null\n * } | null\n *\n * // Basic property access:\n * type Id = Get<POST_QUERY_RESULT, '_id'>;\n * // → string\n *\n * // Nested property access:\n * type Profile = Get<POST_QUERY_RESULT, 'author', 'profile';\n * // → { name: string } | null\n *\n * // Array element access using `number`:\n * type Link = Get<POST_QUERY_RESULT, 'links', number, 'label'>;\n * // → string\n * ```\n */\nexport type Get<\n T,\n K1 extends keyof NonNullish<T>,\n K2 extends keyof NavigatePath<T, [K1]> = never,\n K3 extends keyof NavigatePath<T, [K1, K2]> = never,\n K4 extends keyof NavigatePath<T, [K1, K2, K3]> = never,\n K5 extends keyof NavigatePath<T, [K1, K2, K3, K4]> = never,\n K6 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5]> = never,\n K7 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6]> = never,\n K8 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7]> = never,\n K9 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8]> = never,\n K10 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9]> = never,\n K11 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10]> = never,\n K12 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11]> = never,\n K13 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12]> = never,\n K14 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13]> =\n never,\n K15 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14]> =\n never,\n K16 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15]\n > = never,\n K17 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16]\n > = never,\n K18 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17]\n > = never,\n K19 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17, K18]\n > = never,\n K20 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17, K18, K19]\n > = never,\n> = GetAtPath<\n T,\n TakeUntilNever<\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17, K18, K19, K20]\n >\n>\n\n/**\n * Filter a union of object types by the _type property. This is handy when working with page builder\n * setups where the returned type is an array containing multiple types.\n *\n * @example\n * ```ts\n *\n * export type Callout = {\n * _type: 'callout'\n * title?: string\n * content?: string\n * }\n *\n * export type Video = {\n * _type: 'video'\n * url?: string\n * caption?: string\n * }\n * type FORM_QUERY_RESULT = {\n * _id: string\n * title?: string\n * content?: Array<\n * | ({ _key: string } & Callout)\n * | ({ _key: string } & Video)\n * >\n * } | null\n *\n * // Get the type of the content with the Get helper\n * type Content = Get<FORM_QUERY_RESULT, 'content', number>\n *\n * // Get the type for a callout module from the page builder type\n * type CalloutModule = FilterByType<Content, 'callout'>\n * // → { _key: string } & Callout\n * ```\n */\nexport type FilterByType<U extends {_type: string}, T extends U['_type']> = Extract<U, {_type: T}>\n"],"names":[],"mappings":"AAAA,iDAAiD,
|
|
1
|
+
{"version":3,"sources":["../src/typeUtils.ts"],"sourcesContent":["/** Excludes `null` and `undefined` from a type. */\ntype NonNullish<T> = T extends null | undefined ? never : T\n\n/** Builds a tuple from elements, stopping at the first `never`. */\ntype TakeUntilNever<T extends unknown[]> = T extends [infer H, ...infer Rest]\n ? [H] extends [never]\n ? []\n : [H, ...TakeUntilNever<Rest>]\n : []\n\n/** Recursively navigates through a path, stripping nullability for key lookup. */\ntype NavigatePath<T, Path extends unknown[]> = Path extends []\n ? NonNullish<T>\n : Path extends [infer K, ...infer Rest]\n ? K extends keyof NonNullish<T>\n ? NavigatePath<NonNullish<T>[K], Rest>\n : never\n : never\n\n/** Recursively gets value at path, preserving nullability at final access. */\ntype GetAtPath<T, Path extends unknown[]> = Path extends []\n ? T\n : Path extends [infer K]\n ? K extends keyof NonNullish<T>\n ? NonNullish<T>[K]\n : never\n : Path extends [infer K, ...infer Rest]\n ? K extends keyof NonNullish<T>\n ? GetAtPath<NonNullish<T>[K], Rest>\n : never\n : never\n\n/**\n * Get a deeply nested property type from a complex type structure. Safely navigates\n * through nullable types (`T | null | undefined`) at each level, preserving the\n * nullability of the final accessed property.\n *\n * Supports up to 20 levels of nesting.\n *\n * @example\n * ```ts\n * type POST_QUERY_RESULT = {\n * _id: string\n * author: {\n * profile: {\n * name: string;\n * } | null;\n * } | null;\n * links: Array<{\n * _key: string\n * type: 'link'\n * label: string\n * url: string\n * }> | null\n * } | null\n *\n * // Basic property access:\n * type Id = Get<POST_QUERY_RESULT, '_id'>;\n * // → string\n *\n * // Nested property access:\n * type Profile = Get<POST_QUERY_RESULT, 'author', 'profile';\n * // → { name: string } | null\n *\n * // Array element access using `number`:\n * type Link = Get<POST_QUERY_RESULT, 'links', number, 'label'>;\n * // → string\n * ```\n * @public\n */\nexport type Get<\n T,\n K1 extends keyof NonNullish<T>,\n K2 extends keyof NavigatePath<T, [K1]> = never,\n K3 extends keyof NavigatePath<T, [K1, K2]> = never,\n K4 extends keyof NavigatePath<T, [K1, K2, K3]> = never,\n K5 extends keyof NavigatePath<T, [K1, K2, K3, K4]> = never,\n K6 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5]> = never,\n K7 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6]> = never,\n K8 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7]> = never,\n K9 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8]> = never,\n K10 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9]> = never,\n K11 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10]> = never,\n K12 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11]> = never,\n K13 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12]> = never,\n K14 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13]> =\n never,\n K15 extends keyof NavigatePath<T, [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14]> =\n never,\n K16 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15]\n > = never,\n K17 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16]\n > = never,\n K18 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17]\n > = never,\n K19 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17, K18]\n > = never,\n K20 extends keyof NavigatePath<\n T,\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17, K18, K19]\n > = never,\n> = GetAtPath<\n T,\n TakeUntilNever<\n [K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, K12, K13, K14, K15, K16, K17, K18, K19, K20]\n >\n>\n\n/**\n * Filter a union of object types by the _type property. This is handy when working with page builder\n * setups where the returned type is an array containing multiple types.\n *\n * @example\n * ```ts\n *\n * export type Callout = {\n * _type: 'callout'\n * title?: string\n * content?: string\n * }\n *\n * export type Video = {\n * _type: 'video'\n * url?: string\n * caption?: string\n * }\n * type FORM_QUERY_RESULT = {\n * _id: string\n * title?: string\n * content?: Array<\n * | ({ _key: string } & Callout)\n * | ({ _key: string } & Video)\n * >\n * } | null\n *\n * // Get the type of the content with the Get helper\n * type Content = Get<FORM_QUERY_RESULT, 'content', number>\n *\n * // Get the type for a callout module from the page builder type\n * type CalloutModule = FilterByType<Content, 'callout'>\n * // → { _key: string } & Callout\n * ```\n * @public\n */\nexport type FilterByType<U extends {_type: string}, T extends U['_type']> = Extract<U, {_type: T}>\n"],"names":[],"mappings":"AAAA,iDAAiD,GAoHjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCC,GACD,WAAkG"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { defineTrace } from '@sanity/telemetry';
|
|
2
|
-
export const TypesGeneratedTrace = defineTrace({
|
|
2
|
+
/** @public */ export const TypesGeneratedTrace = defineTrace({
|
|
3
3
|
description: 'Trace emitted when generating TypeScript types for queries',
|
|
4
4
|
name: 'Types Generated',
|
|
5
5
|
version: 0
|
|
6
6
|
});
|
|
7
|
-
export const TypegenWatchModeTrace = defineTrace({
|
|
7
|
+
/** @public */ export const TypegenWatchModeTrace = defineTrace({
|
|
8
8
|
description: 'Trace emitted when typegen watch mode is run',
|
|
9
9
|
name: 'Typegen Watch Mode Started',
|
|
10
10
|
version: 0
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/typegen.telemetry.ts"],"sourcesContent":["import {defineTrace} from '@sanity/telemetry'\n\ninterface TypesGeneratedTraceAttributes {\n configMethod: 'cli' | 'legacy'\n configOverloadClientMethods: boolean\n emptyUnionTypeNodesGenerated: number\n filesWithErrors: number\n outputSize: number\n queriesCount: number\n queryFilesCount: number\n schemaTypesCount: number\n typeNodesGenerated: number\n unknownTypeNodesGenerated: number\n unknownTypeNodesRatio: number\n}\n\nexport const TypesGeneratedTrace = defineTrace<TypesGeneratedTraceAttributes>({\n description: 'Trace emitted when generating TypeScript types for queries',\n name: 'Types Generated',\n version: 0,\n})\n\n/**\n * Attributes for typegen watch mode trace - tracks the start and stop of watch mode\n * sessions with statistics about generation runs.\n */\nexport type TypegenWatchModeTraceAttributes =\n | {\n averageGenerationDuration: number\n generationFailedCount: number\n generationSuccessfulCount: number\n step: 'stopped'\n watcherDuration: number\n }\n | {\n step: 'started'\n }\n\nexport const TypegenWatchModeTrace = defineTrace<TypegenWatchModeTraceAttributes>({\n description: 'Trace emitted when typegen watch mode is run',\n name: 'Typegen Watch Mode Started',\n version: 0,\n})\n"],"names":["defineTrace","TypesGeneratedTrace","description","name","version","TypegenWatchModeTrace"],"mappings":"AAAA,SAAQA,WAAW,QAAO,oBAAmB;AAgB7C,OAAO,MAAMC,sBAAsBD,YAA2C;IAC5EE,aAAa;IACbC,MAAM;IACNC,SAAS;AACX,GAAE;AAkBF,OAAO,MAAMC,wBAAwBL,YAA6C;IAChFE,aAAa;IACbC,MAAM;IACNC,SAAS;AACX,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../src/typegen.telemetry.ts"],"sourcesContent":["import {defineTrace} from '@sanity/telemetry'\n\ninterface TypesGeneratedTraceAttributes {\n configMethod: 'cli' | 'legacy'\n configOverloadClientMethods: boolean\n emptyUnionTypeNodesGenerated: number\n filesWithErrors: number\n outputSize: number\n queriesCount: number\n queryFilesCount: number\n schemaTypesCount: number\n typeNodesGenerated: number\n unknownTypeNodesGenerated: number\n unknownTypeNodesRatio: number\n}\n\n/** @public */\nexport const TypesGeneratedTrace = defineTrace<TypesGeneratedTraceAttributes>({\n description: 'Trace emitted when generating TypeScript types for queries',\n name: 'Types Generated',\n version: 0,\n})\n\n/**\n * Attributes for typegen watch mode trace - tracks the start and stop of watch mode\n * sessions with statistics about generation runs.\n */\nexport type TypegenWatchModeTraceAttributes =\n | {\n averageGenerationDuration: number\n generationFailedCount: number\n generationSuccessfulCount: number\n step: 'stopped'\n watcherDuration: number\n }\n | {\n step: 'started'\n }\n\n/** @public */\nexport const TypegenWatchModeTrace = defineTrace<TypegenWatchModeTraceAttributes>({\n description: 'Trace emitted when typegen watch mode is run',\n name: 'Typegen Watch Mode Started',\n version: 0,\n})\n"],"names":["defineTrace","TypesGeneratedTrace","description","name","version","TypegenWatchModeTrace"],"mappings":"AAAA,SAAQA,WAAW,QAAO,oBAAmB;AAgB7C,YAAY,GACZ,OAAO,MAAMC,sBAAsBD,YAA2C;IAC5EE,aAAa;IACbC,MAAM;IACNC,SAAS;AACX,GAAE;AAkBF,YAAY,GACZ,OAAO,MAAMC,wBAAwBL,YAA6C;IAChFE,aAAa;IACbC,MAAM;IACNC,SAAS;AACX,GAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/typescript/typeGenerator.ts"],"sourcesContent":["/* eslint-disable unicorn/consistent-function-scoping */\nimport process from 'node:process'\n\nimport * as t from '@babel/types'\nimport {type WorkerChannel, type WorkerChannelReporter} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\nimport {createSelector} from 'reselect'\n\nimport {resultSuffix} from '../casing.js'\nimport {\n ALL_SANITY_SCHEMA_TYPES,\n ARRAY_OF,\n INTERNAL_REFERENCE_SYMBOL,\n SANITY_QUERIES,\n} from './constants.js'\nimport {\n computeOnce,\n generateCode,\n getUniqueIdentifierForName,\n normalizePrintablePath,\n} from './helpers.js'\nimport {SchemaTypeGenerator} from './schemaTypeGenerator.js'\nimport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n QueryEvaluationError,\n type QueryExtractionError,\n} from './types.js'\n\nexport type TypegenWorkerChannel = WorkerChannel.Definition<{\n evaluatedModules: WorkerChannel.Stream<EvaluatedModule>\n generatedQueryTypes: WorkerChannel.Event<{\n queryMapDeclaration: {ast: t.Program; code: string}\n }>\n generatedSchemaTypes: WorkerChannel.Event<{\n allSanitySchemaTypesDeclaration: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n internalReferenceSymbol: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n schemaTypeDeclarations: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n name: string\n tsType: t.TSType\n }[]\n }>\n}>\n\nexport interface GenerateTypesOptions {\n schema: SchemaType\n\n overloadClientMethods?: boolean\n queries?: AsyncIterable<ExtractedModule>\n reporter?: WorkerChannelReporter<TypegenWorkerChannel>\n root?: string\n schemaPath?: string\n}\n\ntype GetEvaluatedModulesOptions = GenerateTypesOptions & {\n schemaTypeDeclarations: ReturnType<TypeGenerator['getSchemaTypeDeclarations']>\n schemaTypeGenerator: SchemaTypeGenerator\n}\ntype GetQueryMapDeclarationOptions = GenerateTypesOptions & {\n evaluatedModules: EvaluatedModule[]\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @beta\n */\nexport class TypeGenerator {\n private getSchemaTypeGenerator = createSelector(\n [(options: GenerateTypesOptions) => options.schema],\n\n (schema) => new SchemaTypeGenerator(schema),\n )\n\n private getSchemaTypeDeclarations = createSelector(\n [\n (options: GenerateTypesOptions) => options.root,\n (options: GenerateTypesOptions) => options.schemaPath,\n this.getSchemaTypeGenerator,\n ],\n\n (root = process.cwd(), schemaPath, schema) =>\n [...schema].map(({id, name, tsType}, index) => {\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n let ast = t.exportNamedDeclaration(typeAlias)\n\n if (index === 0 && schemaPath) {\n ast = t.addComments(ast, 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, schemaPath)}`},\n ])\n }\n const code = generateCode(ast)\n return {ast, code, id, name, tsType}\n }),\n )\n\n private getAllSanitySchemaTypesDeclaration = createSelector(\n [this.getSchemaTypeDeclarations],\n (schemaTypes) => {\n const ast = t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n ALL_SANITY_SCHEMA_TYPES,\n null,\n schemaTypes.length > 0\n ? t.tsUnionType(schemaTypes.map(({id}) => t.tsTypeReference(id)))\n : t.tsNeverKeyword(),\n ),\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ALL_SANITY_SCHEMA_TYPES}\n },\n )\n\n private getArrayOfDeclaration = computeOnce(() => {\n // Creates: type ArrayOf<T> = Array<T & { _key: string }>;\n const typeParam = t.tsTypeParameter(null, null, 'T')\n const intersectionType = t.tsIntersectionType([\n t.tsTypeReference(t.identifier('T')),\n t.tsTypeLiteral([\n t.tsPropertySignature(t.identifier('_key'), t.tsTypeAnnotation(t.tsStringKeyword())),\n ]),\n ])\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([intersectionType]),\n )\n\n const ast = t.tsTypeAliasDeclaration(\n ARRAY_OF,\n t.tsTypeParameterDeclaration([typeParam]),\n arrayType,\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ARRAY_OF}\n })\n\n private getInternalReferenceSymbolDeclaration = computeOnce(() => {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), 'unique')\n\n const id = INTERNAL_REFERENCE_SYMBOL\n id.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const declaration = t.variableDeclaration('const', [t.variableDeclarator(id)])\n declaration.declare = true\n const ast = t.exportNamedDeclaration(declaration)\n const code = generateCode(ast)\n\n return {ast, code, id}\n })\n\n private static async getEvaluatedModules({\n queries: extractedModules,\n reporter: report,\n root = process.cwd(),\n schemaTypeDeclarations,\n schemaTypeGenerator,\n }: GetEvaluatedModulesOptions) {\n if (!extractedModules) {\n report?.stream.evaluatedModules.end()\n return []\n }\n\n const currentIdentifiers = new Set<string>(schemaTypeDeclarations.map(({id}) => id.name))\n const evaluatedModuleResults: EvaluatedModule[] = []\n\n for await (const {filename, ...extractedModule} of extractedModules) {\n const queries: EvaluatedQuery[] = []\n const errors: (QueryEvaluationError | QueryExtractionError)[] = [...extractedModule.errors]\n\n for (const extractedQuery of extractedModule.queries) {\n const {variable} = extractedQuery\n try {\n const {stats, tsType} = schemaTypeGenerator.evaluateQuery(extractedQuery)\n const id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers)\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n const trimmedQuery = extractedQuery.query.replaceAll(/(\\r\\n|\\n|\\r)/gm, '').trim()\n const ast = t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, filename)}`},\n {type: 'CommentLine', value: ` Variable: ${variable.id.name}`},\n {type: 'CommentLine', value: ` Query: ${trimmedQuery}`},\n ])\n\n const evaluatedQueryResult: EvaluatedQuery = {\n ast,\n code: generateCode(ast),\n id,\n stats,\n tsType,\n ...extractedQuery,\n }\n\n currentIdentifiers.add(id.name)\n queries.push(evaluatedQueryResult)\n } catch (cause) {\n errors.push(new QueryEvaluationError({cause, filename, variable}))\n }\n }\n\n const evaluatedModule: EvaluatedModule = {\n errors,\n filename,\n queries,\n }\n report?.stream.evaluatedModules.emit(evaluatedModule)\n evaluatedModuleResults.push(evaluatedModule)\n }\n report?.stream.evaluatedModules.end()\n\n return evaluatedModuleResults\n }\n\n private static async getQueryMapDeclaration({\n evaluatedModules,\n overloadClientMethods = true,\n }: GetQueryMapDeclarationOptions) {\n if (!overloadClientMethods) return {ast: t.program([]), code: ''}\n\n const queries = evaluatedModules.flatMap((module) => module.queries)\n if (queries.length === 0) return {ast: t.program([]), code: ''}\n\n const typesByQuerystring: {[query: string]: string[]} = {}\n for (const {id, query} of queries) {\n typesByQuerystring[query] ??= []\n typesByQuerystring[query].push(id.name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [],\n t.tsInterfaceBody(\n Object.entries(typesByQuerystring).map(([query, types]) => {\n return t.tsPropertySignature(\n t.stringLiteral(query),\n t.tsTypeAnnotation(\n types.length > 0\n ? t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type))))\n : t.tsNeverKeyword(),\n ),\n )\n }),\n ),\n )\n\n const declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.addComments(\n t.importDeclaration([], t.stringLiteral('@sanity/client')),\n 'leading',\n [{type: 'CommentLine', value: ' Query TypeMap'}],\n )\n\n const ast = t.program([clientImport, declareModule])\n const code = generateCode(ast)\n return {ast, code}\n }\n\n async generateTypes(options: GenerateTypesOptions) {\n const {reporter: report} = options\n const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration()\n const schemaTypeGenerator = this.getSchemaTypeGenerator(options)\n const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options)\n const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options)\n\n report?.event.generatedSchemaTypes({\n allSanitySchemaTypesDeclaration,\n internalReferenceSymbol,\n schemaTypeDeclarations,\n })\n\n const program = t.program([])\n let code = ''\n\n for (const declaration of schemaTypeDeclarations) {\n program.body.push(declaration.ast)\n code += declaration.code\n }\n\n program.body.push(allSanitySchemaTypesDeclaration.ast)\n code += allSanitySchemaTypesDeclaration.code\n\n program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator,\n })\n\n // Only generate ArrayOf if it's actually used\n if (schemaTypeGenerator.isArrayOfUsed()) {\n const arrayOfDeclaration = this.getArrayOfDeclaration()\n program.body.push(arrayOfDeclaration.ast)\n code += arrayOfDeclaration.code\n }\n\n for (const {queries} of evaluatedModules) {\n for (const query of queries) {\n program.body.push(query.ast)\n code += query.code\n }\n }\n\n const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({\n ...options,\n evaluatedModules,\n })\n program.body.push(...queryMapDeclaration.ast.body)\n code += queryMapDeclaration.code\n\n report?.event.generatedQueryTypes({queryMapDeclaration})\n\n return {ast: program, code}\n }\n}\n"],"names":["process","t","createSelector","resultSuffix","ALL_SANITY_SCHEMA_TYPES","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","SANITY_QUERIES","computeOnce","generateCode","getUniqueIdentifierForName","normalizePrintablePath","SchemaTypeGenerator","QueryEvaluationError","TypeGenerator","getSchemaTypeGenerator","options","schema","getSchemaTypeDeclarations","root","schemaPath","cwd","map","id","name","tsType","index","typeAlias","tsTypeAliasDeclaration","ast","exportNamedDeclaration","addComments","type","value","code","getAllSanitySchemaTypesDeclaration","schemaTypes","length","tsUnionType","tsTypeReference","tsNeverKeyword","getArrayOfDeclaration","typeParam","tsTypeParameter","intersectionType","tsIntersectionType","identifier","tsTypeLiteral","tsPropertySignature","tsTypeAnnotation","tsStringKeyword","arrayType","tsTypeParameterInstantiation","tsTypeParameterDeclaration","getInternalReferenceSymbolDeclaration","typeOperator","tsTypeOperator","tsSymbolKeyword","typeAnnotation","declaration","variableDeclaration","variableDeclarator","declare","getEvaluatedModules","queries","extractedModules","reporter","report","schemaTypeDeclarations","schemaTypeGenerator","stream","evaluatedModules","end","currentIdentifiers","Set","evaluatedModuleResults","filename","extractedModule","errors","extractedQuery","variable","stats","evaluateQuery","trimmedQuery","query","replaceAll","trim","evaluatedQueryResult","add","push","cause","evaluatedModule","emit","getQueryMapDeclaration","overloadClientMethods","program","flatMap","module","typesByQuerystring","queryReturnInterface","tsInterfaceDeclaration","tsInterfaceBody","Object","entries","types","stringLiteral","declareModule","blockStatement","clientImport","importDeclaration","generateTypes","internalReferenceSymbol","allSanitySchemaTypesDeclaration","event","generatedSchemaTypes","body","isArrayOfUsed","arrayOfDeclaration","queryMapDeclaration","generatedQueryTypes"],"mappings":"AAAA,sDAAsD,GACtD,OAAOA,aAAa,eAAc;AAElC,YAAYC,OAAO,eAAc;AAGjC,SAAQC,cAAc,QAAO,WAAU;AAEvC,SAAQC,YAAY,QAAO,eAAc;AACzC,SACEC,uBAAuB,EACvBC,QAAQ,EACRC,yBAAyB,EACzBC,cAAc,QACT,iBAAgB;AACvB,SACEC,WAAW,EACXC,YAAY,EACZC,0BAA0B,EAC1BC,sBAAsB,QACjB,eAAc;AACrB,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAIEC,oBAAoB,QAEf,aAAY;AA8CnB;;;CAGC,GACD,OAAO,MAAMC;IACHC,yBAAyBb,eAC/B;QAAC,CAACc,UAAkCA,QAAQC,MAAM;KAAC,EAEnD,CAACA,SAAW,IAAIL,oBAAoBK,SACrC;IAEOC,4BAA4BhB,eAClC;QACE,CAACc,UAAkCA,QAAQG,IAAI;QAC/C,CAACH,UAAkCA,QAAQI,UAAU;QACrD,IAAI,CAACL,sBAAsB;KAC5B,EAED,CAACI,OAAOnB,QAAQqB,GAAG,EAAE,EAAED,YAAYH,SACjC;eAAIA;SAAO,CAACK,GAAG,CAAC,CAAC,EAACC,EAAE,EAAEC,IAAI,EAAEC,MAAM,EAAC,EAAEC;YACnC,MAAMC,YAAY1B,EAAE2B,sBAAsB,CAACL,IAAI,MAAME;YACrD,IAAII,MAAM5B,EAAE6B,sBAAsB,CAACH;YAEnC,IAAID,UAAU,KAAKN,YAAY;gBAC7BS,MAAM5B,EAAE8B,WAAW,CAACF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AQoF,oBAAoBpF,IAAI;QAEhCiC,QAAQ8C,MAAMM,oBAAoB;YAACD;QAAmB;QAEtD,OAAO;YAACzF,KAAKkE;YAAS7D;QAAI;IAC5B;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/typescript/typeGenerator.ts"],"sourcesContent":["/* eslint-disable unicorn/consistent-function-scoping */\nimport process from 'node:process'\n\nimport * as t from '@babel/types'\nimport {type WorkerChannel, type WorkerChannelReporter} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\nimport {createSelector} from 'reselect'\n\nimport {resultSuffix} from '../casing.js'\nimport {\n ALL_SANITY_SCHEMA_TYPES,\n ARRAY_OF,\n INTERNAL_REFERENCE_SYMBOL,\n SANITY_QUERIES,\n} from './constants.js'\nimport {\n computeOnce,\n generateCode,\n getUniqueIdentifierForName,\n normalizePrintablePath,\n} from './helpers.js'\nimport {SchemaTypeGenerator} from './schemaTypeGenerator.js'\nimport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n QueryEvaluationError,\n type QueryExtractionError,\n} from './types.js'\n\n/** @public */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<{\n evaluatedModules: WorkerChannel.Stream<EvaluatedModule>\n generatedQueryTypes: WorkerChannel.Event<{\n queryMapDeclaration: {ast: t.Program; code: string}\n }>\n generatedSchemaTypes: WorkerChannel.Event<{\n allSanitySchemaTypesDeclaration: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n internalReferenceSymbol: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n schemaTypeDeclarations: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n name: string\n tsType: t.TSType\n }[]\n }>\n}>\n\n/** @public */\nexport interface GenerateTypesOptions {\n schema: SchemaType\n\n overloadClientMethods?: boolean\n queries?: AsyncIterable<ExtractedModule>\n reporter?: WorkerChannelReporter<TypegenWorkerChannel>\n root?: string\n schemaPath?: string\n}\n\ntype GetEvaluatedModulesOptions = GenerateTypesOptions & {\n schemaTypeDeclarations: ReturnType<TypeGenerator['getSchemaTypeDeclarations']>\n schemaTypeGenerator: SchemaTypeGenerator\n}\ntype GetQueryMapDeclarationOptions = GenerateTypesOptions & {\n evaluatedModules: EvaluatedModule[]\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @beta\n */\nexport class TypeGenerator {\n private getSchemaTypeGenerator = createSelector(\n [(options: GenerateTypesOptions) => options.schema],\n\n (schema) => new SchemaTypeGenerator(schema),\n )\n\n private getSchemaTypeDeclarations = createSelector(\n [\n (options: GenerateTypesOptions) => options.root,\n (options: GenerateTypesOptions) => options.schemaPath,\n this.getSchemaTypeGenerator,\n ],\n\n (root = process.cwd(), schemaPath, schema) =>\n [...schema].map(({id, name, tsType}, index) => {\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n let ast = t.exportNamedDeclaration(typeAlias)\n\n if (index === 0 && schemaPath) {\n ast = t.addComments(ast, 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, schemaPath)}`},\n ])\n }\n const code = generateCode(ast)\n return {ast, code, id, name, tsType}\n }),\n )\n\n private getAllSanitySchemaTypesDeclaration = createSelector(\n [this.getSchemaTypeDeclarations],\n (schemaTypes) => {\n const ast = t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n ALL_SANITY_SCHEMA_TYPES,\n null,\n schemaTypes.length > 0\n ? t.tsUnionType(schemaTypes.map(({id}) => t.tsTypeReference(id)))\n : t.tsNeverKeyword(),\n ),\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ALL_SANITY_SCHEMA_TYPES}\n },\n )\n\n private getArrayOfDeclaration = computeOnce(() => {\n // Creates: type ArrayOf<T> = Array<T & { _key: string }>;\n const typeParam = t.tsTypeParameter(null, null, 'T')\n const intersectionType = t.tsIntersectionType([\n t.tsTypeReference(t.identifier('T')),\n t.tsTypeLiteral([\n t.tsPropertySignature(t.identifier('_key'), t.tsTypeAnnotation(t.tsStringKeyword())),\n ]),\n ])\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([intersectionType]),\n )\n\n const ast = t.tsTypeAliasDeclaration(\n ARRAY_OF,\n t.tsTypeParameterDeclaration([typeParam]),\n arrayType,\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ARRAY_OF}\n })\n\n private getInternalReferenceSymbolDeclaration = computeOnce(() => {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), 'unique')\n\n const id = INTERNAL_REFERENCE_SYMBOL\n id.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const declaration = t.variableDeclaration('const', [t.variableDeclarator(id)])\n declaration.declare = true\n const ast = t.exportNamedDeclaration(declaration)\n const code = generateCode(ast)\n\n return {ast, code, id}\n })\n\n private static async getEvaluatedModules({\n queries: extractedModules,\n reporter: report,\n root = process.cwd(),\n schemaTypeDeclarations,\n schemaTypeGenerator,\n }: GetEvaluatedModulesOptions) {\n if (!extractedModules) {\n report?.stream.evaluatedModules.end()\n return []\n }\n\n const currentIdentifiers = new Set<string>(schemaTypeDeclarations.map(({id}) => id.name))\n const evaluatedModuleResults: EvaluatedModule[] = []\n\n for await (const {filename, ...extractedModule} of extractedModules) {\n const queries: EvaluatedQuery[] = []\n const errors: (QueryEvaluationError | QueryExtractionError)[] = [...extractedModule.errors]\n\n for (const extractedQuery of extractedModule.queries) {\n const {variable} = extractedQuery\n try {\n const {stats, tsType} = schemaTypeGenerator.evaluateQuery(extractedQuery)\n const id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers)\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n const trimmedQuery = extractedQuery.query.replaceAll(/(\\r\\n|\\n|\\r)/gm, '').trim()\n const ast = t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, filename)}`},\n {type: 'CommentLine', value: ` Variable: ${variable.id.name}`},\n {type: 'CommentLine', value: ` Query: ${trimmedQuery}`},\n ])\n\n const evaluatedQueryResult: EvaluatedQuery = {\n ast,\n code: generateCode(ast),\n id,\n stats,\n tsType,\n ...extractedQuery,\n }\n\n currentIdentifiers.add(id.name)\n queries.push(evaluatedQueryResult)\n } catch (cause) {\n errors.push(new QueryEvaluationError({cause, filename, variable}))\n }\n }\n\n const evaluatedModule: EvaluatedModule = {\n errors,\n filename,\n queries,\n }\n report?.stream.evaluatedModules.emit(evaluatedModule)\n evaluatedModuleResults.push(evaluatedModule)\n }\n report?.stream.evaluatedModules.end()\n\n return evaluatedModuleResults\n }\n\n private static async getQueryMapDeclaration({\n evaluatedModules,\n overloadClientMethods = true,\n }: GetQueryMapDeclarationOptions) {\n if (!overloadClientMethods) return {ast: t.program([]), code: ''}\n\n const queries = evaluatedModules.flatMap((module) => module.queries)\n if (queries.length === 0) return {ast: t.program([]), code: ''}\n\n const typesByQuerystring: {[query: string]: string[]} = {}\n for (const {id, query} of queries) {\n typesByQuerystring[query] ??= []\n typesByQuerystring[query].push(id.name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [],\n t.tsInterfaceBody(\n Object.entries(typesByQuerystring).map(([query, types]) => {\n return t.tsPropertySignature(\n t.stringLiteral(query),\n t.tsTypeAnnotation(\n types.length > 0\n ? t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type))))\n : t.tsNeverKeyword(),\n ),\n )\n }),\n ),\n )\n\n const declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.addComments(\n t.importDeclaration([], t.stringLiteral('@sanity/client')),\n 'leading',\n [{type: 'CommentLine', value: ' Query TypeMap'}],\n )\n\n const ast = t.program([clientImport, declareModule])\n const code = generateCode(ast)\n return {ast, code}\n }\n\n async generateTypes(options: GenerateTypesOptions) {\n const {reporter: report} = options\n const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration()\n const schemaTypeGenerator = this.getSchemaTypeGenerator(options)\n const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options)\n const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options)\n\n report?.event.generatedSchemaTypes({\n allSanitySchemaTypesDeclaration,\n internalReferenceSymbol,\n schemaTypeDeclarations,\n })\n\n const program = t.program([])\n let code = ''\n\n for (const declaration of schemaTypeDeclarations) {\n program.body.push(declaration.ast)\n code += declaration.code\n }\n\n program.body.push(allSanitySchemaTypesDeclaration.ast)\n code += allSanitySchemaTypesDeclaration.code\n\n program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator,\n })\n\n // Only generate ArrayOf if it's actually used\n if (schemaTypeGenerator.isArrayOfUsed()) {\n const arrayOfDeclaration = this.getArrayOfDeclaration()\n program.body.push(arrayOfDeclaration.ast)\n code += arrayOfDeclaration.code\n }\n\n for (const {queries} of evaluatedModules) {\n for (const query of queries) {\n program.body.push(query.ast)\n code += query.code\n }\n }\n\n const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({\n ...options,\n evaluatedModules,\n })\n program.body.push(...queryMapDeclaration.ast.body)\n code += queryMapDeclaration.code\n\n report?.event.generatedQueryTypes({queryMapDeclaration})\n\n return {ast: program, code}\n }\n}\n"],"names":["process","t","createSelector","resultSuffix","ALL_SANITY_SCHEMA_TYPES","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","SANITY_QUERIES","computeOnce","generateCode","getUniqueIdentifierForName","normalizePrintablePath","SchemaTypeGenerator","QueryEvaluationError","TypeGenerator","getSchemaTypeGenerator","options","schema","getSchemaTypeDeclarations","root","schemaPath","cwd","map","id","name","tsType","index","typeAlias","tsTypeAliasDeclaration","ast","exportNamedDeclaration","addComments","type","value","code","getAllSanitySchemaTypesDeclaration","schemaTypes","length","tsUnionType","tsTypeReference","tsNeverKeyword","getArrayOfDeclaration","typeParam","tsTypeParameter","intersectionType","tsIntersectionType","identifier","tsTypeLiteral","tsPropertySignature","tsTypeAnnotation","tsStringKeyword","arrayType","tsTypeParameterInstantiation","tsTypeParameterDeclaration","getInternalReferenceSymbolDeclaration","typeOperator","tsTypeOperator","tsSymbolKeyword","typeAnnotation","declaration","variableDeclaration","variableDeclarator","declare","getEvaluatedModules","queries","extractedModules","reporter","report","schemaTypeDeclarations","schemaTypeGenerator","stream","evaluatedModules","end","currentIdentifiers","Set","evaluatedModuleResults","filename","extractedModule","errors","extractedQuery","variable","stats","evaluateQuery","trimmedQuery","query","replaceAll","trim","evaluatedQueryResult","add","push","cause","evaluatedModule","emit","getQueryMapDeclaration","overloadClientMethods","program","flatMap","module","typesByQuerystring","queryReturnInterface","tsInterfaceDeclaration","tsInterfaceBody","Object","entries","types","stringLiteral","declareModule","blockStatement","clientImport","importDeclaration","generateTypes","internalReferenceSymbol","allSanitySchemaTypesDeclaration","event","generatedSchemaTypes","body","isArrayOfUsed","arrayOfDeclaration","queryMapDeclaration","generatedQueryTypes"],"mappings":"AAAA,sDAAsD,GACtD,OAAOA,aAAa,eAAc;AAElC,YAAYC,OAAO,eAAc;AAGjC,SAAQC,cAAc,QAAO,WAAU;AAEvC,SAAQC,YAAY,QAAO,eAAc;AACzC,SACEC,uBAAuB,EACvBC,QAAQ,EACRC,yBAAyB,EACzBC,cAAc,QACT,iBAAgB;AACvB,SACEC,WAAW,EACXC,YAAY,EACZC,0BAA0B,EAC1BC,sBAAsB,QACjB,eAAc;AACrB,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAIEC,oBAAoB,QAEf,aAAY;AAgDnB;;;CAGC,GACD,OAAO,MAAMC;IACHC,yBAAyBb,eAC/B;QAAC,CAACc,UAAkCA,QAAQC,MAAM;KAAC,EAEnD,CAACA,SAAW,IAAIL,oBAAoBK,SACrC;IAEOC,4BAA4BhB,eAClC;QACE,CAACc,UAAkCA,QAAQG,IAAI;QAC/C,CAACH,UAAkCA,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C;QAEA,KAAK,MAAM,EAAC8B,OAAO,EAAC,IAAIO,iBAAkB;YACxC,KAAK,MAAMa,SAASpB,QAAS;gBAC3B+B,QAAQoB,IAAI,CAAC1B,IAAI,CAACL,MAAMvD,GAAG;gBAC3BK,QAAQkD,MAAMlD,IAAI;YACpB;QACF;QAEA,MAAMoF,sBAAsB,MAAMxG,cAAc+E,sBAAsB,CAAC;YACrE,GAAG7E,OAAO;YACVuD;QACF;QACAwB,QAAQoB,IAAI,CAAC1B,IAAI,IAAI6B,oBAAoBzF,GAAG,CAACsF,IAAI;QACjDjF,QAAQoF,oBAAoBpF,IAAI;QAEhCiC,QAAQ8C,MAAMM,oBAAoB;YAACD;QAAmB;QAEtD,OAAO;YAACzF,KAAKkE;YAAS7D;QAAI;IAC5B;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
|
-
import
|
|
4
|
+
import once from 'lodash-es/once.js';
|
|
5
5
|
const BIN = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../bin/run.js');
|
|
6
6
|
const isAssertionError = (e)=>e instanceof Error && e.name === 'AssertionError';
|
|
7
7
|
export async function testLongRunning(command, opts) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/test/testLongRunning.ts"],"sourcesContent":["import {spawn} from 'node:child_process'\nimport path from 'node:path'\nimport {fileURLToPath} from 'node:url'\n\nimport
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/test/testLongRunning.ts"],"sourcesContent":["import {spawn} from 'node:child_process'\nimport path from 'node:path'\nimport {fileURLToPath} from 'node:url'\n\nimport once from 'lodash-es/once.js'\n\nconst BIN = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../bin/run.js')\n\ninterface Options {\n expect: (o: {stderr: string; stdout: string}) => Promise<void> | void\n\n cwd?: string\n interval?: number\n timeout?: number\n}\n\nconst isAssertionError = (e: unknown) => e instanceof Error && e.name === 'AssertionError'\n\nexport async function testLongRunning(\n command: string[],\n opts: Options,\n): Promise<{stderr: string; stdout: string}> {\n const {cwd = process.cwd(), expect: assertion, interval = 150, timeout = 20_000} = opts\n let stderr = '',\n stdout = ''\n\n // spawn command in child process\n const child = spawn('node', [BIN, ...command], {\n cwd,\n env: {...process.env, NO_COLOR: '1'},\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n\n // track err and out\n child.stdout?.on('data', (d) => (stdout += d))\n child.stderr?.on('data', (d) => (stderr += d))\n\n const kill = once(() => child.kill('SIGTERM'))\n\n // track errors from the child process\n let exitError: Error | null = null\n child.on('exit', (code) => {\n if (code === 0) return\n exitError = new Error(`Process exited with code ${code}\\nstderr: ${stderr}`)\n })\n\n child.on('error', (e) => {\n exitError = e\n })\n\n // assert once every interval until expectation met, error or timeout\n const start = Date.now()\n async function assertExpectation(): Promise<{stderr: string; stdout: string}> {\n if (exitError) throw exitError\n\n try {\n await assertion({stderr, stdout})\n return {stderr, stdout}\n } catch (e) {\n if (!isAssertionError(e)) throw e\n if (Date.now() - start > timeout) throw e\n\n return new Promise((resolve) => {\n setTimeout(() => resolve(assertExpectation()), interval)\n })\n }\n }\n\n try {\n return await assertExpectation()\n } finally {\n kill()\n }\n}\n"],"names":["spawn","path","fileURLToPath","once","BIN","resolve","dirname","url","isAssertionError","e","Error","name","testLongRunning","command","opts","cwd","process","expect","assertion","interval","timeout","stderr","stdout","child","env","NO_COLOR","stdio","on","d","kill","exitError","code","start","Date","now","assertExpectation","Promise","setTimeout"],"mappings":"AAAA,SAAQA,KAAK,QAAO,qBAAoB;AACxC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,aAAa,QAAO,WAAU;AAEtC,OAAOC,UAAU,oBAAmB;AAEpC,MAAMC,MAAMH,KAAKI,OAAO,CAACJ,KAAKK,OAAO,CAACJ,cAAc,YAAYK,GAAG,IAAI;AAUvE,MAAMC,mBAAmB,CA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Q8B,sBAAsBhB;YACjD;QACF;IACF;IAEA,IAAI;QACF,OAAO,MAAMgB;IACf,SAAU;QACRN;IACF;AACF"}
|
package/oclif.config.js
CHANGED
package/oclif.manifest.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/codegen",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "6.0.0",
|
|
4
4
|
"description": "Codegen toolkit for Sanity.io",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -24,20 +24,15 @@
|
|
|
24
24
|
"type": "module",
|
|
25
25
|
"exports": {
|
|
26
26
|
".": {
|
|
27
|
-
"types": "./dist/index.d.ts",
|
|
28
27
|
"source": "./src/_exports/index.ts",
|
|
29
28
|
"default": "./dist/_exports/index.js"
|
|
30
29
|
},
|
|
31
30
|
"./package.json": "./package.json"
|
|
32
31
|
},
|
|
33
32
|
"main": "./dist/_exports/index.js",
|
|
34
|
-
"types": "./dist/index.d.ts",
|
|
35
|
-
"bin": {
|
|
36
|
-
"sanity-typegen": "./bin/run.js"
|
|
37
|
-
},
|
|
33
|
+
"types": "./dist/_exports/index.d.ts",
|
|
38
34
|
"files": [
|
|
39
35
|
"dist",
|
|
40
|
-
"bin",
|
|
41
36
|
"oclif.manifest.json",
|
|
42
37
|
"oclif.config.js",
|
|
43
38
|
"babel.config.json"
|
|
@@ -51,10 +46,7 @@
|
|
|
51
46
|
"@babel/register": "^7.28.6",
|
|
52
47
|
"@babel/traverse": "^7.28.6",
|
|
53
48
|
"@babel/types": "^7.28.6",
|
|
54
|
-
"@
|
|
55
|
-
"@oclif/plugin-help": "^6.2.37",
|
|
56
|
-
"@sanity/cli-core": "^0.1.0-alpha.15",
|
|
57
|
-
"@sanity/worker-channels": "^1.1.0",
|
|
49
|
+
"@sanity/worker-channels": "^2.0.0",
|
|
58
50
|
"chokidar": "^3.6.0",
|
|
59
51
|
"debug": "^4.4.3",
|
|
60
52
|
"globby": "^11.1.0",
|
|
@@ -68,12 +60,12 @@
|
|
|
68
60
|
"zod": "^4.3.6"
|
|
69
61
|
},
|
|
70
62
|
"devDependencies": {
|
|
71
|
-
"@eslint/compat": "^2.0.
|
|
72
|
-
"@
|
|
73
|
-
"@
|
|
74
|
-
"@sanity/cli
|
|
75
|
-
"@sanity/
|
|
76
|
-
"@sanity/telemetry": "^0.8.
|
|
63
|
+
"@eslint/compat": "^2.0.2",
|
|
64
|
+
"@sanity/cli-core": "^1.0.0",
|
|
65
|
+
"@sanity/cli-test": "^0.2.0",
|
|
66
|
+
"@sanity/eslint-config-cli": "^1.0.0",
|
|
67
|
+
"@sanity/pkg-utils": "^10.4.6",
|
|
68
|
+
"@sanity/telemetry": "^0.8.1",
|
|
77
69
|
"@swc/cli": "^0.7.9",
|
|
78
70
|
"@swc/core": "^1.15.8",
|
|
79
71
|
"@types/babel__core": "^7.20.5",
|
|
@@ -82,20 +74,22 @@
|
|
|
82
74
|
"@types/babel__traverse": "^7.28.0",
|
|
83
75
|
"@types/debug": "^4.1.12",
|
|
84
76
|
"@types/lodash-es": "^4.17.12",
|
|
85
|
-
"@types/node": "^20.19.
|
|
86
|
-
"@vitest/coverage-istanbul": "^4.0.
|
|
87
|
-
"eslint": "^9.39.
|
|
77
|
+
"@types/node": "^20.19.35",
|
|
78
|
+
"@vitest/coverage-istanbul": "^4.0.18",
|
|
79
|
+
"eslint": "^9.39.3",
|
|
88
80
|
"husky": "^9.1.7",
|
|
89
|
-
"lint-staged": "^16.
|
|
90
|
-
"oclif": "^4.22.
|
|
91
|
-
"prettier-plugin-packagejson": "^2.5.
|
|
81
|
+
"lint-staged": "^16.3.1",
|
|
82
|
+
"oclif": "^4.22.85",
|
|
83
|
+
"prettier-plugin-packagejson": "^2.5.22",
|
|
92
84
|
"rimraf": "^5.0.10",
|
|
93
85
|
"tinyglobby": "^0.2.15",
|
|
94
86
|
"typescript": "^5.9.3",
|
|
95
|
-
"vitest": "^4.0.
|
|
87
|
+
"vitest": "^4.0.18"
|
|
96
88
|
},
|
|
97
89
|
"peerDependencies": {
|
|
98
|
-
"@
|
|
90
|
+
"@oclif/core": "^4.8.0",
|
|
91
|
+
"@sanity/cli-core": "^1",
|
|
92
|
+
"@sanity/telemetry": "^0.8.1"
|
|
99
93
|
},
|
|
100
94
|
"engines": {
|
|
101
95
|
"node": ">=20.19 <22 || >=22.12"
|
|
@@ -106,8 +100,7 @@
|
|
|
106
100
|
"scripts": {
|
|
107
101
|
"build": "swc --delete-dir-on-start src -d dist --strip-leading-paths --ignore '**/__tests__/**' && pnpm run build:types",
|
|
108
102
|
"postbuild": "oclif manifest",
|
|
109
|
-
"build:
|
|
110
|
-
"build:types": "tsc --project tsconfig.lib.json && pnpm run build:api && rimraf dist/__tmp__",
|
|
103
|
+
"build:types": "pkg-utils build --emitDeclarationOnly",
|
|
111
104
|
"clean": "rimraf dist coverage",
|
|
112
105
|
"lint": "eslint . --fix",
|
|
113
106
|
"pretest": "pnpm build",
|
package/bin/run.js
DELETED
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {execute} from '@oclif/core'
|
|
3
|
-
import {CLI_TELEMETRY_SYMBOL} from '@sanity/cli-core'
|
|
4
|
-
|
|
5
|
-
const err = '\u001B[31m\u001B[1mERROR:\u001B[22m\u001B[39m '
|
|
6
|
-
const nodeVersionParts = process.version.replace(/^v/i, '').split('.').map(Number)
|
|
7
|
-
|
|
8
|
-
const majorVersion = nodeVersionParts[0]
|
|
9
|
-
const minorVersion = nodeVersionParts[1]
|
|
10
|
-
const patchVersion = nodeVersionParts[2]
|
|
11
|
-
|
|
12
|
-
function isSupportedNodeVersion(major, minor, patch) {
|
|
13
|
-
if (major === 20) {
|
|
14
|
-
if (minor > 19) return true
|
|
15
|
-
if (minor === 19 && patch >= 1) return true
|
|
16
|
-
return false
|
|
17
|
-
}
|
|
18
|
-
if (major === 21) return true
|
|
19
|
-
if (major === 22 && minor >= 12) return true
|
|
20
|
-
if (major > 22) return true
|
|
21
|
-
return false
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
if (!isSupportedNodeVersion(majorVersion, minorVersion, patchVersion)) {
|
|
25
|
-
// eslint-disable-next-line no-console
|
|
26
|
-
console.error(
|
|
27
|
-
`${err}Node.js version >=20.19.1 <22 or >=22.12 required. You are running ${process.version}`,
|
|
28
|
-
)
|
|
29
|
-
// eslint-disable-next-line no-console
|
|
30
|
-
console.error('')
|
|
31
|
-
process.exit(1)
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
if (process.env.NODE_ENV !== 'production') {
|
|
35
|
-
/**
|
|
36
|
-
* Telemetry is added via a plugin in the main CLI.
|
|
37
|
-
* This adds a mock implementation of the telemetry API to allow running this CLI for testing.
|
|
38
|
-
*
|
|
39
|
-
* We won't be exposing this API to the public, so it's ok to use a globalThis assignment.
|
|
40
|
-
*/
|
|
41
|
-
globalThis[CLI_TELEMETRY_SYMBOL] = {
|
|
42
|
-
trace: () => ({
|
|
43
|
-
complete: () => {},
|
|
44
|
-
error: () => {},
|
|
45
|
-
log: () => {},
|
|
46
|
-
start: () => {},
|
|
47
|
-
}),
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
await execute({dir: import.meta.url})
|