@sanity/codegen 3.86.2-experimental.0 → 3.87.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 +91 -79
- package/lib/index.d.ts +91 -79
- package/lib/index.js +151 -492
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +152 -493
- package/lib/index.mjs.map +1 -1
- package/package.json +17 -15
- package/src/_exports/index.ts +3 -16
- package/src/readConfig.ts +19 -77
- package/src/typescript/expressionResolvers.ts +3 -4
- package/src/typescript/findQueriesInPath.ts +2 -2
- package/src/typescript/findQueriesInSource.ts +5 -25
- package/src/typescript/typeGenerator.ts +374 -0
- package/src/typescript/asyncQueue.ts +0 -100
- package/src/typescript/generateTypes.ts +0 -425
- package/src/typescript/schemaTypeGenerator.ts +0 -415
|
@@ -1,425 +0,0 @@
|
|
|
1
|
-
/* eslint-disable max-depth */
|
|
2
|
-
/* eslint-disable max-statements */
|
|
3
|
-
import {CodeGenerator} from '@babel/generator'
|
|
4
|
-
import * as t from '@babel/types'
|
|
5
|
-
import {type SchemaType} from 'groq-js'
|
|
6
|
-
|
|
7
|
-
import {AsyncQueue} from './asyncQueue'
|
|
8
|
-
import {type ResultError, type ResultQueries} 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 DocumentTypeScoped = t.identifier('DocumentTypeScoped')
|
|
15
|
-
const DatasetScoped = t.identifier('DatasetScoped')
|
|
16
|
-
const ExtractDataset = t.identifier('ExtractDataset')
|
|
17
|
-
const AllSchemaTypes = t.identifier('AllSanitySchemaTypes')
|
|
18
|
-
const ReferenceSymbol = Object.assign(t.identifier(SchemaTypeGenerator.REFERENCE_SYMBOL_NAME), {
|
|
19
|
-
typeAnnotation: t.tsTypeAnnotation(
|
|
20
|
-
Object.assign(t.tsTypeOperator(t.tsSymbolKeyword()), {operator: 'unique'}),
|
|
21
|
-
),
|
|
22
|
-
})
|
|
23
|
-
|
|
24
|
-
export interface GeneratedSchema {
|
|
25
|
-
code: string
|
|
26
|
-
schemas: {
|
|
27
|
-
filename: string
|
|
28
|
-
projectId: string | 'default'
|
|
29
|
-
dataset: string | 'default'
|
|
30
|
-
typeCount: number
|
|
31
|
-
}[]
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export interface GeneratedQueries {
|
|
35
|
-
filename: string
|
|
36
|
-
results: GeneratedQuery[]
|
|
37
|
-
error?: unknown
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export interface GeneratedQuery {
|
|
41
|
-
name: string
|
|
42
|
-
query: string
|
|
43
|
-
code: string
|
|
44
|
-
type: 'query' | 'projection'
|
|
45
|
-
stats: TypeEvaluationStats
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export interface GeneratedTypemap {
|
|
49
|
-
code: string
|
|
50
|
-
stats: TypeEvaluationStats
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export interface TypegenResults {
|
|
54
|
-
generatedSchema: () => Promise<GeneratedSchema>
|
|
55
|
-
generatedQueries: () => AsyncIterable<GeneratedQueries>
|
|
56
|
-
generatedTypemap: () => Promise<GeneratedTypemap>
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
export interface GenerateTypesOptions {
|
|
60
|
-
schemas: {
|
|
61
|
-
projectId: string
|
|
62
|
-
dataset: string
|
|
63
|
-
filename: string
|
|
64
|
-
schema: SchemaType
|
|
65
|
-
}[]
|
|
66
|
-
queriesByFile: AsyncIterable<ResultQueries | ResultError>
|
|
67
|
-
augmentGroqModule: boolean
|
|
68
|
-
overloadClientMethods: boolean
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function generateCode(node: t.Node) {
|
|
72
|
-
return `${new CodeGenerator(node).generate().code.trim()}\n\n`
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function scopeByDataset(tsType: t.TSType, options: {dataset: string; projectId: string}) {
|
|
76
|
-
return t.tsTypeReference(
|
|
77
|
-
DatasetScoped,
|
|
78
|
-
t.tsTypeParameterInstantiation([
|
|
79
|
-
tsType,
|
|
80
|
-
t.tsLiteralType(t.stringLiteral(options.dataset)),
|
|
81
|
-
t.tsLiteralType(t.stringLiteral(options.projectId)),
|
|
82
|
-
]),
|
|
83
|
-
)
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// TODO: replace with `Promise.withResolvers` once the environments supports it
|
|
87
|
-
function PromiseWithResolvers<T = void>() {
|
|
88
|
-
let resolve!: (value: T) => void
|
|
89
|
-
let reject!: (error: unknown) => void
|
|
90
|
-
const promise = new Promise<T>((thisResolve, thisReject) => {
|
|
91
|
-
resolve = thisResolve
|
|
92
|
-
reject = thisReject
|
|
93
|
-
})
|
|
94
|
-
return {promise, resolve, reject}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
export function generateTypes({
|
|
98
|
-
schemas,
|
|
99
|
-
queriesByFile,
|
|
100
|
-
augmentGroqModule,
|
|
101
|
-
overloadClientMethods,
|
|
102
|
-
}: GenerateTypesOptions): TypegenResults {
|
|
103
|
-
const globalIdentifiers = new Set<string>()
|
|
104
|
-
|
|
105
|
-
globalIdentifiers.add(SanityQueries.name)
|
|
106
|
-
globalIdentifiers.add(SanityProjections.name)
|
|
107
|
-
globalIdentifiers.add(SanitySchemas.name)
|
|
108
|
-
globalIdentifiers.add(DocumentTypeScoped.name)
|
|
109
|
-
globalIdentifiers.add(DatasetScoped.name)
|
|
110
|
-
globalIdentifiers.add(ExtractDataset.name)
|
|
111
|
-
globalIdentifiers.add(AllSchemaTypes.name)
|
|
112
|
-
globalIdentifiers.add(ReferenceSymbol.name)
|
|
113
|
-
|
|
114
|
-
const generatedQueries = new AsyncQueue<GeneratedQueries>()
|
|
115
|
-
const {
|
|
116
|
-
promise: generatedSchema,
|
|
117
|
-
resolve: resolveGeneratedSchema,
|
|
118
|
-
reject: rejectGeneratedSchema,
|
|
119
|
-
} = PromiseWithResolvers<GeneratedSchema>()
|
|
120
|
-
const {
|
|
121
|
-
promise: generatedTypemap,
|
|
122
|
-
resolve: resolveGeneratedTypemap,
|
|
123
|
-
reject: rejectGeneratedTypemap,
|
|
124
|
-
} = PromiseWithResolvers<GeneratedTypemap>()
|
|
125
|
-
|
|
126
|
-
;(async () => {
|
|
127
|
-
const schemaGenerators = schemas.map((options) => new SchemaTypeGenerator(options))
|
|
128
|
-
const typeNames = new Set(schemaGenerators.flatMap((i) => i.getTypeNames()))
|
|
129
|
-
|
|
130
|
-
let schemaCode = ''
|
|
131
|
-
|
|
132
|
-
if (overloadClientMethods) {
|
|
133
|
-
schemaCode += generateCode(t.importDeclaration([], t.stringLiteral('@sanity/client')))
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
schemaCode += generateCode(
|
|
137
|
-
Object.assign(
|
|
138
|
-
t.importDeclaration(
|
|
139
|
-
[
|
|
140
|
-
t.importSpecifier(DocumentTypeScoped, DocumentTypeScoped),
|
|
141
|
-
t.importSpecifier(ExtractDataset, ExtractDataset),
|
|
142
|
-
t.importSpecifier(DatasetScoped, DatasetScoped),
|
|
143
|
-
],
|
|
144
|
-
t.stringLiteral('groq'),
|
|
145
|
-
),
|
|
146
|
-
{importKind: 'type'},
|
|
147
|
-
),
|
|
148
|
-
)
|
|
149
|
-
|
|
150
|
-
schemaCode += generateCode(
|
|
151
|
-
t.exportNamedDeclaration(
|
|
152
|
-
Object.assign(t.variableDeclaration('const', [t.variableDeclarator(ReferenceSymbol)]), {
|
|
153
|
-
declare: true,
|
|
154
|
-
}),
|
|
155
|
-
),
|
|
156
|
-
)
|
|
157
|
-
|
|
158
|
-
const schemaIdentifiers = new Set<string>()
|
|
159
|
-
|
|
160
|
-
for (const typeName of typeNames) {
|
|
161
|
-
const identifiers = new Set(
|
|
162
|
-
schemaGenerators
|
|
163
|
-
.map((i) => i.getIdentifier(typeName)?.name)
|
|
164
|
-
.filter((i) => typeof i === 'string'),
|
|
165
|
-
)
|
|
166
|
-
|
|
167
|
-
for (const identifier of identifiers) {
|
|
168
|
-
globalIdentifiers.add(identifier)
|
|
169
|
-
|
|
170
|
-
const tsTypes = schemaGenerators
|
|
171
|
-
.filter((i) => i.getIdentifier(typeName)?.name === identifier)
|
|
172
|
-
.map((i) => {
|
|
173
|
-
const tsType = i.getTsType(typeName)
|
|
174
|
-
if (tsType && schemaGenerators.length > 1) return scopeByDataset(tsType, i)
|
|
175
|
-
return tsType
|
|
176
|
-
})
|
|
177
|
-
.filter((i) => i !== undefined)
|
|
178
|
-
|
|
179
|
-
const tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes)
|
|
180
|
-
|
|
181
|
-
const typeAlias = t.tsTypeAliasDeclaration(t.identifier(identifier), null, tsType)
|
|
182
|
-
const code = generateCode(t.exportNamedDeclaration(typeAlias))
|
|
183
|
-
schemaIdentifiers.add(identifier)
|
|
184
|
-
schemaCode += code
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
const allSchemaTypesDeclaration = generateCode(
|
|
189
|
-
t.exportNamedDeclaration(
|
|
190
|
-
t.tsTypeAliasDeclaration(
|
|
191
|
-
AllSchemaTypes,
|
|
192
|
-
null,
|
|
193
|
-
t.tsUnionType(
|
|
194
|
-
Array.from(schemaIdentifiers).map((identifier) =>
|
|
195
|
-
t.tsTypeReference(t.identifier(identifier)),
|
|
196
|
-
),
|
|
197
|
-
),
|
|
198
|
-
),
|
|
199
|
-
),
|
|
200
|
-
)
|
|
201
|
-
|
|
202
|
-
schemaCode += allSchemaTypesDeclaration
|
|
203
|
-
|
|
204
|
-
if (augmentGroqModule) {
|
|
205
|
-
const sanitySchemasProperties = schemas.map(({dataset, projectId}) =>
|
|
206
|
-
t.tsPropertySignature(
|
|
207
|
-
t.stringLiteral(`${projectId}:${dataset}`),
|
|
208
|
-
t.tsTypeAnnotation(
|
|
209
|
-
t.tsTypeReference(
|
|
210
|
-
ExtractDataset,
|
|
211
|
-
t.tsTypeParameterInstantiation([
|
|
212
|
-
t.tsTypeReference(AllSchemaTypes),
|
|
213
|
-
t.tsLiteralType(t.stringLiteral(dataset)),
|
|
214
|
-
t.tsLiteralType(t.stringLiteral(projectId)),
|
|
215
|
-
]),
|
|
216
|
-
),
|
|
217
|
-
),
|
|
218
|
-
),
|
|
219
|
-
)
|
|
220
|
-
|
|
221
|
-
const sanitySchemasDeclaration = generateCode(
|
|
222
|
-
t.declareModule(
|
|
223
|
-
t.stringLiteral('groq'),
|
|
224
|
-
t.blockStatement([
|
|
225
|
-
t.tsInterfaceDeclaration(
|
|
226
|
-
SanitySchemas,
|
|
227
|
-
null,
|
|
228
|
-
[],
|
|
229
|
-
t.tsInterfaceBody(sanitySchemasProperties),
|
|
230
|
-
),
|
|
231
|
-
]),
|
|
232
|
-
),
|
|
233
|
-
)
|
|
234
|
-
schemaCode += sanitySchemasDeclaration
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
resolveGeneratedSchema({
|
|
238
|
-
code: schemaCode,
|
|
239
|
-
schemas: schemas.map(({schema, ...rest}) => ({
|
|
240
|
-
...rest,
|
|
241
|
-
typeCount: schema.length,
|
|
242
|
-
})),
|
|
243
|
-
})
|
|
244
|
-
|
|
245
|
-
const queryIdentifiers = new Map<string, t.Identifier[]>()
|
|
246
|
-
const projectionIdentifiers = new Map<string, t.Identifier[]>()
|
|
247
|
-
const totalStats: TypeEvaluationStats = {
|
|
248
|
-
totalTypeNodes: 0,
|
|
249
|
-
unknownTypeCount: 0,
|
|
250
|
-
emptyUnionCount: 0,
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
for await (const input of queriesByFile) {
|
|
254
|
-
try {
|
|
255
|
-
if (input.type === 'error') throw input.error
|
|
256
|
-
|
|
257
|
-
const results: GeneratedQuery[] = []
|
|
258
|
-
for (const query of input.queries) {
|
|
259
|
-
const desiredName = SchemaTypeGenerator.sanitizeIdentifier(
|
|
260
|
-
query.type === 'projection' ? `${query.name}ProjectionResult` : `${query.name}Result`,
|
|
261
|
-
)
|
|
262
|
-
|
|
263
|
-
let resultingName = desiredName
|
|
264
|
-
let index = 2
|
|
265
|
-
while (globalIdentifiers.has(resultingName)) {
|
|
266
|
-
resultingName = `${desiredName}_${index}`
|
|
267
|
-
index++
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
const identifier = t.identifier(resultingName)
|
|
271
|
-
let identifiers =
|
|
272
|
-
query.type === 'projection'
|
|
273
|
-
? projectionIdentifiers.get(query.result)
|
|
274
|
-
: queryIdentifiers.get(query.result)
|
|
275
|
-
|
|
276
|
-
if (!identifiers) {
|
|
277
|
-
identifiers = []
|
|
278
|
-
if (query.type === 'projection') {
|
|
279
|
-
projectionIdentifiers.set(query.result, identifiers)
|
|
280
|
-
} else {
|
|
281
|
-
queryIdentifiers.set(query.result, identifiers)
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
identifiers.push(identifier)
|
|
285
|
-
|
|
286
|
-
const evaluationResults = schemaGenerators.map((i) => {
|
|
287
|
-
const result =
|
|
288
|
-
query.type === 'projection'
|
|
289
|
-
? i.evaluateProjection(query.result)
|
|
290
|
-
: i.evaluateQuery(query.result)
|
|
291
|
-
|
|
292
|
-
return result
|
|
293
|
-
})
|
|
294
|
-
|
|
295
|
-
const aggregatedQueryStats = evaluationResults.reduce<TypeEvaluationStats>(
|
|
296
|
-
(acc, {stats}) => ({
|
|
297
|
-
totalTypeNodes: acc.totalTypeNodes + stats.totalTypeNodes,
|
|
298
|
-
unknownTypeCount: acc.unknownTypeCount + stats.unknownTypeCount,
|
|
299
|
-
emptyUnionCount: acc.emptyUnionCount + stats.emptyUnionCount,
|
|
300
|
-
}),
|
|
301
|
-
{totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 0},
|
|
302
|
-
)
|
|
303
|
-
|
|
304
|
-
totalStats.totalTypeNodes += aggregatedQueryStats.totalTypeNodes
|
|
305
|
-
totalStats.unknownTypeCount += aggregatedQueryStats.unknownTypeCount
|
|
306
|
-
totalStats.emptyUnionCount += aggregatedQueryStats.emptyUnionCount
|
|
307
|
-
|
|
308
|
-
const tsTypes = evaluationResults.map(({tsType}, resultIndex) => {
|
|
309
|
-
if (schemas.length === 1) return tsType
|
|
310
|
-
return scopeByDataset(tsType, schemaGenerators[resultIndex])
|
|
311
|
-
})
|
|
312
|
-
|
|
313
|
-
const tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes)
|
|
314
|
-
const typeAlias = t.tsTypeAliasDeclaration(identifier, null, tsType)
|
|
315
|
-
|
|
316
|
-
const code = generateCode(
|
|
317
|
-
t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [
|
|
318
|
-
{type: 'CommentLine', value: ` Source: ${input.filename}`},
|
|
319
|
-
{type: 'CommentLine', value: ` Variable: ${query.name}`},
|
|
320
|
-
{
|
|
321
|
-
type: 'CommentLine',
|
|
322
|
-
value: ` ${query.type === 'projection' ? 'Projection' : 'Query'}: ${query.result.replace(/(\r\n|\n|\r)/gm, '').trim()}`,
|
|
323
|
-
},
|
|
324
|
-
]),
|
|
325
|
-
)
|
|
326
|
-
|
|
327
|
-
results.push({
|
|
328
|
-
name: query.name,
|
|
329
|
-
query: query.result,
|
|
330
|
-
type: query.type,
|
|
331
|
-
code,
|
|
332
|
-
stats: aggregatedQueryStats,
|
|
333
|
-
})
|
|
334
|
-
}
|
|
335
|
-
generatedQueries.enqueue({filename: input.filename, results})
|
|
336
|
-
} catch (error) {
|
|
337
|
-
generatedQueries.enqueue({filename: input.filename, results: [], error})
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
generatedQueries.finish()
|
|
342
|
-
|
|
343
|
-
let typemapCode = ''
|
|
344
|
-
const clientModuleBlockStatement: t.Statement[] = []
|
|
345
|
-
const groqModuleBlockStatement: t.Statement[] = []
|
|
346
|
-
|
|
347
|
-
// Only generate SanityQueries if there are query results
|
|
348
|
-
if (queryIdentifiers.size > 0) {
|
|
349
|
-
const sanityQueriesInterfaceDeclaration = t.tsInterfaceDeclaration(
|
|
350
|
-
SanityQueries,
|
|
351
|
-
null,
|
|
352
|
-
[],
|
|
353
|
-
t.tsInterfaceBody(
|
|
354
|
-
Array.from(queryIdentifiers).map(([query, identifiers]) =>
|
|
355
|
-
t.tsPropertySignature(
|
|
356
|
-
t.stringLiteral(query),
|
|
357
|
-
t.tsTypeAnnotation(
|
|
358
|
-
identifiers.length === 1
|
|
359
|
-
? t.tsTypeReference(identifiers[0])
|
|
360
|
-
: t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i))),
|
|
361
|
-
),
|
|
362
|
-
),
|
|
363
|
-
),
|
|
364
|
-
),
|
|
365
|
-
)
|
|
366
|
-
// Add to both module declarations if needed
|
|
367
|
-
clientModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)
|
|
368
|
-
groqModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
// Only generate SanityProjections if there are projection results
|
|
372
|
-
if (projectionIdentifiers.size > 0) {
|
|
373
|
-
const sanityProjectionsInterfaceDeclaration = t.tsInterfaceDeclaration(
|
|
374
|
-
SanityProjections,
|
|
375
|
-
null,
|
|
376
|
-
[],
|
|
377
|
-
t.tsInterfaceBody(
|
|
378
|
-
Array.from(projectionIdentifiers).map(([projection, identifiers]) =>
|
|
379
|
-
t.tsPropertySignature(
|
|
380
|
-
t.stringLiteral(projection),
|
|
381
|
-
t.tsTypeAnnotation(
|
|
382
|
-
identifiers.length === 1
|
|
383
|
-
? t.tsTypeReference(identifiers[0])
|
|
384
|
-
: t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i))),
|
|
385
|
-
),
|
|
386
|
-
),
|
|
387
|
-
),
|
|
388
|
-
),
|
|
389
|
-
)
|
|
390
|
-
// Add only to groq module declaration
|
|
391
|
-
groqModuleBlockStatement.push(sanityProjectionsInterfaceDeclaration)
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
if (overloadClientMethods && clientModuleBlockStatement.length > 0) {
|
|
395
|
-
const clientModuleDeclaration = t.declareModule(
|
|
396
|
-
t.stringLiteral('@sanity/client'),
|
|
397
|
-
t.blockStatement(clientModuleBlockStatement),
|
|
398
|
-
)
|
|
399
|
-
typemapCode += generateCode(clientModuleDeclaration)
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
if (augmentGroqModule && groqModuleBlockStatement.length > 0) {
|
|
403
|
-
const groqModuleDeclaration = t.declareModule(
|
|
404
|
-
t.stringLiteral('groq'),
|
|
405
|
-
t.blockStatement(groqModuleBlockStatement),
|
|
406
|
-
)
|
|
407
|
-
typemapCode += generateCode(groqModuleDeclaration)
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
resolveGeneratedTypemap({
|
|
411
|
-
code: typemapCode,
|
|
412
|
-
stats: totalStats,
|
|
413
|
-
})
|
|
414
|
-
})().catch((err) => {
|
|
415
|
-
generatedQueries.throwError(err)
|
|
416
|
-
rejectGeneratedSchema(err)
|
|
417
|
-
rejectGeneratedTypemap(err)
|
|
418
|
-
})
|
|
419
|
-
|
|
420
|
-
return {
|
|
421
|
-
generatedSchema: () => generatedSchema,
|
|
422
|
-
generatedQueries: () => generatedQueries,
|
|
423
|
-
generatedTypemap: () => generatedTypemap,
|
|
424
|
-
}
|
|
425
|
-
}
|