@sanity/codegen 3.88.1-typegen-experimental.0 → 3.88.1
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 +85 -282
- package/lib/index.d.ts +85 -282
- package/lib/index.js +172 -537
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +173 -538
- package/lib/index.mjs.map +1 -1
- package/package.json +17 -15
- package/src/_exports/index.ts +3 -14
- package/src/readConfig.ts +23 -71
- package/src/readSchema.ts +1 -0
- package/src/typescript/expressionResolvers.ts +3 -4
- package/src/typescript/findQueriesInPath.ts +2 -9
- package/src/typescript/findQueriesInSource.ts +6 -22
- package/src/typescript/typeGenerator.ts +306 -445
- package/src/typescript/asyncQueue.ts +0 -100
- package/src/typescript/schemaTypeGenerator.ts +0 -381
|
@@ -1,513 +1,374 @@
|
|
|
1
|
-
/* eslint-disable max-nested-callbacks */
|
|
2
1
|
import {CodeGenerator} from '@babel/generator'
|
|
3
2
|
import * as t from '@babel/types'
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
name: string
|
|
21
|
-
id: t.Identifier
|
|
3
|
+
import {
|
|
4
|
+
type ArrayTypeNode,
|
|
5
|
+
type DocumentSchemaType,
|
|
6
|
+
type InlineTypeNode,
|
|
7
|
+
type ObjectAttribute,
|
|
8
|
+
type ObjectTypeNode,
|
|
9
|
+
type SchemaType,
|
|
10
|
+
type TypeDeclarationSchemaType,
|
|
11
|
+
type TypeNode,
|
|
12
|
+
type UnionTypeNode,
|
|
13
|
+
} from 'groq-js'
|
|
14
|
+
|
|
15
|
+
const REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'
|
|
16
|
+
const ALL_SCHEMA_TYPES = 'AllSanitySchemaTypes'
|
|
17
|
+
|
|
18
|
+
type QueryWithTypeNode = {
|
|
22
19
|
query: string
|
|
23
|
-
|
|
24
|
-
type: 'query' | 'projection'
|
|
25
|
-
stats: TypeEvaluationStats
|
|
26
|
-
}
|
|
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
|
-
|
|
40
|
-
/**
|
|
41
|
-
* @internal
|
|
42
|
-
*/
|
|
43
|
-
export interface TypeGeneratorOptions {
|
|
44
|
-
schemas: {schema: SchemaType; schemaId: string; filename?: string}[]
|
|
45
|
-
queriesByFile?: AsyncIterable<QueryExtractionResult>
|
|
46
|
-
augmentGroqModule?: boolean
|
|
47
|
-
overloadClientMethods?: boolean
|
|
20
|
+
typeNode: TypeNode
|
|
48
21
|
}
|
|
49
22
|
|
|
50
23
|
/**
|
|
24
|
+
* A class used to generate TypeScript types from a given schema
|
|
51
25
|
* @internal
|
|
26
|
+
* @beta
|
|
52
27
|
*/
|
|
53
28
|
export class TypeGenerator {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
private
|
|
60
|
-
|
|
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
|
-
}
|
|
29
|
+
// Simple set to keep track of generated type names, to avoid conflicts
|
|
30
|
+
private generatedTypeName: Set<string> = new Set()
|
|
31
|
+
// Map between type names and their generated type names, used to resolve the correct generated type name
|
|
32
|
+
private typeNameMap: Map<string, string> = new Map()
|
|
33
|
+
// Map between type nodes and their generated type names, used for query mapping
|
|
34
|
+
private typeNodeNameMap: Map<TypeNode | DocumentSchemaType | TypeDeclarationSchemaType, string> =
|
|
35
|
+
new Map()
|
|
91
36
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
}
|
|
37
|
+
private readonly schema: SchemaType
|
|
38
|
+
|
|
39
|
+
constructor(schema: SchemaType) {
|
|
40
|
+
this.schema = schema
|
|
41
|
+
|
|
42
|
+
this.schema.forEach((s) => {
|
|
43
|
+
this.getTypeName(s.name, s)
|
|
44
|
+
})
|
|
112
45
|
}
|
|
113
46
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
47
|
+
/**
|
|
48
|
+
* Generate TypeScript types for the given schema
|
|
49
|
+
* @returns string
|
|
50
|
+
* @internal
|
|
51
|
+
* @beta
|
|
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}`)
|
|
119
63
|
}
|
|
120
64
|
|
|
121
|
-
|
|
122
|
-
|
|
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
|
-
}
|
|
65
|
+
schemaNames.add(schemaName)
|
|
66
|
+
const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral)
|
|
137
67
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
this.queryResultsQueue.enqueue({type: 'error', filename: result.filename, error})
|
|
141
|
-
}
|
|
142
|
-
}
|
|
68
|
+
typeDeclarations.push(t.exportNamedDeclaration(typeAlias))
|
|
69
|
+
})
|
|
143
70
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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
|
-
),
|
|
71
|
+
typeDeclarations.push(
|
|
72
|
+
t.exportNamedDeclaration(
|
|
73
|
+
t.tsTypeAliasDeclaration(
|
|
74
|
+
t.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),
|
|
75
|
+
null,
|
|
76
|
+
t.tsUnionType(
|
|
77
|
+
[...schemaNames].map((typeName) => t.tsTypeReference(t.identifier(typeName))),
|
|
166
78
|
),
|
|
167
79
|
),
|
|
168
|
-
)
|
|
169
|
-
|
|
170
|
-
clientModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)
|
|
171
|
-
groqModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)
|
|
172
|
-
}
|
|
80
|
+
),
|
|
81
|
+
)
|
|
173
82
|
|
|
174
|
-
//
|
|
175
|
-
|
|
176
|
-
|
|
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
|
-
)
|
|
83
|
+
// Generate TypeScript code from the AST nodes
|
|
84
|
+
return typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join('\n\n')
|
|
85
|
+
}
|
|
193
86
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
87
|
+
/**
|
|
88
|
+
* Takes a identifier and a type node and generates a type alias for the type node.
|
|
89
|
+
* @param identifierName - The name of the type to generated
|
|
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
|
+
}
|
|
197
103
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
t.blockStatement(clientModuleBlockStatement),
|
|
202
|
-
)
|
|
203
|
-
augmentedQueryResultsCode += generateCode(clientModuleDeclaration)
|
|
204
|
-
}
|
|
104
|
+
static generateKnownTypes(): string {
|
|
105
|
+
const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword())
|
|
106
|
+
typeOperator.operator = 'unique'
|
|
205
107
|
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
t.stringLiteral('groq'),
|
|
209
|
-
t.blockStatement(groqModuleBlockStatement),
|
|
210
|
-
)
|
|
211
|
-
augmentedQueryResultsCode += generateCode(groqModuleDeclaration)
|
|
212
|
-
}
|
|
108
|
+
const identifier = t.identifier(REFERENCE_SYMBOL_NAME)
|
|
109
|
+
identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator)
|
|
213
110
|
|
|
214
|
-
|
|
111
|
+
const decleration = t.variableDeclaration('const', [t.variableDeclarator(identifier)])
|
|
112
|
+
decleration.declare = true
|
|
113
|
+
return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()
|
|
215
114
|
}
|
|
216
115
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
116
|
+
/**
|
|
117
|
+
* Takes a list of queries from the codebase and generates a type declaration
|
|
118
|
+
* for SanityClient to consume.
|
|
119
|
+
*
|
|
120
|
+
* Note: only types that have previously been generated with `generateTypeNodeTypes`
|
|
121
|
+
* will be included in the query map.
|
|
122
|
+
*
|
|
123
|
+
* @param queries - A list of queries to generate a type declaration for
|
|
124
|
+
* @returns
|
|
125
|
+
* @internal
|
|
126
|
+
* @beta
|
|
127
|
+
*/
|
|
128
|
+
generateQueryMap(queries: QueryWithTypeNode[]): string {
|
|
129
|
+
const typesByQuerystring: {[query: string]: string[]} = {}
|
|
130
|
+
|
|
131
|
+
for (const query of queries) {
|
|
132
|
+
const name = this.typeNodeNameMap.get(query.typeNode)
|
|
133
|
+
if (!name) {
|
|
134
|
+
continue
|
|
234
135
|
}
|
|
235
|
-
}
|
|
236
136
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
})
|
|
241
|
-
|
|
242
|
-
const tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes)
|
|
137
|
+
typesByQuerystring[query.query] ??= []
|
|
138
|
+
typesByQuerystring[query.query].push(name)
|
|
139
|
+
}
|
|
243
140
|
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
[
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
141
|
+
const queryReturnInterface = t.tsInterfaceDeclaration(
|
|
142
|
+
t.identifier('SanityQueries'),
|
|
143
|
+
null,
|
|
144
|
+
[],
|
|
145
|
+
t.tsInterfaceBody(
|
|
146
|
+
Object.entries(typesByQuerystring).map(([query, types]) => {
|
|
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
|
+
),
|
|
255
155
|
)
|
|
256
156
|
|
|
257
|
-
const
|
|
258
|
-
|
|
157
|
+
const declareModule = t.declareModule(
|
|
158
|
+
t.stringLiteral('@sanity/client'),
|
|
159
|
+
t.blockStatement([queryReturnInterface]),
|
|
160
|
+
)
|
|
259
161
|
|
|
260
|
-
|
|
162
|
+
const clientImport = t.importDeclaration([], t.stringLiteral('@sanity/client'))
|
|
261
163
|
|
|
262
|
-
|
|
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
|
-
}
|
|
164
|
+
return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim()
|
|
282
165
|
}
|
|
283
166
|
|
|
284
|
-
|
|
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(
|
|
285
173
|
name: string,
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
let
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
index++
|
|
174
|
+
typeNode?: TypeNode | DocumentSchemaType | TypeDeclarationSchemaType,
|
|
175
|
+
): string {
|
|
176
|
+
const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name))
|
|
177
|
+
|
|
178
|
+
let generatedName = desiredName
|
|
179
|
+
let i = 2
|
|
180
|
+
while (this.generatedTypeName.has(generatedName)) {
|
|
181
|
+
// add _ and a index and increment that index until we find a name that is not in the map
|
|
182
|
+
generatedName = `${desiredName}_${i++}`
|
|
296
183
|
}
|
|
297
|
-
|
|
298
|
-
this.
|
|
299
|
-
|
|
300
|
-
|
|
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)
|
|
184
|
+
this.generatedTypeName.add(generatedName)
|
|
185
|
+
this.typeNameMap.set(name, generatedName)
|
|
186
|
+
if (typeNode) {
|
|
187
|
+
this.typeNodeNameMap.set(typeNode, generatedName)
|
|
307
188
|
}
|
|
308
189
|
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
return {id, code}
|
|
190
|
+
return generatedName
|
|
312
191
|
}
|
|
313
192
|
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
193
|
+
private getTypeNodeType(
|
|
194
|
+
typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,
|
|
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
|
+
}
|
|
324
239
|
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
240
|
+
default:
|
|
241
|
+
// @ts-expect-error This should never happen
|
|
242
|
+
throw new Error(`Type "${typeNode.type}" not found in schema`)
|
|
328
243
|
}
|
|
244
|
+
}
|
|
329
245
|
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
code += generateCode(
|
|
337
|
-
t.exportNamedDeclaration(
|
|
338
|
-
Object.assign(
|
|
339
|
-
t.variableDeclaration('const', [
|
|
340
|
-
t.variableDeclarator(SchemaTypeGenerator.InternalReferenceSymbol),
|
|
341
|
-
]),
|
|
342
|
-
{declare: true},
|
|
343
|
-
),
|
|
344
|
-
),
|
|
246
|
+
// Helper function used to generate TS types for array type nodes.
|
|
247
|
+
private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference {
|
|
248
|
+
const typeNodes = this.getTypeNodeType(typeNode.of)
|
|
249
|
+
const arrayType = t.tsTypeReference(
|
|
250
|
+
t.identifier('Array'),
|
|
251
|
+
t.tsTypeParameterInstantiation([typeNodes]),
|
|
345
252
|
)
|
|
346
253
|
|
|
347
|
-
return
|
|
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
|
|
254
|
+
return arrayType
|
|
255
|
+
}
|
|
369
256
|
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
257
|
+
// Helper function used to generate TS types for object properties.
|
|
258
|
+
private generateObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {
|
|
259
|
+
const type = this.getTypeNodeType(attribute.value)
|
|
260
|
+
const propertySignature = t.tsPropertySignature(
|
|
261
|
+
t.identifier(sanitizeIdentifier(key)),
|
|
262
|
+
t.tsTypeAnnotation(type),
|
|
263
|
+
)
|
|
264
|
+
propertySignature.optional = attribute.optional
|
|
374
265
|
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
types.length === 1 ? types[0].tsType : t.tsUnionType(types.map((i) => i.tsType))
|
|
378
|
-
const {id, code} = this.generateAndRegisterExportedTypeAlias(identifier, tsType)
|
|
266
|
+
return propertySignature
|
|
267
|
+
}
|
|
379
268
|
|
|
380
|
-
|
|
381
|
-
|
|
269
|
+
// Helper function used to generate TS types for object type nodes.
|
|
270
|
+
private generateObjectTsType(typeNode: ObjectTypeNode): t.TSType {
|
|
271
|
+
const props: t.TSPropertySignature[] = []
|
|
272
|
+
Object.entries(typeNode.attributes).forEach(([key, attribute]) => {
|
|
273
|
+
props.push(this.generateObjectProperty(key, attribute))
|
|
382
274
|
})
|
|
383
|
-
|
|
275
|
+
const rest = typeNode.rest
|
|
276
|
+
if (rest !== undefined) {
|
|
277
|
+
switch (rest.type) {
|
|
278
|
+
case 'unknown': {
|
|
279
|
+
return t.tsUnknownKeyword()
|
|
280
|
+
}
|
|
281
|
+
case 'object': {
|
|
282
|
+
Object.entries(rest.attributes).forEach(([key, attribute]) => {
|
|
283
|
+
props.push(this.generateObjectProperty(key, attribute))
|
|
284
|
+
})
|
|
285
|
+
break
|
|
286
|
+
}
|
|
287
|
+
case 'inline': {
|
|
288
|
+
const resolved = this.generateInlineTsType(rest)
|
|
384
289
|
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
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
|
|
290
|
+
// if an object's rest type is unknown, we can't generate a type literal for it
|
|
291
|
+
// so we return unknown
|
|
292
|
+
if (t.isTSUnknownKeyword(resolved)) {
|
|
293
|
+
return resolved
|
|
294
|
+
}
|
|
295
|
+
return t.tsIntersectionType([t.tsTypeLiteral(props), resolved])
|
|
296
|
+
}
|
|
297
|
+
default: {
|
|
298
|
+
// @ts-expect-error This should never happen
|
|
299
|
+
throw new Error(`Type "${rest.type}" not found in schema`)
|
|
300
|
+
}
|
|
407
301
|
}
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
([identifierName, schemaCount]) => {
|
|
414
|
-
const schemaTypeReferencer = t.tsTypeReference(t.identifier(identifierName))
|
|
415
|
-
if (schemaCount > 1) return addPickSchema(schemaTypeReferencer, schemaId)
|
|
416
|
-
return schemaTypeReferencer
|
|
417
|
-
},
|
|
302
|
+
}
|
|
303
|
+
if (typeNode.dereferencesTo !== undefined) {
|
|
304
|
+
const derefType = t.tsPropertySignature(
|
|
305
|
+
t.identifier(REFERENCE_SYMBOL_NAME),
|
|
306
|
+
t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),
|
|
418
307
|
)
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
308
|
+
derefType.computed = true
|
|
309
|
+
derefType.optional = true
|
|
310
|
+
props.push(derefType)
|
|
311
|
+
}
|
|
312
|
+
return t.tsTypeLiteral(props)
|
|
313
|
+
}
|
|
422
314
|
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
315
|
+
private generateInlineTsType(typeNode: InlineTypeNode): t.TSType {
|
|
316
|
+
const referencedTypeNode = this.schema.find((schema) => schema.name === typeNode.name)
|
|
317
|
+
// Check if we have a schema reference for the type node
|
|
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))
|
|
426
323
|
}
|
|
427
|
-
comments.push({type: 'CommentLine', value: ` Schema ID: ${schemaId}`})
|
|
428
324
|
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
getAugmentedSchemasDeclarations = computeOnce(() => {
|
|
440
|
-
if (!this.augmentGroqModule) return {code: ''}
|
|
441
|
-
const schemaDeclarations = this.getSchemaDeclarations()
|
|
442
|
-
|
|
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
|
-
)
|
|
325
|
+
// Not found in schema, return unknown type
|
|
326
|
+
const missing = t.tsUnknownKeyword()
|
|
327
|
+
missing.trailingComments = [
|
|
328
|
+
{
|
|
329
|
+
type: 'CommentLine',
|
|
330
|
+
value: ` Unable to locate the referenced type "${typeNode.name}" in schema`,
|
|
331
|
+
},
|
|
332
|
+
]
|
|
333
|
+
return missing
|
|
334
|
+
}
|
|
461
335
|
|
|
462
|
-
|
|
463
|
-
})
|
|
336
|
+
const generatedName = this.typeNameMap.get(referencedTypeNode.name)
|
|
464
337
|
|
|
465
|
-
|
|
338
|
+
if (generatedName) {
|
|
339
|
+
return t.tsTypeReference(t.identifier(generatedName))
|
|
340
|
+
}
|
|
466
341
|
|
|
467
|
-
|
|
468
|
-
|
|
342
|
+
return t.tsUnknownKeyword()
|
|
343
|
+
}
|
|
469
344
|
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
345
|
+
// Helper function used to generate TS types for union type nodes.
|
|
346
|
+
private generateUnionTsType(typeNode: UnionTypeNode): t.TSType {
|
|
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
|
+
}
|
|
473
353
|
|
|
474
|
-
|
|
475
|
-
const ref = {current: undefined as TReturn | undefined, computed: false}
|
|
354
|
+
const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))
|
|
476
355
|
|
|
477
|
-
|
|
478
|
-
if (ref.computed) return ref.current as TReturn
|
|
479
|
-
ref.current = fn.call(this)
|
|
480
|
-
ref.computed = true
|
|
481
|
-
return ref.current
|
|
356
|
+
return t.tsUnionType(typeNodes)
|
|
482
357
|
}
|
|
483
|
-
}
|
|
484
358
|
|
|
485
|
-
function
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
}
|
|
359
|
+
// Helper function used to generate TS types for document type nodes.
|
|
360
|
+
private generateDocumentType(document: DocumentSchemaType): t.TSType {
|
|
361
|
+
const props = Object.entries(document.attributes).map(([key, node]) =>
|
|
362
|
+
this.generateObjectProperty(key, node),
|
|
363
|
+
)
|
|
491
364
|
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
PickSchema,
|
|
495
|
-
t.tsTypeParameterInstantiation([tsType, t.tsLiteralType(t.stringLiteral(schemaId))]),
|
|
496
|
-
)
|
|
365
|
+
return t.tsTypeLiteral(props)
|
|
366
|
+
}
|
|
497
367
|
}
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
return `${new CodeGenerator(node).generate().code.trim()}\n\n`
|
|
368
|
+
function uppercaseFirstLetter(input: string): string {
|
|
369
|
+
return input.charAt(0).toUpperCase() + input.slice(1)
|
|
501
370
|
}
|
|
502
371
|
|
|
503
|
-
|
|
504
|
-
|
|
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}
|
|
372
|
+
function sanitizeIdentifier(input: string): string {
|
|
373
|
+
return `${input.replace(/^\d/, '_').replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`
|
|
513
374
|
}
|