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
| 1 | /** |
| 2 | * Validates executable documents against the schema, including literal |
| 3 | * values that bypass the runtime variables Schema. Validation spans all |
| 4 | * input files: fragments resolve across files, and operations and fragments |
| 5 | * share one namespace. |
| 6 | * |
| 7 | * @internal |
| 8 | */ |
| 9 | import type * as Ast from "./Ast.ts" |
| 10 | import { type Diagnostic, make, type Source } from "./Diagnostic.ts" |
| 11 | import * as SchemaModel from "./SchemaModel.ts" |
| 12 | |
| 13 | /** One parsed input file. */ |
| 14 | export interface File { |
| 15 | readonly source: Source |
| 16 | readonly document: Ast.Document |
| 17 | } |
| 18 | |
| 19 | /** |
| 20 | * Collects every diagnostic across `files`, ordered by file (input order) and |
| 21 | * then by position. Each diagnostic is reported in the file holding the node |
| 22 | * it points at. Messages follow graphql-js 16.14.2 where it has a matching rule, |
| 23 | * without its "Did you mean" suggestion lists. |
| 24 | * |
| 25 | * - Fields exist on their parent type (`__typename` exists on every composite |
| 26 | * type), and their types are defined by the schema. |
| 27 | * - Arguments exist and are unique; required arguments (non-null, no default) |
| 28 | * are provided. |
| 29 | * - Variables are unique, defined, used (directly or through spread fragments, |
| 30 | * from any file) and of known input types. Each usage fits its position: |
| 31 | * a nullable variable fills a non-null position only when the variable or |
| 32 | * the position has a non-null default. |
| 33 | * - Fragments are defined in some input file, used by some operation, acyclic, |
| 34 | * and spread onto a possible type (a composite type always overlaps |
| 35 | * itself); type conditions name known types. |
| 36 | * - Subscriptions select exactly one root field, counted by response key |
| 37 | * through inline fragments and fragment spreads. |
| 38 | * - Operations are named. Operations and fragments share one namespace across |
| 39 | * all files; every definition sharing a name gets one diagnostic at its |
| 40 | * name, worded for its kind or as "operation or fragment" when kinds mix. |
| 41 | * - Leaf fields have no selection set; composite fields have one. |
| 42 | * - Fields sharing a response key, collected through inline fragments and |
| 43 | * fragment spreads, can be merged: the same field with the same arguments |
| 44 | * unless their parents are different object types, compatible response |
| 45 | * shapes, and mergeable subselections. The second field is reported. |
| 46 | * - `@skip` and `@include` appear only on fields, fragment spreads and inline |
| 47 | * fragments, at most once per location, with a required `if: Boolean!`. Other |
| 48 | * directives are passed to the server unchecked. |
| 49 | * - Literal arguments, input fields and variable defaults match their input |
| 50 | * types: enum values exist, required input fields are provided, input fields |
| 51 | * are known and unique. A `@oneOf` input supplies exactly one field and no |
| 52 | * null literal, matching graphql-js 16.14.2. Nullable variables in those |
| 53 | * fields remain accepted; the server must reject null variable values. The |
| 54 | * runtime variables `Schema` checks the declared variable type, not the |
| 55 | * enclosing document literal. Custom scalars accept any literal, and `Int` |
| 56 | * literals are not range checked. |
| 57 | * |
| 58 | * Fields under an unknown field or type are not checked further. The server |
| 59 | * schema is not validated. |
| 60 | */ |
| 61 | export const validate = ( |
| 62 | schema: SchemaModel.Schema, |
| 63 | files: ReadonlyArray<File> |
| 64 | ): ReadonlyArray<Diagnostic> => { |
| 65 | const reports: Array<Report> = [] |
| 66 | // A conflict inside an inline fragment is found from both its own and the enclosing selection set. |
| 67 | const seen = new Set<string>() |
| 68 | const report = (fileIndex: number, offset: number, message: string) => { |
| 69 | const key = `${fileIndex}:${offset}:${message}` |
| 70 | if (seen.has(key)) return |
| 71 | seen.add(key) |
| 72 | reports.push({ fileIndex, offset, diagnostic: make(files[fileIndex]!.source, offset, message) }) |
| 73 | } |
| 74 | new Validator(schema, files, report).validate() |
| 75 | // `sort` is stable, so diagnostics at the same position keep the order they were found in. |
| 76 | return reports |
| 77 | .sort((a, b) => a.fileIndex - b.fileIndex || a.offset - b.offset) |
| 78 | .map((report) => report.diagnostic) |
| 79 | } |
| 80 | |
| 81 | interface Report { |
| 82 | readonly fileIndex: number |
| 83 | readonly offset: number |
| 84 | readonly diagnostic: Diagnostic |
| 85 | } |
| 86 | |
| 87 | /** Reports `message` at a code-unit offset into input file `fileIndex`. */ |
| 88 | type Reporter = (fileIndex: number, offset: number, message: string) => void |
| 89 | |
| 90 | /** A definition together with the index of the input file it came from. */ |
| 91 | interface Located<A> { |
| 92 | readonly node: A |
| 93 | readonly file: number |
| 94 | } |
| 95 | |
| 96 | type Composite = SchemaModel.ObjectType | SchemaModel.InterfaceType | SchemaModel.UnionType |
| 97 | |
| 98 | const isComposite = (type: SchemaModel.NamedType): type is Composite => |
| 99 | type._tag === "ObjectType" || type._tag === "InterfaceType" || type._tag === "UnionType" |
| 100 | |
| 101 | const isInput = (type: SchemaModel.NamedType): boolean => |
| 102 | type._tag === "ScalarType" || type._tag === "EnumType" || type._tag === "InputObjectType" |
| 103 | |
| 104 | const typenameField: SchemaModel.Field = { |
| 105 | name: "__typename", |
| 106 | description: undefined, |
| 107 | arguments: [], |
| 108 | type: { _tag: "NonNullTypeRef", ofType: { _tag: "NamedTypeRef", name: "String" } }, |
| 109 | deprecationReason: undefined |
| 110 | } |
| 111 | |
| 112 | const fieldOf = (parent: Composite, name: string): SchemaModel.Field | undefined => { |
| 113 | if (name === "__typename") return typenameField |
| 114 | return parent._tag === "UnionType" ? undefined : parent.fields.find((field) => field.name === name) |
| 115 | } |
| 116 | |
| 117 | const possibleTypes = (type: Composite): ReadonlyArray<string> => |
| 118 | type._tag === "ObjectType" ? [type.name] : type.possibleTypes |
| 119 | |
| 120 | const printAstType = (type: Ast.Type): string => SchemaModel.printTypeRef(SchemaModel.fromAstType(type)) |
| 121 | |
| 122 | const namedAstType = (type: Ast.Type): Ast.NamedType => type._tag === "NamedType" ? type : namedAstType(type.type) |
| 123 | |
| 124 | /** Structural equality of argument values, ignoring locations. */ |
| 125 | const valueEquals = (a: Ast.Value, b: Ast.Value): boolean => { |
| 126 | switch (a._tag) { |
| 127 | case "Variable": |
| 128 | return b._tag === "Variable" && a.name.value === b.name.value |
| 129 | case "IntValue": |
| 130 | case "FloatValue": |
| 131 | case "StringValue": |
| 132 | case "EnumValue": |
| 133 | case "BooleanValue": |
| 134 | return b._tag === a._tag && b.value === a.value |
| 135 | case "NullValue": |
| 136 | return b._tag === "NullValue" |
| 137 | case "ListValue": |
| 138 | return b._tag === "ListValue" && a.values.length === b.values.length && |
| 139 | a.values.every((value, i) => valueEquals(value, b.values[i]!)) |
| 140 | case "ObjectValue": |
| 141 | return b._tag === "ObjectValue" && a.fields.length === b.fields.length && |
| 142 | a.fields.every((field) => { |
| 143 | const other = b.fields.find((candidate) => candidate.name.value === field.name.value) |
| 144 | return other !== undefined && valueEquals(field.value, other.value) |
| 145 | }) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | const sameArguments = (a: ReadonlyArray<Ast.Argument>, b: ReadonlyArray<Ast.Argument>): boolean => |
| 150 | a.length === b.length && |
| 151 | a.every((argument) => { |
| 152 | const other = b.find((candidate) => candidate.name.value === argument.name.value) |
| 153 | return other !== undefined && valueEquals(argument.value, other.value) |
| 154 | }) |
| 155 | |
| 156 | /** The items whose name an earlier item already has, in order: each is reported where it repeats. */ |
| 157 | const repeated = <A>(items: ReadonlyArray<A>, name: (item: A) => string): Array<A> => { |
| 158 | const seen = new Set<string>() |
| 159 | return items.filter((item) => { |
| 160 | const key = name(item) |
| 161 | if (seen.has(key)) return true |
| 162 | seen.add(key) |
| 163 | return false |
| 164 | }) |
| 165 | } |
| 166 | |
| 167 | /** A value as it appears in graphql-js messages. */ |
| 168 | const printValue = (value: Ast.Value | Ast.ConstValue): string => { |
| 169 | switch (value._tag) { |
| 170 | case "Variable": |
| 171 | return `$${value.name.value}` |
| 172 | case "StringValue": |
| 173 | return JSON.stringify(value.value) |
| 174 | case "NullValue": |
| 175 | return "null" |
| 176 | case "BooleanValue": |
| 177 | return String(value.value) |
| 178 | case "IntValue": |
| 179 | case "FloatValue": |
| 180 | case "EnumValue": |
| 181 | return value.value |
| 182 | case "ListValue": |
| 183 | return `[${value.values.map(printValue).join(", ")}]` |
| 184 | case "ObjectValue": |
| 185 | return `{${value.fields.map((field) => `${field.name.value}: ${printValue(field.value)}`).join(", ")}}` |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | const booleanNonNull: SchemaModel.TypeRef = { |
| 190 | _tag: "NonNullTypeRef", |
| 191 | ofType: { _tag: "NamedTypeRef", name: "Boolean" } |
| 192 | } |
| 193 | |
| 194 | /** |
| 195 | * The built-in directives the emitter interprets. Other directives are passed |
| 196 | * through to the server unchecked, so servers can define their own. |
| 197 | */ |
| 198 | const conditionDirectives: ReadonlySet<string> = new Set(["skip", "include"]) |
| 199 | |
| 200 | type DirectiveLocation = |
| 201 | | "QUERY" |
| 202 | | "MUTATION" |
| 203 | | "SUBSCRIPTION" |
| 204 | | "FIELD" |
| 205 | | "FRAGMENT_DEFINITION" |
| 206 | | "FRAGMENT_SPREAD" |
| 207 | | "INLINE_FRAGMENT" |
| 208 | | "VARIABLE_DEFINITION" |
| 209 | |
| 210 | const conditionLocations: ReadonlySet<DirectiveLocation> = new Set(["FIELD", "FRAGMENT_SPREAD", "INLINE_FRAGMENT"]) |
| 211 | |
| 212 | /** A variable in an argument, input field or condition of a known type. */ |
| 213 | interface VariableUsage { |
| 214 | readonly file: number |
| 215 | readonly node: Ast.Variable |
| 216 | readonly type: SchemaModel.TypeRef |
| 217 | /** Whether the argument or input field has a default value. */ |
| 218 | readonly hasDefault: boolean |
| 219 | } |
| 220 | |
| 221 | /** One field selected under a response key, with the type it is selected on. */ |
| 222 | interface FieldEntry { |
| 223 | readonly file: number |
| 224 | readonly parent: Composite | undefined |
| 225 | readonly node: Ast.Field |
| 226 | readonly definition: SchemaModel.Field | undefined |
| 227 | } |
| 228 | |
| 229 | /** The fields of a selection set by response key, through inline fragments, and the fragments it spreads. */ |
| 230 | interface CollectedFields { |
| 231 | readonly fields: ReadonlyMap<string, ReadonlyArray<FieldEntry>> |
| 232 | readonly fragments: ReadonlyArray<string> |
| 233 | } |
| 234 | |
| 235 | /** Two fields that can't be merged, reported at the second. */ |
| 236 | interface Conflict { |
| 237 | readonly responseName: string |
| 238 | readonly reason: string | ReadonlyArray<Conflict> |
| 239 | readonly file: number |
| 240 | readonly offset: number |
| 241 | } |
| 242 | |
| 243 | const reasonMessage = (reason: Conflict["reason"]): string => |
| 244 | typeof reason === "string" |
| 245 | ? reason |
| 246 | : reason.map((conflict) => |
| 247 | `subfields "${conflict.responseName}" conflict because ${reasonMessage(conflict.reason)}` |
| 248 | ) |
| 249 | .join(" and ") |
| 250 | |
| 251 | class Validator { |
| 252 | readonly schema: SchemaModel.Schema |
| 253 | readonly report: Reporter |
| 254 | /** Every operation and fragment, in file order and then document order. */ |
| 255 | readonly operations: Array<Located<Ast.OperationDefinition>> = [] |
| 256 | readonly fragmentList: Array<Located<Ast.FragmentDefinition>> = [] |
| 257 | /** The first fragment with each name in any file; duplicates are reported by `checkUniqueNames`. */ |
| 258 | readonly fragments = new Map<string, Located<Ast.FragmentDefinition>>() |
| 259 | readonly collected = new Map<Ast.SelectionSet, CollectedFields>() |
| 260 | /** The variable positions in each operation's or fragment's own selections, once validated. */ |
| 261 | readonly usages = new Map<Ast.OperationDefinition | Ast.FragmentDefinition, ReadonlyArray<VariableUsage>>() |
| 262 | /** Where `checkValue` records variables while a definition's selections are validated. */ |
| 263 | positions: Array<VariableUsage> | undefined = undefined |
| 264 | /** Fragment pairs already compared for conflicts, keyed by the sorted names, to whether they were mutually exclusive. */ |
| 265 | readonly comparedFragments = new Map<string, boolean>() |
| 266 | /** Field maps already compared with a fragment, by fragment name, to whether they were mutually exclusive. */ |
| 267 | readonly comparedFieldsAndFragments = new WeakMap<CollectedFields["fields"], Map<string, boolean>>() |
| 268 | |
| 269 | constructor(schema: SchemaModel.Schema, files: ReadonlyArray<File>, report: Reporter) { |
| 270 | this.schema = schema |
| 271 | this.report = report |
| 272 | files.forEach((file, index) => { |
| 273 | for (const definition of file.document.definitions) { |
| 274 | if (definition._tag === "OperationDefinition") { |
| 275 | this.operations.push({ node: definition, file: index }) |
| 276 | } else if (definition._tag === "FragmentDefinition") { |
| 277 | const fragment = { node: definition, file: index } |
| 278 | this.fragmentList.push(fragment) |
| 279 | if (!this.fragments.has(definition.name.value)) this.fragments.set(definition.name.value, fragment) |
| 280 | } |
| 281 | } |
| 282 | }) |
| 283 | } |
| 284 | |
| 285 | validate(): void { |
| 286 | const defined = this.operations.map((operation) => this.validateOperation(operation)) |
| 287 | for (const { file, node: fragment } of this.fragmentList) { |
| 288 | const type = this.typeCondition( |
| 289 | file, |
| 290 | fragment.typeCondition, |
| 291 | (name) => `Fragment "${fragment.name.value}" cannot condition on non composite type "${name}".` |
| 292 | ) |
| 293 | this.checkDirectives(file, fragment.directives, "FRAGMENT_DEFINITION") |
| 294 | if (type !== undefined) this.validateDefinition(file, fragment, type) |
| 295 | } |
| 296 | // Variables reach fragments in any file, so they are checked once every definition is validated. |
| 297 | this.operations.forEach((operation, i) => this.checkVariables(operation, defined[i]!)) |
| 298 | this.checkUnusedFragments() |
| 299 | this.checkFragmentCycles() |
| 300 | this.checkUniqueNames() |
| 301 | } |
| 302 | |
| 303 | // Operations and variables |
| 304 | |
| 305 | /** Returns the first definition of each variable, when its type is a known input type. */ |
| 306 | validateOperation( |
| 307 | { file, node: operation }: Located<Ast.OperationDefinition> |
| 308 | ): ReadonlyMap<string, Ast.VariableDefinition | undefined> { |
| 309 | const name = operation.name?.value |
| 310 | if (name === undefined) { |
| 311 | this.report(file, operation.loc.start, "Anonymous operations are not supported, name this operation.") |
| 312 | } |
| 313 | |
| 314 | this.checkDirectives(file, operation.directives, operation.operation.toUpperCase() as DirectiveLocation) |
| 315 | for ( |
| 316 | const { variable } of repeated(operation.variableDefinitions, (definition) => definition.variable.name.value) |
| 317 | ) { |
| 318 | this.report(file, variable.loc.start, `There can be only one variable named "$${variable.name.value}".`) |
| 319 | } |
| 320 | const defined = new Map<string, Ast.VariableDefinition | undefined>() |
| 321 | for (const definition of operation.variableDefinitions) { |
| 322 | this.checkDirectives(file, definition.directives, "VARIABLE_DEFINITION") |
| 323 | const named = namedAstType(definition.type) |
| 324 | const type = this.schema.types.get(named.name.value) |
| 325 | const known = type !== undefined && isInput(type) |
| 326 | if (!defined.has(definition.variable.name.value)) { |
| 327 | defined.set(definition.variable.name.value, known ? definition : undefined) |
| 328 | } |
| 329 | if (type === undefined) { |
| 330 | this.report(file, named.loc.start, `Unknown type "${named.name.value}".`) |
| 331 | } else if (!known) { |
| 332 | this.report( |
| 333 | file, |
| 334 | definition.type.loc.start, |
| 335 | `Variable "$${definition.variable.name.value}" cannot be non-input type "${printAstType(definition.type)}".` |
| 336 | ) |
| 337 | } else if (definition.defaultValue !== undefined) { |
| 338 | this.checkValue(file, definition.defaultValue, SchemaModel.fromAstType(definition.type)) |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | const root = this.composite(SchemaModel.rootTypeName(this.schema, operation.operation)) |
| 343 | if (root === undefined) { |
| 344 | this.report(file, operation.loc.start, `Schema is not configured to execute ${operation.operation} operation.`) |
| 345 | return defined |
| 346 | } |
| 347 | if (operation.operation === "subscription") this.checkSingleRootField(file, operation) |
| 348 | this.validateDefinition(file, operation, root) |
| 349 | return defined |
| 350 | } |
| 351 | |
| 352 | /** Validates a definition's selections, recording the variable positions in them for `checkVariables`. */ |
| 353 | validateDefinition( |
| 354 | file: number, |
| 355 | definition: Ast.OperationDefinition | Ast.FragmentDefinition, |
| 356 | root: Composite |
| 357 | ): void { |
| 358 | this.positions = [] |
| 359 | this.validateSelectionSet(file, definition.selectionSet, root) |
| 360 | this.usages.set(definition, this.positions) |
| 361 | this.positions = undefined |
| 362 | } |
| 363 | |
| 364 | /** |
| 365 | * Checks the variables an operation uses, directly or through every fragment |
| 366 | * it spreads, transitively and across files: each fits its position, is |
| 367 | * defined, and each definition is used. |
| 368 | */ |
| 369 | checkVariables( |
| 370 | { file, node: operation }: Located<Ast.OperationDefinition>, |
| 371 | defined: ReadonlyMap<string, Ast.VariableDefinition | undefined> |
| 372 | ): void { |
| 373 | const name = operation.name?.value |
| 374 | const definitions = [{ node: operation, file }, ...this.reachableFragments([operation.selectionSet])] |
| 375 | for (const definition of definitions) { |
| 376 | for (const usage of this.usages.get(definition.node) ?? []) { |
| 377 | const variable = defined.get(usage.node.name.value) |
| 378 | if (variable === undefined || this.allowedPosition(variable, usage)) continue |
| 379 | this.report( |
| 380 | usage.file, |
| 381 | usage.node.loc.start, |
| 382 | `Variable "$${usage.node.name.value}" of type "${ |
| 383 | printAstType(variable.type) |
| 384 | }" used in position expecting type "${SchemaModel.printTypeRef(usage.type)}".` |
| 385 | ) |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | const usages: Array<Located<Ast.Variable>> = [] |
| 390 | for (const { file: at, node: definition } of definitions) { |
| 391 | const found: Array<Ast.Variable> = [] |
| 392 | variablesInDirectives(definition.directives, found) |
| 393 | variablesInSelectionSet(definition.selectionSet, found) |
| 394 | for (const variable of found) usages.push({ node: variable, file: at }) |
| 395 | } |
| 396 | const used = new Set(usages.map((usage) => usage.node.name.value)) |
| 397 | for (const { file: usageFile, node: usage } of usages) { |
| 398 | if (defined.has(usage.name.value)) continue |
| 399 | this.report( |
| 400 | usageFile, |
| 401 | usage.loc.start, |
| 402 | name === undefined |
| 403 | ? `Variable "$${usage.name.value}" is not defined.` |
| 404 | : `Variable "$${usage.name.value}" is not defined by operation "${name}".` |
| 405 | ) |
| 406 | } |
| 407 | for (const definition of operation.variableDefinitions) { |
| 408 | const variable = definition.variable.name.value |
| 409 | if (used.has(variable)) continue |
| 410 | this.report( |
| 411 | file, |
| 412 | definition.variable.loc.start, |
| 413 | name === undefined |
| 414 | ? `Variable "$${variable}" is never used.` |
| 415 | : `Variable "$${variable}" is never used in operation "${name}".` |
| 416 | ) |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | /** |
| 421 | * graphql-js's SingleFieldSubscriptions rule: a subscription selects one |
| 422 | * root response key, counted through inline fragments and fragment spreads. |
| 423 | * Selections a literal `@skip` or `@include` condition leaves out don't |
| 424 | * count. Reported at the first field of the second key. |
| 425 | */ |
| 426 | checkSingleRootField(file: number, operation: Ast.OperationDefinition): void { |
| 427 | const keys = new Map<string, Located<Ast.Field>>() |
| 428 | const visited = new Set<string>() |
| 429 | const collect = (at: number, selectionSet: Ast.SelectionSet): void => { |
| 430 | for (const selection of selectionSet.selections) { |
| 431 | if (inclusion(selection.directives) === "exclude") continue |
| 432 | if (selection._tag === "Field") { |
| 433 | const key = (selection.alias ?? selection.name).value |
| 434 | if (!keys.has(key)) keys.set(key, { node: selection, file: at }) |
| 435 | } else if (selection._tag === "InlineFragment") { |
| 436 | collect(at, selection.selectionSet) |
| 437 | } else if (!visited.has(selection.name.value)) { |
| 438 | visited.add(selection.name.value) |
| 439 | const fragment = this.fragments.get(selection.name.value) |
| 440 | if (fragment !== undefined) collect(fragment.file, fragment.node.selectionSet) |
| 441 | } |
| 442 | } |
| 443 | } |
| 444 | collect(file, operation.selectionSet) |
| 445 | const extra = Array.from(keys.values())[1] |
| 446 | if (extra === undefined) return |
| 447 | const name = operation.name?.value |
| 448 | this.report( |
| 449 | extra.file, |
| 450 | extra.node.loc.start, |
| 451 | name === undefined |
| 452 | ? "Anonymous Subscription must select only one top level field." |
| 453 | : `Subscription "${name}" must select only one top level field.` |
| 454 | ) |
| 455 | } |
| 456 | |
| 457 | /** The defined fragments spread from `selectionSets`, transitively and across files, each once. */ |
| 458 | reachableFragments(selectionSets: ReadonlyArray<Ast.SelectionSet>): Array<Located<Ast.FragmentDefinition>> { |
| 459 | const reached: Array<Located<Ast.FragmentDefinition>> = [] |
| 460 | const seen = new Set<string>() |
| 461 | const pending = selectionSets.flatMap((selectionSet) => fragmentSpreads(selectionSet)) |
| 462 | while (pending.length > 0) { |
| 463 | const name = pending.pop()!.name.value |
| 464 | if (seen.has(name)) continue |
| 465 | seen.add(name) |
| 466 | const fragment = this.fragments.get(name) |
| 467 | if (fragment === undefined) continue |
| 468 | reached.push(fragment) |
| 469 | pending.push(...fragmentSpreads(fragment.node.selectionSet)) |
| 470 | } |
| 471 | return reached |
| 472 | } |
| 473 | |
| 474 | // Selections |
| 475 | |
| 476 | validateSelectionSet(file: number, selectionSet: Ast.SelectionSet, parent: Composite): void { |
| 477 | for (const conflict of this.conflictsWithin(file, selectionSet, parent)) { |
| 478 | this.report( |
| 479 | conflict.file, |
| 480 | conflict.offset, |
| 481 | `Fields "${conflict.responseName}" conflict because ${ |
| 482 | reasonMessage(conflict.reason) |
| 483 | }. Use different aliases on the fields to fetch both if this was intentional.` |
| 484 | ) |
| 485 | } |
| 486 | for (const selection of selectionSet.selections) { |
| 487 | switch (selection._tag) { |
| 488 | case "Field": { |
| 489 | this.checkDirectives(file, selection.directives, "FIELD") |
| 490 | this.validateField(file, selection, parent) |
| 491 | break |
| 492 | } |
| 493 | case "InlineFragment": { |
| 494 | this.checkDirectives(file, selection.directives, "INLINE_FRAGMENT") |
| 495 | if (selection.typeCondition === undefined) { |
| 496 | this.validateSelectionSet(file, selection.selectionSet, parent) |
| 497 | break |
| 498 | } |
| 499 | const type = this.typeCondition( |
| 500 | file, |
| 501 | selection.typeCondition, |
| 502 | (name) => `Fragment cannot condition on non composite type "${name}".` |
| 503 | ) |
| 504 | if (type === undefined) break |
| 505 | if (!this.overlaps(parent, type)) { |
| 506 | this.report( |
| 507 | file, |
| 508 | selection.loc.start, |
| 509 | `Fragment cannot be spread here as objects of type "${parent.name}" can never be of type "${type.name}".` |
| 510 | ) |
| 511 | } |
| 512 | this.validateSelectionSet(file, selection.selectionSet, type) |
| 513 | break |
| 514 | } |
| 515 | case "FragmentSpread": { |
| 516 | this.checkDirectives(file, selection.directives, "FRAGMENT_SPREAD") |
| 517 | const fragment = this.fragments.get(selection.name.value)?.node |
| 518 | if (fragment === undefined) { |
| 519 | this.report(file, selection.name.loc.start, `Unknown fragment "${selection.name.value}".`) |
| 520 | break |
| 521 | } |
| 522 | // Unknown and non-composite type conditions are reported on the fragment definition. |
| 523 | const type = this.composite(fragment.typeCondition.name.value) |
| 524 | if (type !== undefined && !this.overlaps(parent, type)) { |
| 525 | this.report( |
| 526 | file, |
| 527 | selection.loc.start, |
| 528 | `Fragment "${fragment.name.value}" cannot be spread here as objects of type "${parent.name}" can never be of type "${type.name}".` |
| 529 | ) |
| 530 | } |
| 531 | break |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | validateField(file: number, field: Ast.Field, parent: Composite): void { |
| 538 | const name = field.name.value |
| 539 | const definition = fieldOf(parent, name) |
| 540 | if (definition === undefined) { |
| 541 | this.report(file, field.loc.start, `Cannot query field "${name}" on type "${parent.name}".`) |
| 542 | return |
| 543 | } |
| 544 | |
| 545 | this.checkUniqueArguments(file, field.arguments) |
| 546 | for (const argument of field.arguments) { |
| 547 | const argumentDefinition = definition.arguments.find((candidate) => candidate.name === argument.name.value) |
| 548 | if (argumentDefinition === undefined) { |
| 549 | this.report( |
| 550 | file, |
| 551 | argument.loc.start, |
| 552 | `Unknown argument "${argument.name.value}" on field "${parent.name}.${name}".` |
| 553 | ) |
| 554 | } else { |
| 555 | this.checkValue(file, argument.value, argumentDefinition.type, argumentDefinition.defaultValue !== undefined) |
| 556 | } |
| 557 | } |
| 558 | for (const argument of definition.arguments) { |
| 559 | if ( |
| 560 | argument.type._tag === "NonNullTypeRef" && |
| 561 | argument.defaultValue === undefined && |
| 562 | !field.arguments.some((candidate) => candidate.name.value === argument.name) |
| 563 | ) { |
| 564 | this.report( |
| 565 | file, |
| 566 | field.loc.start, |
| 567 | `Field "${name}" argument "${argument.name}" of type "${ |
| 568 | SchemaModel.printTypeRef(argument.type) |
| 569 | }" is required, but it was not provided.` |
| 570 | ) |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | const typeName = SchemaModel.namedTypeOf(definition.type) |
| 575 | const type = this.schema.types.get(typeName) |
| 576 | if (type === undefined) { |
| 577 | // The schema reader accepts references to undefined types; the emitter can't type such a field. |
| 578 | this.report(file, field.loc.start, `Unknown type "${typeName}".`) |
| 579 | return |
| 580 | } |
| 581 | const printed = SchemaModel.printTypeRef(definition.type) |
| 582 | if (!isComposite(type)) { |
| 583 | if (field.selectionSet !== undefined) { |
| 584 | this.report( |
| 585 | file, |
| 586 | field.selectionSet.loc.start, |
| 587 | `Field "${name}" must not have a selection since type "${printed}" has no subfields.` |
| 588 | ) |
| 589 | } |
| 590 | } else if (field.selectionSet === undefined) { |
| 591 | this.report( |
| 592 | file, |
| 593 | field.loc.start, |
| 594 | `Field "${name}" of type "${printed}" must have a selection of subfields. Did you mean "${name} { ... }"?` |
| 595 | ) |
| 596 | } else { |
| 597 | this.validateSelectionSet(file, field.selectionSet, type) |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | /** The composite type named `name`, if there is one. */ |
| 602 | composite(name: string | undefined): Composite | undefined { |
| 603 | const type = name === undefined ? undefined : this.schema.types.get(name) |
| 604 | return type !== undefined && isComposite(type) ? type : undefined |
| 605 | } |
| 606 | |
| 607 | /** Resolves a type condition, reporting unknown and non-composite types. */ |
| 608 | typeCondition( |
| 609 | file: number, |
| 610 | condition: Ast.NamedType, |
| 611 | nonComposite: (name: string) => string |
| 612 | ): Composite | undefined { |
| 613 | const type = this.schema.types.get(condition.name.value) |
| 614 | if (type === undefined) { |
| 615 | this.report(file, condition.loc.start, `Unknown type "${condition.name.value}".`) |
| 616 | return undefined |
| 617 | } |
| 618 | if (!isComposite(type)) { |
| 619 | this.report(file, condition.loc.start, nonComposite(condition.name.value)) |
| 620 | return undefined |
| 621 | } |
| 622 | return type |
| 623 | } |
| 624 | |
| 625 | /** Whether some object type can be both `a` and `b`; a type always overlaps itself, as in graphql-js. */ |
| 626 | overlaps(a: Composite, b: Composite): boolean { |
| 627 | if (a.name === b.name) return true |
| 628 | const names = new Set(possibleTypes(a)) |
| 629 | return possibleTypes(b).some((name) => names.has(name)) |
| 630 | } |
| 631 | |
| 632 | // Directives, arguments and values |
| 633 | |
| 634 | /** |
| 635 | * Checks `@skip` and `@include`: allowed locations, once per location, and |
| 636 | * their required `if: Boolean!`. Other directives are not checked. |
| 637 | */ |
| 638 | checkDirectives( |
| 639 | file: number, |
| 640 | directives: ReadonlyArray<Ast.Directive | Ast.ConstDirective>, |
| 641 | location: DirectiveLocation |
| 642 | ): void { |
| 643 | const conditions = directives.filter((directive) => conditionDirectives.has(directive.name.value)) |
| 644 | for (const directive of repeated(conditions, (directive) => directive.name.value)) { |
| 645 | this.report( |
| 646 | file, |
| 647 | directive.loc.start, |
| 648 | `The directive "@${directive.name.value}" can only be used once at this location.` |
| 649 | ) |
| 650 | } |
| 651 | for (const directive of conditions) { |
| 652 | const name = directive.name.value |
| 653 | if (!conditionLocations.has(location)) { |
| 654 | this.report(file, directive.loc.start, `Directive "@${name}" may not be used on ${location}.`) |
| 655 | } |
| 656 | this.checkUniqueArguments(file, directive.arguments) |
| 657 | for (const argument of directive.arguments) { |
| 658 | if (argument.name.value === "if") { |
| 659 | this.checkValue(file, argument.value, booleanNonNull) |
| 660 | } else { |
| 661 | this.report(file, argument.loc.start, `Unknown argument "${argument.name.value}" on directive "@${name}".`) |
| 662 | } |
| 663 | } |
| 664 | if (!directive.arguments.some((argument) => argument.name.value === "if")) { |
| 665 | this.report( |
| 666 | file, |
| 667 | directive.loc.start, |
| 668 | `Directive "@${name}" argument "if" of type "Boolean!" is required, but it was not provided.` |
| 669 | ) |
| 670 | } |
| 671 | } |
| 672 | } |
| 673 | |
| 674 | checkUniqueArguments(file: number, args: ReadonlyArray<Ast.Argument | Ast.ConstArgument>): void { |
| 675 | for (const argument of repeated(args, (argument) => argument.name.value)) { |
| 676 | this.report(file, argument.loc.start, `There can be only one argument named "${argument.name.value}".`) |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | /** |
| 681 | * Checks a literal against an input type, as graphql-js's ValuesOfCorrectType |
| 682 | * does without its suggestions. Variables are recorded in `positions` and |
| 683 | * checked by `checkVariables` instead; `hasDefault` is whether the argument |
| 684 | * or input field has a default value. Custom scalars accept any literal, and |
| 685 | * `Int` literals are not range checked. |
| 686 | */ |
| 687 | checkValue(file: number, value: Ast.Value | Ast.ConstValue, type: SchemaModel.TypeRef, hasDefault = false): void { |
| 688 | if (value._tag === "Variable") { |
| 689 | this.positions?.push({ file, node: value, type, hasDefault }) |
| 690 | return |
| 691 | } |
| 692 | if (value._tag === "NullValue") { |
| 693 | if (type._tag === "NonNullTypeRef") { |
| 694 | this.report( |
| 695 | file, |
| 696 | value.loc.start, |
| 697 | `Expected value of type "${SchemaModel.printTypeRef(type)}", found null.` |
| 698 | ) |
| 699 | } |
| 700 | return |
| 701 | } |
| 702 | if (type._tag === "NonNullTypeRef") return this.checkValue(file, value, type.ofType) |
| 703 | if (type._tag === "ListTypeRef") { |
| 704 | if (value._tag === "ListValue") { |
| 705 | for (const item of value.values) this.checkValue(file, item, type.ofType) |
| 706 | } else { |
| 707 | this.checkValue(file, value, type.ofType) |
| 708 | } |
| 709 | return |
| 710 | } |
| 711 | const named = this.schema.types.get(type.name) |
| 712 | if (named === undefined) return |
| 713 | const invalid = (message: string) => this.report(file, value.loc.start, message) |
| 714 | switch (named._tag) { |
| 715 | case "InputObjectType": { |
| 716 | if (value._tag !== "ObjectValue") { |
| 717 | return invalid(`Expected value of type "${named.name}", found ${printValue(value)}.`) |
| 718 | } |
| 719 | for (const field of repeated(value.fields, (field) => field.name.value)) { |
| 720 | this.report(file, field.loc.start, `There can be only one input field named "${field.name.value}".`) |
| 721 | } |
| 722 | for (const field of value.fields) { |
| 723 | const definition = named.fields.find((candidate) => candidate.name === field.name.value) |
| 724 | if (definition === undefined) { |
| 725 | this.report(file, field.loc.start, `Field "${field.name.value}" is not defined by type "${named.name}".`) |
| 726 | } else { |
| 727 | this.checkValue(file, field.value, definition.type, definition.defaultValue !== undefined) |
| 728 | } |
| 729 | } |
| 730 | if (named.oneOf) { |
| 731 | if (value.fields.length !== 1) { |
| 732 | invalid(`OneOf Input Object "${named.name}" must specify exactly one key.`) |
| 733 | } else if (value.fields[0]!.value._tag === "NullValue") { |
| 734 | invalid(`Field "${named.name}.${value.fields[0]!.name.value}" must be non-null.`) |
| 735 | } |
| 736 | return |
| 737 | } |
| 738 | for (const field of named.fields) { |
| 739 | if ( |
| 740 | field.type._tag === "NonNullTypeRef" && field.defaultValue === undefined && |
| 741 | !value.fields.some((candidate) => candidate.name.value === field.name) |
| 742 | ) { |
| 743 | invalid( |
| 744 | `Field "${named.name}.${field.name}" of required type "${ |
| 745 | SchemaModel.printTypeRef(field.type) |
| 746 | }" was not provided.` |
| 747 | ) |
| 748 | } |
| 749 | } |
| 750 | return |
| 751 | } |
| 752 | case "EnumType": { |
| 753 | if (value._tag !== "EnumValue") { |
| 754 | return invalid(`Enum "${named.name}" cannot represent non-enum value: ${printValue(value)}.`) |
| 755 | } |
| 756 | if (!named.values.some((candidate) => candidate.name === value.value)) { |
| 757 | invalid(`Value "${value.value}" does not exist in "${named.name}" enum.`) |
| 758 | } |
| 759 | return |
| 760 | } |
| 761 | case "ScalarType": { |
| 762 | const printed = printValue(value) |
| 763 | switch (named.name) { |
| 764 | case "Int": |
| 765 | if (value._tag !== "IntValue") invalid(`Int cannot represent non-integer value: ${printed}`) |
| 766 | return |
| 767 | case "Float": |
| 768 | if (value._tag !== "IntValue" && value._tag !== "FloatValue") { |
| 769 | invalid(`Float cannot represent non numeric value: ${printed}`) |
| 770 | } |
| 771 | return |
| 772 | case "String": |
| 773 | if (value._tag !== "StringValue") invalid(`String cannot represent a non string value: ${printed}`) |
| 774 | return |
| 775 | case "Boolean": |
| 776 | if (value._tag !== "BooleanValue") invalid(`Boolean cannot represent a non boolean value: ${printed}`) |
| 777 | return |
| 778 | case "ID": |
| 779 | if (value._tag !== "StringValue" && value._tag !== "IntValue") { |
| 780 | invalid(`ID cannot represent a non-string and non-integer value: ${printed}`) |
| 781 | } |
| 782 | return |
| 783 | } |
| 784 | return |
| 785 | } |
| 786 | } |
| 787 | } |
| 788 | |
| 789 | // Variable positions |
| 790 | |
| 791 | /** |
| 792 | * graphql-js's allowed-variable-usage rule: a nullable variable may fill a |
| 793 | * non-null position when the variable or the position has a non-null |
| 794 | * default. |
| 795 | */ |
| 796 | allowedPosition(variable: Ast.VariableDefinition, usage: VariableUsage): boolean { |
| 797 | const variableType = SchemaModel.fromAstType(variable.type) |
| 798 | if (usage.type._tag === "NonNullTypeRef" && variableType._tag !== "NonNullTypeRef") { |
| 799 | const hasNonNullDefault = variable.defaultValue !== undefined && variable.defaultValue._tag !== "NullValue" |
| 800 | if (!hasNonNullDefault && !usage.hasDefault) return false |
| 801 | return isSubType(variableType, usage.type.ofType) |
| 802 | } |
| 803 | return isSubType(variableType, usage.type) |
| 804 | } |
| 805 | |
| 806 | // Overlapping fields |
| 807 | |
| 808 | /** |
| 809 | * graphql-js's OverlappingFieldsCanBeMerged: fields sharing a response key, |
| 810 | * collected through inline fragments and fragment spreads, must be the same |
| 811 | * field with the same arguments unless their parents are distinct object |
| 812 | * types, must return compatible shapes, and must have mergeable |
| 813 | * subselections. |
| 814 | */ |
| 815 | conflictsWithin(file: number, selectionSet: Ast.SelectionSet, parent: Composite): Array<Conflict> { |
| 816 | const conflicts: Array<Conflict> = [] |
| 817 | const { fields, fragments } = this.collectFields(file, selectionSet, parent) |
| 818 | for (const [responseName, entries] of fields) { |
| 819 | for (let i = 0; i < entries.length; i++) { |
| 820 | for (let j = i + 1; j < entries.length; j++) { |
| 821 | const conflict = this.findConflict(false, responseName, entries[i]!, entries[j]!) |
| 822 | if (conflict !== undefined) conflicts.push(conflict) |
| 823 | } |
| 824 | } |
| 825 | } |
| 826 | for (let i = 0; i < fragments.length; i++) { |
| 827 | this.conflictsWithFragment(conflicts, false, fields, fragments[i]!) |
| 828 | for (let j = i + 1; j < fragments.length; j++) { |
| 829 | this.conflictsBetweenFragments(conflicts, false, fragments[i]!, fragments[j]!) |
| 830 | } |
| 831 | } |
| 832 | return conflicts |
| 833 | } |
| 834 | |
| 835 | collectFields(file: number, selectionSet: Ast.SelectionSet, parent: Composite | undefined): CollectedFields { |
| 836 | const cached = this.collected.get(selectionSet) |
| 837 | if (cached !== undefined) return cached |
| 838 | const fields = new Map<string, Array<FieldEntry>>() |
| 839 | const fragments: Array<string> = [] |
| 840 | const visit = (set: Ast.SelectionSet, parent: Composite | undefined): void => { |
| 841 | for (const selection of set.selections) { |
| 842 | if (selection._tag === "Field") { |
| 843 | const key = (selection.alias ?? selection.name).value |
| 844 | const entry: FieldEntry = { |
| 845 | file, |
| 846 | parent, |
| 847 | node: selection, |
| 848 | definition: parent === undefined ? undefined : fieldOf(parent, selection.name.value) |
| 849 | } |
| 850 | const entries = fields.get(key) |
| 851 | if (entries === undefined) fields.set(key, [entry]) |
| 852 | else entries.push(entry) |
| 853 | } else if (selection._tag === "FragmentSpread") { |
| 854 | if (!fragments.includes(selection.name.value)) fragments.push(selection.name.value) |
| 855 | } else { |
| 856 | visit( |
| 857 | selection.selectionSet, |
| 858 | selection.typeCondition === undefined ? parent : this.composite(selection.typeCondition.name.value) |
| 859 | ) |
| 860 | } |
| 861 | } |
| 862 | } |
| 863 | visit(selectionSet, parent) |
| 864 | const collected = { fields, fragments } |
| 865 | this.collected.set(selectionSet, collected) |
| 866 | return collected |
| 867 | } |
| 868 | |
| 869 | fragmentFields(name: string): CollectedFields | undefined { |
| 870 | const fragment = this.fragments.get(name) |
| 871 | if (fragment === undefined) return undefined |
| 872 | return this.collectFields( |
| 873 | fragment.file, |
| 874 | fragment.node.selectionSet, |
| 875 | this.composite(fragment.node.typeCondition.name.value) |
| 876 | ) |
| 877 | } |
| 878 | |
| 879 | conflictsBetween( |
| 880 | conflicts: Array<Conflict>, |
| 881 | exclusive: boolean, |
| 882 | fields1: CollectedFields["fields"], |
| 883 | fields2: CollectedFields["fields"] |
| 884 | ): void { |
| 885 | for (const [responseName, entries1] of fields1) { |
| 886 | const entries2 = fields2.get(responseName) |
| 887 | if (entries2 === undefined) continue |
| 888 | for (const entry1 of entries1) { |
| 889 | for (const entry2 of entries2) { |
| 890 | const conflict = this.findConflict(exclusive, responseName, entry1, entry2) |
| 891 | if (conflict !== undefined) conflicts.push(conflict) |
| 892 | } |
| 893 | } |
| 894 | } |
| 895 | } |
| 896 | |
| 897 | conflictsWithFragment( |
| 898 | conflicts: Array<Conflict>, |
| 899 | exclusive: boolean, |
| 900 | fields: CollectedFields["fields"], |
| 901 | fragmentName: string |
| 902 | ): void { |
| 903 | let compared = this.comparedFieldsAndFragments.get(fields) |
| 904 | if (compared === undefined) { |
| 905 | compared = new Map() |
| 906 | this.comparedFieldsAndFragments.set(fields, compared) |
| 907 | } |
| 908 | if (!firstComparison(compared, fragmentName, exclusive)) return |
| 909 | const fragment = this.fragmentFields(fragmentName) |
| 910 | if (fragment === undefined || fragment.fields === fields) return |
| 911 | this.conflictsBetween(conflicts, exclusive, fields, fragment.fields) |
| 912 | for (const nested of fragment.fragments) this.conflictsWithFragment(conflicts, exclusive, fields, nested) |
| 913 | } |
| 914 | |
| 915 | conflictsBetweenFragments(conflicts: Array<Conflict>, exclusive: boolean, name1: string, name2: string): void { |
| 916 | if (name1 === name2) return |
| 917 | const key = name1 < name2 ? `${name1}\u0000${name2}` : `${name2}\u0000${name1}` |
| 918 | if (!firstComparison(this.comparedFragments, key, exclusive)) return |
| 919 | const fragment1 = this.fragmentFields(name1) |
| 920 | const fragment2 = this.fragmentFields(name2) |
| 921 | if (fragment1 === undefined || fragment2 === undefined) return |
| 922 | this.conflictsBetween(conflicts, exclusive, fragment1.fields, fragment2.fields) |
| 923 | for (const nested of fragment2.fragments) this.conflictsBetweenFragments(conflicts, exclusive, name1, nested) |
| 924 | for (const nested of fragment1.fragments) this.conflictsBetweenFragments(conflicts, exclusive, nested, name2) |
| 925 | } |
| 926 | |
| 927 | findConflict( |
| 928 | parentsExclusive: boolean, |
| 929 | responseName: string, |
| 930 | entry1: FieldEntry, |
| 931 | entry2: FieldEntry |
| 932 | ): Conflict | undefined { |
| 933 | const exclusive = parentsExclusive || |
| 934 | (entry1.parent !== undefined && entry2.parent !== undefined && entry1.parent.name !== entry2.parent.name && |
| 935 | entry1.parent._tag === "ObjectType" && entry2.parent._tag === "ObjectType") |
| 936 | const conflict = (reason: Conflict["reason"]): Conflict => ({ |
| 937 | responseName, |
| 938 | reason, |
| 939 | file: entry2.file, |
| 940 | offset: entry2.node.loc.start |
| 941 | }) |
| 942 | const name1 = entry1.node.name.value |
| 943 | const name2 = entry2.node.name.value |
| 944 | if (!exclusive) { |
| 945 | if (name1 !== name2) return conflict(`"${name1}" and "${name2}" are different fields`) |
| 946 | if (!sameArguments(entry1.node.arguments, entry2.node.arguments)) { |
| 947 | return conflict("they have differing arguments") |
| 948 | } |
| 949 | } |
| 950 | const type1 = entry1.definition?.type |
| 951 | const type2 = entry2.definition?.type |
| 952 | if (type1 !== undefined && type2 !== undefined && this.typesConflict(type1, type2)) { |
| 953 | return conflict( |
| 954 | `they return conflicting types "${SchemaModel.printTypeRef(type1)}" and "${SchemaModel.printTypeRef(type2)}"` |
| 955 | ) |
| 956 | } |
| 957 | const set1 = entry1.node.selectionSet |
| 958 | const set2 = entry2.node.selectionSet |
| 959 | if (set1 === undefined || set2 === undefined) return undefined |
| 960 | const sub = this.conflictsBetweenSubselections( |
| 961 | exclusive, |
| 962 | entry1.file, |
| 963 | this.compositeOf(type1), |
| 964 | set1, |
| 965 | entry2.file, |
| 966 | this.compositeOf(type2), |
| 967 | set2 |
| 968 | ) |
| 969 | return sub.length > 0 ? conflict(sub) : undefined |
| 970 | } |
| 971 | |
| 972 | conflictsBetweenSubselections( |
| 973 | exclusive: boolean, |
| 974 | file1: number, |
| 975 | parent1: Composite | undefined, |
| 976 | set1: Ast.SelectionSet, |
| 977 | file2: number, |
| 978 | parent2: Composite | undefined, |
| 979 | set2: Ast.SelectionSet |
| 980 | ): Array<Conflict> { |
| 981 | const conflicts: Array<Conflict> = [] |
| 982 | const collected1 = this.collectFields(file1, set1, parent1) |
| 983 | const collected2 = this.collectFields(file2, set2, parent2) |
| 984 | this.conflictsBetween(conflicts, exclusive, collected1.fields, collected2.fields) |
| 985 | for (const name of collected2.fragments) { |
| 986 | this.conflictsWithFragment(conflicts, exclusive, collected1.fields, name) |
| 987 | } |
| 988 | for (const name of collected1.fragments) { |
| 989 | this.conflictsWithFragment(conflicts, exclusive, collected2.fields, name) |
| 990 | } |
| 991 | for (const name1 of collected1.fragments) { |
| 992 | for (const name2 of collected2.fragments) this.conflictsBetweenFragments(conflicts, exclusive, name1, name2) |
| 993 | } |
| 994 | return conflicts |
| 995 | } |
| 996 | |
| 997 | /** Whether two field types give different response shapes: list or null-ness, or different leaf types. */ |
| 998 | typesConflict(type1: SchemaModel.TypeRef, type2: SchemaModel.TypeRef): boolean { |
| 999 | if (type1._tag === "ListTypeRef") { |
| 1000 | return type2._tag === "ListTypeRef" ? this.typesConflict(type1.ofType, type2.ofType) : true |
| 1001 | } |
| 1002 | if (type2._tag === "ListTypeRef") return true |
| 1003 | if (type1._tag === "NonNullTypeRef") { |
| 1004 | return type2._tag === "NonNullTypeRef" ? this.typesConflict(type1.ofType, type2.ofType) : true |
| 1005 | } |
| 1006 | if (type2._tag === "NonNullTypeRef") return true |
| 1007 | const isLeaf = (name: string) => { |
| 1008 | const named = this.schema.types.get(name) |
| 1009 | return named !== undefined && !isComposite(named) |
| 1010 | } |
| 1011 | return (isLeaf(type1.name) || isLeaf(type2.name)) && type1.name !== type2.name |
| 1012 | } |
| 1013 | |
| 1014 | compositeOf(type: SchemaModel.TypeRef | undefined): Composite | undefined { |
| 1015 | return type === undefined ? undefined : this.composite(SchemaModel.namedTypeOf(type)) |
| 1016 | } |
| 1017 | |
| 1018 | // Fragments |
| 1019 | |
| 1020 | checkUnusedFragments(): void { |
| 1021 | const used = new Set( |
| 1022 | this.reachableFragments(this.operations.map((operation) => operation.node.selectionSet)) |
| 1023 | .map((fragment) => fragment.node.name.value) |
| 1024 | ) |
| 1025 | for (const { file, node: fragment } of this.fragmentList) { |
| 1026 | if (!used.has(fragment.name.value)) { |
| 1027 | this.report(file, fragment.loc.start, `Fragment "${fragment.name.value}" is never used.`) |
| 1028 | } |
| 1029 | } |
| 1030 | } |
| 1031 | |
| 1032 | /** |
| 1033 | * Depth-first search from each fragment in file and document order, |
| 1034 | * reporting each cycle once at the first spread on its path (as graphql-js's |
| 1035 | * NoFragmentCycles rule does), in the file holding that spread. |
| 1036 | */ |
| 1037 | checkFragmentCycles(): void { |
| 1038 | const visited = new Set<string>() |
| 1039 | const path: Array<Located<Ast.FragmentSpread>> = [] |
| 1040 | const indexOnPath = new Map<string, number>() |
| 1041 | const visit = ({ file, node: fragment }: Located<Ast.FragmentDefinition>): void => { |
| 1042 | const name = fragment.name.value |
| 1043 | if (visited.has(name)) return |
| 1044 | visited.add(name) |
| 1045 | const spreads = fragmentSpreads(fragment.selectionSet) |
| 1046 | if (spreads.length === 0) return |
| 1047 | indexOnPath.set(name, path.length) |
| 1048 | for (const spread of spreads) { |
| 1049 | const target = spread.name.value |
| 1050 | const cycleStart = indexOnPath.get(target) |
| 1051 | path.push({ node: spread, file }) |
| 1052 | if (cycleStart === undefined) { |
| 1053 | const next = this.fragments.get(target) |
| 1054 | if (next !== undefined) visit(next) |
| 1055 | } else { |
| 1056 | const cycle = path.slice(cycleStart) |
| 1057 | const via = cycle.slice(0, -1).map((step) => `"${step.node.name.value}"`).join(", ") |
| 1058 | this.report( |
| 1059 | cycle[0]!.file, |
| 1060 | cycle[0]!.node.loc.start, |
| 1061 | `Cannot spread fragment "${target}" within itself${via === "" ? "." : ` via ${via}.`}` |
| 1062 | ) |
| 1063 | } |
| 1064 | path.pop() |
| 1065 | } |
| 1066 | indexOnPath.delete(name) |
| 1067 | } |
| 1068 | for (const fragment of this.fragmentList) visit(fragment) |
| 1069 | } |
| 1070 | |
| 1071 | /** Operations and fragments share one namespace across every file: both become generated exports. */ |
| 1072 | checkUniqueNames(): void { |
| 1073 | const byName = new Map<string, Array<{ readonly kind: string; readonly file: number; readonly name: Ast.Name }>>() |
| 1074 | const add = (kind: string, file: number, name: Ast.Name | undefined): void => { |
| 1075 | if (name === undefined) return |
| 1076 | const entries = byName.get(name.value) |
| 1077 | if (entries === undefined) byName.set(name.value, [{ kind, file, name }]) |
| 1078 | else entries.push({ kind, file, name }) |
| 1079 | } |
| 1080 | for (const { file, node } of this.operations) add("operation", file, node.name) |
| 1081 | for (const { file, node } of this.fragmentList) add("fragment", file, node.name) |
| 1082 | for (const [name, entries] of byName) { |
| 1083 | if (entries.length < 2) continue |
| 1084 | const kind = entries.every((entry) => entry.kind === entries[0]!.kind) |
| 1085 | ? entries[0]!.kind |
| 1086 | : "operation or fragment" |
| 1087 | for (const entry of entries) { |
| 1088 | this.report(entry.file, entry.name.loc.start, `There can be only one ${kind} named "${name}".`) |
| 1089 | } |
| 1090 | } |
| 1091 | } |
| 1092 | } |
| 1093 | |
| 1094 | /** |
| 1095 | * How `@skip` / `@include` decide a selection: a literal condition is folded, |
| 1096 | * so the selection is dropped or the directive ignored, and a variable |
| 1097 | * condition makes it conditional. |
| 1098 | */ |
| 1099 | export const inclusion = (directives: ReadonlyArray<Ast.Directive>): "exclude" | "include" | "conditional" => { |
| 1100 | let result: "include" | "conditional" = "include" |
| 1101 | for (const directive of directives) { |
| 1102 | const name = directive.name.value |
| 1103 | if (name !== "skip" && name !== "include") continue |
| 1104 | const value = directive.arguments.find((argument) => argument.name.value === "if")?.value |
| 1105 | if (value?._tag === "BooleanValue") { |
| 1106 | if (value.value === (name === "skip")) return "exclude" |
| 1107 | } else { |
| 1108 | result = "conditional" |
| 1109 | } |
| 1110 | } |
| 1111 | return result |
| 1112 | } |
| 1113 | |
| 1114 | /** |
| 1115 | * Whether `key` is still to be compared as `exclusive`, recording that it now |
| 1116 | * is. A comparison that wasn't mutually exclusive covers both cases. |
| 1117 | */ |
| 1118 | const firstComparison = <K>(compared: Map<K, boolean>, key: K, exclusive: boolean): boolean => { |
| 1119 | const previous = compared.get(key) |
| 1120 | if (previous === false || previous === exclusive) return false |
| 1121 | compared.set(key, exclusive) |
| 1122 | return true |
| 1123 | } |
| 1124 | |
| 1125 | /** Whether a value of input type `sub` can be used where `sup` is expected. */ |
| 1126 | const isSubType = (sub: SchemaModel.TypeRef, sup: SchemaModel.TypeRef): boolean => { |
| 1127 | if (sup._tag === "NonNullTypeRef") return sub._tag === "NonNullTypeRef" && isSubType(sub.ofType, sup.ofType) |
| 1128 | if (sub._tag === "NonNullTypeRef") return isSubType(sub.ofType, sup) |
| 1129 | if (sup._tag === "ListTypeRef") return sub._tag === "ListTypeRef" && isSubType(sub.ofType, sup.ofType) |
| 1130 | if (sub._tag === "ListTypeRef") return false |
| 1131 | return sub.name === sup.name |
| 1132 | } |
| 1133 | |
| 1134 | /** Every fragment spread in a selection set, at any depth and in source order, without following spreads. */ |
| 1135 | export const fragmentSpreads = (selectionSet: Ast.SelectionSet): Array<Ast.FragmentSpread> => |
| 1136 | selectionSet.selections.flatMap((selection) => |
| 1137 | selection._tag === "FragmentSpread" |
| 1138 | ? [selection] |
| 1139 | : selection.selectionSet === undefined |
| 1140 | ? [] |
| 1141 | : fragmentSpreads(selection.selectionSet) |
| 1142 | ) |
| 1143 | |
| 1144 | /** Appends every variable referenced in `value`, in document order. */ |
| 1145 | const variablesInValue = (value: Ast.Value, out: Array<Ast.Variable>): void => { |
| 1146 | switch (value._tag) { |
| 1147 | case "Variable": |
| 1148 | out.push(value) |
| 1149 | break |
| 1150 | case "ListValue": |
| 1151 | for (const item of value.values) variablesInValue(item, out) |
| 1152 | break |
| 1153 | case "ObjectValue": |
| 1154 | for (const field of value.fields) variablesInValue(field.value, out) |
| 1155 | break |
| 1156 | } |
| 1157 | } |
| 1158 | |
| 1159 | const variablesInArguments = (args: ReadonlyArray<Ast.Argument>, out: Array<Ast.Variable>): void => { |
| 1160 | for (const argument of args) variablesInValue(argument.value, out) |
| 1161 | } |
| 1162 | |
| 1163 | const variablesInDirectives = (directives: ReadonlyArray<Ast.Directive>, out: Array<Ast.Variable>): void => { |
| 1164 | for (const directive of directives) variablesInArguments(directive.arguments, out) |
| 1165 | } |
| 1166 | |
| 1167 | /** Variables in arguments and directives at any depth, without following fragment spreads. */ |
| 1168 | const variablesInSelectionSet = (selectionSet: Ast.SelectionSet, out: Array<Ast.Variable>): void => { |
| 1169 | for (const selection of selectionSet.selections) { |
| 1170 | variablesInDirectives(selection.directives, out) |
| 1171 | if (selection._tag === "Field") variablesInArguments(selection.arguments, out) |
| 1172 | if (selection._tag !== "FragmentSpread" && selection.selectionSet !== undefined) { |
| 1173 | variablesInSelectionSet(selection.selectionSet, out) |
| 1174 | } |
| 1175 | } |
| 1176 | } |