@sanity/codegen 8.1.1 → 8.3.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 +53 -0
- package/dist/_exports/index.d.ts +194 -18
- package/dist/_exports/index.js +1 -0
- package/dist/_exports/index.js.map +1 -1
- package/dist/actions/typegenGenerate.js +4 -1
- package/dist/actions/typegenGenerate.js.map +1 -1
- package/dist/actions/typegenGenerate.worker.js +9 -4
- package/dist/actions/typegenGenerate.worker.js.map +1 -1
- package/dist/actions/typegenWatch.js +3 -2
- package/dist/actions/typegenWatch.js.map +1 -1
- package/dist/actions/types.js.map +1 -1
- package/dist/typescript/constants.js +3 -0
- package/dist/typescript/constants.js.map +1 -1
- package/dist/typescript/findQueriesInSource.js +48 -0
- package/dist/typescript/findQueriesInSource.js.map +1 -1
- package/dist/typescript/schemaTypeGenerator.js +99 -63
- package/dist/typescript/schemaTypeGenerator.js.map +1 -1
- package/dist/typescript/typeGenerator.js +216 -12
- package/dist/typescript/typeGenerator.js.map +1 -1
- package/dist/typescript/types.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -27,3 +27,56 @@ The two blocks serve different `@sanity/client` releases, and the same generated
|
|
|
27
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
28
|
|
|
29
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.
|
|
30
|
+
|
|
31
|
+
## Types per dataset
|
|
32
|
+
|
|
33
|
+
Pass `resource: {projectId, dataset}` to a generation run and the generated file also registers its schema and query result types under that resource, keyed `projectId.dataset`:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// Resource TypeMap: abc123.production
|
|
37
|
+
declare global {
|
|
38
|
+
interface SanitySchemasByResource {
|
|
39
|
+
'abc123.production': AllSanitySchemaTypes
|
|
40
|
+
}
|
|
41
|
+
interface SanityQueriesByResource {
|
|
42
|
+
'abc123.production': {
|
|
43
|
+
'*[_type == "post"]': PostsQueryResult
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
interface SanityProjectionsByResource {
|
|
47
|
+
'abc123.production': {
|
|
48
|
+
post: {
|
|
49
|
+
'{title}': PostTitleResult
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
An app that reads more than one dataset generates one file per dataset, and the same query text then resolves to a different type for each. `@sanity/client` 8.7.0 and later declare these interfaces, and the App SDK's hooks read them. The key is the same string the App SDK uses for its runtime cache.
|
|
57
|
+
|
|
58
|
+
This block has no `declare module '@sanity/client'` bridge. The registries first shipped as globals, so no client release needs one, and without it the block never resolves `@sanity/client`. That matters when the client is only a dependency of another package, as with the App SDK under pnpm. The flat query type map's bridge still resolves it, so in that layout also set `overloadClientMethods: false` (it defaults to `true`), or point `generates` at a `.d.ts` path as described above.
|
|
59
|
+
|
|
60
|
+
The flat query type map above is still controlled by `overloadClientMethods`, independently. When generating more than one resource into one TypeScript program, set `overloadClientMethods: false` for all of them: each file would declare the same query text in `SanityQueries` with a different type, which TypeScript rejects. For the same reason, generate one file per resource. Two files registering the same resource conflict.
|
|
61
|
+
|
|
62
|
+
Without `resource`, the generated file is unchanged.
|
|
63
|
+
|
|
64
|
+
### Projections
|
|
65
|
+
|
|
66
|
+
Projections passed to the App SDK's `defineProjection`, imported from `@sanity/sdk` or `@sanity/sdk-react`, are typed too:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import {defineProjection} from '@sanity/sdk-react'
|
|
70
|
+
|
|
71
|
+
// Evaluated for `post` documents only
|
|
72
|
+
export const postTitle = defineProjection('post', '{title}')
|
|
73
|
+
|
|
74
|
+
// Evaluated for every document type in the schema
|
|
75
|
+
export const anyTitle = defineProjection('{title}')
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Each projection is evaluated as `*[_type == TYPE][0]PROJECTION` for its document type, and its result type is the object without `null`, since the SDK only projects documents it has found. A projection without a document type is evaluated for every document type in the schema. Document types with the same result share one type alias; the others get an alias named after the document type, such as `AnyTitleAuthorResult`. Passing the document type keeps the generated file smaller.
|
|
79
|
+
|
|
80
|
+
With `resource` set, results are registered in `SanityProjectionsByResource` by document type and then by the exact projection text, which is what `useDocumentProjection` looks up. Without `resource`, only the result type aliases are generated. As with `defineQuery`, only calls assigned to a variable are found, and the arguments must be resolvable without running the code. With `resource` set, a projection naming a document type the schema does not have is skipped, because another dataset scanning the same files can have it. A name that is an object type in the schema, or any unknown name in a run without `resource`, is reported as an error.
|
|
81
|
+
|
|
82
|
+
`runTypegenGenerate` also accepts `extractedSchema`, a schema already in memory in the shape `sanity schema extract` writes, so a caller that fetched and compiled a schema does not have to write it to a temporary file first. The file then has no `// Source:` line naming a schema file, since there is none.
|
package/dist/_exports/index.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import {DefinedTelemetryTrace} from '@sanity/telemetry'
|
|
2
|
+
import {DocumentSchemaType} from 'groq-js'
|
|
2
3
|
import {ExprNode} from 'groq-js'
|
|
3
4
|
import {FSWatcher} from 'chokidar'
|
|
4
5
|
import {SchemaType} from 'groq-js'
|
|
5
6
|
import * as t from '@babel/types'
|
|
6
7
|
import {TransformOptions} from '@babel/core'
|
|
8
|
+
import {TypeDeclarationSchemaType} from 'groq-js'
|
|
9
|
+
import {TypeNode} from 'groq-js'
|
|
7
10
|
import * as v from 'valibot'
|
|
8
11
|
import {WorkerChannel} from '@sanity/worker-channels'
|
|
9
12
|
import {WorkerChannelReporter} from '@sanity/worker-channels'
|
|
@@ -52,6 +55,26 @@ export declare interface EvaluatedModule {
|
|
|
52
55
|
errors: (QueryEvaluationError | QueryExtractionError)[]
|
|
53
56
|
filename: string
|
|
54
57
|
queries: EvaluatedQuery[]
|
|
58
|
+
/** @beta */
|
|
59
|
+
projections?: EvaluatedProjection[]
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* An `ExtractedProjection` evaluated against the document types it applies to.
|
|
64
|
+
* @beta
|
|
65
|
+
*/
|
|
66
|
+
export declare interface EvaluatedProjection extends ExtractedProjection {
|
|
67
|
+
/** One result type alias per distinct result. */
|
|
68
|
+
declarations: {
|
|
69
|
+
ast: t.ExportNamedDeclaration
|
|
70
|
+
code: string
|
|
71
|
+
id: t.Identifier
|
|
72
|
+
}[]
|
|
73
|
+
/** The result alias for each document type the projection was evaluated against. */
|
|
74
|
+
resultsByDocumentType: {
|
|
75
|
+
[documentType: string]: t.Identifier
|
|
76
|
+
}
|
|
77
|
+
stats: TypeEvaluationStats
|
|
55
78
|
}
|
|
56
79
|
|
|
57
80
|
/**
|
|
@@ -74,6 +97,24 @@ export declare interface ExtractedModule {
|
|
|
74
97
|
errors: QueryExtractionError[]
|
|
75
98
|
filename: string
|
|
76
99
|
queries: ExtractedQuery[]
|
|
100
|
+
/** @beta */
|
|
101
|
+
projections?: ExtractedProjection[]
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* A projection extracted from a `defineProjection` call in a source file.
|
|
106
|
+
* @beta
|
|
107
|
+
*/
|
|
108
|
+
export declare interface ExtractedProjection {
|
|
109
|
+
filename: string
|
|
110
|
+
/** The exact projection string, which is also its lookup key. */
|
|
111
|
+
projection: string
|
|
112
|
+
variable: QueryVariable
|
|
113
|
+
/**
|
|
114
|
+
* The document type the projection is written for, when passed as the first argument.
|
|
115
|
+
* Without it, the projection is evaluated against every document type.
|
|
116
|
+
*/
|
|
117
|
+
documentType?: string
|
|
77
118
|
}
|
|
78
119
|
|
|
79
120
|
/**
|
|
@@ -178,9 +219,30 @@ export declare function findQueriesInSource(
|
|
|
178
219
|
/** @public */
|
|
179
220
|
export declare interface GenerateTypesOptions {
|
|
180
221
|
schema: SchemaType
|
|
222
|
+
/**
|
|
223
|
+
* Generate the client's flat `SanityQueries` map, which types `client.fetch`. Independent of
|
|
224
|
+
* `resource`. When an app generates types for more than one resource into one TypeScript
|
|
225
|
+
* program, set this to `false` for all of them: each file would declare the same query text
|
|
226
|
+
* in the flat map with a different type, and TypeScript rejects that merge.
|
|
227
|
+
*/
|
|
181
228
|
overloadClientMethods?: boolean
|
|
182
229
|
queries?: AsyncIterable<ExtractedModule>
|
|
183
230
|
reporter?: WorkerChannelReporter<TypegenWorkerChannel>
|
|
231
|
+
/**
|
|
232
|
+
* Also register the schema and query result types under this project and dataset, so one
|
|
233
|
+
* app can read more than one dataset and resolve the same query text to a different type for
|
|
234
|
+
* each. Types go into the global `SanitySchemasByResource` and `SanityQueriesByResource`
|
|
235
|
+
* interfaces that `@sanity/client` 8.7.0 and later declare, keyed `projectId.dataset`, the
|
|
236
|
+
* same string the App SDK uses for its runtime cache.
|
|
237
|
+
*
|
|
238
|
+
* The registration is a plain global declaration and never resolves `@sanity/client`, so it
|
|
239
|
+
* works when the client is only a dependency of another package, as with the App SDK under
|
|
240
|
+
* pnpm. The flat map's bridge does resolve it, so in that layout also set
|
|
241
|
+
* `overloadClientMethods: false`. Generate one file per resource per TypeScript program: two
|
|
242
|
+
* files registering the same resource conflict.
|
|
243
|
+
* @beta
|
|
244
|
+
*/
|
|
245
|
+
resource?: TypegenResource
|
|
184
246
|
root?: string
|
|
185
247
|
schemaPath?: string
|
|
186
248
|
}
|
|
@@ -403,13 +465,28 @@ export declare interface RunTypegenOptions {
|
|
|
403
465
|
workDir: string
|
|
404
466
|
/** Typegen configuration */
|
|
405
467
|
config?: Partial<TypeGenConfig>
|
|
468
|
+
/**
|
|
469
|
+
* An extracted schema to generate from, used instead of reading `config.schema` from disk.
|
|
470
|
+
* Same shape as the output of `sanity schema extract`. Pass this when the schema is extracted
|
|
471
|
+
* in memory, for example after fetching and compiling a dataset's schema, so it does not have
|
|
472
|
+
* to be written to a temporary file first. The watcher then watches query files only.
|
|
473
|
+
* @beta
|
|
474
|
+
*/
|
|
475
|
+
extractedSchema?: SchemaType
|
|
406
476
|
/** Optional progress reporter. Called synchronously as generation proceeds. */
|
|
407
477
|
onProgress?: (event: TypegenProgressEvent) => void
|
|
478
|
+
/**
|
|
479
|
+
* Also register the generated types under this project and dataset. See
|
|
480
|
+
* `GenerateTypesOptions.resource`.
|
|
481
|
+
* @beta
|
|
482
|
+
*/
|
|
483
|
+
resource?: TypegenResource
|
|
408
484
|
}
|
|
409
485
|
|
|
410
486
|
/**
|
|
411
487
|
* Starts a file watcher that triggers typegen on changes.
|
|
412
|
-
* Watches
|
|
488
|
+
* Watches query files (via patterns) and the schema JSON file. With `extractedSchema`, the
|
|
489
|
+
* schema is fixed for the life of the watcher, so only query files are watched.
|
|
413
490
|
* Implements debouncing and concurrency control to prevent multiple generations.
|
|
414
491
|
* @public
|
|
415
492
|
*/
|
|
@@ -426,6 +503,74 @@ export declare function runTypegenWatcher(options: RunTypegenOptions): {
|
|
|
426
503
|
*/
|
|
427
504
|
export declare function safeParseQuery(query: string): ExprNode
|
|
428
505
|
|
|
506
|
+
/**
|
|
507
|
+
* Generates TypeScript types from a schema, as `sanity schema extract` writes it.
|
|
508
|
+
*
|
|
509
|
+
* On construction, every type in the schema gets a TypeScript type and a unique alias
|
|
510
|
+
* identifier; iterating the instance yields them as `{name, id, tsType}`, in schema order.
|
|
511
|
+
* `generateTsType` turns any groq-js type node into a TypeScript type that names schema types
|
|
512
|
+
* by those aliases, and `evaluateQuery` does so for the result of a GROQ query. A tool that
|
|
513
|
+
* types GROQ outside `TypeGenerator`, such as a TypeScript content mapper for `.groq` files,
|
|
514
|
+
* uses this class so that its output agrees with what `sanity typegen generate` writes.
|
|
515
|
+
* @beta
|
|
516
|
+
*/
|
|
517
|
+
export declare class SchemaTypeGenerator {
|
|
518
|
+
readonly schema: SchemaType
|
|
519
|
+
evaluateQuery: (arg: Pick<ExtractedQuery, 'query'>) => {
|
|
520
|
+
stats: TypeEvaluationStats
|
|
521
|
+
tsType: t.TSType
|
|
522
|
+
}
|
|
523
|
+
private arrayOfUsed
|
|
524
|
+
private identifiers
|
|
525
|
+
private tsTypes
|
|
526
|
+
constructor(schema: SchemaType)
|
|
527
|
+
/** The names of the schema's document types, in schema order. */
|
|
528
|
+
documentTypeNames(): string[]
|
|
529
|
+
/**
|
|
530
|
+
* Evaluates a projection for one document type, as `*[_type == TYPE][0]PROJECTION` without
|
|
531
|
+
* the `null` for a missing document: the SDK projects documents it has found.
|
|
532
|
+
*/
|
|
533
|
+
evaluateProjection({documentType, projection}: {documentType: string; projection: string}): {
|
|
534
|
+
stats: TypeEvaluationStats
|
|
535
|
+
tsType: t.TSType
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* The TypeScript type for a groq-js type node. A reference to a schema type becomes its alias
|
|
539
|
+
* identifier, an array of inline types becomes `ArrayOf<...>` (and `isArrayOfUsed` reports
|
|
540
|
+
* that the helper is needed), and a reference object carries `internalGroqTypeReferenceTo`.
|
|
541
|
+
*/
|
|
542
|
+
generateTsType(typeNode: DocumentSchemaType | TypeDeclarationSchemaType | TypeNode): t.TSType
|
|
543
|
+
getType(typeName: string):
|
|
544
|
+
| {
|
|
545
|
+
id: t.Identifier
|
|
546
|
+
tsType: t.TSType
|
|
547
|
+
}
|
|
548
|
+
| undefined
|
|
549
|
+
hasType(typeName: string): boolean
|
|
550
|
+
isArrayOfUsed(): boolean
|
|
551
|
+
[Symbol.iterator](): Generator<
|
|
552
|
+
{
|
|
553
|
+
id: t.Identifier
|
|
554
|
+
tsType: t.TSType
|
|
555
|
+
name: string
|
|
556
|
+
},
|
|
557
|
+
void,
|
|
558
|
+
unknown
|
|
559
|
+
>
|
|
560
|
+
typeNames(): string[]
|
|
561
|
+
/**
|
|
562
|
+
* Helper function used to generate TS types for arrays of inline types, or arrays of inline types
|
|
563
|
+
* wrapped in the ArrayOf wrapper that adds _key prop
|
|
564
|
+
*/
|
|
565
|
+
private generateArrayOfTsType
|
|
566
|
+
private generateArrayTsType
|
|
567
|
+
private generateDocumentTsType
|
|
568
|
+
private generateInlineTsType
|
|
569
|
+
private generateObjectTsType
|
|
570
|
+
private generateTsObjectProperty
|
|
571
|
+
private generateUnionTsType
|
|
572
|
+
}
|
|
573
|
+
|
|
429
574
|
/** Builds a tuple from elements, stopping at the first `never`. */
|
|
430
575
|
declare type TakeUntilNever<T extends unknown[]> = T extends [infer H, ...infer Rest]
|
|
431
576
|
? [H] extends [never]
|
|
@@ -456,8 +601,30 @@ export declare class TypeGenerator {
|
|
|
456
601
|
private getAllSanitySchemaTypesDeclaration
|
|
457
602
|
private getArrayOfDeclaration
|
|
458
603
|
private getInternalReferenceSymbolDeclaration
|
|
604
|
+
/**
|
|
605
|
+
* Evaluates a projection against its document type, or against every document type when it
|
|
606
|
+
* names none. Document types with the same result share one group, so a projection that does
|
|
607
|
+
* not apply to most types does not repeat the same type once per document type.
|
|
608
|
+
*
|
|
609
|
+
* Returns `undefined` for a document type this schema does not have when generating for a
|
|
610
|
+
* resource: datasets of one app can scan the same files, and the type can belong to another.
|
|
611
|
+
*/
|
|
612
|
+
private static evaluateProjection
|
|
459
613
|
private static getEvaluatedModules
|
|
614
|
+
/**
|
|
615
|
+
* One property per document type, each holding one property per distinct projection string,
|
|
616
|
+
* typed as the union of every result alias generated for that pair.
|
|
617
|
+
*/
|
|
618
|
+
private static getProjectionResultProperties
|
|
460
619
|
private static getQueryMapDeclaration
|
|
620
|
+
/**
|
|
621
|
+
* One property per distinct query string, typed as the union of every result type generated
|
|
622
|
+
* for it. Two variables holding the same query text share a key.
|
|
623
|
+
*/
|
|
624
|
+
private static getQueryResultProperties
|
|
625
|
+
private static getResourceRegistryDeclaration
|
|
626
|
+
/** Declares one result alias per group, with names not yet in `currentIdentifiers`. */
|
|
627
|
+
private static nameProjection
|
|
461
628
|
generateTypes(options: GenerateTypesOptions): Promise<{
|
|
462
629
|
ast: t.Program
|
|
463
630
|
code: string
|
|
@@ -471,37 +638,46 @@ export declare class TypeGenerator {
|
|
|
471
638
|
*/
|
|
472
639
|
export declare type TypegenProgressEvent =
|
|
473
640
|
| {
|
|
474
|
-
|
|
475
|
-
}
|
|
476
|
-
| {
|
|
477
|
-
type: 'typegenStarted'
|
|
478
|
-
expectedFileCount: number
|
|
479
|
-
}
|
|
480
|
-
| {
|
|
481
|
-
type: 'schemaTypesGenerated'
|
|
482
|
-
schemaTypesCount: number
|
|
483
|
-
}
|
|
484
|
-
| {
|
|
485
|
-
type: 'moduleEvaluated'
|
|
641
|
+
errors: string[]
|
|
486
642
|
evaluatedFiles: number
|
|
487
643
|
expectedFileCount: number
|
|
488
644
|
queriesCount: number
|
|
489
645
|
queryFilesCount: number
|
|
490
|
-
|
|
646
|
+
type: 'moduleEvaluated'
|
|
491
647
|
}
|
|
492
648
|
| {
|
|
493
|
-
|
|
494
|
-
|
|
649
|
+
expectedFileCount: number
|
|
650
|
+
type: 'typegenStarted'
|
|
495
651
|
}
|
|
496
652
|
| {
|
|
497
|
-
type: 'formatFailed'
|
|
498
653
|
formatterName: string
|
|
499
654
|
message: string
|
|
655
|
+
type: 'formatFailed'
|
|
656
|
+
}
|
|
657
|
+
| {
|
|
658
|
+
formatterName: string
|
|
659
|
+
type: 'formatting'
|
|
500
660
|
}
|
|
501
661
|
| {
|
|
502
|
-
type: 'complete'
|
|
503
662
|
result: GenerationResult
|
|
663
|
+
type: 'complete'
|
|
664
|
+
}
|
|
665
|
+
| {
|
|
666
|
+
schemaTypesCount: number
|
|
667
|
+
type: 'schemaTypesGenerated'
|
|
504
668
|
}
|
|
669
|
+
| {
|
|
670
|
+
type: 'schemaLoaded'
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* The project and dataset a schema belongs to.
|
|
675
|
+
* @beta
|
|
676
|
+
*/
|
|
677
|
+
export declare interface TypegenResource {
|
|
678
|
+
dataset: string
|
|
679
|
+
projectId: string
|
|
680
|
+
}
|
|
505
681
|
|
|
506
682
|
/** @public */
|
|
507
683
|
export declare const TypegenWatchModeTrace: DefinedTelemetryTrace<
|
package/dist/_exports/index.js
CHANGED
|
@@ -8,6 +8,7 @@ export { findQueriesInPath } from '../typescript/findQueriesInPath.js';
|
|
|
8
8
|
export { findQueriesInSource } from '../typescript/findQueriesInSource.js';
|
|
9
9
|
export { getResolver } from '../typescript/moduleResolver.js';
|
|
10
10
|
export { registerBabel } from '../typescript/registerBabel.js';
|
|
11
|
+
export { SchemaTypeGenerator } from '../typescript/schemaTypeGenerator.js';
|
|
11
12
|
export { TypeGenerator } from '../typescript/typeGenerator.js';
|
|
12
13
|
export { QueryExtractionError } from '../typescript/types.js';
|
|
13
14
|
|
|
@@ -1 +1 @@
|
|
|
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,
|
|
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 {SchemaTypeGenerator} from '../typescript/schemaTypeGenerator.js'\nexport {\n type GenerateTypesOptions,\n TypeGenerator,\n type TypegenResource,\n type TypegenWorkerChannel,\n} from '../typescript/typeGenerator.js'\nexport {\n type EvaluatedModule,\n type EvaluatedProjection,\n type EvaluatedQuery,\n type ExtractedModule,\n type ExtractedProjection,\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","SchemaTypeGenerator","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,SAAQC,mBAAmB,QAAO,uCAAsC;AACxE,SAEEC,aAAa,QAGR,iCAAgC;AACvC,SAOEC,oBAAoB,QACf,yBAAwB"}
|
|
@@ -16,7 +16,7 @@ import { processTypegenWorkerStream } from './streamProcessor.js';
|
|
|
16
16
|
* @returns Generation result containing the generated code and statistics
|
|
17
17
|
* @public
|
|
18
18
|
*/ export async function runTypegenGenerate(options) {
|
|
19
|
-
const { config,
|
|
19
|
+
const { config, extractedSchema, onProgress, resource, workDir } = 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
|
|
@@ -27,7 +27,10 @@ import { processTypegenWorkerStream } from './streamProcessor.js';
|
|
|
27
27
|
// set up worker
|
|
28
28
|
const workerPath = new URL('../actions/typegenGenerate.worker.js', import.meta.url);
|
|
29
29
|
const workerData = {
|
|
30
|
+
// Structured-cloned into the worker. An extracted schema is plain JSON, so it survives.
|
|
31
|
+
extractedSchema,
|
|
30
32
|
overloadClientMethods,
|
|
33
|
+
resource,
|
|
31
34
|
schemaPath: schema,
|
|
32
35
|
searchPath: path,
|
|
33
36
|
workDir
|
|
@@ -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 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,
|
|
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, extractedSchema, onProgress, resource, 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 // Structured-cloned into the worker. An extracted schema is plain JSON, so it survives.\n extractedSchema,\n overloadClientMethods,\n resource,\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","extractedSchema","onProgress","resource","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,eAAe,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,OAAO,EAAC,GAAGL;IAEjE,MAAM,EAACM,mBAAmB,EAAEC,SAAS,EAAEC,qBAAqB,EAAEC,IAAI,EAAEC,MAAM,EAAC,GACzEd,cAAcK;IAEhB,MAAMU,aAAapB,WAAWgB,aAAaA,YAAYf,KAAKa,SAASE;IAErE,sCAAsC;IACtC,MAAMK,YAAYtB,QAAQqB;IAC1B,MAAMtB,MAAMuB,WAAW;QAACC,WAAW;IAAI;IAEvC,gBAAgB;IAChB,MAAMC,aAAa,IAAIC,IAAI,wCAAwC,YAAYC,GAAG;IAClF,MAAMC,aAA6C;QACjD,wFAAwF;QACxFf;QACAM;QACAJ;QACAc,YAAYR;QACZS,YAAYV;QACZJ;IACF;IACA,MAAMe,SAAS,IAAI1B,OAAOoB,YAAY;QAACrB;QAAKwB;IAAU;IAEtD,IAAI;QACF,MAAMI,SAAS,MAAMvB,2BACnBH,sBAAsB2B,IAAI,CAAuBF,SACjD;YACEd;YACAC,WAAWI;YACXH;YACAC;YACAC;QACF,GACAP;QAGF,OAAOkB;IACT,EAAE,OAAOE,KAAK;QACZ1B,MAAM,0BAA0B0B;QAChC,MAAMA;IACR,SAAU;QACRH,OAAOI,SAAS;IAClB;AACF"}
|
|
@@ -11,8 +11,7 @@ if (isMainThread || !parentPort) {
|
|
|
11
11
|
throw new Error('This module must be run as a worker thread');
|
|
12
12
|
}
|
|
13
13
|
registerBabel();
|
|
14
|
-
async function
|
|
15
|
-
const report = WorkerChannelReporter.from(parentPort);
|
|
14
|
+
async function loadSchema(schemaPath, workDir) {
|
|
16
15
|
const fullPath = isAbsolute(schemaPath) ? schemaPath : join(workDir, schemaPath);
|
|
17
16
|
try {
|
|
18
17
|
const schemaStats = await stat(fullPath);
|
|
@@ -29,7 +28,11 @@ async function main({ overloadClientMethods, schemaPath, searchPath, workDir })
|
|
|
29
28
|
}
|
|
30
29
|
throw err;
|
|
31
30
|
}
|
|
32
|
-
|
|
31
|
+
return readSchema(fullPath);
|
|
32
|
+
}
|
|
33
|
+
async function main({ extractedSchema, overloadClientMethods, resource, schemaPath, searchPath, workDir }) {
|
|
34
|
+
const report = WorkerChannelReporter.from(parentPort);
|
|
35
|
+
const schema = extractedSchema ?? await loadSchema(schemaPath, workDir);
|
|
33
36
|
report.event.loadedSchema();
|
|
34
37
|
const typeGenerator = new TypeGenerator();
|
|
35
38
|
const { files, queries } = findQueriesInPath({
|
|
@@ -43,9 +46,11 @@ async function main({ overloadClientMethods, schemaPath, searchPath, workDir })
|
|
|
43
46
|
overloadClientMethods,
|
|
44
47
|
queries,
|
|
45
48
|
reporter: report,
|
|
49
|
+
resource,
|
|
46
50
|
root: workDir,
|
|
47
51
|
schema,
|
|
48
|
-
|
|
52
|
+
// Only a schema read from disk has a path worth naming in the output.
|
|
53
|
+
schemaPath: extractedSchema ? undefined : schemaPath
|
|
49
54
|
});
|
|
50
55
|
report.event.typegenComplete(result);
|
|
51
56
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/typegenGenerate.worker.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {isAbsolute, join} from 'node:path'\nimport {isMainThread, parentPort, workerData} from 'node:worker_threads'\n\nimport {WorkerChannelReporter} from '@sanity/worker-channels'\n\nimport {readSchema} from '../readSchema.js'\nimport {findQueriesInPath} from '../typescript/findQueriesInPath.js'\nimport {getResolver} from '../typescript/moduleResolver.js'\nimport {registerBabel} from '../typescript/registerBabel.js'\nimport {TypeGenerator} from '../typescript/typeGenerator.js'\nimport {TypegenGenerateTypesWorkerData, TypegenWorkerChannel} from './types.js'\n\nif (isMainThread || !parentPort) {\n throw new Error('This module must be run as a worker thread')\n}\n\nregisterBabel()\n\nasync function
|
|
1
|
+
{"version":3,"sources":["../../src/actions/typegenGenerate.worker.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {isAbsolute, join} from 'node:path'\nimport {isMainThread, parentPort, workerData} from 'node:worker_threads'\n\nimport {WorkerChannelReporter} from '@sanity/worker-channels'\n\nimport {readSchema} from '../readSchema.js'\nimport {findQueriesInPath} from '../typescript/findQueriesInPath.js'\nimport {getResolver} from '../typescript/moduleResolver.js'\nimport {registerBabel} from '../typescript/registerBabel.js'\nimport {TypeGenerator} from '../typescript/typeGenerator.js'\nimport {TypegenGenerateTypesWorkerData, TypegenWorkerChannel} from './types.js'\n\nif (isMainThread || !parentPort) {\n throw new Error('This module must be run as a worker thread')\n}\n\nregisterBabel()\n\nasync function loadSchema(schemaPath: string, workDir: string) {\n const fullPath = isAbsolute(schemaPath) ? schemaPath : join(workDir, schemaPath)\n\n try {\n const schemaStats = await stat(fullPath)\n if (!schemaStats.isFile()) {\n throw new Error(`Schema path is not a file: ${schemaPath}`)\n }\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT') {\n // If the user has not provided a specific schema path (eg we're using the default), give some help\n const hint = schemaPath === './schema.json' ? ` - did you run \"sanity schema extract\"?` : ''\n throw new Error(`Schema file not found: ${fullPath}${hint}`, {cause: err})\n }\n throw err\n }\n\n return readSchema(fullPath)\n}\n\nasync function main({\n extractedSchema,\n overloadClientMethods,\n resource,\n schemaPath,\n searchPath,\n workDir,\n}: TypegenGenerateTypesWorkerData) {\n const report = WorkerChannelReporter.from<TypegenWorkerChannel>(parentPort)\n\n const schema = extractedSchema ?? (await loadSchema(schemaPath, workDir))\n\n report.event.loadedSchema()\n\n const typeGenerator = new TypeGenerator()\n\n const {files, queries} = findQueriesInPath({\n path: searchPath,\n resolver: getResolver(workDir),\n })\n report.event.typegenStarted({expectedFileCount: files.length})\n\n const result = await typeGenerator.generateTypes({\n overloadClientMethods,\n queries,\n reporter: report,\n resource,\n root: workDir,\n schema,\n // Only a schema read from disk has a path worth naming in the output.\n schemaPath: extractedSchema ? undefined : schemaPath,\n })\n report.event.typegenComplete(result)\n}\n\nawait main(workerData)\n"],"names":["stat","isAbsolute","join","isMainThread","parentPort","workerData","WorkerChannelReporter","readSchema","findQueriesInPath","getResolver","registerBabel","TypeGenerator","Error","loadSchema","schemaPath","workDir","fullPath","schemaStats","isFile","err","code","hint","cause","main","extractedSchema","overloadClientMethods","resource","searchPath","report","from","schema","event","loadedSchema","typeGenerator","files","queries","path","resolver","typegenStarted","expectedFileCount","length","result","generateTypes","reporter","root","undefined","typegenComplete"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,UAAU,EAAEC,IAAI,QAAO,YAAW;AAC1C,SAAQC,YAAY,EAAEC,UAAU,EAAEC,UAAU,QAAO,sBAAqB;AAExE,SAAQC,qBAAqB,QAAO,0BAAyB;AAE7D,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,iBAAiB,QAAO,qCAAoC;AACpE,SAAQC,WAAW,QAAO,kCAAiC;AAC3D,SAAQC,aAAa,QAAO,iCAAgC;AAC5D,SAAQC,aAAa,QAAO,iCAAgC;AAG5D,IAAIR,gBAAgB,CAACC,YAAY;IAC/B,MAAM,IAAIQ,MAAM;AAClB;AAEAF;AAEA,eAAeG,WAAWC,UAAkB,EAAEC,OAAe;IAC3D,MAAMC,WAAWf,WAAWa,cAAcA,aAAaZ,KAAKa,SAASD;IAErE,IAAI;QACF,MAAMG,cAAc,MAAMjB,KAAKgB;QAC/B,IAAI,CAACC,YAAYC,MAAM,IAAI;YACzB,MAAM,IAAIN,MAAM,CAAC,2BAA2B,EAAEE,YAAY;QAC5D;IACF,EAAE,OAAOK,KAAK;QACZ,IAAIA,eAAeP,SAAS,UAAUO,OAAOA,IAAIC,IAAI,KAAK,UAAU;YAClE,mGAAmG;YACnG,MAAMC,OAAOP,eAAe,kBAAkB,CAAC,uCAAuC,CAAC,GAAG;YAC1F,MAAM,IAAIF,MAAM,CAAC,uBAAuB,EAAEI,WAAWK,MAAM,EAAE;gBAACC,OAAOH;YAAG;QAC1E;QACA,MAAMA;IACR;IAEA,OAAOZ,WAAWS;AACpB;AAEA,eAAeO,KAAK,EAClBC,eAAe,EACfC,qBAAqB,EACrBC,QAAQ,EACRZ,UAAU,EACVa,UAAU,EACVZ,OAAO,EACwB;IAC/B,MAAMa,SAAStB,sBAAsBuB,IAAI,CAAuBzB;IAEhE,MAAM0B,SAASN,mBAAoB,MAAMX,WAAWC,YAAYC;IAEhEa,OAAOG,KAAK,CAACC,YAAY;IAEzB,MAAMC,gBAAgB,IAAItB;IAE1B,MAAM,EAACuB,KAAK,EAAEC,OAAO,EAAC,GAAG3B,kBAAkB;QACzC4B,MAAMT;QACNU,UAAU5B,YAAYM;IACxB;IACAa,OAAOG,KAAK,CAACO,cAAc,CAAC;QAACC,mBAAmBL,MAAMM,MAAM;IAAA;IAE5D,MAAMC,SAAS,MAAMR,cAAcS,aAAa,CAAC;QAC/CjB;QACAU;QACAQ,UAAUf;QACVF;QACAkB,MAAM7B;QACNe;QACA,sEAAsE;QACtEhB,YAAYU,kBAAkBqB,YAAY/B;IAC5C;IACAc,OAAOG,KAAK,CAACe,eAAe,CAACL;AAC/B;AAEA,MAAMlB,KAAKlB"}
|
|
@@ -47,7 +47,8 @@ const IGNORED_PATTERNS = [
|
|
|
47
47
|
}
|
|
48
48
|
/**
|
|
49
49
|
* Starts a file watcher that triggers typegen on changes.
|
|
50
|
-
* Watches
|
|
50
|
+
* Watches query files (via patterns) and the schema JSON file. With `extractedSchema`, the
|
|
51
|
+
* schema is fixed for the life of the watcher, so only query files are watched.
|
|
51
52
|
* Implements debouncing and concurrency control to prevent multiple generations.
|
|
52
53
|
* @public
|
|
53
54
|
*/ export function runTypegenWatcher(options) {
|
|
@@ -78,7 +79,7 @@ const IGNORED_PATTERNS = [
|
|
|
78
79
|
];
|
|
79
80
|
const absoluteQueryPatterns = paths.map((pattern)=>isAbsolute(pattern) ? pattern : join(workDir, pattern));
|
|
80
81
|
const absoluteSchemaPath = isAbsolute(schema) ? schema : join(workDir, schema);
|
|
81
|
-
const watchTargets = [
|
|
82
|
+
const watchTargets = options.extractedSchema ? absoluteQueryPatterns : [
|
|
82
83
|
...absoluteQueryPatterns,
|
|
83
84
|
absoluteSchemaPath
|
|
84
85
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/typegenWatch.ts"],"sourcesContent":["import {error, log} from 'node:console'\nimport {isAbsolute, join, relative} from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {type FSWatcher, watch} from 'chokidar'\nimport debounce from 'lodash-es/debounce.js'\nimport mean from 'lodash-es/mean.js'\n\nimport {TypegenWatchModeTraceAttributes} from '../typegen.telemetry.js'\nimport {prepareConfig} from '../utils/config.js'\nimport {runTypegenGenerate} from './typegenGenerate.js'\nimport {type RunTypegenOptions} from './types.js'\n\nconst IGNORED_PATTERNS = [\n '**/node_modules/**',\n '**/.git/**',\n '**/dist/**',\n '**/lib/**',\n '**/.sanity/**',\n]\n\n/** State for tracking generation status */\ninterface WatchState {\n isGenerating: boolean\n pendingGeneration: boolean\n}\n\n/** Return type for createTypegenRunner */\ninterface TypegenRunner {\n runGeneration: () => Promise<void>\n state: WatchState\n}\n\ntype WatcherStats = Omit<Extract<TypegenWatchModeTraceAttributes, {step: 'stopped'}>, 'step'>\n\n/**\n * Creates a typegen runner with concurrency control.\n * If generation is already running, queues one more generation to run after completion.\n * Multiple queued requests are coalesced into a single pending generation.\n */\nfunction createTypegenRunner(onGenerate: () => Promise<unknown>): TypegenRunner {\n const state: WatchState = {\n isGenerating: false,\n pendingGeneration: false,\n }\n\n async function runGeneration(): Promise<void> {\n if (state.isGenerating) {\n state.pendingGeneration = true\n return\n }\n\n state.isGenerating = true\n state.pendingGeneration = false\n\n try {\n await onGenerate()\n } finally {\n state.isGenerating = false\n\n // If a change came in during generation, run again\n if (state.pendingGeneration) {\n state.pendingGeneration = false\n await runGeneration()\n }\n }\n }\n\n return {runGeneration, state}\n}\n\n/**\n * Starts a file watcher that triggers typegen on changes.\n * Watches
|
|
1
|
+
{"version":3,"sources":["../../src/actions/typegenWatch.ts"],"sourcesContent":["import {error, log} from 'node:console'\nimport {isAbsolute, join, relative} from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {type FSWatcher, watch} from 'chokidar'\nimport debounce from 'lodash-es/debounce.js'\nimport mean from 'lodash-es/mean.js'\n\nimport {TypegenWatchModeTraceAttributes} from '../typegen.telemetry.js'\nimport {prepareConfig} from '../utils/config.js'\nimport {runTypegenGenerate} from './typegenGenerate.js'\nimport {type RunTypegenOptions} from './types.js'\n\nconst IGNORED_PATTERNS = [\n '**/node_modules/**',\n '**/.git/**',\n '**/dist/**',\n '**/lib/**',\n '**/.sanity/**',\n]\n\n/** State for tracking generation status */\ninterface WatchState {\n isGenerating: boolean\n pendingGeneration: boolean\n}\n\n/** Return type for createTypegenRunner */\ninterface TypegenRunner {\n runGeneration: () => Promise<void>\n state: WatchState\n}\n\ntype WatcherStats = Omit<Extract<TypegenWatchModeTraceAttributes, {step: 'stopped'}>, 'step'>\n\n/**\n * Creates a typegen runner with concurrency control.\n * If generation is already running, queues one more generation to run after completion.\n * Multiple queued requests are coalesced into a single pending generation.\n */\nfunction createTypegenRunner(onGenerate: () => Promise<unknown>): TypegenRunner {\n const state: WatchState = {\n isGenerating: false,\n pendingGeneration: false,\n }\n\n async function runGeneration(): Promise<void> {\n if (state.isGenerating) {\n state.pendingGeneration = true\n return\n }\n\n state.isGenerating = true\n state.pendingGeneration = false\n\n try {\n await onGenerate()\n } finally {\n state.isGenerating = false\n\n // If a change came in during generation, run again\n if (state.pendingGeneration) {\n state.pendingGeneration = false\n await runGeneration()\n }\n }\n }\n\n return {runGeneration, state}\n}\n\n/**\n * Starts a file watcher that triggers typegen on changes.\n * Watches query files (via patterns) and the schema JSON file. With `extractedSchema`, the\n * schema is fixed for the life of the watcher, so only query files are watched.\n * Implements debouncing and concurrency control to prevent multiple generations.\n * @public\n */\nexport function runTypegenWatcher(options: RunTypegenOptions): {\n getStats: () => WatcherStats\n stop: () => Promise<void>\n watcher: FSWatcher\n} {\n const {config, workDir} = options\n const {path, schema} = prepareConfig(config)\n\n const stats = {\n failedCount: 0,\n startTime: Date.now(),\n successfulDurations: [] as number[],\n }\n\n const {runGeneration} = createTypegenRunner(async () => {\n try {\n const {duration} = await runTypegenGenerate({...options})\n stats.successfulDurations.push(duration)\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : err\n error(` ${styleText('red', '›')} ${errorMessage}`)\n stats.failedCount++\n }\n })\n\n // Debounced generation trigger\n const debouncedGenerate = debounce(runGeneration, 1000)\n\n // Build absolute patterns for query files and schema file\n const paths = Array.isArray(path) ? path : [path]\n const absoluteQueryPatterns = paths.map((pattern) =>\n isAbsolute(pattern) ? pattern : join(workDir, pattern),\n )\n const absoluteSchemaPath = isAbsolute(schema) ? schema : join(workDir, schema)\n const watchTargets = options.extractedSchema\n ? absoluteQueryPatterns\n : [...absoluteQueryPatterns, absoluteSchemaPath]\n\n // perform initial generation\n debouncedGenerate()\n\n // set up watcher\n const watcher = watch(watchTargets, {\n cwd: workDir,\n ignored: IGNORED_PATTERNS,\n ignoreInitial: true,\n })\n\n watcher.on('all', (event: string, filePath: string) => {\n const timestamp = new Date().toLocaleTimeString()\n const relativePath = isAbsolute(filePath) ? relative(workDir, filePath) : filePath\n log(`[${timestamp}] ${event}: ${relativePath}`)\n debouncedGenerate()\n })\n\n watcher.on('error', (err: Error) => {\n error(`Watcher error: ${err.message}`)\n })\n\n return {\n getStats: () => ({\n averageGenerationDuration: mean(stats.successfulDurations) || 0,\n generationFailedCount: stats.failedCount,\n generationSuccessfulCount: stats.successfulDurations.length,\n watcherDuration: Date.now() - stats.startTime,\n }),\n stop: async () => {\n await watcher.close()\n },\n watcher,\n }\n}\n"],"names":["error","log","isAbsolute","join","relative","styleText","watch","debounce","mean","prepareConfig","runTypegenGenerate","IGNORED_PATTERNS","createTypegenRunner","onGenerate","state","isGenerating","pendingGeneration","runGeneration","runTypegenWatcher","options","config","workDir","path","schema","stats","failedCount","startTime","Date","now","successfulDurations","duration","push","err","errorMessage","Error","message","debouncedGenerate","paths","Array","isArray","absoluteQueryPatterns","map","pattern","absoluteSchemaPath","watchTargets","extractedSchema","watcher","cwd","ignored","ignoreInitial","on","event","filePath","timestamp","toLocaleTimeString","relativePath","getStats","averageGenerationDuration","generationFailedCount","generationSuccessfulCount","length","watcherDuration","stop","close"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,GAAG,QAAO,eAAc;AACvC,SAAQC,UAAU,EAAEC,IAAI,EAAEC,QAAQ,QAAO,YAAW;AACpD,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAwBC,KAAK,QAAO,WAAU;AAC9C,OAAOC,cAAc,wBAAuB;AAC5C,OAAOC,UAAU,oBAAmB;AAGpC,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,kBAAkB,QAAO,uBAAsB;AAGvD,MAAMC,mBAAmB;IACvB;IACA;IACA;IACA;IACA;CACD;AAgBD;;;;CAIC,GACD,SAASC,oBAAoBC,UAAkC;IAC7D,MAAMC,QAAoB;QACxBC,cAAc;QACdC,mBAAmB;IACrB;IAEA,eAAeC;QACb,IAAIH,MAAMC,YAAY,EAAE;YACtBD,MAAME,iBAAiB,GAAG;YAC1B;QACF;QAEAF,MAAMC,YAAY,GAAG;QACrBD,MAAME,iBAAiB,GAAG;QAE1B,IAAI;YACF,MAAMH;QACR,SAAU;YACRC,MAAMC,YAAY,GAAG;YAErB,mDAAmD;YACnD,IAAID,MAAME,iBAAiB,EAAE;gBAC3BF,MAAME,iBAAiB,GAAG;gBAC1B,MAAMC;YACR;QACF;IACF;IAEA,OAAO;QAACA;QAAeH;IAAK;AAC9B;AAEA;;;;;;CAMC,GACD,OAAO,SAASI,kBAAkBC,OAA0B;IAK1D,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;IAC1B,MAAM,EAACG,IAAI,EAAEC,MAAM,EAAC,GAAGd,cAAcW;IAErC,MAAMI,QAAQ;QACZC,aAAa;QACbC,WAAWC,KAAKC,GAAG;QACnBC,qBAAqB,EAAE;IACzB;IAEA,MAAM,EAACZ,aAAa,EAAC,GAAGL,oBAAoB;QAC1C,IAAI;YACF,MAAM,EAACkB,QAAQ,EAAC,GAAG,MAAMpB,mBAAmB;gBAAC,GAAGS,OAAO;YAAA;YACvDK,MAAMK,mBAAmB,CAACE,IAAI,CAACD;QACjC,EAAE,OAAOE,KAAK;YACZ,MAAMC,eAAeD,eAAeE,QAAQF,IAAIG,OAAO,GAAGH;YAC1DhC,MAAM,CAAC,CAAC,EAAEK,UAAU,OAAO,KAAK,GAAG,EAAE4B,cAAc;YACnDT,MAAMC,WAAW;QACnB;IACF;IAEA,+BAA+B;IAC/B,MAAMW,oBAAoB7B,SAASU,eAAe;IAElD,0DAA0D;IAC1D,MAAMoB,QAAQC,MAAMC,OAAO,CAACjB,QAAQA,OAAO;QAACA;KAAK;IACjD,MAAMkB,wBAAwBH,MAAMI,GAAG,CAAC,CAACC,UACvCxC,WAAWwC,WAAWA,UAAUvC,KAAKkB,SAASqB;IAEhD,MAAMC,qBAAqBzC,WAAWqB,UAAUA,SAASpB,KAAKkB,SAASE;IACvE,MAAMqB,eAAezB,QAAQ0B,eAAe,GACxCL,wBACA;WAAIA;QAAuBG;KAAmB;IAElD,6BAA6B;IAC7BP;IAEA,iBAAiB;IACjB,MAAMU,UAAUxC,MAAMsC,cAAc;QAClCG,KAAK1B;QACL2B,SAASrC;QACTsC,eAAe;IACjB;IAEAH,QAAQI,EAAE,CAAC,OAAO,CAACC,OAAeC;QAChC,MAAMC,YAAY,IAAI1B,OAAO2B,kBAAkB;QAC/C,MAAMC,eAAerD,WAAWkD,YAAYhD,SAASiB,SAAS+B,YAAYA;QAC1EnD,IAAI,CAAC,CAAC,EAAEoD,UAAU,EAAE,EAAEF,MAAM,EAAE,EAAEI,cAAc;QAC9CnB;IACF;IAEAU,QAAQI,EAAE,CAAC,SAAS,CAAClB;QACnBhC,MAAM,CAAC,eAAe,EAAEgC,IAAIG,OAAO,EAAE;IACvC;IAEA,OAAO;QACLqB,UAAU,IAAO,CAAA;gBACfC,2BAA2BjD,KAAKgB,MAAMK,mBAAmB,KAAK;gBAC9D6B,uBAAuBlC,MAAMC,WAAW;gBACxCkC,2BAA2BnC,MAAMK,mBAAmB,CAAC+B,MAAM;gBAC3DC,iBAAiBlC,KAAKC,GAAG,KAAKJ,MAAME,SAAS;YAC/C,CAAA;QACAoC,MAAM;YACJ,MAAMhB,QAAQiB,KAAK;QACrB;QACAjB;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
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 | {
|
|
1
|
+
{"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {WorkerChannel} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {\n type TypegenWorkerChannel as CodegenTypegenWorkerChannel,\n type TypegenResource,\n} 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 /** An extracted schema to use instead of reading `schemaPath`. */\n extractedSchema?: SchemaType\n /** Whether to generate client method overloads */\n overloadClientMethods?: boolean\n /** Register output under this resource. See `GenerateTypesOptions.resource`. */\n resource?: TypegenResource\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 | {\n errors: string[]\n evaluatedFiles: number\n expectedFileCount: number\n queriesCount: number\n queryFilesCount: number\n type: 'moduleEvaluated'\n }\n | {expectedFileCount: number; type: 'typegenStarted'}\n | {formatterName: string; message: string; type: 'formatFailed'}\n | {formatterName: string; type: 'formatting'}\n | {result: GenerationResult; type: 'complete'}\n | {schemaTypesCount: number; type: 'schemaTypesGenerated'}\n | {type: 'schemaLoaded'}\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 /**\n * An extracted schema to generate from, used instead of reading `config.schema` from disk.\n * Same shape as the output of `sanity schema extract`. Pass this when the schema is extracted\n * in memory, for example after fetching and compiling a dataset's schema, so it does not have\n * to be written to a temporary file first. The watcher then watches query files only.\n * @beta\n */\n extractedSchema?: SchemaType\n\n /** Optional progress reporter. Called synchronously as generation proceeds. */\n onProgress?: (event: TypegenProgressEvent) => void\n\n /**\n * Also register the generated types under this project and dataset. See\n * `GenerateTypesOptions.resource`.\n * @beta\n */\n resource?: TypegenResource\n}\n"],"names":[],"mappings":"AAiFA;;;CAGC,GACD,WAyBC"}
|
|
@@ -2,6 +2,9 @@ import * as t from '@babel/types';
|
|
|
2
2
|
export const INTERNAL_REFERENCE_SYMBOL = t.identifier('internalGroqTypeReferenceTo');
|
|
3
3
|
export const ALL_SANITY_SCHEMA_TYPES = t.identifier('AllSanitySchemaTypes');
|
|
4
4
|
export const SANITY_QUERIES = t.identifier('SanityQueries');
|
|
5
|
+
export const SANITY_SCHEMAS_BY_RESOURCE = t.identifier('SanitySchemasByResource');
|
|
6
|
+
export const SANITY_QUERIES_BY_RESOURCE = t.identifier('SanityQueriesByResource');
|
|
7
|
+
export const SANITY_PROJECTIONS_BY_RESOURCE = t.identifier('SanityProjectionsByResource');
|
|
5
8
|
export const ARRAY_OF = t.identifier('ArrayOf');
|
|
6
9
|
export const RESERVED_IDENTIFIERS = new Set();
|
|
7
10
|
RESERVED_IDENTIFIERS.add(SANITY_QUERIES.name);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/typescript/constants.ts"],"sourcesContent":["import * as t from '@babel/types'\n\nexport const INTERNAL_REFERENCE_SYMBOL = t.identifier('internalGroqTypeReferenceTo')\nexport const ALL_SANITY_SCHEMA_TYPES = t.identifier('AllSanitySchemaTypes')\nexport const SANITY_QUERIES = t.identifier('SanityQueries')\nexport const ARRAY_OF = t.identifier('ArrayOf')\n\nexport const RESERVED_IDENTIFIERS = new Set<string>()\nRESERVED_IDENTIFIERS.add(SANITY_QUERIES.name)\nRESERVED_IDENTIFIERS.add(ALL_SANITY_SCHEMA_TYPES.name)\nRESERVED_IDENTIFIERS.add(INTERNAL_REFERENCE_SYMBOL.name)\nRESERVED_IDENTIFIERS.add(ARRAY_OF.name)\n"],"names":["t","INTERNAL_REFERENCE_SYMBOL","identifier","ALL_SANITY_SCHEMA_TYPES","SANITY_QUERIES","ARRAY_OF","RESERVED_IDENTIFIERS","Set","add","name"],"mappings":"AAAA,YAAYA,OAAO,eAAc;AAEjC,OAAO,MAAMC,4BAA4BD,EAAEE,UAAU,CAAC,+BAA8B;AACpF,OAAO,MAAMC,0BAA0BH,EAAEE,UAAU,CAAC,wBAAuB;AAC3E,OAAO,MAAME,iBAAiBJ,EAAEE,UAAU,CAAC,iBAAgB;AAC3D,OAAO,MAAMG,
|
|
1
|
+
{"version":3,"sources":["../../src/typescript/constants.ts"],"sourcesContent":["import * as t from '@babel/types'\n\nexport const INTERNAL_REFERENCE_SYMBOL = t.identifier('internalGroqTypeReferenceTo')\nexport const ALL_SANITY_SCHEMA_TYPES = t.identifier('AllSanitySchemaTypes')\nexport const SANITY_QUERIES = t.identifier('SanityQueries')\nexport const SANITY_SCHEMAS_BY_RESOURCE = t.identifier('SanitySchemasByResource')\nexport const SANITY_QUERIES_BY_RESOURCE = t.identifier('SanityQueriesByResource')\nexport const SANITY_PROJECTIONS_BY_RESOURCE = t.identifier('SanityProjectionsByResource')\nexport const ARRAY_OF = t.identifier('ArrayOf')\n\nexport const RESERVED_IDENTIFIERS = new Set<string>()\nRESERVED_IDENTIFIERS.add(SANITY_QUERIES.name)\nRESERVED_IDENTIFIERS.add(ALL_SANITY_SCHEMA_TYPES.name)\nRESERVED_IDENTIFIERS.add(INTERNAL_REFERENCE_SYMBOL.name)\nRESERVED_IDENTIFIERS.add(ARRAY_OF.name)\n"],"names":["t","INTERNAL_REFERENCE_SYMBOL","identifier","ALL_SANITY_SCHEMA_TYPES","SANITY_QUERIES","SANITY_SCHEMAS_BY_RESOURCE","SANITY_QUERIES_BY_RESOURCE","SANITY_PROJECTIONS_BY_RESOURCE","ARRAY_OF","RESERVED_IDENTIFIERS","Set","add","name"],"mappings":"AAAA,YAAYA,OAAO,eAAc;AAEjC,OAAO,MAAMC,4BAA4BD,EAAEE,UAAU,CAAC,+BAA8B;AACpF,OAAO,MAAMC,0BAA0BH,EAAEE,UAAU,CAAC,wBAAuB;AAC3E,OAAO,MAAME,iBAAiBJ,EAAEE,UAAU,CAAC,iBAAgB;AAC3D,OAAO,MAAMG,6BAA6BL,EAAEE,UAAU,CAAC,2BAA0B;AACjF,OAAO,MAAMI,6BAA6BN,EAAEE,UAAU,CAAC,2BAA0B;AACjF,OAAO,MAAMK,iCAAiCP,EAAEE,UAAU,CAAC,+BAA8B;AACzF,OAAO,MAAMM,WAAWR,EAAEE,UAAU,CAAC,WAAU;AAE/C,OAAO,MAAMO,uBAAuB,IAAIC,MAAa;AACrDD,qBAAqBE,GAAG,CAACP,eAAeQ,IAAI;AAC5CH,qBAAqBE,GAAG,CAACR,wBAAwBS,IAAI;AACrDH,qBAAqBE,GAAG,CAACV,0BAA0BW,IAAI;AACvDH,qBAAqBE,GAAG,CAACH,SAASI,IAAI"}
|