@sanity/codegen 7.0.3 → 8.1.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/README.md CHANGED
@@ -1,3 +1,29 @@
1
1
  # @sanity/codegen
2
2
 
3
3
  Codegen toolkit for Sanity.io, used to generate Typescript types for a Sanity Schema & GROQ queries.
4
+
5
+ ## Typed `client.fetch` results
6
+
7
+ With `overloadClientMethods` enabled (the default), the generated file ends with a query type map that registers every query it found, so `client.fetch(query)` in `@sanity/client`, and `sanityFetch({query})` in `next-sanity`, return the generated result type without a generic:
8
+
9
+ ```ts
10
+ // Query TypeMap
11
+ declare global {
12
+ interface SanityQueries {
13
+ '*[_type == "post"]': PostsQueryResult
14
+ }
15
+ }
16
+ // Lets @sanity/client releases that predate the global registry read it too
17
+ declare module '@sanity/client' {
18
+ interface SanityQueries extends globalThis.SanityQueries {}
19
+ }
20
+ ```
21
+
22
+ The two blocks serve different `@sanity/client` releases, and the same generated file works with all of them:
23
+
24
+ - The `declare global` block is the registry. `@sanity/client` releases that know about it read it directly, and because it is a global interface rather than a module augmentation, it does not depend on module resolution: it is seen whether or not `@sanity/client` is a direct dependency of the project that holds the generated file, however many copies of the client are installed (a copy nested inside `next-sanity` reads the same registry), and from every entry point, `@sanity/client/stega` included.
25
+ - The `declare module '@sanity/client'` block is a bridge for releases that only read the `SanityQueries` interface exported from `@sanity/client`, which is every release since 6.21.0. Interface merging unions the `extends` clauses of an interface's declarations, so the bridge makes that interface inherit the global registry. On releases that already inherit it, the bridge is a duplicate `extends` of the same type, which TypeScript accepts.
26
+
27
+ The bridge is the only line that resolves `@sanity/client`. When the client cannot be resolved from the generated file, TypeScript reports `TS2664: Invalid module name in augmentation` for it in a `.ts` file, while in a declaration file an augmentation whose module cannot be found is skipped silently. Pointing `generates` at a `.d.ts` path therefore keeps the file valid in such a layout, and the global registry still types the client that is installed.
28
+
29
+ The earlier output, a `declare module '@sanity/client'` block that carried the whole map, keeps working with every `@sanity/client` release that accepts the new one.
@@ -1,17 +1,12 @@
1
- import {BooleanFlag} from '@oclif/core/interfaces'
2
- import {CustomOptions} from '@oclif/core/interfaces'
3
1
  import {DefinedTelemetryTrace} from '@sanity/telemetry'
4
2
  import {ExprNode} from 'groq-js'
5
3
  import {FSWatcher} from 'chokidar'
6
- import {OptionFlag} from '@oclif/core/interfaces'
7
- import {SanityCommand} from '@sanity/cli-core'
8
4
  import {SchemaType} from 'groq-js'
9
- import {spinner} from '@sanity/cli-core/ux'
10
5
  import * as t from '@babel/types'
11
6
  import {TransformOptions} from '@babel/core'
7
+ import * as v from 'valibot'
12
8
  import {WorkerChannel} from '@sanity/worker-channels'
13
9
  import {WorkerChannelReporter} from '@sanity/worker-channels'
14
- import * as z from 'zod/mini'
15
10
 
16
11
  /**
17
12
  * @deprecated use TypeGenConfig
@@ -22,27 +17,31 @@ export declare type CodegenConfig = TypeGenConfig
22
17
  /**
23
18
  * @public
24
19
  */
25
- export declare const configDefinition: z.ZodMiniObject<
20
+ export declare const configDefinition: v.ObjectSchema<
26
21
  {
27
- formatGeneratedCode: z.ZodMiniDefault<
28
- z.ZodMiniUnion<
29
- readonly [
30
- z.ZodMiniBoolean<boolean>,
31
- z.ZodMiniEnum<{
32
- oxfmt: 'oxfmt'
33
- prettier: 'prettier'
34
- }>,
35
- ]
36
- >
22
+ readonly formatGeneratedCode: v.OptionalSchema<
23
+ v.UnionSchema<
24
+ [v.BooleanSchema<undefined>, v.PicklistSchema<['oxfmt', 'prettier'], undefined>],
25
+ undefined
26
+ >,
27
+ true
37
28
  >
38
- generates: z.ZodMiniDefault<z.ZodMiniString<string>>
39
- overloadClientMethods: z.ZodMiniDefault<z.ZodMiniBoolean<boolean>>
40
- path: z.ZodMiniDefault<
41
- z.ZodMiniUnion<readonly [z.ZodMiniString<string>, z.ZodMiniArray<z.ZodMiniString<string>>]>
29
+ readonly generates: v.OptionalSchema<v.StringSchema<undefined>, './sanity.types.ts'>
30
+ readonly overloadClientMethods: v.OptionalSchema<v.BooleanSchema<undefined>, true>
31
+ readonly path: v.OptionalSchema<
32
+ v.UnionSchema<
33
+ [v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>],
34
+ undefined
35
+ >,
36
+ readonly [
37
+ './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
38
+ './app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
39
+ './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',
40
+ ]
42
41
  >
43
- schema: z.ZodMiniDefault<z.ZodMiniString<string>>
42
+ readonly schema: v.OptionalSchema<v.StringSchema<undefined>, './schema.json'>
44
43
  },
45
- z.core.$strip
44
+ undefined
46
45
  >
47
46
 
48
47
  /**
@@ -387,7 +386,7 @@ export declare function registerBabel(babelOptions?: TransformOptions): void
387
386
  * Runs a single typegen generation.
388
387
  *
389
388
  * This is the programmatic API for generating TypeScript types from GROQ queries.
390
- * It spawns a worker thread to perform the generation and displays progress via CLI spinners.
389
+ * It spawns a worker thread to perform the generation and reports progress via the optional `onProgress` callback.
391
390
  *
392
391
  * @param options - Configuration options including typegen config and working directory
393
392
  * @returns Generation result containing the generated code and statistics
@@ -397,7 +396,6 @@ export declare function runTypegenGenerate(options: RunTypegenOptions): Promise<
397
396
 
398
397
  /**
399
398
  * Options for running a single typegen generation.
400
- * This is the programmatic API for one-off generation without file watching.
401
399
  * @public
402
400
  */
