-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathindex.ts
More file actions
709 lines (630 loc) · 22 KB
/
index.ts
File metadata and controls
709 lines (630 loc) · 22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
import { iterableFirst, mapFromObject, setMap } from "collection-utils";
import { Kind } from "graphql";
import * as graphql from "graphql/language";
import type {
DirectiveNode,
DocumentNode,
FieldNode,
FragmentDefinitionNode,
OperationDefinitionNode,
SelectionNode,
SelectionSetNode,
} from "graphql/language/ast";
import {
type ClassProperty,
type Input,
type RunContext,
StringTypes,
type TypeAttributes,
type TypeBuilder,
TypeNames,
type TypeRef,
UnionType,
assertNever,
derefTypeRef,
emptyTypeAttributes,
makeNamesTypeAttributes,
messageAssert,
namesTypeAttributeKind,
panic,
removeNullFromUnion,
} from "quicktype-core";
import { type GraphQLSchema, TypeKind } from "./GraphQLSchema";
interface GQLType {
description?: string;
enumValues?: EnumValue[];
fields?: Field[];
inputFields?: InputValue[];
interfaces?: GQLType[];
kind: TypeKind;
name?: string;
ofType?: GQLType;
possibleTypes?: GQLType[];
}
interface EnumValue {
description?: string;
name: string;
}
interface Field {
args: InputValue[];
description?: string;
name: string;
type: GQLType;
}
interface InputValue {
defaultValue?: string;
description?: string;
name: string;
type: GQLType;
}
function getField(t: GQLType, name: string): Field {
if (!t.fields)
return panic(
`Required field ${name} in type ${t.name} which doesn't have fields.`,
);
for (const f of t.fields) {
if (f.name === name) {
return f;
}
}
return panic(`Required field ${name} not defined on type ${t.name}.`);
}
function makeNames(
name: string,
fieldName: string | null,
containingTypeName: string | null,
): TypeAttributes {
const alternatives: string[] = [];
if (fieldName) alternatives.push(fieldName);
if (containingTypeName) alternatives.push(`${containingTypeName}_${name}`);
if (fieldName && containingTypeName)
alternatives.push(`${containingTypeName}_${fieldName}`);
return namesTypeAttributeKind.makeAttributes(
TypeNames.make(new Set([name]), new Set(alternatives), false),
);
}
function makeNullable(
builder: TypeBuilder,
tref: TypeRef,
name: string,
fieldName: string | null,
containingTypeName: string,
): TypeRef {
const typeNames = makeNames(name, fieldName, containingTypeName);
const t = derefTypeRef(tref, builder.typeGraph);
if (!(t instanceof UnionType)) {
return builder.getUnionType(
typeNames,
new Set([tref, builder.getPrimitiveType("null")]),
);
}
const [maybeNull, nonNulls] = removeNullFromUnion(t);
if (maybeNull) return tref;
return builder.getUnionType(
typeNames,
setMap(nonNulls, (nn) => nn.typeRef).add(
builder.getPrimitiveType("null"),
),
);
}
// This is really not the way to do this, but it's easy and works. By default
// all types in GraphQL are nullable, and non-nullability must be specially marked,
// so we just construct a nullable type first, and then remove the null from the
// union if the type is modified to be non-nullable. That means that the union
// (and the null) might be left unreachable in the graph. Provenance checking
// won't work in this case, which is why it's disabled in testing for GraphQL.
function removeNull(builder: TypeBuilder, tref: TypeRef): TypeRef {
const t = derefTypeRef(tref, builder.typeGraph);
if (!(t instanceof UnionType)) {
return tref;
}
const nonNulls = removeNullFromUnion(t)[1];
const first = iterableFirst(nonNulls);
if (first) {
if (nonNulls.size === 1) return first.typeRef;
return builder.getUnionType(
t.getAttributes(),
setMap(nonNulls, (nn) => nn.typeRef),
);
}
return panic("Trying to remove null results in empty union.");
}
function makeScalar(builder: TypeBuilder, ft: GQLType): TypeRef {
switch (ft.name) {
case "Boolean":
return builder.getPrimitiveType("bool");
case "Int":
return builder.getPrimitiveType("integer");
case "Float":
return builder.getPrimitiveType("double");
default:
// FIXME: support ID specifically?
return builder.getStringType(
emptyTypeAttributes,
StringTypes.unrestricted,
);
}
}
function hasOptionalDirectives(directives?: readonly DirectiveNode[]): boolean {
if (!directives) return false;
for (const d of directives) {
const name = d.name.value;
if (name === "include" || name === "skip") return true;
}
return false;
}
interface Selection {
inType: GQLType;
optional: boolean;
selection: SelectionNode;
}
function expandSelectionSet(
selectionSet: SelectionSetNode,
inType: GQLType,
optional: boolean,
): Selection[] {
return [...selectionSet.selections]
.reverse()
.map((s) => ({
selection: s,
inType,
optional: optional || hasOptionalDirectives(s.directives),
}));
}
interface GQLSchema {
readonly mutationType?: GQLType;
readonly queryType: GQLType;
readonly types: { [name: string]: GQLType };
}
class GQLQuery {
private readonly _schema: GQLSchema;
private readonly _fragments: { [name: string]: FragmentDefinitionNode };
public readonly queries: readonly OperationDefinitionNode[];
public constructor(schema: GQLSchema, queryString: string) {
this._schema = schema;
this._fragments = {};
const queryDocument = graphql.parse(queryString) as DocumentNode;
const queries: OperationDefinitionNode[] = [];
for (const def of queryDocument.definitions) {
if (def.kind === "OperationDefinition") {
if (def.operation === "query" || def.operation === "mutation") {
queries.push(def);
}
} else if (def.kind === "FragmentDefinition") {
this._fragments[def.name.value] = def;
}
}
messageAssert(queries.length >= 1, "GraphQLNoQueriesDefined", {});
this.queries = queries;
}
private readonly makeIRTypeFromFieldNode = (
builder: TypeBuilder,
fieldNode: FieldNode,
fieldType: GQLType,
containingTypeName: string,
): TypeRef => {
let optional = hasOptionalDirectives(fieldNode.directives);
let result: TypeRef;
switch (fieldType.kind) {
case TypeKind.SCALAR:
result = makeScalar(builder, fieldType);
optional = true;
break;
case TypeKind.OBJECT:
case TypeKind.INTERFACE:
case TypeKind.UNION:
if (!fieldNode.selectionSet) {
return panic("No selection set on object or interface");
}
return makeNullable(
builder,
this.makeIRTypeFromSelectionSet(
builder,
fieldNode.selectionSet,
fieldType,
fieldNode.name.value,
containingTypeName,
),
fieldNode.name.value,
null,
containingTypeName,
);
case TypeKind.ENUM:
if (!fieldType.enumValues) {
return panic("Enum type doesn't have values");
}
const values = fieldType.enumValues.map((ev) => ev.name);
let name: string;
let fieldName: string | null;
if (fieldType.name) {
name = fieldType.name;
fieldName = fieldNode.name.value;
} else {
name = fieldNode.name.value;
fieldName = null;
}
optional = true;
result = builder.getEnumType(
makeNames(name, fieldName, containingTypeName),
new Set(values),
);
break;
case TypeKind.INPUT_OBJECT:
// FIXME: Support input objects
return panic("Input objects not supported");
case TypeKind.LIST:
if (!fieldType.ofType) {
return panic("No type for list");
}
optional = true;
result = builder.getArrayType(
emptyTypeAttributes,
this.makeIRTypeFromFieldNode(
builder,
fieldNode,
fieldType.ofType,
containingTypeName,
),
);
break;
case TypeKind.NON_NULL:
if (!fieldType.ofType) {
return panic("No type for non-null");
}
result = removeNull(
builder,
this.makeIRTypeFromFieldNode(
builder,
fieldNode,
fieldType.ofType,
containingTypeName,
),
);
break;
default:
return assertNever(fieldType.kind);
}
if (optional) {
result = makeNullable(
builder,
result,
fieldNode.name.value,
null,
containingTypeName,
);
}
return result;
};
private readonly getFragment = (name: string): FragmentDefinitionNode => {
const fragment = this._fragments[name];
if (!fragment) return panic(`Fragment ${name} is not defined.`);
return fragment;
};
private readonly makeIRTypeFromSelectionSet = (
builder: TypeBuilder,
selectionSet: SelectionSetNode,
gqlType: GQLType,
containingFieldName: string | null,
containingTypeName: string | null,
overrideName?: string,
): TypeRef => {
if (
gqlType.kind !== TypeKind.OBJECT &&
gqlType.kind !== TypeKind.INTERFACE &&
gqlType.kind !== TypeKind.UNION
) {
return panic(
"Type for selection set is not object, interface, or union.",
);
}
if (!gqlType.name) {
return panic(
"Object, interface, or union type doesn't have a name.",
);
}
const nameOrOverride = overrideName ?? gqlType.name;
const properties = new Map<string, ClassProperty>();
let selections = expandSelectionSet(selectionSet, gqlType, false);
for (;;) {
const nextItem = selections.pop();
if (!nextItem) break;
const { selection, optional, inType } = nextItem;
switch (selection.kind) {
case Kind.FIELD:
const fieldName = selection.name.value;
const givenName = selection.alias
? selection.alias.value
: fieldName;
const field = getField(inType, fieldName);
const fieldType = this.makeIRTypeFromFieldNode(
builder,
selection,
field.type,
nameOrOverride,
);
properties.set(
givenName,
builder.makeClassProperty(fieldType, optional),
);
break;
case Kind.FRAGMENT_SPREAD: {
const fragment = this.getFragment(selection.name.value);
const fragmentType =
this._schema.types[fragment.typeCondition.name.value];
const fragmentOptional =
optional || fragmentType.name !== inType.name;
const expanded = expandSelectionSet(
fragment.selectionSet,
fragmentType,
fragmentOptional,
);
selections = selections.concat(expanded);
break;
}
case Kind.INLINE_FRAGMENT: {
// FIXME: support type conditions with discriminated unions
const fragmentType = selection.typeCondition
? this._schema.types[selection.typeCondition.name.value]
: inType;
const fragmentOptional =
optional ||
fragmentType.name !== inType.name ||
hasOptionalDirectives(selection.directives);
const expanded = expandSelectionSet(
selection.selectionSet,
fragmentType,
fragmentOptional,
);
selections = selections.concat(expanded);
break;
}
default:
assertNever(selection);
}
}
return builder.getClassType(
makeNames(nameOrOverride, containingFieldName, containingTypeName),
properties,
);
};
public makeType(
builder: TypeBuilder,
query: OperationDefinitionNode,
queryName: string,
): TypeRef {
if (query.operation === "query") {
return this.makeIRTypeFromSelectionSet(
builder,
query.selectionSet,
this._schema.queryType,
null,
queryName,
"data",
);
}
if (query.operation === "mutation") {
if (this._schema.mutationType === undefined) {
return panic("This GraphQL endpoint has no mutations.");
}
return this.makeIRTypeFromSelectionSet(
builder,
query.selectionSet,
this._schema.mutationType,
null,
queryName,
"data",
);
}
return panic(`Unknown query operation type: "${query.operation}"`);
}
}
class GQLSchemaFromJSON implements GQLSchema {
public readonly types: { [name: string]: GQLType } = {};
// @ts-expect-error: The constructor can return early, but only by throwing.
public readonly queryType: GQLType;
public readonly mutationType?: GQLType;
public constructor(json: { data: GraphQLSchema }) {
const schema: GraphQLSchema = json.data;
if (schema.__schema.queryType.name === null) {
return panic("Query type doesn't have a name.");
}
for (const t of schema.__schema.types as GQLType[]) {
if (!t.name) return panic("No top-level type name given");
this.types[t.name] = {
kind: t.kind,
name: t.name,
description: t.description,
};
}
for (const t of schema.__schema.types) {
if (!t.name) return panic("This cannot happen");
const type = this.types[t.name];
this.addTypeFields(type, t as GQLType);
// console.log(`type ${type.name} is ${type.kind}`);
}
const queryType = this.types[schema.__schema.queryType.name];
if (queryType === undefined) {
return panic("Query type not found.");
}
// console.log(`query type ${queryType.name} is ${queryType.kind}`);
this.queryType = queryType;
if (schema.__schema.mutationType === null) {
return;
}
if (schema.__schema.mutationType.name === null) {
return panic("Mutation type doesn't have a name.");
}
const mutationType = this.types[schema.__schema.mutationType.name];
if (mutationType === undefined) {
return panic("Mutation type not found.");
}
this.mutationType = mutationType;
}
private readonly addTypeFields = (
target: GQLType,
source: GQLType,
): void => {
if (source.fields) {
target.fields = source.fields.map((f) => {
return {
name: f.name,
description: f.description,
type: this.makeType(f.type),
args: f.args.map(this.makeInputValue),
};
});
// console.log(`${target.name} has ${target.fields.length} fields`);
}
if (source.interfaces) {
target.interfaces = source.interfaces.map(this.makeType);
// console.log(`${target.name} has ${target.interfaces.length} interfaces`);
}
if (source.possibleTypes) {
target.possibleTypes = source.possibleTypes.map(this.makeType);
// console.log(`${target.name} has ${target.possibleTypes.length} possibleTypes`);
}
if (source.inputFields) {
target.inputFields = source.inputFields.map(this.makeInputValue);
// console.log(`${target.name} has ${target.inputFields.length} inputFields`);
}
if (source.enumValues) {
target.enumValues = source.enumValues.map((ev) => {
return { name: ev.name, description: ev.description };
});
// console.log(`${target.name} has ${target.enumValues.length} enumValues`);
}
};
private readonly makeInputValue = (iv: InputValue): InputValue => {
return {
name: iv.name,
description: iv.description,
type: this.makeType(iv.type),
defaultValue: iv.defaultValue,
};
};
private readonly makeType = (t: GQLType): GQLType => {
if (t.name) {
const namedType = this.types[t.name];
if (!namedType) return panic(`Type ${t.name} not found`);
return namedType;
}
if (!t.ofType)
return panic(`Type of kind ${t.kind} has neither name nor ofType`);
const type: GQLType = {
kind: t.kind,
description: t.description,
ofType: this.makeType(t.ofType),
};
this.addTypeFields(type, t);
return type;
};
}
function makeGraphQLQueryTypes(
topLevelName: string,
builder: TypeBuilder,
json: { data: GraphQLSchema },
queryString: string,
): Map<string, TypeRef> {
const schema = new GQLSchemaFromJSON(json);
const query = new GQLQuery(schema, queryString);
const types = new Map<string, TypeRef>();
for (const odn of query.queries) {
const queryName = odn.name ? odn.name.value : topLevelName;
if (types.has(queryName)) {
return panic(`Duplicate query name ${queryName}`);
}
const dataType = query.makeType(builder, odn, queryName);
const dataOrNullType = builder.getUnionType(
emptyTypeAttributes,
new Set([dataType, builder.getPrimitiveType("null")]),
);
const errorType = builder.getClassType(
namesTypeAttributeKind.makeAttributes(
TypeNames.make(
new Set(["error"]),
new Set(["graphQLError"]),
false,
),
),
mapFromObject({
message: builder.makeClassProperty(
builder.getStringType(
emptyTypeAttributes,
StringTypes.unrestricted,
),
false,
),
}),
);
const errorArray = builder.getArrayType(
namesTypeAttributeKind.makeAttributes(
TypeNames.make(
new Set(["errors"]),
new Set(["graphQLErrors"]),
false,
),
),
errorType,
);
const t = builder.getClassType(
makeNamesTypeAttributes(queryName, false),
mapFromObject({
data: builder.makeClassProperty(dataOrNullType, false),
errors: builder.makeClassProperty(errorArray, true),
}),
);
types.set(queryName, t);
}
return types;
}
export interface GraphQLSourceData {
name: string;
query: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
schema: any;
}
interface GraphQLTopLevel {
query: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
schema: any;
}
export class GraphQLInput implements Input<GraphQLSourceData> {
public readonly kind: string = "graphql";
public readonly needIR: boolean = true;
public readonly needSchemaProcessing: boolean = false;
private readonly _topLevels: Map<string, GraphQLTopLevel> = new Map();
public async addSource(source: GraphQLSourceData): Promise<void> {
this.addSourceSync(source);
}
public addSourceSync(source: GraphQLSourceData): void {
this._topLevels.set(source.name, {
schema: source.schema,
query: source.query,
});
}
public singleStringSchemaSource(): undefined {
return undefined;
}
public async addTypes(
ctx: RunContext,
typeBuilder: TypeBuilder,
): Promise<void> {
this.addTypesSync(ctx, typeBuilder);
}
public addTypesSync(_ctx: RunContext, typeBuilder: TypeBuilder): void {
for (const [name, { schema, query }] of this._topLevels) {
const newTopLevels = makeGraphQLQueryTypes(
name,
typeBuilder,
schema,
query,
);
for (const [actualName, t] of newTopLevels) {
typeBuilder.addTopLevel(
this._topLevels.size === 1 ? name : actualName,
t,
);
}
}
}
}