@graphql-tools/executor 0.0.1-alpha-20221025014654-e3be5659

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.
Files changed (35) hide show
  1. package/README.md +3 -0
  2. package/cjs/execution/AccumulatorMap.js +21 -0
  3. package/cjs/execution/collectFields.js +114 -0
  4. package/cjs/execution/execute.js +792 -0
  5. package/cjs/execution/index.js +10 -0
  6. package/cjs/execution/mapAsyncIterator.js +53 -0
  7. package/cjs/execution/subscribe.js +164 -0
  8. package/cjs/execution/values.js +168 -0
  9. package/cjs/index.js +4 -0
  10. package/cjs/package.json +1 -0
  11. package/esm/execution/AccumulatorMap.js +17 -0
  12. package/esm/execution/collectFields.js +109 -0
  13. package/esm/execution/execute.js +779 -0
  14. package/esm/execution/index.js +5 -0
  15. package/esm/execution/mapAsyncIterator.js +49 -0
  16. package/esm/execution/subscribe.js +159 -0
  17. package/esm/execution/values.js +162 -0
  18. package/esm/index.js +1 -0
  19. package/package.json +58 -0
  20. package/typings/execution/AccumulatorMap.d.cts +7 -0
  21. package/typings/execution/AccumulatorMap.d.ts +7 -0
  22. package/typings/execution/collectFields.d.cts +27 -0
  23. package/typings/execution/collectFields.d.ts +27 -0
  24. package/typings/execution/execute.d.cts +196 -0
  25. package/typings/execution/execute.d.ts +196 -0
  26. package/typings/execution/index.d.cts +5 -0
  27. package/typings/execution/index.d.ts +5 -0
  28. package/typings/execution/mapAsyncIterator.d.cts +6 -0
  29. package/typings/execution/mapAsyncIterator.d.ts +6 -0
  30. package/typings/execution/subscribe.d.cts +56 -0
  31. package/typings/execution/subscribe.d.ts +56 -0
  32. package/typings/execution/values.d.cts +54 -0
  33. package/typings/execution/values.d.ts +54 -0
  34. package/typings/index.d.cts +1 -0
  35. package/typings/index.d.ts +1 -0