403
401
  export declare interface RunTypegenOptions {
@@ -405,8 +403,8 @@ export declare interface RunTypegenOptions {
405
403
  workDir: string
406
404
  /** Typegen configuration */
407
405
  config?: Partial<TypeGenConfig>
408
- /** Optional spinner instance for progress display */
409
- spin?: ReturnType<typeof spinner>
406
+ /** Optional progress reporter. Called synchronously as generation proceeds. */
407
+ onProgress?: (event: TypegenProgressEvent) => void
410
408
  }
411
409
 
412
410
  /**
@@ -446,7 +444,7 @@ declare interface TypeEvaluationStats {
446
444
  }
447
445
 
448
446
  /** @public */
449
- export declare type TypeGenConfig = z.infer<typeof configDefinition>
447
+ export declare type TypeGenConfig = v.InferOutput<typeof configDefinition>
450
448
 
451
449
  /**
452
450
  * A class used to generate TypeScript types from a given schema
@@ -467,23 +465,43 @@ export declare class TypeGenerator {
467
465
  }
468
466
 
469
467
  /**
470
- * @internal
468
+ * A progress event emitted during a single typegen run.
469
+ * Consumers (e.g. the Sanity CLI) render these; the library performs no terminal output.
470
+ * @public
471
471
  */
472
- export declare class TypegenGenerateCommand extends SanityCommand<typeof TypegenGenerateCommand> {
473
- static description: string
474
- static examples: {
475
- command: string
476
- description: string
477
- }[]
478
- static flags: {
479
- 'config-path': OptionFlag<string | undefined, CustomOptions>
480
- watch: BooleanFlag<boolean>
481
- }
482
- run(): Promise<void>
483
- private getConfig
484
- private runSingle
485
- private runWatcher
486
- }
472
+ export declare type TypegenProgressEvent =
473
+ | {
474
+ type: 'schemaLoaded'
475
+ }
476
+ | {
477
+ type: 'typegenStarted'
478
+ expectedFileCount: number
479
+ }
480
+ | {
481
+ type: 'schemaTypesGenerated'
482
+ schemaTypesCount: number
483
+ }
484
+ | {
485
+ type: 'moduleEvaluated'
486
+ evaluatedFiles: number
487
+ expectedFileCount: number
488
+ queriesCount: number
489
+ queryFilesCount: number
490
+ errors: string[]
491
+ }
492
+ | {
493
+ type: 'formatting'
494
+ formatterName: string
495
+ }
496
+ | {
497
+ type: 'formatFailed'
498
+ formatterName: string
499
+ message: string
500
+ }
501
+ | {
502
+ type: 'complete'
503
+ result: GenerationResult
504
+ }
487
505
 
488
506
  /** @public */
489
507
  export declare const TypegenWatchModeTrace: DefinedTelemetryTrace<
@@ -1,6 +1,5 @@
1
1
  export { runTypegenGenerate } from '../actions/typegenGenerate.js';
2
2
  export { runTypegenWatcher } from '../actions/typegenWatch.js';
3
- export { TypegenGenerateCommand } from '../commands/typegen/generate.js';
4
3
  export { configDefinition, readConfig } from '../readConfig.js';
5
4
  export { readSchema } from '../readSchema.js';
6
5
  export { safeParseQuery } from '../safeParseQuery.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_exports/index.ts"],"sourcesContent":["export {runTypegenGenerate} from '../actions/typegenGenerate.js'\nexport {runTypegenWatcher} from '../actions/typegenWatch.js'\nexport {type GenerationResult, type RunTypegenOptions} from '../actions/types.js'\nexport {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 {TypegenWatchModeTrace, TypesGeneratedTrace} from '../typegen.telemetry.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":["runTypegenGenerate","runTypegenWatcher","TypegenGenerateCommand","configDefinition","readConfig","readSchema","safeParseQuery","TypegenWatchModeTrace","TypesGeneratedTrace","findQueriesInPath","findQueriesInSource","getResolver","registerBabel","TypeGenerator","QueryExtractionError"],"mappings":"AAAA,SAAQA,kBAAkB,QAAO,gCAA+B;AAChE,SAAQC,iBAAiB,QAAO,6BAA4B;AAE5D,SAAQC,sBAAsB,QAAO,kCAAiC;AACtE,SAEEC,gBAAgB,EAChBC,UAAU,QAEL,mBAAkB;AACzB,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,qBAAqB,EAAEC,mBAAmB,QAAO,0BAAyB;AAClF,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"}
1
+ {"version":3,"sources":["../../src/_exports/index.ts"],"sourcesContent":["export {runTypegenGenerate} from '../actions/typegenGenerate.js'\nexport {runTypegenWatcher} from '../actions/typegenWatch.js'\nexport {\n type GenerationResult,\n type RunTypegenOptions,\n type TypegenProgressEvent,\n} from '../actions/types.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 {TypegenWatchModeTrace, TypesGeneratedTrace} from '../typegen.telemetry.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":["runTypegenGenerate","runTypegenWatcher","configDefinition","readConfig","readSchema","safeParseQuery","TypegenWatchModeTrace","TypesGeneratedTrace","findQueriesInPath","findQueriesInSource","getResolver","registerBabel","TypeGenerator","QueryExtractionError"],"mappings":"AAAA,SAAQA,kBAAkB,QAAO,gCAA+B;AAChE,SAAQC,iBAAiB,QAAO,6BAA4B;AAM5D,SAEEC,gBAAgB,EAChBC,UAAU,QAEL,mBAAkB;AACzB,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,qBAAqB,EAAEC,mBAAmB,QAAO,0BAAyB;AAClF,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"}
@@ -1,33 +1,33 @@
1
1
  import { writeFile } from 'node:fs/promises';
2
- import { spinner } from '@sanity/cli-core/ux';
3
- import { count } from '../utils/count.js';
4
2
  import { debug } from '../utils/debug.js';
5
- import { formatPath } from '../utils/formatPath.js';
6
3
  import { getMessage } from '../utils/getMessage.js';
7
- import { percent } from '../utils/percent.js';
8
4
  import { defineFormatter } from '../utils/resolveFormatter.js';
9
5
  import { generatedFileWarning } from './generatedFileWarning.js';
6
+ const noopProgress = (_event)=>{};
10
7
  /**
11
8
  * Processes the event stream from a typegen worker thread.
12
9
  *
13
- * Listens to worker channel events, displays progress via CLI spinners,
14
- * writes the generated types to disk, and optionally formats with prettier.
15
- *
16
- * @param receiver - Worker channel receiver for typegen events
17
- * @param options - Typegen configuration options
18
- * @returns Generation result containing the generated code and statistics
19
- */ export async function processTypegenWorkerStream(receiver, options) {
10
+ * Consumes worker channel events, reports progress via `onProgress`,
11
+ * writes generated types to disk, and optionally formats them.
12
+ */ export async function processTypegenWorkerStream(receiver, options, onProgress = noopProgress) {
20
13
  const start = Date.now();
21
- const { formatGeneratedCode, generates, schema } = options;
22
- const spin = spinner().start(`Loading schema…`);
14
+ const { formatGeneratedCode, generates } = options;
23
15
  try {
24
16
  await receiver.event.loadedSchema();
25
- spin.succeed(`Schema loaded from ${formatPath(schema ?? '')}`);
26
- spin.start('Generating schema types…');
17
+ onProgress({
18
+ type: 'schemaLoaded'
19
+ });
27
20
  const { expectedFileCount } = await receiver.event.typegenStarted();
21
+ onProgress({
22
+ expectedFileCount,
23
+ type: 'typegenStarted'
24
+ });
28
25
  const { schemaTypeDeclarations } = await receiver.event.generatedSchemaTypes();
29
26
  const schemaTypesCount = schemaTypeDeclarations.length;
30
- spin.text = 'Generating query types…';
27
+ onProgress({
28
+ schemaTypesCount,
29
+ type: 'schemaTypesGenerated'
30
+ });
31
31
  let queriesCount = 0;
32
32
  let evaluatedFiles = 0;
33
33
  let filesWithErrors = 0;
@@ -45,40 +45,42 @@ import { generatedFileWarning } from './generatedFileWarning.js';
45
45
  unknownTypeNodesGenerated += stats.unknownTypes;
46
46
  emptyUnionTypeNodesGenerated += stats.emptyUnions;
47
47
  }
48
- for (const error of errors){
49
- spin.fail(getMessage(error));
50
- }
51
- if (!spin.isSpinning) {
52
- spin.start();
53
- }
54
- spin.text = `Generating query types… (${percent(evaluatedFiles / expectedFileCount)})\n` + ` └─ Processed ${count(evaluatedFiles)} of ${count(expectedFileCount, 'files')}. ` + `Found ${count(queriesCount, 'queries', 'query')} from ${count(queryFilesCount, 'files')}.`;
48
+ onProgress({
49
+ errors: errors.map((error)=>getMessage(error)),
50
+ evaluatedFiles,
51
+ expectedFileCount,
52
+ queriesCount,
53
+ queryFilesCount,
54
+ type: 'moduleEvaluated'
55
+ });
55
56
  }
56
57
  const result = await receiver.event.typegenComplete();
57
58
  const code = `${generatedFileWarning}${result.code}`;
58
59
  await writeFile(generates, code);
59
- let formattingError = false;
60
- let formatterName;
61
60
  if (formatGeneratedCode !== false) {
62
61
  const formatter = defineFormatter(formatGeneratedCode);
63
62
  if (formatter) {
64
- formatterName = formatter.name;
65
63
  try {
66
64
  const { format } = await formatter.resolve();
67
65
  if (format) {
68
- spin.text = `Formatting generated types with ${formatter.name}…`;
66
+ onProgress({
67
+ formatterName: formatter.name,
68
+ type: 'formatting'
69
+ });
69
70
  const formattedCode = await format(generates, code);
70
71
  await writeFile(generates, formattedCode);
71
72
  }
72
73
  } catch (err) {
73
- formattingError = true;
74
- spin.warn(`Failed to format generated types with ${formatter.name}: ${getMessage(err)}`);
74
+ onProgress({
75
+ formatterName: formatter.name,
76
+ message: getMessage(err),
77
+ type: 'formatFailed'
78
+ });
75
79
  }
76
80
  }
77
81
  }
78
- if (filesWithErrors > 0) {
79
- spin.warn(`Encountered errors in ${count(filesWithErrors, 'files')} while generating types`);
80
- }
81
- const stats = {
82
+ const generationResult = {
83
+ code,
82
84
  duration: Date.now() - start,
83
85
  emptyUnionTypeNodesGenerated,
84
86
  filesWithErrors,
@@ -90,17 +92,12 @@ import { generatedFileWarning } from './generatedFileWarning.js';
90
92
  unknownTypeNodesGenerated,
91
93
  unknownTypeNodesRatio: typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0
92
94
  };
93
- let successText = `Successfully generated types to ${formatPath(generates)} in ${Number(stats.duration).toFixed(0)}ms` + `\n └─ ${count(queriesCount, 'queries', 'query')} and ${count(schemaTypesCount, 'schema types', 'schema type')}` + `\n └─ found queries in ${count(queryFilesCount, 'files', 'file')} after evaluating ${count(evaluatedFiles, 'files', 'file')}`;
94
- if (formatterName) {
95
- successText += `\n └─ ${formattingError ? 'an error occurred during formatting' : `formatted the generated code with ${formatterName}`}`;
96
- }
97
- spin.succeed(successText);
98
- return {
99
- ...stats,
100
- code
101
- };
95
+ onProgress({
96
+ result: generationResult,
97
+ type: 'complete'
98
+ });
99
+ return generationResult;
102
100
  } catch (err) {
103
- spin.fail();
104
101
  debug('error generating types', err);
105
102
  throw err;
106
103
  } finally{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/actions/streamProcessor.ts"],"sourcesContent":["import {writeFile} from 'node:fs/promises'\n\nimport {spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {count} from '../utils/count.js'\nimport {debug} from '../utils/debug.js'\nimport {formatPath} from '../utils/formatPath.js'\nimport {getMessage} from '../utils/getMessage.js'\nimport {percent} from '../utils/percent.js'\nimport {defineFormatter} from '../utils/resolveFormatter.js'\nimport {generatedFileWarning} from './generatedFileWarning.js'\nimport {TypegenWorkerChannel} from './types.js'\n\n/**\n * Processes the event stream from a typegen worker thread.\n *\n * Listens to worker channel events, displays progress via CLI spinners,\n * writes the generated types to disk, and optionally formats with prettier.\n *\n * @param receiver - Worker channel receiver for typegen events\n * @param options - Typegen configuration options\n * @returns Generation result containing the generated code and statistics\n */\nexport async function processTypegenWorkerStream(\n receiver: WorkerChannelReceiver<TypegenWorkerChannel>,\n options: TypeGenConfig,\n) {\n const start = Date.now()\n const {formatGeneratedCode, generates, schema} = options\n\n const spin = spinner().start(`Loading schema…`)\n\n try {\n await receiver.event.loadedSchema()\n spin.succeed(`Schema loaded from ${formatPath(schema ?? '')}`)\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\n spin.text = 'Generating query types…'\n\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 if (!spin.isSpinning) {\n spin.start()\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(generates, code)\n\n let formattingError = false\n let formatterName: string | undefined\n if (formatGeneratedCode !== false) {\n const formatter = defineFormatter(formatGeneratedCode)\n if (formatter) {\n formatterName = formatter.name\n try {\n const {format} = await formatter.resolve()\n if (format) {\n spin.text = `Formatting generated types with ${formatter.name}…`\n const formattedCode = await format(generates, code)\n await writeFile(generates, formattedCode)\n }\n } catch (err) {\n formattingError = true\n spin.warn(`Failed to format generated types with ${formatter.name}: ${getMessage(err)}`)\n }\n }\n }\n\n if (filesWithErrors > 0) {\n spin.warn(`Encountered errors in ${count(filesWithErrors, 'files')} while generating types`)\n }\n\n const stats = {\n duration: Date.now() - start,\n emptyUnionTypeNodesGenerated,\n filesWithErrors,\n outputSize: Buffer.byteLength(code),\n queriesCount,\n queryFilesCount,\n schemaTypesCount,\n typeNodesGenerated,\n unknownTypeNodesGenerated,\n unknownTypeNodesRatio:\n typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n }\n\n let successText =\n `Successfully generated types to ${formatPath(generates)} in ${Number(stats.duration).toFixed(0)}ms` +\n `\\n └─ ${count(queriesCount, 'queries', 'query')} and ${count(schemaTypesCount, 'schema types', 'schema type')}` +\n `\\n └─ found queries in ${count(queryFilesCount, 'files', 'file')} after evaluating ${count(evaluatedFiles, 'files', 'file')}`\n\n if (formatterName) {\n successText += `\\n └─ ${formattingError ? 'an error occurred during formatting' : `formatted the generated code with ${formatterName}`}`\n }\n\n spin.succeed(successText)\n\n return {\n ...stats,\n code,\n }\n } catch (err) {\n spin.fail()\n debug('error generating types', err)\n throw err\n } finally {\n receiver.unsubscribe()\n }\n}\n"],"names":["writeFile","spinner","count","debug","formatPath","getMessage","percent","defineFormatter","generatedFileWarning","processTypegenWorkerStream","receiver","options","start","Date","now","formatGeneratedCode","generates","schema","spin","event","loadedSchema","succeed","expectedFileCount","typegenStarted","schemaTypeDeclarations","generatedSchemaTypes","schemaTypesCount","length","text","queriesCount","evaluatedFiles","filesWithErrors","queryFilesCount","typeNodesGenerated","unknownTypeNodesGenerated","emptyUnionTypeNodesGenerated","errors","queries","stream","evaluatedModules","stats","allTypes","unknownTypes","emptyUnions","error","fail","isSpinning","result","typegenComplete","code","formattingError","formatterName","formatter","name","format","resolve","formattedCode","err","warn","duration","outputSize","Buffer","byteLength","unknownTypeNodesRatio","successText","Number","toFixed","unsubscribe"],"mappings":"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"}
1
+ {"version":3,"sources":["../../src/actions/streamProcessor.ts"],"sourcesContent":["import {writeFile} from 'node:fs/promises'\n\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {debug} from '../utils/debug.js'\nimport {getMessage} from '../utils/getMessage.js'\nimport {defineFormatter} from '../utils/resolveFormatter.js'\nimport {generatedFileWarning} from './generatedFileWarning.js'\nimport {type TypegenProgressEvent, TypegenWorkerChannel} from './types.js'\n\nconst noopProgress = (_event: TypegenProgressEvent): void => {}\n\n/**\n * Processes the event stream from a typegen worker thread.\n *\n * Consumes worker channel events, reports progress via `onProgress`,\n * writes generated types to disk, and optionally formats them.\n */\nexport async function processTypegenWorkerStream(\n receiver: WorkerChannelReceiver<TypegenWorkerChannel>,\n options: TypeGenConfig,\n onProgress: (event: TypegenProgressEvent) => void = noopProgress,\n) {\n const start = Date.now()\n const {formatGeneratedCode, generates} = options\n\n try {\n await receiver.event.loadedSchema()\n onProgress({type: 'schemaLoaded'})\n\n const {expectedFileCount} = await receiver.event.typegenStarted()\n onProgress({expectedFileCount, type: 'typegenStarted'})\n\n const {schemaTypeDeclarations} = await receiver.event.generatedSchemaTypes()\n const schemaTypesCount = schemaTypeDeclarations.length\n onProgress({schemaTypesCount, type: 'schemaTypesGenerated'})\n\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 onProgress({\n errors: errors.map((error) => getMessage(error)),\n evaluatedFiles,\n expectedFileCount,\n queriesCount,\n queryFilesCount,\n type: 'moduleEvaluated',\n })\n }\n\n const result = await receiver.event.typegenComplete()\n const code = `${generatedFileWarning}${result.code}`\n await writeFile(generates, code)\n\n if (formatGeneratedCode !== false) {\n const formatter = defineFormatter(formatGeneratedCode)\n if (formatter) {\n try {\n const {format} = await formatter.resolve()\n if (format) {\n onProgress({formatterName: formatter.name, type: 'formatting'})\n const formattedCode = await format(generates, code)\n await writeFile(generates, formattedCode)\n }\n } catch (err) {\n onProgress({\n formatterName: formatter.name,\n message: getMessage(err),\n type: 'formatFailed',\n })\n }\n }\n }\n\n const generationResult = {\n code,\n duration: Date.now() - start,\n emptyUnionTypeNodesGenerated,\n filesWithErrors,\n outputSize: Buffer.byteLength(code),\n queriesCount,\n queryFilesCount,\n schemaTypesCount,\n typeNodesGenerated,\n unknownTypeNodesGenerated,\n unknownTypeNodesRatio:\n typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n }\n\n onProgress({result: generationResult, type: 'complete'})\n\n return generationResult\n } catch (err) {\n debug('error generating types', err)\n throw err\n } finally {\n receiver.unsubscribe()\n }\n}\n"],"names":["writeFile","debug","getMessage","defineFormatter","generatedFileWarning","noopProgress","_event","processTypegenWorkerStream","receiver","options","onProgress","start","Date","now","formatGeneratedCode","generates","event","loadedSchema","type","expectedFileCount","typegenStarted","schemaTypeDeclarations","generatedSchemaTypes","schemaTypesCount","length","queriesCount","evaluatedFiles","filesWithErrors","queryFilesCount","typeNodesGenerated","unknownTypeNodesGenerated","emptyUnionTypeNodesGenerated","errors","queries","stream","evaluatedModules","stats","allTypes","unknownTypes","emptyUnions","map","error","result","typegenComplete","code","formatter","format","resolve","formatterName","name","formattedCode","err","message","generationResult","duration","outputSize","Buffer","byteLength","unknownTypeNodesRatio","unsubscribe"],"mappings":"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"}
@@ -10,13 +10,13 @@ import { processTypegenWorkerStream } from './streamProcessor.js';
10
10
  * Runs a single typegen generation.
11
11
  *
12
12
  * This is the programmatic API for generating TypeScript types from GROQ queries.
13
- * It spawns a worker thread to perform the generation and displays progress via CLI spinners.
13
+ * It spawns a worker thread to perform the generation and reports progress via the optional `onProgress` callback.
14
14
  *
15
15
  * @param options - Configuration options including typegen config and working directory
16
16
  * @returns Generation result containing the generated code and statistics
17
17
  * @public
18
18
  */ export async function runTypegenGenerate(options) {
19
- const { config, workDir } = options;
19
+ const { config, workDir, onProgress } = options;
20
20
  const { formatGeneratedCode, generates, overloadClientMethods, path, schema } = prepareConfig(config);
21
21
  const outputPath = isAbsolute(generates) ? generates : join(workDir, generates);
22
22
  // create output dir if it isn't there
@@ -43,7 +43,7 @@ import { processTypegenWorkerStream } from './streamProcessor.js';
43
43
  overloadClientMethods,
44
44
  path,
45
45
  schema
46
- });
46
+ }, onProgress);
47
47
  return result;
48
48
  } catch (err) {
49
49
  debug('error generating types', err);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/actions/typegenGenerate.ts"],"sourcesContent":["import {mkdir} from 'node:fs/promises'\nimport {dirname, isAbsolute, join} from 'node:path'\nimport {env} from 'node:process'\nimport {Worker} from 'node:worker_threads'\n\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {prepareConfig} from '../utils/config.js'\nimport {debug} from '../utils/debug.js'\nimport {processTypegenWorkerStream} from './streamProcessor.js'\nimport {\n type GenerationResult,\n type RunTypegenOptions,\n TypegenGenerateTypesWorkerData,\n TypegenWorkerChannel,\n} from './types.js'\n\n/**\n * Runs a single typegen generation.\n *\n * This is the programmatic API for generating TypeScript types from GROQ queries.\n * It spawns a worker thread to perform the generation and displays progress via CLI spinners.\n *\n * @param options - Configuration options including typegen config and working directory\n * @returns Generation result containing the generated code and statistics\n * @public\n */\nexport async function runTypegenGenerate(options: RunTypegenOptions): Promise<GenerationResult> {\n const {config, workDir} = options\n\n const {formatGeneratedCode, generates, overloadClientMethods, path, schema} =\n prepareConfig(config)\n\n const outputPath = isAbsolute(generates) ? generates : join(workDir, generates)\n\n // create output dir if it isn't there\n const outputDir = dirname(outputPath)\n await mkdir(outputDir, {recursive: true})\n\n // set up worker\n const workerPath = new URL('../actions/typegenGenerate.worker.js', import.meta.url)\n const workerData: TypegenGenerateTypesWorkerData = {\n overloadClientMethods,\n schemaPath: schema,\n searchPath: path,\n workDir,\n }\n const worker = new Worker(workerPath, {env, workerData})\n\n try {\n const result = await processTypegenWorkerStream(\n WorkerChannelReceiver.from<TypegenWorkerChannel>(worker),\n {\n formatGeneratedCode,\n generates: outputPath,\n overloadClientMethods,\n path,\n schema,\n },\n )\n\n return result\n } catch (err) {\n debug('error generating types', err)\n throw err\n } finally {\n worker.terminate()\n }\n}\n"],"names":["mkdir","dirname","isAbsolute","join","env","Worker","WorkerChannelReceiver","prepareConfig","debug","processTypegenWorkerStream","runTypegenGenerate","options","config","workDir","formatGeneratedCode","generates","overloadClientMethods","path","schema","outputPath","outputDir","recursive","workerPath","URL","url","workerData","schemaPath","searchPath","worker","result","from","err","terminate"],"mappings":"AAAA,SAAQA,KAAK,QAAO,mBAAkB;AACtC,SAAQC,OAAO,EAAEC,UAAU,EAAEC,IAAI,QAAO,YAAW;AACnD,SAAQC,GAAG,QAAO,eAAc;AAChC,SAAQC,MAAM,QAAO,sBAAqB;AAE1C,SAAQC,qBAAqB,QAAO,0BAAyB;AAE7D,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,KAAK,QAAO,oBAAmB;AACvC,SAAQC,0BAA0B,QAAO,uBAAsB;AAQ/D;;;;;;;;;CASC,GACD,OAAO,eAAeC,mBAAmBC,OAA0B;IACjE,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;IAE1B,MAAM,EAACG,mBAAmB,EAAEC,SAAS,EAAEC,qBAAqB,EAAEC,IAAI,EAAEC,MAAM,EAAC,GACzEX,cAAcK;IAEhB,MAAMO,aAAajB,WAAWa,aAAaA,YAAYZ,KAAKU,SAASE;IAErE,sCAAsC;IACtC,MAAMK,YAAYnB,QAAQkB;IAC1B,MAAMnB,MAAMoB,WAAW;QAACC,WAAW;IAAI;IAEvC,gBAAgB;IAChB,MAAMC,aAAa,IAAIC,IAAI,wCAAwC,YAAYC,GAAG;IAClF,MAAMC,aAA6C;QACjDT;QACAU,YAAYR;QACZS,YAAYV;QACZJ;IACF;IACA,MAAMe,SAAS,IAAIvB,OAAOiB,YAAY;QAAClB;QAAKqB;IAAU;IAEtD,IAAI;QACF,MAAMI,SAAS,MAAMpB,2BACnBH,sBAAsBwB,IAAI,CAAuBF,SACjD;YACEd;YACAC,WAAWI;YACXH;YACAC;YACAC;QACF;QAGF,OAAOW;IACT,EAAE,OAAOE,KAAK;QACZvB,MAAM,0BAA0BuB;QAChC,MAAMA;IACR,SAAU;QACRH,OAAOI,SAAS;IAClB;AACF"}
1
+ {"version":3,"sources":["../../src/actions/typegenGenerate.ts"],"sourcesContent":["import {mkdir} from 'node:fs/promises'\nimport {dirname, isAbsolute, join} from 'node:path'\nimport {env} from 'node:process'\nimport {Worker} from 'node:worker_threads'\n\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {prepareConfig} from '../utils/config.js'\nimport {debug} from '../utils/debug.js'\nimport {processTypegenWorkerStream} from './streamProcessor.js'\nimport {\n type GenerationResult,\n type RunTypegenOptions,\n TypegenGenerateTypesWorkerData,\n TypegenWorkerChannel,\n} from './types.js'\n\n/**\n * Runs a single typegen generation.\n *\n * This is the programmatic API for generating TypeScript types from GROQ queries.\n * It spawns a worker thread to perform the generation and reports progress via the optional `onProgress` callback.\n *\n * @param options - Configuration options including typegen config and working directory\n * @returns Generation result containing the generated code and statistics\n * @public\n */\nexport async function runTypegenGenerate(options: RunTypegenOptions): Promise<GenerationResult> {\n const {config, workDir, onProgress} = options\n\n const {formatGeneratedCode, generates, overloadClientMethods, path, schema} =\n prepareConfig(config)\n\n const outputPath = isAbsolute(generates) ? generates : join(workDir, generates)\n\n // create output dir if it isn't there\n const outputDir = dirname(outputPath)\n await mkdir(outputDir, {recursive: true})\n\n // set up worker\n const workerPath = new URL('../actions/typegenGenerate.worker.js', import.meta.url)\n const workerData: TypegenGenerateTypesWorkerData = {\n overloadClientMethods,\n schemaPath: schema,\n searchPath: path,\n workDir,\n }\n const worker = new Worker(workerPath, {env, workerData})\n\n try {\n const result = await processTypegenWorkerStream(\n WorkerChannelReceiver.from<TypegenWorkerChannel>(worker),\n {\n formatGeneratedCode,\n generates: outputPath,\n overloadClientMethods,\n path,\n schema,\n },\n onProgress,\n )\n\n return result\n } catch (err) {\n debug('error generating types', err)\n throw err\n } finally {\n worker.terminate()\n }\n}\n"],"names":["mkdir","dirname","isAbsolute","join","env","Worker","WorkerChannelReceiver","prepareConfig","debug","processTypegenWorkerStream","runTypegenGenerate","options","config","workDir","onProgress","formatGeneratedCode","generates","overloadClientMethods","path","schema","outputPath","outputDir","recursive","workerPath","URL","url","workerData","schemaPath","searchPath","worker","result","from","err","terminate"],"mappings":"AAAA,SAAQA,KAAK,QAAO,mBAAkB;AACtC,SAAQC,OAAO,EAAEC,UAAU,EAAEC,IAAI,QAAO,YAAW;AACnD,SAAQC,GAAG,QAAO,eAAc;AAChC,SAAQC,MAAM,QAAO,sBAAqB;AAE1C,SAAQC,qBAAqB,QAAO,0BAAyB;AAE7D,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,KAAK,QAAO,oBAAmB;AACvC,SAAQC,0BAA0B,QAAO,uBAAsB;AAQ/D;;;;;;;;;CASC,GACD,OAAO,eAAeC,mBAAmBC,OAA0B;IACjE,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAEC,UAAU,EAAC,GAAGH;IAEtC,MAAM,EAACI,mBAAmB,EAAEC,SAAS,EAAEC,qBAAqB,EAAEC,IAAI,EAAEC,MAAM,EAAC,GACzEZ,cAAcK;IAEhB,MAAMQ,aAAalB,WAAWc,aAAaA,YAAYb,KAAKU,SAASG;IAErE,sCAAsC;IACtC,MAAMK,YAAYpB,QAAQmB;IAC1B,MAAMpB,MAAMqB,WAAW;QAACC,WAAW;IAAI;IAEvC,gBAAgB;IAChB,MAAMC,aAAa,IAAIC,IAAI,wCAAwC,YAAYC,GAAG;IAClF,MAAMC,aAA6C;QACjDT;QACAU,YAAYR;QACZS,YAAYV;QACZL;IACF;IACA,MAAMgB,SAAS,IAAIxB,OAAOkB,YAAY;QAACnB;QAAKsB;IAAU;IAEtD,IAAI;QACF,MAAMI,SAAS,MAAMrB,2BACnBH,sBAAsByB,IAAI,CAAuBF,SACjD;YACEd;YACAC,WAAWI;YACXH;YACAC;YACAC;QACF,GACAL;QAGF,OAAOgB;IACT,EAAE,OAAOE,KAAK;QACZxB,MAAM,0BAA0BwB;QAChC,MAAMA;IACR,SAAU;QACRH,OAAOI,SAAS;IAClB;AACF"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Result from a single generation run.
2
+ * Options for running a single typegen generation.
3
3
  * @public
4
4
  */ export { };
5
5
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannel} from '@sanity/worker-channels'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {type TypegenWorkerChannel as CodegenTypegenWorkerChannel} from '../typescript/typeGenerator.js'\n\n/**\n * Data passed to the typegen worker thread.\n * @internal\n */\nexport interface TypegenGenerateTypesWorkerData {\n /** Path to the schema JSON file */\n schemaPath: string\n /** Glob pattern(s) for finding query files */\n searchPath: string | string[]\n /** Working directory (project root) */\n workDir: string\n\n /** Whether to generate client method overloads */\n overloadClientMethods?: boolean\n}\n\n/**\n * Worker channel definition for typegen worker communication.\n * Extends the base TypegenWorkerChannel with additional events for progress tracking.\n * @internal\n */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<\n CodegenTypegenWorkerChannel['__definition'] & {\n loadedSchema: WorkerChannel.Event\n typegenComplete: WorkerChannel.Event<{code: string}>\n typegenStarted: WorkerChannel.Event<{expectedFileCount: number}>\n }\n>\n\n/**\n * Options for running a single typegen generation.\n * This is the programmatic API for one-off generation without file watching.\n * @public\n */\nexport interface RunTypegenOptions {\n /** Working directory (usually project root) */\n workDir: string\n\n /** Typegen configuration */\n config?: Partial<TypeGenConfig>\n\n /** Optional spinner instance for progress display */\n spin?: ReturnType<typeof spinner>\n}\n\n/**\n * Result from a single generation run.\n * @public\n */\nexport interface GenerationResult {\n code: string\n duration: number\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"],"names":[],"mappings":"AAmDA;;;CAGC,GACD,WAYC"}
1
+ {"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {WorkerChannel} from '@sanity/worker-channels'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {type TypegenWorkerChannel as CodegenTypegenWorkerChannel} from '../typescript/typeGenerator.js'\n\n/**\n * Data passed to the typegen worker thread.\n * @internal\n */\nexport interface TypegenGenerateTypesWorkerData {\n /** Path to the schema JSON file */\n schemaPath: string\n /** Glob pattern(s) for finding query files */\n searchPath: string | string[]\n /** Working directory (project root) */\n workDir: string\n\n /** Whether to generate client method overloads */\n overloadClientMethods?: boolean\n}\n\n/**\n * Worker channel definition for typegen worker communication.\n * Extends the base TypegenWorkerChannel with additional events for progress tracking.\n * @internal\n */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<\n CodegenTypegenWorkerChannel['__definition'] & {\n loadedSchema: WorkerChannel.Event\n typegenComplete: WorkerChannel.Event<{code: string}>\n typegenStarted: WorkerChannel.Event<{expectedFileCount: number}>\n }\n>\n\n/**\n * Result from a single generation run.\n * @public\n */\nexport interface GenerationResult {\n code: string\n duration: number\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/**\n * A progress event emitted during a single typegen run.\n * Consumers (e.g. the Sanity CLI) render these; the library performs no terminal output.\n * @public\n */\nexport type TypegenProgressEvent =\n | {type: 'schemaLoaded'}\n | {type: 'typegenStarted'; expectedFileCount: number}\n | {type: 'schemaTypesGenerated'; schemaTypesCount: number}\n | {\n type: 'moduleEvaluated'\n evaluatedFiles: number\n expectedFileCount: number\n queriesCount: number\n queryFilesCount: number\n errors: string[]\n }\n | {type: 'formatting'; formatterName: string}\n | {type: 'formatFailed'; formatterName: string; message: string}\n | {type: 'complete'; result: GenerationResult}\n\n/**\n * Options for running a single typegen generation.\n * @public\n */\nexport interface RunTypegenOptions {\n /** Working directory (usually project root) */\n workDir: string\n\n /** Typegen configuration */\n config?: Partial<TypeGenConfig>\n\n /** Optional progress reporter. Called synchronously as generation proceeds. */\n onProgress?: (event: TypegenProgressEvent) => void\n}\n"],"names":[],"mappings":"AAyEA;;;CAGC,GACD,WASC"}
@@ -1,27 +1,27 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import json5 from 'json5';
3
- import * as z from 'zod/mini';
3
+ import * as v from 'valibot';
4
4
  /**
5
5
  * @public
6
- */ export const configDefinition = z.object({
7
- formatGeneratedCode: z._default(z.union([
8
- z.boolean(),
9
- z.enum([
6
+ */ export const configDefinition = v.object({
7
+ formatGeneratedCode: v.optional(v.union([
8
+ v.boolean(),
9
+ v.picklist([
10
10
  'oxfmt',
11
11
  'prettier'
12
12
  ])
13
13
  ]), true),
14
- generates: z._default(z.string(), './sanity.types.ts'),
15
- overloadClientMethods: z._default(z.boolean(), true),
16
- path: z._default(z.union([
17
- z.string(),
18
- z.array(z.string())
14
+ generates: v.optional(v.string(), './sanity.types.ts'),
15
+ overloadClientMethods: v.optional(v.boolean(), true),
16
+ path: v.optional(v.union([
17
+ v.string(),
18
+ v.array(v.string())
19
19
  ]), [
20
20
  './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
21
21
  './app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
22
22
  './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}'
23
23
  ]),
24
- schema: z._default(z.string(), './schema.json')
24
+ schema: v.optional(v.string(), './schema.json')
25
25
  });
26
26
  /**
27
27
  * Read, parse and process a config file
@@ -31,15 +31,15 @@ import * as z from 'zod/mini';
31
31
  const content = await readFile(path, 'utf8');
32
32
  // eslint-disable-next-line import-x/no-named-as-default-member -- json5 is CJS and doesn't support named exports
33
33
  const json = json5.parse(content);
34
- return configDefinition.parseAsync(json);
34
+ return v.parseAsync(configDefinition, json);
35
35
  } catch (error) {
36
- if (typeof error === 'object' && error !== null && 'issues' in error && Array.isArray(error.issues)) {
37
- throw new TypeError(`Error in config file\n ${error.issues.map((err)=>err.message).join('\n')}`, {
36
+ if (v.isValiError(error)) {
37
+ throw new TypeError(`Error in config file\n ${error.issues.map((issue)=>issue.message).join('\n')}`, {
38
38
  cause: error
39
39
  });
40
40
  }
41
41
  if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {
42
- return configDefinition.parse({});
42
+ return v.parse(configDefinition, {});
43
43
  }
44
44
  throw error;
45
45
  }
@@ -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/mini'\n\n/**\n * The formatter to use for generated code.\n * - `false` - Do not format generated code.\n * - `true` | `'prettier'` - Format with prettier.\n * - `'oxfmt'` - Format with oxfmt. Throws if oxfmt is not installed.\n * @public\n */\nexport type FormatGeneratedCode = 'oxfmt' | 'prettier' | boolean\n\n/**\n * @public\n */\nexport const configDefinition = z.object({\n formatGeneratedCode: z._default(z.union([z.boolean(), z.enum(['oxfmt', 'prettier'])]), true),\n generates: z._default(z.string(), './sanity.types.ts'),\n overloadClientMethods: z._default(z.boolean(), true),\n path: z._default(z.union([z.string(), z.array(z.string())]), [\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._default(z.string(), './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 // eslint-disable-next-line import-x/no-named-as-default-member -- json5 is CJS and doesn't support named exports\n const json = json5.parse(content)\n return configDefinition.parseAsync(json)\n } catch (error) {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'issues' in error &&\n Array.isArray(error.issues)\n ) {\n throw new TypeError(\n `Error in config file\\n ${error.issues.map((err: {message: string}) => 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","_default","union","boolean","enum","generates","string","overloadClientMethods","path","array","schema","readConfig","content","json","parse","parseAsync","error","Array","isArray","issues","TypeError","map","err","message","join","cause","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,OAAOC,WAAW,QAAO;AACzB,YAAYC,OAAO,WAAU;AAW7B;;CAEC,GACD,OAAO,MAAMC,mBAAmBD,EAAEE,MAAM,CAAC;IACvCC,qBAAqBH,EAAEI,QAAQ,CAACJ,EAAEK,KAAK,CAAC;QAACL,EAAEM,OAAO;QAAIN,EAAEO,IAAI,CAAC;YAAC;YAAS;SAAW;KAAE,GAAG;IACvFC,WAAWR,EAAEI,QAAQ,CAACJ,EAAES,MAAM,IAAI;IAClCC,uBAAuBV,EAAEI,QAAQ,CAACJ,EAAEM,OAAO,IAAI;IAC/CK,MAAMX,EAAEI,QAAQ,CAACJ,EAAEK,KAAK,CAAC;QAACL,EAAES,MAAM;QAAIT,EAAEY,KAAK,CAACZ,EAAES,MAAM;KAAI,GAAG;QAC3D;QACA;QACA;KACD;IACDI,QAAQb,EAAEI,QAAQ,CAACJ,EAAES,MAAM,IAAI;AACjC,GAAE;AAWF;;;CAGC,GACD,OAAO,eAAeK,WAAWH,IAAY;IAC3C,IAAI;QACF,MAAMI,UAAU,MAAMjB,SAASa,MAAM;QACrC,iHAAiH;QACjH,MAAMK,OAAOjB,MAAMkB,KAAK,CAACF;QACzB,OAAOd,iBAAiBiB,UAAU,CAACF;IACrC,EAAE,OAAOG,OAAO;QACd,IACE,OAAOA,UAAU,YACjBA,UAAU,QACV,YAAYA,SACZC,MAAMC,OAAO,CAACF,MAAMG,MAAM,GAC1B;YACA,MAAM,IAAIC,UACR,CAAC,uBAAuB,EAAEJ,MAAMG,MAAM,CAACE,GAAG,CAAC,CAACC,MAA2BA,IAAIC,OAAO,EAAEC,IAAI,CAAC,OAAO,EAChG;gBAACC,OAAOT;YAAK;QAEjB;QACA,IAAI,OAAOA,UAAU,YAAYA,UAAU,QAAQ,UAAUA,SAASA,MAAMU,IAAI,KAAK,UAAU;YAC7F,OAAO5B,iBAAiBgB,KAAK,CAAC,CAAC;QACjC;QAEA,MAAME;IACR;AACF"}
1
+ {"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as v from 'valibot'\n\n/**\n * The formatter to use for generated code.\n * - `false` - Do not format generated code.\n * - `true` | `'prettier'` - Format with prettier.\n * - `'oxfmt'` - Format with oxfmt. Throws if oxfmt is not installed.\n * @public\n */\nexport type FormatGeneratedCode = 'oxfmt' | 'prettier' | boolean\n\n/**\n * @public\n */\nexport const configDefinition = v.object({\n formatGeneratedCode: v.optional(v.union([v.boolean(), v.picklist(['oxfmt', 'prettier'])]), true),\n generates: v.optional(v.string(), './sanity.types.ts'),\n overloadClientMethods: v.optional(v.boolean(), true),\n path: v.optional(v.union([v.string(), v.array(v.string())]), [\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: v.optional(v.string(), './schema.json'),\n})\n\n/** @public */\nexport type TypeGenConfig = v.InferOutput<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 // eslint-disable-next-line import-x/no-named-as-default-member -- json5 is CJS and doesn't support named exports\n const json = json5.parse(content)\n return v.parseAsync(configDefinition, json)\n } catch (error) {\n if (v.isValiError(error)) {\n throw new TypeError(\n `Error in config file\\n ${error.issues.map((issue) => issue.message).join('\\n')}`,\n {cause: error},\n )\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return v.parse(configDefinition, {})\n }\n\n throw error\n }\n}\n"],"names":["readFile","json5","v","configDefinition","object","formatGeneratedCode","optional","union","boolean","picklist","generates","string","overloadClientMethods","path","array","schema","readConfig","content","json","parse","parseAsync","error","isValiError","TypeError","issues","map","issue","message","join","cause","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,OAAOC,WAAW,QAAO;AACzB,YAAYC,OAAO,UAAS;AAW5B;;CAEC,GACD,OAAO,MAAMC,mBAAmBD,EAAEE,MAAM,CAAC;IACvCC,qBAAqBH,EAAEI,QAAQ,CAACJ,EAAEK,KAAK,CAAC;QAACL,EAAEM,OAAO;QAAIN,EAAEO,QAAQ,CAAC;YAAC;YAAS;SAAW;KAAE,GAAG;IAC3FC,WAAWR,EAAEI,QAAQ,CAACJ,EAAES,MAAM,IAAI;IAClCC,uBAAuBV,EAAEI,QAAQ,CAACJ,EAAEM,OAAO,IAAI;IAC/CK,MAAMX,EAAEI,QAAQ,CAACJ,EAAEK,KAAK,CAAC;QAACL,EAAES,MAAM;QAAIT,EAAEY,KAAK,CAACZ,EAAES,MAAM;KAAI,GAAG;QAC3D;QACA;QACA;KACD;IACDI,QAAQb,EAAEI,QAAQ,CAACJ,EAAES,MAAM,IAAI;AACjC,GAAE;AAWF;;;CAGC,GACD,OAAO,eAAeK,WAAWH,IAAY;IAC3C,IAAI;QACF,MAAMI,UAAU,MAAMjB,SAASa,MAAM;QACrC,iHAAiH;QACjH,MAAMK,OAAOjB,MAAMkB,KAAK,CAACF;QACzB,OAAOf,EAAEkB,UAAU,CAACjB,kBAAkBe;IACxC,EAAE,OAAOG,OAAO;QACd,IAAInB,EAAEoB,WAAW,CAACD,QAAQ;YACxB,MAAM,IAAIE,UACR,CAAC,uBAAuB,EAAEF,MAAMG,MAAM,CAACC,GAAG,CAAC,CAACC,QAAUA,MAAMC,OAAO,EAAEC,IAAI,CAAC,OAAO,EACjF;gBAACC,OAAOR;YAAK;QAEjB;QACA,IAAI,OAAOA,UAAU,YAAYA,UAAU,QAAQ,UAAUA,SAASA,MAAMS,IAAI,KAAK,UAAU;YAC7F,OAAO5B,EAAEiB,KAAK,CAAChB,kBAAkB,CAAC;QACpC;QAEA,MAAMkB;IACR;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/safeParseQuery.ts"],"sourcesContent":["import {parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string) {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start!\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end!\n }\n }\n}\n"],"names":["parse","safeParseQuery","query","params","param","extractSliceParams","sliceRegex","matches","matchAll","match","start","end"],"mappings":"AAAA,SAAQA,KAAK,QAAO,UAAS;AAE7B;;;;CAIC,GACD,OAAO,SAASC,eAAeC,KAAa;IAC1C,MAAMC,SAAkC,CAAC;IAEzC,KAAK,MAAMC,SAASC,mBAAmBH,OAAQ;QAC7CC,MAAM,CAACC,MAAM,GAAG,GAAE,+CAA+C;IACnE;IACA,OAAOJ,MAAME,OAAO;QAACC;IAAM;AAC7B;AAEA;;;;CAIC,GACD,OAAO,UAAUE,mBAAmBH,KAAa;IAC/C,MAAMI,aAAa;IACnB,MAAMC,UAAUL,MAAMM,QAAQ,CAACF;IAC/B,IAAI,CAACC,SAAS;QACZ;IACF;IACA,KAAK,MAAME,SAASF,QAAS;QAC3B,MAAMG,QAAQD,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,EAAEA,KAAK,CAAC,EAAE,EAAE,GAAGA,KAAK,CAAC,EAAE,GAAG;QACvD,IAAIC,UAAU,MAAM;YAClB,MAAMA;QACR;QACA,MAAMC,MAAMF,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,EAAEA,KAAK,CAAC,EAAE,EAAE,GAAGA,KAAK,CAAC,EAAE,GAAG;QACrD,IAAIE,QAAQ,MAAM;YAChB,MAAMA;QACR;IACF;AACF"}
1
+ {"version":3,"sources":["../src/safeParseQuery.ts"],"sourcesContent":["import {type ExprNode, parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string): ExprNode {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start!\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end!\n }\n }\n}\n"],"names":["parse","safeParseQuery","query","params","param","extractSliceParams","sliceRegex","matches","matchAll","match","start","end"],"mappings":"AAAA,SAAuBA,KAAK,QAAO,UAAS;AAE5C;;;;CAIC,GACD,OAAO,SAASC,eAAeC,KAAa;IAC1C,MAAMC,SAAkC,CAAC;IAEzC,KAAK,MAAMC,SAASC,mBAAmBH,OAAQ;QAC7CC,MAAM,CAACC,MAAM,GAAG,GAAE,+CAA+C;IACnE;IACA,OAAOJ,MAAME,OAAO;QAACC;IAAM;AAC7B;AAEA;;;;CAIC,GACD,OAAO,UAAUE,mBAAmBH,KAAa;IAC/C,MAAMI,aAAa;IACnB,MAAMC,UAAUL,MAAMM,QAAQ,CAACF;IAC/B,IAAI,CAACC,SAAS;QACZ;IACF;IACA,KAAK,MAAME,SAASF,QAAS;QAC3B,MAAMG,QAAQD,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,EAAEA,KAAK,CAAC,EAAE,EAAE,GAAGA,KAAK,CAAC,EAAE,GAAG;QACvD,IAAIC,UAAU,MAAM;YAClB,MAAMA;QACR;QACA,MAAMC,MAAMF,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,EAAEA,KAAK,CAAC,EAAE,EAAE,GAAGA,KAAK,CAAC,EAAE,GAAG;QACrD,IAAIE,QAAQ,MAAM;YAChB,MAAMA;QACR;IACF;AACF"}
@@ -70,6 +70,25 @@ export function weakMapMemo(fn) {
70
70
  export function generateCode(node) {
71
71
  return `${new CodeGenerator(node).generate().code.trim()}\n\n`;
72
72
  }
73
+ /**
74
+ * Builds a `declare global { … }` block.
75
+ */ export function tsDeclareGlobal(body) {
76
+ const declaration = t.tsModuleDeclaration(t.identifier('global'), t.tsModuleBlock(body));
77
+ declaration.declare = true;
78
+ // Babel 7's generator reads the keyword from `global`, Babel 8's from `kind`; set both so the
79
+ // output is `declare global {` on either.
80
+ declaration.global = true;
81
+ declaration.kind = 'global';
82
+ return declaration;
83
+ }
84
+ /**
85
+ * Builds a `declare module "<name>" { … }` block.
86
+ */ export function tsDeclareModule(name, body) {
87
+ const declaration = t.tsModuleDeclaration(t.stringLiteral(name), t.tsModuleBlock(body));
88
+ declaration.declare = true;
89
+ declaration.kind = 'module';
90
+ return declaration;
91
+ }
73
92
  export function getFilterArrayUnionType(typeNode, predicate) {
74
93
  if (typeNode.of.type !== 'union') {
75
94
  return typeNode;