@sanity/codegen 3.88.0 → 3.88.1-typegen-experimental.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/lib/index.d.mts +282 -85
- package/lib/index.d.ts +282 -85
- package/lib/index.js +537 -172
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +538 -173
- package/lib/index.mjs.map +1 -1
- package/package.json +15 -17
- package/src/_exports/index.ts +14 -3
- package/src/readConfig.ts +71 -23
- package/src/readSchema.ts +0 -1
- package/src/typescript/asyncQueue.ts +100 -0
- package/src/typescript/expressionResolvers.ts +4 -3
- package/src/typescript/findQueriesInPath.ts +9 -2
- package/src/typescript/findQueriesInSource.ts +22 -6
- package/src/typescript/schemaTypeGenerator.ts +381 -0
- package/src/typescript/typeGenerator.ts +445 -306
|
@@ -1,374 +1,513 @@
|
|
|
1
|
+
/* eslint-disable max-nested-callbacks */
|
|
1
2
|
import {CodeGenerator} from '@babel/generator'
|
|
2
3
|
import * as t from '@babel/types'
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
4
|
+
import {type SchemaType} from 'groq-js'
|
|
5
|
+
|
|
6
|
+
import {AsyncQueue} from './asyncQueue'
|
|
7
|
+
import {type NamedQueryResult} from './expressionResolvers'
|
|
8
|
+
import {type QueryExtractionResult} from './findQueriesInPath'
|
|
9
|
+
import {SchemaTypeGenerator, type TypeEvaluationStats} from './schemaTypeGenerator'
|
|
10
|
+
|
|
11
|
+
const SanityQueries = t.identifier('SanityQueries')
|
|
12
|
+
const SanityProjections = t.identifier('SanityProjections')
|
|
13
|
+
const SanitySchemas = t.identifier('SanitySchemas')
|
|
14
|
+
const SchemaOrigin = t.identifier('SchemaOrigin')
|
|
15
|
+
const PickSchema = t.identifier('PickSchema')
|
|
16
|
+
const AllSanitySchemaTypes = t.identifier('AllSanitySchemaTypes')
|
|
17
|
+
|
|
18
|
+
export interface QueryResultDeclaration {
|
|
19
|
+
filename: string
|
|
20
|
+
name: string
|
|
21
|
+
id: t.Identifier
|
|
19
22
|
query: string
|
|
20
|
-
|
|
23
|
+
code: string
|
|
24
|
+
type: 'query' | 'projection'
|
|
25
|
+
stats: TypeEvaluationStats
|
|
21
26
|
}
|
|
22
27
|
|
|
28
|
+
export type QueryResultDeclarationsFileResult =
|
|
29
|
+
| {
|
|
30
|
+
type: 'queries'
|
|
31
|
+
filename: string
|
|
32
|
+
queryResultDeclarations: QueryResultDeclaration[]
|
|
33
|
+
}
|
|
34
|
+
| {
|
|
35
|
+
type: 'error'
|
|
36
|
+
filename: string
|
|
37
|
+
error: unknown
|
|
38
|
+
}
|
|
39
|
+
|
|
23
40
|
/**
|
|
24
|
-
* A class used to generate TypeScript types from a given schema
|
|
25
41
|
* @internal
|
|
26
|
-
* @beta
|
|
27
42
|
*/
|
|
28
|
-
export
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
private typeNodeNameMap: Map<TypeNode | DocumentSchemaType | TypeDeclarationSchemaType, string> =
|
|
35
|
-
new Map()
|
|
36
|
-
|
|
37
|
-
private readonly schema: SchemaType
|
|
43
|
+
export interface TypeGeneratorOptions {
|
|
44
|
+
schemas: {schema: SchemaType; schemaId: string; filename?: string}[]
|
|
45
|
+
queriesByFile?: AsyncIterable<QueryExtractionResult>
|
|
46
|
+
augmentGroqModule?: boolean
|
|
47
|
+
overloadClientMethods?: boolean
|
|
48
|
+
}
|
|
38
49
|
|
|
39
|
-
|
|
40
|
-
|
|
50
|
+
/**
|
|
51
|
+
* @internal
|
|
52
|
+
*/
|
|
53
|
+
export class TypeGenerator {
|
|
54
|
+
public readonly schemas: SchemaTypeGenerator[]
|
|
55
|
+
public readonly augmentGroqModule: boolean
|
|
56
|
+
public readonly overloadClientMethods: boolean
|
|
57
|
+
|
|
58
|
+
private schemaFilenames = new Map<string, string>()
|
|
59
|
+
private globalIdentifiers = new Set<string>()
|
|
60
|
+
private identifiersByQuery = new Map<string, t.Identifier[]>()
|
|
61
|
+
private identifiersByProjection = new Map<string, t.Identifier[]>()
|
|
62
|
+
private queryResultsQueue = new AsyncQueue<QueryResultDeclarationsFileResult>()
|
|
63
|
+
private augmentedQueryResultsPromise = promiseWithResolvers<{code: string}>()
|
|
64
|
+
private queryFileCountPromise = promiseWithResolvers<{fileCount: number}>()
|
|
65
|
+
|
|
66
|
+
constructor({
|
|
67
|
+
schemas,
|
|
68
|
+
queriesByFile,
|
|
69
|
+
augmentGroqModule = true,
|
|
70
|
+
overloadClientMethods = true,
|
|
71
|
+
}: TypeGeneratorOptions) {
|
|
72
|
+
this.globalIdentifiers.add(SanityQueries.name)
|
|
73
|
+
this.globalIdentifiers.add(SanityProjections.name)
|
|
74
|
+
this.globalIdentifiers.add(SanitySchemas.name)
|
|
75
|
+
this.globalIdentifiers.add(SchemaOrigin.name)
|
|
76
|
+
this.globalIdentifiers.add(PickSchema.name)
|
|
77
|
+
this.globalIdentifiers.add(AllSanitySchemaTypes.name)
|
|
78
|
+
this.globalIdentifiers.add(SchemaTypeGenerator.InternalReferenceSymbol.name)
|
|
79
|
+
this.globalIdentifiers.add(SchemaTypeGenerator.ProjectionBase.name)
|
|
80
|
+
|
|
81
|
+
const schemaIds = new Set<string>()
|
|
82
|
+
for (const {schemaId, filename} of schemas) {
|
|
83
|
+
if (schemaIds.has(schemaId)) {
|
|
84
|
+
throw new Error(`Duplicate schema ID "${schemaId}". Schema IDs must be unique.`)
|
|
85
|
+
}
|
|
86
|
+
schemaIds.add(schemaId)
|
|
87
|
+
if (filename) {
|
|
88
|
+
this.schemaFilenames.set(schemaId, filename)
|
|
89
|
+
}
|
|
90
|
+
}
|
|
41
91
|
|
|
42
|
-
this.
|
|
43
|
-
|
|
44
|
-
|
|
92
|
+
this.schemas = schemas.map((opts) => new SchemaTypeGenerator(opts))
|
|
93
|
+
this.augmentGroqModule = augmentGroqModule
|
|
94
|
+
this.overloadClientMethods = overloadClientMethods
|
|
95
|
+
|
|
96
|
+
// We need to eagerly compute these in the constructor because
|
|
97
|
+
// `generateAndRegisterExportedTypeAlias` has a side effect of reserving
|
|
98
|
+
// global identifier names. The order also matters as `getSchemaDeclarations`
|
|
99
|
+
// depends on the identifiers generated by `getSchemaTypeDeclarations`.
|
|
100
|
+
this.getSchemaTypeDeclarations()
|
|
101
|
+
this.getSchemaDeclarations()
|
|
102
|
+
|
|
103
|
+
if (queriesByFile) {
|
|
104
|
+
this.handleQueries(queriesByFile).catch((error) => {
|
|
105
|
+
this.queryFileCountPromise.reject(error)
|
|
106
|
+
this.queryResultsQueue.throwError(error)
|
|
107
|
+
this.augmentedQueryResultsPromise.reject(error)
|
|
108
|
+
})
|
|
109
|
+
} else {
|
|
110
|
+
this.queryFileCountPromise.resolve({fileCount: 0})
|
|
111
|
+
}
|
|
45
112
|
}
|
|
46
113
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
*/
|
|
53
|
-
generateSchemaTypes(): string {
|
|
54
|
-
const typeDeclarations: (t.TSTypeAliasDeclaration | t.ExportNamedDeclaration)[] = []
|
|
55
|
-
|
|
56
|
-
const schemaNames = new Set<string>()
|
|
57
|
-
this.schema.forEach((schema) => {
|
|
58
|
-
const typeLiteral = this.getTypeNodeType(schema)
|
|
59
|
-
|
|
60
|
-
const schemaName = this.typeNodeNameMap.get(schema)
|
|
61
|
-
if (!schemaName) {
|
|
62
|
-
throw new Error(`Schema name not found for schema ${schema.name}`)
|
|
114
|
+
private async handleQueries(queriesByFile: AsyncIterable<QueryExtractionResult>) {
|
|
115
|
+
for await (const result of queriesByFile) {
|
|
116
|
+
if (result.type === 'files') {
|
|
117
|
+
this.queryFileCountPromise.resolve({fileCount: result.fileCount})
|
|
118
|
+
continue
|
|
63
119
|
}
|
|
64
120
|
|
|
65
|
-
|
|
66
|
-
|
|
121
|
+
try {
|
|
122
|
+
if (result.type === 'error') throw result.error
|
|
123
|
+
const {filename, queries} = result
|
|
124
|
+
|
|
125
|
+
const queryResultDeclarations: QueryResultDeclaration[] = []
|
|
126
|
+
for (const query of queries) {
|
|
127
|
+
try {
|
|
128
|
+
queryResultDeclarations.push({
|
|
129
|
+
filename,
|
|
130
|
+
query: query.result,
|
|
131
|
+
...this.generateQueryResultType({...query, filename}),
|
|
132
|
+
})
|
|
133
|
+
} catch (error) {
|
|
134
|
+
this.queryResultsQueue.enqueue({type: 'error', filename, error})
|
|
135
|
+
}
|
|
136
|
+
}
|
|
67
137
|
|
|
68
|
-
|
|
69
|
-
|
|
138
|
+
this.queryResultsQueue.enqueue({type: 'queries', filename, queryResultDeclarations})
|
|
139
|
+
} catch (error) {
|
|
140
|
+
this.queryResultsQueue.enqueue({type: 'error', filename: result.filename, error})
|
|
141
|
+
}
|
|
142
|
+
}
|
|
70
143
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
144
|
+
this.queryResultsQueue.finish()
|
|
145
|
+
|
|
146
|
+
let augmentedQueryResultsCode = ''
|
|
147
|
+
const clientModuleBlockStatement: t.Statement[] = []
|
|
148
|
+
const groqModuleBlockStatement: t.Statement[] = []
|
|
149
|
+
|
|
150
|
+
// Only generate SanityQueries if there are query results
|
|
151
|
+
if (this.identifiersByQuery.size > 0) {
|
|
152
|
+
const sanityQueriesInterfaceDeclaration = t.tsInterfaceDeclaration(
|
|
153
|
+
SanityQueries,
|
|
154
|
+
null,
|
|
155
|
+
[],
|
|
156
|
+
t.tsInterfaceBody(
|
|
157
|
+
Array.from(this.identifiersByQuery).map(([query, identifiers]) =>
|
|
158
|
+
t.tsPropertySignature(
|
|
159
|
+
t.stringLiteral(query),
|
|
160
|
+
t.tsTypeAnnotation(
|
|
161
|
+
identifiers.length === 1
|
|
162
|
+
? t.tsTypeReference(identifiers[0])
|
|
163
|
+
: t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i))),
|
|
164
|
+
),
|
|
165
|
+
),
|
|
78
166
|
),
|
|
79
167
|
),
|
|
80
|
-
)
|
|
81
|
-
|
|
168
|
+
)
|
|
169
|
+
// Add to both module declarations if needed
|
|
170
|
+
clientModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)
|
|
171
|
+
groqModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)
|
|
172
|
+
}
|
|
82
173
|
|
|
83
|
-
//
|
|
84
|
-
|
|
85
|
-
|
|
174
|
+
// Only generate SanityProjections if there are projection results
|
|
175
|
+
if (this.identifiersByProjection.size > 0) {
|
|
176
|
+
const sanityProjectionsInterfaceDeclaration = t.tsInterfaceDeclaration(
|
|
177
|
+
SanityProjections,
|
|
178
|
+
null,
|
|
179
|
+
[],
|
|
180
|
+
t.tsInterfaceBody(
|
|
181
|
+
Array.from(this.identifiersByProjection).map(([projection, identifiers]) =>
|
|
182
|
+
t.tsPropertySignature(
|
|
183
|
+
t.stringLiteral(projection),
|
|
184
|
+
t.tsTypeAnnotation(
|
|
185
|
+
identifiers.length === 1
|
|
186
|
+
? t.tsTypeReference(identifiers[0])
|
|
187
|
+
: t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i))),
|
|
188
|
+
),
|
|
189
|
+
),
|
|
190
|
+
),
|
|
191
|
+
),
|
|
192
|
+
)
|
|
86
193
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
* @param typeNode - The type node to generate the type for
|
|
91
|
-
* @returns
|
|
92
|
-
* @internal
|
|
93
|
-
* @beta
|
|
94
|
-
*/
|
|
95
|
-
generateTypeNodeTypes(identifierName: string, typeNode: TypeNode): string {
|
|
96
|
-
const type = this.getTypeNodeType(typeNode)
|
|
97
|
-
|
|
98
|
-
const typeName = this.getTypeName(identifierName, typeNode)
|
|
99
|
-
const typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type)
|
|
100
|
-
|
|
101
|
-
return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim()
|
|
102
|
-
}
|
|
194
|
+
// Add only to groq module declaration
|
|
195
|
+
groqModuleBlockStatement.push(sanityProjectionsInterfaceDeclaration)
|
|
196
|
+
}
|
|
103
197
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
198
|
+
if (this.overloadClientMethods && clientModuleBlockStatement.length > 0) {
|
|
199
|
+
const clientModuleDeclaration = t.declareModule(
|
|
200
|
+
t.stringLiteral('@sanity/client'),
|
|
201
|
+
t.blockStatement(clientModuleBlockStatement),
|
|
202
|
+
)
|
|
203
|
+
augmentedQueryResultsCode += generateCode(clientModuleDeclaration)
|
|
204
|
+
}
|
|
107
205
|
|
|
108
|
-
|
|
109
|
-
|
|
206
|
+
if (this.augmentGroqModule && groqModuleBlockStatement.length > 0) {
|
|
207
|
+
const groqModuleDeclaration = t.declareModule(
|
|
208
|
+
t.stringLiteral('groq'),
|
|
209
|
+
t.blockStatement(groqModuleBlockStatement),
|
|
210
|
+
)
|
|
211
|
+
augmentedQueryResultsCode += generateCode(groqModuleDeclaration)
|
|
212
|
+
}
|
|
110
213
|
|
|
111
|
-
|
|
112
|
-
decleration.declare = true
|
|
113
|
-
return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()
|
|
214
|
+
this.augmentedQueryResultsPromise.resolve({code: augmentedQueryResultsCode})
|
|
114
215
|
}
|
|
115
216
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
if (!name) {
|
|
134
|
-
continue
|
|
217
|
+
private generateQueryResultType({
|
|
218
|
+
name,
|
|
219
|
+
result,
|
|
220
|
+
type,
|
|
221
|
+
filename,
|
|
222
|
+
}: NamedQueryResult & {filename: string}) {
|
|
223
|
+
const evaluationResults: {schemaId: string; tsType: t.TSType; stats: TypeEvaluationStats}[] = []
|
|
224
|
+
for (const schema of this.schemas) {
|
|
225
|
+
const {schemaId} = schema
|
|
226
|
+
|
|
227
|
+
if (type === 'projection') {
|
|
228
|
+
const projectionResult = schema.evaluateProjection(result)
|
|
229
|
+
if (!projectionResult) continue
|
|
230
|
+
evaluationResults.push({schemaId, ...projectionResult})
|
|
231
|
+
} else {
|
|
232
|
+
const queryResult = schema.evaluateQuery(result)
|
|
233
|
+
evaluationResults.push({schemaId, ...queryResult})
|
|
135
234
|
}
|
|
136
|
-
|
|
137
|
-
typesByQuerystring[query.query] ??= []
|
|
138
|
-
typesByQuerystring[query.query].push(name)
|
|
139
235
|
}
|
|
140
236
|
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
return t.tsPropertySignature(
|
|
148
|
-
t.stringLiteral(query),
|
|
149
|
-
t.tsTypeAnnotation(
|
|
150
|
-
t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type)))),
|
|
151
|
-
),
|
|
152
|
-
)
|
|
153
|
-
}),
|
|
154
|
-
),
|
|
155
|
-
)
|
|
237
|
+
const tsTypes = evaluationResults.map(({tsType, schemaId}) => {
|
|
238
|
+
if (this.schemas.length === 1) return tsType
|
|
239
|
+
return addSchemaOrigin(tsType, schemaId)
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
const tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes)
|
|
156
243
|
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
|
|
244
|
+
const {code, id} = this.generateAndRegisterExportedTypeAlias(
|
|
245
|
+
`${name}${type === 'projection' ? 'ProjectionResult' : 'Result'}`,
|
|
246
|
+
tsType,
|
|
247
|
+
[
|
|
248
|
+
{type: 'CommentLine', value: ` Source: ${filename}`},
|
|
249
|
+
{type: 'CommentLine', value: ` Variable: ${name}`},
|
|
250
|
+
{
|
|
251
|
+
type: 'CommentLine',
|
|
252
|
+
value: ` ${type === 'projection' ? 'Projection' : 'Query'}: ${result.replace(/(\r\n|\n|\r)/gm, '').trim()}`,
|
|
253
|
+
},
|
|
254
|
+
],
|
|
160
255
|
)
|
|
161
256
|
|
|
162
|
-
const
|
|
257
|
+
const identifiersByProjectionOrQuery =
|
|
258
|
+
type === 'projection' ? this.identifiersByProjection : this.identifiersByQuery
|
|
259
|
+
|
|
260
|
+
let identifiers = identifiersByProjectionOrQuery.get(result)
|
|
163
261
|
|
|
164
|
-
|
|
262
|
+
if (!identifiers) {
|
|
263
|
+
identifiers = []
|
|
264
|
+
identifiersByProjectionOrQuery.set(result, identifiers)
|
|
265
|
+
}
|
|
266
|
+
identifiers.push(id)
|
|
267
|
+
|
|
268
|
+
return {
|
|
269
|
+
code,
|
|
270
|
+
id,
|
|
271
|
+
name,
|
|
272
|
+
type,
|
|
273
|
+
stats: evaluationResults.reduce<TypeEvaluationStats>(
|
|
274
|
+
(acc, {stats}) => ({
|
|
275
|
+
allTypes: acc.allTypes + stats.allTypes,
|
|
276
|
+
unknownTypes: acc.unknownTypes + stats.unknownTypes,
|
|
277
|
+
emptyUnions: acc.emptyUnions + stats.emptyUnions,
|
|
278
|
+
}),
|
|
279
|
+
{allTypes: 0, unknownTypes: 0, emptyUnions: 0},
|
|
280
|
+
),
|
|
281
|
+
}
|
|
165
282
|
}
|
|
166
283
|
|
|
167
|
-
|
|
168
|
-
* Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these
|
|
169
|
-
* types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.
|
|
170
|
-
* When we reference a type we also keep track of the original name so we can reference the correct type later.
|
|
171
|
-
*/
|
|
172
|
-
private getTypeName(
|
|
284
|
+
private generateAndRegisterExportedTypeAlias(
|
|
173
285
|
name: string,
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
let
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
286
|
+
tsType: t.TSType,
|
|
287
|
+
comments?: t.Comment[],
|
|
288
|
+
): {code: string; id: t.Identifier} {
|
|
289
|
+
const desiredName = SchemaTypeGenerator.normalizeIdentifier(name)
|
|
290
|
+
|
|
291
|
+
let resultingName = desiredName
|
|
292
|
+
let index = 2
|
|
293
|
+
while (this.globalIdentifiers.has(resultingName)) {
|
|
294
|
+
resultingName = `${desiredName}_${index}`
|
|
295
|
+
index++
|
|
183
296
|
}
|
|
184
|
-
|
|
185
|
-
this.
|
|
186
|
-
|
|
187
|
-
|
|
297
|
+
|
|
298
|
+
this.globalIdentifiers.add(resultingName)
|
|
299
|
+
|
|
300
|
+
const id = t.identifier(resultingName)
|
|
301
|
+
|
|
302
|
+
const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)
|
|
303
|
+
let exportDeclaration = t.exportNamedDeclaration(typeAlias)
|
|
304
|
+
|
|
305
|
+
if (comments) {
|
|
306
|
+
exportDeclaration = t.addComments(exportDeclaration, 'leading', comments)
|
|
188
307
|
}
|
|
189
308
|
|
|
190
|
-
|
|
309
|
+
const code = generateCode(exportDeclaration)
|
|
310
|
+
|
|
311
|
+
return {id, code}
|
|
191
312
|
}
|
|
192
313
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
): t.TSType {
|
|
196
|
-
switch (typeNode.type) {
|
|
197
|
-
case 'string': {
|
|
198
|
-
if (typeNode.value !== undefined) {
|
|
199
|
-
return t.tsLiteralType(t.stringLiteral(typeNode.value))
|
|
200
|
-
}
|
|
201
|
-
return t.tsStringKeyword()
|
|
202
|
-
}
|
|
203
|
-
case 'number': {
|
|
204
|
-
if (typeNode.value !== undefined) {
|
|
205
|
-
return t.tsLiteralType(t.numericLiteral(typeNode.value))
|
|
206
|
-
}
|
|
207
|
-
return t.tsNumberKeyword()
|
|
208
|
-
}
|
|
209
|
-
case 'boolean': {
|
|
210
|
-
if (typeNode.value !== undefined) {
|
|
211
|
-
return t.tsLiteralType(t.booleanLiteral(typeNode.value))
|
|
212
|
-
}
|
|
213
|
-
return t.tsBooleanKeyword()
|
|
214
|
-
}
|
|
215
|
-
case 'unknown': {
|
|
216
|
-
return t.tsUnknownKeyword()
|
|
217
|
-
}
|
|
218
|
-
case 'document': {
|
|
219
|
-
return this.generateDocumentType(typeNode)
|
|
220
|
-
}
|
|
221
|
-
case 'type': {
|
|
222
|
-
return this.getTypeNodeType(typeNode.value)
|
|
223
|
-
}
|
|
224
|
-
case 'array': {
|
|
225
|
-
return this.generateArrayTsType(typeNode)
|
|
226
|
-
}
|
|
227
|
-
case 'object': {
|
|
228
|
-
return this.generateObjectTsType(typeNode)
|
|
229
|
-
}
|
|
230
|
-
case 'union': {
|
|
231
|
-
return this.generateUnionTsType(typeNode)
|
|
232
|
-
}
|
|
233
|
-
case 'inline': {
|
|
234
|
-
return this.generateInlineTsType(typeNode)
|
|
235
|
-
}
|
|
236
|
-
case 'null': {
|
|
237
|
-
return t.tsNullKeyword()
|
|
238
|
-
}
|
|
314
|
+
getKnownTypes = computeOnce(() => {
|
|
315
|
+
let code = ''
|
|
239
316
|
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
throw new Error(`Type "${typeNode.type}" not found in schema`)
|
|
317
|
+
if (this.overloadClientMethods) {
|
|
318
|
+
code += generateCode(t.importDeclaration([], t.stringLiteral('@sanity/client')))
|
|
243
319
|
}
|
|
244
|
-
}
|
|
245
320
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
const arrayType = t.tsTypeReference(
|
|
250
|
-
t.identifier('Array'),
|
|
251
|
-
t.tsTypeParameterInstantiation([typeNodes]),
|
|
252
|
-
)
|
|
321
|
+
const importSpecifiers = [
|
|
322
|
+
t.importSpecifier(SchemaTypeGenerator.ProjectionBase, SchemaTypeGenerator.ProjectionBase),
|
|
323
|
+
]
|
|
253
324
|
|
|
254
|
-
|
|
255
|
-
|
|
325
|
+
if (this.schemas.length > 1) {
|
|
326
|
+
importSpecifiers.push(t.importSpecifier(PickSchema, PickSchema))
|
|
327
|
+
importSpecifiers.push(t.importSpecifier(SchemaOrigin, SchemaOrigin))
|
|
328
|
+
}
|
|
256
329
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
t.identifier(sanitizeIdentifier(key)),
|
|
262
|
-
t.tsTypeAnnotation(type),
|
|
330
|
+
code += generateCode(
|
|
331
|
+
Object.assign(t.importDeclaration(importSpecifiers, t.stringLiteral('groq')), {
|
|
332
|
+
importKind: 'type',
|
|
333
|
+
}),
|
|
263
334
|
)
|
|
264
|
-
propertySignature.optional = attribute.optional
|
|
265
335
|
|
|
266
|
-
|
|
267
|
-
|
|
336
|
+
code += generateCode(
|
|
337
|
+
t.exportNamedDeclaration(
|
|
338
|
+
Object.assign(
|
|
339
|
+
t.variableDeclaration('const', [
|
|
340
|
+
t.variableDeclarator(SchemaTypeGenerator.InternalReferenceSymbol),
|
|
341
|
+
]),
|
|
342
|
+
{declare: true},
|
|
343
|
+
),
|
|
344
|
+
),
|
|
345
|
+
)
|
|
268
346
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
347
|
+
return {code}
|
|
348
|
+
})
|
|
349
|
+
|
|
350
|
+
getSchemaTypeDeclarations = computeOnce(() => {
|
|
351
|
+
const typeNames = new Set(this.schemas.flatMap((schema) => schema.getTypeNames()))
|
|
352
|
+
|
|
353
|
+
return Array.from(typeNames).flatMap((typeName) => {
|
|
354
|
+
const identifiers = new Set(
|
|
355
|
+
this.schemas
|
|
356
|
+
.map((schema) => schema.getIdentifier(typeName)?.name)
|
|
357
|
+
.filter((i) => typeof i === 'string'),
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
return Array.from(identifiers).map((identifier) => {
|
|
361
|
+
const types = this.schemas
|
|
362
|
+
.filter(
|
|
363
|
+
(schema) =>
|
|
364
|
+
schema.getIdentifier(typeName)?.name === identifier && !!schema.getTsType(typeName),
|
|
365
|
+
)
|
|
366
|
+
.map((schema) => {
|
|
367
|
+
const tsType = schema.getTsType(typeName)!
|
|
368
|
+
const schemaId = schema.schemaId
|
|
369
|
+
|
|
370
|
+
// no need to wrap with SchemaOrigin if there aren't at least 2 schemas
|
|
371
|
+
if (this.schemas.length < 2) return {schemaId, tsType}
|
|
372
|
+
return {schemaId, tsType: addSchemaOrigin(tsType, schemaId)}
|
|
284
373
|
})
|
|
285
|
-
break
|
|
286
|
-
}
|
|
287
|
-
case 'inline': {
|
|
288
|
-
const resolved = this.generateInlineTsType(rest)
|
|
289
374
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
375
|
+
const schemaIds = types.map((i) => i.schemaId)
|
|
376
|
+
const tsType =
|
|
377
|
+
types.length === 1 ? types[0].tsType : t.tsUnionType(types.map((i) => i.tsType))
|
|
378
|
+
const {id, code} = this.generateAndRegisterExportedTypeAlias(identifier, tsType)
|
|
379
|
+
|
|
380
|
+
return {id, code, schemaIds}
|
|
381
|
+
})
|
|
382
|
+
})
|
|
383
|
+
})
|
|
384
|
+
|
|
385
|
+
getAllSanitySchemaTypesDeclaration = computeOnce(() => {
|
|
386
|
+
const schemaTypeDeclarations = this.getSchemaTypeDeclarations()
|
|
387
|
+
const code = generateCode(
|
|
388
|
+
t.exportNamedDeclaration(
|
|
389
|
+
t.tsTypeAliasDeclaration(
|
|
390
|
+
AllSanitySchemaTypes,
|
|
391
|
+
null,
|
|
392
|
+
t.tsUnionType(schemaTypeDeclarations.map(({id}) => t.tsTypeReference(id))),
|
|
393
|
+
),
|
|
394
|
+
),
|
|
395
|
+
)
|
|
396
|
+
return {code}
|
|
397
|
+
})
|
|
398
|
+
|
|
399
|
+
getSchemaDeclarations = computeOnce(() => {
|
|
400
|
+
const schemaTypeDeclarations = this.getSchemaTypeDeclarations()
|
|
401
|
+
const identifierUsageCountBySchemaId = schemaTypeDeclarations.reduce<{
|
|
402
|
+
[schemaId: string]: {[identifier: string]: number}
|
|
403
|
+
}>((acc, {schemaIds, id}) => {
|
|
404
|
+
for (const schemaId of schemaIds) {
|
|
405
|
+
acc[schemaId] = acc[schemaId] ?? {}
|
|
406
|
+
acc[schemaId][id.name] = schemaIds.length
|
|
301
407
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
408
|
+
return acc
|
|
409
|
+
}, {})
|
|
410
|
+
|
|
411
|
+
return this.schemas.map(({schemaId}) => {
|
|
412
|
+
const tsTypes = Object.entries(identifierUsageCountBySchemaId[schemaId]).map(
|
|
413
|
+
([identifierName, schemaCount]) => {
|
|
414
|
+
const schemaTypeReferencer = t.tsTypeReference(t.identifier(identifierName))
|
|
415
|
+
if (schemaCount > 1) return addPickSchema(schemaTypeReferencer, schemaId)
|
|
416
|
+
return schemaTypeReferencer
|
|
417
|
+
},
|
|
307
418
|
)
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
}
|
|
312
|
-
return t.tsTypeLiteral(props)
|
|
313
|
-
}
|
|
419
|
+
const tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes)
|
|
420
|
+
|
|
421
|
+
const comments: t.Comment[] = []
|
|
314
422
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
if (referencedTypeNode === undefined) {
|
|
319
|
-
// Is it already generated by another type node?
|
|
320
|
-
const generatedName = this.typeNameMap.get(typeNode.name)
|
|
321
|
-
if (generatedName) {
|
|
322
|
-
return t.tsTypeReference(t.identifier(generatedName))
|
|
423
|
+
const filename = this.schemaFilenames.get(schemaId)
|
|
424
|
+
if (filename) {
|
|
425
|
+
comments.push({type: 'CommentLine', value: ` Source: ${filename}`})
|
|
323
426
|
}
|
|
427
|
+
comments.push({type: 'CommentLine', value: ` Schema ID: ${schemaId}`})
|
|
324
428
|
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
value: ` Unable to locate the referenced type "${typeNode.name}" in schema`,
|
|
331
|
-
},
|
|
332
|
-
]
|
|
333
|
-
return missing
|
|
334
|
-
}
|
|
429
|
+
const {id, code} = this.generateAndRegisterExportedTypeAlias(
|
|
430
|
+
`${schemaId}Schema`,
|
|
431
|
+
tsType,
|
|
432
|
+
comments,
|
|
433
|
+
)
|
|
335
434
|
|
|
336
|
-
|
|
435
|
+
return {id, code, schemaId}
|
|
436
|
+
})
|
|
437
|
+
})
|
|
337
438
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
439
|
+
getAugmentedSchemasDeclarations = computeOnce(() => {
|
|
440
|
+
if (!this.augmentGroqModule) return {code: ''}
|
|
441
|
+
const schemaDeclarations = this.getSchemaDeclarations()
|
|
341
442
|
|
|
342
|
-
|
|
343
|
-
|
|
443
|
+
const groqModuleDeclaration = t.declareModule(
|
|
444
|
+
t.stringLiteral('groq'),
|
|
445
|
+
t.blockStatement([
|
|
446
|
+
t.tsInterfaceDeclaration(
|
|
447
|
+
SanitySchemas,
|
|
448
|
+
null,
|
|
449
|
+
[],
|
|
450
|
+
t.tsInterfaceBody(
|
|
451
|
+
schemaDeclarations.map(({id, schemaId}) =>
|
|
452
|
+
t.tsPropertySignature(
|
|
453
|
+
t.stringLiteral(schemaId),
|
|
454
|
+
t.tsTypeAnnotation(t.tsTypeReference(id)),
|
|
455
|
+
),
|
|
456
|
+
),
|
|
457
|
+
),
|
|
458
|
+
),
|
|
459
|
+
]),
|
|
460
|
+
)
|
|
344
461
|
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
if (typeNode.of.length === 0) {
|
|
348
|
-
return t.tsNeverKeyword()
|
|
349
|
-
}
|
|
350
|
-
if (typeNode.of.length === 1) {
|
|
351
|
-
return this.getTypeNodeType(typeNode.of[0])
|
|
352
|
-
}
|
|
462
|
+
return {code: generateCode(groqModuleDeclaration)}
|
|
463
|
+
})
|
|
353
464
|
|
|
354
|
-
|
|
465
|
+
getQueryFileCount = (): Promise<{fileCount: number}> => this.queryFileCountPromise.promise
|
|
355
466
|
|
|
356
|
-
|
|
357
|
-
|
|
467
|
+
getQueryResultDeclarations = (): AsyncIterable<QueryResultDeclarationsFileResult> =>
|
|
468
|
+
this.queryResultsQueue
|
|
358
469
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
this.generateObjectProperty(key, node),
|
|
363
|
-
)
|
|
470
|
+
getAugmentedQueryResultsDeclarations = (): Promise<{code: string}> =>
|
|
471
|
+
this.augmentedQueryResultsPromise.promise
|
|
472
|
+
}
|
|
364
473
|
|
|
365
|
-
|
|
474
|
+
function computeOnce<TThis, TReturn>(this: TThis, fn: () => TReturn): (this: TThis) => TReturn {
|
|
475
|
+
const ref = {current: undefined as TReturn | undefined, computed: false}
|
|
476
|
+
|
|
477
|
+
return function (this: TThis) {
|
|
478
|
+
if (ref.computed) return ref.current as TReturn
|
|
479
|
+
ref.current = fn.call(this)
|
|
480
|
+
ref.computed = true
|
|
481
|
+
return ref.current
|
|
366
482
|
}
|
|
367
483
|
}
|
|
368
|
-
|
|
369
|
-
|
|
484
|
+
|
|
485
|
+
function addSchemaOrigin(tsType: t.TSType, schemaId: string) {
|
|
486
|
+
return t.tsTypeReference(
|
|
487
|
+
SchemaOrigin,
|
|
488
|
+
t.tsTypeParameterInstantiation([tsType, t.tsLiteralType(t.stringLiteral(schemaId))]),
|
|
489
|
+
)
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function addPickSchema(tsType: t.TSType, schemaId: string) {
|
|
493
|
+
return t.tsTypeReference(
|
|
494
|
+
PickSchema,
|
|
495
|
+
t.tsTypeParameterInstantiation([tsType, t.tsLiteralType(t.stringLiteral(schemaId))]),
|
|
496
|
+
)
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function generateCode(node: t.Node) {
|
|
500
|
+
return `${new CodeGenerator(node).generate().code.trim()}\n\n`
|
|
370
501
|
}
|
|
371
502
|
|
|
372
|
-
|
|
373
|
-
|
|
503
|
+
// Similar to `Promise.withResolvers`
|
|
504
|
+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers
|
|
505
|
+
function promiseWithResolvers<T = void>() {
|
|
506
|
+
let resolve!: (t: T) => void
|
|
507
|
+
let reject!: (error: unknown) => void
|
|
508
|
+
const promise = new Promise<T>((thisResolve, thisReject) => {
|
|
509
|
+
resolve = thisResolve
|
|
510
|
+
reject = thisReject
|
|
511
|
+
})
|
|
512
|
+
return {promise, resolve, reject}
|
|
374
513
|
}
|