@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 237 lines 9.41 KB
Raw
1 /**
2 * Builds a {@link SchemaModel.Schema} from a parsed type-system document.
3 *
4 * @internal
5 */
6 import type * as Result from "effect/Result"
7 import type * as Ast from "./Ast.ts"
8 import { catchDiagnostic, type Diagnostic, make, type Source } from "./Diagnostic.ts"
9 import * as SchemaModel from "./SchemaModel.ts"
10
11 /**
12 * Reads every definition and `extend` form in `document`, merging extensions
13 * into their base definitions in document order. Root operation types come
14 * from `schema { ... }` and `extend schema`, or default to the types named
15 * `Query`, `Mutation` and `Subscription` when there is no schema definition.
16 * Executable definitions are ignored.
17 *
18 * Fails with a diagnostic located in `source` when the document cannot form a
19 * schema, e.g. it has no query root type or extends a type it never defines.
20 * The server schema is not otherwise validated.
21 */
22 export const read = (source: Source, document: Ast.Document): Result.Result<SchemaModel.Schema, Diagnostic> =>
23 catchDiagnostic(() => build(source, document))
24
25 /** The definition each extension kind extends, and the word graphql-js uses for it. */
26 const extensionTargets: Record<Ast.TypeExtension["_tag"], readonly [Ast.TypeDefinition["_tag"], string]> = {
27 ScalarTypeExtension: ["ScalarTypeDefinition", "scalar"],
28 ObjectTypeExtension: ["ObjectTypeDefinition", "object"],
29 InterfaceTypeExtension: ["InterfaceTypeDefinition", "interface"],
30 UnionTypeExtension: ["UnionTypeDefinition", "union"],
31 EnumTypeExtension: ["EnumTypeDefinition", "enum"],
32 InputObjectTypeExtension: ["InputObjectTypeDefinition", "input object"]
33 }
34
35 const build = (source: Source, document: Ast.Document): SchemaModel.Schema => {
36 const fail = (offset: number, message: string): never => {
37 throw make(source, offset, message)
38 }
39
40 const definitions = new Map<string, Ast.TypeDefinition>()
41 const extensions = new Map<string, Array<Ast.TypeExtension>>()
42 let schemaDefinition: Ast.SchemaDefinition | undefined
43 const schemaExtensions: Array<Ast.SchemaExtension> = []
44
45 for (const definition of document.definitions) {
46 switch (definition._tag) {
47 case "OperationDefinition":
48 case "FragmentDefinition":
49 case "DirectiveDefinition":
50 break
51
52 case "SchemaDefinition":
53 if (schemaDefinition !== undefined) fail(definition.loc.start, "Must provide only one schema definition.")
54 schemaDefinition = definition
55 break
56 case "SchemaExtension":
57 schemaExtensions.push(definition)
58 break
59
60 case "ScalarTypeExtension":
61 case "ObjectTypeExtension":
62 case "InterfaceTypeExtension":
63 case "UnionTypeExtension":
64 case "EnumTypeExtension":
65 case "InputObjectTypeExtension": {
66 const list = extensions.get(definition.name.value)
67 if (list === undefined) extensions.set(definition.name.value, [definition])
68 else list.push(definition)
69 break
70 }
71 default: {
72 const name = definition.name.value
73 if (definitions.has(name)) fail(definition.name.loc.start, `There can be only one type named "${name}".`)
74 definitions.set(name, definition)
75 }
76 }
77 }
78
79 for (const [name, list] of extensions) {
80 const definition = definitions.get(name)
81 for (const extension of list) {
82 const [target, word] = extensionTargets[extension._tag]
83 if (definition === undefined) {
84 if (extension._tag === "ScalarTypeExtension" && SchemaModel.builtInScalarNames.includes(name)) continue
85 fail(extension.name.loc.start, `Cannot extend type "${name}" because it is not defined.`)
86 } else if (definition._tag !== target) {
87 fail(extension.name.loc.start, `Cannot extend non-${word} type "${name}".`)
88 }
89 }
90 }
91
92 // Interface name -> implementing object types, for `possibleTypes`.
93 const implementations = new Map<string, Array<string>>()
94 for (const [name, definition] of definitions) {
95 if (definition._tag !== "ObjectTypeDefinition") continue
96 const parts = withExtensions(definition, extensions) as ReadonlyArray<
97 Ast.ObjectTypeDefinition | Ast.ObjectTypeExtension
98 >
99 for (const part of parts) {
100 for (const iface of part.interfaces) {
101 const list = implementations.get(iface.name.value)
102 if (list === undefined) implementations.set(iface.name.value, [name])
103 else if (!list.includes(name)) list.push(name)
104 }
105 }
106 }
107
108 const types = new Map<string, SchemaModel.NamedType>()
109 for (const name of SchemaModel.builtInScalarNames) types.set(name, SchemaModel.builtInScalar(name))
110 for (const [name, definition] of definitions) {
111 if (SchemaModel.builtInScalarNames.includes(name)) continue
112 types.set(name, buildType(definition, extensions, implementations))
113 }
114
115 const defaultRoot = (name: string) => schemaDefinition === undefined && types.has(name) ? name : undefined
116 const roots: Record<Ast.OperationType, string | undefined> = {
117 query: defaultRoot("Query"),
118 mutation: defaultRoot("Mutation"),
119 subscription: defaultRoot("Subscription")
120 }
121 for (const part of schemaDefinition === undefined ? schemaExtensions : [schemaDefinition, ...schemaExtensions]) {
122 for (const operationType of part.operationTypes) {
123 roots[operationType.operation] = operationType.type.name.value
124 }
125 }
126 if (roots.query === undefined) {
127 return fail(schemaDefinition?.loc.start ?? 0, "Query root type must be provided.")
128 }
129
130 return {
131 queryType: roots.query,
132 mutationType: roots.mutation,
133 subscriptionType: roots.subscription,
134 types
135 }
136 }
137
138 /** A definition followed by its extensions, which share the members being merged. */
139 const withExtensions = <D extends Ast.TypeDefinition>(
140 definition: D,
141 extensions: ReadonlyMap<string, ReadonlyArray<Ast.TypeExtension>>
142 ): ReadonlyArray<D | Ast.TypeExtension> => [definition, ...(extensions.get(definition.name.value) ?? [])]
143
144 const buildType = (
145 definition: Ast.TypeDefinition,
146 extensions: ReadonlyMap<string, ReadonlyArray<Ast.TypeExtension>>,
147 implementations: ReadonlyMap<string, ReadonlyArray<string>>
148 ): SchemaModel.NamedType => {
149 const name = definition.name.value
150 const description = definition.description?.value
151 // Each extension has already been checked to match its definition's kind.
152 const parts = withExtensions(definition, extensions)
153 switch (definition._tag) {
154 case "ScalarTypeDefinition":
155 return { _tag: "ScalarType", name, description }
156 case "ObjectTypeDefinition":
157 case "InterfaceTypeDefinition": {
158 const objectParts = parts as ReadonlyArray<
159 Ast.ObjectTypeDefinition | Ast.ObjectTypeExtension | Ast.InterfaceTypeDefinition | Ast.InterfaceTypeExtension
160 >
161 const interfaces = objectParts.flatMap((part) => part.interfaces.map((iface) => iface.name.value))
162 const fields = objectParts.flatMap((part) => part.fields.map(buildField))
163 return definition._tag === "ObjectTypeDefinition"
164 ? { _tag: "ObjectType", name, description, interfaces, fields }
165 : {
166 _tag: "InterfaceType",
167 name,
168 description,
169 interfaces,
170 fields,
171 possibleTypes: [...(implementations.get(name) ?? [])].sort()
172 }
173 }
174
175 case "UnionTypeDefinition":
176 return {
177 _tag: "UnionType",
178 name,
179 description,
180 possibleTypes: (parts as ReadonlyArray<Ast.UnionTypeDefinition | Ast.UnionTypeExtension>).flatMap((part) =>
181 part.types.map((member) => member.name.value)
182 )
183 }
184 case "EnumTypeDefinition":
185 return {
186 _tag: "EnumType",
187 name,
188 description,
189 values: (parts as ReadonlyArray<Ast.EnumTypeDefinition | Ast.EnumTypeExtension>).flatMap((part) =>
190 part.values.map((value) => ({
191 name: value.name.value,
192 description: value.description?.value,
193 deprecationReason: deprecationReason(value.directives)
194 }))
195 )
196 }
197 case "InputObjectTypeDefinition":
198 return {
199 _tag: "InputObjectType",
200 name,
201 description,
202 oneOf: parts.some((part) => findDirective(part.directives, "oneOf") !== undefined),
203
204 fields: (parts as ReadonlyArray<Ast.InputObjectTypeDefinition | Ast.InputObjectTypeExtension>).flatMap((
205 part
206 ) => part.fields.map(buildInputValue))
207 }
208 }
209 }
210
211 const buildField = (field: Ast.FieldDefinition): SchemaModel.Field => ({
212 name: field.name.value,
213 description: field.description?.value,
214 arguments: field.arguments.map(buildInputValue),
215 type: SchemaModel.fromAstType(field.type),
216 deprecationReason: deprecationReason(field.directives)
217 })
218
219 const buildInputValue = (value: Ast.InputValueDefinition): SchemaModel.InputValue => ({
220 name: value.name.value,
221 description: value.description?.value,
222 type: SchemaModel.fromAstType(value.type),
223 defaultValue: value.defaultValue === undefined ? undefined : SchemaModel.fromAstConstValue(value.defaultValue),
224 deprecationReason: deprecationReason(value.directives)
225 })
226
227 const findDirective = (
228 directives: ReadonlyArray<Ast.ConstDirective>,
229 name: string
230 ): Ast.ConstDirective | undefined => directives.find((directive) => directive.name.value === name)
231
232 const deprecationReason = (directives: ReadonlyArray<Ast.ConstDirective>): string | undefined => {
233 const directive = findDirective(directives, "deprecated")
234 if (directive === undefined) return undefined
235 const reason = directive.arguments.find((argument) => argument.name.value === "reason")?.value
236 return reason?._tag === "StringValue" ? reason.value : SchemaModel.defaultDeprecationReason
237 }