@@ -0,0 +1,779 @@
1
+ import { devAssert } from 'graphql/jsutils/devAssert.js';
2
+ import { inspect } from 'graphql/jsutils/inspect.js';
3
+ import { invariant } from 'graphql/jsutils/invariant.js';
4
+ import { isAsyncIterable } from 'graphql/jsutils/isAsyncIterable.js';
5
+ import { isIterableObject } from 'graphql/jsutils/isIterableObject.js';
6
+ import { isObjectLike } from 'graphql/jsutils/isObjectLike.js';
7
+ import { isPromise } from 'graphql/jsutils/isPromise.js';
8
+ import { memoize3 } from 'graphql/jsutils/memoize3.js';
9
+ import { addPath, pathToArray } from 'graphql/jsutils/Path.js';
10
+ import { promiseForObject } from 'graphql/jsutils/promiseForObject.js';
11
+ import { promiseReduce } from 'graphql/jsutils/promiseReduce.js';
12
+ import { locatedError, GraphQLError, OperationTypeNode, Kind, isAbstractType, isLeafType, isListType, isNonNullType, isObjectType, assertValidSchema, SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef, } from 'graphql';
13
+ import { collectFields, collectSubfields as _collectSubfields } from './collectFields.js';
14
+ import { mapAsyncIterator } from './mapAsyncIterator.js';
15
+ import { getArgumentValues, getVariableValues } from './values.js';
16
+ // This file contains a lot of such errors but we plan to refactor it anyway
17
+ // so just disable it for entire file.
18
+ /**
19
+ * A memoized collection of relevant subfields with regard to the return
20
+ * type. Memoizing ensures the subfields are not repeatedly calculated, which
21
+ * saves overhead when resolving lists of values.
22
+ */
23
+ const collectSubfields = memoize3((exeContext, returnType, fieldNodes) => _collectSubfields(exeContext.schema, exeContext.fragments, exeContext.variableValues, returnType, fieldNodes));
24
+ /**
25
+ * Implements the "Executing requests" section of the GraphQL specification.
26
+ *
27
+ * Returns either a synchronous ExecutionResult (if all encountered resolvers
28
+ * are synchronous), or a Promise of an ExecutionResult that will eventually be
29
+ * resolved and never rejected.
30
+ *
31
+ * If the arguments to this function do not result in a legal execution context,
32
+ * a GraphQLError will be thrown immediately explaining the invalid input.
33
+ */
34
+ export function execute(args) {
35
+ // If a valid execution context cannot be created due to incorrect arguments,
36
+ // a "Response" with only errors is returned.
37
+ const exeContext = buildExecutionContext(args);
38
+ // Return early errors if execution context failed.
39
+ if (!('schema' in exeContext)) {
40
+ return { errors: exeContext };
41
+ }
42
+ return executeImpl(exeContext);
43
+ }
44
+ function executeImpl(exeContext) {
45
+ // Return a Promise that will eventually resolve to the data described by
46
+ // The "Response" section of the GraphQL specification.
47
+ //
48
+ // If errors are encountered while executing a GraphQL field, only that
49
+ // field and its descendants will be omitted, and sibling fields will still
50
+ // be executed. An execution which encounters errors will still result in a
51
+ // resolved Promise.
52
+ //
53
+ // Errors from sub-fields of a NonNull type may propagate to the top level,
54
+ // at which point we still log the error and null the parent field, which
55
+ // in this case is the entire response.
56
+ try {
57
+ const result = executeOperation(exeContext);
58
+ if (isPromise(result)) {
59
+ return result.then(data => buildResponse(data, exeContext.errors), error => {
60
+ exeContext.errors.push(error);
61
+ return buildResponse(null, exeContext.errors);
62
+ });
63
+ }
64
+ return buildResponse(result, exeContext.errors);
65
+ }
66
+ catch (error) {
67
+ exeContext.errors.push(error);
68
+ return buildResponse(null, exeContext.errors);
69
+ }
70
+ }
71
+ /**
72
+ * Also implements the "Executing requests" section of the GraphQL specification.
73
+ * However, it guarantees to complete synchronously (or throw an error) assuming
74
+ * that all field resolvers are also synchronous.
75
+ */
76
+ export function executeSync(args) {
77
+ const result = execute(args);
78
+ // Assert that the execution was synchronous.
79
+ if (isPromise(result)) {
80
+ throw new Error('GraphQL execution failed to complete synchronously.');
81
+ }
82
+ return result;
83
+ }
84
+ /**
85
+ * Given a completed execution context and data, build the `{ errors, data }`
86
+ * response defined by the "Response" section of the GraphQL specification.
87
+ */
88
+ function buildResponse(data, errors) {
89
+ return errors.length === 0 ? { data } : { errors, data };
90
+ }
91
+ /**
92
+ * Essential assertions before executing to provide developer feedback for
93
+ * improper use of the GraphQL library.
94
+ *
95
+ * @internal
96
+ */
97
+ export function assertValidExecutionArguments(schema, document, rawVariableValues) {
98
+ devAssert(!!document, 'Must provide document.');
99
+ // If the schema used for execution is invalid, throw an error.
100
+ assertValidSchema(schema);
101
+ // Variables, if provided, must be an object.
102
+ devAssert(rawVariableValues == null || isObjectLike(rawVariableValues), 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.');
103
+ }
104
+ /**
105
+ * Constructs a ExecutionContext object from the arguments passed to
106
+ * execute, which we will pass throughout the other execution methods.
107
+ *
108
+ * Throws a GraphQLError if a valid execution context cannot be created.
109
+ *
110
+ * TODO: consider no longer exporting this function
111
+ * @internal
112
+ */
113
+ export function buildExecutionContext(args) {
114
+ var _a, _b;
115
+ const { schema, document, rootValue, contextValue, variableValues: rawVariableValues, operationName, fieldResolver, typeResolver, subscribeFieldResolver, } = args;
116
+ // If the schema used for execution is invalid, throw an error.
117
+ assertValidSchema(schema);
118
+ let operation;
119
+ const fragments = Object.create(null);
120
+ for (const definition of document.definitions) {
121
+ switch (definition.kind) {
122
+ case Kind.OPERATION_DEFINITION:
123
+ if (operationName == null) {
124
+ if (operation !== undefined) {
125
+ return [new GraphQLError('Must provide operation name if query contains multiple operations.')];
126
+ }
127
+ operation = definition;
128
+ }
129
+ else if (((_a = definition.name) === null || _a === void 0 ? void 0 : _a.value) === operationName) {
130
+ operation = definition;
131
+ }
132
+ break;
133
+ case Kind.FRAGMENT_DEFINITION:
134
+ fragments[definition.name.value] = definition;
135
+ break;
136
+ default:
137
+ // ignore non-executable definitions
138
+ }
139
+ }
140
+ if (!operation) {
141
+ if (operationName != null) {
142
+ return [new GraphQLError(`Unknown operation named "${operationName}".`)];
143
+ }
144
+ return [new GraphQLError('Must provide an operation.')];
145
+ }
146
+ // FIXME: https://github.com/graphql/graphql-js/issues/2203
147
+ /* c8 ignore next */
148
+ const variableDefinitions = (_b = operation.variableDefinitions) !== null && _b !== void 0 ? _b : [];
149
+ const coercedVariableValues = getVariableValues(schema, variableDefinitions, rawVariableValues !== null && rawVariableValues !== void 0 ? rawVariableValues : {}, {
150
+ maxErrors: 50,
151
+ });
152
+ if (coercedVariableValues.errors) {
153
+ return coercedVariableValues.errors;
154
+ }
155
+ return {
156
+ schema,
157
+ fragments,
158
+ rootValue,
159
+ contextValue,
160
+ operation,
161
+ variableValues: coercedVariableValues.coerced,
162
+ fieldResolver: fieldResolver !== null && fieldResolver !== void 0 ? fieldResolver : defaultFieldResolver,
163
+ typeResolver: typeResolver !== null && typeResolver !== void 0 ? typeResolver : defaultTypeResolver,
164
+ subscribeFieldResolver: subscribeFieldResolver !== null && subscribeFieldResolver !== void 0 ? subscribeFieldResolver : defaultFieldResolver,
165
+ errors: [],
166
+ };
167
+ }
168
+ function buildPerEventExecutionContext(exeContext, payload) {
169
+ return {
170
+ ...exeContext,
171
+ rootValue: payload,
172
+ errors: [],
173
+ };
174
+ }
175
+ /**
176
+ * Implements the "Executing operations" section of the spec.
177
+ */
178
+ function executeOperation(exeContext) {
179
+ const { operation, schema, fragments, variableValues, rootValue } = exeContext;
180
+ const rootType = schema.getRootType(operation.operation);
181
+ if (rootType == null) {
182
+ throw new GraphQLError(`Schema is not configured to execute ${operation.operation} operation.`, {
183
+ nodes: operation,
184
+ });
185
+ }
186
+ const rootFields = collectFields(schema, fragments, variableValues, rootType, operation.selectionSet);
187
+ const path = undefined;
188
+ switch (operation.operation) {
189
+ case OperationTypeNode.QUERY:
190
+ return executeFields(exeContext, rootType, rootValue, path, rootFields);
191
+ case OperationTypeNode.MUTATION:
192
+ return executeFieldsSerially(exeContext, rootType, rootValue, path, rootFields);
193
+ case OperationTypeNode.SUBSCRIPTION:
194
+ // TODO: deprecate `subscribe` and move all logic here
195
+ // Temporary solution until we finish merging execute and subscribe together
196
+ return executeFields(exeContext, rootType, rootValue, path, rootFields);
197
+ }
198
+ }
199
+ /**
200
+ * Implements the "Executing selection sets" section of the spec
201
+ * for fields that must be executed serially.
202
+ */
203
+ function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) {
204
+ return promiseReduce(fields.entries(), (results, [responseName, fieldNodes]) => {
205
+ const fieldPath = addPath(path, responseName, parentType.name);
206
+ const result = executeField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
207
+ if (result === undefined) {
208
+ return results;
209
+ }
210
+ if (isPromise(result)) {
211
+ return result.then(resolvedResult => {
212
+ results[responseName] = resolvedResult;
213
+ return results;
214
+ });
215
+ }
216
+ results[responseName] = result;
217
+ return results;
218
+ }, Object.create(null));
219
+ }
220
+ /**
221
+ * Implements the "Executing selection sets" section of the spec
222
+ * for fields that may be executed in parallel.
223
+ */
224
+ function executeFields(exeContext, parentType, sourceValue, path, fields) {
225
+ const results = Object.create(null);
226
+ let containsPromise = false;
227
+ for (const [responseName, fieldNodes] of fields.entries()) {
228
+ const fieldPath = addPath(path, responseName, parentType.name);
229
+ const result = executeField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
230
+ if (result !== undefined) {
231
+ results[responseName] = result;
232
+ if (isPromise(result)) {
233
+ containsPromise = true;
234
+ }
235
+ }
236
+ }
237
+ // If there are no promises, we can just return the object
238
+ if (!containsPromise) {
239
+ return results;
240
+ }
241
+ // Otherwise, results is a map from field name to the result of resolving that
242
+ // field, which is possibly a promise. Return a promise that will return this
243
+ // same map, but with any promises replaced with the values they resolved to.
244
+ return promiseForObject(results);
245
+ }
246
+ /**
247
+ * Implements the "Executing fields" section of the spec
248
+ * In particular, this function figures out the value that the field returns by
249
+ * calling its resolve function, then calls completeValue to complete promises,
250
+ * serialize scalars, or execute the sub-selection-set for objects.
251
+ */
252
+ function executeField(exeContext, parentType, source, fieldNodes, path) {
253
+ var _a;
254
+ const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]);
255
+ if (!fieldDef) {
256
+ return;
257
+ }
258
+ const returnType = fieldDef.type;
259
+ const resolveFn = (_a = fieldDef.resolve) !== null && _a !== void 0 ? _a : exeContext.fieldResolver;
260
+ const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path);
261
+ // Get the resolve function, regardless of if its result is normal or abrupt (error).
262
+ try {
263
+ // Build a JS object of arguments from the field.arguments AST, using the
264
+ // variables scope to fulfill any variable references.
265
+ // TODO: find a way to memoize, in case this field is within a List type.
266
+ const args = getArgumentValues(fieldDef, fieldNodes[0], exeContext.variableValues);
267
+ // The resolve function's optional third argument is a context value that
268
+ // is provided to every resolve function within an execution. It is commonly
269
+ // used to represent an authenticated user, or request-specific caches.
270
+ const contextValue = exeContext.contextValue;
271
+ const result = resolveFn(source, args, contextValue, info);
272
+ let completed;
273
+ if (isPromise(result)) {
274
+ completed = result.then(resolved => completeValue(exeContext, returnType, fieldNodes, info, path, resolved));
275
+ }
276
+ else {
277
+ completed = completeValue(exeContext, returnType, fieldNodes, info, path, result);
278
+ }
279
+ if (isPromise(completed)) {
280
+ // Note: we don't rely on a `catch` method, but we do expect "thenable"
281
+ // to take a second callback for the error case.
282
+ return completed.then(undefined, rawError => {
283
+ const error = locatedError(rawError, fieldNodes, pathToArray(path));
284
+ return handleFieldError(error, returnType, exeContext);
285
+ });
286
+ }
287
+ return completed;
288
+ }
289
+ catch (rawError) {
290
+ const error = locatedError(rawError, fieldNodes, pathToArray(path));
291
+ return handleFieldError(error, returnType, exeContext);
292
+ }
293
+ }
294
+ /**
295
+ * TODO: consider no longer exporting this function
296
+ * @internal
297
+ */
298
+ export function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) {
299
+ // The resolve function's optional fourth argument is a collection of
300
+ // information about the current execution state.
301
+ return {
302
+ fieldName: fieldDef.name,
303
+ fieldNodes,
304
+ returnType: fieldDef.type,
305
+ parentType,
306
+ path,
307
+ schema: exeContext.schema,
308
+ fragments: exeContext.fragments,
309
+ rootValue: exeContext.rootValue,
310
+ operation: exeContext.operation,
311
+ variableValues: exeContext.variableValues,
312
+ };
313
+ }
314
+ function handleFieldError(error, returnType, exeContext) {
315
+ // If the field type is non-nullable, then it is resolved without any
316
+ // protection from errors, however it still properly locates the error.
317
+ if (isNonNullType(returnType)) {
318
+ throw error;
319
+ }
320
+ // Otherwise, error protection is applied, logging the error and resolving
321
+ // a null value for this field if one is encountered.
322
+ exeContext.errors.push(error);
323
+ return null;
324
+ }
325
+ /**
326
+ * Implements the instructions for completeValue as defined in the
327
+ * "Value Completion" section of the spec.
328
+ *
329
+ * If the field type is Non-Null, then this recursively completes the value
330
+ * for the inner type. It throws a field error if that completion returns null,
331
+ * as per the "Nullability" section of the spec.
332
+ *
333
+ * If the field type is a List, then this recursively completes the value
334
+ * for the inner type on each item in the list.
335
+ *
336
+ * If the field type is a Scalar or Enum, ensures the completed value is a legal
337
+ * value of the type by calling the `serialize` method of GraphQL type
338
+ * definition.
339
+ *
340
+ * If the field is an abstract type, determine the runtime type of the value
341
+ * and then complete based on that type
342
+ *
343
+ * Otherwise, the field type expects a sub-selection set, and will complete the
344
+ * value by executing all sub-selections.
345
+ */
346
+ function completeValue(exeContext, returnType, fieldNodes, info, path, result) {
347
+ // If result is an Error, throw a located error.
348
+ if (result instanceof Error) {
349
+ throw result;
350
+ }
351
+ // If field type is NonNull, complete for inner type, and throw field error
352
+ // if result is null.
353
+ if (isNonNullType(returnType)) {
354
+ const completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result);
355
+ if (completed === null) {
356
+ throw new Error(`Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`);
357
+ }
358
+ return completed;
359
+ }
360
+ // If result value is null or undefined then return null.
361
+ if (result == null) {
362
+ return null;
363
+ }
364
+ // If field type is List, complete each item in the list with the inner type
365
+ if (isListType(returnType)) {
366
+ return completeListValue(exeContext, returnType, fieldNodes, info, path, result);
367
+ }
368
+ // If field type is a leaf type, Scalar or Enum, serialize to a valid value,
369
+ // returning null if serialization is not possible.
370
+ if (isLeafType(returnType)) {
371
+ return completeLeafValue(returnType, result);
372
+ }
373
+ // If field type is an abstract type, Interface or Union, determine the
374
+ // runtime Object type and complete for that type.
375
+ if (isAbstractType(returnType)) {
376
+ return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result);
377
+ }
378
+ // If field type is Object, execute and complete all sub-selections.
379
+ if (isObjectType(returnType)) {
380
+ return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result);
381
+ }
382
+ /* c8 ignore next 6 */
383
+ // Not reachable, all possible output types have been considered.
384
+ invariant(false, 'Cannot complete value of unexpected output type: ' + inspect(returnType));
385
+ }
386
+ /**
387
+ * Complete a async iterator value by completing the result and calling
388
+ * recursively until all the results are completed.
389
+ */
390
+ async function completeAsyncIteratorValue(exeContext, itemType, fieldNodes, info, path, iterator) {
391
+ let containsPromise = false;
392
+ const completedResults = [];
393
+ let index = 0;
394
+ while (true) {
395
+ const fieldPath = addPath(path, index, undefined);
396
+ try {
397
+ const { value, done } = await iterator.next();
398
+ if (done) {
399
+ break;
400
+ }
401
+ try {
402
+ // TODO can the error checking logic be consolidated with completeListValue?
403
+ const completedItem = completeValue(exeContext, itemType, fieldNodes, info, fieldPath, value);
404
+ if (isPromise(completedItem)) {
405
+ containsPromise = true;
406
+ }
407
+ completedResults.push(completedItem);
408
+ }
409
+ catch (rawError) {
410
+ completedResults.push(null);
411
+ const error = locatedError(rawError, fieldNodes, pathToArray(fieldPath));
412
+ handleFieldError(error, itemType, exeContext);
413
+ }
414
+ }
415
+ catch (rawError) {
416
+ completedResults.push(null);
417
+ const error = locatedError(rawError, fieldNodes, pathToArray(fieldPath));
418
+ handleFieldError(error, itemType, exeContext);
419
+ break;
420
+ }
421
+ index += 1;
422
+ }
423
+ return containsPromise ? Promise.all(completedResults) : completedResults;
424
+ }
425
+ /**
426
+ * Complete a list value by completing each item in the list with the
427
+ * inner type
428
+ */
429
+ function completeListValue(exeContext, returnType, fieldNodes, info, path, result) {
430
+ const itemType = returnType.ofType;
431
+ if (isAsyncIterable(result)) {
432
+ const iterator = result[Symbol.asyncIterator]();
433
+ return completeAsyncIteratorValue(exeContext, itemType, fieldNodes, info, path, iterator);
434
+ }
435
+ if (!isIterableObject(result)) {
436
+ throw new GraphQLError(`Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`);
437
+ }
438
+ // This is specified as a simple map, however we're optimizing the path
439
+ // where the list contains no Promises by avoiding creating another Promise.
440
+ let containsPromise = false;
441
+ const completedResults = Array.from(result, (item, index) => {
442
+ // No need to modify the info object containing the path,
443
+ // since from here on it is not ever accessed by resolver functions.
444
+ const itemPath = addPath(path, index, undefined);
445
+ try {
446
+ let completedItem;
447
+ if (isPromise(item)) {
448
+ completedItem = item.then(resolved => completeValue(exeContext, itemType, fieldNodes, info, itemPath, resolved));
449
+ }
450
+ else {
451
+ completedItem = completeValue(exeContext, itemType, fieldNodes, info, itemPath, item);
452
+ }
453
+ if (isPromise(completedItem)) {
454
+ containsPromise = true;
455
+ // Note: we don't rely on a `catch` method, but we do expect "thenable"
456
+ // to take a second callback for the error case.
457
+ return completedItem.then(undefined, rawError => {
458
+ const error = locatedError(rawError, fieldNodes, pathToArray(itemPath));
459
+ return handleFieldError(error, itemType, exeContext);
460
+ });
461
+ }
462
+ return completedItem;
463
+ }
464
+ catch (rawError) {
465
+ const error = locatedError(rawError, fieldNodes, pathToArray(itemPath));
466
+ return handleFieldError(error, itemType, exeContext);
467
+ }
468
+ });
469
+ return containsPromise ? Promise.all(completedResults) : completedResults;
470
+ }
471
+ /**
472
+ * Complete a Scalar or Enum by serializing to a valid value, returning
473
+ * null if serialization is not possible.
474
+ */
475
+ function completeLeafValue(returnType, result) {
476
+ const serializedResult = returnType.serialize(result);
477
+ if (serializedResult == null) {
478
+ throw new Error(`Expected \`${inspect(returnType)}.serialize(${inspect(result)})\` to ` +
479
+ `return non-nullable value, returned: ${inspect(serializedResult)}`);
480
+ }
481
+ return serializedResult;
482
+ }
483
+ /**
484
+ * Complete a value of an abstract type by determining the runtime object type
485
+ * of that value, then complete the value for that type.
486
+ */
487
+ function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) {
488
+ var _a;
489
+ const resolveTypeFn = (_a = returnType.resolveType) !== null && _a !== void 0 ? _a : exeContext.typeResolver;
490
+ const contextValue = exeContext.contextValue;
491
+ const runtimeType = resolveTypeFn(result, contextValue, info, returnType);
492
+ if (isPromise(runtimeType)) {
493
+ return runtimeType.then(resolvedRuntimeType => completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result));
494
+ }
495
+ return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
496
+ }
497
+ function ensureValidRuntimeType(runtimeTypeName, exeContext, returnType, fieldNodes, info, result) {
498
+ if (runtimeTypeName == null) {
499
+ throw new GraphQLError(`Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}". Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`, { nodes: fieldNodes });
500
+ }
501
+ // releases before 16.0.0 supported returning `GraphQLObjectType` from `resolveType`
502
+ // TODO: remove in 17.0.0 release
503
+ if (isObjectType(runtimeTypeName)) {
504
+ throw new GraphQLError('Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead.');
505
+ }
506
+ if (typeof runtimeTypeName !== 'string') {
507
+ throw new GraphQLError(`Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` +
508
+ `value ${inspect(result)}, received "${inspect(runtimeTypeName)}".`);
509
+ }
510
+ const runtimeType = exeContext.schema.getType(runtimeTypeName);
511
+ if (runtimeType == null) {
512
+ throw new GraphQLError(`Abstract type "${returnType.name}" was resolved to a type "${runtimeTypeName}" that does not exist inside the schema.`, { nodes: fieldNodes });
513
+ }
514
+ if (!isObjectType(runtimeType)) {
515
+ throw new GraphQLError(`Abstract type "${returnType.name}" was resolved to a non-object type "${runtimeTypeName}".`, { nodes: fieldNodes });
516
+ }
517
+ if (!exeContext.schema.isSubType(returnType, runtimeType)) {
518
+ throw new GraphQLError(`Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`, { nodes: fieldNodes });
519
+ }
520
+ return runtimeType;
521
+ }
522
+ /**
523
+ * Complete an Object value by executing all sub-selections.
524
+ */
525
+ function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) {
526
+ // Collect sub-fields to execute to complete this value.
527
+ const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes);
528
+ // If there is an isTypeOf predicate function, call it with the
529
+ // current result. If isTypeOf returns false, then raise an error rather
530
+ // than continuing execution.
531
+ if (returnType.isTypeOf) {
532
+ const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);
533
+ if (isPromise(isTypeOf)) {
534
+ return isTypeOf.then(resolvedIsTypeOf => {
535
+ if (!resolvedIsTypeOf) {
536
+ throw invalidReturnTypeError(returnType, result, fieldNodes);
537
+ }
538
+ return executeFields(exeContext, returnType, result, path, subFieldNodes);
539
+ });
540
+ }
541
+ if (!isTypeOf) {
542
+ throw invalidReturnTypeError(returnType, result, fieldNodes);
543
+ }
544
+ }
545
+ return executeFields(exeContext, returnType, result, path, subFieldNodes);
546
+ }
547
+ function invalidReturnTypeError(returnType, result, fieldNodes) {
548
+ return new GraphQLError(`Expected value of type "${returnType.name}" but got: ${inspect(result)}.`, {
549
+ nodes: fieldNodes,
550
+ });
551
+ }
552
+ /**
553
+ * If a resolveType function is not given, then a default resolve behavior is
554
+ * used which attempts two strategies:
555
+ *
556
+ * First, See if the provided value has a `__typename` field defined, if so, use
557
+ * that value as name of the resolved type.
558
+ *
559
+ * Otherwise, test each possible type for the abstract type by calling
560
+ * isTypeOf for the object being coerced, returning the first type that matches.
561
+ */
562
+ export const defaultTypeResolver = function (value, contextValue, info, abstractType) {
563
+ // First, look for `__typename`.
564
+ if (isObjectLike(value) && typeof value['__typename'] === 'string') {
565
+ return value['__typename'];
566
+ }
567
+ // Otherwise, test each possible type.
568
+ const possibleTypes = info.schema.getPossibleTypes(abstractType);
569
+ const promisedIsTypeOfResults = [];
570
+ for (let i = 0; i < possibleTypes.length; i++) {
571
+ const type = possibleTypes[i];
572
+ if (type.isTypeOf) {
573
+ const isTypeOfResult = type.isTypeOf(value, contextValue, info);
574
+ if (isPromise(isTypeOfResult)) {
575
+ promisedIsTypeOfResults[i] = isTypeOfResult;
576
+ }
577
+ else if (isTypeOfResult) {
578
+ return type.name;
579
+ }
580
+ }
581
+ }
582
+ if (promisedIsTypeOfResults.length) {
583
+ return Promise.all(promisedIsTypeOfResults).then(isTypeOfResults => {
584
+ for (let i = 0; i < isTypeOfResults.length; i++) {
585
+ if (isTypeOfResults[i]) {
586
+ return possibleTypes[i].name;
587
+ }
588
+ }
589
+ });
590
+ }
591
+ };
592
+ /**
593
+ * If a resolve function is not given, then a default resolve behavior is used
594
+ * which takes the property of the source object of the same name as the field
595
+ * and returns it as the result, or if it's a function, returns the result
596
+ * of calling that function while passing along args and context value.
597
+ */
598
+ export const defaultFieldResolver = function (source, args, contextValue, info) {
599
+ // ensure source is a value for which property access is acceptable.
600
+ if (isObjectLike(source) || typeof source === 'function') {
601
+ const property = source[info.fieldName];
602
+ if (typeof property === 'function') {
603
+ return source[info.fieldName](args, contextValue, info);
604
+ }
605
+ return property;
606
+ }
607
+ };
608
+ /**
609
+ * Implements the "Subscribe" algorithm described in the GraphQL specification.
610
+ *
611
+ * Returns a Promise which resolves to either an AsyncIterator (if successful)
612
+ * or an ExecutionResult (error). The promise will be rejected if the schema or
613
+ * other arguments to this function are invalid, or if the resolved event stream
614
+ * is not an async iterable.
615
+ *
616
+ * If the client-provided arguments to this function do not result in a
617
+ * compliant subscription, a GraphQL Response (ExecutionResult) with
618
+ * descriptive errors and no data will be returned.
619
+ *
620
+ * If the source stream could not be created due to faulty subscription
621
+ * resolver logic or underlying systems, the promise will resolve to a single
622
+ * ExecutionResult containing `errors` and no `data`.
623
+ *
624
+ * If the operation succeeded, the promise resolves to an AsyncIterator, which
625
+ * yields a stream of ExecutionResults representing the response stream.
626
+ *
627
+ * Accepts either an object with named arguments, or individual arguments.
628
+ */
629
+ export function subscribe(args) {
630
+ // If a valid execution context cannot be created due to incorrect arguments,
631
+ // a "Response" with only errors is returned.
632
+ const exeContext = buildExecutionContext(args);
633
+ // Return early errors if execution context failed.
634
+ if (!('schema' in exeContext)) {
635
+ return { errors: exeContext };
636
+ }
637
+ const resultOrStream = createSourceEventStreamImpl(exeContext);
638
+ if (isPromise(resultOrStream)) {
639
+ return resultOrStream.then(resolvedResultOrStream => mapSourceToResponse(exeContext, resolvedResultOrStream));
640
+ }
641
+ return mapSourceToResponse(exeContext, resultOrStream);
642
+ }
643
+ function mapSourceToResponse(exeContext, resultOrStream) {
644
+ if (!isAsyncIterable(resultOrStream)) {
645
+ return resultOrStream;
646
+ }
647
+ // For each payload yielded from a subscription, map it over the normal
648
+ // GraphQL `execute` function, with `payload` as the rootValue.
649
+ // This implements the "MapSourceToResponseEvent" algorithm described in
650
+ // the GraphQL specification. The `execute` function provides the
651
+ // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
652
+ // "ExecuteQuery" algorithm, for which `execute` is also used.
653
+ return mapAsyncIterator(resultOrStream, (payload) => executeImpl(buildPerEventExecutionContext(exeContext, payload)));
654
+ }
655
+ /**
656
+ * Implements the "CreateSourceEventStream" algorithm described in the
657
+ * GraphQL specification, resolving the subscription source event stream.
658
+ *
659
+ * Returns a Promise which resolves to either an AsyncIterable (if successful)
660
+ * or an ExecutionResult (error). The promise will be rejected if the schema or
661
+ * other arguments to this function are invalid, or if the resolved event stream
662
+ * is not an async iterable.
663
+ *
664
+ * If the client-provided arguments to this function do not result in a
665
+ * compliant subscription, a GraphQL Response (ExecutionResult) with
666
+ * descriptive errors and no data will be returned.
667
+ *
668
+ * If the the source stream could not be created due to faulty subscription
669
+ * resolver logic or underlying systems, the promise will resolve to a single
670
+ * ExecutionResult containing `errors` and no `data`.
671
+ *
672
+ * If the operation succeeded, the promise resolves to the AsyncIterable for the
673
+ * event stream returned by the resolver.
674
+ *
675
+ * A Source Event Stream represents a sequence of events, each of which triggers
676
+ * a GraphQL execution for that event.
677
+ *
678
+ * This may be useful when hosting the stateful subscription service in a
679
+ * different process or machine than the stateless GraphQL execution engine,
680
+ * or otherwise separating these two steps. For more on this, see the
681
+ * "Supporting Subscriptions at Scale" information in the GraphQL specification.
682
+ */
683
+ export function createSourceEventStream(args) {
684
+ // If a valid execution context cannot be created due to incorrect arguments,
685
+ // a "Response" with only errors is returned.
686
+ const exeContext = buildExecutionContext(args);
687
+ // Return early errors if execution context failed.
688
+ if (!('schema' in exeContext)) {
689
+ return { errors: exeContext };
690
+ }
691
+ return createSourceEventStreamImpl(exeContext);
692
+ }
693
+ function createSourceEventStreamImpl(exeContext) {
694
+ try {
695
+ const eventStream = executeSubscription(exeContext);
696
+ if (isPromise(eventStream)) {
697
+ return eventStream.then(undefined, error => ({ errors: [error] }));
698
+ }
699
+ return eventStream;
700
+ }
701
+ catch (error) {
702
+ return { errors: [error] };
703
+ }
704
+ }
705
+ function executeSubscription(exeContext) {
706
+ var _a;
707
+ const { schema, fragments, operation, variableValues, rootValue } = exeContext;
708
+ const rootType = schema.getSubscriptionType();
709
+ if (rootType == null) {
710
+ throw new GraphQLError('Schema is not configured to execute subscription operation.', { nodes: operation });
711
+ }
712
+ const rootFields = collectFields(schema, fragments, variableValues, rootType, operation.selectionSet);
713
+ const [responseName, fieldNodes] = [...rootFields.entries()][0];
714
+ const fieldName = fieldNodes[0].name.value;
715
+ const fieldDef = getFieldDef(schema, rootType, fieldNodes[0]);
716
+ if (!fieldDef) {
717
+ throw new GraphQLError(`The subscription field "${fieldName}" is not defined.`, { nodes: fieldNodes });
718
+ }
719
+ const path = addPath(undefined, responseName, rootType.name);
720
+ const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, rootType, path);
721
+ try {
722
+ // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification.
723
+ // It differs from "ResolveFieldValue" due to providing a different `resolveFn`.
724
+ // Build a JS object of arguments from the field.arguments AST, using the
725
+ // variables scope to fulfill any variable references.
726
+ const args = getArgumentValues(fieldDef, fieldNodes[0], variableValues);
727
+ // The resolve function's optional third argument is a context value that
728
+ // is provided to every resolve function within an execution. It is commonly
729
+ // used to represent an authenticated user, or request-specific caches.
730
+ const contextValue = exeContext.contextValue;
731
+ // Call the `subscribe()` resolver or the default resolver to produce an
732
+ // AsyncIterable yielding raw payloads.
733
+ const resolveFn = (_a = fieldDef.subscribe) !== null && _a !== void 0 ? _a : exeContext.subscribeFieldResolver;
734
+ const result = resolveFn(rootValue, args, contextValue, info);
735
+ if (isPromise(result)) {
736
+ return result.then(assertEventStream).then(undefined, error => {
737
+ throw locatedError(error, fieldNodes, pathToArray(path));
738
+ });
739
+ }
740
+ return assertEventStream(result);
741
+ }
742
+ catch (error) {
743
+ throw locatedError(error, fieldNodes, pathToArray(path));
744
+ }
745
+ }
746
+ function assertEventStream(result) {
747
+ if (result instanceof Error) {
748
+ throw result;
749
+ }
750
+ // Assert field returned an event stream, otherwise yield an error.
751
+ if (!isAsyncIterable(result)) {
752
+ throw new GraphQLError('Subscription field must return Async Iterable. ' + `Received: ${inspect(result)}.`);
753
+ }
754
+ return result;
755
+ }
756
+ /**
757
+ * This method looks up the field on the given type definition.
758
+ * It has special casing for the three introspection fields,
759
+ * __schema, __type and __typename. __typename is special because
760
+ * it can always be queried as a field, even in situations where no
761
+ * other fields are allowed, like on a Union. __schema and __type
762
+ * could get automatically added to the query type, but that would
763
+ * require mutating type definitions, which would cause issues.
764
+ *
765
+ * @internal
766
+ */
767
+ export function getFieldDef(schema, parentType, fieldNode) {
768
+ const fieldName = fieldNode.name.value;
769
+ if (fieldName === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
770
+ return SchemaMetaFieldDef;
771
+ }
772
+ else if (fieldName === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
773
+ return TypeMetaFieldDef;
774
+ }
775
+ else if (fieldName === TypeNameMetaFieldDef.name) {
776
+ return TypeNameMetaFieldDef;
777
+ }
778
+ return parentType.getFields()[fieldName];
779
+ }