Initial commit
This commit is contained in:
commit
f47e08fdcb
2409 files changed
+363607
No files matched your search
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2015-present, Facebook, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
# GraphQL.js
|
||||
|
||||
The JavaScript reference implementation for GraphQL, a query language for APIs created by Facebook.
|
||||
|
||||
[](http://badge.fury.io/js/graphql)
|
||||
[](https://travis-ci.org/graphql/graphql-js?branch=master)
|
||||
[](https://coveralls.io/r/graphql/graphql-js?branch=master)
|
||||
|
||||
See more complete documentation at http://graphql.org/ and
|
||||
http://graphql.org/graphql-js/.
|
||||
|
||||
Looking for help? Find resources [from the community](http://graphql.org/community/).
|
||||
|
||||
|
||||
## Getting Started
|
||||
|
||||
An overview of GraphQL in general is available in the
|
||||
[README](https://github.com/facebook/graphql/blob/master/README.md) for the
|
||||
[Specification for GraphQL](https://github.com/facebook/graphql). That overview
|
||||
describes a simple set of GraphQL examples that exist as [tests](src/__tests__)
|
||||
in this repository. A good way to get started with this repository is to walk
|
||||
through that README and the corresponding tests in parallel.
|
||||
|
||||
### Using GraphQL.js
|
||||
|
||||
Install GraphQL.js from npm
|
||||
|
||||
With yarn:
|
||||
|
||||
```sh
|
||||
yarn add graphql
|
||||
```
|
||||
|
||||
or alternatively using npm:
|
||||
|
||||
```sh
|
||||
npm install --save graphql
|
||||
```
|
||||
|
||||
GraphQL.js provides two important capabilities: building a type schema, and
|
||||
serving queries against that type schema.
|
||||
|
||||
First, build a GraphQL type schema which maps to your code base.
|
||||
|
||||
```js
|
||||
import {
|
||||
graphql,
|
||||
GraphQLSchema,
|
||||
GraphQLObjectType,
|
||||
GraphQLString
|
||||
} from 'graphql';
|
||||
|
||||
var schema = new GraphQLSchema({
|
||||
query: new GraphQLObjectType({
|
||||
name: 'RootQueryType',
|
||||
fields: {
|
||||
hello: {
|
||||
type: GraphQLString,
|
||||
resolve() {
|
||||
return 'world';
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
This defines a simple schema with one type and one field, that resolves
|
||||
to a fixed value. The `resolve` function can return a value, a promise,
|
||||
or an array of promises. A more complex example is included in the top
|
||||
level [tests](src/__tests__) directory.
|
||||
|
||||
Then, serve the result of a query against that type schema.
|
||||
|
||||
```js
|
||||
var query = '{ hello }';
|
||||
|
||||
graphql(schema, query).then(result => {
|
||||
|
||||
// Prints
|
||||
// {
|
||||
// data: { hello: "world" }
|
||||
// }
|
||||
console.log(result);
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
This runs a query fetching the one field defined. The `graphql` function will
|
||||
first ensure the query is syntactically and semantically valid before executing
|
||||
it, reporting errors otherwise.
|
||||
|
||||
```js
|
||||
var query = '{ boyhowdy }';
|
||||
|
||||
graphql(schema, query).then(result => {
|
||||
|
||||
// Prints
|
||||
// {
|
||||
// errors: [
|
||||
// { message: 'Cannot query field boyhowdy on RootQueryType',
|
||||
// locations: [ { line: 1, column: 3 } ] }
|
||||
// ]
|
||||
// }
|
||||
console.log(result);
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
### Want to ride the bleeding edge?
|
||||
|
||||
The `npm` branch in this repository is automatically maintained to be the last
|
||||
commit to `master` to pass all tests, in the same form found on npm. It is
|
||||
recommended to use builds deployed to npm for many reasons, but if you want to use
|
||||
the latest not-yet-released version of graphql-js, you can do so by depending
|
||||
directly on this branch:
|
||||
|
||||
```
|
||||
npm install graphql@git://github.com/graphql/graphql-js.git#npm
|
||||
```
|
||||
|
||||
### Using in a Browser
|
||||
|
||||
GraphQL.js is a general purpose library and can be used both in a Node server
|
||||
and in the browser. As an example, the [GraphiQL](https://github.com/graphql/graphiql/)
|
||||
tool is built with GraphQL.js!
|
||||
|
||||
Building a project using GraphQL.js with [webpack](https://webpack.js.org) or
|
||||
[rollup](https://github.com/rollup/rollup) should just work and only include
|
||||
the portions of the library you use. This works because GraphQL.js is distributed
|
||||
with both CommonJS (`require()`) and ESModule (`import`) files. Ensure that any
|
||||
custom build configurations look for `.mjs` files!
|
||||
|
||||
### Contributing
|
||||
|
||||
We actively welcome pull requests, learn how to
|
||||
[contribute](https://github.com/graphql/graphql-js/blob/master/.github/CONTRIBUTING.md).
|
||||
|
||||
### Changelog
|
||||
|
||||
Changes are tracked as [GitHub releases](https://github.com/graphql/graphql-js/releases).
|
||||
|
||||
### License
|
||||
|
||||
GraphQL.js is [MIT-licensed](https://github.com/graphql/graphql-js/blob/master/LICENSE).
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.GraphQLError = GraphQLError;
|
||||
|
||||
var _printError = require("./printError");
|
||||
|
||||
var _location = require("../language/location");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
function GraphQLError( // eslint-disable-line no-redeclare
|
||||
message, nodes, source, positions, path, originalError, extensions) {
|
||||
// Compute list of blame nodes.
|
||||
var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions.
|
||||
|
||||
|
||||
var _source = source;
|
||||
|
||||
if (!_source && _nodes) {
|
||||
var node = _nodes[0];
|
||||
_source = node && node.loc && node.loc.source;
|
||||
}
|
||||
|
||||
var _positions = positions;
|
||||
|
||||
if (!_positions && _nodes) {
|
||||
_positions = _nodes.reduce(function (list, node) {
|
||||
if (node.loc) {
|
||||
list.push(node.loc.start);
|
||||
}
|
||||
|
||||
return list;
|
||||
}, []);
|
||||
}
|
||||
|
||||
if (_positions && _positions.length === 0) {
|
||||
_positions = undefined;
|
||||
}
|
||||
|
||||
var _locations;
|
||||
|
||||
if (positions && source) {
|
||||
_locations = positions.map(function (pos) {
|
||||
return (0, _location.getLocation)(source, pos);
|
||||
});
|
||||
} else if (_nodes) {
|
||||
_locations = _nodes.reduce(function (list, node) {
|
||||
if (node.loc) {
|
||||
list.push((0, _location.getLocation)(node.loc.source, node.loc.start));
|
||||
}
|
||||
|
||||
return list;
|
||||
}, []);
|
||||
}
|
||||
|
||||
var _extensions = extensions || originalError && originalError.extensions;
|
||||
|
||||
Object.defineProperties(this, {
|
||||
message: {
|
||||
value: message,
|
||||
// By being enumerable, JSON.stringify will include `message` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: true,
|
||||
writable: true
|
||||
},
|
||||
locations: {
|
||||
// Coercing falsey values to undefined ensures they will not be included
|
||||
// in JSON.stringify() when not provided.
|
||||
value: _locations || undefined,
|
||||
// By being enumerable, JSON.stringify will include `locations` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: Boolean(_locations)
|
||||
},
|
||||
path: {
|
||||
// Coercing falsey values to undefined ensures they will not be included
|
||||
// in JSON.stringify() when not provided.
|
||||
value: path || undefined,
|
||||
// By being enumerable, JSON.stringify will include `path` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: Boolean(path)
|
||||
},
|
||||
nodes: {
|
||||
value: _nodes || undefined
|
||||
},
|
||||
source: {
|
||||
value: _source || undefined
|
||||
},
|
||||
positions: {
|
||||
value: _positions || undefined
|
||||
},
|
||||
originalError: {
|
||||
value: originalError
|
||||
},
|
||||
extensions: {
|
||||
// Coercing falsey values to undefined ensures they will not be included
|
||||
// in JSON.stringify() when not provided.
|
||||
value: _extensions || undefined,
|
||||
// By being enumerable, JSON.stringify will include `path` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: Boolean(_extensions)
|
||||
}
|
||||
}); // Include (non-enumerable) stack trace.
|
||||
|
||||
if (originalError && originalError.stack) {
|
||||
Object.defineProperty(this, 'stack', {
|
||||
value: originalError.stack,
|
||||
writable: true,
|
||||
configurable: true
|
||||
});
|
||||
} else if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, GraphQLError);
|
||||
} else {
|
||||
Object.defineProperty(this, 'stack', {
|
||||
value: Error().stack,
|
||||
writable: true,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
GraphQLError.prototype = Object.create(Error.prototype, {
|
||||
constructor: {
|
||||
value: GraphQLError
|
||||
},
|
||||
name: {
|
||||
value: 'GraphQLError'
|
||||
},
|
||||
toString: {
|
||||
value: function toString() {
|
||||
return (0, _printError.printError)(this);
|
||||
}
|
||||
}
|
||||
});
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { printError } from './printError';
|
||||
import { getLocation } from '../language/location';
|
||||
import type { SourceLocation } from '../language/location';
|
||||
import type { ASTNode } from '../language/ast';
|
||||
import type { Source } from '../language/source';
|
||||
|
||||
/**
|
||||
* A GraphQLError describes an Error found during the parse, validate, or
|
||||
* execute phases of performing a GraphQL operation. In addition to a message
|
||||
* and stack trace, it also includes information about the locations in a
|
||||
* GraphQL document and/or execution result that correspond to the Error.
|
||||
*/
|
||||
declare class GraphQLError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
nodes?: $ReadOnlyArray<ASTNode> | ASTNode | void,
|
||||
source?: ?Source,
|
||||
positions?: ?$ReadOnlyArray<number>,
|
||||
path?: ?$ReadOnlyArray<string | number>,
|
||||
originalError?: ?Error,
|
||||
extensions?: ?{ [key: string]: mixed },
|
||||
): void;
|
||||
|
||||
/**
|
||||
* A message describing the Error for debugging purposes.
|
||||
*
|
||||
* Enumerable, and appears in the result of JSON.stringify().
|
||||
*
|
||||
* Note: should be treated as readonly, despite invariant usage.
|
||||
*/
|
||||
message: string;
|
||||
|
||||
/**
|
||||
* An array of { line, column } locations within the source GraphQL document
|
||||
* which correspond to this error.
|
||||
*
|
||||
* Errors during validation often contain multiple locations, for example to
|
||||
* point out two things with the same name. Errors during execution include a
|
||||
* single location, the field which produced the error.
|
||||
*
|
||||
* Enumerable, and appears in the result of JSON.stringify().
|
||||
*/
|
||||
+locations: $ReadOnlyArray<SourceLocation> | void;
|
||||
|
||||
/**
|
||||
* An array describing the JSON-path into the execution response which
|
||||
* corresponds to this error. Only included for errors during execution.
|
||||
*
|
||||
* Enumerable, and appears in the result of JSON.stringify().
|
||||
*/
|
||||
+path: $ReadOnlyArray<string | number> | void;
|
||||
|
||||
/**
|
||||
* An array of GraphQL AST Nodes corresponding to this error.
|
||||
*/
|
||||
+nodes: $ReadOnlyArray<ASTNode> | void;
|
||||
|
||||
/**
|
||||
* The source GraphQL document for the first location of this error.
|
||||
*
|
||||
* Note that if this Error represents more than one node, the source may not
|
||||
* represent nodes after the first node.
|
||||
*/
|
||||
+source: Source | void;
|
||||
|
||||
/**
|
||||
* An array of character offsets within the source GraphQL document
|
||||
* which correspond to this error.
|
||||
*/
|
||||
+positions: $ReadOnlyArray<number> | void;
|
||||
|
||||
/**
|
||||
* The original error thrown from a field resolver during execution.
|
||||
*/
|
||||
+originalError: ?Error;
|
||||
|
||||
/**
|
||||
* Extension fields to add to the formatted error.
|
||||
*/
|
||||
+extensions: { [key: string]: mixed } | void;
|
||||
}
|
||||
|
||||
export function GraphQLError( // eslint-disable-line no-redeclare
|
||||
message: string,
|
||||
nodes?: $ReadOnlyArray<ASTNode> | ASTNode | void,
|
||||
source?: ?Source,
|
||||
positions?: ?$ReadOnlyArray<number>,
|
||||
path?: ?$ReadOnlyArray<string | number>,
|
||||
originalError?: ?Error & { +extensions: mixed },
|
||||
extensions?: ?{ [key: string]: mixed },
|
||||
) {
|
||||
// Compute list of blame nodes.
|
||||
const _nodes = Array.isArray(nodes)
|
||||
? nodes.length !== 0
|
||||
? nodes
|
||||
: undefined
|
||||
: nodes
|
||||
? [nodes]
|
||||
: undefined;
|
||||
|
||||
// Compute locations in the source for the given nodes/positions.
|
||||
let _source = source;
|
||||
if (!_source && _nodes) {
|
||||
const node = _nodes[0];
|
||||
_source = node && node.loc && node.loc.source;
|
||||
}
|
||||
|
||||
let _positions = positions;
|
||||
if (!_positions && _nodes) {
|
||||
_positions = _nodes.reduce((list, node) => {
|
||||
if (node.loc) {
|
||||
list.push(node.loc.start);
|
||||
}
|
||||
return list;
|
||||
}, []);
|
||||
}
|
||||
if (_positions && _positions.length === 0) {
|
||||
_positions = undefined;
|
||||
}
|
||||
|
||||
let _locations;
|
||||
if (positions && source) {
|
||||
_locations = positions.map(pos => getLocation(source, pos));
|
||||
} else if (_nodes) {
|
||||
_locations = _nodes.reduce((list, node) => {
|
||||
if (node.loc) {
|
||||
list.push(getLocation(node.loc.source, node.loc.start));
|
||||
}
|
||||
return list;
|
||||
}, []);
|
||||
}
|
||||
|
||||
const _extensions = extensions || (originalError && originalError.extensions);
|
||||
|
||||
Object.defineProperties(this, {
|
||||
message: {
|
||||
value: message,
|
||||
// By being enumerable, JSON.stringify will include `message` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
},
|
||||
locations: {
|
||||
// Coercing falsey values to undefined ensures they will not be included
|
||||
// in JSON.stringify() when not provided.
|
||||
value: _locations || undefined,
|
||||
// By being enumerable, JSON.stringify will include `locations` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: Boolean(_locations),
|
||||
},
|
||||
path: {
|
||||
// Coercing falsey values to undefined ensures they will not be included
|
||||
// in JSON.stringify() when not provided.
|
||||
value: path || undefined,
|
||||
// By being enumerable, JSON.stringify will include `path` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: Boolean(path),
|
||||
},
|
||||
nodes: {
|
||||
value: _nodes || undefined,
|
||||
},
|
||||
source: {
|
||||
value: _source || undefined,
|
||||
},
|
||||
positions: {
|
||||
value: _positions || undefined,
|
||||
},
|
||||
originalError: {
|
||||
value: originalError,
|
||||
},
|
||||
extensions: {
|
||||
// Coercing falsey values to undefined ensures they will not be included
|
||||
// in JSON.stringify() when not provided.
|
||||
value: _extensions || undefined,
|
||||
// By being enumerable, JSON.stringify will include `path` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: Boolean(_extensions),
|
||||
},
|
||||
});
|
||||
|
||||
// Include (non-enumerable) stack trace.
|
||||
if (originalError && originalError.stack) {
|
||||
Object.defineProperty(this, 'stack', {
|
||||
value: originalError.stack,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
} else if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, GraphQLError);
|
||||
} else {
|
||||
Object.defineProperty(this, 'stack', {
|
||||
value: Error().stack,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
(GraphQLError: any).prototype = Object.create(Error.prototype, {
|
||||
constructor: { value: GraphQLError },
|
||||
name: { value: 'GraphQLError' },
|
||||
toString: {
|
||||
value: function toString() {
|
||||
return printError(this);
|
||||
},
|
||||
},
|
||||
});
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { printError } from './printError';
|
||||
import { getLocation } from '../language/location';
|
||||
export function GraphQLError( // eslint-disable-line no-redeclare
|
||||
message, nodes, source, positions, path, originalError, extensions) {
|
||||
// Compute list of blame nodes.
|
||||
var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions.
|
||||
|
||||
|
||||
var _source = source;
|
||||
|
||||
if (!_source && _nodes) {
|
||||
var node = _nodes[0];
|
||||
_source = node && node.loc && node.loc.source;
|
||||
}
|
||||
|
||||
var _positions = positions;
|
||||
|
||||
if (!_positions && _nodes) {
|
||||
_positions = _nodes.reduce(function (list, node) {
|
||||
if (node.loc) {
|
||||
list.push(node.loc.start);
|
||||
}
|
||||
|
||||
return list;
|
||||
}, []);
|
||||
}
|
||||
|
||||
if (_positions && _positions.length === 0) {
|
||||
_positions = undefined;
|
||||
}
|
||||
|
||||
var _locations;
|
||||
|
||||
if (positions && source) {
|
||||
_locations = positions.map(function (pos) {
|
||||
return getLocation(source, pos);
|
||||
});
|
||||
} else if (_nodes) {
|
||||
_locations = _nodes.reduce(function (list, node) {
|
||||
if (node.loc) {
|
||||
list.push(getLocation(node.loc.source, node.loc.start));
|
||||
}
|
||||
|
||||
return list;
|
||||
}, []);
|
||||
}
|
||||
|
||||
var _extensions = extensions || originalError && originalError.extensions;
|
||||
|
||||
Object.defineProperties(this, {
|
||||
message: {
|
||||
value: message,
|
||||
// By being enumerable, JSON.stringify will include `message` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: true,
|
||||
writable: true
|
||||
},
|
||||
locations: {
|
||||
// Coercing falsey values to undefined ensures they will not be included
|
||||
// in JSON.stringify() when not provided.
|
||||
value: _locations || undefined,
|
||||
// By being enumerable, JSON.stringify will include `locations` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: Boolean(_locations)
|
||||
},
|
||||
path: {
|
||||
// Coercing falsey values to undefined ensures they will not be included
|
||||
// in JSON.stringify() when not provided.
|
||||
value: path || undefined,
|
||||
// By being enumerable, JSON.stringify will include `path` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: Boolean(path)
|
||||
},
|
||||
nodes: {
|
||||
value: _nodes || undefined
|
||||
},
|
||||
source: {
|
||||
value: _source || undefined
|
||||
},
|
||||
positions: {
|
||||
value: _positions || undefined
|
||||
},
|
||||
originalError: {
|
||||
value: originalError
|
||||
},
|
||||
extensions: {
|
||||
// Coercing falsey values to undefined ensures they will not be included
|
||||
// in JSON.stringify() when not provided.
|
||||
value: _extensions || undefined,
|
||||
// By being enumerable, JSON.stringify will include `path` in the
|
||||
// resulting output. This ensures that the simplest possible GraphQL
|
||||
// service adheres to the spec.
|
||||
enumerable: Boolean(_extensions)
|
||||
}
|
||||
}); // Include (non-enumerable) stack trace.
|
||||
|
||||
if (originalError && originalError.stack) {
|
||||
Object.defineProperty(this, 'stack', {
|
||||
value: originalError.stack,
|
||||
writable: true,
|
||||
configurable: true
|
||||
});
|
||||
} else if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, GraphQLError);
|
||||
} else {
|
||||
Object.defineProperty(this, 'stack', {
|
||||
value: Error().stack,
|
||||
writable: true,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
GraphQLError.prototype = Object.create(Error.prototype, {
|
||||
constructor: {
|
||||
value: GraphQLError
|
||||
},
|
||||
name: {
|
||||
value: 'GraphQLError'
|
||||
},
|
||||
toString: {
|
||||
value: function toString() {
|
||||
return printError(this);
|
||||
}
|
||||
}
|
||||
});
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.formatError = formatError;
|
||||
|
||||
var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Given a GraphQLError, format it according to the rules described by the
|
||||
* Response Format, Errors section of the GraphQL Specification.
|
||||
*/
|
||||
function formatError(error) {
|
||||
!error ? (0, _invariant.default)(0, 'Received null or undefined error.') : void 0;
|
||||
var message = error.message || 'An unknown error occurred.';
|
||||
var locations = error.locations;
|
||||
var path = error.path;
|
||||
var extensions = error.extensions;
|
||||
return extensions ? {
|
||||
message: message,
|
||||
locations: locations,
|
||||
path: path,
|
||||
extensions: extensions
|
||||
} : {
|
||||
message: message,
|
||||
locations: locations,
|
||||
path: path
|
||||
};
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import invariant from '../jsutils/invariant';
|
||||
import type { GraphQLError } from './GraphQLError';
|
||||
import type { SourceLocation } from '../language/location';
|
||||
|
||||
/**
|
||||
* Given a GraphQLError, format it according to the rules described by the
|
||||
* Response Format, Errors section of the GraphQL Specification.
|
||||
*/
|
||||
export function formatError(error: GraphQLError): GraphQLFormattedError {
|
||||
invariant(error, 'Received null or undefined error.');
|
||||
const message = error.message || 'An unknown error occurred.';
|
||||
const locations = error.locations;
|
||||
const path = error.path;
|
||||
const extensions = error.extensions;
|
||||
|
||||
return extensions
|
||||
? { message, locations, path, extensions }
|
||||
: { message, locations, path };
|
||||
}
|
||||
|
||||
export type GraphQLFormattedError = {|
|
||||
+message: string,
|
||||
+locations: $ReadOnlyArray<SourceLocation> | void,
|
||||
+path: $ReadOnlyArray<string | number> | void,
|
||||
+extensions?: { [key: string]: mixed },
|
||||
|};
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import invariant from '../jsutils/invariant';
|
||||
|
||||
/**
|
||||
* Given a GraphQLError, format it according to the rules described by the
|
||||
* Response Format, Errors section of the GraphQL Specification.
|
||||
*/
|
||||
export function formatError(error) {
|
||||
!error ? invariant(0, 'Received null or undefined error.') : void 0;
|
||||
var message = error.message || 'An unknown error occurred.';
|
||||
var locations = error.locations;
|
||||
var path = error.path;
|
||||
var extensions = error.extensions;
|
||||
return extensions ? {
|
||||
message: message,
|
||||
locations: locations,
|
||||
path: path,
|
||||
extensions: extensions
|
||||
} : {
|
||||
message: message,
|
||||
locations: locations,
|
||||
path: path
|
||||
};
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "GraphQLError", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _GraphQLError.GraphQLError;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "syntaxError", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _syntaxError.syntaxError;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "locatedError", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _locatedError.locatedError;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "printError", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _printError.printError;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "formatError", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _formatError.formatError;
|
||||
}
|
||||
});
|
||||
|
||||
var _GraphQLError = require("./GraphQLError");
|
||||
|
||||
var _syntaxError = require("./syntaxError");
|
||||
|
||||
var _locatedError = require("./locatedError");
|
||||
|
||||
var _printError = require("./printError");
|
||||
|
||||
var _formatError = require("./formatError");
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
export { GraphQLError } from './GraphQLError';
|
||||
export { syntaxError } from './syntaxError';
|
||||
export { locatedError } from './locatedError';
|
||||
export { printError } from './printError';
|
||||
export { formatError } from './formatError';
|
||||
|
||||
export type { GraphQLFormattedError } from './formatError';
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
export { GraphQLError } from './GraphQLError';
|
||||
export { syntaxError } from './syntaxError';
|
||||
export { locatedError } from './locatedError';
|
||||
export { printError } from './printError';
|
||||
export { formatError } from './formatError';
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.locatedError = locatedError;
|
||||
|
||||
var _GraphQLError = require("./GraphQLError");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Given an arbitrary Error, presumably thrown while attempting to execute a
|
||||
* GraphQL operation, produce a new GraphQLError aware of the location in the
|
||||
* document responsible for the original Error.
|
||||
*/
|
||||
function locatedError(originalError, nodes, path) {
|
||||
// Note: this uses a brand-check to support GraphQL errors originating from
|
||||
// other contexts.
|
||||
if (originalError && Array.isArray(originalError.path)) {
|
||||
return originalError;
|
||||
}
|
||||
|
||||
return new _GraphQLError.GraphQLError(originalError && originalError.message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError);
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { GraphQLError } from './GraphQLError';
|
||||
import type { ASTNode } from '../language/ast';
|
||||
|
||||
/**
|
||||
* Given an arbitrary Error, presumably thrown while attempting to execute a
|
||||
* GraphQL operation, produce a new GraphQLError aware of the location in the
|
||||
* document responsible for the original Error.
|
||||
*/
|
||||
export function locatedError(
|
||||
originalError: Error | GraphQLError,
|
||||
nodes: $ReadOnlyArray<ASTNode>,
|
||||
path: $ReadOnlyArray<string | number>,
|
||||
): GraphQLError {
|
||||
// Note: this uses a brand-check to support GraphQL errors originating from
|
||||
// other contexts.
|
||||
if (originalError && Array.isArray(originalError.path)) {
|
||||
return (originalError: any);
|
||||
}
|
||||
|
||||
return new GraphQLError(
|
||||
originalError && originalError.message,
|
||||
(originalError && (originalError: any).nodes) || nodes,
|
||||
originalError && (originalError: any).source,
|
||||
originalError && (originalError: any).positions,
|
||||
path,
|
||||
originalError,
|
||||
);
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { GraphQLError } from './GraphQLError';
|
||||
|
||||
/**
|
||||
* Given an arbitrary Error, presumably thrown while attempting to execute a
|
||||
* GraphQL operation, produce a new GraphQLError aware of the location in the
|
||||
* document responsible for the original Error.
|
||||
*/
|
||||
export function locatedError(originalError, nodes, path) {
|
||||
// Note: this uses a brand-check to support GraphQL errors originating from
|
||||
// other contexts.
|
||||
if (originalError && Array.isArray(originalError.path)) {
|
||||
return originalError;
|
||||
}
|
||||
|
||||
return new GraphQLError(originalError && originalError.message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError);
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.printError = printError;
|
||||
|
||||
var _location = require("../language/location");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Prints a GraphQLError to a string, representing useful location information
|
||||
* about the error's position in the source.
|
||||
*/
|
||||
function printError(error) {
|
||||
var printedLocations = [];
|
||||
|
||||
if (error.nodes) {
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = error.nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var node = _step.value;
|
||||
|
||||
if (node.loc) {
|
||||
printedLocations.push(highlightSourceAtLocation(node.loc.source, (0, _location.getLocation)(node.loc.source, node.loc.start)));
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (error.source && error.locations) {
|
||||
var source = error.source;
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = error.locations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var location = _step2.value;
|
||||
printedLocations.push(highlightSourceAtLocation(source, location));
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return printedLocations.length === 0 ? error.message : [error.message].concat(printedLocations).join('\n\n') + '\n';
|
||||
}
|
||||
/**
|
||||
* Render a helpful description of the location of the error in the GraphQL
|
||||
* Source document.
|
||||
*/
|
||||
|
||||
|
||||
function highlightSourceAtLocation(source, location) {
|
||||
var firstLineColumnOffset = source.locationOffset.column - 1;
|
||||
var body = whitespace(firstLineColumnOffset) + source.body;
|
||||
var lineIndex = location.line - 1;
|
||||
var lineOffset = source.locationOffset.line - 1;
|
||||
var lineNum = location.line + lineOffset;
|
||||
var columnOffset = location.line === 1 ? firstLineColumnOffset : 0;
|
||||
var columnNum = location.column + columnOffset;
|
||||
var lines = body.split(/\r\n|[\n\r]/g);
|
||||
return "".concat(source.name, " (").concat(lineNum, ":").concat(columnNum, ")\n") + printPrefixedLines([// Lines specified like this: ["prefix", "string"],
|
||||
["".concat(lineNum - 1, ": "), lines[lineIndex - 1]], ["".concat(lineNum, ": "), lines[lineIndex]], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1, ": "), lines[lineIndex + 1]]]);
|
||||
}
|
||||
|
||||
function printPrefixedLines(lines) {
|
||||
var existingLines = lines.filter(function (_ref) {
|
||||
var _ = _ref[0],
|
||||
line = _ref[1];
|
||||
return line !== undefined;
|
||||
});
|
||||
var padLen = 0;
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = existingLines[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var _ref4 = _step3.value;
|
||||
var prefix = _ref4[0];
|
||||
padLen = Math.max(padLen, prefix.length);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return existingLines.map(function (_ref3) {
|
||||
var prefix = _ref3[0],
|
||||
line = _ref3[1];
|
||||
return lpad(padLen, prefix) + line;
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
function whitespace(len) {
|
||||
return Array(len + 1).join(' ');
|
||||
}
|
||||
|
||||
function lpad(len, str) {
|
||||
return whitespace(len - str.length) + str;
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { getLocation } from '../language/location';
|
||||
import type { SourceLocation } from '../language/location';
|
||||
import type { Source } from '../language/source';
|
||||
import type { GraphQLError } from './GraphQLError';
|
||||
|
||||
/**
|
||||
* Prints a GraphQLError to a string, representing useful location information
|
||||
* about the error's position in the source.
|
||||
*/
|
||||
export function printError(error: GraphQLError): string {
|
||||
const printedLocations = [];
|
||||
if (error.nodes) {
|
||||
for (const node of error.nodes) {
|
||||
if (node.loc) {
|
||||
printedLocations.push(
|
||||
highlightSourceAtLocation(
|
||||
node.loc.source,
|
||||
getLocation(node.loc.source, node.loc.start),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
} else if (error.source && error.locations) {
|
||||
const source = error.source;
|
||||
for (const location of error.locations) {
|
||||
printedLocations.push(highlightSourceAtLocation(source, location));
|
||||
}
|
||||
}
|
||||
return printedLocations.length === 0
|
||||
? error.message
|
||||
: [error.message, ...printedLocations].join('\n\n') + '\n';
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a helpful description of the location of the error in the GraphQL
|
||||
* Source document.
|
||||
*/
|
||||
function highlightSourceAtLocation(
|
||||
source: Source,
|
||||
location: SourceLocation,
|
||||
): string {
|
||||
const firstLineColumnOffset = source.locationOffset.column - 1;
|
||||
const body = whitespace(firstLineColumnOffset) + source.body;
|
||||
|
||||
const lineIndex = location.line - 1;
|
||||
const lineOffset = source.locationOffset.line - 1;
|
||||
const lineNum = location.line + lineOffset;
|
||||
|
||||
const columnOffset = location.line === 1 ? firstLineColumnOffset : 0;
|
||||
const columnNum = location.column + columnOffset;
|
||||
|
||||
const lines = body.split(/\r\n|[\n\r]/g);
|
||||
return (
|
||||
`${source.name} (${lineNum}:${columnNum})\n` +
|
||||
printPrefixedLines([
|
||||
// Lines specified like this: ["prefix", "string"],
|
||||
[`${lineNum - 1}: `, lines[lineIndex - 1]],
|
||||
[`${lineNum}: `, lines[lineIndex]],
|
||||
['', whitespace(columnNum - 1) + '^'],
|
||||
[`${lineNum + 1}: `, lines[lineIndex + 1]],
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
function printPrefixedLines(lines: Array<[string, string]>): string {
|
||||
const existingLines = lines.filter(([_, line]) => line !== undefined);
|
||||
|
||||
let padLen = 0;
|
||||
for (const [prefix] of existingLines) {
|
||||
padLen = Math.max(padLen, prefix.length);
|
||||
}
|
||||
|
||||
return existingLines
|
||||
.map(([prefix, line]) => lpad(padLen, prefix) + line)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function whitespace(len: number): string {
|
||||
return Array(len + 1).join(' ');
|
||||
}
|
||||
|
||||
function lpad(len: number, str: string): string {
|
||||
return whitespace(len - str.length) + str;
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { getLocation } from '../language/location';
|
||||
|
||||
/**
|
||||
* Prints a GraphQLError to a string, representing useful location information
|
||||
* about the error's position in the source.
|
||||
*/
|
||||
export function printError(error) {
|
||||
var printedLocations = [];
|
||||
|
||||
if (error.nodes) {
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = error.nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var node = _step.value;
|
||||
|
||||
if (node.loc) {
|
||||
printedLocations.push(highlightSourceAtLocation(node.loc.source, getLocation(node.loc.source, node.loc.start)));
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (error.source && error.locations) {
|
||||
var source = error.source;
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = error.locations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var location = _step2.value;
|
||||
printedLocations.push(highlightSourceAtLocation(source, location));
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return printedLocations.length === 0 ? error.message : [error.message].concat(printedLocations).join('\n\n') + '\n';
|
||||
}
|
||||
/**
|
||||
* Render a helpful description of the location of the error in the GraphQL
|
||||
* Source document.
|
||||
*/
|
||||
|
||||
function highlightSourceAtLocation(source, location) {
|
||||
var firstLineColumnOffset = source.locationOffset.column - 1;
|
||||
var body = whitespace(firstLineColumnOffset) + source.body;
|
||||
var lineIndex = location.line - 1;
|
||||
var lineOffset = source.locationOffset.line - 1;
|
||||
var lineNum = location.line + lineOffset;
|
||||
var columnOffset = location.line === 1 ? firstLineColumnOffset : 0;
|
||||
var columnNum = location.column + columnOffset;
|
||||
var lines = body.split(/\r\n|[\n\r]/g);
|
||||
return "".concat(source.name, " (").concat(lineNum, ":").concat(columnNum, ")\n") + printPrefixedLines([// Lines specified like this: ["prefix", "string"],
|
||||
["".concat(lineNum - 1, ": "), lines[lineIndex - 1]], ["".concat(lineNum, ": "), lines[lineIndex]], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1, ": "), lines[lineIndex + 1]]]);
|
||||
}
|
||||
|
||||
function printPrefixedLines(lines) {
|
||||
var existingLines = lines.filter(function (_ref) {
|
||||
var _ = _ref[0],
|
||||
line = _ref[1];
|
||||
return line !== undefined;
|
||||
});
|
||||
var padLen = 0;
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = existingLines[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var _ref4 = _step3.value;
|
||||
var prefix = _ref4[0];
|
||||
padLen = Math.max(padLen, prefix.length);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return existingLines.map(function (_ref3) {
|
||||
var prefix = _ref3[0],
|
||||
line = _ref3[1];
|
||||
return lpad(padLen, prefix) + line;
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
function whitespace(len) {
|
||||
return Array(len + 1).join(' ');
|
||||
}
|
||||
|
||||
function lpad(len, str) {
|
||||
return whitespace(len - str.length) + str;
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.syntaxError = syntaxError;
|
||||
|
||||
var _GraphQLError = require("./GraphQLError");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Produces a GraphQLError representing a syntax error, containing useful
|
||||
* descriptive information about the syntax error's position in the source.
|
||||
*/
|
||||
function syntaxError(source, position, description) {
|
||||
return new _GraphQLError.GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]);
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import type { Source } from '../language/source';
|
||||
import { GraphQLError } from './GraphQLError';
|
||||
|
||||
/**
|
||||
* Produces a GraphQLError representing a syntax error, containing useful
|
||||
* descriptive information about the syntax error's position in the source.
|
||||
*/
|
||||
export function syntaxError(
|
||||
source: Source,
|
||||
position: number,
|
||||
description: string,
|
||||
): GraphQLError {
|
||||
return new GraphQLError(`Syntax Error: ${description}`, undefined, source, [
|
||||
position,
|
||||
]);
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { GraphQLError } from './GraphQLError';
|
||||
/**
|
||||
* Produces a GraphQLError representing a syntax error, containing useful
|
||||
* descriptive information about the syntax error's position in the source.
|
||||
*/
|
||||
|
||||
export function syntaxError(source, position, description) {
|
||||
return new GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]);
|
||||
}
|
||||
+831
@@ -0,0 +1,831 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.execute = execute;
|
||||
exports.responsePathAsArray = responsePathAsArray;
|
||||
exports.addPath = addPath;
|
||||
exports.assertValidExecutionArguments = assertValidExecutionArguments;
|
||||
exports.buildExecutionContext = buildExecutionContext;
|
||||
exports.collectFields = collectFields;
|
||||
exports.buildResolveInfo = buildResolveInfo;
|
||||
exports.resolveFieldValueOrError = resolveFieldValueOrError;
|
||||
exports.getFieldDef = getFieldDef;
|
||||
exports.defaultFieldResolver = void 0;
|
||||
|
||||
var _iterall = require("iterall");
|
||||
|
||||
var _GraphQLError = require("../error/GraphQLError");
|
||||
|
||||
var _locatedError = require("../error/locatedError");
|
||||
|
||||
var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
|
||||
|
||||
var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
|
||||
|
||||
var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
|
||||
|
||||
var _isNullish = _interopRequireDefault(require("../jsutils/isNullish"));
|
||||
|
||||
var _isPromise = _interopRequireDefault(require("../jsutils/isPromise"));
|
||||
|
||||
var _memoize = _interopRequireDefault(require("../jsutils/memoize3"));
|
||||
|
||||
var _promiseForObject = _interopRequireDefault(require("../jsutils/promiseForObject"));
|
||||
|
||||
var _promiseReduce = _interopRequireDefault(require("../jsutils/promiseReduce"));
|
||||
|
||||
var _getOperationRootType = require("../utilities/getOperationRootType");
|
||||
|
||||
var _typeFromAST = require("../utilities/typeFromAST");
|
||||
|
||||
var _kinds = require("../language/kinds");
|
||||
|
||||
var _values = require("./values");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
var _introspection = require("../type/introspection");
|
||||
|
||||
var _directives = require("../type/directives");
|
||||
|
||||
var _validate = require("../type/validate");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
|
||||
|
||||
function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) {
|
||||
/* eslint-enable no-redeclare */
|
||||
// Extract arguments from object args if provided.
|
||||
return arguments.length === 1 ? executeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : executeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver);
|
||||
}
|
||||
|
||||
function executeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) {
|
||||
// If arguments are missing or incorrect, throw an error.
|
||||
assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments,
|
||||
// a "Response" with only errors is returned.
|
||||
|
||||
var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed.
|
||||
|
||||
if (Array.isArray(exeContext)) {
|
||||
return {
|
||||
errors: exeContext
|
||||
};
|
||||
} // Return a Promise that will eventually resolve to the data described by
|
||||
// The "Response" section of the GraphQL specification.
|
||||
//
|
||||
// If errors are encountered while executing a GraphQL field, only that
|
||||
// field and its descendants will be omitted, and sibling fields will still
|
||||
// be executed. An execution which encounters errors will still result in a
|
||||
// resolved Promise.
|
||||
|
||||
|
||||
var data = executeOperation(exeContext, exeContext.operation, rootValue);
|
||||
return buildResponse(exeContext, data);
|
||||
}
|
||||
/**
|
||||
* Given a completed execution context and data, build the { errors, data }
|
||||
* response defined by the "Response" section of the GraphQL specification.
|
||||
*/
|
||||
|
||||
|
||||
function buildResponse(exeContext, data) {
|
||||
if ((0, _isPromise.default)(data)) {
|
||||
return data.then(function (resolved) {
|
||||
return buildResponse(exeContext, resolved);
|
||||
});
|
||||
}
|
||||
|
||||
return exeContext.errors.length === 0 ? {
|
||||
data: data
|
||||
} : {
|
||||
errors: exeContext.errors,
|
||||
data: data
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Given a ResponsePath (found in the `path` entry in the information provided
|
||||
* as the last argument to a field resolver), return an Array of the path keys.
|
||||
*/
|
||||
|
||||
|
||||
function responsePathAsArray(path) {
|
||||
var flattened = [];
|
||||
var curr = path;
|
||||
|
||||
while (curr) {
|
||||
flattened.push(curr.key);
|
||||
curr = curr.prev;
|
||||
}
|
||||
|
||||
return flattened.reverse();
|
||||
}
|
||||
/**
|
||||
* Given a ResponsePath and a key, return a new ResponsePath containing the
|
||||
* new key.
|
||||
*/
|
||||
|
||||
|
||||
function addPath(prev, key) {
|
||||
return {
|
||||
prev: prev,
|
||||
key: key
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Essential assertions before executing to provide developer feedback for
|
||||
* improper use of the GraphQL library.
|
||||
*/
|
||||
|
||||
|
||||
function assertValidExecutionArguments(schema, document, rawVariableValues) {
|
||||
!document ? (0, _invariant.default)(0, 'Must provide document') : void 0; // If the schema used for execution is invalid, throw an error.
|
||||
|
||||
(0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object.
|
||||
|
||||
!(!rawVariableValues || _typeof(rawVariableValues) === 'object') ? (0, _invariant.default)(0, '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.') : void 0;
|
||||
}
|
||||
/**
|
||||
* Constructs a ExecutionContext object from the arguments passed to
|
||||
* execute, which we will pass throughout the other execution methods.
|
||||
*
|
||||
* Throws a GraphQLError if a valid execution context cannot be created.
|
||||
*/
|
||||
|
||||
|
||||
function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver) {
|
||||
var errors = [];
|
||||
var operation;
|
||||
var hasMultipleAssumedOperations = false;
|
||||
var fragments = Object.create(null);
|
||||
|
||||
for (var i = 0; i < document.definitions.length; i++) {
|
||||
var definition = document.definitions[i];
|
||||
|
||||
switch (definition.kind) {
|
||||
case _kinds.Kind.OPERATION_DEFINITION:
|
||||
if (!operationName && operation) {
|
||||
hasMultipleAssumedOperations = true;
|
||||
} else if (!operationName || definition.name && definition.name.value === operationName) {
|
||||
operation = definition;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.FRAGMENT_DEFINITION:
|
||||
fragments[definition.name.value] = definition;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!operation) {
|
||||
if (operationName) {
|
||||
errors.push(new _GraphQLError.GraphQLError("Unknown operation named \"".concat(operationName, "\".")));
|
||||
} else {
|
||||
errors.push(new _GraphQLError.GraphQLError('Must provide an operation.'));
|
||||
}
|
||||
} else if (hasMultipleAssumedOperations) {
|
||||
errors.push(new _GraphQLError.GraphQLError('Must provide operation name if query contains ' + 'multiple operations.'));
|
||||
}
|
||||
|
||||
var variableValues;
|
||||
|
||||
if (operation) {
|
||||
var coercedVariableValues = (0, _values.getVariableValues)(schema, operation.variableDefinitions || [], rawVariableValues || {});
|
||||
|
||||
if (coercedVariableValues.errors) {
|
||||
errors.push.apply(errors, coercedVariableValues.errors);
|
||||
} else {
|
||||
variableValues = coercedVariableValues.coerced;
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length !== 0) {
|
||||
return errors;
|
||||
}
|
||||
|
||||
!operation ? (0, _invariant.default)(0, 'Has operation if no errors.') : void 0;
|
||||
!variableValues ? (0, _invariant.default)(0, 'Has variables if no errors.') : void 0;
|
||||
return {
|
||||
schema: schema,
|
||||
fragments: fragments,
|
||||
rootValue: rootValue,
|
||||
contextValue: contextValue,
|
||||
operation: operation,
|
||||
variableValues: variableValues,
|
||||
fieldResolver: fieldResolver || defaultFieldResolver,
|
||||
errors: errors
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Implements the "Evaluating operations" section of the spec.
|
||||
*/
|
||||
|
||||
|
||||
function executeOperation(exeContext, operation, rootValue) {
|
||||
var type = (0, _getOperationRootType.getOperationRootType)(exeContext.schema, operation);
|
||||
var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null));
|
||||
var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level,
|
||||
// at which point we still log the error and null the parent field, which
|
||||
// in this case is the entire response.
|
||||
//
|
||||
// Similar to completeValueCatchingError.
|
||||
|
||||
try {
|
||||
var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields);
|
||||
|
||||
if ((0, _isPromise.default)(result)) {
|
||||
return result.then(undefined, function (error) {
|
||||
exeContext.errors.push(error);
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
exeContext.errors.push(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Implements the "Evaluating selection sets" section of the spec
|
||||
* for "write" mode.
|
||||
*/
|
||||
|
||||
|
||||
function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) {
|
||||
return (0, _promiseReduce.default)(Object.keys(fields), function (results, responseName) {
|
||||
var fieldNodes = fields[responseName];
|
||||
var fieldPath = addPath(path, responseName);
|
||||
var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
|
||||
|
||||
if (result === undefined) {
|
||||
return results;
|
||||
}
|
||||
|
||||
if ((0, _isPromise.default)(result)) {
|
||||
return result.then(function (resolvedResult) {
|
||||
results[responseName] = resolvedResult;
|
||||
return results;
|
||||
});
|
||||
}
|
||||
|
||||
results[responseName] = result;
|
||||
return results;
|
||||
}, Object.create(null));
|
||||
}
|
||||
/**
|
||||
* Implements the "Evaluating selection sets" section of the spec
|
||||
* for "read" mode.
|
||||
*/
|
||||
|
||||
|
||||
function executeFields(exeContext, parentType, sourceValue, path, fields) {
|
||||
var results = Object.create(null);
|
||||
var containsPromise = false;
|
||||
|
||||
for (var i = 0, keys = Object.keys(fields); i < keys.length; ++i) {
|
||||
var responseName = keys[i];
|
||||
var fieldNodes = fields[responseName];
|
||||
var fieldPath = addPath(path, responseName);
|
||||
var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
|
||||
|
||||
if (result !== undefined) {
|
||||
results[responseName] = result;
|
||||
|
||||
if (!containsPromise && (0, _isPromise.default)(result)) {
|
||||
containsPromise = true;
|
||||
}
|
||||
}
|
||||
} // If there are no promises, we can just return the object
|
||||
|
||||
|
||||
if (!containsPromise) {
|
||||
return results;
|
||||
} // Otherwise, results is a map from field name to the result of resolving that
|
||||
// field, which is possibly a promise. Return a promise that will return this
|
||||
// same map, but with any promises replaced with the values they resolved to.
|
||||
|
||||
|
||||
return (0, _promiseForObject.default)(results);
|
||||
}
|
||||
/**
|
||||
* Given a selectionSet, adds all of the fields in that selection to
|
||||
* the passed in map of fields, and returns it at the end.
|
||||
*
|
||||
* CollectFields requires the "runtime type" of an object. For a field which
|
||||
* returns an Interface or Union type, the "runtime type" will be the actual
|
||||
* Object type returned by that field.
|
||||
*/
|
||||
|
||||
|
||||
function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) {
|
||||
for (var i = 0; i < selectionSet.selections.length; i++) {
|
||||
var selection = selectionSet.selections[i];
|
||||
|
||||
switch (selection.kind) {
|
||||
case _kinds.Kind.FIELD:
|
||||
if (!shouldIncludeNode(exeContext, selection)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var name = getFieldEntryKey(selection);
|
||||
|
||||
if (!fields[name]) {
|
||||
fields[name] = [];
|
||||
}
|
||||
|
||||
fields[name].push(selection);
|
||||
break;
|
||||
|
||||
case _kinds.Kind.INLINE_FRAGMENT:
|
||||
if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames);
|
||||
break;
|
||||
|
||||
case _kinds.Kind.FRAGMENT_SPREAD:
|
||||
var fragName = selection.name.value;
|
||||
|
||||
if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
visitedFragmentNames[fragName] = true;
|
||||
var fragment = exeContext.fragments[fragName];
|
||||
|
||||
if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return fields;
|
||||
}
|
||||
/**
|
||||
* Determines if a field should be included based on the @include and @skip
|
||||
* directives, where @skip has higher precidence than @include.
|
||||
*/
|
||||
|
||||
|
||||
function shouldIncludeNode(exeContext, node) {
|
||||
var skip = (0, _values.getDirectiveValues)(_directives.GraphQLSkipDirective, node, exeContext.variableValues);
|
||||
|
||||
if (skip && skip.if === true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var include = (0, _values.getDirectiveValues)(_directives.GraphQLIncludeDirective, node, exeContext.variableValues);
|
||||
|
||||
if (include && include.if === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Determines if a fragment is applicable to the given type.
|
||||
*/
|
||||
|
||||
|
||||
function doesFragmentConditionMatch(exeContext, fragment, type) {
|
||||
var typeConditionNode = fragment.typeCondition;
|
||||
|
||||
if (!typeConditionNode) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var conditionalType = (0, _typeFromAST.typeFromAST)(exeContext.schema, typeConditionNode);
|
||||
|
||||
if (conditionalType === type) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ((0, _definition.isAbstractType)(conditionalType)) {
|
||||
return exeContext.schema.isPossibleType(conditionalType, type);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Implements the logic to compute the key of a given field's entry
|
||||
*/
|
||||
|
||||
|
||||
function getFieldEntryKey(node) {
|
||||
return node.alias ? node.alias.value : node.name.value;
|
||||
}
|
||||
/**
|
||||
* Resolves the field on the given source object. In particular, this
|
||||
* figures out the value that the field returns by calling its resolve function,
|
||||
* then calls completeValue to complete promises, serialize scalars, or execute
|
||||
* the sub-selection-set for objects.
|
||||
*/
|
||||
|
||||
|
||||
function resolveField(exeContext, parentType, source, fieldNodes, path) {
|
||||
var fieldNode = fieldNodes[0];
|
||||
var fieldName = fieldNode.name.value;
|
||||
var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName);
|
||||
|
||||
if (!fieldDef) {
|
||||
return;
|
||||
}
|
||||
|
||||
var resolveFn = fieldDef.resolve || exeContext.fieldResolver;
|
||||
var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal
|
||||
// or abrupt (error).
|
||||
|
||||
var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info);
|
||||
return completeValueCatchingError(exeContext, fieldDef.type, fieldNodes, info, path, result);
|
||||
}
|
||||
|
||||
function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) {
|
||||
// The resolve function's optional fourth argument is a collection of
|
||||
// information about the current execution state.
|
||||
return {
|
||||
fieldName: fieldDef.name,
|
||||
fieldNodes: fieldNodes,
|
||||
returnType: fieldDef.type,
|
||||
parentType: parentType,
|
||||
path: path,
|
||||
schema: exeContext.schema,
|
||||
fragments: exeContext.fragments,
|
||||
rootValue: exeContext.rootValue,
|
||||
operation: exeContext.operation,
|
||||
variableValues: exeContext.variableValues
|
||||
};
|
||||
} // Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField`
|
||||
// function. Returns the result of resolveFn or the abrupt-return Error object.
|
||||
|
||||
|
||||
function resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info) {
|
||||
try {
|
||||
// Build a JS object of arguments from the field.arguments AST, using the
|
||||
// variables scope to fulfill any variable references.
|
||||
// TODO: find a way to memoize, in case this field is within a List type.
|
||||
var args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that
|
||||
// is provided to every resolve function within an execution. It is commonly
|
||||
// used to represent an authenticated user, or request-specific caches.
|
||||
|
||||
var _contextValue = exeContext.contextValue;
|
||||
var result = resolveFn(source, args, _contextValue, info);
|
||||
return (0, _isPromise.default)(result) ? result.then(undefined, asErrorInstance) : result;
|
||||
} catch (error) {
|
||||
return asErrorInstance(error);
|
||||
}
|
||||
} // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a
|
||||
// consistent Error interface.
|
||||
|
||||
|
||||
function asErrorInstance(error) {
|
||||
return error instanceof Error ? error : new Error(error || undefined);
|
||||
} // This is a small wrapper around completeValue which detects and logs errors
|
||||
// in the execution context.
|
||||
|
||||
|
||||
function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) {
|
||||
try {
|
||||
var completed;
|
||||
|
||||
if ((0, _isPromise.default)(result)) {
|
||||
completed = result.then(function (resolved) {
|
||||
return completeValue(exeContext, returnType, fieldNodes, info, path, resolved);
|
||||
});
|
||||
} else {
|
||||
completed = completeValue(exeContext, returnType, fieldNodes, info, path, result);
|
||||
}
|
||||
|
||||
if ((0, _isPromise.default)(completed)) {
|
||||
// Note: we don't rely on a `catch` method, but we do expect "thenable"
|
||||
// to take a second callback for the error case.
|
||||
return completed.then(undefined, function (error) {
|
||||
return handleFieldError(error, fieldNodes, path, returnType, exeContext);
|
||||
});
|
||||
}
|
||||
|
||||
return completed;
|
||||
} catch (error) {
|
||||
return handleFieldError(error, fieldNodes, path, returnType, exeContext);
|
||||
}
|
||||
}
|
||||
|
||||
function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) {
|
||||
var error = (0, _locatedError.locatedError)(asErrorInstance(rawError), fieldNodes, responsePathAsArray(path)); // If the field type is non-nullable, then it is resolved without any
|
||||
// protection from errors, however it still properly locates the error.
|
||||
|
||||
if ((0, _definition.isNonNullType)(returnType)) {
|
||||
throw error;
|
||||
} // Otherwise, error protection is applied, logging the error and resolving
|
||||
// a null value for this field if one is encountered.
|
||||
|
||||
|
||||
exeContext.errors.push(error);
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Implements the instructions for completeValue as defined in the
|
||||
* "Field entries" section of the spec.
|
||||
*
|
||||
* If the field type is Non-Null, then this recursively completes the value
|
||||
* for the inner type. It throws a field error if that completion returns null,
|
||||
* as per the "Nullability" section of the spec.
|
||||
*
|
||||
* If the field type is a List, then this recursively completes the value
|
||||
* for the inner type on each item in the list.
|
||||
*
|
||||
* If the field type is a Scalar or Enum, ensures the completed value is a legal
|
||||
* value of the type by calling the `serialize` method of GraphQL type
|
||||
* definition.
|
||||
*
|
||||
* If the field is an abstract type, determine the runtime type of the value
|
||||
* and then complete based on that type
|
||||
*
|
||||
* Otherwise, the field type expects a sub-selection set, and will complete the
|
||||
* value by evaluating all sub-selections.
|
||||
*/
|
||||
|
||||
|
||||
function completeValue(exeContext, returnType, fieldNodes, info, path, result) {
|
||||
// If result is an Error, throw a located error.
|
||||
if (result instanceof Error) {
|
||||
throw result;
|
||||
} // If field type is NonNull, complete for inner type, and throw field error
|
||||
// if result is null.
|
||||
|
||||
|
||||
if ((0, _definition.isNonNullType)(returnType)) {
|
||||
var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result);
|
||||
|
||||
if (completed === null) {
|
||||
throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, "."));
|
||||
}
|
||||
|
||||
return completed;
|
||||
} // If result value is null-ish (null, undefined, or NaN) then return null.
|
||||
|
||||
|
||||
if ((0, _isNullish.default)(result)) {
|
||||
return null;
|
||||
} // If field type is List, complete each item in the list with the inner type
|
||||
|
||||
|
||||
if ((0, _definition.isListType)(returnType)) {
|
||||
return completeListValue(exeContext, returnType, fieldNodes, info, path, result);
|
||||
} // If field type is a leaf type, Scalar or Enum, serialize to a valid value,
|
||||
// returning null if serialization is not possible.
|
||||
|
||||
|
||||
if ((0, _definition.isLeafType)(returnType)) {
|
||||
return completeLeafValue(returnType, result);
|
||||
} // If field type is an abstract type, Interface or Union, determine the
|
||||
// runtime Object type and complete for that type.
|
||||
|
||||
|
||||
if ((0, _definition.isAbstractType)(returnType)) {
|
||||
return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result);
|
||||
} // If field type is Object, execute and complete all sub-selections.
|
||||
|
||||
|
||||
if ((0, _definition.isObjectType)(returnType)) {
|
||||
return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result);
|
||||
} // Not reachable. All possible output types have been considered.
|
||||
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Cannot complete value of unexpected type \"".concat((0, _inspect.default)(returnType), "\"."));
|
||||
}
|
||||
/**
|
||||
* Complete a list value by completing each item in the list with the
|
||||
* inner type
|
||||
*/
|
||||
|
||||
|
||||
function completeListValue(exeContext, returnType, fieldNodes, info, path, result) {
|
||||
!(0, _iterall.isCollection)(result) ? (0, _invariant.default)(0, "Expected Iterable, but did not find one for field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")) : void 0; // This is specified as a simple map, however we're optimizing the path
|
||||
// where the list contains no Promises by avoiding creating another Promise.
|
||||
|
||||
var itemType = returnType.ofType;
|
||||
var containsPromise = false;
|
||||
var completedResults = [];
|
||||
(0, _iterall.forEach)(result, function (item, index) {
|
||||
// No need to modify the info object containing the path,
|
||||
// since from here on it is not ever accessed by resolver functions.
|
||||
var fieldPath = addPath(path, index);
|
||||
var completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item);
|
||||
|
||||
if (!containsPromise && (0, _isPromise.default)(completedItem)) {
|
||||
containsPromise = true;
|
||||
}
|
||||
|
||||
completedResults.push(completedItem);
|
||||
});
|
||||
return containsPromise ? Promise.all(completedResults) : completedResults;
|
||||
}
|
||||
/**
|
||||
* Complete a Scalar or Enum by serializing to a valid value, returning
|
||||
* null if serialization is not possible.
|
||||
*/
|
||||
|
||||
|
||||
function completeLeafValue(returnType, result) {
|
||||
!returnType.serialize ? (0, _invariant.default)(0, 'Missing serialize method on type') : void 0;
|
||||
var serializedResult = returnType.serialize(result);
|
||||
|
||||
if ((0, _isInvalid.default)(serializedResult)) {
|
||||
throw new Error("Expected a value of type \"".concat((0, _inspect.default)(returnType), "\" but ") + "received: ".concat((0, _inspect.default)(result)));
|
||||
}
|
||||
|
||||
return serializedResult;
|
||||
}
|
||||
/**
|
||||
* Complete a value of an abstract type by determining the runtime object type
|
||||
* of that value, then complete the value for that type.
|
||||
*/
|
||||
|
||||
|
||||
function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) {
|
||||
var runtimeType = returnType.resolveType ? returnType.resolveType(result, exeContext.contextValue, info) : defaultResolveTypeFn(result, exeContext.contextValue, info, returnType);
|
||||
|
||||
if ((0, _isPromise.default)(runtimeType)) {
|
||||
return runtimeType.then(function (resolvedRuntimeType) {
|
||||
return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
|
||||
});
|
||||
}
|
||||
|
||||
return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
|
||||
}
|
||||
|
||||
function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) {
|
||||
var runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName;
|
||||
|
||||
if (!(0, _definition.isObjectType)(runtimeType)) {
|
||||
throw new _GraphQLError.GraphQLError("Abstract type ".concat(returnType.name, " must resolve to an Object type at ") + "runtime for field ".concat(info.parentType.name, ".").concat(info.fieldName, " with ") + "value ".concat((0, _inspect.default)(result), ", received \"").concat((0, _inspect.default)(runtimeType), "\". ") + "Either the ".concat(returnType.name, " type should provide a \"resolveType\" ") + 'function or each possible type should provide an ' + '"isTypeOf" function.', fieldNodes);
|
||||
}
|
||||
|
||||
if (!exeContext.schema.isPossibleType(returnType, runtimeType)) {
|
||||
throw new _GraphQLError.GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type ") + "for \"".concat(returnType.name, "\"."), fieldNodes);
|
||||
}
|
||||
|
||||
return runtimeType;
|
||||
}
|
||||
/**
|
||||
* Complete an Object value by executing all sub-selections.
|
||||
*/
|
||||
|
||||
|
||||
function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) {
|
||||
// If there is an isTypeOf predicate function, call it with the
|
||||
// current result. If isTypeOf returns false, then raise an error rather
|
||||
// than continuing execution.
|
||||
if (returnType.isTypeOf) {
|
||||
var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);
|
||||
|
||||
if ((0, _isPromise.default)(isTypeOf)) {
|
||||
return isTypeOf.then(function (resolvedIsTypeOf) {
|
||||
if (!resolvedIsTypeOf) {
|
||||
throw invalidReturnTypeError(returnType, result, fieldNodes);
|
||||
}
|
||||
|
||||
return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);
|
||||
});
|
||||
}
|
||||
|
||||
if (!isTypeOf) {
|
||||
throw invalidReturnTypeError(returnType, result, fieldNodes);
|
||||
}
|
||||
}
|
||||
|
||||
return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);
|
||||
}
|
||||
|
||||
function invalidReturnTypeError(returnType, result, fieldNodes) {
|
||||
return new _GraphQLError.GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat((0, _inspect.default)(result), "."), fieldNodes);
|
||||
}
|
||||
|
||||
function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) {
|
||||
// Collect sub-fields to execute to complete this value.
|
||||
var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes);
|
||||
return executeFields(exeContext, returnType, result, path, subFieldNodes);
|
||||
}
|
||||
/**
|
||||
* A memoized collection of relevant subfields with regard to the return
|
||||
* type. Memoizing ensures the subfields are not repeatedly calculated, which
|
||||
* saves overhead when resolving lists of values.
|
||||
*/
|
||||
|
||||
|
||||
var collectSubfields = (0, _memoize.default)(_collectSubfields);
|
||||
|
||||
function _collectSubfields(exeContext, returnType, fieldNodes) {
|
||||
var subFieldNodes = Object.create(null);
|
||||
var visitedFragmentNames = Object.create(null);
|
||||
|
||||
for (var i = 0; i < fieldNodes.length; i++) {
|
||||
var selectionSet = fieldNodes[i].selectionSet;
|
||||
|
||||
if (selectionSet) {
|
||||
subFieldNodes = collectFields(exeContext, returnType, selectionSet, subFieldNodes, visitedFragmentNames);
|
||||
}
|
||||
}
|
||||
|
||||
return subFieldNodes;
|
||||
}
|
||||
/**
|
||||
* If a resolveType function is not given, then a default resolve behavior is
|
||||
* used which attempts two strategies:
|
||||
*
|
||||
* First, See if the provided value has a `__typename` field defined, if so, use
|
||||
* that value as name of the resolved type.
|
||||
*
|
||||
* Otherwise, test each possible type for the abstract type by calling
|
||||
* isTypeOf for the object being coerced, returning the first type that matches.
|
||||
*/
|
||||
|
||||
|
||||
function defaultResolveTypeFn(value, contextValue, info, abstractType) {
|
||||
// First, look for `__typename`.
|
||||
if (value !== null && _typeof(value) === 'object' && typeof value.__typename === 'string') {
|
||||
return value.__typename;
|
||||
} // Otherwise, test each possible type.
|
||||
|
||||
|
||||
var possibleTypes = info.schema.getPossibleTypes(abstractType);
|
||||
var promisedIsTypeOfResults = [];
|
||||
|
||||
for (var i = 0; i < possibleTypes.length; i++) {
|
||||
var type = possibleTypes[i];
|
||||
|
||||
if (type.isTypeOf) {
|
||||
var isTypeOfResult = type.isTypeOf(value, contextValue, info);
|
||||
|
||||
if ((0, _isPromise.default)(isTypeOfResult)) {
|
||||
promisedIsTypeOfResults[i] = isTypeOfResult;
|
||||
} else if (isTypeOfResult) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (promisedIsTypeOfResults.length) {
|
||||
return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) {
|
||||
for (var _i = 0; _i < isTypeOfResults.length; _i++) {
|
||||
if (isTypeOfResults[_i]) {
|
||||
return possibleTypes[_i];
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* If a resolve function is not given, then a default resolve behavior is used
|
||||
* which takes the property of the source object of the same name as the field
|
||||
* and returns it as the result, or if it's a function, returns the result
|
||||
* of calling that function while passing along args and context value.
|
||||
*/
|
||||
|
||||
|
||||
var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) {
|
||||
// ensure source is a value for which property access is acceptable.
|
||||
if (_typeof(source) === 'object' || typeof source === 'function') {
|
||||
var property = source[info.fieldName];
|
||||
|
||||
if (typeof property === 'function') {
|
||||
return source[info.fieldName](args, contextValue, info);
|
||||
}
|
||||
|
||||
return property;
|
||||
}
|
||||
};
|
||||
/**
|
||||
* This method looks up the field on the given type defintion.
|
||||
* It has special casing for the two introspection fields, __schema
|
||||
* and __typename. __typename is special because it can always be
|
||||
* queried as a field, even in situations where no other fields
|
||||
* are allowed, like on a Union. __schema could get automatically
|
||||
* added to the query type, but that would require mutating type
|
||||
* definitions, which would cause issues.
|
||||
*/
|
||||
|
||||
|
||||
exports.defaultFieldResolver = defaultFieldResolver;
|
||||
|
||||
function getFieldDef(schema, parentType, fieldName) {
|
||||
if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
|
||||
return _introspection.SchemaMetaFieldDef;
|
||||
} else if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
|
||||
return _introspection.TypeMetaFieldDef;
|
||||
} else if (fieldName === _introspection.TypeNameMetaFieldDef.name) {
|
||||
return _introspection.TypeNameMetaFieldDef;
|
||||
}
|
||||
|
||||
return parentType.getFields()[fieldName];
|
||||
}
|
||||
+1270
File diff suppressed because it is too large.
Load diff
+792
@@ -0,0 +1,792 @@
|
||||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { forEach, isCollection } from 'iterall';
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import { locatedError } from '../error/locatedError';
|
||||
import inspect from '../jsutils/inspect';
|
||||
import invariant from '../jsutils/invariant';
|
||||
import isInvalid from '../jsutils/isInvalid';
|
||||
import isNullish from '../jsutils/isNullish';
|
||||
import isPromise from '../jsutils/isPromise';
|
||||
import memoize3 from '../jsutils/memoize3';
|
||||
import promiseForObject from '../jsutils/promiseForObject';
|
||||
import promiseReduce from '../jsutils/promiseReduce';
|
||||
import { getOperationRootType } from '../utilities/getOperationRootType';
|
||||
import { typeFromAST } from '../utilities/typeFromAST';
|
||||
import { Kind } from '../language/kinds';
|
||||
import { getVariableValues, getArgumentValues, getDirectiveValues } from './values';
|
||||
import { isObjectType, isAbstractType, isLeafType, isListType, isNonNullType } from '../type/definition';
|
||||
import { SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from '../type/introspection';
|
||||
import { GraphQLIncludeDirective, GraphQLSkipDirective } from '../type/directives';
|
||||
import { assertValidSchema } from '../type/validate';
|
||||
export function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) {
|
||||
/* eslint-enable no-redeclare */
|
||||
// Extract arguments from object args if provided.
|
||||
return arguments.length === 1 ? executeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : executeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver);
|
||||
}
|
||||
|
||||
function executeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) {
|
||||
// If arguments are missing or incorrect, throw an error.
|
||||
assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments,
|
||||
// a "Response" with only errors is returned.
|
||||
|
||||
var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed.
|
||||
|
||||
if (Array.isArray(exeContext)) {
|
||||
return {
|
||||
errors: exeContext
|
||||
};
|
||||
} // Return a Promise that will eventually resolve to the data described by
|
||||
// The "Response" section of the GraphQL specification.
|
||||
//
|
||||
// If errors are encountered while executing a GraphQL field, only that
|
||||
// field and its descendants will be omitted, and sibling fields will still
|
||||
// be executed. An execution which encounters errors will still result in a
|
||||
// resolved Promise.
|
||||
|
||||
|
||||
var data = executeOperation(exeContext, exeContext.operation, rootValue);
|
||||
return buildResponse(exeContext, data);
|
||||
}
|
||||
/**
|
||||
* Given a completed execution context and data, build the { errors, data }
|
||||
* response defined by the "Response" section of the GraphQL specification.
|
||||
*/
|
||||
|
||||
|
||||
function buildResponse(exeContext, data) {
|
||||
if (isPromise(data)) {
|
||||
return data.then(function (resolved) {
|
||||
return buildResponse(exeContext, resolved);
|
||||
});
|
||||
}
|
||||
|
||||
return exeContext.errors.length === 0 ? {
|
||||
data: data
|
||||
} : {
|
||||
errors: exeContext.errors,
|
||||
data: data
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Given a ResponsePath (found in the `path` entry in the information provided
|
||||
* as the last argument to a field resolver), return an Array of the path keys.
|
||||
*/
|
||||
|
||||
|
||||
export function responsePathAsArray(path) {
|
||||
var flattened = [];
|
||||
var curr = path;
|
||||
|
||||
while (curr) {
|
||||
flattened.push(curr.key);
|
||||
curr = curr.prev;
|
||||
}
|
||||
|
||||
return flattened.reverse();
|
||||
}
|
||||
/**
|
||||
* Given a ResponsePath and a key, return a new ResponsePath containing the
|
||||
* new key.
|
||||
*/
|
||||
|
||||
export function addPath(prev, key) {
|
||||
return {
|
||||
prev: prev,
|
||||
key: key
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Essential assertions before executing to provide developer feedback for
|
||||
* improper use of the GraphQL library.
|
||||
*/
|
||||
|
||||
export function assertValidExecutionArguments(schema, document, rawVariableValues) {
|
||||
!document ? invariant(0, 'Must provide document') : void 0; // If the schema used for execution is invalid, throw an error.
|
||||
|
||||
assertValidSchema(schema); // Variables, if provided, must be an object.
|
||||
|
||||
!(!rawVariableValues || _typeof(rawVariableValues) === 'object') ? invariant(0, '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.') : void 0;
|
||||
}
|
||||
/**
|
||||
* Constructs a ExecutionContext object from the arguments passed to
|
||||
* execute, which we will pass throughout the other execution methods.
|
||||
*
|
||||
* Throws a GraphQLError if a valid execution context cannot be created.
|
||||
*/
|
||||
|
||||
export function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver) {
|
||||
var errors = [];
|
||||
var operation;
|
||||
var hasMultipleAssumedOperations = false;
|
||||
var fragments = Object.create(null);
|
||||
|
||||
for (var i = 0; i < document.definitions.length; i++) {
|
||||
var definition = document.definitions[i];
|
||||
|
||||
switch (definition.kind) {
|
||||
case Kind.OPERATION_DEFINITION:
|
||||
if (!operationName && operation) {
|
||||
hasMultipleAssumedOperations = true;
|
||||
} else if (!operationName || definition.name && definition.name.value === operationName) {
|
||||
operation = definition;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case Kind.FRAGMENT_DEFINITION:
|
||||
fragments[definition.name.value] = definition;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!operation) {
|
||||
if (operationName) {
|
||||
errors.push(new GraphQLError("Unknown operation named \"".concat(operationName, "\".")));
|
||||
} else {
|
||||
errors.push(new GraphQLError('Must provide an operation.'));
|
||||
}
|
||||
} else if (hasMultipleAssumedOperations) {
|
||||
errors.push(new GraphQLError('Must provide operation name if query contains ' + 'multiple operations.'));
|
||||
}
|
||||
|
||||
var variableValues;
|
||||
|
||||
if (operation) {
|
||||
var coercedVariableValues = getVariableValues(schema, operation.variableDefinitions || [], rawVariableValues || {});
|
||||
|
||||
if (coercedVariableValues.errors) {
|
||||
errors.push.apply(errors, coercedVariableValues.errors);
|
||||
} else {
|
||||
variableValues = coercedVariableValues.coerced;
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length !== 0) {
|
||||
return errors;
|
||||
}
|
||||
|
||||
!operation ? invariant(0, 'Has operation if no errors.') : void 0;
|
||||
!variableValues ? invariant(0, 'Has variables if no errors.') : void 0;
|
||||
return {
|
||||
schema: schema,
|
||||
fragments: fragments,
|
||||
rootValue: rootValue,
|
||||
contextValue: contextValue,
|
||||
operation: operation,
|
||||
variableValues: variableValues,
|
||||
fieldResolver: fieldResolver || defaultFieldResolver,
|
||||
errors: errors
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Implements the "Evaluating operations" section of the spec.
|
||||
*/
|
||||
|
||||
function executeOperation(exeContext, operation, rootValue) {
|
||||
var type = getOperationRootType(exeContext.schema, operation);
|
||||
var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null));
|
||||
var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level,
|
||||
// at which point we still log the error and null the parent field, which
|
||||
// in this case is the entire response.
|
||||
//
|
||||
// Similar to completeValueCatchingError.
|
||||
|
||||
try {
|
||||
var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields);
|
||||
|
||||
if (isPromise(result)) {
|
||||
return result.then(undefined, function (error) {
|
||||
exeContext.errors.push(error);
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
exeContext.errors.push(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Implements the "Evaluating selection sets" section of the spec
|
||||
* for "write" mode.
|
||||
*/
|
||||
|
||||
|
||||
function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) {
|
||||
return promiseReduce(Object.keys(fields), function (results, responseName) {
|
||||
var fieldNodes = fields[responseName];
|
||||
var fieldPath = addPath(path, responseName);
|
||||
var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
|
||||
|
||||
if (result === undefined) {
|
||||
return results;
|
||||
}
|
||||
|
||||
if (isPromise(result)) {
|
||||
return result.then(function (resolvedResult) {
|
||||
results[responseName] = resolvedResult;
|
||||
return results;
|
||||
});
|
||||
}
|
||||
|
||||
results[responseName] = result;
|
||||
return results;
|
||||
}, Object.create(null));
|
||||
}
|
||||
/**
|
||||
* Implements the "Evaluating selection sets" section of the spec
|
||||
* for "read" mode.
|
||||
*/
|
||||
|
||||
|
||||
function executeFields(exeContext, parentType, sourceValue, path, fields) {
|
||||
var results = Object.create(null);
|
||||
var containsPromise = false;
|
||||
|
||||
for (var i = 0, keys = Object.keys(fields); i < keys.length; ++i) {
|
||||
var responseName = keys[i];
|
||||
var fieldNodes = fields[responseName];
|
||||
var fieldPath = addPath(path, responseName);
|
||||
var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
|
||||
|
||||
if (result !== undefined) {
|
||||
results[responseName] = result;
|
||||
|
||||
if (!containsPromise && isPromise(result)) {
|
||||
containsPromise = true;
|
||||
}
|
||||
}
|
||||
} // If there are no promises, we can just return the object
|
||||
|
||||
|
||||
if (!containsPromise) {
|
||||
return results;
|
||||
} // Otherwise, results is a map from field name to the result of resolving that
|
||||
// field, which is possibly a promise. Return a promise that will return this
|
||||
// same map, but with any promises replaced with the values they resolved to.
|
||||
|
||||
|
||||
return promiseForObject(results);
|
||||
}
|
||||
/**
|
||||
* Given a selectionSet, adds all of the fields in that selection to
|
||||
* the passed in map of fields, and returns it at the end.
|
||||
*
|
||||
* CollectFields requires the "runtime type" of an object. For a field which
|
||||
* returns an Interface or Union type, the "runtime type" will be the actual
|
||||
* Object type returned by that field.
|
||||
*/
|
||||
|
||||
|
||||
export function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) {
|
||||
for (var i = 0; i < selectionSet.selections.length; i++) {
|
||||
var selection = selectionSet.selections[i];
|
||||
|
||||
switch (selection.kind) {
|
||||
case Kind.FIELD:
|
||||
if (!shouldIncludeNode(exeContext, selection)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var name = getFieldEntryKey(selection);
|
||||
|
||||
if (!fields[name]) {
|
||||
fields[name] = [];
|
||||
}
|
||||
|
||||
fields[name].push(selection);
|
||||
break;
|
||||
|
||||
case Kind.INLINE_FRAGMENT:
|
||||
if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames);
|
||||
break;
|
||||
|
||||
case Kind.FRAGMENT_SPREAD:
|
||||
var fragName = selection.name.value;
|
||||
|
||||
if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
visitedFragmentNames[fragName] = true;
|
||||
var fragment = exeContext.fragments[fragName];
|
||||
|
||||
if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return fields;
|
||||
}
|
||||
/**
|
||||
* Determines if a field should be included based on the @include and @skip
|
||||
* directives, where @skip has higher precidence than @include.
|
||||
*/
|
||||
|
||||
function shouldIncludeNode(exeContext, node) {
|
||||
var skip = getDirectiveValues(GraphQLSkipDirective, node, exeContext.variableValues);
|
||||
|
||||
if (skip && skip.if === true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var include = getDirectiveValues(GraphQLIncludeDirective, node, exeContext.variableValues);
|
||||
|
||||
if (include && include.if === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Determines if a fragment is applicable to the given type.
|
||||
*/
|
||||
|
||||
|
||||
function doesFragmentConditionMatch(exeContext, fragment, type) {
|
||||
var typeConditionNode = fragment.typeCondition;
|
||||
|
||||
if (!typeConditionNode) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var conditionalType = typeFromAST(exeContext.schema, typeConditionNode);
|
||||
|
||||
if (conditionalType === type) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isAbstractType(conditionalType)) {
|
||||
return exeContext.schema.isPossibleType(conditionalType, type);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Implements the logic to compute the key of a given field's entry
|
||||
*/
|
||||
|
||||
|
||||
function getFieldEntryKey(node) {
|
||||
return node.alias ? node.alias.value : node.name.value;
|
||||
}
|
||||
/**
|
||||
* Resolves the field on the given source object. In particular, this
|
||||
* figures out the value that the field returns by calling its resolve function,
|
||||
* then calls completeValue to complete promises, serialize scalars, or execute
|
||||
* the sub-selection-set for objects.
|
||||
*/
|
||||
|
||||
|
||||
function resolveField(exeContext, parentType, source, fieldNodes, path) {
|
||||
var fieldNode = fieldNodes[0];
|
||||
var fieldName = fieldNode.name.value;
|
||||
var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName);
|
||||
|
||||
if (!fieldDef) {
|
||||
return;
|
||||
}
|
||||
|
||||
var resolveFn = fieldDef.resolve || exeContext.fieldResolver;
|
||||
var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal
|
||||
// or abrupt (error).
|
||||
|
||||
var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info);
|
||||
return completeValueCatchingError(exeContext, fieldDef.type, fieldNodes, info, path, result);
|
||||
}
|
||||
|
||||
export function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) {
|
||||
// The resolve function's optional fourth argument is a collection of
|
||||
// information about the current execution state.
|
||||
return {
|
||||
fieldName: fieldDef.name,
|
||||
fieldNodes: fieldNodes,
|
||||
returnType: fieldDef.type,
|
||||
parentType: parentType,
|
||||
path: path,
|
||||
schema: exeContext.schema,
|
||||
fragments: exeContext.fragments,
|
||||
rootValue: exeContext.rootValue,
|
||||
operation: exeContext.operation,
|
||||
variableValues: exeContext.variableValues
|
||||
};
|
||||
} // Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField`
|
||||
// function. Returns the result of resolveFn or the abrupt-return Error object.
|
||||
|
||||
export function resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info) {
|
||||
try {
|
||||
// Build a JS object of arguments from the field.arguments AST, using the
|
||||
// variables scope to fulfill any variable references.
|
||||
// TODO: find a way to memoize, in case this field is within a List type.
|
||||
var args = getArgumentValues(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that
|
||||
// is provided to every resolve function within an execution. It is commonly
|
||||
// used to represent an authenticated user, or request-specific caches.
|
||||
|
||||
var _contextValue = exeContext.contextValue;
|
||||
var result = resolveFn(source, args, _contextValue, info);
|
||||
return isPromise(result) ? result.then(undefined, asErrorInstance) : result;
|
||||
} catch (error) {
|
||||
return asErrorInstance(error);
|
||||
}
|
||||
} // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a
|
||||
// consistent Error interface.
|
||||
|
||||
function asErrorInstance(error) {
|
||||
return error instanceof Error ? error : new Error(error || undefined);
|
||||
} // This is a small wrapper around completeValue which detects and logs errors
|
||||
// in the execution context.
|
||||
|
||||
|
||||
function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) {
|
||||
try {
|
||||
var completed;
|
||||
|
||||
if (isPromise(result)) {
|
||||
completed = result.then(function (resolved) {
|
||||
return completeValue(exeContext, returnType, fieldNodes, info, path, resolved);
|
||||
});
|
||||
} else {
|
||||
completed = completeValue(exeContext, returnType, fieldNodes, info, path, result);
|
||||
}
|
||||
|
||||
if (isPromise(completed)) {
|
||||
// Note: we don't rely on a `catch` method, but we do expect "thenable"
|
||||
// to take a second callback for the error case.
|
||||
return completed.then(undefined, function (error) {
|
||||
return handleFieldError(error, fieldNodes, path, returnType, exeContext);
|
||||
});
|
||||
}
|
||||
|
||||
return completed;
|
||||
} catch (error) {
|
||||
return handleFieldError(error, fieldNodes, path, returnType, exeContext);
|
||||
}
|
||||
}
|
||||
|
||||
function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) {
|
||||
var error = locatedError(asErrorInstance(rawError), fieldNodes, responsePathAsArray(path)); // If the field type is non-nullable, then it is resolved without any
|
||||
// protection from errors, however it still properly locates the error.
|
||||
|
||||
if (isNonNullType(returnType)) {
|
||||
throw error;
|
||||
} // Otherwise, error protection is applied, logging the error and resolving
|
||||
// a null value for this field if one is encountered.
|
||||
|
||||
|
||||
exeContext.errors.push(error);
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Implements the instructions for completeValue as defined in the
|
||||
* "Field entries" section of the spec.
|
||||
*
|
||||
* If the field type is Non-Null, then this recursively completes the value
|
||||
* for the inner type. It throws a field error if that completion returns null,
|
||||
* as per the "Nullability" section of the spec.
|
||||
*
|
||||
* If the field type is a List, then this recursively completes the value
|
||||
* for the inner type on each item in the list.
|
||||
*
|
||||
* If the field type is a Scalar or Enum, ensures the completed value is a legal
|
||||
* value of the type by calling the `serialize` method of GraphQL type
|
||||
* definition.
|
||||
*
|
||||
* If the field is an abstract type, determine the runtime type of the value
|
||||
* and then complete based on that type
|
||||
*
|
||||
* Otherwise, the field type expects a sub-selection set, and will complete the
|
||||
* value by evaluating all sub-selections.
|
||||
*/
|
||||
|
||||
|
||||
function completeValue(exeContext, returnType, fieldNodes, info, path, result) {
|
||||
// If result is an Error, throw a located error.
|
||||
if (result instanceof Error) {
|
||||
throw result;
|
||||
} // If field type is NonNull, complete for inner type, and throw field error
|
||||
// if result is null.
|
||||
|
||||
|
||||
if (isNonNullType(returnType)) {
|
||||
var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result);
|
||||
|
||||
if (completed === null) {
|
||||
throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, "."));
|
||||
}
|
||||
|
||||
return completed;
|
||||
} // If result value is null-ish (null, undefined, or NaN) then return null.
|
||||
|
||||
|
||||
if (isNullish(result)) {
|
||||
return null;
|
||||
} // If field type is List, complete each item in the list with the inner type
|
||||
|
||||
|
||||
if (isListType(returnType)) {
|
||||
return completeListValue(exeContext, returnType, fieldNodes, info, path, result);
|
||||
} // If field type is a leaf type, Scalar or Enum, serialize to a valid value,
|
||||
// returning null if serialization is not possible.
|
||||
|
||||
|
||||
if (isLeafType(returnType)) {
|
||||
return completeLeafValue(returnType, result);
|
||||
} // If field type is an abstract type, Interface or Union, determine the
|
||||
// runtime Object type and complete for that type.
|
||||
|
||||
|
||||
if (isAbstractType(returnType)) {
|
||||
return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result);
|
||||
} // If field type is Object, execute and complete all sub-selections.
|
||||
|
||||
|
||||
if (isObjectType(returnType)) {
|
||||
return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result);
|
||||
} // Not reachable. All possible output types have been considered.
|
||||
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Cannot complete value of unexpected type \"".concat(inspect(returnType), "\"."));
|
||||
}
|
||||
/**
|
||||
* Complete a list value by completing each item in the list with the
|
||||
* inner type
|
||||
*/
|
||||
|
||||
|
||||
function completeListValue(exeContext, returnType, fieldNodes, info, path, result) {
|
||||
!isCollection(result) ? invariant(0, "Expected Iterable, but did not find one for field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")) : void 0; // This is specified as a simple map, however we're optimizing the path
|
||||
// where the list contains no Promises by avoiding creating another Promise.
|
||||
|
||||
var itemType = returnType.ofType;
|
||||
var containsPromise = false;
|
||||
var completedResults = [];
|
||||
forEach(result, function (item, index) {
|
||||
// No need to modify the info object containing the path,
|
||||
// since from here on it is not ever accessed by resolver functions.
|
||||
var fieldPath = addPath(path, index);
|
||||
var completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item);
|
||||
|
||||
if (!containsPromise && isPromise(completedItem)) {
|
||||
containsPromise = true;
|
||||
}
|
||||
|
||||
completedResults.push(completedItem);
|
||||
});
|
||||
return containsPromise ? Promise.all(completedResults) : completedResults;
|
||||
}
|
||||
/**
|
||||
* Complete a Scalar or Enum by serializing to a valid value, returning
|
||||
* null if serialization is not possible.
|
||||
*/
|
||||
|
||||
|
||||
function completeLeafValue(returnType, result) {
|
||||
!returnType.serialize ? invariant(0, 'Missing serialize method on type') : void 0;
|
||||
var serializedResult = returnType.serialize(result);
|
||||
|
||||
if (isInvalid(serializedResult)) {
|
||||
throw new Error("Expected a value of type \"".concat(inspect(returnType), "\" but ") + "received: ".concat(inspect(result)));
|
||||
}
|
||||
|
||||
return serializedResult;
|
||||
}
|
||||
/**
|
||||
* Complete a value of an abstract type by determining the runtime object type
|
||||
* of that value, then complete the value for that type.
|
||||
*/
|
||||
|
||||
|
||||
function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) {
|
||||
var runtimeType = returnType.resolveType ? returnType.resolveType(result, exeContext.contextValue, info) : defaultResolveTypeFn(result, exeContext.contextValue, info, returnType);
|
||||
|
||||
if (isPromise(runtimeType)) {
|
||||
return runtimeType.then(function (resolvedRuntimeType) {
|
||||
return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
|
||||
});
|
||||
}
|
||||
|
||||
return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
|
||||
}
|
||||
|
||||
function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) {
|
||||
var runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName;
|
||||
|
||||
if (!isObjectType(runtimeType)) {
|
||||
throw new GraphQLError("Abstract type ".concat(returnType.name, " must resolve to an Object type at ") + "runtime for field ".concat(info.parentType.name, ".").concat(info.fieldName, " with ") + "value ".concat(inspect(result), ", received \"").concat(inspect(runtimeType), "\". ") + "Either the ".concat(returnType.name, " type should provide a \"resolveType\" ") + 'function or each possible type should provide an ' + '"isTypeOf" function.', fieldNodes);
|
||||
}
|
||||
|
||||
if (!exeContext.schema.isPossibleType(returnType, runtimeType)) {
|
||||
throw new GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type ") + "for \"".concat(returnType.name, "\"."), fieldNodes);
|
||||
}
|
||||
|
||||
return runtimeType;
|
||||
}
|
||||
/**
|
||||
* Complete an Object value by executing all sub-selections.
|
||||
*/
|
||||
|
||||
|
||||
function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) {
|
||||
// If there is an isTypeOf predicate function, call it with the
|
||||
// current result. If isTypeOf returns false, then raise an error rather
|
||||
// than continuing execution.
|
||||
if (returnType.isTypeOf) {
|
||||
var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);
|
||||
|
||||
if (isPromise(isTypeOf)) {
|
||||
return isTypeOf.then(function (resolvedIsTypeOf) {
|
||||
if (!resolvedIsTypeOf) {
|
||||
throw invalidReturnTypeError(returnType, result, fieldNodes);
|
||||
}
|
||||
|
||||
return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);
|
||||
});
|
||||
}
|
||||
|
||||
if (!isTypeOf) {
|
||||
throw invalidReturnTypeError(returnType, result, fieldNodes);
|
||||
}
|
||||
}
|
||||
|
||||
return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);
|
||||
}
|
||||
|
||||
function invalidReturnTypeError(returnType, result, fieldNodes) {
|
||||
return new GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat(inspect(result), "."), fieldNodes);
|
||||
}
|
||||
|
||||
function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) {
|
||||
// Collect sub-fields to execute to complete this value.
|
||||
var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes);
|
||||
return executeFields(exeContext, returnType, result, path, subFieldNodes);
|
||||
}
|
||||
/**
|
||||
* A memoized collection of relevant subfields with regard to the return
|
||||
* type. Memoizing ensures the subfields are not repeatedly calculated, which
|
||||
* saves overhead when resolving lists of values.
|
||||
*/
|
||||
|
||||
|
||||
var collectSubfields = memoize3(_collectSubfields);
|
||||
|
||||
function _collectSubfields(exeContext, returnType, fieldNodes) {
|
||||
var subFieldNodes = Object.create(null);
|
||||
var visitedFragmentNames = Object.create(null);
|
||||
|
||||
for (var i = 0; i < fieldNodes.length; i++) {
|
||||
var selectionSet = fieldNodes[i].selectionSet;
|
||||
|
||||
if (selectionSet) {
|
||||
subFieldNodes = collectFields(exeContext, returnType, selectionSet, subFieldNodes, visitedFragmentNames);
|
||||
}
|
||||
}
|
||||
|
||||
return subFieldNodes;
|
||||
}
|
||||
/**
|
||||
* If a resolveType function is not given, then a default resolve behavior is
|
||||
* used which attempts two strategies:
|
||||
*
|
||||
* First, See if the provided value has a `__typename` field defined, if so, use
|
||||
* that value as name of the resolved type.
|
||||
*
|
||||
* Otherwise, test each possible type for the abstract type by calling
|
||||
* isTypeOf for the object being coerced, returning the first type that matches.
|
||||
*/
|
||||
|
||||
|
||||
function defaultResolveTypeFn(value, contextValue, info, abstractType) {
|
||||
// First, look for `__typename`.
|
||||
if (value !== null && _typeof(value) === 'object' && typeof value.__typename === 'string') {
|
||||
return value.__typename;
|
||||
} // Otherwise, test each possible type.
|
||||
|
||||
|
||||
var possibleTypes = info.schema.getPossibleTypes(abstractType);
|
||||
var promisedIsTypeOfResults = [];
|
||||
|
||||
for (var i = 0; i < possibleTypes.length; i++) {
|
||||
var type = possibleTypes[i];
|
||||
|
||||
if (type.isTypeOf) {
|
||||
var isTypeOfResult = type.isTypeOf(value, contextValue, info);
|
||||
|
||||
if (isPromise(isTypeOfResult)) {
|
||||
promisedIsTypeOfResults[i] = isTypeOfResult;
|
||||
} else if (isTypeOfResult) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (promisedIsTypeOfResults.length) {
|
||||
return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) {
|
||||
for (var _i = 0; _i < isTypeOfResults.length; _i++) {
|
||||
if (isTypeOfResults[_i]) {
|
||||
return possibleTypes[_i];
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* If a resolve function is not given, then a default resolve behavior is used
|
||||
* which takes the property of the source object of the same name as the field
|
||||
* and returns it as the result, or if it's a function, returns the result
|
||||
* of calling that function while passing along args and context value.
|
||||
*/
|
||||
|
||||
|
||||
export var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) {
|
||||
// ensure source is a value for which property access is acceptable.
|
||||
if (_typeof(source) === 'object' || typeof source === 'function') {
|
||||
var property = source[info.fieldName];
|
||||
|
||||
if (typeof property === 'function') {
|
||||
return source[info.fieldName](args, contextValue, info);
|
||||
}
|
||||
|
||||
return property;
|
||||
}
|
||||
};
|
||||
/**
|
||||
* This method looks up the field on the given type defintion.
|
||||
* It has special casing for the two introspection fields, __schema
|
||||
* and __typename. __typename is special because it can always be
|
||||
* queried as a field, even in situations where no other fields
|
||||
* are allowed, like on a Union. __schema could get automatically
|
||||
* added to the query type, but that would require mutating type
|
||||
* definitions, which would cause issues.
|
||||
*/
|
||||
|
||||
export function getFieldDef(schema, parentType, fieldName) {
|
||||
if (fieldName === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
|
||||
return SchemaMetaFieldDef;
|
||||
} else if (fieldName === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
|
||||
return TypeMetaFieldDef;
|
||||
} else if (fieldName === TypeNameMetaFieldDef.name) {
|
||||
return TypeNameMetaFieldDef;
|
||||
}
|
||||
|
||||
return parentType.getFields()[fieldName];
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "execute", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _execute.execute;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "defaultFieldResolver", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _execute.defaultFieldResolver;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "responsePathAsArray", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _execute.responsePathAsArray;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "getDirectiveValues", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _values.getDirectiveValues;
|
||||
}
|
||||
});
|
||||
|
||||
var _execute = require("./execute");
|
||||
|
||||
var _values = require("./values");
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
export { execute, defaultFieldResolver, responsePathAsArray } from './execute';
|
||||
export { getDirectiveValues } from './values';
|
||||
|
||||
export type { ExecutionArgs, ExecutionResult } from './execute';
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
export { execute, defaultFieldResolver, responsePathAsArray } from './execute';
|
||||
export { getDirectiveValues } from './values';
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.getVariableValues = getVariableValues;
|
||||
exports.getArgumentValues = getArgumentValues;
|
||||
exports.getDirectiveValues = getDirectiveValues;
|
||||
|
||||
var _GraphQLError = require("../error/GraphQLError");
|
||||
|
||||
var _find = _interopRequireDefault(require("../jsutils/find"));
|
||||
|
||||
var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
|
||||
|
||||
var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
|
||||
|
||||
var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
|
||||
|
||||
var _coerceValue = require("../utilities/coerceValue");
|
||||
|
||||
var _typeFromAST = require("../utilities/typeFromAST");
|
||||
|
||||
var _valueFromAST = require("../utilities/valueFromAST");
|
||||
|
||||
var _kinds = require("../language/kinds");
|
||||
|
||||
var _printer = require("../language/printer");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Prepares an object map of variableValues of the correct type based on the
|
||||
* provided variable definitions and arbitrary input. If the input cannot be
|
||||
* parsed to match the variable definitions, a GraphQLError will be thrown.
|
||||
*
|
||||
* Note: The returned value is a plain Object with a prototype, since it is
|
||||
* exposed to user code. Care should be taken to not pull values from the
|
||||
* Object prototype.
|
||||
*/
|
||||
function getVariableValues(schema, varDefNodes, inputs) {
|
||||
var errors = [];
|
||||
var coercedValues = {};
|
||||
|
||||
for (var i = 0; i < varDefNodes.length; i++) {
|
||||
var varDefNode = varDefNodes[i];
|
||||
var varName = varDefNode.variable.name.value;
|
||||
var varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type);
|
||||
|
||||
if (!(0, _definition.isInputType)(varType)) {
|
||||
// Must use input types for variables. This should be caught during
|
||||
// validation, however is checked again here for safety.
|
||||
errors.push(new _GraphQLError.GraphQLError("Variable \"$".concat(varName, "\" expected value of type ") + "\"".concat((0, _printer.print)(varDefNode.type), "\" which cannot be used as an input type."), [varDefNode.type]));
|
||||
} else {
|
||||
var hasValue = hasOwnProperty(inputs, varName);
|
||||
var value = hasValue ? inputs[varName] : undefined;
|
||||
|
||||
if (!hasValue && varDefNode.defaultValue) {
|
||||
// If no value was provided to a variable with a default value,
|
||||
// use the default value.
|
||||
coercedValues[varName] = (0, _valueFromAST.valueFromAST)(varDefNode.defaultValue, varType);
|
||||
} else if ((!hasValue || value === null) && (0, _definition.isNonNullType)(varType)) {
|
||||
// If no value or a nullish value was provided to a variable with a
|
||||
// non-null type (required), produce an error.
|
||||
errors.push(new _GraphQLError.GraphQLError(hasValue ? "Variable \"$".concat(varName, "\" of non-null type ") + "\"".concat((0, _inspect.default)(varType), "\" must not be null.") : "Variable \"$".concat(varName, "\" of required type ") + "\"".concat((0, _inspect.default)(varType), "\" was not provided."), [varDefNode]));
|
||||
} else if (hasValue) {
|
||||
if (value === null) {
|
||||
// If the explicit value `null` was provided, an entry in the coerced
|
||||
// values must exist as the value `null`.
|
||||
coercedValues[varName] = null;
|
||||
} else {
|
||||
// Otherwise, a non-null value was provided, coerce it to the expected
|
||||
// type or report an error if coercion fails.
|
||||
var coerced = (0, _coerceValue.coerceValue)(value, varType, varDefNode);
|
||||
var coercionErrors = coerced.errors;
|
||||
|
||||
if (coercionErrors) {
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = coercionErrors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var error = _step.value;
|
||||
error.message = "Variable \"$".concat(varName, "\" got invalid ") + "value ".concat((0, _inspect.default)(value), "; ").concat(error.message);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
errors.push.apply(errors, coercionErrors);
|
||||
} else {
|
||||
coercedValues[varName] = coerced.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return errors.length === 0 ? {
|
||||
errors: undefined,
|
||||
coerced: coercedValues
|
||||
} : {
|
||||
errors: errors,
|
||||
coerced: undefined
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Prepares an object map of argument values given a list of argument
|
||||
* definitions and list of argument AST nodes.
|
||||
*
|
||||
* Note: The returned value is a plain Object with a prototype, since it is
|
||||
* exposed to user code. Care should be taken to not pull values from the
|
||||
* Object prototype.
|
||||
*/
|
||||
|
||||
|
||||
function getArgumentValues(def, node, variableValues) {
|
||||
var coercedValues = {};
|
||||
var argDefs = def.args;
|
||||
var argNodes = node.arguments;
|
||||
|
||||
if (!argDefs || !argNodes) {
|
||||
return coercedValues;
|
||||
}
|
||||
|
||||
var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) {
|
||||
return arg.name.value;
|
||||
});
|
||||
|
||||
for (var i = 0; i < argDefs.length; i++) {
|
||||
var argDef = argDefs[i];
|
||||
var name = argDef.name;
|
||||
var argType = argDef.type;
|
||||
var argumentNode = argNodeMap[name];
|
||||
var hasValue = void 0;
|
||||
var isNull = void 0;
|
||||
|
||||
if (argumentNode && argumentNode.value.kind === _kinds.Kind.VARIABLE) {
|
||||
var variableName = argumentNode.value.name.value;
|
||||
hasValue = variableValues && hasOwnProperty(variableValues, variableName);
|
||||
isNull = variableValues && variableValues[variableName] === null;
|
||||
} else {
|
||||
hasValue = argumentNode != null;
|
||||
isNull = argumentNode && argumentNode.value.kind === _kinds.Kind.NULL;
|
||||
}
|
||||
|
||||
if (!hasValue && argDef.defaultValue !== undefined) {
|
||||
// If no argument was provided where the definition has a default value,
|
||||
// use the default value.
|
||||
coercedValues[name] = argDef.defaultValue;
|
||||
} else if ((!hasValue || isNull) && (0, _definition.isNonNullType)(argType)) {
|
||||
// If no argument or a null value was provided to an argument with a
|
||||
// non-null type (required), produce a field error.
|
||||
if (isNull) {
|
||||
throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat((0, _inspect.default)(argType), "\" ") + 'must not be null.', [argumentNode.value]);
|
||||
} else if (argumentNode && argumentNode.value.kind === _kinds.Kind.VARIABLE) {
|
||||
var _variableName = argumentNode.value.name.value;
|
||||
throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + "was provided the variable \"$".concat(_variableName, "\" ") + 'which was not provided a runtime value.', [argumentNode.value]);
|
||||
} else {
|
||||
throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + 'was not provided.', [node]);
|
||||
}
|
||||
} else if (hasValue) {
|
||||
if (argumentNode.value.kind === _kinds.Kind.NULL) {
|
||||
// If the explicit value `null` was provided, an entry in the coerced
|
||||
// values must exist as the value `null`.
|
||||
coercedValues[name] = null;
|
||||
} else if (argumentNode.value.kind === _kinds.Kind.VARIABLE) {
|
||||
var _variableName2 = argumentNode.value.name.value;
|
||||
!variableValues ? (0, _invariant.default)(0, 'Must exist for hasValue to be true.') : void 0; // Note: This does no further checking that this variable is correct.
|
||||
// This assumes that this query has been validated and the variable
|
||||
// usage here is of the correct type.
|
||||
|
||||
coercedValues[name] = variableValues[_variableName2];
|
||||
} else {
|
||||
var valueNode = argumentNode.value;
|
||||
var coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues);
|
||||
|
||||
if (coercedValue === undefined) {
|
||||
// Note: ValuesOfCorrectType validation should catch this before
|
||||
// execution. This is a runtime check to ensure execution does not
|
||||
// continue with an invalid argument value.
|
||||
throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat((0, _printer.print)(valueNode), "."), [argumentNode.value]);
|
||||
}
|
||||
|
||||
coercedValues[name] = coercedValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return coercedValues;
|
||||
}
|
||||
/**
|
||||
* Prepares an object map of argument values given a directive definition
|
||||
* and a AST node which may contain directives. Optionally also accepts a map
|
||||
* of variable values.
|
||||
*
|
||||
* If the directive does not exist on the node, returns undefined.
|
||||
*
|
||||
* Note: The returned value is a plain Object with a prototype, since it is
|
||||
* exposed to user code. Care should be taken to not pull values from the
|
||||
* Object prototype.
|
||||
*/
|
||||
|
||||
|
||||
function getDirectiveValues(directiveDef, node, variableValues) {
|
||||
var directiveNode = node.directives && (0, _find.default)(node.directives, function (directive) {
|
||||
return directive.name.value === directiveDef.name;
|
||||
});
|
||||
|
||||
if (directiveNode) {
|
||||
return getArgumentValues(directiveDef, directiveNode, variableValues);
|
||||
}
|
||||
}
|
||||
|
||||
function hasOwnProperty(obj, prop) {
|
||||
return Object.prototype.hasOwnProperty.call(obj, prop);
|
||||
}
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import find from '../jsutils/find';
|
||||
import inspect from '../jsutils/inspect';
|
||||
import invariant from '../jsutils/invariant';
|
||||
import keyMap from '../jsutils/keyMap';
|
||||
import { coerceValue } from '../utilities/coerceValue';
|
||||
import { typeFromAST } from '../utilities/typeFromAST';
|
||||
import { valueFromAST } from '../utilities/valueFromAST';
|
||||
import { Kind } from '../language/kinds';
|
||||
import { print } from '../language/printer';
|
||||
import { isInputType, isNonNullType } from '../type/definition';
|
||||
import type { ObjMap } from '../jsutils/ObjMap';
|
||||
import type { GraphQLField } from '../type/definition';
|
||||
import type { GraphQLDirective } from '../type/directives';
|
||||
import type { GraphQLSchema } from '../type/schema';
|
||||
import type {
|
||||
FieldNode,
|
||||
DirectiveNode,
|
||||
VariableDefinitionNode,
|
||||
} from '../language/ast';
|
||||
|
||||
type CoercedVariableValues = {|
|
||||
errors: $ReadOnlyArray<GraphQLError> | void,
|
||||
coerced: { [variable: string]: mixed } | void,
|
||||
|};
|
||||
|
||||
/**
|
||||
* Prepares an object map of variableValues of the correct type based on the
|
||||
* provided variable definitions and arbitrary input. If the input cannot be
|
||||
* parsed to match the variable definitions, a GraphQLError will be thrown.
|
||||
*
|
||||
* Note: The returned value is a plain Object with a prototype, since it is
|
||||
* exposed to user code. Care should be taken to not pull values from the
|
||||
* Object prototype.
|
||||
*/
|
||||
export function getVariableValues(
|
||||
schema: GraphQLSchema,
|
||||
varDefNodes: Array<VariableDefinitionNode>,
|
||||
inputs: ObjMap<mixed>,
|
||||
): CoercedVariableValues {
|
||||
const errors = [];
|
||||
const coercedValues = {};
|
||||
for (let i = 0; i < varDefNodes.length; i++) {
|
||||
const varDefNode = varDefNodes[i];
|
||||
const varName = varDefNode.variable.name.value;
|
||||
const varType = typeFromAST(schema, varDefNode.type);
|
||||
if (!isInputType(varType)) {
|
||||
// Must use input types for variables. This should be caught during
|
||||
// validation, however is checked again here for safety.
|
||||
errors.push(
|
||||
new GraphQLError(
|
||||
`Variable "$${varName}" expected value of type ` +
|
||||
`"${print(
|
||||
varDefNode.type,
|
||||
)}" which cannot be used as an input type.`,
|
||||
[varDefNode.type],
|
||||
),
|
||||
);
|
||||
} else {
|
||||
const hasValue = hasOwnProperty(inputs, varName);
|
||||
const value = hasValue ? inputs[varName] : undefined;
|
||||
if (!hasValue && varDefNode.defaultValue) {
|
||||
// If no value was provided to a variable with a default value,
|
||||
// use the default value.
|
||||
coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType);
|
||||
} else if ((!hasValue || value === null) && isNonNullType(varType)) {
|
||||
// If no value or a nullish value was provided to a variable with a
|
||||
// non-null type (required), produce an error.
|
||||
errors.push(
|
||||
new GraphQLError(
|
||||
hasValue
|
||||
? `Variable "$${varName}" of non-null type ` +
|
||||
`"${inspect(varType)}" must not be null.`
|
||||
: `Variable "$${varName}" of required type ` +
|
||||
`"${inspect(varType)}" was not provided.`,
|
||||
[varDefNode],
|
||||
),
|
||||
);
|
||||
} else if (hasValue) {
|
||||
if (value === null) {
|
||||
// If the explicit value `null` was provided, an entry in the coerced
|
||||
// values must exist as the value `null`.
|
||||
coercedValues[varName] = null;
|
||||
} else {
|
||||
// Otherwise, a non-null value was provided, coerce it to the expected
|
||||
// type or report an error if coercion fails.
|
||||
const coerced = coerceValue(value, varType, varDefNode);
|
||||
const coercionErrors = coerced.errors;
|
||||
if (coercionErrors) {
|
||||
for (const error of coercionErrors) {
|
||||
error.message =
|
||||
`Variable "$${varName}" got invalid ` +
|
||||
`value ${inspect(value)}; ${error.message}`;
|
||||
}
|
||||
errors.push(...coercionErrors);
|
||||
} else {
|
||||
coercedValues[varName] = coerced.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors.length === 0
|
||||
? { errors: undefined, coerced: coercedValues }
|
||||
: { errors, coerced: undefined };
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares an object map of argument values given a list of argument
|
||||
* definitions and list of argument AST nodes.
|
||||
*
|
||||
* Note: The returned value is a plain Object with a prototype, since it is
|
||||
* exposed to user code. Care should be taken to not pull values from the
|
||||
* Object prototype.
|
||||
*/
|
||||
export function getArgumentValues(
|
||||
def: GraphQLField<*, *> | GraphQLDirective,
|
||||
node: FieldNode | DirectiveNode,
|
||||
variableValues?: ?ObjMap<mixed>,
|
||||
): { [argument: string]: mixed } {
|
||||
const coercedValues = {};
|
||||
const argDefs = def.args;
|
||||
const argNodes = node.arguments;
|
||||
if (!argDefs || !argNodes) {
|
||||
return coercedValues;
|
||||
}
|
||||
const argNodeMap = keyMap(argNodes, arg => arg.name.value);
|
||||
for (let i = 0; i < argDefs.length; i++) {
|
||||
const argDef = argDefs[i];
|
||||
const name = argDef.name;
|
||||
const argType = argDef.type;
|
||||
const argumentNode = argNodeMap[name];
|
||||
let hasValue;
|
||||
let isNull;
|
||||
if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) {
|
||||
const variableName = argumentNode.value.name.value;
|
||||
hasValue = variableValues && hasOwnProperty(variableValues, variableName);
|
||||
isNull = variableValues && variableValues[variableName] === null;
|
||||
} else {
|
||||
hasValue = argumentNode != null;
|
||||
isNull = argumentNode && argumentNode.value.kind === Kind.NULL;
|
||||
}
|
||||
|
||||
if (!hasValue && argDef.defaultValue !== undefined) {
|
||||
// If no argument was provided where the definition has a default value,
|
||||
// use the default value.
|
||||
coercedValues[name] = argDef.defaultValue;
|
||||
} else if ((!hasValue || isNull) && isNonNullType(argType)) {
|
||||
// If no argument or a null value was provided to an argument with a
|
||||
// non-null type (required), produce a field error.
|
||||
if (isNull) {
|
||||
throw new GraphQLError(
|
||||
`Argument "${name}" of non-null type "${inspect(argType)}" ` +
|
||||
'must not be null.',
|
||||
[argumentNode.value],
|
||||
);
|
||||
} else if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) {
|
||||
const variableName = argumentNode.value.name.value;
|
||||
throw new GraphQLError(
|
||||
`Argument "${name}" of required type "${inspect(argType)}" ` +
|
||||
`was provided the variable "$${variableName}" ` +
|
||||
'which was not provided a runtime value.',
|
||||
[argumentNode.value],
|
||||
);
|
||||
} else {
|
||||
throw new GraphQLError(
|
||||
`Argument "${name}" of required type "${inspect(argType)}" ` +
|
||||
'was not provided.',
|
||||
[node],
|
||||
);
|
||||
}
|
||||
} else if (hasValue) {
|
||||
if (argumentNode.value.kind === Kind.NULL) {
|
||||
// If the explicit value `null` was provided, an entry in the coerced
|
||||
// values must exist as the value `null`.
|
||||
coercedValues[name] = null;
|
||||
} else if (argumentNode.value.kind === Kind.VARIABLE) {
|
||||
const variableName = argumentNode.value.name.value;
|
||||
invariant(variableValues, 'Must exist for hasValue to be true.');
|
||||
// Note: This does no further checking that this variable is correct.
|
||||
// This assumes that this query has been validated and the variable
|
||||
// usage here is of the correct type.
|
||||
coercedValues[name] = variableValues[variableName];
|
||||
} else {
|
||||
const valueNode = argumentNode.value;
|
||||
const coercedValue = valueFromAST(valueNode, argType, variableValues);
|
||||
if (coercedValue === undefined) {
|
||||
// Note: ValuesOfCorrectType validation should catch this before
|
||||
// execution. This is a runtime check to ensure execution does not
|
||||
// continue with an invalid argument value.
|
||||
throw new GraphQLError(
|
||||
`Argument "${name}" has invalid value ${print(valueNode)}.`,
|
||||
[argumentNode.value],
|
||||
);
|
||||
}
|
||||
coercedValues[name] = coercedValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return coercedValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares an object map of argument values given a directive definition
|
||||
* and a AST node which may contain directives. Optionally also accepts a map
|
||||
* of variable values.
|
||||
*
|
||||
* If the directive does not exist on the node, returns undefined.
|
||||
*
|
||||
* Note: The returned value is a plain Object with a prototype, since it is
|
||||
* exposed to user code. Care should be taken to not pull values from the
|
||||
* Object prototype.
|
||||
*/
|
||||
export function getDirectiveValues(
|
||||
directiveDef: GraphQLDirective,
|
||||
node: { +directives?: $ReadOnlyArray<DirectiveNode> },
|
||||
variableValues?: ?ObjMap<mixed>,
|
||||
): void | { [argument: string]: mixed } {
|
||||
const directiveNode =
|
||||
node.directives &&
|
||||
find(
|
||||
node.directives,
|
||||
directive => directive.name.value === directiveDef.name,
|
||||
);
|
||||
|
||||
if (directiveNode) {
|
||||
return getArgumentValues(directiveDef, directiveNode, variableValues);
|
||||
}
|
||||
}
|
||||
|
||||
function hasOwnProperty(obj: mixed, prop: string): boolean {
|
||||
return Object.prototype.hasOwnProperty.call(obj, prop);
|
||||
}
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import find from '../jsutils/find';
|
||||
import inspect from '../jsutils/inspect';
|
||||
import invariant from '../jsutils/invariant';
|
||||
import keyMap from '../jsutils/keyMap';
|
||||
import { coerceValue } from '../utilities/coerceValue';
|
||||
import { typeFromAST } from '../utilities/typeFromAST';
|
||||
import { valueFromAST } from '../utilities/valueFromAST';
|
||||
import { Kind } from '../language/kinds';
|
||||
import { print } from '../language/printer';
|
||||
import { isInputType, isNonNullType } from '../type/definition';
|
||||
|
||||
/**
|
||||
* Prepares an object map of variableValues of the correct type based on the
|
||||
* provided variable definitions and arbitrary input. If the input cannot be
|
||||
* parsed to match the variable definitions, a GraphQLError will be thrown.
|
||||
*
|
||||
* Note: The returned value is a plain Object with a prototype, since it is
|
||||
* exposed to user code. Care should be taken to not pull values from the
|
||||
* Object prototype.
|
||||
*/
|
||||
export function getVariableValues(schema, varDefNodes, inputs) {
|
||||
var errors = [];
|
||||
var coercedValues = {};
|
||||
|
||||
for (var i = 0; i < varDefNodes.length; i++) {
|
||||
var varDefNode = varDefNodes[i];
|
||||
var varName = varDefNode.variable.name.value;
|
||||
var varType = typeFromAST(schema, varDefNode.type);
|
||||
|
||||
if (!isInputType(varType)) {
|
||||
// Must use input types for variables. This should be caught during
|
||||
// validation, however is checked again here for safety.
|
||||
errors.push(new GraphQLError("Variable \"$".concat(varName, "\" expected value of type ") + "\"".concat(print(varDefNode.type), "\" which cannot be used as an input type."), [varDefNode.type]));
|
||||
} else {
|
||||
var hasValue = hasOwnProperty(inputs, varName);
|
||||
var value = hasValue ? inputs[varName] : undefined;
|
||||
|
||||
if (!hasValue && varDefNode.defaultValue) {
|
||||
// If no value was provided to a variable with a default value,
|
||||
// use the default value.
|
||||
coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType);
|
||||
} else if ((!hasValue || value === null) && isNonNullType(varType)) {
|
||||
// If no value or a nullish value was provided to a variable with a
|
||||
// non-null type (required), produce an error.
|
||||
errors.push(new GraphQLError(hasValue ? "Variable \"$".concat(varName, "\" of non-null type ") + "\"".concat(inspect(varType), "\" must not be null.") : "Variable \"$".concat(varName, "\" of required type ") + "\"".concat(inspect(varType), "\" was not provided."), [varDefNode]));
|
||||
} else if (hasValue) {
|
||||
if (value === null) {
|
||||
// If the explicit value `null` was provided, an entry in the coerced
|
||||
// values must exist as the value `null`.
|
||||
coercedValues[varName] = null;
|
||||
} else {
|
||||
// Otherwise, a non-null value was provided, coerce it to the expected
|
||||
// type or report an error if coercion fails.
|
||||
var coerced = coerceValue(value, varType, varDefNode);
|
||||
var coercionErrors = coerced.errors;
|
||||
|
||||
if (coercionErrors) {
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = coercionErrors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var error = _step.value;
|
||||
error.message = "Variable \"$".concat(varName, "\" got invalid ") + "value ".concat(inspect(value), "; ").concat(error.message);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
errors.push.apply(errors, coercionErrors);
|
||||
} else {
|
||||
coercedValues[varName] = coerced.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return errors.length === 0 ? {
|
||||
errors: undefined,
|
||||
coerced: coercedValues
|
||||
} : {
|
||||
errors: errors,
|
||||
coerced: undefined
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Prepares an object map of argument values given a list of argument
|
||||
* definitions and list of argument AST nodes.
|
||||
*
|
||||
* Note: The returned value is a plain Object with a prototype, since it is
|
||||
* exposed to user code. Care should be taken to not pull values from the
|
||||
* Object prototype.
|
||||
*/
|
||||
|
||||
export function getArgumentValues(def, node, variableValues) {
|
||||
var coercedValues = {};
|
||||
var argDefs = def.args;
|
||||
var argNodes = node.arguments;
|
||||
|
||||
if (!argDefs || !argNodes) {
|
||||
return coercedValues;
|
||||
}
|
||||
|
||||
var argNodeMap = keyMap(argNodes, function (arg) {
|
||||
return arg.name.value;
|
||||
});
|
||||
|
||||
for (var i = 0; i < argDefs.length; i++) {
|
||||
var argDef = argDefs[i];
|
||||
var name = argDef.name;
|
||||
var argType = argDef.type;
|
||||
var argumentNode = argNodeMap[name];
|
||||
var hasValue = void 0;
|
||||
var isNull = void 0;
|
||||
|
||||
if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) {
|
||||
var variableName = argumentNode.value.name.value;
|
||||
hasValue = variableValues && hasOwnProperty(variableValues, variableName);
|
||||
isNull = variableValues && variableValues[variableName] === null;
|
||||
} else {
|
||||
hasValue = argumentNode != null;
|
||||
isNull = argumentNode && argumentNode.value.kind === Kind.NULL;
|
||||
}
|
||||
|
||||
if (!hasValue && argDef.defaultValue !== undefined) {
|
||||
// If no argument was provided where the definition has a default value,
|
||||
// use the default value.
|
||||
coercedValues[name] = argDef.defaultValue;
|
||||
} else if ((!hasValue || isNull) && isNonNullType(argType)) {
|
||||
// If no argument or a null value was provided to an argument with a
|
||||
// non-null type (required), produce a field error.
|
||||
if (isNull) {
|
||||
throw new GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat(inspect(argType), "\" ") + 'must not be null.', [argumentNode.value]);
|
||||
} else if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) {
|
||||
var _variableName = argumentNode.value.name.value;
|
||||
throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + "was provided the variable \"$".concat(_variableName, "\" ") + 'which was not provided a runtime value.', [argumentNode.value]);
|
||||
} else {
|
||||
throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + 'was not provided.', [node]);
|
||||
}
|
||||
} else if (hasValue) {
|
||||
if (argumentNode.value.kind === Kind.NULL) {
|
||||
// If the explicit value `null` was provided, an entry in the coerced
|
||||
// values must exist as the value `null`.
|
||||
coercedValues[name] = null;
|
||||
} else if (argumentNode.value.kind === Kind.VARIABLE) {
|
||||
var _variableName2 = argumentNode.value.name.value;
|
||||
!variableValues ? invariant(0, 'Must exist for hasValue to be true.') : void 0; // Note: This does no further checking that this variable is correct.
|
||||
// This assumes that this query has been validated and the variable
|
||||
// usage here is of the correct type.
|
||||
|
||||
coercedValues[name] = variableValues[_variableName2];
|
||||
} else {
|
||||
var valueNode = argumentNode.value;
|
||||
var coercedValue = valueFromAST(valueNode, argType, variableValues);
|
||||
|
||||
if (coercedValue === undefined) {
|
||||
// Note: ValuesOfCorrectType validation should catch this before
|
||||
// execution. This is a runtime check to ensure execution does not
|
||||
// continue with an invalid argument value.
|
||||
throw new GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat(print(valueNode), "."), [argumentNode.value]);
|
||||
}
|
||||
|
||||
coercedValues[name] = coercedValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return coercedValues;
|
||||
}
|
||||
/**
|
||||
* Prepares an object map of argument values given a directive definition
|
||||
* and a AST node which may contain directives. Optionally also accepts a map
|
||||
* of variable values.
|
||||
*
|
||||
* If the directive does not exist on the node, returns undefined.
|
||||
*
|
||||
* Note: The returned value is a plain Object with a prototype, since it is
|
||||
* exposed to user code. Care should be taken to not pull values from the
|
||||
* Object prototype.
|
||||
*/
|
||||
|
||||
export function getDirectiveValues(directiveDef, node, variableValues) {
|
||||
var directiveNode = node.directives && find(node.directives, function (directive) {
|
||||
return directive.name.value === directiveDef.name;
|
||||
});
|
||||
|
||||
if (directiveNode) {
|
||||
return getArgumentValues(directiveDef, directiveNode, variableValues);
|
||||
}
|
||||
}
|
||||
|
||||
function hasOwnProperty(obj, prop) {
|
||||
return Object.prototype.hasOwnProperty.call(obj, prop);
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.graphql = graphql;
|
||||
exports.graphqlSync = graphqlSync;
|
||||
|
||||
var _validate = require("./type/validate");
|
||||
|
||||
var _parser = require("./language/parser");
|
||||
|
||||
var _validate2 = require("./validation/validate");
|
||||
|
||||
var _execute = require("./execution/execute");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) {
|
||||
var _arguments = arguments;
|
||||
|
||||
/* eslint-enable no-redeclare */
|
||||
// Always return a Promise for a consistent API.
|
||||
return new Promise(function (resolve) {
|
||||
return resolve( // Extract arguments from object args if provided.
|
||||
_arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* The graphqlSync function also fulfills GraphQL operations by parsing,
|
||||
* validating, and executing a GraphQL document along side a GraphQL schema.
|
||||
* However, it guarantees to complete synchronously (or throw an error) assuming
|
||||
* that all field resolvers are also synchronous.
|
||||
*/
|
||||
|
||||
|
||||
function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) {
|
||||
/* eslint-enable no-redeclare */
|
||||
// Extract arguments from object args if provided.
|
||||
var result = arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver); // Assert that the execution was synchronous.
|
||||
|
||||
if (result.then) {
|
||||
throw new Error('GraphQL execution failed to complete synchronously.');
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function graphqlImpl(schema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) {
|
||||
// Validate Schema
|
||||
var schemaValidationErrors = (0, _validate.validateSchema)(schema);
|
||||
|
||||
if (schemaValidationErrors.length > 0) {
|
||||
return {
|
||||
errors: schemaValidationErrors
|
||||
};
|
||||
} // Parse
|
||||
|
||||
|
||||
var document;
|
||||
|
||||
try {
|
||||
document = (0, _parser.parse)(source);
|
||||
} catch (syntaxError) {
|
||||
return {
|
||||
errors: [syntaxError]
|
||||
};
|
||||
} // Validate
|
||||
|
||||
|
||||
var validationErrors = (0, _validate2.validate)(schema, document);
|
||||
|
||||
if (validationErrors.length > 0) {
|
||||
return {
|
||||
errors: validationErrors
|
||||
};
|
||||
} // Execute
|
||||
|
||||
|
||||
return (0, _execute.execute)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver);
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { validateSchema } from './type/validate';
|
||||
import { parse } from './language/parser';
|
||||
import { validate } from './validation/validate';
|
||||
import { execute } from './execution/execute';
|
||||
import type { ObjMap } from './jsutils/ObjMap';
|
||||
import type { Source } from './language/source';
|
||||
import type { GraphQLFieldResolver } from './type/definition';
|
||||
import type { GraphQLSchema } from './type/schema';
|
||||
import type { ExecutionResult } from './execution/execute';
|
||||
import type { MaybePromise } from './jsutils/MaybePromise';
|
||||
|
||||
/**
|
||||
* This is the primary entry point function for fulfilling GraphQL operations
|
||||
* by parsing, validating, and executing a GraphQL document along side a
|
||||
* GraphQL schema.
|
||||
*
|
||||
* More sophisticated GraphQL servers, such as those which persist queries,
|
||||
* may wish to separate the validation and execution phases to a static time
|
||||
* tooling step, and a server runtime step.
|
||||
*
|
||||
* Accepts either an object with named arguments, or individual arguments:
|
||||
*
|
||||
* schema:
|
||||
* The GraphQL type system to use when validating and executing a query.
|
||||
* source:
|
||||
* A GraphQL language formatted string representing the requested operation.
|
||||
* rootValue:
|
||||
* The value provided as the first argument to resolver functions on the top
|
||||
* level type (e.g. the query object type).
|
||||
* contextValue:
|
||||
* The context value is provided as an argument to resolver functions after
|
||||
* field arguments. It is used to pass shared information useful at any point
|
||||
* during executing this query, for example the currently logged in user and
|
||||
* connections to databases or other services.
|
||||
* variableValues:
|
||||
* A mapping of variable name to runtime value to use for all variables
|
||||
* defined in the requestString.
|
||||
* operationName:
|
||||
* The name of the operation to use if requestString contains multiple
|
||||
* possible operations. Can be omitted if requestString contains only
|
||||
* one operation.
|
||||
* fieldResolver:
|
||||
* A resolver function to use when one is not provided by the schema.
|
||||
* If not provided, the default field resolver is used (which looks for a
|
||||
* value or method on the source value with the field's name).
|
||||
*/
|
||||
export type GraphQLArgs = {|
|
||||
schema: GraphQLSchema,
|
||||
source: string | Source,
|
||||
rootValue?: mixed,
|
||||
contextValue?: mixed,
|
||||
variableValues?: ?ObjMap<mixed>,
|
||||
operationName?: ?string,
|
||||
fieldResolver?: ?GraphQLFieldResolver<any, any>,
|
||||
|};
|
||||
declare function graphql(GraphQLArgs, ..._: []): Promise<ExecutionResult>;
|
||||
/* eslint-disable no-redeclare */
|
||||
declare function graphql(
|
||||
schema: GraphQLSchema,
|
||||
source: Source | string,
|
||||
rootValue?: mixed,
|
||||
contextValue?: mixed,
|
||||
variableValues?: ?ObjMap<mixed>,
|
||||
operationName?: ?string,
|
||||
fieldResolver?: ?GraphQLFieldResolver<any, any>,
|
||||
): Promise<ExecutionResult>;
|
||||
export function graphql(
|
||||
argsOrSchema,
|
||||
source,
|
||||
rootValue,
|
||||
contextValue,
|
||||
variableValues,
|
||||
operationName,
|
||||
fieldResolver,
|
||||
) {
|
||||
/* eslint-enable no-redeclare */
|
||||
// Always return a Promise for a consistent API.
|
||||
return new Promise(resolve =>
|
||||
resolve(
|
||||
// Extract arguments from object args if provided.
|
||||
arguments.length === 1
|
||||
? graphqlImpl(
|
||||
argsOrSchema.schema,
|
||||
argsOrSchema.source,
|
||||
argsOrSchema.rootValue,
|
||||
argsOrSchema.contextValue,
|
||||
argsOrSchema.variableValues,
|
||||
argsOrSchema.operationName,
|
||||
argsOrSchema.fieldResolver,
|
||||
)
|
||||
: graphqlImpl(
|
||||
argsOrSchema,
|
||||
source,
|
||||
rootValue,
|
||||
contextValue,
|
||||
variableValues,
|
||||
operationName,
|
||||
fieldResolver,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The graphqlSync function also fulfills GraphQL operations by parsing,
|
||||
* validating, and executing a GraphQL document along side a GraphQL schema.
|
||||
* However, it guarantees to complete synchronously (or throw an error) assuming
|
||||
* that all field resolvers are also synchronous.
|
||||
*/
|
||||
declare function graphqlSync(GraphQLArgs, ..._: []): ExecutionResult;
|
||||
/* eslint-disable no-redeclare */
|
||||
declare function graphqlSync(
|
||||
schema: GraphQLSchema,
|
||||
source: Source | string,
|
||||
rootValue?: mixed,
|
||||
contextValue?: mixed,
|
||||
variableValues?: ?ObjMap<mixed>,
|
||||
operationName?: ?string,
|
||||
fieldResolver?: ?GraphQLFieldResolver<any, any>,
|
||||
): ExecutionResult;
|
||||
export function graphqlSync(
|
||||
argsOrSchema,
|
||||
source,
|
||||
rootValue,
|
||||
contextValue,
|
||||
variableValues,
|
||||
operationName,
|
||||
fieldResolver,
|
||||
) {
|
||||
/* eslint-enable no-redeclare */
|
||||
// Extract arguments from object args if provided.
|
||||
const result =
|
||||
arguments.length === 1
|
||||
? graphqlImpl(
|
||||
argsOrSchema.schema,
|
||||
argsOrSchema.source,
|
||||
argsOrSchema.rootValue,
|
||||
argsOrSchema.contextValue,
|
||||
argsOrSchema.variableValues,
|
||||
argsOrSchema.operationName,
|
||||
argsOrSchema.fieldResolver,
|
||||
)
|
||||
: graphqlImpl(
|
||||
argsOrSchema,
|
||||
source,
|
||||
rootValue,
|
||||
contextValue,
|
||||
variableValues,
|
||||
operationName,
|
||||
fieldResolver,
|
||||
);
|
||||
|
||||
// Assert that the execution was synchronous.
|
||||
if (result.then) {
|
||||
throw new Error('GraphQL execution failed to complete synchronously.');
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function graphqlImpl(
|
||||
schema,
|
||||
source,
|
||||
rootValue,
|
||||
contextValue,
|
||||
variableValues,
|
||||
operationName,
|
||||
fieldResolver,
|
||||
): MaybePromise<ExecutionResult> {
|
||||
// Validate Schema
|
||||
const schemaValidationErrors = validateSchema(schema);
|
||||
if (schemaValidationErrors.length > 0) {
|
||||
return { errors: schemaValidationErrors };
|
||||
}
|
||||
|
||||
// Parse
|
||||
let document;
|
||||
try {
|
||||
document = parse(source);
|
||||
} catch (syntaxError) {
|
||||
return { errors: [syntaxError] };
|
||||
}
|
||||
|
||||
// Validate
|
||||
const validationErrors = validate(schema, document);
|
||||
if (validationErrors.length > 0) {
|
||||
return { errors: validationErrors };
|
||||
}
|
||||
|
||||
// Execute
|
||||
return execute(
|
||||
schema,
|
||||
document,
|
||||
rootValue,
|
||||
contextValue,
|
||||
variableValues,
|
||||
operationName,
|
||||
fieldResolver,
|
||||
);
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { validateSchema } from './type/validate';
|
||||
import { parse } from './language/parser';
|
||||
import { validate } from './validation/validate';
|
||||
import { execute } from './execution/execute';
|
||||
export function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) {
|
||||
var _arguments = arguments;
|
||||
|
||||
/* eslint-enable no-redeclare */
|
||||
// Always return a Promise for a consistent API.
|
||||
return new Promise(function (resolve) {
|
||||
return resolve( // Extract arguments from object args if provided.
|
||||
_arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* The graphqlSync function also fulfills GraphQL operations by parsing,
|
||||
* validating, and executing a GraphQL document along side a GraphQL schema.
|
||||
* However, it guarantees to complete synchronously (or throw an error) assuming
|
||||
* that all field resolvers are also synchronous.
|
||||
*/
|
||||
|
||||
export function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) {
|
||||
/* eslint-enable no-redeclare */
|
||||
// Extract arguments from object args if provided.
|
||||
var result = arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver); // Assert that the execution was synchronous.
|
||||
|
||||
if (result.then) {
|
||||
throw new Error('GraphQL execution failed to complete synchronously.');
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function graphqlImpl(schema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) {
|
||||
// Validate Schema
|
||||
var schemaValidationErrors = validateSchema(schema);
|
||||
|
||||
if (schemaValidationErrors.length > 0) {
|
||||
return {
|
||||
errors: schemaValidationErrors
|
||||
};
|
||||
} // Parse
|
||||
|
||||
|
||||
var document;
|
||||
|
||||
try {
|
||||
document = parse(source);
|
||||
} catch (syntaxError) {
|
||||
return {
|
||||
errors: [syntaxError]
|
||||
};
|
||||
} // Validate
|
||||
|
||||
|
||||
var validationErrors = validate(schema, document);
|
||||
|
||||
if (validationErrors.length > 0) {
|
||||
return {
|
||||
errors: validationErrors
|
||||
};
|
||||
} // Execute
|
||||
|
||||
|
||||
return execute(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver);
|
||||
}
|
||||
+1071
File diff suppressed because it is too large.
Load diff
+427
@@ -0,0 +1,427 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* GraphQL.js provides a reference implementation for the GraphQL specification
|
||||
* but is also a useful utility for operating on GraphQL files and building
|
||||
* sophisticated tools.
|
||||
*
|
||||
* This primary module exports a general purpose function for fulfilling all
|
||||
* steps of the GraphQL specification in a single operation, but also includes
|
||||
* utilities for every part of the GraphQL specification:
|
||||
*
|
||||
* - Parsing the GraphQL language.
|
||||
* - Building a GraphQL type schema.
|
||||
* - Validating a GraphQL request against a type schema.
|
||||
* - Executing a GraphQL request against a type schema.
|
||||
*
|
||||
* This also includes utility functions for operating on GraphQL types and
|
||||
* GraphQL documents to facilitate building tools.
|
||||
*
|
||||
* You may also import from each sub-directory directly. For example, the
|
||||
* following two import statements are equivalent:
|
||||
*
|
||||
* import { parse } from 'graphql';
|
||||
* import { parse } from 'graphql/language';
|
||||
*/
|
||||
|
||||
// The primary entry point into fulfilling a GraphQL request.
|
||||
export type { GraphQLArgs } from './graphql';
|
||||
export { graphql, graphqlSync } from './graphql';
|
||||
|
||||
// Create and operate on GraphQL type definitions and schema.
|
||||
export {
|
||||
GraphQLSchema,
|
||||
// Definitions
|
||||
GraphQLScalarType,
|
||||
GraphQLObjectType,
|
||||
GraphQLInterfaceType,
|
||||
GraphQLUnionType,
|
||||
GraphQLEnumType,
|
||||
GraphQLInputObjectType,
|
||||
GraphQLList,
|
||||
GraphQLNonNull,
|
||||
GraphQLDirective,
|
||||
// "Enum" of Type Kinds
|
||||
TypeKind,
|
||||
// Scalars
|
||||
specifiedScalarTypes,
|
||||
GraphQLInt,
|
||||
GraphQLFloat,
|
||||
GraphQLString,
|
||||
GraphQLBoolean,
|
||||
GraphQLID,
|
||||
// Built-in Directives defined by the Spec
|
||||
specifiedDirectives,
|
||||
GraphQLIncludeDirective,
|
||||
GraphQLSkipDirective,
|
||||
GraphQLDeprecatedDirective,
|
||||
// Constant Deprecation Reason
|
||||
DEFAULT_DEPRECATION_REASON,
|
||||
// Meta-field definitions.
|
||||
SchemaMetaFieldDef,
|
||||
TypeMetaFieldDef,
|
||||
TypeNameMetaFieldDef,
|
||||
// GraphQL Types for introspection.
|
||||
introspectionTypes,
|
||||
__Schema,
|
||||
__Directive,
|
||||
__DirectiveLocation,
|
||||
__Type,
|
||||
__Field,
|
||||
__InputValue,
|
||||
__EnumValue,
|
||||
__TypeKind,
|
||||
// Predicates
|
||||
isSchema,
|
||||
isDirective,
|
||||
isType,
|
||||
isScalarType,
|
||||
isObjectType,
|
||||
isInterfaceType,
|
||||
isUnionType,
|
||||
isEnumType,
|
||||
isInputObjectType,
|
||||
isListType,
|
||||
isNonNullType,
|
||||
isInputType,
|
||||
isOutputType,
|
||||
isLeafType,
|
||||
isCompositeType,
|
||||
isAbstractType,
|
||||
isWrappingType,
|
||||
isNullableType,
|
||||
isNamedType,
|
||||
isRequiredArgument,
|
||||
isRequiredInputField,
|
||||
isSpecifiedScalarType,
|
||||
isIntrospectionType,
|
||||
isSpecifiedDirective,
|
||||
// Assertions
|
||||
assertType,
|
||||
assertScalarType,
|
||||
assertObjectType,
|
||||
assertInterfaceType,
|
||||
assertUnionType,
|
||||
assertEnumType,
|
||||
assertInputObjectType,
|
||||
assertListType,
|
||||
assertNonNullType,
|
||||
assertInputType,
|
||||
assertOutputType,
|
||||
assertLeafType,
|
||||
assertCompositeType,
|
||||
assertAbstractType,
|
||||
assertWrappingType,
|
||||
assertNullableType,
|
||||
assertNamedType,
|
||||
// Un-modifiers
|
||||
getNullableType,
|
||||
getNamedType,
|
||||
// Validate GraphQL schema.
|
||||
validateSchema,
|
||||
assertValidSchema,
|
||||
} from './type';
|
||||
|
||||
export type {
|
||||
GraphQLType,
|
||||
GraphQLInputType,
|
||||
GraphQLOutputType,
|
||||
GraphQLLeafType,
|
||||
GraphQLCompositeType,
|
||||
GraphQLAbstractType,
|
||||
GraphQLWrappingType,
|
||||
GraphQLNullableType,
|
||||
GraphQLNamedType,
|
||||
Thunk,
|
||||
GraphQLSchemaConfig,
|
||||
GraphQLArgument,
|
||||
GraphQLArgumentConfig,
|
||||
GraphQLEnumTypeConfig,
|
||||
GraphQLEnumValue,
|
||||
GraphQLEnumValueConfig,
|
||||
GraphQLEnumValueConfigMap,
|
||||
GraphQLField,
|
||||
GraphQLFieldConfig,
|
||||
GraphQLFieldConfigArgumentMap,
|
||||
GraphQLFieldConfigMap,
|
||||
GraphQLFieldMap,
|
||||
GraphQLFieldResolver,
|
||||
GraphQLInputField,
|
||||
GraphQLInputFieldConfig,
|
||||
GraphQLInputFieldConfigMap,
|
||||
GraphQLInputFieldMap,
|
||||
GraphQLInputObjectTypeConfig,
|
||||
GraphQLInterfaceTypeConfig,
|
||||
GraphQLIsTypeOfFn,
|
||||
GraphQLObjectTypeConfig,
|
||||
GraphQLResolveInfo,
|
||||
ResponsePath,
|
||||
GraphQLScalarTypeConfig,
|
||||
GraphQLTypeResolver,
|
||||
GraphQLUnionTypeConfig,
|
||||
GraphQLDirectiveConfig,
|
||||
GraphQLScalarSerializer,
|
||||
GraphQLScalarValueParser,
|
||||
GraphQLScalarLiteralParser,
|
||||
} from './type';
|
||||
|
||||
// Parse and operate on GraphQL language source files.
|
||||
export {
|
||||
Source,
|
||||
getLocation,
|
||||
// Parse
|
||||
parse,
|
||||
parseValue,
|
||||
parseType,
|
||||
// Print
|
||||
print,
|
||||
// Visit
|
||||
visit,
|
||||
visitInParallel,
|
||||
visitWithTypeInfo,
|
||||
getVisitFn,
|
||||
Kind,
|
||||
TokenKind,
|
||||
DirectiveLocation,
|
||||
BREAK,
|
||||
// Predicates
|
||||
isDefinitionNode,
|
||||
isExecutableDefinitionNode,
|
||||
isSelectionNode,
|
||||
isValueNode,
|
||||
isTypeNode,
|
||||
isTypeSystemDefinitionNode,
|
||||
isTypeDefinitionNode,
|
||||
isTypeSystemExtensionNode,
|
||||
isTypeExtensionNode,
|
||||
} from './language';
|
||||
|
||||
export type {
|
||||
Lexer,
|
||||
ParseOptions,
|
||||
SourceLocation,
|
||||
// Visitor utilities
|
||||
ASTVisitor,
|
||||
Visitor,
|
||||
VisitFn,
|
||||
VisitorKeyMap,
|
||||
// AST nodes
|
||||
Location,
|
||||
Token,
|
||||
ASTNode,
|
||||
ASTKindToNode,
|
||||
NameNode,
|
||||
DocumentNode,
|
||||
DefinitionNode,
|
||||
ExecutableDefinitionNode,
|
||||
OperationDefinitionNode,
|
||||
OperationTypeNode,
|
||||
VariableDefinitionNode,
|
||||
VariableNode,
|
||||
SelectionSetNode,
|
||||
SelectionNode,
|
||||
FieldNode,
|
||||
ArgumentNode,
|
||||
FragmentSpreadNode,
|
||||
InlineFragmentNode,
|
||||
FragmentDefinitionNode,
|
||||
ValueNode,
|
||||
IntValueNode,
|
||||
FloatValueNode,
|
||||
StringValueNode,
|
||||
BooleanValueNode,
|
||||
NullValueNode,
|
||||
EnumValueNode,
|
||||
ListValueNode,
|
||||
ObjectValueNode,
|
||||
ObjectFieldNode,
|
||||
DirectiveNode,
|
||||
TypeNode,
|
||||
NamedTypeNode,
|
||||
ListTypeNode,
|
||||
NonNullTypeNode,
|
||||
TypeSystemDefinitionNode,
|
||||
SchemaDefinitionNode,
|
||||
OperationTypeDefinitionNode,
|
||||
TypeDefinitionNode,
|
||||
ScalarTypeDefinitionNode,
|
||||
ObjectTypeDefinitionNode,
|
||||
FieldDefinitionNode,
|
||||
InputValueDefinitionNode,
|
||||
InterfaceTypeDefinitionNode,
|
||||
UnionTypeDefinitionNode,
|
||||
EnumTypeDefinitionNode,
|
||||
EnumValueDefinitionNode,
|
||||
InputObjectTypeDefinitionNode,
|
||||
DirectiveDefinitionNode,
|
||||
TypeSystemExtensionNode,
|
||||
SchemaExtensionNode,
|
||||
TypeExtensionNode,
|
||||
ScalarTypeExtensionNode,
|
||||
ObjectTypeExtensionNode,
|
||||
InterfaceTypeExtensionNode,
|
||||
UnionTypeExtensionNode,
|
||||
EnumTypeExtensionNode,
|
||||
InputObjectTypeExtensionNode,
|
||||
KindEnum,
|
||||
TokenKindEnum,
|
||||
DirectiveLocationEnum,
|
||||
} from './language';
|
||||
|
||||
// Execute GraphQL queries.
|
||||
export {
|
||||
execute,
|
||||
defaultFieldResolver,
|
||||
responsePathAsArray,
|
||||
getDirectiveValues,
|
||||
} from './execution';
|
||||
|
||||
export type { ExecutionArgs, ExecutionResult } from './execution';
|
||||
|
||||
export { subscribe, createSourceEventStream } from './subscription';
|
||||
|
||||
// Validate GraphQL queries.
|
||||
export {
|
||||
validate,
|
||||
ValidationContext,
|
||||
// All validation rules in the GraphQL Specification.
|
||||
specifiedRules,
|
||||
// Individual validation rules.
|
||||
FieldsOnCorrectTypeRule,
|
||||
FragmentsOnCompositeTypesRule,
|
||||
KnownArgumentNamesRule,
|
||||
KnownDirectivesRule,
|
||||
KnownFragmentNamesRule,
|
||||
KnownTypeNamesRule,
|
||||
LoneAnonymousOperationRule,
|
||||
NoFragmentCyclesRule,
|
||||
NoUndefinedVariablesRule,
|
||||
NoUnusedFragmentsRule,
|
||||
NoUnusedVariablesRule,
|
||||
OverlappingFieldsCanBeMergedRule,
|
||||
PossibleFragmentSpreadsRule,
|
||||
ProvidedRequiredArgumentsRule,
|
||||
ScalarLeafsRule,
|
||||
SingleFieldSubscriptionsRule,
|
||||
UniqueArgumentNamesRule,
|
||||
UniqueDirectivesPerLocationRule,
|
||||
UniqueFragmentNamesRule,
|
||||
UniqueInputFieldNamesRule,
|
||||
UniqueOperationNamesRule,
|
||||
UniqueVariableNamesRule,
|
||||
ValuesOfCorrectTypeRule,
|
||||
VariablesAreInputTypesRule,
|
||||
VariablesInAllowedPositionRule,
|
||||
} from './validation';
|
||||
|
||||
// Create, format, and print GraphQL errors.
|
||||
export { GraphQLError, formatError, printError } from './error';
|
||||
|
||||
export type { GraphQLFormattedError } from './error';
|
||||
|
||||
// Utilities for operating on GraphQL type schema and parsed sources.
|
||||
export {
|
||||
// Produce the GraphQL query recommended for a full schema introspection.
|
||||
// Accepts optional IntrospectionOptions.
|
||||
getIntrospectionQuery,
|
||||
// @deprecated: use getIntrospectionQuery - will be removed in v15
|
||||
introspectionQuery,
|
||||
// Gets the target Operation from a Document
|
||||
getOperationAST,
|
||||
// Gets the Type for the target Operation AST.
|
||||
getOperationRootType,
|
||||
// Convert a GraphQLSchema to an IntrospectionQuery
|
||||
introspectionFromSchema,
|
||||
// Build a GraphQLSchema from an introspection result.
|
||||
buildClientSchema,
|
||||
// Build a GraphQLSchema from a parsed GraphQL Schema language AST.
|
||||
buildASTSchema,
|
||||
// Build a GraphQLSchema from a GraphQL schema language document.
|
||||
buildSchema,
|
||||
// @deprecated: Get the description from a schema AST node and supports legacy
|
||||
// syntax for specifying descriptions - will be removed in v16
|
||||
getDescription,
|
||||
// Extends an existing GraphQLSchema from a parsed GraphQL Schema
|
||||
// language AST.
|
||||
extendSchema,
|
||||
// Sort a GraphQLSchema.
|
||||
lexicographicSortSchema,
|
||||
// Print a GraphQLSchema to GraphQL Schema language.
|
||||
printSchema,
|
||||
// Prints the built-in introspection schema in the Schema Language
|
||||
// format.
|
||||
printIntrospectionSchema,
|
||||
// Print a GraphQLType to GraphQL Schema language.
|
||||
printType,
|
||||
// Create a GraphQLType from a GraphQL language AST.
|
||||
typeFromAST,
|
||||
// Create a JavaScript value from a GraphQL language AST with a Type.
|
||||
valueFromAST,
|
||||
// Create a JavaScript value from a GraphQL language AST without a Type.
|
||||
valueFromASTUntyped,
|
||||
// Create a GraphQL language AST from a JavaScript value.
|
||||
astFromValue,
|
||||
// A helper to use within recursive-descent visitors which need to be aware of
|
||||
// the GraphQL type system.
|
||||
TypeInfo,
|
||||
// Coerces a JavaScript value to a GraphQL type, or produces errors.
|
||||
coerceValue,
|
||||
// @deprecated use coerceValue - will be removed in v15
|
||||
isValidJSValue,
|
||||
// @deprecated use validation - will be removed in v15
|
||||
isValidLiteralValue,
|
||||
// Concatenates multiple AST together.
|
||||
concatAST,
|
||||
// Separates an AST into an AST per Operation.
|
||||
separateOperations,
|
||||
// Comparators for types
|
||||
isEqualType,
|
||||
isTypeSubTypeOf,
|
||||
doTypesOverlap,
|
||||
// Asserts a string is a valid GraphQL name.
|
||||
assertValidName,
|
||||
// Determine if a string is a valid GraphQL name.
|
||||
isValidNameError,
|
||||
// Compares two GraphQLSchemas and detects breaking changes.
|
||||
findBreakingChanges,
|
||||
findDangerousChanges,
|
||||
BreakingChangeType,
|
||||
DangerousChangeType,
|
||||
// Report all deprecated usage within a GraphQL document.
|
||||
findDeprecatedUsages,
|
||||
} from './utilities';
|
||||
|
||||
export type {
|
||||
BuildSchemaOptions,
|
||||
BreakingChange,
|
||||
DangerousChange,
|
||||
IntrospectionOptions,
|
||||
IntrospectionDirective,
|
||||
IntrospectionEnumType,
|
||||
IntrospectionEnumValue,
|
||||
IntrospectionField,
|
||||
IntrospectionInputObjectType,
|
||||
IntrospectionInputType,
|
||||
IntrospectionInputTypeRef,
|
||||
IntrospectionInputValue,
|
||||
IntrospectionInterfaceType,
|
||||
IntrospectionListTypeRef,
|
||||
IntrospectionNamedTypeRef,
|
||||
IntrospectionNonNullTypeRef,
|
||||
IntrospectionObjectType,
|
||||
IntrospectionOutputType,
|
||||
IntrospectionOutputTypeRef,
|
||||
IntrospectionQuery,
|
||||
IntrospectionScalarType,
|
||||
IntrospectionSchema,
|
||||
IntrospectionType,
|
||||
IntrospectionTypeRef,
|
||||
IntrospectionUnionType,
|
||||
} from './utilities';
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* GraphQL.js provides a reference implementation for the GraphQL specification
|
||||
* but is also a useful utility for operating on GraphQL files and building
|
||||
* sophisticated tools.
|
||||
*
|
||||
* This primary module exports a general purpose function for fulfilling all
|
||||
* steps of the GraphQL specification in a single operation, but also includes
|
||||
* utilities for every part of the GraphQL specification:
|
||||
*
|
||||
* - Parsing the GraphQL language.
|
||||
* - Building a GraphQL type schema.
|
||||
* - Validating a GraphQL request against a type schema.
|
||||
* - Executing a GraphQL request against a type schema.
|
||||
*
|
||||
* This also includes utility functions for operating on GraphQL types and
|
||||
* GraphQL documents to facilitate building tools.
|
||||
*
|
||||
* You may also import from each sub-directory directly. For example, the
|
||||
* following two import statements are equivalent:
|
||||
*
|
||||
* import { parse } from 'graphql';
|
||||
* import { parse } from 'graphql/language';
|
||||
*/
|
||||
// The primary entry point into fulfilling a GraphQL request.
|
||||
export { graphql, graphqlSync } from './graphql'; // Create and operate on GraphQL type definitions and schema.
|
||||
|
||||
export { GraphQLSchema, // Definitions
|
||||
GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLDirective, // "Enum" of Type Kinds
|
||||
TypeKind, // Scalars
|
||||
specifiedScalarTypes, GraphQLInt, GraphQLFloat, GraphQLString, GraphQLBoolean, GraphQLID, // Built-in Directives defined by the Spec
|
||||
specifiedDirectives, GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, // Constant Deprecation Reason
|
||||
DEFAULT_DEPRECATION_REASON, // Meta-field definitions.
|
||||
SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef, // GraphQL Types for introspection.
|
||||
introspectionTypes, __Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind, // Predicates
|
||||
isSchema, isDirective, isType, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isListType, isNonNullType, isInputType, isOutputType, isLeafType, isCompositeType, isAbstractType, isWrappingType, isNullableType, isNamedType, isRequiredArgument, isRequiredInputField, isSpecifiedScalarType, isIntrospectionType, isSpecifiedDirective, // Assertions
|
||||
assertType, assertScalarType, assertObjectType, assertInterfaceType, assertUnionType, assertEnumType, assertInputObjectType, assertListType, assertNonNullType, assertInputType, assertOutputType, assertLeafType, assertCompositeType, assertAbstractType, assertWrappingType, assertNullableType, assertNamedType, // Un-modifiers
|
||||
getNullableType, getNamedType, // Validate GraphQL schema.
|
||||
validateSchema, assertValidSchema } from './type';
|
||||
// Parse and operate on GraphQL language source files.
|
||||
export { Source, getLocation, // Parse
|
||||
parse, parseValue, parseType, // Print
|
||||
print, // Visit
|
||||
visit, visitInParallel, visitWithTypeInfo, getVisitFn, Kind, TokenKind, DirectiveLocation, BREAK, // Predicates
|
||||
isDefinitionNode, isExecutableDefinitionNode, isSelectionNode, isValueNode, isTypeNode, isTypeSystemDefinitionNode, isTypeDefinitionNode, isTypeSystemExtensionNode, isTypeExtensionNode } from './language';
|
||||
// Execute GraphQL queries.
|
||||
export { execute, defaultFieldResolver, responsePathAsArray, getDirectiveValues } from './execution';
|
||||
export { subscribe, createSourceEventStream } from './subscription'; // Validate GraphQL queries.
|
||||
|
||||
export { validate, ValidationContext, // All validation rules in the GraphQL Specification.
|
||||
specifiedRules, // Individual validation rules.
|
||||
FieldsOnCorrectTypeRule, FragmentsOnCompositeTypesRule, KnownArgumentNamesRule, KnownDirectivesRule, KnownFragmentNamesRule, KnownTypeNamesRule, LoneAnonymousOperationRule, NoFragmentCyclesRule, NoUndefinedVariablesRule, NoUnusedFragmentsRule, NoUnusedVariablesRule, OverlappingFieldsCanBeMergedRule, PossibleFragmentSpreadsRule, ProvidedRequiredArgumentsRule, ScalarLeafsRule, SingleFieldSubscriptionsRule, UniqueArgumentNamesRule, UniqueDirectivesPerLocationRule, UniqueFragmentNamesRule, UniqueInputFieldNamesRule, UniqueOperationNamesRule, UniqueVariableNamesRule, ValuesOfCorrectTypeRule, VariablesAreInputTypesRule, VariablesInAllowedPositionRule } from './validation'; // Create, format, and print GraphQL errors.
|
||||
|
||||
export { GraphQLError, formatError, printError } from './error';
|
||||
// Utilities for operating on GraphQL type schema and parsed sources.
|
||||
export { // Produce the GraphQL query recommended for a full schema introspection.
|
||||
// Accepts optional IntrospectionOptions.
|
||||
getIntrospectionQuery, // @deprecated: use getIntrospectionQuery - will be removed in v15
|
||||
introspectionQuery, // Gets the target Operation from a Document
|
||||
getOperationAST, // Gets the Type for the target Operation AST.
|
||||
getOperationRootType, // Convert a GraphQLSchema to an IntrospectionQuery
|
||||
introspectionFromSchema, // Build a GraphQLSchema from an introspection result.
|
||||
buildClientSchema, // Build a GraphQLSchema from a parsed GraphQL Schema language AST.
|
||||
buildASTSchema, // Build a GraphQLSchema from a GraphQL schema language document.
|
||||
buildSchema, // @deprecated: Get the description from a schema AST node and supports legacy
|
||||
// syntax for specifying descriptions - will be removed in v16
|
||||
getDescription, // Extends an existing GraphQLSchema from a parsed GraphQL Schema
|
||||
// language AST.
|
||||
extendSchema, // Sort a GraphQLSchema.
|
||||
lexicographicSortSchema, // Print a GraphQLSchema to GraphQL Schema language.
|
||||
printSchema, // Prints the built-in introspection schema in the Schema Language
|
||||
// format.
|
||||
printIntrospectionSchema, // Print a GraphQLType to GraphQL Schema language.
|
||||
printType, // Create a GraphQLType from a GraphQL language AST.
|
||||
typeFromAST, // Create a JavaScript value from a GraphQL language AST with a Type.
|
||||
valueFromAST, // Create a JavaScript value from a GraphQL language AST without a Type.
|
||||
valueFromASTUntyped, // Create a GraphQL language AST from a JavaScript value.
|
||||
astFromValue, // A helper to use within recursive-descent visitors which need to be aware of
|
||||
// the GraphQL type system.
|
||||
TypeInfo, // Coerces a JavaScript value to a GraphQL type, or produces errors.
|
||||
coerceValue, // @deprecated use coerceValue - will be removed in v15
|
||||
isValidJSValue, // @deprecated use validation - will be removed in v15
|
||||
isValidLiteralValue, // Concatenates multiple AST together.
|
||||
concatAST, // Separates an AST into an AST per Operation.
|
||||
separateOperations, // Comparators for types
|
||||
isEqualType, isTypeSubTypeOf, doTypesOverlap, // Asserts a string is a valid GraphQL name.
|
||||
assertValidName, // Determine if a string is a valid GraphQL name.
|
||||
isValidNameError, // Compares two GraphQLSchemas and detects breaking changes.
|
||||
findBreakingChanges, findDangerousChanges, BreakingChangeType, DangerousChangeType, // Report all deprecated usage within a GraphQL document.
|
||||
findDeprecatedUsages } from './utilities';
|
||||
+1
@@ -0,0 +1 @@
|
||||
"use strict";
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
export type MaybePromise<+T> = Promise<T> | T;
|
||||
Whitespace-only changes.
+1
@@ -0,0 +1 @@
|
||||
"use strict";
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
export type ObjMap<T> = { [key: string]: T, __proto__: null };
|
||||
Whitespace-only changes.
+66
@@ -0,0 +1,66 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = dedent;
|
||||
|
||||
var _invariant = _interopRequireDefault(require("./invariant"));
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* fixes indentation by removing leading spaces and tabs from each line
|
||||
*/
|
||||
function fixIndent(str) {
|
||||
var trimmedStr = str.replace(/^\n*/m, '') // remove leading newline
|
||||
.replace(/[ \t]*$/, ''); // remove trailing spaces and tabs
|
||||
|
||||
var indentMatch = /^[ \t]*/.exec(trimmedStr);
|
||||
!Array.isArray(indentMatch) ? (0, _invariant.default)(0) : void 0;
|
||||
var indent = indentMatch[0]; // figure out indent
|
||||
|
||||
return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent
|
||||
}
|
||||
/**
|
||||
* An ES6 string tag that fixes indentation. Also removes leading newlines
|
||||
* and trailing spaces and tabs, but keeps trailing newlines.
|
||||
*
|
||||
* Example usage:
|
||||
* const str = dedent`
|
||||
* {
|
||||
* test
|
||||
* }
|
||||
* `
|
||||
* str === "{\n test\n}\n";
|
||||
*/
|
||||
|
||||
|
||||
function dedent(strings) {
|
||||
for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
||||
values[_key - 1] = arguments[_key];
|
||||
}
|
||||
|
||||
// when used as an ordinary function, allow passing a singleton string
|
||||
var strArray = typeof strings === 'string' ? [strings] : strings;
|
||||
var numValues = values.length;
|
||||
var str = strArray.reduce(function (prev, cur, index) {
|
||||
var next = prev + cur;
|
||||
|
||||
if (index < numValues) {
|
||||
next += values[index]; // interpolation
|
||||
}
|
||||
|
||||
return next;
|
||||
}, '');
|
||||
return fixIndent(str);
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import invariant from './invariant';
|
||||
|
||||
/**
|
||||
* fixes indentation by removing leading spaces and tabs from each line
|
||||
*/
|
||||
function fixIndent(str: string): string {
|
||||
const trimmedStr = str
|
||||
.replace(/^\n*/m, '') // remove leading newline
|
||||
.replace(/[ \t]*$/, ''); // remove trailing spaces and tabs
|
||||
const indentMatch = /^[ \t]*/.exec(trimmedStr);
|
||||
invariant(Array.isArray(indentMatch));
|
||||
const indent = indentMatch[0]; // figure out indent
|
||||
return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent
|
||||
}
|
||||
|
||||
/**
|
||||
* An ES6 string tag that fixes indentation. Also removes leading newlines
|
||||
* and trailing spaces and tabs, but keeps trailing newlines.
|
||||
*
|
||||
* Example usage:
|
||||
* const str = dedent`
|
||||
* {
|
||||
* test
|
||||
* }
|
||||
* `
|
||||
* str === "{\n test\n}\n";
|
||||
*/
|
||||
export default function dedent(
|
||||
strings: string | Array<string>,
|
||||
...values: Array<string>
|
||||
): string {
|
||||
// when used as an ordinary function, allow passing a singleton string
|
||||
const strArray = typeof strings === 'string' ? [strings] : strings;
|
||||
const numValues = values.length;
|
||||
|
||||
const str = strArray.reduce((prev, cur, index) => {
|
||||
let next = prev + cur;
|
||||
if (index < numValues) {
|
||||
next += values[index]; // interpolation
|
||||
}
|
||||
return next;
|
||||
}, '');
|
||||
|
||||
return fixIndent(str);
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import invariant from './invariant';
|
||||
/**
|
||||
* fixes indentation by removing leading spaces and tabs from each line
|
||||
*/
|
||||
|
||||
function fixIndent(str) {
|
||||
var trimmedStr = str.replace(/^\n*/m, '') // remove leading newline
|
||||
.replace(/[ \t]*$/, ''); // remove trailing spaces and tabs
|
||||
|
||||
var indentMatch = /^[ \t]*/.exec(trimmedStr);
|
||||
!Array.isArray(indentMatch) ? invariant(0) : void 0;
|
||||
var indent = indentMatch[0]; // figure out indent
|
||||
|
||||
return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent
|
||||
}
|
||||
/**
|
||||
* An ES6 string tag that fixes indentation. Also removes leading newlines
|
||||
* and trailing spaces and tabs, but keeps trailing newlines.
|
||||
*
|
||||
* Example usage:
|
||||
* const str = dedent`
|
||||
* {
|
||||
* test
|
||||
* }
|
||||
* `
|
||||
* str === "{\n test\n}\n";
|
||||
*/
|
||||
|
||||
|
||||
export default function dedent(strings) {
|
||||
for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
||||
values[_key - 1] = arguments[_key];
|
||||
}
|
||||
|
||||
// when used as an ordinary function, allow passing a singleton string
|
||||
var strArray = typeof strings === 'string' ? [strings] : strings;
|
||||
var numValues = values.length;
|
||||
var str = strArray.reduce(function (prev, cur, index) {
|
||||
var next = prev + cur;
|
||||
|
||||
if (index < numValues) {
|
||||
next += values[index]; // interpolation
|
||||
}
|
||||
|
||||
return next;
|
||||
}, '');
|
||||
return fixIndent(str);
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = applyToJSON;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* The `applyToJSON()` function defines toJSON() and inspect() prototype
|
||||
* methods which are aliases for toString().
|
||||
*/
|
||||
function applyToJSON(classObject) {
|
||||
classObject.prototype.toJSON = classObject.prototype.inspect = classObject.prototype.toString;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* The `applyToJSON()` function defines toJSON() and inspect() prototype
|
||||
* methods which are aliases for toString().
|
||||
*/
|
||||
export default function applyToJSON(classObject: Class<any>): void {
|
||||
classObject.prototype.toJSON = classObject.prototype.inspect =
|
||||
classObject.prototype.toString;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* The `applyToJSON()` function defines toJSON() and inspect() prototype
|
||||
* methods which are aliases for toString().
|
||||
*/
|
||||
export default function applyToJSON(classObject) {
|
||||
classObject.prototype.toJSON = classObject.prototype.inspect = classObject.prototype.toString;
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = applyToStringTag;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* The `applyToStringTag()` function checks first to see if the runtime
|
||||
* supports the `Symbol` class and then if the `Symbol.toStringTag` constant
|
||||
* is defined as a `Symbol` instance. If both conditions are met, the
|
||||
* Symbol.toStringTag property is defined as a getter that returns the
|
||||
* supplied class constructor's name.
|
||||
*
|
||||
* @method applyToStringTag
|
||||
*
|
||||
* @param {Class<any>} classObject a class such as Object, String, Number but
|
||||
* typically one of your own creation through the class keyword; `class A {}`,
|
||||
* for example.
|
||||
*/
|
||||
function applyToStringTag(classObject) {
|
||||
if (typeof Symbol === 'function' && Symbol.toStringTag) {
|
||||
Object.defineProperty(classObject.prototype, Symbol.toStringTag, {
|
||||
get: function get() {
|
||||
return this.constructor.name;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* The `applyToStringTag()` function checks first to see if the runtime
|
||||
* supports the `Symbol` class and then if the `Symbol.toStringTag` constant
|
||||
* is defined as a `Symbol` instance. If both conditions are met, the
|
||||
* Symbol.toStringTag property is defined as a getter that returns the
|
||||
* supplied class constructor's name.
|
||||
*
|
||||
* @method applyToStringTag
|
||||
*
|
||||
* @param {Class<any>} classObject a class such as Object, String, Number but
|
||||
* typically one of your own creation through the class keyword; `class A {}`,
|
||||
* for example.
|
||||
*/
|
||||
export default function applyToStringTag(classObject: Class<any>): void {
|
||||
if (typeof Symbol === 'function' && Symbol.toStringTag) {
|
||||
Object.defineProperty(classObject.prototype, Symbol.toStringTag, {
|
||||
get() {
|
||||
return this.constructor.name;
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* The `applyToStringTag()` function checks first to see if the runtime
|
||||
* supports the `Symbol` class and then if the `Symbol.toStringTag` constant
|
||||
* is defined as a `Symbol` instance. If both conditions are met, the
|
||||
* Symbol.toStringTag property is defined as a getter that returns the
|
||||
* supplied class constructor's name.
|
||||
*
|
||||
* @method applyToStringTag
|
||||
*
|
||||
* @param {Class<any>} classObject a class such as Object, String, Number but
|
||||
* typically one of your own creation through the class keyword; `class A {}`,
|
||||
* for example.
|
||||
*/
|
||||
export default function applyToStringTag(classObject) {
|
||||
if (typeof Symbol === 'function' && Symbol.toStringTag) {
|
||||
Object.defineProperty(classObject.prototype, Symbol.toStringTag, {
|
||||
get: function get() {
|
||||
return this.constructor.name;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = find;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
function find(list, predicate) {
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
if (predicate(list[i])) {
|
||||
return list[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
export default function find<T>(
|
||||
list: $ReadOnlyArray<T>,
|
||||
predicate: (item: T) => boolean,
|
||||
): ?T {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
if (predicate(list[i])) {
|
||||
return list[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
export default function find(list, predicate) {
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
if (predicate(list[i])) {
|
||||
return list[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = inspect;
|
||||
|
||||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Used to print values in error messages.
|
||||
*/
|
||||
function inspect(value) {
|
||||
return value && _typeof(value) === 'object' ? typeof value.inspect === 'function' ? value.inspect() : Array.isArray(value) ? '[' + value.map(inspect).join(', ') + ']' : '{' + Object.keys(value).map(function (k) {
|
||||
return "".concat(k, ": ").concat(inspect(value[k]));
|
||||
}).join(', ') + '}' : typeof value === 'string' ? '"' + value + '"' : typeof value === 'function' ? "[function ".concat(value.name, "]") : String(value);
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Used to print values in error messages.
|
||||
*/
|
||||
export default function inspect(value: mixed): string {
|
||||
return value && typeof value === 'object'
|
||||
? typeof value.inspect === 'function'
|
||||
? value.inspect()
|
||||
: Array.isArray(value)
|
||||
? '[' + value.map(inspect).join(', ') + ']'
|
||||
: '{' +
|
||||
Object.keys(value)
|
||||
.map(k => `${k}: ${inspect(value[k])}`)
|
||||
.join(', ') +
|
||||
'}'
|
||||
: typeof value === 'string'
|
||||
? '"' + value + '"'
|
||||
: typeof value === 'function'
|
||||
? `[function ${value.name}]`
|
||||
: String(value);
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Used to print values in error messages.
|
||||
*/
|
||||
export default function inspect(value) {
|
||||
return value && _typeof(value) === 'object' ? typeof value.inspect === 'function' ? value.inspect() : Array.isArray(value) ? '[' + value.map(inspect).join(', ') + ']' : '{' + Object.keys(value).map(function (k) {
|
||||
return "".concat(k, ": ").concat(inspect(value[k]));
|
||||
}).join(', ') + '}' : typeof value === 'string' ? '"' + value + '"' : typeof value === 'function' ? "[function ".concat(value.name, "]") : String(value);
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = void 0;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* A replacement for instanceof which includes an error warning when multi-realm
|
||||
* constructors are detected.
|
||||
*/
|
||||
// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
|
||||
// See: https://webpack.js.org/guides/production/
|
||||
var _default = process.env.NODE_ENV === 'production' ? // eslint-disable-next-line no-shadow
|
||||
function instanceOf(value, constructor) {
|
||||
return value instanceof constructor;
|
||||
} : // eslint-disable-next-line no-shadow
|
||||
function instanceOf(value, constructor) {
|
||||
if (value instanceof constructor) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value) {
|
||||
var valueClass = value.constructor;
|
||||
var className = constructor.name;
|
||||
|
||||
if (className && valueClass && valueClass.name === className) {
|
||||
throw new Error("Cannot use ".concat(className, " \"").concat(value, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results."));
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
exports.default = _default;
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* A replacement for instanceof which includes an error warning when multi-realm
|
||||
* constructors are detected.
|
||||
*/
|
||||
declare function instanceOf(
|
||||
value: mixed,
|
||||
constructor: mixed,
|
||||
): boolean %checks(value instanceof constructor);
|
||||
|
||||
// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
|
||||
// See: https://webpack.js.org/guides/production/
|
||||
export default (process.env.NODE_ENV === 'production'
|
||||
? // eslint-disable-next-line no-shadow
|
||||
function instanceOf(value: mixed, constructor: mixed) {
|
||||
return value instanceof constructor;
|
||||
}
|
||||
: // eslint-disable-next-line no-shadow
|
||||
function instanceOf(value: any, constructor: any) {
|
||||
if (value instanceof constructor) {
|
||||
return true;
|
||||
}
|
||||
if (value) {
|
||||
const valueClass = value.constructor;
|
||||
const className = constructor.name;
|
||||
if (className && valueClass && valueClass.name === className) {
|
||||
throw new Error(
|
||||
`Cannot use ${className} "${value}" from another module or realm.
|
||||
|
||||
Ensure that there is only one instance of "graphql" in the node_modules
|
||||
directory. If different versions of "graphql" are the dependencies of other
|
||||
relied on modules, use "resolutions" to ensure only one version is installed.
|
||||
|
||||
https://yarnpkg.com/en/docs/selective-version-resolutions
|
||||
|
||||
Duplicate "graphql" modules cannot be used at the same time since different
|
||||
versions may have different capabilities and behavior. The data from one
|
||||
version used in the function from another could produce confusing and
|
||||
spurious results.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* A replacement for instanceof which includes an error warning when multi-realm
|
||||
* constructors are detected.
|
||||
*/
|
||||
// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
|
||||
// See: https://webpack.js.org/guides/production/
|
||||
export default process.env.NODE_ENV === 'production' ? // eslint-disable-next-line no-shadow
|
||||
function instanceOf(value, constructor) {
|
||||
return value instanceof constructor;
|
||||
} : // eslint-disable-next-line no-shadow
|
||||
function instanceOf(value, constructor) {
|
||||
if (value instanceof constructor) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value) {
|
||||
var valueClass = value.constructor;
|
||||
var className = constructor.name;
|
||||
|
||||
if (className && valueClass && valueClass.name === className) {
|
||||
throw new Error("Cannot use ".concat(className, " \"").concat(value, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results."));
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = invariant;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
function invariant(condition, message) {
|
||||
/* istanbul ignore else */
|
||||
if (!condition) {
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
export default function invariant(condition: mixed, message: string) {
|
||||
/* istanbul ignore else */
|
||||
if (!condition) {
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
export default function invariant(condition, message) {
|
||||
/* istanbul ignore else */
|
||||
if (!condition) {
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = void 0;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2018-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/* eslint-disable no-redeclare */
|
||||
// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441
|
||||
var isFinite = Number.isFinite || function (value) {
|
||||
return typeof value === 'number' && isFinite(value);
|
||||
};
|
||||
|
||||
var _default = isFinite;
|
||||
exports.default = _default;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) 2018-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
declare function isFinite(value: mixed): boolean %checks(typeof value ===
|
||||
'number');
|
||||
|
||||
/* eslint-disable no-redeclare */
|
||||
// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441
|
||||
const isFinite =
|
||||
Number.isFinite ||
|
||||
function(value) {
|
||||
return typeof value === 'number' && isFinite(value);
|
||||
};
|
||||
export default isFinite;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Copyright (c) 2018-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/* eslint-disable no-redeclare */
|
||||
// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441
|
||||
var isFinite = Number.isFinite || function (value) {
|
||||
return typeof value === 'number' && isFinite(value);
|
||||
};
|
||||
|
||||
export default isFinite;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = void 0;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2018-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/* eslint-disable no-redeclare */
|
||||
// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441
|
||||
var isInteger = Number.isInteger || function (value) {
|
||||
return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
|
||||
};
|
||||
|
||||
var _default = isInteger;
|
||||
exports.default = _default;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Copyright (c) 2018-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
declare function isInteger(value: mixed): boolean %checks(typeof value ===
|
||||
'number');
|
||||
|
||||
/* eslint-disable no-redeclare */
|
||||
// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441
|
||||
const isInteger =
|
||||
Number.isInteger ||
|
||||
function(value) {
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
isFinite(value) &&
|
||||
Math.floor(value) === value
|
||||
);
|
||||
};
|
||||
export default isInteger;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Copyright (c) 2018-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/* eslint-disable no-redeclare */
|
||||
// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441
|
||||
var isInteger = Number.isInteger || function (value) {
|
||||
return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
|
||||
};
|
||||
|
||||
export default isInteger;
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = isInvalid;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns true if a value is undefined, or NaN.
|
||||
*/
|
||||
function isInvalid(value) {
|
||||
return value === undefined || value !== value;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns true if a value is undefined, or NaN.
|
||||
*/
|
||||
export default function isInvalid(value: mixed): boolean %checks {
|
||||
return value === undefined || value !== value;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns true if a value is undefined, or NaN.
|
||||
*/
|
||||
export default function isInvalid(value) {
|
||||
return value === undefined || value !== value;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = isNullish;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns true if a value is null, undefined, or NaN.
|
||||
*/
|
||||
function isNullish(value) {
|
||||
return value === null || value === undefined || value !== value;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns true if a value is null, undefined, or NaN.
|
||||
*/
|
||||
export default function isNullish(value: mixed): boolean %checks {
|
||||
return value === null || value === undefined || value !== value;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns true if a value is null, undefined, or NaN.
|
||||
*/
|
||||
export default function isNullish(value) {
|
||||
return value === null || value === undefined || value !== value;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = isPromise;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns true if the value acts like a Promise, i.e. has a "then" function,
|
||||
* otherwise returns false.
|
||||
*/
|
||||
// eslint-disable-next-line no-redeclare
|
||||
function isPromise(value) {
|
||||
return Boolean(value && typeof value.then === 'function');
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns true if the value acts like a Promise, i.e. has a "then" function,
|
||||
* otherwise returns false.
|
||||
*/
|
||||
declare function isPromise(value: mixed): boolean %checks(value instanceof
|
||||
Promise);
|
||||
|
||||
// eslint-disable-next-line no-redeclare
|
||||
export default function isPromise(value) {
|
||||
return Boolean(value && typeof value.then === 'function');
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns true if the value acts like a Promise, i.e. has a "then" function,
|
||||
* otherwise returns false.
|
||||
*/
|
||||
// eslint-disable-next-line no-redeclare
|
||||
export default function isPromise(value) {
|
||||
return Boolean(value && typeof value.then === 'function');
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = keyMap;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a keyed JS object from an array, given a function to produce the keys
|
||||
* for each value in the array.
|
||||
*
|
||||
* This provides a convenient lookup for the array items if the key function
|
||||
* produces unique results.
|
||||
*
|
||||
* const phoneBook = [
|
||||
* { name: 'Jon', num: '555-1234' },
|
||||
* { name: 'Jenny', num: '867-5309' }
|
||||
* ]
|
||||
*
|
||||
* // { Jon: { name: 'Jon', num: '555-1234' },
|
||||
* // Jenny: { name: 'Jenny', num: '867-5309' } }
|
||||
* const entriesByName = keyMap(
|
||||
* phoneBook,
|
||||
* entry => entry.name
|
||||
* )
|
||||
*
|
||||
* // { name: 'Jenny', num: '857-6309' }
|
||||
* const jennyEntry = entriesByName['Jenny']
|
||||
*
|
||||
*/
|
||||
function keyMap(list, keyFn) {
|
||||
return list.reduce(function (map, item) {
|
||||
return map[keyFn(item)] = item, map;
|
||||
}, Object.create(null));
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import type { ObjMap } from './ObjMap';
|
||||
|
||||
/**
|
||||
* Creates a keyed JS object from an array, given a function to produce the keys
|
||||
* for each value in the array.
|
||||
*
|
||||
* This provides a convenient lookup for the array items if the key function
|
||||
* produces unique results.
|
||||
*
|
||||
* const phoneBook = [
|
||||
* { name: 'Jon', num: '555-1234' },
|
||||
* { name: 'Jenny', num: '867-5309' }
|
||||
* ]
|
||||
*
|
||||
* // { Jon: { name: 'Jon', num: '555-1234' },
|
||||
* // Jenny: { name: 'Jenny', num: '867-5309' } }
|
||||
* const entriesByName = keyMap(
|
||||
* phoneBook,
|
||||
* entry => entry.name
|
||||
* )
|
||||
*
|
||||
* // { name: 'Jenny', num: '857-6309' }
|
||||
* const jennyEntry = entriesByName['Jenny']
|
||||
*
|
||||
*/
|
||||
export default function keyMap<T>(
|
||||
list: $ReadOnlyArray<T>,
|
||||
keyFn: (item: T) => string,
|
||||
): ObjMap<T> {
|
||||
return list.reduce(
|
||||
(map, item) => ((map[keyFn(item)] = item), map),
|
||||
Object.create(null),
|
||||
);
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a keyed JS object from an array, given a function to produce the keys
|
||||
* for each value in the array.
|
||||
*
|
||||
* This provides a convenient lookup for the array items if the key function
|
||||
* produces unique results.
|
||||
*
|
||||
* const phoneBook = [
|
||||
* { name: 'Jon', num: '555-1234' },
|
||||
* { name: 'Jenny', num: '867-5309' }
|
||||
* ]
|
||||
*
|
||||
* // { Jon: { name: 'Jon', num: '555-1234' },
|
||||
* // Jenny: { name: 'Jenny', num: '867-5309' } }
|
||||
* const entriesByName = keyMap(
|
||||
* phoneBook,
|
||||
* entry => entry.name
|
||||
* )
|
||||
*
|
||||
* // { name: 'Jenny', num: '857-6309' }
|
||||
* const jennyEntry = entriesByName['Jenny']
|
||||
*
|
||||
*/
|
||||
export default function keyMap(list, keyFn) {
|
||||
return list.reduce(function (map, item) {
|
||||
return map[keyFn(item)] = item, map;
|
||||
}, Object.create(null));
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = keyValMap;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a keyed JS object from an array, given a function to produce the keys
|
||||
* and a function to produce the values from each item in the array.
|
||||
*
|
||||
* const phoneBook = [
|
||||
* { name: 'Jon', num: '555-1234' },
|
||||
* { name: 'Jenny', num: '867-5309' }
|
||||
* ]
|
||||
*
|
||||
* // { Jon: '555-1234', Jenny: '867-5309' }
|
||||
* const phonesByName = keyValMap(
|
||||
* phoneBook,
|
||||
* entry => entry.name,
|
||||
* entry => entry.num
|
||||
* )
|
||||
*
|
||||
*/
|
||||
function keyValMap(list, keyFn, valFn) {
|
||||
return list.reduce(function (map, item) {
|
||||
return map[keyFn(item)] = valFn(item), map;
|
||||
}, Object.create(null));
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import type { ObjMap } from './ObjMap';
|
||||
|
||||
/**
|
||||
* Creates a keyed JS object from an array, given a function to produce the keys
|
||||
* and a function to produce the values from each item in the array.
|
||||
*
|
||||
* const phoneBook = [
|
||||
* { name: 'Jon', num: '555-1234' },
|
||||
* { name: 'Jenny', num: '867-5309' }
|
||||
* ]
|
||||
*
|
||||
* // { Jon: '555-1234', Jenny: '867-5309' }
|
||||
* const phonesByName = keyValMap(
|
||||
* phoneBook,
|
||||
* entry => entry.name,
|
||||
* entry => entry.num
|
||||
* )
|
||||
*
|
||||
*/
|
||||
export default function keyValMap<T, V>(
|
||||
list: $ReadOnlyArray<T>,
|
||||
keyFn: (item: T) => string,
|
||||
valFn: (item: T) => V,
|
||||
): ObjMap<V> {
|
||||
return list.reduce(
|
||||
(map, item) => ((map[keyFn(item)] = valFn(item)), map),
|
||||
Object.create(null),
|
||||
);
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a keyed JS object from an array, given a function to produce the keys
|
||||
* and a function to produce the values from each item in the array.
|
||||
*
|
||||
* const phoneBook = [
|
||||
* { name: 'Jon', num: '555-1234' },
|
||||
* { name: 'Jenny', num: '867-5309' }
|
||||
* ]
|
||||
*
|
||||
* // { Jon: '555-1234', Jenny: '867-5309' }
|
||||
* const phonesByName = keyValMap(
|
||||
* phoneBook,
|
||||
* entry => entry.name,
|
||||
* entry => entry.num
|
||||
* )
|
||||
*
|
||||
*/
|
||||
export default function keyValMap(list, keyFn, valFn) {
|
||||
return list.reduce(function (map, item) {
|
||||
return map[keyFn(item)] = valFn(item), map;
|
||||
}, Object.create(null));
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = memoize3;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Memoizes the provided three-argument function.
|
||||
*/
|
||||
function memoize3(fn) {
|
||||
var cache0;
|
||||
|
||||
function memoized(a1, a2, a3) {
|
||||
if (!cache0) {
|
||||
cache0 = new WeakMap();
|
||||
}
|
||||
|
||||
var cache1 = cache0.get(a1);
|
||||
var cache2;
|
||||
|
||||
if (cache1) {
|
||||
cache2 = cache1.get(a2);
|
||||
|
||||
if (cache2) {
|
||||
var cachedValue = cache2.get(a3);
|
||||
|
||||
if (cachedValue !== undefined) {
|
||||
return cachedValue;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cache1 = new WeakMap();
|
||||
cache0.set(a1, cache1);
|
||||
}
|
||||
|
||||
if (!cache2) {
|
||||
cache2 = new WeakMap();
|
||||
cache1.set(a2, cache2);
|
||||
}
|
||||
|
||||
var newValue = fn.apply(this, arguments);
|
||||
cache2.set(a3, newValue);
|
||||
return newValue;
|
||||
}
|
||||
|
||||
return memoized;
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Memoizes the provided three-argument function.
|
||||
*/
|
||||
export default function memoize3<T: (a1: any, a2: any, a3: any) => any>(
|
||||
fn: T,
|
||||
): T {
|
||||
let cache0;
|
||||
function memoized(a1, a2, a3) {
|
||||
if (!cache0) {
|
||||
cache0 = new WeakMap();
|
||||
}
|
||||
let cache1 = cache0.get(a1);
|
||||
let cache2;
|
||||
if (cache1) {
|
||||
cache2 = cache1.get(a2);
|
||||
if (cache2) {
|
||||
const cachedValue = cache2.get(a3);
|
||||
if (cachedValue !== undefined) {
|
||||
return cachedValue;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cache1 = new WeakMap();
|
||||
cache0.set(a1, cache1);
|
||||
}
|
||||
if (!cache2) {
|
||||
cache2 = new WeakMap();
|
||||
cache1.set(a2, cache2);
|
||||
}
|
||||
const newValue = fn.apply(this, arguments);
|
||||
cache2.set(a3, newValue);
|
||||
return newValue;
|
||||
}
|
||||
return (memoized: any);
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Memoizes the provided three-argument function.
|
||||
*/
|
||||
export default function memoize3(fn) {
|
||||
var cache0;
|
||||
|
||||
function memoized(a1, a2, a3) {
|
||||
if (!cache0) {
|
||||
cache0 = new WeakMap();
|
||||
}
|
||||
|
||||
var cache1 = cache0.get(a1);
|
||||
var cache2;
|
||||
|
||||
if (cache1) {
|
||||
cache2 = cache1.get(a2);
|
||||
|
||||
if (cache2) {
|
||||
var cachedValue = cache2.get(a3);
|
||||
|
||||
if (cachedValue !== undefined) {
|
||||
return cachedValue;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cache1 = new WeakMap();
|
||||
cache0.set(a1, cache1);
|
||||
}
|
||||
|
||||
if (!cache2) {
|
||||
cache2 = new WeakMap();
|
||||
cache1.set(a2, cache2);
|
||||
}
|
||||
|
||||
var newValue = fn.apply(this, arguments);
|
||||
cache2.set(a3, newValue);
|
||||
return newValue;
|
||||
}
|
||||
|
||||
return memoized;
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = void 0;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/* eslint-disable no-redeclare */
|
||||
// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221
|
||||
var objectValues = Object.values || function (obj) {
|
||||
return Object.keys(obj).map(function (key) {
|
||||
return obj[key];
|
||||
});
|
||||
};
|
||||
|
||||
var _default = objectValues;
|
||||
exports.default = _default;
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import type { ObjMap } from './ObjMap';
|
||||
|
||||
declare function objectValues<T>(obj: ObjMap<T>): Array<T>;
|
||||
|
||||
/* eslint-disable no-redeclare */
|
||||
// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221
|
||||
const objectValues =
|
||||
Object.values || (obj => Object.keys(obj).map(key => obj[key]));
|
||||
export default objectValues;
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/* eslint-disable no-redeclare */
|
||||
// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221
|
||||
var objectValues = Object.values || function (obj) {
|
||||
return Object.keys(obj).map(function (key) {
|
||||
return obj[key];
|
||||
});
|
||||
};
|
||||
|
||||
export default objectValues;
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = orList;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
var MAX_LENGTH = 5;
|
||||
/**
|
||||
* Given [ A, B, C ] return 'A, B, or C'.
|
||||
*/
|
||||
|
||||
function orList(items) {
|
||||
var selected = items.slice(0, MAX_LENGTH);
|
||||
return selected.reduce(function (list, quoted, index) {
|
||||
return list + (selected.length > 2 ? ', ' : ' ') + (index === selected.length - 1 ? 'or ' : '') + quoted;
|
||||
});
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
const MAX_LENGTH = 5;
|
||||
|
||||
/**
|
||||
* Given [ A, B, C ] return 'A, B, or C'.
|
||||
*/
|
||||
export default function orList(items: $ReadOnlyArray<string>): string {
|
||||
const selected = items.slice(0, MAX_LENGTH);
|
||||
return selected.reduce(
|
||||
(list, quoted, index) =>
|
||||
list +
|
||||
(selected.length > 2 ? ', ' : ' ') +
|
||||
(index === selected.length - 1 ? 'or ' : '') +
|
||||
quoted,
|
||||
);
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
var MAX_LENGTH = 5;
|
||||
/**
|
||||
* Given [ A, B, C ] return 'A, B, or C'.
|
||||
*/
|
||||
|
||||
export default function orList(items) {
|
||||
var selected = items.slice(0, MAX_LENGTH);
|
||||
return selected.reduce(function (list, quoted, index) {
|
||||
return list + (selected.length > 2 ? ', ' : ' ') + (index === selected.length - 1 ? 'or ' : '') + quoted;
|
||||
});
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = promiseForObject;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* This function transforms a JS object `ObjMap<Promise<T>>` into
|
||||
* a `Promise<ObjMap<T>>`
|
||||
*
|
||||
* This is akin to bluebird's `Promise.props`, but implemented only using
|
||||
* `Promise.all` so it will work with any implementation of ES6 promises.
|
||||
*/
|
||||
function promiseForObject(object) {
|
||||
var keys = Object.keys(object);
|
||||
var valuesAndPromises = keys.map(function (name) {
|
||||
return object[name];
|
||||
});
|
||||
return Promise.all(valuesAndPromises).then(function (values) {
|
||||
return values.reduce(function (resolvedObject, value, i) {
|
||||
resolvedObject[keys[i]] = value;
|
||||
return resolvedObject;
|
||||
}, Object.create(null));
|
||||
});
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import type { ObjMap } from './ObjMap';
|
||||
|
||||
/**
|
||||
* This function transforms a JS object `ObjMap<Promise<T>>` into
|
||||
* a `Promise<ObjMap<T>>`
|
||||
*
|
||||
* This is akin to bluebird's `Promise.props`, but implemented only using
|
||||
* `Promise.all` so it will work with any implementation of ES6 promises.
|
||||
*/
|
||||
export default function promiseForObject<T>(
|
||||
object: ObjMap<Promise<T>>,
|
||||
): Promise<ObjMap<T>> {
|
||||
const keys = Object.keys(object);
|
||||
const valuesAndPromises = keys.map(name => object[name]);
|
||||
return Promise.all(valuesAndPromises).then(values =>
|
||||
values.reduce((resolvedObject, value, i) => {
|
||||
resolvedObject[keys[i]] = value;
|
||||
return resolvedObject;
|
||||
}, Object.create(null)),
|
||||
);
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* This function transforms a JS object `ObjMap<Promise<T>>` into
|
||||
* a `Promise<ObjMap<T>>`
|
||||
*
|
||||
* This is akin to bluebird's `Promise.props`, but implemented only using
|
||||
* `Promise.all` so it will work with any implementation of ES6 promises.
|
||||
*/
|
||||
export default function promiseForObject(object) {
|
||||
var keys = Object.keys(object);
|
||||
var valuesAndPromises = keys.map(function (name) {
|
||||
return object[name];
|
||||
});
|
||||
return Promise.all(valuesAndPromises).then(function (values) {
|
||||
return values.reduce(function (resolvedObject, value, i) {
|
||||
resolvedObject[keys[i]] = value;
|
||||
return resolvedObject;
|
||||
}, Object.create(null));
|
||||
});
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = promiseReduce;
|
||||
|
||||
var _isPromise = _interopRequireDefault(require("./isPromise"));
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Similar to Array.prototype.reduce(), however the reducing callback may return
|
||||
* a Promise, in which case reduction will continue after each promise resolves.
|
||||
*
|
||||
* If the callback does not return a Promise, then this function will also not
|
||||
* return a Promise.
|
||||
*/
|
||||
function promiseReduce(values, callback, initialValue) {
|
||||
return values.reduce(function (previous, value) {
|
||||
return (0, _isPromise.default)(previous) ? previous.then(function (resolved) {
|
||||
return callback(resolved, value);
|
||||
}) : callback(previous, value);
|
||||
}, initialValue);
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import isPromise from './isPromise';
|
||||
import type { MaybePromise } from './MaybePromise';
|
||||
|
||||
/**
|
||||
* Similar to Array.prototype.reduce(), however the reducing callback may return
|
||||
* a Promise, in which case reduction will continue after each promise resolves.
|
||||
*
|
||||
* If the callback does not return a Promise, then this function will also not
|
||||
* return a Promise.
|
||||
*/
|
||||
export default function promiseReduce<T, U>(
|
||||
values: $ReadOnlyArray<T>,
|
||||
callback: (U, T) => MaybePromise<U>,
|
||||
initialValue: MaybePromise<U>,
|
||||
): MaybePromise<U> {
|
||||
return values.reduce(
|
||||
(previous, value) =>
|
||||
isPromise(previous)
|
||||
? previous.then(resolved => callback(resolved, value))
|
||||
: callback(previous, value),
|
||||
initialValue,
|
||||
);
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import isPromise from './isPromise';
|
||||
|
||||
/**
|
||||
* Similar to Array.prototype.reduce(), however the reducing callback may return
|
||||
* a Promise, in which case reduction will continue after each promise resolves.
|
||||
*
|
||||
* If the callback does not return a Promise, then this function will also not
|
||||
* return a Promise.
|
||||
*/
|
||||
export default function promiseReduce(values, callback, initialValue) {
|
||||
return values.reduce(function (previous, value) {
|
||||
return isPromise(previous) ? previous.then(function (resolved) {
|
||||
return callback(resolved, value);
|
||||
}) : callback(previous, value);
|
||||
}, initialValue);
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = quotedOrList;
|
||||
|
||||
var _orList = _interopRequireDefault(require("./orList"));
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Given [ A, B, C ] return '"A", "B", or "C"'.
|
||||
*/
|
||||
function quotedOrList(items) {
|
||||
return (0, _orList.default)(items.map(function (item) {
|
||||
return "\"".concat(item, "\"");
|
||||
}));
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import orList from './orList';
|
||||
|
||||
/**
|
||||
* Given [ A, B, C ] return '"A", "B", or "C"'.
|
||||
*/
|
||||
export default function quotedOrList(items: $ReadOnlyArray<string>): string {
|
||||
return orList(items.map(item => `"${item}"`));
|
||||
}
|
||||
Loaded 100 of 2409 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user