Skip to content

Instantly share code, notes, and snippets.

@idkjs
Created June 30, 2017 13:12
Show Gist options
  • Save idkjs/b3b6c89275e3efe64052209584ea4ee4 to your computer and use it in GitHub Desktop.
Save idkjs/b3b6c89275e3efe64052209584ea4ee4 to your computer and use it in GitHub Desktop.
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
const { ApolloClient } = require("apollo-client");
const { createNetworkInterface } = require("apollo-client");
const gql = require("graphql-tag");
require("es6-promise").polyfill();
require("isomorphic-fetch");
const networkInterface = createNetworkInterface({
uri: "https://3qmw47n5v.lp.gql.zone/graphql"
});
// networkInterface.use([{
// applyMiddleware(req, next) {
// // we can apply tokens to the header here
// next();
// }
// }]);
const client = new ApolloClient({
initialState: { apollo: "" },
networkInterface: networkInterface
});
let query = gql`
query ( $limit: Int!, $keyword:String){
businesses(limit:$limit, keyword:$keyword){
name
stars
review_count
}
}
`
function getItems(keyword) {
console.log(keyword)
client.query({query,
variables: {
limit: 5,
keyword: keyword
}
}).then((results) => {
//do something useful
console.log(client.store.getState().apollo);
console.log(results)
return results.data
})
.catch(error => {
console.log("error: ", error);
})
}
window._getItems = getItems;
},{"apollo-client":2,"es6-promise":3,"graphql-tag":10,"isomorphic-fetch":43}],2:[function(require,module,exports){
(function (process){
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('whatwg-fetch'), require('graphql/language/printer'), require('redux'), require('graphql-anywhere'), require('symbol-observable')) :
typeof define === 'function' && define.amd ? define(['exports', 'whatwg-fetch', 'graphql/language/printer', 'redux', 'graphql-anywhere', 'symbol-observable'], factory) :
(factory((global.apollo = global.apollo || {}),null,global.graphql_language_printer,global.redux,global.graphqlAnywhere,global.$$observable));
}(this, (function (exports,whatwgFetch,graphql_language_printer,redux,graphqlAnywhere,$$observable) { 'use strict';
graphqlAnywhere = 'default' in graphqlAnywhere ? graphqlAnywhere['default'] : graphqlAnywhere;
$$observable = 'default' in $$observable ? $$observable['default'] : $$observable;
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
function printRequest(request) {
return __assign({}, request, { query: graphql_language_printer.print(request.query) });
}
var BaseNetworkInterface = (function () {
function BaseNetworkInterface(uri, opts) {
if (opts === void 0) { opts = {}; }
if (!uri) {
throw new Error('A remote endpoint is required for a network layer');
}
if (typeof uri !== 'string') {
throw new Error('Remote endpoint must be a string');
}
this._uri = uri;
this._opts = __assign({}, opts);
this._middlewares = [];
this._afterwares = [];
}
BaseNetworkInterface.prototype.query = function (request) {
return new Promise(function (resolve, reject) {
reject(new Error('BaseNetworkInterface should not be used directly'));
});
};
return BaseNetworkInterface;
}());
var HTTPFetchNetworkInterface = (function (_super) {
__extends(HTTPFetchNetworkInterface, _super);
function HTTPFetchNetworkInterface() {
return _super !== null && _super.apply(this, arguments) || this;
}
HTTPFetchNetworkInterface.prototype.applyMiddlewares = function (requestAndOptions) {
var _this = this;
return new Promise(function (resolve, reject) {
var request = requestAndOptions.request, options = requestAndOptions.options;
var queue = function (funcs, scope) {
var next = function () {
if (funcs.length > 0) {
var f = funcs.shift();
if (f) {
f.applyMiddleware.apply(scope, [{ request: request, options: options }, next]);
}
}
else {
resolve({
request: request,
options: options,
});
}
};
next();
};
queue(_this._middlewares.slice(), _this);
});
};
HTTPFetchNetworkInterface.prototype.applyAfterwares = function (_a) {
var _this = this;
var response = _a.response, options = _a.options;
return new Promise(function (resolve, reject) {
var responseObject = { response: response, options: options };
var queue = function (funcs, scope) {
var next = function () {
if (funcs.length > 0) {
var f = funcs.shift();
if (f) {
f.applyAfterware.apply(scope, [responseObject, next]);
}
}
else {
resolve(responseObject);
}
};
next();
};
queue(_this._afterwares.slice(), _this);
});
};
HTTPFetchNetworkInterface.prototype.fetchFromRemoteEndpoint = function (_a) {
var request = _a.request, options = _a.options;
return fetch(this._uri, __assign({}, this._opts, { body: JSON.stringify(printRequest(request)), method: 'POST' }, options, { headers: __assign({ Accept: '*/*', 'Content-Type': 'application/json' }, options.headers) }));
};
HTTPFetchNetworkInterface.prototype.query = function (request) {
var _this = this;
var options = __assign({}, this._opts);
return this.applyMiddlewares({
request: request,
options: options,
}).then(function (rao) { return _this.fetchFromRemoteEndpoint.call(_this, rao); })
.then(function (response) { return _this.applyAfterwares({
response: response,
options: options,
}); })
.then(function (_a) {
var response = _a.response;
var httpResponse = response;
return httpResponse.json().catch(function (error) {
var httpError = new Error("Network request failed with status " + response.status + " - \"" + response.statusText + "\"");
httpError.response = httpResponse;
httpError.parseError = error;
throw httpError;
});
})
.then(function (payload) {
if (!payload.hasOwnProperty('data') && !payload.hasOwnProperty('errors')) {
throw new Error("Server response was missing for query '" + request.debugName + "'.");
}
else {
return payload;
}
});
};
HTTPFetchNetworkInterface.prototype.use = function (middlewares) {
var _this = this;
middlewares.map(function (middleware) {
if (typeof middleware.applyMiddleware === 'function') {
_this._middlewares.push(middleware);
}
else {
throw new Error('Middleware must implement the applyMiddleware function');
}
});
return this;
};
HTTPFetchNetworkInterface.prototype.useAfter = function (afterwares) {
var _this = this;
afterwares.map(function (afterware) {
if (typeof afterware.applyAfterware === 'function') {
_this._afterwares.push(afterware);
}
else {
throw new Error('Afterware must implement the applyAfterware function');
}
});
return this;
};
return HTTPFetchNetworkInterface;
}(BaseNetworkInterface));
function createNetworkInterface(uriOrInterfaceOpts, secondArgOpts) {
if (secondArgOpts === void 0) { secondArgOpts = {}; }
if (!uriOrInterfaceOpts) {
throw new Error('You must pass an options argument to createNetworkInterface.');
}
var uri;
var opts;
if (typeof uriOrInterfaceOpts === 'string') {
console.warn("Passing the URI as the first argument to createNetworkInterface is deprecated as of Apollo Client 0.5. Please pass it as the \"uri\" property of the network interface options.");
opts = secondArgOpts;
uri = uriOrInterfaceOpts;
}
else {
opts = uriOrInterfaceOpts.opts;
uri = uriOrInterfaceOpts.uri;
}
return new HTTPFetchNetworkInterface(uri, opts);
}
var QueryBatcher = (function () {
function QueryBatcher(_a) {
var batchInterval = _a.batchInterval, batchFetchFunction = _a.batchFetchFunction;
this.queuedRequests = [];
this.queuedRequests = [];
this.batchInterval = batchInterval;
this.batchFetchFunction = batchFetchFunction;
}
QueryBatcher.prototype.enqueueRequest = function (request) {
var fetchRequest = {
request: request,
};
this.queuedRequests.push(fetchRequest);
fetchRequest.promise = new Promise(function (resolve, reject) {
fetchRequest.resolve = resolve;
fetchRequest.reject = reject;
});
if (this.queuedRequests.length === 1) {
this.scheduleQueueConsumption();
}
return fetchRequest.promise;
};
QueryBatcher.prototype.consumeQueue = function () {
var requests = this.queuedRequests.map(function (queuedRequest) { return queuedRequest.request; });
var promises = [];
var resolvers = [];
var rejecters = [];
this.queuedRequests.forEach(function (fetchRequest, index) {
promises.push(fetchRequest.promise);
resolvers.push(fetchRequest.resolve);
rejecters.push(fetchRequest.reject);
});
this.queuedRequests = [];
var batchedPromise = this.batchFetchFunction(requests);
batchedPromise.then(function (results) {
results.forEach(function (result, index) {
resolvers[index](result);
});
}).catch(function (error) {
rejecters.forEach(function (rejecter, index) {
rejecters[index](error);
});
});
return promises;
};
QueryBatcher.prototype.scheduleQueueConsumption = function () {
var _this = this;
setTimeout(function () {
_this.consumeQueue();
}, this.batchInterval);
};
return QueryBatcher;
}());
function assign(target) {
var sources = [];
for (var _i = 1; _i < arguments.length; _i++) {
sources[_i - 1] = arguments[_i];
}
sources.forEach(function (source) {
if (typeof (source) === 'undefined' || source === null) {
return;
}
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
});
return target;
}
var __extends$1 = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign$1 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var HTTPBatchedNetworkInterface = (function (_super) {
__extends$1(HTTPBatchedNetworkInterface, _super);
function HTTPBatchedNetworkInterface(uri, batchInterval, fetchOpts) {
var _this = _super.call(this, uri, fetchOpts) || this;
if (typeof batchInterval !== 'number') {
throw new Error("batchInterval must be a number, got " + batchInterval);
}
_this.batcher = new QueryBatcher({
batchInterval: batchInterval,
batchFetchFunction: _this.batchQuery.bind(_this),
});
return _this;
}
HTTPBatchedNetworkInterface.prototype.query = function (request) {
return this.batcher.enqueueRequest(request);
};
HTTPBatchedNetworkInterface.prototype.batchQuery = function (requests) {
var _this = this;
var options = __assign$1({}, this._opts);
var middlewarePromise = this.applyBatchMiddlewares({
requests: requests,
options: options,
});
return new Promise(function (resolve, reject) {
middlewarePromise.then(function (batchRequestAndOptions) {
return _this.batchedFetchFromRemoteEndpoint(batchRequestAndOptions)
.then(function (result) {
var httpResponse = result;
if (!httpResponse.ok) {
return _this.applyBatchAfterwares({ responses: [httpResponse], options: batchRequestAndOptions })
.then(function () {
var httpError = new Error("Network request failed with status " + httpResponse.status + " - \"" + httpResponse.statusText + "\"");
httpError.response = httpResponse;
throw httpError;
});
}
return result.json();
})
.then(function (responses) {
if (typeof responses.map !== 'function') {
throw new Error('BatchingNetworkInterface: server response is not an array');
}
_this.applyBatchAfterwares({
responses: responses,
options: batchRequestAndOptions.options,
}).then(function (responseAndOptions) {
resolve(responseAndOptions.responses);
}).catch(function (error) {
reject(error);
});
});
}).catch(function (error) {
reject(error);
});
});
};
HTTPBatchedNetworkInterface.prototype.applyBatchMiddlewares = function (_a) {
var _this = this;
var requests = _a.requests, options = _a.options;
return new Promise(function (resolve, reject) {
var queue = function (funcs, scope) {
var next = function () {
if (funcs.length > 0) {
var f = funcs.shift();
if (f) {
f.applyBatchMiddleware.apply(scope, [{ requests: requests, options: options }, next]);
}
}
else {
resolve({
requests: requests,
options: options,
});
}
};
next();
};
queue(_this._middlewares.slice(), _this);
});
};
HTTPBatchedNetworkInterface.prototype.applyBatchAfterwares = function (_a) {
var _this = this;
var responses = _a.responses, options = _a.options;
return new Promise(function (resolve, reject) {
var responseObject = { responses: responses, options: options };
var queue = function (funcs, scope) {
var next = function () {
if (funcs.length > 0) {
var f = funcs.shift();
if (f) {
f.applyBatchAfterware.apply(scope, [responseObject, next]);
}
}
else {
resolve(responseObject);
}
};
next();
};
queue(_this._afterwares.slice(), _this);
});
};
HTTPBatchedNetworkInterface.prototype.use = function (middlewares) {
var _this = this;
middlewares.map(function (middleware) {
if (typeof middleware.applyBatchMiddleware === 'function') {
_this._middlewares.push(middleware);
}
else {
throw new Error('Batch middleware must implement the applyBatchMiddleware function');
}
});
return this;
};
HTTPBatchedNetworkInterface.prototype.useAfter = function (afterwares) {
var _this = this;
afterwares.map(function (afterware) {
if (typeof afterware.applyBatchAfterware === 'function') {
_this._afterwares.push(afterware);
}
else {
throw new Error('Batch afterware must implement the applyBatchAfterware function');
}
});
return this;
};
HTTPBatchedNetworkInterface.prototype.batchedFetchFromRemoteEndpoint = function (batchRequestAndOptions) {
var options = {};
assign(options, batchRequestAndOptions.options);
var printedRequests = batchRequestAndOptions.requests.map(function (request) {
return printRequest(request);
});
return fetch(this._uri, __assign$1({}, this._opts, { body: JSON.stringify(printedRequests), method: 'POST' }, options, { headers: __assign$1({ Accept: '*/*', 'Content-Type': 'application/json' }, options.headers) }));
};
return HTTPBatchedNetworkInterface;
}(BaseNetworkInterface));
function createBatchingNetworkInterface(options) {
if (!options) {
throw new Error('You must pass an options argument to createNetworkInterface.');
}
return new HTTPBatchedNetworkInterface(options.uri, options.batchInterval, options.opts || {});
}
function isQueryResultAction(action) {
return action.type === 'APOLLO_QUERY_RESULT';
}
function isQueryErrorAction(action) {
return action.type === 'APOLLO_QUERY_ERROR';
}
function isQueryInitAction(action) {
return action.type === 'APOLLO_QUERY_INIT';
}
function isQueryResultClientAction(action) {
return action.type === 'APOLLO_QUERY_RESULT_CLIENT';
}
function isQueryStopAction(action) {
return action.type === 'APOLLO_QUERY_STOP';
}
function isMutationInitAction(action) {
return action.type === 'APOLLO_MUTATION_INIT';
}
function isMutationResultAction(action) {
return action.type === 'APOLLO_MUTATION_RESULT';
}
function isMutationErrorAction(action) {
return action.type === 'APOLLO_MUTATION_ERROR';
}
function isUpdateQueryResultAction(action) {
return action.type === 'APOLLO_UPDATE_QUERY_RESULT';
}
function isStoreResetAction(action) {
return action.type === 'APOLLO_STORE_RESET';
}
function isSubscriptionResultAction(action) {
return action.type === 'APOLLO_SUBSCRIPTION_RESULT';
}
function isWriteAction(action) {
return action.type === 'APOLLO_WRITE';
}
function isStringValue(value) {
return value.kind === 'StringValue';
}
function isBooleanValue(value) {
return value.kind === 'BooleanValue';
}
function isIntValue(value) {
return value.kind === 'IntValue';
}
function isFloatValue(value) {
return value.kind === 'FloatValue';
}
function isVariable(value) {
return value.kind === 'Variable';
}
function isObjectValue(value) {
return value.kind === 'ObjectValue';
}
function isListValue(value) {
return value.kind === 'ListValue';
}
function isEnumValue(value) {
return value.kind === 'EnumValue';
}
function valueToObjectRepresentation(argObj, name, value, variables) {
if (isIntValue(value) || isFloatValue(value)) {
argObj[name.value] = Number(value.value);
}
else if (isBooleanValue(value) || isStringValue(value)) {
argObj[name.value] = value.value;
}
else if (isObjectValue(value)) {
var nestedArgObj_1 = {};
value.fields.map(function (obj) { return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables); });
argObj[name.value] = nestedArgObj_1;
}
else if (isVariable(value)) {
var variableValue = (variables || {})[value.name.value];
argObj[name.value] = variableValue;
}
else if (isListValue(value)) {
argObj[name.value] = value.values.map(function (listValue) {
var nestedArgArrayObj = {};
valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables);
return nestedArgArrayObj[name.value];
});
}
else if (isEnumValue(value)) {
argObj[name.value] = value.value;
}
else {
throw new Error("The inline argument \"" + name.value + "\" of kind \"" + value.kind + "\" is not supported.\n Use variables instead of inline arguments to overcome this limitation.");
}
}
function storeKeyNameFromField(field, variables) {
if (field.arguments && field.arguments.length) {
var argObj_1 = {};
field.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(argObj_1, name, value, variables);
});
return storeKeyNameFromFieldNameAndArgs(field.name.value, argObj_1);
}
return field.name.value;
}
function storeKeyNameFromFieldNameAndArgs(fieldName, args) {
if (args) {
var stringifiedArgs = JSON.stringify(args);
return fieldName + "(" + stringifiedArgs + ")";
}
return fieldName;
}
function resultKeyNameFromField(field) {
return field.alias ?
field.alias.value :
field.name.value;
}
function isField(selection) {
return selection.kind === 'Field';
}
function isInlineFragment(selection) {
return selection.kind === 'InlineFragment';
}
function graphQLResultHasError(result) {
return result.errors && result.errors.length;
}
function isIdValue(idObject) {
return (idObject != null &&
typeof idObject === 'object' &&
idObject.type === 'id');
}
function toIdValue(id, generated) {
if (generated === void 0) { generated = false; }
return {
type: 'id',
id: id,
generated: generated,
};
}
function isJsonValue(jsonObject) {
return (jsonObject != null &&
typeof jsonObject === 'object' &&
jsonObject.type === 'json');
}
var __assign$5 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
function getMutationDefinition(doc) {
checkDocument(doc);
var mutationDef = null;
doc.definitions.forEach(function (definition) {
if (definition.kind === 'OperationDefinition'
&& definition.operation === 'mutation') {
mutationDef = definition;
}
});
if (!mutationDef) {
throw new Error('Must contain a mutation definition.');
}
return mutationDef;
}
function checkDocument(doc) {
if (doc.kind !== 'Document') {
throw new Error("Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql");
}
var foundOperation = false;
doc.definitions.forEach(function (definition) {
switch (definition.kind) {
case 'FragmentDefinition':
break;
case 'OperationDefinition':
if (foundOperation) {
throw new Error('Queries must have exactly one operation definition.');
}
foundOperation = true;
break;
default:
throw new Error("Schema type definitions not allowed in queries. Found: \"" + definition.kind + "\"");
}
});
}
function getOperationName(doc) {
var res = null;
doc.definitions.forEach(function (definition) {
if (definition.kind === 'OperationDefinition' && definition.name) {
res = definition.name.value;
}
});
return res;
}
function getFragmentDefinitions(doc) {
var fragmentDefinitions = doc.definitions.filter(function (definition) {
if (definition.kind === 'FragmentDefinition') {
return true;
}
else {
return false;
}
});
return fragmentDefinitions;
}
function getQueryDefinition(doc) {
checkDocument(doc);
var queryDef = null;
doc.definitions.map(function (definition) {
if (definition.kind === 'OperationDefinition'
&& definition.operation === 'query') {
queryDef = definition;
}
});
if (!queryDef) {
throw new Error('Must contain a query definition.');
}
return queryDef;
}
function getOperationDefinition(doc) {
checkDocument(doc);
var opDef = null;
doc.definitions.map(function (definition) {
if (definition.kind === 'OperationDefinition') {
opDef = definition;
}
});
if (!opDef) {
throw new Error('Must contain a query definition.');
}
return opDef;
}
function createFragmentMap(fragments) {
if (fragments === void 0) { fragments = []; }
var symTable = {};
fragments.forEach(function (fragment) {
symTable[fragment.name.value] = fragment;
});
return symTable;
}
function getFragmentQueryDocument(document, fragmentName) {
var actualFragmentName = fragmentName;
var fragments = [];
document.definitions.forEach(function (definition) {
if (definition.kind === 'OperationDefinition') {
throw new Error("Found a " + definition.operation + " operation" + (definition.name ? " named '" + definition.name.value + "'" : '') + ". " +
'No operations are allowed when using a fragment as a query. Only fragments are allowed.');
}
if (definition.kind === 'FragmentDefinition') {
fragments.push(definition);
}
});
if (typeof actualFragmentName === 'undefined') {
if (fragments.length !== 1) {
throw new Error("Found " + fragments.length + " fragments. `fragmentName` must be provided when there is not exactly 1 fragment.");
}
actualFragmentName = fragments[0].name.value;
}
var query = __assign$5({}, document, { definitions: [
{
kind: 'OperationDefinition',
operation: 'query',
selectionSet: {
kind: 'SelectionSet',
selections: [
{
kind: 'FragmentSpread',
name: {
kind: 'Name',
value: actualFragmentName,
},
},
],
},
}
].concat(document.definitions) });
return query;
}
function getDefaultValues(definition) {
if (definition.variableDefinitions && definition.variableDefinitions.length) {
var defaultValues = definition.variableDefinitions
.filter(function (_a) {
var defaultValue = _a.defaultValue;
return defaultValue;
})
.map(function (_a) {
var variable = _a.variable, defaultValue = _a.defaultValue;
var defaultValueObj = {};
valueToObjectRepresentation(defaultValueObj, variable.name, defaultValue);
return defaultValueObj;
});
return assign.apply(void 0, [{}].concat(defaultValues));
}
return {};
}
function shouldInclude(selection, variables) {
if (variables === void 0) { variables = {}; }
if (!selection.directives) {
return true;
}
var res = true;
selection.directives.forEach(function (directive) {
if (directive.name.value !== 'skip' && directive.name.value !== 'include') {
return;
}
var directiveArguments = directive.arguments || [];
var directiveName = directive.name.value;
if (directiveArguments.length !== 1) {
throw new Error("Incorrect number of arguments for the @" + directiveName + " directive.");
}
var ifArgument = directiveArguments[0];
if (!ifArgument.name || ifArgument.name.value !== 'if') {
throw new Error("Invalid argument for the @" + directiveName + " directive.");
}
var ifValue = directiveArguments[0].value;
var evaledValue = false;
if (!ifValue || ifValue.kind !== 'BooleanValue') {
if (ifValue.kind !== 'Variable') {
throw new Error("Argument for the @" + directiveName + " directive must be a variable or a bool ean value.");
}
else {
evaledValue = variables[ifValue.name.value];
if (evaledValue === undefined) {
throw new Error("Invalid variable referenced in @" + directiveName + " directive.");
}
}
}
else {
evaledValue = ifValue.value;
}
if (directiveName === 'skip') {
evaledValue = !evaledValue;
}
if (!evaledValue) {
res = false;
}
});
return res;
}
function getEnv() {
if (typeof process !== 'undefined' && process.env.NODE_ENV) {
return process.env.NODE_ENV;
}
return 'development';
}
function isEnv(env) {
return getEnv() === env;
}
function isProduction() {
return isEnv('production') === true;
}
function isDevelopment() {
return isEnv('development') === true;
}
function isTest() {
return isEnv('test') === true;
}
var __extends$2 = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign$4 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var WriteError = (function (_super) {
__extends$2(WriteError, _super);
function WriteError() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = 'WriteError';
return _this;
}
return WriteError;
}(Error));
function enhanceErrorWithDocument(error, document) {
var enhancedError = new WriteError("Error writing result to store for query " + (document.loc && document.loc.source && document.loc.source.body));
enhancedError.message += '/n' + error.message;
enhancedError.stack = error.stack;
return enhancedError;
}
function writeQueryToStore(_a) {
var result = _a.result, query = _a.query, _b = _a.store, store = _b === void 0 ? {} : _b, variables = _a.variables, dataIdFromObject = _a.dataIdFromObject, _c = _a.fragmentMap, fragmentMap = _c === void 0 ? {} : _c, fragmentMatcherFunction = _a.fragmentMatcherFunction;
var queryDefinition = getQueryDefinition(query);
variables = assign({}, getDefaultValues(queryDefinition), variables);
try {
return writeSelectionSetToStore({
dataId: 'ROOT_QUERY',
result: result,
selectionSet: queryDefinition.selectionSet,
context: {
store: store,
variables: variables,
dataIdFromObject: dataIdFromObject,
fragmentMap: fragmentMap,
fragmentMatcherFunction: fragmentMatcherFunction,
},
});
}
catch (e) {
throw enhanceErrorWithDocument(e, query);
}
}
function writeResultToStore(_a) {
var dataId = _a.dataId, result = _a.result, document = _a.document, _b = _a.store, store = _b === void 0 ? {} : _b, variables = _a.variables, dataIdFromObject = _a.dataIdFromObject, fragmentMatcherFunction = _a.fragmentMatcherFunction;
var operationDefinition = getOperationDefinition(document);
var selectionSet = operationDefinition.selectionSet;
var fragmentMap = createFragmentMap(getFragmentDefinitions(document));
variables = assign({}, getDefaultValues(operationDefinition), variables);
try {
return writeSelectionSetToStore({
result: result,
dataId: dataId,
selectionSet: selectionSet,
context: {
store: store,
variables: variables,
dataIdFromObject: dataIdFromObject,
fragmentMap: fragmentMap,
fragmentMatcherFunction: fragmentMatcherFunction,
},
});
}
catch (e) {
throw enhanceErrorWithDocument(e, document);
}
}
function writeSelectionSetToStore(_a) {
var result = _a.result, dataId = _a.dataId, selectionSet = _a.selectionSet, context = _a.context;
var variables = context.variables, store = context.store, dataIdFromObject = context.dataIdFromObject, fragmentMap = context.fragmentMap;
selectionSet.selections.forEach(function (selection) {
var included = shouldInclude(selection, variables);
if (isField(selection)) {
var resultFieldKey = resultKeyNameFromField(selection);
var value = result[resultFieldKey];
if (included) {
if (typeof value !== 'undefined') {
writeFieldToStore({
dataId: dataId,
value: value,
field: selection,
context: context,
});
}
else {
if (context.fragmentMatcherFunction) {
if (!isProduction()) {
console.warn("Missing field " + resultFieldKey);
}
}
}
}
}
else {
var fragment = void 0;
if (isInlineFragment(selection)) {
fragment = selection;
}
else {
fragment = (fragmentMap || {})[selection.name.value];
if (!fragment) {
throw new Error("No fragment named " + selection.name.value + ".");
}
}
var matches = true;
if (context.fragmentMatcherFunction && fragment.typeCondition) {
var idValue = { type: 'id', id: 'self', generated: false };
var fakeContext = {
store: { 'self': result },
returnPartialData: false,
hasMissingField: false,
customResolvers: {},
};
matches = context.fragmentMatcherFunction(idValue, fragment.typeCondition.name.value, fakeContext);
if (fakeContext.returnPartialData) {
console.error('WARNING: heuristic fragment matching going on!');
}
}
if (included && matches) {
writeSelectionSetToStore({
result: result,
selectionSet: fragment.selectionSet,
dataId: dataId,
context: context,
});
}
}
});
return store;
}
function isGeneratedId(id) {
return (id[0] === '$');
}
function mergeWithGenerated(generatedKey, realKey, cache) {
var generated = cache[generatedKey];
var real = cache[realKey];
Object.keys(generated).forEach(function (key) {
var value = generated[key];
var realValue = real[key];
if (isIdValue(value)
&& isGeneratedId(value.id)
&& isIdValue(realValue)) {
mergeWithGenerated(value.id, realValue.id, cache);
}
delete cache[generatedKey];
cache[realKey] = __assign$4({}, generated, real);
});
}
function writeFieldToStore(_a) {
var field = _a.field, value = _a.value, dataId = _a.dataId, context = _a.context;
var variables = context.variables, dataIdFromObject = context.dataIdFromObject, store = context.store, fragmentMap = context.fragmentMap;
var storeValue;
var storeFieldName = storeKeyNameFromField(field, variables);
var shouldMerge = false;
var generatedKey = '';
if (!field.selectionSet || value === null) {
storeValue =
value != null && typeof value === 'object'
? { type: 'json', json: value }
: value;
}
else if (Array.isArray(value)) {
var generatedId = dataId + "." + storeFieldName;
storeValue = processArrayValue(value, generatedId, field.selectionSet, context);
}
else {
var valueDataId = dataId + "." + storeFieldName;
var generated = true;
if (!isGeneratedId(valueDataId)) {
valueDataId = '$' + valueDataId;
}
if (dataIdFromObject) {
var semanticId = dataIdFromObject(value);
if (semanticId && isGeneratedId(semanticId)) {
throw new Error('IDs returned by dataIdFromObject cannot begin with the "$" character.');
}
if (semanticId) {
valueDataId = semanticId;
generated = false;
}
}
writeSelectionSetToStore({
dataId: valueDataId,
result: value,
selectionSet: field.selectionSet,
context: context,
});
storeValue = {
type: 'id',
id: valueDataId,
generated: generated,
};
if (store[dataId] && store[dataId][storeFieldName] !== storeValue) {
var escapedId = store[dataId][storeFieldName];
if (isIdValue(storeValue) && storeValue.generated
&& isIdValue(escapedId) && !escapedId.generated) {
throw new Error("Store error: the application attempted to write an object with no provided id" +
(" but the store already contains an id of " + escapedId.id + " for this object."));
}
if (isIdValue(escapedId) && escapedId.generated) {
generatedKey = escapedId.id;
shouldMerge = true;
}
}
}
var newStoreObj = __assign$4({}, store[dataId], (_b = {}, _b[storeFieldName] = storeValue, _b));
if (shouldMerge) {
mergeWithGenerated(generatedKey, storeValue.id, store);
}
if (!store[dataId] || storeValue !== store[dataId][storeFieldName]) {
store[dataId] = newStoreObj;
}
var _b;
}
function processArrayValue(value, generatedId, selectionSet, context) {
return value.map(function (item, index) {
if (item === null) {
return null;
}
var itemDataId = generatedId + "." + index;
if (Array.isArray(item)) {
return processArrayValue(item, itemDataId, selectionSet, context);
}
var generated = true;
if (context.dataIdFromObject) {
var semanticId = context.dataIdFromObject(item);
if (semanticId) {
itemDataId = semanticId;
generated = false;
}
}
writeSelectionSetToStore({
dataId: itemDataId,
result: item,
selectionSet: selectionSet,
context: context,
});
var idStoreValue = {
type: 'id',
id: itemDataId,
generated: generated,
};
return idStoreValue;
});
}
var __assign$7 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var optimisticDefaultState = [];
function getDataWithOptimisticResults(store) {
if (store.optimistic.length === 0) {
return store.data;
}
var patches = store.optimistic.map(function (opt) { return opt.data; });
return assign.apply(void 0, [{}, store.data].concat(patches));
}
function optimistic(previousState, action, store, config) {
if (previousState === void 0) { previousState = optimisticDefaultState; }
if (isMutationInitAction(action) && action.optimisticResponse) {
var optimisticResponse = void 0;
if (typeof action.optimisticResponse === 'function') {
optimisticResponse = action.optimisticResponse(action.variables);
}
else {
optimisticResponse = action.optimisticResponse;
}
var fakeMutationResultAction = {
type: 'APOLLO_MUTATION_RESULT',
result: { data: optimisticResponse },
document: action.mutation,
operationName: action.operationName,
variables: action.variables,
mutationId: action.mutationId,
extraReducers: action.extraReducers,
updateQueries: action.updateQueries,
update: action.update,
};
var optimisticData = getDataWithOptimisticResults(__assign$7({}, store, { optimistic: previousState }));
var patch = getOptimisticDataPatch(optimisticData, fakeMutationResultAction, store.queries, store.mutations, config);
var optimisticState = {
action: fakeMutationResultAction,
data: patch,
mutationId: action.mutationId,
};
var newState = previousState.concat([optimisticState]);
return newState;
}
else if ((isMutationErrorAction(action) || isMutationResultAction(action))
&& previousState.some(function (change) { return change.mutationId === action.mutationId; })) {
return rollbackOptimisticData(function (change) { return change.mutationId === action.mutationId; }, previousState, store, config);
}
return previousState;
}
function getOptimisticDataPatch(previousData, optimisticAction, queries, mutations, config) {
var optimisticData = data(previousData, optimisticAction, queries, mutations, config);
var patch = {};
Object.keys(optimisticData).forEach(function (key) {
if (optimisticData[key] !== previousData[key]) {
patch[key] = optimisticData[key];
}
});
return patch;
}
function rollbackOptimisticData(filterFn, previousState, store, config) {
if (previousState === void 0) { previousState = optimisticDefaultState; }
var optimisticData = assign({}, store.data);
var newState = previousState
.filter(function (item) { return !filterFn(item); })
.map(function (change) {
var patch = getOptimisticDataPatch(optimisticData, change.action, store.queries, store.mutations, config);
assign(optimisticData, patch);
return __assign$7({}, change, { data: patch });
});
return newState;
}
function isEqual(a, b) {
if (a === b) {
return true;
}
if (a != null && typeof a === 'object' && b != null && typeof b === 'object') {
for (var key in a) {
if (a.hasOwnProperty(key)) {
if (!b.hasOwnProperty(key)) {
return false;
}
if (!isEqual(a[key], b[key])) {
return false;
}
}
}
for (var key in b) {
if (!a.hasOwnProperty(key)) {
return false;
}
}
return true;
}
return false;
}
var __assign$8 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var ID_KEY = typeof Symbol !== 'undefined' ? Symbol('id') : '@@id';
function readQueryFromStore(options) {
var optsPatch = { returnPartialData: false };
return diffQueryAgainstStore(__assign$8({}, options, optsPatch)).result;
}
var readStoreResolver = function (fieldName, idValue, args, context, _a) {
var resultKey = _a.resultKey;
assertIdValue(idValue);
var objId = idValue.id;
var obj = context.store[objId];
var storeKeyName = storeKeyNameFromFieldNameAndArgs(fieldName, args);
var fieldValue = (obj || {})[storeKeyName];
if (typeof fieldValue === 'undefined') {
if (context.customResolvers && obj && (obj.__typename || objId === 'ROOT_QUERY')) {
var typename = obj.__typename || 'Query';
var type = context.customResolvers[typename];
if (type) {
var resolver = type[fieldName];
if (resolver) {
return resolver(obj, args);
}
}
}
if (!context.returnPartialData) {
throw new Error("Can't find field " + storeKeyName + " on object (" + objId + ") " + JSON.stringify(obj, null, 2) + ".");
}
context.hasMissingField = true;
return fieldValue;
}
if (isJsonValue(fieldValue)) {
if (idValue.previousResult && isEqual(idValue.previousResult[resultKey], fieldValue.json)) {
return idValue.previousResult[resultKey];
}
return fieldValue.json;
}
if (idValue.previousResult) {
fieldValue = addPreviousResultToIdValues(fieldValue, idValue.previousResult[resultKey]);
}
return fieldValue;
};
function diffQueryAgainstStore(_a) {
var store = _a.store, query = _a.query, variables = _a.variables, previousResult = _a.previousResult, _b = _a.returnPartialData, returnPartialData = _b === void 0 ? true : _b, _c = _a.rootId, rootId = _c === void 0 ? 'ROOT_QUERY' : _c, fragmentMatcherFunction = _a.fragmentMatcherFunction, config = _a.config;
var queryDefinition = getQueryDefinition(query);
variables = assign({}, getDefaultValues(queryDefinition), variables);
var context = {
store: store,
returnPartialData: returnPartialData,
customResolvers: (config && config.customResolvers) || {},
hasMissingField: false,
};
var rootIdValue = {
type: 'id',
id: rootId,
previousResult: previousResult,
};
var result = graphqlAnywhere(readStoreResolver, query, rootIdValue, context, variables, {
fragmentMatcher: fragmentMatcherFunction,
resultMapper: resultMapper,
});
return {
result: result,
isMissing: context.hasMissingField,
};
}
function assertIdValue(idValue) {
if (!isIdValue(idValue)) {
throw new Error("Encountered a sub-selection on the query, but the store doesn't have an object reference. This should never happen during normal use unless you have custom code that is directly manipulating the store; please file an issue.");
}
}
function addPreviousResultToIdValues(value, previousResult) {
if (isIdValue(value)) {
return __assign$8({}, value, { previousResult: previousResult });
}
else if (Array.isArray(value)) {
var idToPreviousResult_1 = {};
if (Array.isArray(previousResult)) {
previousResult.forEach(function (item) {
if (item && item[ID_KEY]) {
idToPreviousResult_1[item[ID_KEY]] = item;
}
});
}
return value.map(function (item, i) {
var itemPreviousResult = previousResult && previousResult[i];
if (isIdValue(item)) {
itemPreviousResult = idToPreviousResult_1[item.id] || itemPreviousResult;
}
return addPreviousResultToIdValues(item, itemPreviousResult);
});
}
return value;
}
function resultMapper(resultFields, idValue) {
if (idValue.previousResult) {
var currentResultKeys_1 = Object.keys(resultFields);
var sameAsPreviousResult = Object.keys(idValue.previousResult)
.reduce(function (sameKeys, key) { return sameKeys && currentResultKeys_1.indexOf(key) > -1; }, true) &&
currentResultKeys_1.reduce(function (same, key) { return (same && areNestedArrayItemsStrictlyEqual(resultFields[key], idValue.previousResult[key])); }, true);
if (sameAsPreviousResult) {
return idValue.previousResult;
}
}
Object.defineProperty(resultFields, ID_KEY, {
enumerable: false,
configurable: false,
writable: false,
value: idValue.id,
});
return resultFields;
}
function areNestedArrayItemsStrictlyEqual(a, b) {
if (a === b) {
return true;
}
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {
return false;
}
return a.reduce(function (same, item, i) { return same && areNestedArrayItemsStrictlyEqual(item, b[i]); }, true);
}
function cloneDeep(value) {
if (Array.isArray(value)) {
return value.map(function (item) { return cloneDeep(item); });
}
if (value !== null && typeof value === 'object') {
var nextValue = {};
for (var key in value) {
if (value.hasOwnProperty(key)) {
nextValue[key] = cloneDeep(value[key]);
}
}
return nextValue;
}
return value;
}
var TYPENAME_FIELD = {
kind: 'Field',
name: {
kind: 'Name',
value: '__typename',
},
};
function addTypenameToSelectionSet(selectionSet, isRoot) {
if (isRoot === void 0) { isRoot = false; }
if (selectionSet.selections) {
if (!isRoot) {
var alreadyHasThisField = selectionSet.selections.some(function (selection) {
return selection.kind === 'Field' && selection.name.value === '__typename';
});
if (!alreadyHasThisField) {
selectionSet.selections.push(TYPENAME_FIELD);
}
}
selectionSet.selections.forEach(function (selection) {
if (selection.kind === 'Field') {
if (selection.name.value.lastIndexOf('__', 0) !== 0 && selection.selectionSet) {
addTypenameToSelectionSet(selection.selectionSet);
}
}
else if (selection.kind === 'InlineFragment') {
if (selection.selectionSet) {
addTypenameToSelectionSet(selection.selectionSet);
}
}
});
}
}
function addTypenameToDocument(doc) {
checkDocument(doc);
var docClone = cloneDeep(doc);
docClone.definitions.forEach(function (definition) {
var isRoot = definition.kind === 'OperationDefinition';
addTypenameToSelectionSet(definition.selectionSet, isRoot);
});
return docClone;
}
var __assign$6 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var ReduxDataProxy = (function () {
function ReduxDataProxy(store, reduxRootSelector, fragmentMatcher, reducerConfig) {
this.store = store;
this.reduxRootSelector = reduxRootSelector;
this.reducerConfig = reducerConfig;
this.fragmentMatcher = fragmentMatcher;
}
ReduxDataProxy.prototype.readQuery = function (_a) {
var query = _a.query, variables = _a.variables;
if (this.reducerConfig.addTypename) {
query = addTypenameToDocument(query);
}
return readQueryFromStore({
rootId: 'ROOT_QUERY',
store: getDataWithOptimisticResults(this.reduxRootSelector(this.store.getState())),
query: query,
variables: variables,
fragmentMatcherFunction: this.fragmentMatcher.match,
config: this.reducerConfig,
});
};
ReduxDataProxy.prototype.readFragment = function (_a) {
var id = _a.id, fragment = _a.fragment, fragmentName = _a.fragmentName, variables = _a.variables;
var query = getFragmentQueryDocument(fragment, fragmentName);
var data = getDataWithOptimisticResults(this.reduxRootSelector(this.store.getState()));
if (typeof data[id] === 'undefined') {
return null;
}
if (this.reducerConfig.addTypename) {
query = addTypenameToDocument(query);
}
return readQueryFromStore({
rootId: id,
store: data,
query: query,
variables: variables,
fragmentMatcherFunction: this.fragmentMatcher.match,
config: this.reducerConfig,
});
};
ReduxDataProxy.prototype.writeQuery = function (_a) {
var data = _a.data, query = _a.query, variables = _a.variables;
if (this.reducerConfig.addTypename) {
query = addTypenameToDocument(query);
}
this.store.dispatch({
type: 'APOLLO_WRITE',
writes: [{
rootId: 'ROOT_QUERY',
result: data,
document: query,
operationName: getOperationName(query),
variables: variables || {},
}],
});
};
ReduxDataProxy.prototype.writeFragment = function (_a) {
var data = _a.data, id = _a.id, fragment = _a.fragment, fragmentName = _a.fragmentName, variables = _a.variables;
var document = getFragmentQueryDocument(fragment, fragmentName);
if (this.reducerConfig.addTypename) {
document = addTypenameToDocument(document);
}
this.store.dispatch({
type: 'APOLLO_WRITE',
writes: [{
rootId: id,
result: data,
document: document,
operationName: getOperationName(document),
variables: variables || {},
}],
});
};
return ReduxDataProxy;
}());
var TransactionDataProxy = (function () {
function TransactionDataProxy(data, reducerConfig) {
this.data = __assign$6({}, data);
this.reducerConfig = reducerConfig;
this.writes = [];
this.isFinished = false;
}
TransactionDataProxy.prototype.finish = function () {
this.assertNotFinished();
var writes = this.writes;
this.writes = [];
this.isFinished = true;
return writes;
};
TransactionDataProxy.prototype.readQuery = function (_a) {
var query = _a.query, variables = _a.variables;
this.assertNotFinished();
if (this.reducerConfig.addTypename) {
query = addTypenameToDocument(query);
}
return readQueryFromStore({
rootId: 'ROOT_QUERY',
store: this.data,
query: query,
variables: variables,
config: this.reducerConfig,
fragmentMatcherFunction: this.reducerConfig.fragmentMatcher,
});
};
TransactionDataProxy.prototype.readFragment = function (_a) {
var id = _a.id, fragment = _a.fragment, fragmentName = _a.fragmentName, variables = _a.variables;
this.assertNotFinished();
if (!fragment) {
throw new Error('fragment option is required. Please pass a GraphQL fragment to readFragment.');
}
var data = this.data;
var query = getFragmentQueryDocument(fragment, fragmentName);
if (this.reducerConfig.addTypename) {
query = addTypenameToDocument(query);
}
if (typeof data[id] === 'undefined') {
return null;
}
return readQueryFromStore({
rootId: id,
store: data,
query: query,
variables: variables,
config: this.reducerConfig,
fragmentMatcherFunction: this.reducerConfig.fragmentMatcher,
});
};
TransactionDataProxy.prototype.writeQuery = function (_a) {
var data = _a.data, query = _a.query, variables = _a.variables;
this.assertNotFinished();
if (this.reducerConfig.addTypename) {
query = addTypenameToDocument(query);
}
this.applyWrite({
rootId: 'ROOT_QUERY',
result: data,
document: query,
operationName: getOperationName(query),
variables: variables || {},
});
};
TransactionDataProxy.prototype.writeFragment = function (_a) {
var data = _a.data, id = _a.id, fragment = _a.fragment, fragmentName = _a.fragmentName, variables = _a.variables;
this.assertNotFinished();
if (!fragment) {
throw new Error('fragment option is required. Please pass a GraphQL fragment to writeFragment.');
}
var query = getFragmentQueryDocument(fragment, fragmentName);
if (this.reducerConfig.addTypename) {
query = addTypenameToDocument(query);
}
this.applyWrite({
rootId: id,
result: data,
document: query,
operationName: getOperationName(query),
variables: variables || {},
});
};
TransactionDataProxy.prototype.assertNotFinished = function () {
if (this.isFinished) {
throw new Error('Cannot call transaction methods after the transaction has finished.');
}
};
TransactionDataProxy.prototype.applyWrite = function (write) {
writeResultToStore({
result: write.result,
dataId: write.rootId,
document: write.document,
variables: write.variables,
store: this.data,
dataIdFromObject: this.reducerConfig.dataIdFromObject || (function () { return null; }),
fragmentMatcherFunction: this.reducerConfig.fragmentMatcher,
});
this.writes.push(write);
};
return TransactionDataProxy;
}());
var __assign$9 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
function replaceQueryResults(state, _a, config) {
var variables = _a.variables, document = _a.document, newResult = _a.newResult;
var clonedState = __assign$9({}, state);
return writeResultToStore({
result: newResult,
dataId: 'ROOT_QUERY',
variables: variables,
document: document,
store: clonedState,
dataIdFromObject: config.dataIdFromObject,
fragmentMatcherFunction: config.fragmentMatcher,
});
}
function tryFunctionOrLogError(f) {
try {
return f();
}
catch (e) {
if (console.error) {
console.error(e);
}
}
}
var __assign$3 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
function data(previousState, action, queries, mutations, config) {
if (previousState === void 0) { previousState = {}; }
var constAction = action;
if (isQueryResultAction(action)) {
if (!queries[action.queryId]) {
return previousState;
}
if (action.requestId < queries[action.queryId].lastRequestId) {
return previousState;
}
if (!graphQLResultHasError(action.result)) {
var queryStoreValue = queries[action.queryId];
var clonedState = __assign$3({}, previousState);
var newState_1 = writeResultToStore({
result: action.result.data,
dataId: 'ROOT_QUERY',
document: action.document,
variables: queryStoreValue.variables,
store: clonedState,
dataIdFromObject: config.dataIdFromObject,
fragmentMatcherFunction: config.fragmentMatcher,
});
if (action.extraReducers) {
action.extraReducers.forEach(function (reducer) {
newState_1 = reducer(newState_1, constAction);
});
}
return newState_1;
}
}
else if (isSubscriptionResultAction(action)) {
if (!graphQLResultHasError(action.result)) {
var clonedState = __assign$3({}, previousState);
var newState_2 = writeResultToStore({
result: action.result.data,
dataId: 'ROOT_SUBSCRIPTION',
document: action.document,
variables: action.variables,
store: clonedState,
dataIdFromObject: config.dataIdFromObject,
fragmentMatcherFunction: config.fragmentMatcher,
});
if (action.extraReducers) {
action.extraReducers.forEach(function (reducer) {
newState_2 = reducer(newState_2, constAction);
});
}
return newState_2;
}
}
else if (isMutationResultAction(constAction)) {
if (!constAction.result.errors) {
var queryStoreValue = mutations[constAction.mutationId];
var clonedState = __assign$3({}, previousState);
var newState_3 = writeResultToStore({
result: constAction.result.data,
dataId: 'ROOT_MUTATION',
document: constAction.document,
variables: queryStoreValue.variables,
store: clonedState,
dataIdFromObject: config.dataIdFromObject,
fragmentMatcherFunction: config.fragmentMatcher,
});
var updateQueries_1 = constAction.updateQueries;
if (updateQueries_1) {
Object.keys(updateQueries_1).forEach(function (queryId) {
var query = queries[queryId];
if (!query) {
return;
}
var _a = diffQueryAgainstStore({
store: previousState,
query: query.document,
variables: query.variables,
returnPartialData: true,
fragmentMatcherFunction: config.fragmentMatcher,
config: config,
}), currentQueryResult = _a.result, isMissing = _a.isMissing;
if (isMissing) {
return;
}
var reducer = updateQueries_1[queryId];
var nextQueryResult = tryFunctionOrLogError(function () { return reducer(currentQueryResult, {
mutationResult: constAction.result,
queryName: getOperationName(query.document),
queryVariables: query.variables,
}); });
if (nextQueryResult) {
newState_3 = writeResultToStore({
result: nextQueryResult,
dataId: 'ROOT_QUERY',
document: query.document,
variables: query.variables,
store: newState_3,
dataIdFromObject: config.dataIdFromObject,
fragmentMatcherFunction: config.fragmentMatcher,
});
}
});
}
if (constAction.update) {
var update_1 = constAction.update;
var proxy_1 = new TransactionDataProxy(newState_3, config);
tryFunctionOrLogError(function () { return update_1(proxy_1, constAction.result); });
var writes = proxy_1.finish();
newState_3 = data(newState_3, { type: 'APOLLO_WRITE', writes: writes }, queries, mutations, config);
}
if (constAction.extraReducers) {
constAction.extraReducers.forEach(function (reducer) {
newState_3 = reducer(newState_3, constAction);
});
}
return newState_3;
}
}
else if (isUpdateQueryResultAction(constAction)) {
return replaceQueryResults(previousState, constAction, config);
}
else if (isStoreResetAction(action)) {
return {};
}
else if (isWriteAction(action)) {
return action.writes.reduce(function (currentState, write) { return writeResultToStore({
result: write.result,
dataId: write.rootId,
document: write.document,
variables: write.variables,
store: currentState,
dataIdFromObject: config.dataIdFromObject,
fragmentMatcherFunction: config.fragmentMatcher,
}); }, __assign$3({}, previousState));
}
return previousState;
}
(function (NetworkStatus) {
NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
NetworkStatus[NetworkStatus["error"] = 8] = "error";
})(exports.NetworkStatus || (exports.NetworkStatus = {}));
function isNetworkRequestInFlight(networkStatus) {
return networkStatus < 7;
}
var __assign$10 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
function queries(previousState, action) {
if (previousState === void 0) { previousState = {}; }
if (isQueryInitAction(action)) {
var newState = __assign$10({}, previousState);
var previousQuery = previousState[action.queryId];
if (previousQuery && previousQuery.queryString !== action.queryString) {
throw new Error('Internal Error: may not update existing query string in store');
}
var isSetVariables = false;
var previousVariables = null;
if (action.storePreviousVariables &&
previousQuery &&
previousQuery.networkStatus !== exports.NetworkStatus.loading) {
if (!isEqual(previousQuery.variables, action.variables)) {
isSetVariables = true;
previousVariables = previousQuery.variables;
}
}
var newNetworkStatus = exports.NetworkStatus.loading;
if (isSetVariables) {
newNetworkStatus = exports.NetworkStatus.setVariables;
}
else if (action.isPoll) {
newNetworkStatus = exports.NetworkStatus.poll;
}
else if (action.isRefetch) {
newNetworkStatus = exports.NetworkStatus.refetch;
}
else if (action.isPoll) {
newNetworkStatus = exports.NetworkStatus.poll;
}
newState[action.queryId] = {
queryString: action.queryString,
document: action.document,
variables: action.variables,
previousVariables: previousVariables,
networkError: null,
graphQLErrors: [],
networkStatus: newNetworkStatus,
lastRequestId: action.requestId,
metadata: action.metadata,
};
if (typeof action.fetchMoreForQueryId === 'string') {
newState[action.fetchMoreForQueryId] = __assign$10({}, previousState[action.fetchMoreForQueryId], { networkStatus: exports.NetworkStatus.fetchMore });
}
return newState;
}
else if (isQueryResultAction(action)) {
if (!previousState[action.queryId]) {
return previousState;
}
if (action.requestId < previousState[action.queryId].lastRequestId) {
return previousState;
}
var newState = __assign$10({}, previousState);
var resultHasGraphQLErrors = graphQLResultHasError(action.result);
newState[action.queryId] = __assign$10({}, previousState[action.queryId], { networkError: null, graphQLErrors: resultHasGraphQLErrors ? action.result.errors : [], previousVariables: null, networkStatus: exports.NetworkStatus.ready });
if (typeof action.fetchMoreForQueryId === 'string') {
newState[action.fetchMoreForQueryId] = __assign$10({}, previousState[action.fetchMoreForQueryId], { networkStatus: exports.NetworkStatus.ready });
}
return newState;
}
else if (isQueryErrorAction(action)) {
if (!previousState[action.queryId]) {
return previousState;
}
if (action.requestId < previousState[action.queryId].lastRequestId) {
return previousState;
}
var newState = __assign$10({}, previousState);
newState[action.queryId] = __assign$10({}, previousState[action.queryId], { networkError: action.error, networkStatus: exports.NetworkStatus.error });
if (typeof action.fetchMoreForQueryId === 'string') {
newState[action.fetchMoreForQueryId] = __assign$10({}, previousState[action.fetchMoreForQueryId], { networkError: action.error, networkStatus: exports.NetworkStatus.error });
}
return newState;
}
else if (isQueryResultClientAction(action)) {
if (!previousState[action.queryId]) {
return previousState;
}
var newState = __assign$10({}, previousState);
newState[action.queryId] = __assign$10({}, previousState[action.queryId], { networkError: null, previousVariables: null, networkStatus: action.complete ? exports.NetworkStatus.ready : exports.NetworkStatus.loading });
return newState;
}
else if (isQueryStopAction(action)) {
var newState = __assign$10({}, previousState);
delete newState[action.queryId];
return newState;
}
else if (isStoreResetAction(action)) {
return resetQueryState(previousState, action);
}
return previousState;
}
function resetQueryState(state, action) {
var observableQueryIds = action.observableQueryIds;
var newQueries = Object.keys(state).filter(function (queryId) {
return (observableQueryIds.indexOf(queryId) > -1);
}).reduce(function (res, key) {
res[key] = __assign$10({}, state[key], { networkStatus: exports.NetworkStatus.loading });
return res;
}, {});
return newQueries;
}
var __assign$11 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
function mutations(previousState, action) {
if (previousState === void 0) { previousState = {}; }
if (isMutationInitAction(action)) {
var newState = __assign$11({}, previousState);
newState[action.mutationId] = {
mutationString: action.mutationString,
variables: action.variables,
loading: true,
error: null,
};
return newState;
}
else if (isMutationResultAction(action)) {
var newState = __assign$11({}, previousState);
newState[action.mutationId] = __assign$11({}, previousState[action.mutationId], { loading: false, error: null });
return newState;
}
else if (isMutationErrorAction(action)) {
var newState = __assign$11({}, previousState);
newState[action.mutationId] = __assign$11({}, previousState[action.mutationId], { loading: false, error: action.error });
}
else if (isStoreResetAction(action)) {
return {};
}
return previousState;
}
var __assign$2 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var crashReporter = function (store) { return function (next) { return function (action) {
try {
return next(action);
}
catch (err) {
console.error('Caught an exception!', err);
console.error(err.stack);
throw err;
}
}; }; };
var createReducerError = function (error, action) {
var reducerError = { error: error };
if (isQueryResultAction(action)) {
reducerError.queryId = action.queryId;
}
else if (isSubscriptionResultAction(action)) {
reducerError.subscriptionId = action.subscriptionId;
}
else if (isMutationResultAction(action)) {
reducerError.mutationId = action.mutationId;
}
return reducerError;
};
function createApolloReducer(config) {
return function apolloReducer(state, action) {
if (state === void 0) { state = {}; }
try {
var newState = {
queries: queries(state.queries, action),
mutations: mutations(state.mutations, action),
data: data(state.data, action, state.queries, state.mutations, config),
optimistic: [],
reducerError: null,
};
newState.optimistic = optimistic(state.optimistic, action, newState, config);
if (state.data === newState.data &&
state.mutations === newState.mutations &&
state.queries === newState.queries &&
state.optimistic === newState.optimistic &&
state.reducerError === newState.reducerError) {
return state;
}
return newState;
}
catch (reducerError) {
return __assign$2({}, state, { reducerError: createReducerError(reducerError, action) });
}
};
}
function createApolloStore(_a) {
var _b = _a === void 0 ? {} : _a, _c = _b.reduxRootKey, reduxRootKey = _c === void 0 ? 'apollo' : _c, initialState = _b.initialState, _d = _b.config, config = _d === void 0 ? {} : _d, _e = _b.reportCrashes, reportCrashes = _e === void 0 ? true : _e, logger = _b.logger;
var enhancers = [];
var middlewares = [];
if (reportCrashes) {
middlewares.push(crashReporter);
}
if (logger) {
middlewares.push(logger);
}
if (middlewares.length > 0) {
enhancers.push(redux.applyMiddleware.apply(void 0, middlewares));
}
if (typeof window !== 'undefined') {
var anyWindow = window;
if (anyWindow.devToolsExtension) {
enhancers.push(anyWindow.devToolsExtension());
}
}
var compose$$1 = redux.compose;
if (initialState && initialState[reduxRootKey] && initialState[reduxRootKey]['queries']) {
throw new Error('Apollo initial state may not contain queries, only data');
}
if (initialState && initialState[reduxRootKey] && initialState[reduxRootKey]['mutations']) {
throw new Error('Apollo initial state may not contain mutations, only data');
}
return redux.createStore(redux.combineReducers((_f = {}, _f[reduxRootKey] = createApolloReducer(config), _f)), initialState, compose$$1.apply(void 0, enhancers));
var _f;
}
function isSubscription(subscription) {
return subscription.unsubscribe !== undefined;
}
var Observable = (function () {
function Observable(subscriberFunction) {
this.subscriberFunction = subscriberFunction;
}
Observable.prototype[$$observable] = function () {
return this;
};
Observable.prototype.subscribe = function (observer) {
var subscriptionOrCleanupFunction = this.subscriberFunction(observer);
if (isSubscription(subscriptionOrCleanupFunction)) {
return subscriptionOrCleanupFunction;
}
else {
return {
unsubscribe: subscriptionOrCleanupFunction,
};
}
};
return Observable;
}());
var __extends$4 = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
function isApolloError(err) {
return err.hasOwnProperty('graphQLErrors');
}
var generateErrorMessage = function (err) {
var message = '';
if (Array.isArray(err.graphQLErrors) && err.graphQLErrors.length !== 0) {
err.graphQLErrors.forEach(function (graphQLError) {
var errorMessage = graphQLError ? graphQLError.message : 'Error message not found.';
message += "GraphQL error: " + errorMessage + "\n";
});
}
if (err.networkError) {
message += 'Network error: ' + err.networkError.message + '\n';
}
message = message.replace(/\n$/, '');
return message;
};
var ApolloError = (function (_super) {
__extends$4(ApolloError, _super);
function ApolloError(_a) {
var graphQLErrors = _a.graphQLErrors, networkError = _a.networkError, errorMessage = _a.errorMessage, extraInfo = _a.extraInfo;
var _this = _super.call(this, errorMessage) || this;
_this.graphQLErrors = graphQLErrors || [];
_this.networkError = networkError || null;
if (!errorMessage) {
_this.message = generateErrorMessage(_this);
}
else {
_this.message = errorMessage;
}
_this.extraInfo = extraInfo;
return _this;
}
return ApolloError;
}(Error));
var FetchType;
(function (FetchType) {
FetchType[FetchType["normal"] = 1] = "normal";
FetchType[FetchType["refetch"] = 2] = "refetch";
FetchType[FetchType["poll"] = 3] = "poll";
})(FetchType || (FetchType = {}));
function deepFreeze(o) {
Object.freeze(o);
Object.getOwnPropertyNames(o).forEach(function (prop) {
if (o.hasOwnProperty(prop)
&& o[prop] !== null
&& (typeof o[prop] === 'object' || typeof o[prop] === 'function')
&& !Object.isFrozen(o[prop])) {
deepFreeze(o[prop]);
}
});
return o;
}
function maybeDeepFreeze(obj) {
if (isDevelopment() || isTest()) {
return deepFreeze(obj);
}
return obj;
}
var __extends$3 = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign$12 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var ObservableQuery = (function (_super) {
__extends$3(ObservableQuery, _super);
function ObservableQuery(_a) {
var scheduler = _a.scheduler, options = _a.options, _b = _a.shouldSubscribe, shouldSubscribe = _b === void 0 ? true : _b;
var _this = this;
var queryManager = scheduler.queryManager;
var queryId = queryManager.generateQueryId();
var subscriberFunction = function (observer) {
return _this.onSubscribe(observer);
};
_this = _super.call(this, subscriberFunction) || this;
_this.isCurrentlyPolling = false;
_this.options = options;
_this.variables = _this.options.variables || {};
_this.scheduler = scheduler;
_this.queryManager = queryManager;
_this.queryId = queryId;
_this.shouldSubscribe = shouldSubscribe;
_this.observers = [];
_this.subscriptionHandles = [];
return _this;
}
ObservableQuery.prototype.result = function () {
var that = this;
return new Promise(function (resolve, reject) {
var subscription = null;
var observer = {
next: function (result) {
resolve(result);
var selectedObservers = that.observers.filter(function (obs) { return obs !== observer; });
if (selectedObservers.length === 0) {
that.queryManager.removeQuery(that.queryId);
}
setTimeout(function () {
subscription.unsubscribe();
}, 0);
},
error: function (error) {
reject(error);
},
};
subscription = that.subscribe(observer);
});
};
ObservableQuery.prototype.currentResult = function () {
var _a = this.queryManager.getCurrentQueryResult(this, true), data = _a.data, partial = _a.partial;
var queryStoreValue = this.queryManager.getApolloState().queries[this.queryId];
if (queryStoreValue && ((queryStoreValue.graphQLErrors && queryStoreValue.graphQLErrors.length > 0) ||
queryStoreValue.networkError)) {
var error = new ApolloError({
graphQLErrors: queryStoreValue.graphQLErrors,
networkError: queryStoreValue.networkError,
});
return { data: {}, loading: false, networkStatus: queryStoreValue.networkStatus, error: error };
}
var queryLoading = !queryStoreValue || queryStoreValue.networkStatus === exports.NetworkStatus.loading;
var loading = (this.options.fetchPolicy === 'network-only' && queryLoading)
|| (partial && this.options.fetchPolicy !== 'cache-only');
var networkStatus;
if (queryStoreValue) {
networkStatus = queryStoreValue.networkStatus;
}
else {
networkStatus = loading ? exports.NetworkStatus.loading : exports.NetworkStatus.ready;
}
return {
data: data,
loading: isNetworkRequestInFlight(networkStatus),
networkStatus: networkStatus,
partial: partial,
};
};
ObservableQuery.prototype.getLastResult = function () {
return this.lastResult;
};
ObservableQuery.prototype.refetch = function (variables) {
this.variables = __assign$12({}, this.variables, variables);
if (this.options.fetchPolicy === 'cache-only') {
return Promise.reject(new Error('cache-only fetchPolicy option should not be used together with query refetch.'));
}
this.options.variables = __assign$12({}, this.options.variables, this.variables);
var combinedOptions = __assign$12({}, this.options, { fetchPolicy: 'network-only' });
return this.queryManager.fetchQuery(this.queryId, combinedOptions, FetchType.refetch)
.then(function (result) { return maybeDeepFreeze(result); });
};
ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
var _this = this;
if (!fetchMoreOptions.updateQuery) {
throw new Error('updateQuery option is required. This function defines how to update the query data with the new results.');
}
return Promise.resolve()
.then(function () {
var qid = _this.queryManager.generateQueryId();
var combinedOptions = null;
if (fetchMoreOptions.query) {
combinedOptions = fetchMoreOptions;
}
else {
var variables = __assign$12({}, _this.variables, fetchMoreOptions.variables);
combinedOptions = __assign$12({}, _this.options, fetchMoreOptions, { variables: variables });
}
combinedOptions = __assign$12({}, combinedOptions, { query: combinedOptions.query, fetchPolicy: 'network-only' });
return _this.queryManager.fetchQuery(qid, combinedOptions, FetchType.normal, _this.queryId);
})
.then(function (fetchMoreResult) {
var data = fetchMoreResult.data;
var reducer = fetchMoreOptions.updateQuery;
var mapFn = function (previousResult, _a) {
var variables = _a.variables;
var queryVariables = variables;
return reducer(previousResult, {
fetchMoreResult: data,
queryVariables: queryVariables,
});
};
_this.updateQuery(mapFn);
return fetchMoreResult;
});
};
ObservableQuery.prototype.subscribeToMore = function (options) {
var _this = this;
var observable = this.queryManager.startGraphQLSubscription({
query: options.document,
variables: options.variables,
});
var subscription = observable.subscribe({
next: function (data) {
if (options.updateQuery) {
var reducer_1 = options.updateQuery;
var mapFn = function (previousResult, _a) {
var variables = _a.variables;
return reducer_1(previousResult, {
subscriptionData: { data: data },
variables: variables,
});
};
_this.updateQuery(mapFn);
}
},
error: function (err) {
if (options.onError) {
options.onError(err);
}
else {
console.error('Unhandled GraphQL subscription error', err);
}
},
});
this.subscriptionHandles.push(subscription);
return function () {
var i = _this.subscriptionHandles.indexOf(subscription);
if (i >= 0) {
_this.subscriptionHandles.splice(i, 1);
subscription.unsubscribe();
}
};
};
ObservableQuery.prototype.setOptions = function (opts) {
var oldOptions = this.options;
this.options = __assign$12({}, this.options, opts);
if (opts.pollInterval) {
this.startPolling(opts.pollInterval);
}
else if (opts.pollInterval === 0) {
this.stopPolling();
}
var tryFetch = (oldOptions.fetchPolicy !== 'network-only' && opts.fetchPolicy === 'network-only')
|| (oldOptions.fetchPolicy === 'cache-only' && opts.fetchPolicy !== 'cache-only')
|| (oldOptions.fetchPolicy === 'standby' && opts.fetchPolicy !== 'standby')
|| false;
return this.setVariables(this.options.variables, tryFetch, opts.fetchResults);
};
ObservableQuery.prototype.setVariables = function (variables, tryFetch, fetchResults) {
if (tryFetch === void 0) { tryFetch = false; }
if (fetchResults === void 0) { fetchResults = true; }
var newVariables = __assign$12({}, this.variables, variables);
if (isEqual(newVariables, this.variables) && !tryFetch) {
if (this.observers.length === 0 || !fetchResults) {
return new Promise(function (resolve) { return resolve(); });
}
return this.result();
}
else {
this.variables = newVariables;
this.options.variables = newVariables;
if (this.observers.length === 0) {
return new Promise(function (resolve) { return resolve(); });
}
return this.queryManager.fetchQuery(this.queryId, __assign$12({}, this.options, { variables: this.variables }))
.then(function (result) { return maybeDeepFreeze(result); });
}
};
ObservableQuery.prototype.updateQuery = function (mapFn) {
var _a = this.queryManager.getQueryWithPreviousResult(this.queryId), previousResult = _a.previousResult, variables = _a.variables, document = _a.document;
var newResult = tryFunctionOrLogError(function () { return mapFn(previousResult, { variables: variables }); });
if (newResult) {
this.queryManager.store.dispatch({
type: 'APOLLO_UPDATE_QUERY_RESULT',
newResult: newResult,
variables: variables,
document: document,
operationName: getOperationName(document),
});
}
};
ObservableQuery.prototype.stopPolling = function () {
if (this.isCurrentlyPolling) {
this.scheduler.stopPollingQuery(this.queryId);
this.options.pollInterval = undefined;
this.isCurrentlyPolling = false;
}
};
ObservableQuery.prototype.startPolling = function (pollInterval) {
if (this.options.fetchPolicy === 'cache-first' || (this.options.fetchPolicy === 'cache-only')) {
throw new Error('Queries that specify the cache-first and cache-only fetchPolicies cannot also be polling queries.');
}
if (this.isCurrentlyPolling) {
this.scheduler.stopPollingQuery(this.queryId);
this.isCurrentlyPolling = false;
}
this.options.pollInterval = pollInterval;
this.isCurrentlyPolling = true;
this.scheduler.startPollingQuery(this.options, this.queryId);
};
ObservableQuery.prototype.onSubscribe = function (observer) {
var _this = this;
this.observers.push(observer);
if (observer.next && this.lastResult) {
observer.next(this.lastResult);
}
if (observer.error && this.lastError) {
observer.error(this.lastError);
}
if (this.observers.length === 1) {
this.setUpQuery();
}
var retQuerySubscription = {
unsubscribe: function () {
if (!_this.observers.some(function (el) { return el === observer; })) {
return;
}
_this.observers = _this.observers.filter(function (obs) { return obs !== observer; });
if (_this.observers.length === 0) {
_this.tearDownQuery();
}
},
};
return retQuerySubscription;
};
ObservableQuery.prototype.setUpQuery = function () {
var _this = this;
if (this.shouldSubscribe) {
this.queryManager.addObservableQuery(this.queryId, this);
}
if (!!this.options.pollInterval) {
if (this.options.fetchPolicy === 'cache-first' || (this.options.fetchPolicy === 'cache-only')) {
throw new Error('Queries that specify the cache-first and cache-only fetchPolicies cannot also be polling queries.');
}
this.isCurrentlyPolling = true;
this.scheduler.startPollingQuery(this.options, this.queryId);
}
var observer = {
next: function (result) {
_this.lastResult = result;
_this.observers.forEach(function (obs) {
if (obs.next) {
obs.next(result);
}
});
},
error: function (error) {
_this.observers.forEach(function (obs) {
if (obs.error) {
obs.error(error);
}
else {
console.error('Unhandled error', error.message, error.stack);
}
});
_this.lastError = error;
},
};
this.queryManager.startQuery(this.queryId, this.options, this.queryManager.queryListenerForObserver(this.queryId, this.options, observer));
};
ObservableQuery.prototype.tearDownQuery = function () {
if (this.isCurrentlyPolling) {
this.scheduler.stopPollingQuery(this.queryId);
this.isCurrentlyPolling = false;
}
this.subscriptionHandles.forEach(function (sub) { return sub.unsubscribe(); });
this.subscriptionHandles = [];
this.queryManager.stopQuery(this.queryId);
if (this.shouldSubscribe) {
this.queryManager.removeObservableQuery(this.queryId);
}
this.observers = [];
};
return ObservableQuery;
}(Observable));
var haveWarned$1 = Object.create({});
function warnOnceInDevelopment(msg, type) {
if (type === void 0) { type = 'warn'; }
if (isProduction()) {
return;
}
if (!haveWarned$1[msg]) {
if (!isTest()) {
haveWarned$1[msg] = true;
}
switch (type) {
case 'error':
console.error(msg);
break;
default:
console.warn(msg);
}
}
}
var IntrospectionFragmentMatcher = (function () {
function IntrospectionFragmentMatcher(options) {
if (options && options.introspectionQueryResultData) {
this.possibleTypesMap = this.parseIntrospectionResult(options.introspectionQueryResultData);
this.isReady = true;
}
else {
this.isReady = false;
}
this.match = this.match.bind(this);
}
IntrospectionFragmentMatcher.prototype.match = function (idValue, typeCondition, context) {
if (!this.isReady) {
throw new Error('FragmentMatcher.match() was called before FragmentMatcher.init()');
}
var obj = context.store[idValue.id];
if (!obj) {
return false;
}
if (!obj.__typename) {
throw new Error("Cannot match fragment because __typename property is missing: " + JSON.stringify(obj));
}
if (obj.__typename === typeCondition) {
return true;
}
var implementingTypes = this.possibleTypesMap[typeCondition];
if (implementingTypes && implementingTypes.indexOf(obj.__typename) > -1) {
return true;
}
return false;
};
IntrospectionFragmentMatcher.prototype.parseIntrospectionResult = function (introspectionResultData) {
var typeMap = {};
introspectionResultData.__schema.types.forEach(function (type) {
if (type.kind === 'UNION' || type.kind === 'INTERFACE') {
typeMap[type.name] = type.possibleTypes.map(function (implementingType) { return implementingType.name; });
}
});
return typeMap;
};
return IntrospectionFragmentMatcher;
}());
var haveWarned = false;
var HeuristicFragmentMatcher = (function () {
function HeuristicFragmentMatcher() {
}
HeuristicFragmentMatcher.prototype.ensureReady = function () {
return Promise.resolve();
};
HeuristicFragmentMatcher.prototype.canBypassInit = function () {
return true;
};
HeuristicFragmentMatcher.prototype.match = function (idValue, typeCondition, context) {
var obj = context.store[idValue.id];
if (!obj) {
return false;
}
if (!obj.__typename) {
if (!haveWarned) {
console.warn("You're using fragments in your queries, but either don't have the addTypename:\n true option set in Apollo Client, or you are trying to write a fragment to the store without the __typename.\n Please turn on the addTypename option and include __typename when writing fragments so that Apollo Client\n can accurately match fragments.");
console.warn('Could not find __typename on Fragment ', typeCondition, obj);
console.warn("DEPRECATION WARNING: using fragments without __typename is unsupported behavior " +
"and will be removed in future versions of Apollo client. You should fix this and set addTypename to true now.");
if (!isTest()) {
haveWarned = true;
}
}
context.returnPartialData = true;
return true;
}
if (obj.__typename === typeCondition) {
return true;
}
warnOnceInDevelopment("You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types.\n Apollo Client will not be able to able to accurately map fragments." +
"To make this error go away, use the IntrospectionFragmentMatcher as described in the docs: " +
"http://dev.apollodata.com/react/initialization.html#fragment-matcher", 'error');
context.returnPartialData = true;
return true;
};
return HeuristicFragmentMatcher;
}());
var Deduplicator = (function () {
function Deduplicator(networkInterface) {
this.networkInterface = networkInterface;
this.inFlightRequestPromises = {};
}
Deduplicator.prototype.query = function (request, deduplicate) {
var _this = this;
if (deduplicate === void 0) { deduplicate = true; }
if (!deduplicate) {
return this.networkInterface.query(request);
}
var key = this.getKey(request);
if (!this.inFlightRequestPromises[key]) {
this.inFlightRequestPromises[key] = this.networkInterface.query(request);
}
return this.inFlightRequestPromises[key]
.then(function (res) {
delete _this.inFlightRequestPromises[key];
return res;
})
.catch(function (err) {
delete _this.inFlightRequestPromises[key];
throw err;
});
};
Deduplicator.prototype.getKey = function (request) {
return graphql_language_printer.print(request.query) + "|" + JSON.stringify(request.variables) + "|" + request.operationName;
};
return Deduplicator;
}());
function createStoreReducer(resultReducer, document, variables, config) {
return function (store, action) {
var _a = diffQueryAgainstStore({
store: store,
query: document,
variables: variables,
returnPartialData: true,
fragmentMatcherFunction: config.fragmentMatcher,
config: config,
}), result = _a.result, isMissing = _a.isMissing;
if (isMissing) {
return store;
}
var nextResult;
try {
nextResult = resultReducer(result, action, variables);
}
catch (err) {
console.warn('Unhandled error in result reducer', err);
throw err;
}
if (result !== nextResult) {
return writeResultToStore({
dataId: 'ROOT_QUERY',
result: nextResult,
store: store,
document: document,
variables: variables,
dataIdFromObject: config.dataIdFromObject,
fragmentMatcherFunction: config.fragmentMatcher,
});
}
return store;
};
}
var __assign$15 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var QueryScheduler = (function () {
function QueryScheduler(_a) {
var queryManager = _a.queryManager;
this.queryManager = queryManager;
this.pollingTimers = {};
this.inFlightQueries = {};
this.registeredQueries = {};
this.intervalQueries = {};
}
QueryScheduler.prototype.checkInFlight = function (queryId) {
var queries = this.queryManager.getApolloState().queries;
return queries[queryId] && queries[queryId].networkStatus !== exports.NetworkStatus.ready;
};
QueryScheduler.prototype.fetchQuery = function (queryId, options, fetchType) {
var _this = this;
return new Promise(function (resolve, reject) {
_this.queryManager.fetchQuery(queryId, options, fetchType).then(function (result) {
resolve(result);
}).catch(function (error) {
reject(error);
});
});
};
QueryScheduler.prototype.startPollingQuery = function (options, queryId, listener) {
if (!options.pollInterval) {
throw new Error('Attempted to start a polling query without a polling interval.');
}
if (this.queryManager.ssrMode) {
return queryId;
}
this.registeredQueries[queryId] = options;
if (listener) {
this.queryManager.addQueryListener(queryId, listener);
}
this.addQueryOnInterval(queryId, options);
return queryId;
};
QueryScheduler.prototype.stopPollingQuery = function (queryId) {
delete this.registeredQueries[queryId];
};
QueryScheduler.prototype.fetchQueriesOnInterval = function (interval) {
var _this = this;
this.intervalQueries[interval] = this.intervalQueries[interval].filter(function (queryId) {
if (!_this.registeredQueries.hasOwnProperty(queryId)) {
return false;
}
if (_this.checkInFlight(queryId)) {
return true;
}
var queryOptions = _this.registeredQueries[queryId];
var pollingOptions = __assign$15({}, queryOptions);
pollingOptions.fetchPolicy = 'network-only';
_this.fetchQuery(queryId, pollingOptions, FetchType.poll);
return true;
});
if (this.intervalQueries[interval].length === 0) {
clearInterval(this.pollingTimers[interval]);
delete this.intervalQueries[interval];
}
};
QueryScheduler.prototype.addQueryOnInterval = function (queryId, queryOptions) {
var _this = this;
var interval = queryOptions.pollInterval;
if (!interval) {
throw new Error("A poll interval is required to start polling query with id '" + queryId + "'.");
}
if (this.intervalQueries.hasOwnProperty(interval.toString()) && this.intervalQueries[interval].length > 0) {
this.intervalQueries[interval].push(queryId);
}
else {
this.intervalQueries[interval] = [queryId];
this.pollingTimers[interval] = setInterval(function () {
_this.fetchQueriesOnInterval(interval);
}, interval);
}
};
QueryScheduler.prototype.registerPollingQuery = function (queryOptions) {
if (!queryOptions.pollInterval) {
throw new Error('Attempted to register a non-polling query with the scheduler.');
}
return new ObservableQuery({
scheduler: this,
options: queryOptions,
});
};
return QueryScheduler;
}());
var __assign$14 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var QueryManager = (function () {
function QueryManager(_a) {
var networkInterface = _a.networkInterface, store = _a.store, reduxRootSelector = _a.reduxRootSelector, _b = _a.reducerConfig, reducerConfig = _b === void 0 ? { mutationBehaviorReducers: {} } : _b, fragmentMatcher = _a.fragmentMatcher, _c = _a.addTypename, addTypename = _c === void 0 ? true : _c, _d = _a.queryDeduplication, queryDeduplication = _d === void 0 ? false : _d, _e = _a.ssrMode, ssrMode = _e === void 0 ? false : _e;
var _this = this;
this.idCounter = 1;
this.networkInterface = networkInterface;
this.deduplicator = new Deduplicator(networkInterface);
this.store = store;
this.reduxRootSelector = reduxRootSelector;
this.reducerConfig = reducerConfig;
this.pollingTimers = {};
this.queryListeners = {};
this.queryDocuments = {};
this.addTypename = addTypename;
this.queryDeduplication = queryDeduplication;
this.ssrMode = ssrMode;
if (typeof fragmentMatcher === 'undefined') {
this.fragmentMatcher = new HeuristicFragmentMatcher();
}
else {
this.fragmentMatcher = fragmentMatcher;
}
this.scheduler = new QueryScheduler({
queryManager: this,
});
this.fetchQueryPromises = {};
this.observableQueries = {};
this.queryIdsByName = {};
if (this.store['subscribe']) {
var currentStoreData_1;
this.store['subscribe'](function () {
var previousStoreData = currentStoreData_1 || {};
var previousStoreHasData = Object.keys(previousStoreData).length;
currentStoreData_1 = _this.getApolloState();
if (isEqual(previousStoreData, currentStoreData_1) && previousStoreHasData) {
return;
}
_this.broadcastQueries();
});
}
}
QueryManager.prototype.broadcastNewStore = function (store) {
this.broadcastQueries();
};
QueryManager.prototype.mutate = function (_a) {
var _this = this;
var mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, updateQueriesByName = _a.updateQueries, _b = _a.refetchQueries, refetchQueries = _b === void 0 ? [] : _b, updateWithProxyFn = _a.update;
var mutationId = this.generateQueryId();
if (this.addTypename) {
mutation = addTypenameToDocument(mutation);
}
variables = assign({}, getDefaultValues(getMutationDefinition(mutation)), variables);
var mutationString = graphql_language_printer.print(mutation);
var request = {
query: mutation,
variables: variables,
operationName: getOperationName(mutation),
};
this.queryDocuments[mutationId] = mutation;
var updateQueries = {};
if (updateQueriesByName) {
Object.keys(updateQueriesByName).forEach(function (queryName) { return (_this.queryIdsByName[queryName] || []).forEach(function (queryId) {
updateQueries[queryId] = updateQueriesByName[queryName];
}); });
}
this.store.dispatch({
type: 'APOLLO_MUTATION_INIT',
mutationString: mutationString,
mutation: mutation,
variables: variables || {},
operationName: getOperationName(mutation),
mutationId: mutationId,
optimisticResponse: optimisticResponse,
extraReducers: this.getExtraReducers(),
updateQueries: updateQueries,
update: updateWithProxyFn,
});
return new Promise(function (resolve, reject) {
_this.networkInterface.query(request)
.then(function (result) {
if (result.errors) {
var error = new ApolloError({
graphQLErrors: result.errors,
});
_this.store.dispatch({
type: 'APOLLO_MUTATION_ERROR',
error: error,
mutationId: mutationId,
});
delete _this.queryDocuments[mutationId];
reject(error);
return;
}
_this.store.dispatch({
type: 'APOLLO_MUTATION_RESULT',
result: result,
mutationId: mutationId,
document: mutation,
operationName: getOperationName(mutation),
variables: variables || {},
extraReducers: _this.getExtraReducers(),
updateQueries: updateQueries,
update: updateWithProxyFn,
});
var reducerError = _this.getApolloState().reducerError;
if (reducerError && reducerError.mutationId === mutationId) {
reject(reducerError.error);
return;
}
if (typeof refetchQueries[0] === 'string') {
refetchQueries.forEach(function (name) { _this.refetchQueryByName(name); });
}
else {
refetchQueries.forEach(function (pureQuery) {
_this.query({
query: pureQuery.query,
variables: pureQuery.variables,
fetchPolicy: 'network-only',
});
});
}
delete _this.queryDocuments[mutationId];
resolve(result);
})
.catch(function (err) {
_this.store.dispatch({
type: 'APOLLO_MUTATION_ERROR',
error: err,
mutationId: mutationId,
});
delete _this.queryDocuments[mutationId];
reject(new ApolloError({
networkError: err,
}));
});
});
};
QueryManager.prototype.fetchQuery = function (queryId, options, fetchType, fetchMoreForQueryId) {
var _this = this;
var _a = options.variables, variables = _a === void 0 ? {} : _a, _b = options.metadata, metadata = _b === void 0 ? null : _b, _c = options.fetchPolicy, fetchPolicy = _c === void 0 ? 'cache-first' : _c;
var queryDoc = this.transformQueryDocument(options).queryDoc;
var queryString = graphql_language_printer.print(queryDoc);
var storeResult;
var needToFetch = fetchPolicy === 'network-only';
if ((fetchType !== FetchType.refetch && fetchPolicy !== 'network-only')) {
var _d = diffQueryAgainstStore({
query: queryDoc,
store: this.reduxRootSelector(this.store.getState()).data,
variables: variables,
returnPartialData: true,
fragmentMatcherFunction: this.fragmentMatcher.match,
config: this.reducerConfig,
}), isMissing = _d.isMissing, result = _d.result;
needToFetch = isMissing || fetchPolicy === 'cache-and-network';
storeResult = result;
}
var shouldFetch = needToFetch && fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby';
var requestId = this.generateRequestId();
this.queryDocuments[queryId] = queryDoc;
this.store.dispatch({
type: 'APOLLO_QUERY_INIT',
queryString: queryString,
document: queryDoc,
operationName: getOperationName(queryDoc),
variables: variables,
fetchPolicy: fetchPolicy,
queryId: queryId,
requestId: requestId,
storePreviousVariables: shouldFetch,
isPoll: fetchType === FetchType.poll,
isRefetch: fetchType === FetchType.refetch,
fetchMoreForQueryId: fetchMoreForQueryId,
metadata: metadata,
});
var shouldDispatchClientResult = !shouldFetch || fetchPolicy === 'cache-and-network';
if (shouldDispatchClientResult) {
this.store.dispatch({
type: 'APOLLO_QUERY_RESULT_CLIENT',
result: { data: storeResult },
variables: variables,
document: queryDoc,
operationName: getOperationName(queryDoc),
complete: !shouldFetch,
queryId: queryId,
requestId: requestId,
});
}
if (shouldFetch) {
var networkResult = this.fetchRequest({
requestId: requestId,
queryId: queryId,
document: queryDoc,
options: options,
fetchMoreForQueryId: fetchMoreForQueryId,
}).catch(function (error) {
if (isApolloError(error)) {
throw error;
}
else {
_this.store.dispatch({
type: 'APOLLO_QUERY_ERROR',
error: error,
queryId: queryId,
requestId: requestId,
fetchMoreForQueryId: fetchMoreForQueryId,
});
_this.removeFetchQueryPromise(requestId);
throw new ApolloError({
networkError: error,
});
}
});
if (fetchPolicy !== 'cache-and-network') {
return networkResult;
}
}
return Promise.resolve({ data: storeResult });
};
QueryManager.prototype.queryListenerForObserver = function (queryId, options, observer) {
var _this = this;
var lastResult;
var previouslyHadError = false;
return function (queryStoreValue) {
if (!queryStoreValue) {
return;
}
queryStoreValue = _this.getApolloState().queries[queryId];
var storedQuery = _this.observableQueries[queryId];
var fetchPolicy = storedQuery ? storedQuery.observableQuery.options.fetchPolicy : options.fetchPolicy;
if (fetchPolicy === 'standby') {
return;
}
var shouldNotifyIfLoading = queryStoreValue.previousVariables ||
fetchPolicy === 'cache-only' || fetchPolicy === 'cache-and-network';
var networkStatusChanged = lastResult && queryStoreValue.networkStatus !== lastResult.networkStatus;
if (!isNetworkRequestInFlight(queryStoreValue.networkStatus) ||
(networkStatusChanged && options.notifyOnNetworkStatusChange) ||
shouldNotifyIfLoading) {
if ((queryStoreValue.graphQLErrors && queryStoreValue.graphQLErrors.length > 0) ||
queryStoreValue.networkError) {
var apolloError_1 = new ApolloError({
graphQLErrors: queryStoreValue.graphQLErrors,
networkError: queryStoreValue.networkError,
});
previouslyHadError = true;
if (observer.error) {
try {
observer.error(apolloError_1);
}
catch (e) {
setTimeout(function () { throw e; }, 0);
}
}
else {
setTimeout(function () { throw apolloError_1; }, 0);
if (!isProduction()) {
console.info('An unhandled error was thrown because no error handler is registered ' +
'for the query ' + queryStoreValue.queryString);
}
}
}
else {
try {
var _a = diffQueryAgainstStore({
store: _this.getDataWithOptimisticResults(),
query: _this.queryDocuments[queryId],
variables: queryStoreValue.previousVariables || queryStoreValue.variables,
config: _this.reducerConfig,
fragmentMatcherFunction: _this.fragmentMatcher.match,
previousResult: lastResult && lastResult.data,
}), data = _a.result, isMissing = _a.isMissing;
var resultFromStore = void 0;
if (isMissing && fetchPolicy !== 'cache-only') {
resultFromStore = {
data: lastResult && lastResult.data,
loading: isNetworkRequestInFlight(queryStoreValue.networkStatus),
networkStatus: queryStoreValue.networkStatus,
stale: true,
};
}
else {
resultFromStore = {
data: data,
loading: isNetworkRequestInFlight(queryStoreValue.networkStatus),
networkStatus: queryStoreValue.networkStatus,
stale: false,
};
}
if (observer.next) {
var isDifferentResult = !(lastResult &&
resultFromStore &&
lastResult.networkStatus === resultFromStore.networkStatus &&
lastResult.stale === resultFromStore.stale &&
lastResult.data === resultFromStore.data);
if (isDifferentResult || previouslyHadError) {
lastResult = resultFromStore;
try {
observer.next(maybeDeepFreeze(resultFromStore));
}
catch (e) {
setTimeout(function () { throw e; }, 0);
}
}
}
previouslyHadError = false;
}
catch (error) {
previouslyHadError = true;
if (observer.error) {
observer.error(new ApolloError({
networkError: error,
}));
}
return;
}
}
}
};
};
QueryManager.prototype.watchQuery = function (options, shouldSubscribe) {
if (shouldSubscribe === void 0) { shouldSubscribe = true; }
if (options.returnPartialData) {
throw new Error('returnPartialData option is no longer supported since Apollo Client 1.0.');
}
if (options.forceFetch) {
throw new Error('forceFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.');
}
if (options.noFetch) {
throw new Error('noFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.');
}
if (options.fetchPolicy === 'standby') {
throw new Error('client.watchQuery cannot be called with fetchPolicy set to "standby"');
}
var queryDefinition = getQueryDefinition(options.query);
if (queryDefinition.variableDefinitions && queryDefinition.variableDefinitions.length) {
var defaultValues = getDefaultValues(queryDefinition);
options.variables = assign({}, defaultValues, options.variables);
}
if (typeof options.notifyOnNetworkStatusChange === 'undefined') {
options.notifyOnNetworkStatusChange = false;
}
var transformedOptions = __assign$14({}, options);
var observableQuery = new ObservableQuery({
scheduler: this.scheduler,
options: transformedOptions,
shouldSubscribe: shouldSubscribe,
});
return observableQuery;
};
QueryManager.prototype.query = function (options) {
var _this = this;
if (!options.query) {
throw new Error('query option is required. You must specify your GraphQL document in the query option.');
}
if (options.query.kind !== 'Document') {
throw new Error('You must wrap the query string in a "gql" tag.');
}
if (options.returnPartialData) {
throw new Error('returnPartialData option only supported on watchQuery.');
}
if (options.pollInterval) {
throw new Error('pollInterval option only supported on watchQuery.');
}
if (options.forceFetch) {
throw new Error('forceFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.');
}
if (options.noFetch) {
throw new Error('noFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.');
}
if (typeof options.notifyOnNetworkStatusChange !== 'undefined') {
throw new Error('Cannot call "query" with "notifyOnNetworkStatusChange" option. Only "watchQuery" has that option.');
}
options.notifyOnNetworkStatusChange = false;
var requestId = this.idCounter;
var resPromise = new Promise(function (resolve, reject) {
_this.addFetchQueryPromise(requestId, resPromise, resolve, reject);
return _this.watchQuery(options, false).result().then(function (result) {
_this.removeFetchQueryPromise(requestId);
resolve(result);
}).catch(function (error) {
_this.removeFetchQueryPromise(requestId);
reject(error);
});
});
return resPromise;
};
QueryManager.prototype.generateQueryId = function () {
var queryId = this.idCounter.toString();
this.idCounter++;
return queryId;
};
QueryManager.prototype.stopQueryInStore = function (queryId) {
this.store.dispatch({
type: 'APOLLO_QUERY_STOP',
queryId: queryId,
});
};
QueryManager.prototype.getApolloState = function () {
return this.reduxRootSelector(this.store.getState());
};
QueryManager.prototype.selectApolloState = function (store) {
return this.reduxRootSelector(store.getState());
};
QueryManager.prototype.getInitialState = function () {
return { data: this.getApolloState().data };
};
QueryManager.prototype.getDataWithOptimisticResults = function () {
return getDataWithOptimisticResults(this.getApolloState());
};
QueryManager.prototype.addQueryListener = function (queryId, listener) {
this.queryListeners[queryId] = this.queryListeners[queryId] || [];
this.queryListeners[queryId].push(listener);
};
QueryManager.prototype.addFetchQueryPromise = function (requestId, promise, resolve, reject) {
this.fetchQueryPromises[requestId.toString()] = { promise: promise, resolve: resolve, reject: reject };
};
QueryManager.prototype.removeFetchQueryPromise = function (requestId) {
delete this.fetchQueryPromises[requestId.toString()];
};
QueryManager.prototype.addObservableQuery = function (queryId, observableQuery) {
this.observableQueries[queryId] = { observableQuery: observableQuery };
var queryDef = getQueryDefinition(observableQuery.options.query);
if (queryDef.name && queryDef.name.value) {
var queryName = queryDef.name.value;
this.queryIdsByName[queryName] = this.queryIdsByName[queryName] || [];
this.queryIdsByName[queryName].push(observableQuery.queryId);
}
};
QueryManager.prototype.removeObservableQuery = function (queryId) {
var observableQuery = this.observableQueries[queryId].observableQuery;
var definition = getQueryDefinition(observableQuery.options.query);
var queryName = definition.name ? definition.name.value : null;
delete this.observableQueries[queryId];
if (queryName) {
this.queryIdsByName[queryName] = this.queryIdsByName[queryName].filter(function (val) {
return !(observableQuery.queryId === val);
});
}
};
QueryManager.prototype.resetStore = function () {
var _this = this;
Object.keys(this.fetchQueryPromises).forEach(function (key) {
var reject = _this.fetchQueryPromises[key].reject;
reject(new Error('Store reset while query was in flight.'));
});
this.store.dispatch({
type: 'APOLLO_STORE_RESET',
observableQueryIds: Object.keys(this.observableQueries),
});
var observableQueryPromises = [];
Object.keys(this.observableQueries).forEach(function (queryId) {
var storeQuery = _this.reduxRootSelector(_this.store.getState()).queries[queryId];
var fetchPolicy = _this.observableQueries[queryId].observableQuery.options.fetchPolicy;
if (fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby') {
observableQueryPromises.push(_this.observableQueries[queryId].observableQuery.refetch());
}
});
return Promise.all(observableQueryPromises);
};
QueryManager.prototype.startQuery = function (queryId, options, listener) {
this.addQueryListener(queryId, listener);
this.fetchQuery(queryId, options)
.catch(function (error) { return undefined; });
return queryId;
};
QueryManager.prototype.startGraphQLSubscription = function (options) {
var _this = this;
var query = options.query;
var transformedDoc = query;
if (this.addTypename) {
transformedDoc = addTypenameToDocument(transformedDoc);
}
var variables = assign({}, getDefaultValues(getOperationDefinition(query)), options.variables);
var request = {
query: transformedDoc,
variables: variables,
operationName: getOperationName(transformedDoc),
};
var subId;
var observers = [];
return new Observable(function (observer) {
observers.push(observer);
if (observers.length === 1) {
var handler = function (error, result) {
if (error) {
observers.forEach(function (obs) {
if (obs.error) {
obs.error(error);
}
});
}
else {
_this.store.dispatch({
type: 'APOLLO_SUBSCRIPTION_RESULT',
document: transformedDoc,
operationName: getOperationName(transformedDoc),
result: { data: result },
variables: variables,
subscriptionId: subId,
extraReducers: _this.getExtraReducers(),
});
observers.forEach(function (obs) {
if (obs.next) {
obs.next(result);
}
});
}
};
subId = _this.networkInterface.subscribe(request, handler);
}
return {
unsubscribe: function () {
observers = observers.filter(function (obs) { return obs !== observer; });
if (observers.length === 0) {
_this.networkInterface.unsubscribe(subId);
}
},
_networkSubscriptionId: subId,
};
});
};
QueryManager.prototype.removeQuery = function (queryId) {
delete this.queryListeners[queryId];
delete this.queryDocuments[queryId];
};
QueryManager.prototype.stopQuery = function (queryId) {
this.removeQuery(queryId);
this.stopQueryInStore(queryId);
};
QueryManager.prototype.getCurrentQueryResult = function (observableQuery, isOptimistic) {
if (isOptimistic === void 0) { isOptimistic = false; }
var _a = this.getQueryParts(observableQuery), variables = _a.variables, document = _a.document;
var lastResult = observableQuery.getLastResult();
var queryOptions = observableQuery.options;
var readOptions = {
store: isOptimistic ? this.getDataWithOptimisticResults() : this.getApolloState().data,
query: document,
variables: variables,
config: this.reducerConfig,
previousResult: lastResult ? lastResult.data : undefined,
fragmentMatcherFunction: this.fragmentMatcher.match,
};
try {
var data = readQueryFromStore(readOptions);
return maybeDeepFreeze({ data: data, partial: false });
}
catch (e) {
return maybeDeepFreeze({ data: {}, partial: true });
}
};
QueryManager.prototype.getQueryWithPreviousResult = function (queryIdOrObservable, isOptimistic) {
if (isOptimistic === void 0) { isOptimistic = false; }
var observableQuery;
if (typeof queryIdOrObservable === 'string') {
if (!this.observableQueries[queryIdOrObservable]) {
throw new Error("ObservableQuery with this id doesn't exist: " + queryIdOrObservable);
}
observableQuery = this.observableQueries[queryIdOrObservable].observableQuery;
}
else {
observableQuery = queryIdOrObservable;
}
var _a = this.getQueryParts(observableQuery), variables = _a.variables, document = _a.document;
var data = this.getCurrentQueryResult(observableQuery, isOptimistic).data;
return {
previousResult: data,
variables: variables,
document: document,
};
};
QueryManager.prototype.getQueryParts = function (observableQuery) {
var queryOptions = observableQuery.options;
var transformedDoc = observableQuery.options.query;
if (this.addTypename) {
transformedDoc = addTypenameToDocument(transformedDoc);
}
return {
variables: queryOptions.variables,
document: transformedDoc,
};
};
QueryManager.prototype.transformQueryDocument = function (options) {
var queryDoc = options.query;
if (this.addTypename) {
queryDoc = addTypenameToDocument(queryDoc);
}
return {
queryDoc: queryDoc,
};
};
QueryManager.prototype.getExtraReducers = function () {
var _this = this;
return Object.keys(this.observableQueries).map(function (obsQueryId) {
var query = _this.observableQueries[obsQueryId].observableQuery;
var queryOptions = query.options;
if (queryOptions.reducer) {
return createStoreReducer(queryOptions.reducer, _this.addTypename ? addTypenameToDocument(queryOptions.query) : queryOptions.query, query.variables || {}, _this.reducerConfig);
}
return null;
}).filter(function (reducer) { return reducer !== null; });
};
QueryManager.prototype.fetchRequest = function (_a) {
var _this = this;
var requestId = _a.requestId, queryId = _a.queryId, document = _a.document, options = _a.options, fetchMoreForQueryId = _a.fetchMoreForQueryId;
var variables = options.variables;
var request = {
query: document,
variables: variables,
operationName: getOperationName(document),
};
var retPromise = new Promise(function (resolve, reject) {
_this.addFetchQueryPromise(requestId, retPromise, resolve, reject);
_this.deduplicator.query(request, _this.queryDeduplication)
.then(function (result) {
var extraReducers = _this.getExtraReducers();
_this.store.dispatch({
type: 'APOLLO_QUERY_RESULT',
document: document,
operationName: getOperationName(document),
result: result,
queryId: queryId,
requestId: requestId,
fetchMoreForQueryId: fetchMoreForQueryId,
extraReducers: extraReducers,
});
_this.removeFetchQueryPromise(requestId);
if (result.errors) {
throw new ApolloError({
graphQLErrors: result.errors,
});
}
return result;
}).then(function () {
var resultFromStore;
try {
resultFromStore = readQueryFromStore({
store: _this.getApolloState().data,
variables: variables,
query: document,
config: _this.reducerConfig,
fragmentMatcherFunction: _this.fragmentMatcher.match,
});
}
catch (e) { }
var reducerError = _this.getApolloState().reducerError;
if (reducerError && reducerError.queryId === queryId) {
return Promise.reject(reducerError.error);
}
_this.removeFetchQueryPromise(requestId);
resolve({ data: resultFromStore, loading: false, networkStatus: exports.NetworkStatus.ready, stale: false });
return Promise.resolve();
}).catch(function (error) {
reject(error);
});
});
return retPromise;
};
QueryManager.prototype.refetchQueryByName = function (queryName) {
var _this = this;
var refetchedQueries = this.queryIdsByName[queryName];
if (refetchedQueries === undefined) {
console.warn("Warning: unknown query with name " + queryName + " asked to refetch");
return;
}
else {
return Promise.all(refetchedQueries.map(function (queryId) { return _this.observableQueries[queryId].observableQuery.refetch(); }));
}
};
QueryManager.prototype.broadcastQueries = function () {
var _this = this;
var queries = this.getApolloState().queries;
Object.keys(this.queryListeners).forEach(function (queryId) {
var listeners = _this.queryListeners[queryId];
if (listeners) {
listeners.forEach(function (listener) {
if (listener) {
var queryStoreValue = queries[queryId];
listener(queryStoreValue);
}
});
}
});
};
QueryManager.prototype.generateRequestId = function () {
var requestId = this.idCounter;
this.idCounter++;
return requestId;
};
return QueryManager;
}());
var version = 'local';
var __assign$13 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var DEFAULT_REDUX_ROOT_KEY = 'apollo';
function defaultReduxRootSelector(state) {
return state[DEFAULT_REDUX_ROOT_KEY];
}
function defaultDataIdFromObject(result) {
if (result.__typename) {
if (result.id !== undefined) {
return result.__typename + ":" + result.id;
}
if (result._id !== undefined) {
return result.__typename + ":" + result._id;
}
}
return null;
}
var hasSuggestedDevtools = false;
var ApolloClient$1 = (function () {
function ApolloClient(options) {
if (options === void 0) { options = {}; }
var _this = this;
this.middleware = function () {
return function (store) {
_this.setStore(store);
return function (next) { return function (action) {
var previousApolloState = _this.queryManager.selectApolloState(store);
var returnValue = next(action);
var newApolloState = _this.queryManager.selectApolloState(store);
if (newApolloState !== previousApolloState) {
_this.queryManager.broadcastNewStore(store.getState());
}
if (_this.devToolsHookCb) {
_this.devToolsHookCb({
action: action,
state: _this.queryManager.getApolloState(),
dataWithOptimisticResults: _this.queryManager.getDataWithOptimisticResults(),
});
}
return returnValue;
}; };
};
};
var dataIdFromObject = options.dataIdFromObject;
var networkInterface = options.networkInterface, reduxRootSelector = options.reduxRootSelector, initialState = options.initialState, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, _c = options.addTypename, addTypename = _c === void 0 ? true : _c, customResolvers = options.customResolvers, connectToDevTools = options.connectToDevTools, fragmentMatcher = options.fragmentMatcher, _d = options.queryDeduplication, queryDeduplication = _d === void 0 ? true : _d;
if (typeof reduxRootSelector === 'function') {
this.reduxRootSelector = reduxRootSelector;
}
else if (typeof reduxRootSelector !== 'undefined') {
throw new Error('"reduxRootSelector" must be a function.');
}
if (typeof fragmentMatcher === 'undefined') {
this.fragmentMatcher = new HeuristicFragmentMatcher();
}
else {
this.fragmentMatcher = fragmentMatcher;
}
this.initialState = initialState ? initialState : {};
this.networkInterface = networkInterface ? networkInterface :
createNetworkInterface({ uri: '/graphql' });
this.addTypename = addTypename;
this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
this.dataId = dataIdFromObject = dataIdFromObject || defaultDataIdFromObject;
this.dataIdFromObject = this.dataId;
this.fieldWithArgs = storeKeyNameFromFieldNameAndArgs;
this.queryDeduplication = queryDeduplication;
this.ssrMode = ssrMode;
if (ssrForceFetchDelay) {
setTimeout(function () { return _this.disableNetworkFetches = false; }, ssrForceFetchDelay);
}
this.reducerConfig = {
dataIdFromObject: dataIdFromObject,
customResolvers: customResolvers,
addTypename: addTypename,
fragmentMatcher: this.fragmentMatcher.match,
};
this.watchQuery = this.watchQuery.bind(this);
this.query = this.query.bind(this);
this.mutate = this.mutate.bind(this);
this.setStore = this.setStore.bind(this);
this.resetStore = this.resetStore.bind(this);
var defaultConnectToDevTools = !isProduction() &&
typeof window !== 'undefined' && (!window.__APOLLO_CLIENT__);
if (typeof connectToDevTools === 'undefined' ? defaultConnectToDevTools : connectToDevTools) {
window.__APOLLO_CLIENT__ = this;
}
if (!hasSuggestedDevtools && !isProduction()) {
hasSuggestedDevtools = true;
if (typeof window !== 'undefined' && window.document && window.top === window.self) {
if (typeof window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
if (navigator.userAgent.indexOf('Chrome') > -1) {
console.debug('Download the Apollo DevTools ' +
'for a better development experience: ' +
'https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm');
}
}
}
}
this.version = version;
}
ApolloClient.prototype.watchQuery = function (options) {
this.initStore();
if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
options = __assign$13({}, options, { fetchPolicy: 'cache-first' });
}
return this.queryManager.watchQuery(options);
};
ApolloClient.prototype.query = function (options) {
this.initStore();
if (options.fetchPolicy === 'cache-and-network') {
throw new Error('cache-and-network fetchPolicy can only be used with watchQuery');
}
if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
options = __assign$13({}, options, { fetchPolicy: 'cache-first' });
}
return this.queryManager.query(options);
};
ApolloClient.prototype.mutate = function (options) {
this.initStore();
return this.queryManager.mutate(options);
};
ApolloClient.prototype.subscribe = function (options) {
this.initStore();
return this.queryManager.startGraphQLSubscription(options);
};
ApolloClient.prototype.readQuery = function (options) {
return this.initProxy().readQuery(options);
};
ApolloClient.prototype.readFragment = function (options) {
return this.initProxy().readFragment(options);
};
ApolloClient.prototype.writeQuery = function (options) {
return this.initProxy().writeQuery(options);
};
ApolloClient.prototype.writeFragment = function (options) {
return this.initProxy().writeFragment(options);
};
ApolloClient.prototype.reducer = function () {
return createApolloReducer(this.reducerConfig);
};
ApolloClient.prototype.__actionHookForDevTools = function (cb) {
this.devToolsHookCb = cb;
};
ApolloClient.prototype.initStore = function () {
var _this = this;
if (this.store) {
return;
}
if (this.reduxRootSelector) {
throw new Error('Cannot initialize the store because "reduxRootSelector" is provided. ' +
'reduxRootSelector should only be used when the store is created outside of the client. ' +
'This may lead to unexpected results when querying the store internally. ' +
"Please remove that option from ApolloClient constructor.");
}
this.setStore(createApolloStore({
reduxRootKey: DEFAULT_REDUX_ROOT_KEY,
initialState: this.initialState,
config: this.reducerConfig,
logger: function (store) { return function (next) { return function (action) {
var result = next(action);
if (_this.devToolsHookCb) {
_this.devToolsHookCb({
action: action,
state: _this.queryManager.getApolloState(),
dataWithOptimisticResults: _this.queryManager.getDataWithOptimisticResults(),
});
}
return result;
}; }; },
}));
};
ApolloClient.prototype.resetStore = function () {
return this.queryManager ? this.queryManager.resetStore() : null;
};
ApolloClient.prototype.getInitialState = function () {
this.initStore();
return this.queryManager.getInitialState();
};
ApolloClient.prototype.setStore = function (store) {
var reduxRootSelector;
if (this.reduxRootSelector) {
reduxRootSelector = this.reduxRootSelector;
}
else {
reduxRootSelector = defaultReduxRootSelector;
}
if (typeof reduxRootSelector(store.getState()) === 'undefined') {
throw new Error('Existing store does not use apolloReducer. Please make sure the store ' +
'is properly configured and "reduxRootSelector" is correctly specified.');
}
this.store = store;
this.queryManager = new QueryManager({
networkInterface: this.networkInterface,
reduxRootSelector: reduxRootSelector,
store: store,
addTypename: this.addTypename,
reducerConfig: this.reducerConfig,
queryDeduplication: this.queryDeduplication,
fragmentMatcher: this.fragmentMatcher,
ssrMode: this.ssrMode,
});
};
ApolloClient.prototype.initProxy = function () {
if (!this.proxy) {
this.initStore();
this.proxy = new ReduxDataProxy(this.store, this.reduxRootSelector || defaultReduxRootSelector, this.fragmentMatcher, this.reducerConfig);
}
return this.proxy;
};
return ApolloClient;
}());
exports.createNetworkInterface = createNetworkInterface;
exports.createBatchingNetworkInterface = createBatchingNetworkInterface;
exports.createApolloStore = createApolloStore;
exports.createApolloReducer = createApolloReducer;
exports.readQueryFromStore = readQueryFromStore;
exports.writeQueryToStore = writeQueryToStore;
exports.addTypenameToDocument = addTypenameToDocument;
exports.createFragmentMap = createFragmentMap;
exports.ApolloError = ApolloError;
exports.getQueryDefinition = getQueryDefinition;
exports.getMutationDefinition = getMutationDefinition;
exports.getFragmentDefinitions = getFragmentDefinitions;
exports.toIdValue = toIdValue;
exports.IntrospectionFragmentMatcher = IntrospectionFragmentMatcher;
exports.printAST = graphql_language_printer.print;
exports.HTTPFetchNetworkInterface = HTTPFetchNetworkInterface;
exports.HTTPBatchedNetworkInterface = HTTPBatchedNetworkInterface;
exports.ObservableQuery = ObservableQuery;
exports.ApolloClient = ApolloClient$1;
exports['default'] = ApolloClient$1;
Object.defineProperty(exports, '__esModule', { value: true });
})));
}).call(this,require('_process'))
},{"_process":66,"graphql-anywhere":7,"graphql/language/printer":27,"redux":60,"symbol-observable":62,"whatwg-fetch":65}],3:[function(require,module,exports){
(function (process,global){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version 4.1.0
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ES6Promise = factory());
}(this, (function () { 'use strict';
function objectOrFunction(x) {
return typeof x === 'function' || typeof x === 'object' && x !== null;
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = undefined;
if (!Array.isArray) {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
_isArray = Array.isArray;
}
var isArray = _isArray;
var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var r = require;
var vertx = r('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var _arguments = arguments;
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
(function () {
var callback = _arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
})();
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
_resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(16);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch (error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
_resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
_reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
_reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
_reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return _resolve(promise, value);
}, function (reason) {
return _reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$) {
if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$ === GET_THEN_ERROR) {
_reject(promise, GET_THEN_ERROR.error);
GET_THEN_ERROR.error = null;
} else if (then$$ === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$)) {
handleForeignThenable(promise, maybeThenable, then$$);
} else {
fulfill(promise, maybeThenable);
}
}
}
function _resolve(promise, value) {
if (promise === value) {
_reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function _reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = undefined,
callback = undefined,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = undefined,
error = undefined,
succeeded = undefined,
failed = undefined;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value.error = null;
} else {
succeeded = true;
}
if (promise === value) {
_reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
_resolve(promise, value);
} else if (failed) {
_reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
_reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
_resolve(promise, value);
}, function rejectPromise(reason) {
_reject(promise, reason);
});
} catch (e) {
_reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
_reject(this.promise, validationError());
}
}
function validationError() {
return new Error('Array Methods must be provided an Array');
};
Enumerator.prototype._enumerate = function () {
var length = this.length;
var _input = this._input;
for (var i = 0; this._state === PENDING && i < length; i++) {
this._eachEntry(_input[i], i);
}
};
Enumerator.prototype._eachEntry = function (entry, i) {
var c = this._instanceConstructor;
var resolve$$ = c.resolve;
if (resolve$$ === resolve) {
var _then = getThen(entry);
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, _then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$) {
return resolve$$(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$(entry), i);
}
};
Enumerator.prototype._settledAt = function (state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
_reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function (promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries) {
return new Enumerator(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
_reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function Promise(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
Promise.all = all;
Promise.race = race;
Promise.resolve = resolve;
Promise.reject = reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;
Promise.prototype = {
constructor: Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: then,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function _catch(onRejection) {
return this.then(null, onRejection);
}
};
function polyfill() {
var local = undefined;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise;
}
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;
return Promise;
})));
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":66}],4:[function(require,module,exports){
"use strict";
var storeUtils_1 = require("./storeUtils");
function getDirectiveInfoFromField(field, variables) {
if (field.directives && field.directives.length) {
var directiveObj_1 = {};
field.directives.forEach(function (directive) {
directiveObj_1[directive.name.value] = storeUtils_1.argumentsObjectFromField(directive, variables);
});
return directiveObj_1;
}
return null;
}
exports.getDirectiveInfoFromField = getDirectiveInfoFromField;
function shouldInclude(selection, variables) {
if (variables === void 0) { variables = {}; }
if (!selection.directives) {
return true;
}
var res = true;
selection.directives.some(function (directive) {
if (directive.name.value !== 'skip' && directive.name.value !== 'include') {
return;
}
var directiveArguments = directive.arguments;
var directiveName = directive.name.value;
if (directiveArguments.length !== 1) {
throw new Error("Incorrect number of arguments for the @" + directiveName + " directive.");
}
var ifArgument = directive.arguments[0];
if (!ifArgument.name || ifArgument.name.value !== 'if') {
throw new Error("Invalid argument for the @" + directiveName + " directive.");
}
var ifValue = directive.arguments[0].value;
var evaledValue = false;
if (!ifValue || ifValue.kind !== 'BooleanValue') {
if (ifValue.kind !== 'Variable') {
throw new Error("Argument for the @" + directiveName + " directive must be a variable or a bool ean value.");
}
else {
evaledValue = variables[ifValue.name.value];
if (evaledValue === undefined) {
throw new Error("Invalid variable referenced in @" + directiveName + " directive.");
}
}
}
else {
evaledValue = ifValue.value;
}
if (directiveName === 'skip') {
evaledValue = !evaledValue;
}
if (!evaledValue) {
res = false;
return true;
}
return false;
});
return res;
}
exports.shouldInclude = shouldInclude;
},{"./storeUtils":8}],5:[function(require,module,exports){
"use strict";
function checkDocument(doc) {
if (doc.kind !== 'Document') {
throw new Error("Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql");
}
var numOpDefinitions = doc.definitions.filter(function (definition) {
return definition.kind === 'OperationDefinition';
}).length;
if (numOpDefinitions > 1) {
throw new Error('Queries must have exactly one operation definition.');
}
}
function getFragmentDefinitions(doc) {
var fragmentDefinitions = doc.definitions.filter(function (definition) {
if (definition.kind === 'FragmentDefinition') {
return true;
}
else {
return false;
}
});
return fragmentDefinitions;
}
exports.getFragmentDefinitions = getFragmentDefinitions;
function createFragmentMap(fragments) {
if (fragments === void 0) { fragments = []; }
var symTable = {};
fragments.forEach(function (fragment) {
symTable[fragment.name.value] = fragment;
});
return symTable;
}
exports.createFragmentMap = createFragmentMap;
function getMainDefinition(queryDoc) {
checkDocument(queryDoc);
var fragmentDefinition;
for (var _i = 0, _a = queryDoc.definitions; _i < _a.length; _i++) {
var definition = _a[_i];
if (definition.kind === 'OperationDefinition') {
var operation = definition.operation;
if (operation === 'query' || operation === 'mutation' || operation === 'subscription') {
return definition;
}
}
if (definition.kind === 'FragmentDefinition' && !fragmentDefinition) {
fragmentDefinition = definition;
}
}
if (fragmentDefinition) {
return fragmentDefinition;
}
throw new Error('Expected a parsed GraphQL query with a query, mutation, subscription, or a fragment.');
}
exports.getMainDefinition = getMainDefinition;
},{}],6:[function(require,module,exports){
"use strict";
var getFromAST_1 = require("./getFromAST");
var directives_1 = require("./directives");
var storeUtils_1 = require("./storeUtils");
function graphql(resolver, document, rootValue, contextValue, variableValues, execOptions) {
if (execOptions === void 0) { execOptions = {}; }
var mainDefinition = getFromAST_1.getMainDefinition(document);
var fragments = getFromAST_1.getFragmentDefinitions(document);
var fragmentMap = getFromAST_1.createFragmentMap(fragments);
var resultMapper = execOptions.resultMapper;
var fragmentMatcher = execOptions.fragmentMatcher || (function () { return true; });
var execContext = {
fragmentMap: fragmentMap,
contextValue: contextValue,
variableValues: variableValues,
resultMapper: resultMapper,
resolver: resolver,
fragmentMatcher: fragmentMatcher,
};
return executeSelectionSet(mainDefinition.selectionSet, rootValue, execContext);
}
exports.graphql = graphql;
function executeSelectionSet(selectionSet, rootValue, execContext) {
var fragmentMap = execContext.fragmentMap, contextValue = execContext.contextValue, variables = execContext.variableValues;
var result = {};
selectionSet.selections.forEach(function (selection) {
if (!directives_1.shouldInclude(selection, variables)) {
return;
}
if (storeUtils_1.isField(selection)) {
var fieldResult = executeField(selection, rootValue, execContext);
var resultFieldKey = storeUtils_1.resultKeyNameFromField(selection);
if (fieldResult !== undefined) {
if (result[resultFieldKey] === undefined) {
result[resultFieldKey] = fieldResult;
}
else {
merge(result[resultFieldKey], fieldResult);
}
}
}
else {
var fragment = void 0;
if (storeUtils_1.isInlineFragment(selection)) {
fragment = selection;
}
else {
fragment = fragmentMap[selection.name.value];
if (!fragment) {
throw new Error("No fragment named " + selection.name.value);
}
}
var typeCondition = fragment.typeCondition.name.value;
if (execContext.fragmentMatcher(rootValue, typeCondition, contextValue)) {
var fragmentResult = executeSelectionSet(fragment.selectionSet, rootValue, execContext);
merge(result, fragmentResult);
}
}
});
if (execContext.resultMapper) {
return execContext.resultMapper(result, rootValue);
}
return result;
}
function executeField(field, rootValue, execContext) {
var variables = execContext.variableValues, contextValue = execContext.contextValue, resolver = execContext.resolver;
var fieldName = field.name.value;
var args = storeUtils_1.argumentsObjectFromField(field, variables);
var info = {
isLeaf: !field.selectionSet,
resultKey: storeUtils_1.resultKeyNameFromField(field),
directives: directives_1.getDirectiveInfoFromField(field, variables),
};
var result = resolver(fieldName, rootValue, args, contextValue, info);
if (!field.selectionSet) {
return result;
}
if (result == null) {
return result;
}
if (Array.isArray(result)) {
return executeSubSelectedArray(field, result, execContext);
}
return executeSelectionSet(field.selectionSet, result, execContext);
}
function executeSubSelectedArray(field, result, execContext) {
return result.map(function (item) {
if (item === null) {
return null;
}
if (Array.isArray(item)) {
return executeSubSelectedArray(field, item, execContext);
}
return executeSelectionSet(field.selectionSet, item, execContext);
});
}
function merge(dest, src) {
if (src === null ||
typeof src !== 'object') {
return src;
}
Object.keys(dest).forEach(function (destKey) {
if (src.hasOwnProperty(destKey)) {
merge(dest[destKey], src[destKey]);
}
});
Object.keys(src).forEach(function (srcKey) {
if (!dest.hasOwnProperty(srcKey)) {
dest[srcKey] = src[srcKey];
}
});
}
},{"./directives":4,"./getFromAST":5,"./storeUtils":8}],7:[function(require,module,exports){
"use strict";
var utilities_1 = require("./utilities");
exports.filter = utilities_1.filter;
exports.check = utilities_1.check;
exports.propType = utilities_1.propType;
var graphql_1 = require("./graphql");
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = graphql_1.graphql;
},{"./graphql":6,"./utilities":9}],8:[function(require,module,exports){
"use strict";
var SCALAR_TYPES = {
StringValue: true,
BooleanValue: true,
EnumValue: true,
};
function isScalarValue(value) {
return !!SCALAR_TYPES[value.kind];
}
var NUMBER_TYPES = {
IntValue: true,
FloatValue: true,
};
function isNumberValue(value) {
return NUMBER_TYPES[value.kind];
}
function isVariable(value) {
return value.kind === 'Variable';
}
function isObject(value) {
return value.kind === 'ObjectValue';
}
function isList(value) {
return value.kind === 'ListValue';
}
function valueToObjectRepresentation(argObj, name, value, variables) {
if (variables === void 0) { variables = {}; }
if (isNumberValue(value)) {
argObj[name.value] = Number(value.value);
}
else if (isScalarValue(value)) {
argObj[name.value] = value.value;
}
else if (isObject(value)) {
var nestedArgObj_1 = {};
value.fields.map(function (obj) { return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables); });
argObj[name.value] = nestedArgObj_1;
}
else if (isVariable(value)) {
var variableValue = variables[value.name.value];
argObj[name.value] = variableValue;
}
else if (isList(value)) {
argObj[name.value] = value.values.map(function (listValue) {
var nestedArgArrayObj = {};
valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables);
return nestedArgArrayObj[name.value];
});
}
else {
throw new Error("The inline argument \"" + name.value + "\" of kind \"" + value.kind + "\" is not supported. Use variables instead of inline arguments to overcome this limitation.");
}
}
function argumentsObjectFromField(field, variables) {
if (field.arguments && field.arguments.length) {
var argObj_1 = {};
field.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(argObj_1, name, value, variables);
});
return argObj_1;
}
return null;
}
exports.argumentsObjectFromField = argumentsObjectFromField;
function resultKeyNameFromField(field) {
return field.alias ?
field.alias.value :
field.name.value;
}
exports.resultKeyNameFromField = resultKeyNameFromField;
function isField(selection) {
return selection.kind === 'Field';
}
exports.isField = isField;
function isInlineFragment(selection) {
return selection.kind === 'InlineFragment';
}
exports.isInlineFragment = isInlineFragment;
function graphQLResultHasError(result) {
return result.errors && result.errors.length;
}
exports.graphQLResultHasError = graphQLResultHasError;
},{}],9:[function(require,module,exports){
"use strict";
var graphql_1 = require("./graphql");
function filter(doc, data) {
var resolver = function (fieldName, root, args, context, info) {
return root[info.resultKey];
};
return graphql_1.graphql(resolver, doc, data);
}
exports.filter = filter;
function check(doc, data) {
var resolver = function (fieldName, root, args, context, info) {
if (!{}.hasOwnProperty.call(root, info.resultKey)) {
throw new Error(info.resultKey + " missing on " + root);
}
return root[info.resultKey];
};
graphql_1.graphql(resolver, doc, data, {}, {}, {
fragmentMatcher: function () { return false; },
});
}
exports.check = check;
var ANONYMOUS = '<<anonymous>>';
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
PropTypeError.prototype = Error.prototype;
var reactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context',
};
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (props[propName] == null) {
var locationName = reactPropTypeLocationNames[location];
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError("The " + locationName + " `" + propFullName + "` is marked as required " +
("in `" + componentName + "`, but its value is `null`."));
}
return new PropTypeError("The " + locationName + " `" + propFullName + "` is marked as required in " +
("`" + componentName + "`, but its value is `undefined`."));
}
return null;
}
else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function propType(doc) {
return createChainableTypeChecker(function (props, propName) {
var prop = props[propName];
try {
check(doc, prop);
return null;
}
catch (e) {
return e;
}
});
}
exports.propType = propType;
},{"./graphql":6}],10:[function(require,module,exports){
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
typeof define === 'function' && define.amd ? define(factory) :
(factory());
}(this, (function () { 'use strict';
var parser = require('graphql/language/parser');
var buildASTSchema = require('graphql/utilities/buildASTSchema');
var parse = parser.parse;
var getDescription = buildASTSchema.getDescription;
// Strip insignificant whitespace
// Note that this could do a lot more, such as reorder fields etc.
function normalize(string) {
return string.replace(/[\s,]+/g, ' ').trim();
}
// A map docString -> graphql document
var docCache = {};
// A map fragmentName -> [normalized source]
var fragmentSourceMap = {};
function cacheKeyFromLoc(loc) {
return normalize(loc.source.body.substring(loc.start, loc.end));
}
// For testing.
function resetCaches() {
docCache = {};
fragmentSourceMap = {};
}
// Take a unstripped parsed document (query/mutation or even fragment), and
// check all fragment definitions, checking for name->source uniqueness.
// We also want to make sure only unique fragments exist in the document.
var printFragmentWarnings = true;
function processFragments(ast) {
var astFragmentMap = {};
var definitions = [];
for (var i = 0; i < ast.definitions.length; i++) {
var fragmentDefinition = ast.definitions[i];
if (fragmentDefinition.kind === 'FragmentDefinition') {
var fragmentName = fragmentDefinition.name.value;
var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc);
// We know something about this fragment
if (fragmentSourceMap.hasOwnProperty(fragmentName) && !fragmentSourceMap[fragmentName][sourceKey]) {
// this is a problem because the app developer is trying to register another fragment with
// the same name as one previously registered. So, we tell them about it.
if (printFragmentWarnings) {
console.warn("Warning: fragment with name " + fragmentName + " already exists.\n"
+ "graphql-tag enforces all fragment names across your application to be unique; read more about\n"
+ "this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names");
}
fragmentSourceMap[fragmentName][sourceKey] = true;
} else if (!fragmentSourceMap.hasOwnProperty(fragmentName)) {
fragmentSourceMap[fragmentName] = {};
fragmentSourceMap[fragmentName][sourceKey] = true;
}
if (!astFragmentMap[sourceKey]) {
astFragmentMap[sourceKey] = true;
definitions.push(fragmentDefinition);
}
} else {
definitions.push(fragmentDefinition);
}
}
ast.definitions = definitions;
return ast;
}
function disableFragmentWarnings() {
printFragmentWarnings = false;
}
function stripLoc(doc, removeLocAtThisLevel) {
var docType = Object.prototype.toString.call(doc);
if (docType === '[object Array]') {
return doc.map(function (d) {
return stripLoc(d, removeLocAtThisLevel);
});
}
if (!doc.description) {
var description = getDescription(doc);
if (description) {
doc.description = description;
}
}
if (docType !== '[object Object]') {
throw new Error('Unexpected input.');
}
// We don't want to remove the root loc field so we can use it
// for fragment substitution (see below)
if (removeLocAtThisLevel && doc.loc) {
delete doc.loc;
}
// https://github.com/apollographql/graphql-tag/issues/40
if (doc.loc) {
delete doc.loc.startToken;
delete doc.loc.endToken;
}
var keys = Object.keys(doc);
var key;
var value;
var valueType;
for (key in keys) {
if (keys.hasOwnProperty(key)) {
value = doc[keys[key]];
valueType = Object.prototype.toString.call(value);
if (valueType === '[object Object]' || valueType === '[object Array]') {
doc[keys[key]] = stripLoc(value, true);
}
}
}
return doc;
}
function parseDocument(doc) {
var cacheKey = normalize(doc);
if (docCache[cacheKey]) {
return docCache[cacheKey];
}
var parsed = parse(doc);
if (!parsed || parsed.kind !== 'Document') {
throw new Error('Not a valid GraphQL document.');
}
// check that all "new" fragments inside the documents are consistent with
// existing fragments of the same name
parsed = processFragments(parsed);
parsed = stripLoc(parsed, false);
docCache[cacheKey] = parsed;
return parsed;
}
// XXX This should eventually disallow arbitrary string interpolation, like Relay does
function gql(/* arguments */) {
var args = Array.prototype.slice.call(arguments);
var literals = args[0];
// We always get literals[0] and then matching post literals for each arg given
var result = (typeof(literals) === "string") ? literals : literals[0];
for (var i = 1; i < args.length; i++) {
if (args[i] && args[i].kind && args[i].kind === 'Document') {
result += args[i].loc.source.body;
} else {
result += args[i];
}
result += literals[i];
}
return parseDocument(result);
}
// Support typescript, which isn't as nice as Babel about default exports
gql.default = gql;
gql.resetCaches = resetCaches;
gql.disableFragmentWarnings = disableFragmentWarnings;
module.exports = gql;
})));
},{"graphql/language/parser":26,"graphql/utilities/buildASTSchema":37}],11:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GraphQLError = GraphQLError;
var _location = require('../language/location');
/**
* 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.
*/
function GraphQLError( // eslint-disable-line no-redeclare
message, nodes, source, positions, path, originalError) {
// Compute locations in the source for the given nodes/positions.
var _source = source;
if (!_source && nodes && nodes.length > 0) {
var node = nodes[0];
_source = node && node.loc && node.loc.source;
}
var _positions = positions;
if (!_positions && nodes) {
_positions = nodes.filter(function (node) {
return Boolean(node.loc);
}).map(function (node) {
return node.loc.start;
});
}
if (_positions && _positions.length === 0) {
_positions = undefined;
}
var _locations = void 0;
var _source2 = _source; // seems here Flow need a const to resolve type.
if (_source2 && _positions) {
_locations = _positions.map(function (pos) {
return (0, _location.getLocation)(_source2, pos);
});
}
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: true
},
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: true
},
nodes: {
value: nodes || undefined
},
source: {
value: _source || undefined
},
positions: {
value: _positions || undefined
},
originalError: {
value: originalError
}
});
// 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
});
}
}
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
GraphQLError.prototype = Object.create(Error.prototype, {
constructor: { value: GraphQLError },
name: { value: 'GraphQLError' }
});
},{"../language/location":25}],12:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.formatError = formatError;
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Given a GraphQLError, format it according to the rules described by the
* Response Format, Errors section of the GraphQL Specification.
*/
function formatError(error) {
(0, _invariant2.default)(error, 'Received null or undefined error.');
return {
message: error.message,
locations: error.locations,
path: error.path
};
}
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
},{"../jsutils/invariant":18}],13:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _GraphQLError = require('./GraphQLError');
Object.defineProperty(exports, 'GraphQLError', {
enumerable: true,
get: function get() {
return _GraphQLError.GraphQLError;
}
});
var _syntaxError = require('./syntaxError');
Object.defineProperty(exports, 'syntaxError', {
enumerable: true,
get: function get() {
return _syntaxError.syntaxError;
}
});
var _locatedError = require('./locatedError');
Object.defineProperty(exports, 'locatedError', {
enumerable: true,
get: function get() {
return _locatedError.locatedError;
}
});
var _formatError = require('./formatError');
Object.defineProperty(exports, 'formatError', {
enumerable: true,
get: function get() {
return _formatError.formatError;
}
});
},{"./GraphQLError":11,"./formatError":12,"./locatedError":14,"./syntaxError":15}],14:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.locatedError = locatedError;
var _GraphQLError = require('./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.
*/
function locatedError(originalError, nodes, path) {
// Note: this uses a brand-check to support GraphQL errors originating from
// other contexts.
if (originalError && originalError.path) {
return originalError;
}
var message = originalError ? originalError.message || String(originalError) : 'An unknown error occurred.';
return new _GraphQLError.GraphQLError(message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError);
}
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
},{"./GraphQLError":11}],15:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.syntaxError = syntaxError;
var _location = require('../language/location');
var _GraphQLError = require('./GraphQLError');
/**
* Produces a GraphQLError representing a syntax error, containing useful
* descriptive information about the syntax error's position in the source.
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function syntaxError(source, position, description) {
var location = (0, _location.getLocation)(source, position);
var error = new _GraphQLError.GraphQLError('Syntax Error ' + source.name + ' (' + location.line + ':' + location.column + ') ' + description + '\n\n' + highlightSourceAtLocation(source, location), undefined, source, [position]);
return error;
}
/**
* Render a helpful description of the location of the error in the GraphQL
* Source document.
*/
function highlightSourceAtLocation(source, location) {
var line = location.line;
var prevLineNum = (line - 1).toString();
var lineNum = line.toString();
var nextLineNum = (line + 1).toString();
var padLen = nextLineNum.length;
var lines = source.body.split(/\r\n|[\n\r]/g);
return (line >= 2 ? lpad(padLen, prevLineNum) + ': ' + lines[line - 2] + '\n' : '') + lpad(padLen, lineNum) + ': ' + lines[line - 1] + '\n' + Array(2 + padLen + location.column).join(' ') + '^\n' + (line < lines.length ? lpad(padLen, nextLineNum) + ': ' + lines[line] + '\n' : '');
}
function lpad(len, str) {
return Array(len - str.length + 1).join(' ') + str;
}
},{"../language/location":25,"./GraphQLError":11}],16:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getVariableValues = getVariableValues;
exports.getArgumentValues = getArgumentValues;
exports.getDirectiveValues = getDirectiveValues;
var _iterall = require('iterall');
var _error = require('../error');
var _find = require('../jsutils/find');
var _find2 = _interopRequireDefault(_find);
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _isNullish = require('../jsutils/isNullish');
var _isNullish2 = _interopRequireDefault(_isNullish);
var _isInvalid = require('../jsutils/isInvalid');
var _isInvalid2 = _interopRequireDefault(_isInvalid);
var _keyMap = require('../jsutils/keyMap');
var _keyMap2 = _interopRequireDefault(_keyMap);
var _typeFromAST = require('../utilities/typeFromAST');
var _valueFromAST = require('../utilities/valueFromAST');
var _isValidJSValue = require('../utilities/isValidJSValue');
var _isValidLiteralValue = require('../utilities/isValidLiteralValue');
var _kinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_kinds);
var _printer = require('../language/printer');
var _definition = require('../type/definition');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* 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.
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function getVariableValues(schema, varDefNodes, inputs) {
var coercedValues = Object.create(null);
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)) {
throw new _error.GraphQLError('Variable "$' + varName + '" expected value of type ' + ('"' + (0, _printer.print)(varDefNode.type) + '" which cannot be used as an input type.'), [varDefNode.type]);
}
var value = inputs[varName];
if ((0, _isInvalid2.default)(value)) {
var defaultValue = varDefNode.defaultValue;
if (defaultValue) {
coercedValues[varName] = (0, _valueFromAST.valueFromAST)(defaultValue, varType);
}
if (varType instanceof _definition.GraphQLNonNull) {
throw new _error.GraphQLError('Variable "$' + varName + '" of required type ' + ('"' + String(varType) + '" was not provided.'), [varDefNode]);
}
} else {
var errors = (0, _isValidJSValue.isValidJSValue)(value, varType);
if (errors.length) {
var message = errors ? '\n' + errors.join('\n') : '';
throw new _error.GraphQLError('Variable "$' + varName + '" got invalid value ' + (JSON.stringify(value) + '.' + message), [varDefNode]);
}
var coercedValue = coerceValue(varType, value);
(0, _invariant2.default)(!(0, _isInvalid2.default)(coercedValue), 'Should have reported error.');
coercedValues[varName] = coercedValue;
}
}
return coercedValues;
}
/**
* Prepares an object map of argument values given a list of argument
* definitions and list of argument AST nodes.
*/
function getArgumentValues(def, node, variableValues) {
var argDefs = def.args;
var argNodes = node.arguments;
if (!argDefs || !argNodes) {
return {};
}
var coercedValues = Object.create(null);
var argNodeMap = (0, _keyMap2.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 defaultValue = argDef.defaultValue;
if (!argumentNode) {
if (!(0, _isInvalid2.default)(defaultValue)) {
coercedValues[name] = defaultValue;
} else if (argType instanceof _definition.GraphQLNonNull) {
throw new _error.GraphQLError('Argument "' + name + '" of required type ' + ('"' + String(argType) + '" was not provided.'), [node]);
}
} else if (argumentNode.value.kind === Kind.VARIABLE) {
var variableName = argumentNode.value.name.value;
if (variableValues && !(0, _isInvalid2.default)(variableValues[variableName])) {
// Note: this does not check that this variable value 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 if (!(0, _isInvalid2.default)(defaultValue)) {
coercedValues[name] = defaultValue;
} else if (argType instanceof _definition.GraphQLNonNull) {
throw new _error.GraphQLError('Argument "' + name + '" of required type "' + String(argType) + '" was ' + ('provided the variable "$' + variableName + '" which was not provided ') + 'a runtime value.', [argumentNode.value]);
}
} else {
var valueNode = argumentNode.value;
var coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues);
if ((0, _isInvalid2.default)(coercedValue)) {
var errors = (0, _isValidLiteralValue.isValidLiteralValue)(argType, valueNode);
var message = errors ? '\n' + errors.join('\n') : '';
throw new _error.GraphQLError('Argument "' + name + '" got invalid value ' + (0, _printer.print)(valueNode) + '.' + message, [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.
*/
function getDirectiveValues(directiveDef, node, variableValues) {
var directiveNode = node.directives && (0, _find2.default)(node.directives, function (directive) {
return directive.name.value === directiveDef.name;
});
if (directiveNode) {
return getArgumentValues(directiveDef, directiveNode, variableValues);
}
}
/**
* Given a type and any value, return a runtime value coerced to match the type.
*/
function coerceValue(type, value) {
// Ensure flow knows that we treat function params as const.
var _value = value;
if ((0, _isInvalid2.default)(_value)) {
return; // Intentionally return no value.
}
if (type instanceof _definition.GraphQLNonNull) {
if (_value === null) {
return; // Intentionally return no value.
}
return coerceValue(type.ofType, _value);
}
if (_value === null) {
// Intentionally return the value null.
return null;
}
if (type instanceof _definition.GraphQLList) {
var itemType = type.ofType;
if ((0, _iterall.isCollection)(_value)) {
var coercedValues = [];
var valueIter = (0, _iterall.createIterator)(_value);
if (!valueIter) {
return; // Intentionally return no value.
}
var step = void 0;
while (!(step = valueIter.next()).done) {
var itemValue = coerceValue(itemType, step.value);
if ((0, _isInvalid2.default)(itemValue)) {
return; // Intentionally return no value.
}
coercedValues.push(itemValue);
}
return coercedValues;
}
var coercedValue = coerceValue(itemType, _value);
if ((0, _isInvalid2.default)(coercedValue)) {
return; // Intentionally return no value.
}
return [coerceValue(itemType, _value)];
}
if (type instanceof _definition.GraphQLInputObjectType) {
if (typeof _value !== 'object') {
return; // Intentionally return no value.
}
var coercedObj = Object.create(null);
var fields = type.getFields();
var fieldNames = Object.keys(fields);
for (var i = 0; i < fieldNames.length; i++) {
var fieldName = fieldNames[i];
var field = fields[fieldName];
if ((0, _isInvalid2.default)(_value[fieldName])) {
if (!(0, _isInvalid2.default)(field.defaultValue)) {
coercedObj[fieldName] = field.defaultValue;
} else if (field.type instanceof _definition.GraphQLNonNull) {
return; // Intentionally return no value.
}
continue;
}
var fieldValue = coerceValue(field.type, _value[fieldName]);
if ((0, _isInvalid2.default)(fieldValue)) {
return; // Intentionally return no value.
}
coercedObj[fieldName] = fieldValue;
}
return coercedObj;
}
(0, _invariant2.default)(type instanceof _definition.GraphQLScalarType || type instanceof _definition.GraphQLEnumType, 'Must be input type');
var parsed = type.parseValue(_value);
if ((0, _isNullish2.default)(parsed)) {
// null or invalid values represent a failure to parse correctly,
// in which case no value is returned.
return;
}
return parsed;
}
},{"../error":13,"../jsutils/find":17,"../jsutils/invariant":18,"../jsutils/isInvalid":19,"../jsutils/isNullish":20,"../jsutils/keyMap":21,"../language/kinds":23,"../language/printer":27,"../type/definition":30,"../utilities/isValidJSValue":38,"../utilities/isValidLiteralValue":39,"../utilities/typeFromAST":41,"../utilities/valueFromAST":42,"iterall":44}],17:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = find;
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function find(list, predicate) {
for (var i = 0; i < list.length; i++) {
if (predicate(list[i])) {
return list[i];
}
}
}
},{}],18:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = invariant;
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function invariant(condition, message) {
if (!condition) {
throw new Error(message);
}
}
},{}],19:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isInvalid;
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/**
* Returns true if a value is undefined, or NaN.
*/
function isInvalid(value) {
return value === undefined || value !== value;
}
},{}],20:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isNullish;
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/**
* Returns true if a value is null, undefined, or NaN.
*/
function isNullish(value) {
return value === null || value === undefined || value !== value;
}
},{}],21:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = keyMap;
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/**
* 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));
}
},{}],22:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = keyValMap;
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/**
* 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));
}
},{}],23:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
// Name
var NAME = exports.NAME = 'Name';
// Document
var DOCUMENT = exports.DOCUMENT = 'Document';
var OPERATION_DEFINITION = exports.OPERATION_DEFINITION = 'OperationDefinition';
var VARIABLE_DEFINITION = exports.VARIABLE_DEFINITION = 'VariableDefinition';
var VARIABLE = exports.VARIABLE = 'Variable';
var SELECTION_SET = exports.SELECTION_SET = 'SelectionSet';
var FIELD = exports.FIELD = 'Field';
var ARGUMENT = exports.ARGUMENT = 'Argument';
// Fragments
var FRAGMENT_SPREAD = exports.FRAGMENT_SPREAD = 'FragmentSpread';
var INLINE_FRAGMENT = exports.INLINE_FRAGMENT = 'InlineFragment';
var FRAGMENT_DEFINITION = exports.FRAGMENT_DEFINITION = 'FragmentDefinition';
// Values
var INT = exports.INT = 'IntValue';
var FLOAT = exports.FLOAT = 'FloatValue';
var STRING = exports.STRING = 'StringValue';
var BOOLEAN = exports.BOOLEAN = 'BooleanValue';
var NULL = exports.NULL = 'NullValue';
var ENUM = exports.ENUM = 'EnumValue';
var LIST = exports.LIST = 'ListValue';
var OBJECT = exports.OBJECT = 'ObjectValue';
var OBJECT_FIELD = exports.OBJECT_FIELD = 'ObjectField';
// Directives
var DIRECTIVE = exports.DIRECTIVE = 'Directive';
// Types
var NAMED_TYPE = exports.NAMED_TYPE = 'NamedType';
var LIST_TYPE = exports.LIST_TYPE = 'ListType';
var NON_NULL_TYPE = exports.NON_NULL_TYPE = 'NonNullType';
// Type System Definitions
var SCHEMA_DEFINITION = exports.SCHEMA_DEFINITION = 'SchemaDefinition';
var OPERATION_TYPE_DEFINITION = exports.OPERATION_TYPE_DEFINITION = 'OperationTypeDefinition';
// Type Definitions
var SCALAR_TYPE_DEFINITION = exports.SCALAR_TYPE_DEFINITION = 'ScalarTypeDefinition';
var OBJECT_TYPE_DEFINITION = exports.OBJECT_TYPE_DEFINITION = 'ObjectTypeDefinition';
var FIELD_DEFINITION = exports.FIELD_DEFINITION = 'FieldDefinition';
var INPUT_VALUE_DEFINITION = exports.INPUT_VALUE_DEFINITION = 'InputValueDefinition';
var INTERFACE_TYPE_DEFINITION = exports.INTERFACE_TYPE_DEFINITION = 'InterfaceTypeDefinition';
var UNION_TYPE_DEFINITION = exports.UNION_TYPE_DEFINITION = 'UnionTypeDefinition';
var ENUM_TYPE_DEFINITION = exports.ENUM_TYPE_DEFINITION = 'EnumTypeDefinition';
var ENUM_VALUE_DEFINITION = exports.ENUM_VALUE_DEFINITION = 'EnumValueDefinition';
var INPUT_OBJECT_TYPE_DEFINITION = exports.INPUT_OBJECT_TYPE_DEFINITION = 'InputObjectTypeDefinition';
// Type Extensions
var TYPE_EXTENSION_DEFINITION = exports.TYPE_EXTENSION_DEFINITION = 'TypeExtensionDefinition';
// Directive Definitions
var DIRECTIVE_DEFINITION = exports.DIRECTIVE_DEFINITION = 'DirectiveDefinition';
},{}],24:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TokenKind = undefined;
exports.createLexer = createLexer;
exports.getTokenDesc = getTokenDesc;
var _error = require('../error');
/**
* Given a Source object, this returns a Lexer for that source.
* A Lexer is a stateful stream generator in that every time
* it is advanced, it returns the next token in the Source. Assuming the
* source lexes, the final Token emitted by the lexer will be of kind
* EOF, after which the lexer will repeatedly return the same EOF token
* whenever called.
*/
function createLexer(source, options) {
var startOfFileToken = new Tok(SOF, 0, 0, 0, 0, null);
var lexer = {
source: source,
options: options,
lastToken: startOfFileToken,
token: startOfFileToken,
line: 1,
lineStart: 0,
advance: advanceLexer
};
return lexer;
} /* /
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function advanceLexer() {
var token = this.lastToken = this.token;
if (token.kind !== EOF) {
do {
token = token.next = readToken(this, token);
} while (token.kind === COMMENT);
this.token = token;
}
return token;
}
/**
* The return type of createLexer.
*/
// Each kind of token.
var SOF = '<SOF>';
var EOF = '<EOF>';
var BANG = '!';
var DOLLAR = '$';
var PAREN_L = '(';
var PAREN_R = ')';
var SPREAD = '...';
var COLON = ':';
var EQUALS = '=';
var AT = '@';
var BRACKET_L = '[';
var BRACKET_R = ']';
var BRACE_L = '{';
var PIPE = '|';
var BRACE_R = '}';
var NAME = 'Name';
var INT = 'Int';
var FLOAT = 'Float';
var STRING = 'String';
var COMMENT = 'Comment';
/**
* An exported enum describing the different kinds of tokens that the
* lexer emits.
*/
var TokenKind = exports.TokenKind = {
SOF: SOF,
EOF: EOF,
BANG: BANG,
DOLLAR: DOLLAR,
PAREN_L: PAREN_L,
PAREN_R: PAREN_R,
SPREAD: SPREAD,
COLON: COLON,
EQUALS: EQUALS,
AT: AT,
BRACKET_L: BRACKET_L,
BRACKET_R: BRACKET_R,
BRACE_L: BRACE_L,
PIPE: PIPE,
BRACE_R: BRACE_R,
NAME: NAME,
INT: INT,
FLOAT: FLOAT,
STRING: STRING,
COMMENT: COMMENT
};
/**
* A helper function to describe a token as a string for debugging
*/
function getTokenDesc(token) {
var value = token.value;
return value ? token.kind + ' "' + value + '"' : token.kind;
}
var charCodeAt = String.prototype.charCodeAt;
var slice = String.prototype.slice;
/**
* Helper function for constructing the Token object.
*/
function Tok(kind, start, end, line, column, prev, value) {
this.kind = kind;
this.start = start;
this.end = end;
this.line = line;
this.column = column;
this.value = value;
this.prev = prev;
this.next = null;
}
// Print a simplified form when appearing in JSON/util.inspect.
Tok.prototype.toJSON = Tok.prototype.inspect = function toJSON() {
return {
kind: this.kind,
value: this.value,
line: this.line,
column: this.column
};
};
function printCharCode(code) {
return (
// NaN/undefined represents access beyond the end of the file.
isNaN(code) ? EOF :
// Trust JSON for ASCII.
code < 0x007F ? JSON.stringify(String.fromCharCode(code)) :
// Otherwise print the escaped form.
'"\\u' + ('00' + code.toString(16).toUpperCase()).slice(-4) + '"'
);
}
/**
* Gets the next token from the source starting at the given position.
*
* This skips over whitespace and comments until it finds the next lexable
* token, then lexes punctuators immediately or calls the appropriate helper
* function for more complicated tokens.
*/
function readToken(lexer, prev) {
var source = lexer.source;
var body = source.body;
var bodyLength = body.length;
var position = positionAfterWhitespace(body, prev.end, lexer);
var line = lexer.line;
var col = 1 + position - lexer.lineStart;
if (position >= bodyLength) {
return new Tok(EOF, bodyLength, bodyLength, line, col, prev);
}
var code = charCodeAt.call(body, position);
// SourceCharacter
if (code < 0x0020 && code !== 0x0009 && code !== 0x000A && code !== 0x000D) {
throw (0, _error.syntaxError)(source, position, 'Cannot contain the invalid character ' + printCharCode(code) + '.');
}
switch (code) {
// !
case 33:
return new Tok(BANG, position, position + 1, line, col, prev);
// #
case 35:
return readComment(source, position, line, col, prev);
// $
case 36:
return new Tok(DOLLAR, position, position + 1, line, col, prev);
// (
case 40:
return new Tok(PAREN_L, position, position + 1, line, col, prev);
// )
case 41:
return new Tok(PAREN_R, position, position + 1, line, col, prev);
// .
case 46:
if (charCodeAt.call(body, position + 1) === 46 && charCodeAt.call(body, position + 2) === 46) {
return new Tok(SPREAD, position, position + 3, line, col, prev);
}
break;
// :
case 58:
return new Tok(COLON, position, position + 1, line, col, prev);
// =
case 61:
return new Tok(EQUALS, position, position + 1, line, col, prev);
// @
case 64:
return new Tok(AT, position, position + 1, line, col, prev);
// [
case 91:
return new Tok(BRACKET_L, position, position + 1, line, col, prev);
// ]
case 93:
return new Tok(BRACKET_R, position, position + 1, line, col, prev);
// {
case 123:
return new Tok(BRACE_L, position, position + 1, line, col, prev);
// |
case 124:
return new Tok(PIPE, position, position + 1, line, col, prev);
// }
case 125:
return new Tok(BRACE_R, position, position + 1, line, col, prev);
// A-Z _ a-z
case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:
case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:
case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:
case 89:case 90:
case 95:
case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:
case 105:case 106:case 107:case 108:case 109:case 110:case 111:
case 112:case 113:case 114:case 115:case 116:case 117:case 118:
case 119:case 120:case 121:case 122:
return readName(source, position, line, col, prev);
// - 0-9
case 45:
case 48:case 49:case 50:case 51:case 52:
case 53:case 54:case 55:case 56:case 57:
return readNumber(source, position, code, line, col, prev);
// "
case 34:
return readString(source, position, line, col, prev);
}
throw (0, _error.syntaxError)(source, position, unexpectedCharacterMessage(code));
}
/**
* Report a message that an unexpected character was encountered.
*/
function unexpectedCharacterMessage(code) {
if (code === 39) {
// '
return 'Unexpected single quote character (\'), did you mean to use ' + 'a double quote (")?';
}
return 'Cannot parse the unexpected character ' + printCharCode(code) + '.';
}
/**
* Reads from body starting at startPosition until it finds a non-whitespace
* or commented character, then returns the position of that character for
* lexing.
*/
function positionAfterWhitespace(body, startPosition, lexer) {
var bodyLength = body.length;
var position = startPosition;
while (position < bodyLength) {
var code = charCodeAt.call(body, position);
// tab | space | comma | BOM
if (code === 9 || code === 32 || code === 44 || code === 0xFEFF) {
++position;
} else if (code === 10) {
// new line
++position;
++lexer.line;
lexer.lineStart = position;
} else if (code === 13) {
// carriage return
if (charCodeAt.call(body, position + 1) === 10) {
position += 2;
} else {
++position;
}
++lexer.line;
lexer.lineStart = position;
} else {
break;
}
}
return position;
}
/**
* Reads a comment token from the source file.
*
* #[\u0009\u0020-\uFFFF]*
*/
function readComment(source, start, line, col, prev) {
var body = source.body;
var code = void 0;
var position = start;
do {
code = charCodeAt.call(body, ++position);
} while (code !== null && (
// SourceCharacter but not LineTerminator
code > 0x001F || code === 0x0009));
return new Tok(COMMENT, start, position, line, col, prev, slice.call(body, start + 1, position));
}
/**
* Reads a number token from the source file, either a float
* or an int depending on whether a decimal point appears.
*
* Int: -?(0|[1-9][0-9]*)
* Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?
*/
function readNumber(source, start, firstCode, line, col, prev) {
var body = source.body;
var code = firstCode;
var position = start;
var isFloat = false;
if (code === 45) {
// -
code = charCodeAt.call(body, ++position);
}
if (code === 48) {
// 0
code = charCodeAt.call(body, ++position);
if (code >= 48 && code <= 57) {
throw (0, _error.syntaxError)(source, position, 'Invalid number, unexpected digit after 0: ' + printCharCode(code) + '.');
}
} else {
position = readDigits(source, position, code);
code = charCodeAt.call(body, position);
}
if (code === 46) {
// .
isFloat = true;
code = charCodeAt.call(body, ++position);
position = readDigits(source, position, code);
code = charCodeAt.call(body, position);
}
if (code === 69 || code === 101) {
// E e
isFloat = true;
code = charCodeAt.call(body, ++position);
if (code === 43 || code === 45) {
// + -
code = charCodeAt.call(body, ++position);
}
position = readDigits(source, position, code);
}
return new Tok(isFloat ? FLOAT : INT, start, position, line, col, prev, slice.call(body, start, position));
}
/**
* Returns the new position in the source after reading digits.
*/
function readDigits(source, start, firstCode) {
var body = source.body;
var position = start;
var code = firstCode;
if (code >= 48 && code <= 57) {
// 0 - 9
do {
code = charCodeAt.call(body, ++position);
} while (code >= 48 && code <= 57); // 0 - 9
return position;
}
throw (0, _error.syntaxError)(source, position, 'Invalid number, expected digit but got: ' + printCharCode(code) + '.');
}
/**
* Reads a string token from the source file.
*
* "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"
*/
function readString(source, start, line, col, prev) {
var body = source.body;
var position = start + 1;
var chunkStart = position;
var code = 0;
var value = '';
while (position < body.length && (code = charCodeAt.call(body, position)) !== null &&
// not LineTerminator
code !== 0x000A && code !== 0x000D &&
// not Quote (")
code !== 34) {
// SourceCharacter
if (code < 0x0020 && code !== 0x0009) {
throw (0, _error.syntaxError)(source, position, 'Invalid character within String: ' + printCharCode(code) + '.');
}
++position;
if (code === 92) {
// \
value += slice.call(body, chunkStart, position - 1);
code = charCodeAt.call(body, position);
switch (code) {
case 34:
value += '"';break;
case 47:
value += '/';break;
case 92:
value += '\\';break;
case 98:
value += '\b';break;
case 102:
value += '\f';break;
case 110:
value += '\n';break;
case 114:
value += '\r';break;
case 116:
value += '\t';break;
case 117:
// u
var charCode = uniCharCode(charCodeAt.call(body, position + 1), charCodeAt.call(body, position + 2), charCodeAt.call(body, position + 3), charCodeAt.call(body, position + 4));
if (charCode < 0) {
throw (0, _error.syntaxError)(source, position, 'Invalid character escape sequence: ' + ('\\u' + body.slice(position + 1, position + 5) + '.'));
}
value += String.fromCharCode(charCode);
position += 4;
break;
default:
throw (0, _error.syntaxError)(source, position, 'Invalid character escape sequence: \\' + String.fromCharCode(code) + '.');
}
++position;
chunkStart = position;
}
}
if (code !== 34) {
// quote (")
throw (0, _error.syntaxError)(source, position, 'Unterminated string.');
}
value += slice.call(body, chunkStart, position);
return new Tok(STRING, start, position + 1, line, col, prev, value);
}
/**
* Converts four hexidecimal chars to the integer that the
* string represents. For example, uniCharCode('0','0','0','f')
* will return 15, and uniCharCode('0','0','f','f') returns 255.
*
* Returns a negative number on error, if a char was invalid.
*
* This is implemented by noting that char2hex() returns -1 on error,
* which means the result of ORing the char2hex() will also be negative.
*/
function uniCharCode(a, b, c, d) {
return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);
}
/**
* Converts a hex character to its integer value.
* '0' becomes 0, '9' becomes 9
* 'A' becomes 10, 'F' becomes 15
* 'a' becomes 10, 'f' becomes 15
*
* Returns -1 on error.
*/
function char2hex(a) {
return a >= 48 && a <= 57 ? a - 48 : // 0-9
a >= 65 && a <= 70 ? a - 55 : // A-F
a >= 97 && a <= 102 ? a - 87 : // a-f
-1;
}
/**
* Reads an alphanumeric + underscore name from the source.
*
* [_A-Za-z][_0-9A-Za-z]*
*/
function readName(source, position, line, col, prev) {
var body = source.body;
var bodyLength = body.length;
var end = position + 1;
var code = 0;
while (end !== bodyLength && (code = charCodeAt.call(body, end)) !== null && (code === 95 || // _
code >= 48 && code <= 57 || // 0-9
code >= 65 && code <= 90 || // A-Z
code >= 97 && code <= 122 // a-z
)) {
++end;
}
return new Tok(NAME, position, end, line, col, prev, slice.call(body, position, end));
}
},{"../error":13}],25:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getLocation = getLocation;
/**
* Takes a Source and a UTF-8 character offset, and returns the corresponding
* line and column as a SourceLocation.
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function getLocation(source, position) {
var lineRegexp = /\r\n|[\n\r]/g;
var line = 1;
var column = position + 1;
var match = void 0;
while ((match = lineRegexp.exec(source.body)) && match.index < position) {
line += 1;
column = position + 1 - (match.index + match[0].length);
}
return { line: line, column: column };
}
/**
* Represents a location in a Source.
*/
},{}],26:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parse = parse;
exports.parseValue = parseValue;
exports.parseType = parseType;
exports.parseConstValue = parseConstValue;
exports.parseTypeReference = parseTypeReference;
exports.parseNamedType = parseNamedType;
var _source = require('./source');
var _error = require('../error');
var _lexer = require('./lexer');
var _kinds = require('./kinds');
/**
* Given a GraphQL source, parses it into a Document.
* Throws GraphQLError if a syntax error is encountered.
*/
/**
* Configuration options to control parser behavior
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function parse(source, options) {
var sourceObj = typeof source === 'string' ? new _source.Source(source) : source;
if (!(sourceObj instanceof _source.Source)) {
throw new TypeError('Must provide Source. Received: ' + String(sourceObj));
}
var lexer = (0, _lexer.createLexer)(sourceObj, options || {});
return parseDocument(lexer);
}
/**
* Given a string containing a GraphQL value (ex. `[42]`), parse the AST for
* that value.
* Throws GraphQLError if a syntax error is encountered.
*
* This is useful within tools that operate upon GraphQL Values directly and
* in isolation of complete GraphQL documents.
*
* Consider providing the results to the utility function: valueFromAST().
*/
function parseValue(source, options) {
var sourceObj = typeof source === 'string' ? new _source.Source(source) : source;
var lexer = (0, _lexer.createLexer)(sourceObj, options || {});
expect(lexer, _lexer.TokenKind.SOF);
var value = parseValueLiteral(lexer, false);
expect(lexer, _lexer.TokenKind.EOF);
return value;
}
/**
* Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for
* that type.
* Throws GraphQLError if a syntax error is encountered.
*
* This is useful within tools that operate upon GraphQL Types directly and
* in isolation of complete GraphQL documents.
*
* Consider providing the results to the utility function: typeFromAST().
*/
function parseType(source, options) {
var sourceObj = typeof source === 'string' ? new _source.Source(source) : source;
var lexer = (0, _lexer.createLexer)(sourceObj, options || {});
expect(lexer, _lexer.TokenKind.SOF);
var type = parseTypeReference(lexer);
expect(lexer, _lexer.TokenKind.EOF);
return type;
}
/**
* Converts a name lex token into a name parse node.
*/
function parseName(lexer) {
var token = expect(lexer, _lexer.TokenKind.NAME);
return {
kind: _kinds.NAME,
value: token.value,
loc: loc(lexer, token)
};
}
// Implements the parsing rules in the Document section.
/**
* Document : Definition+
*/
function parseDocument(lexer) {
var start = lexer.token;
expect(lexer, _lexer.TokenKind.SOF);
var definitions = [];
do {
definitions.push(parseDefinition(lexer));
} while (!skip(lexer, _lexer.TokenKind.EOF));
return {
kind: _kinds.DOCUMENT,
definitions: definitions,
loc: loc(lexer, start)
};
}
/**
* Definition :
* - OperationDefinition
* - FragmentDefinition
* - TypeSystemDefinition
*/
function parseDefinition(lexer) {
if (peek(lexer, _lexer.TokenKind.BRACE_L)) {
return parseOperationDefinition(lexer);
}
if (peek(lexer, _lexer.TokenKind.NAME)) {
switch (lexer.token.value) {
// Note: subscription is an experimental non-spec addition.
case 'query':
case 'mutation':
case 'subscription':
return parseOperationDefinition(lexer);
case 'fragment':
return parseFragmentDefinition(lexer);
// Note: the Type System IDL is an experimental non-spec addition.
case 'schema':
case 'scalar':
case 'type':
case 'interface':
case 'union':
case 'enum':
case 'input':
case 'extend':
case 'directive':
return parseTypeSystemDefinition(lexer);
}
}
throw unexpected(lexer);
}
// Implements the parsing rules in the Operations section.
/**
* OperationDefinition :
* - SelectionSet
* - OperationType Name? VariableDefinitions? Directives? SelectionSet
*/
function parseOperationDefinition(lexer) {
var start = lexer.token;
if (peek(lexer, _lexer.TokenKind.BRACE_L)) {
return {
kind: _kinds.OPERATION_DEFINITION,
operation: 'query',
name: null,
variableDefinitions: null,
directives: [],
selectionSet: parseSelectionSet(lexer),
loc: loc(lexer, start)
};
}
var operation = parseOperationType(lexer);
var name = void 0;
if (peek(lexer, _lexer.TokenKind.NAME)) {
name = parseName(lexer);
}
return {
kind: _kinds.OPERATION_DEFINITION,
operation: operation,
name: name,
variableDefinitions: parseVariableDefinitions(lexer),
directives: parseDirectives(lexer),
selectionSet: parseSelectionSet(lexer),
loc: loc(lexer, start)
};
}
/**
* OperationType : one of query mutation subscription
*/
function parseOperationType(lexer) {
var operationToken = expect(lexer, _lexer.TokenKind.NAME);
switch (operationToken.value) {
case 'query':
return 'query';
case 'mutation':
return 'mutation';
// Note: subscription is an experimental non-spec addition.
case 'subscription':
return 'subscription';
}
throw unexpected(lexer, operationToken);
}
/**
* VariableDefinitions : ( VariableDefinition+ )
*/
function parseVariableDefinitions(lexer) {
return peek(lexer, _lexer.TokenKind.PAREN_L) ? many(lexer, _lexer.TokenKind.PAREN_L, parseVariableDefinition, _lexer.TokenKind.PAREN_R) : [];
}
/**
* VariableDefinition : Variable : Type DefaultValue?
*/
function parseVariableDefinition(lexer) {
var start = lexer.token;
return {
kind: _kinds.VARIABLE_DEFINITION,
variable: parseVariable(lexer),
type: (expect(lexer, _lexer.TokenKind.COLON), parseTypeReference(lexer)),
defaultValue: skip(lexer, _lexer.TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : null,
loc: loc(lexer, start)
};
}
/**
* Variable : $ Name
*/
function parseVariable(lexer) {
var start = lexer.token;
expect(lexer, _lexer.TokenKind.DOLLAR);
return {
kind: _kinds.VARIABLE,
name: parseName(lexer),
loc: loc(lexer, start)
};
}
/**
* SelectionSet : { Selection+ }
*/
function parseSelectionSet(lexer) {
var start = lexer.token;
return {
kind: _kinds.SELECTION_SET,
selections: many(lexer, _lexer.TokenKind.BRACE_L, parseSelection, _lexer.TokenKind.BRACE_R),
loc: loc(lexer, start)
};
}
/**
* Selection :
* - Field
* - FragmentSpread
* - InlineFragment
*/
function parseSelection(lexer) {
return peek(lexer, _lexer.TokenKind.SPREAD) ? parseFragment(lexer) : parseField(lexer);
}
/**
* Field : Alias? Name Arguments? Directives? SelectionSet?
*
* Alias : Name :
*/
function parseField(lexer) {
var start = lexer.token;
var nameOrAlias = parseName(lexer);
var alias = void 0;
var name = void 0;
if (skip(lexer, _lexer.TokenKind.COLON)) {
alias = nameOrAlias;
name = parseName(lexer);
} else {
alias = null;
name = nameOrAlias;
}
return {
kind: _kinds.FIELD,
alias: alias,
name: name,
arguments: parseArguments(lexer),
directives: parseDirectives(lexer),
selectionSet: peek(lexer, _lexer.TokenKind.BRACE_L) ? parseSelectionSet(lexer) : null,
loc: loc(lexer, start)
};
}
/**
* Arguments : ( Argument+ )
*/
function parseArguments(lexer) {
return peek(lexer, _lexer.TokenKind.PAREN_L) ? many(lexer, _lexer.TokenKind.PAREN_L, parseArgument, _lexer.TokenKind.PAREN_R) : [];
}
/**
* Argument : Name : Value
*/
function parseArgument(lexer) {
var start = lexer.token;
return {
kind: _kinds.ARGUMENT,
name: parseName(lexer),
value: (expect(lexer, _lexer.TokenKind.COLON), parseValueLiteral(lexer, false)),
loc: loc(lexer, start)
};
}
// Implements the parsing rules in the Fragments section.
/**
* Corresponds to both FragmentSpread and InlineFragment in the spec.
*
* FragmentSpread : ... FragmentName Directives?
*
* InlineFragment : ... TypeCondition? Directives? SelectionSet
*/
function parseFragment(lexer) {
var start = lexer.token;
expect(lexer, _lexer.TokenKind.SPREAD);
if (peek(lexer, _lexer.TokenKind.NAME) && lexer.token.value !== 'on') {
return {
kind: _kinds.FRAGMENT_SPREAD,
name: parseFragmentName(lexer),
directives: parseDirectives(lexer),
loc: loc(lexer, start)
};
}
var typeCondition = null;
if (lexer.token.value === 'on') {
lexer.advance();
typeCondition = parseNamedType(lexer);
}
return {
kind: _kinds.INLINE_FRAGMENT,
typeCondition: typeCondition,
directives: parseDirectives(lexer),
selectionSet: parseSelectionSet(lexer),
loc: loc(lexer, start)
};
}
/**
* FragmentDefinition :
* - fragment FragmentName on TypeCondition Directives? SelectionSet
*
* TypeCondition : NamedType
*/
function parseFragmentDefinition(lexer) {
var start = lexer.token;
expectKeyword(lexer, 'fragment');
return {
kind: _kinds.FRAGMENT_DEFINITION,
name: parseFragmentName(lexer),
typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)),
directives: parseDirectives(lexer),
selectionSet: parseSelectionSet(lexer),
loc: loc(lexer, start)
};
}
/**
* FragmentName : Name but not `on`
*/
function parseFragmentName(lexer) {
if (lexer.token.value === 'on') {
throw unexpected(lexer);
}
return parseName(lexer);
}
// Implements the parsing rules in the Values section.
/**
* Value[Const] :
* - [~Const] Variable
* - IntValue
* - FloatValue
* - StringValue
* - BooleanValue
* - NullValue
* - EnumValue
* - ListValue[?Const]
* - ObjectValue[?Const]
*
* BooleanValue : one of `true` `false`
*
* NullValue : `null`
*
* EnumValue : Name but not `true`, `false` or `null`
*/
function parseValueLiteral(lexer, isConst) {
var token = lexer.token;
switch (token.kind) {
case _lexer.TokenKind.BRACKET_L:
return parseList(lexer, isConst);
case _lexer.TokenKind.BRACE_L:
return parseObject(lexer, isConst);
case _lexer.TokenKind.INT:
lexer.advance();
return {
kind: _kinds.INT,
value: token.value,
loc: loc(lexer, token)
};
case _lexer.TokenKind.FLOAT:
lexer.advance();
return {
kind: _kinds.FLOAT,
value: token.value,
loc: loc(lexer, token)
};
case _lexer.TokenKind.STRING:
lexer.advance();
return {
kind: _kinds.STRING,
value: token.value,
loc: loc(lexer, token)
};
case _lexer.TokenKind.NAME:
if (token.value === 'true' || token.value === 'false') {
lexer.advance();
return {
kind: _kinds.BOOLEAN,
value: token.value === 'true',
loc: loc(lexer, token)
};
} else if (token.value === 'null') {
lexer.advance();
return {
kind: _kinds.NULL,
loc: loc(lexer, token)
};
}
lexer.advance();
return {
kind: _kinds.ENUM,
value: token.value,
loc: loc(lexer, token)
};
case _lexer.TokenKind.DOLLAR:
if (!isConst) {
return parseVariable(lexer);
}
break;
}
throw unexpected(lexer);
}
function parseConstValue(lexer) {
return parseValueLiteral(lexer, true);
}
function parseValueValue(lexer) {
return parseValueLiteral(lexer, false);
}
/**
* ListValue[Const] :
* - [ ]
* - [ Value[?Const]+ ]
*/
function parseList(lexer, isConst) {
var start = lexer.token;
var item = isConst ? parseConstValue : parseValueValue;
return {
kind: _kinds.LIST,
values: any(lexer, _lexer.TokenKind.BRACKET_L, item, _lexer.TokenKind.BRACKET_R),
loc: loc(lexer, start)
};
}
/**
* ObjectValue[Const] :
* - { }
* - { ObjectField[?Const]+ }
*/
function parseObject(lexer, isConst) {
var start = lexer.token;
expect(lexer, _lexer.TokenKind.BRACE_L);
var fields = [];
while (!skip(lexer, _lexer.TokenKind.BRACE_R)) {
fields.push(parseObjectField(lexer, isConst));
}
return {
kind: _kinds.OBJECT,
fields: fields,
loc: loc(lexer, start)
};
}
/**
* ObjectField[Const] : Name : Value[?Const]
*/
function parseObjectField(lexer, isConst) {
var start = lexer.token;
return {
kind: _kinds.OBJECT_FIELD,
name: parseName(lexer),
value: (expect(lexer, _lexer.TokenKind.COLON), parseValueLiteral(lexer, isConst)),
loc: loc(lexer, start)
};
}
// Implements the parsing rules in the Directives section.
/**
* Directives : Directive+
*/
function parseDirectives(lexer) {
var directives = [];
while (peek(lexer, _lexer.TokenKind.AT)) {
directives.push(parseDirective(lexer));
}
return directives;
}
/**
* Directive : @ Name Arguments?
*/
function parseDirective(lexer) {
var start = lexer.token;
expect(lexer, _lexer.TokenKind.AT);
return {
kind: _kinds.DIRECTIVE,
name: parseName(lexer),
arguments: parseArguments(lexer),
loc: loc(lexer, start)
};
}
// Implements the parsing rules in the Types section.
/**
* Type :
* - NamedType
* - ListType
* - NonNullType
*/
function parseTypeReference(lexer) {
var start = lexer.token;
var type = void 0;
if (skip(lexer, _lexer.TokenKind.BRACKET_L)) {
type = parseTypeReference(lexer);
expect(lexer, _lexer.TokenKind.BRACKET_R);
type = {
kind: _kinds.LIST_TYPE,
type: type,
loc: loc(lexer, start)
};
} else {
type = parseNamedType(lexer);
}
if (skip(lexer, _lexer.TokenKind.BANG)) {
return {
kind: _kinds.NON_NULL_TYPE,
type: type,
loc: loc(lexer, start)
};
}
return type;
}
/**
* NamedType : Name
*/
function parseNamedType(lexer) {
var start = lexer.token;
return {
kind: _kinds.NAMED_TYPE,
name: parseName(lexer),
loc: loc(lexer, start)
};
}
// Implements the parsing rules in the Type Definition section.
/**
* TypeSystemDefinition :
* - SchemaDefinition
* - TypeDefinition
* - TypeExtensionDefinition
* - DirectiveDefinition
*
* TypeDefinition :
* - ScalarTypeDefinition
* - ObjectTypeDefinition
* - InterfaceTypeDefinition
* - UnionTypeDefinition
* - EnumTypeDefinition
* - InputObjectTypeDefinition
*/
function parseTypeSystemDefinition(lexer) {
if (peek(lexer, _lexer.TokenKind.NAME)) {
switch (lexer.token.value) {
case 'schema':
return parseSchemaDefinition(lexer);
case 'scalar':
return parseScalarTypeDefinition(lexer);
case 'type':
return parseObjectTypeDefinition(lexer);
case 'interface':
return parseInterfaceTypeDefinition(lexer);
case 'union':
return parseUnionTypeDefinition(lexer);
case 'enum':
return parseEnumTypeDefinition(lexer);
case 'input':
return parseInputObjectTypeDefinition(lexer);
case 'extend':
return parseTypeExtensionDefinition(lexer);
case 'directive':
return parseDirectiveDefinition(lexer);
}
}
throw unexpected(lexer);
}
/**
* SchemaDefinition : schema Directives? { OperationTypeDefinition+ }
*
* OperationTypeDefinition : OperationType : NamedType
*/
function parseSchemaDefinition(lexer) {
var start = lexer.token;
expectKeyword(lexer, 'schema');
var directives = parseDirectives(lexer);
var operationTypes = many(lexer, _lexer.TokenKind.BRACE_L, parseOperationTypeDefinition, _lexer.TokenKind.BRACE_R);
return {
kind: _kinds.SCHEMA_DEFINITION,
directives: directives,
operationTypes: operationTypes,
loc: loc(lexer, start)
};
}
function parseOperationTypeDefinition(lexer) {
var start = lexer.token;
var operation = parseOperationType(lexer);
expect(lexer, _lexer.TokenKind.COLON);
var type = parseNamedType(lexer);
return {
kind: _kinds.OPERATION_TYPE_DEFINITION,
operation: operation,
type: type,
loc: loc(lexer, start)
};
}
/**
* ScalarTypeDefinition : scalar Name Directives?
*/
function parseScalarTypeDefinition(lexer) {
var start = lexer.token;
expectKeyword(lexer, 'scalar');
var name = parseName(lexer);
var directives = parseDirectives(lexer);
return {
kind: _kinds.SCALAR_TYPE_DEFINITION,
name: name,
directives: directives,
loc: loc(lexer, start)
};
}
/**
* ObjectTypeDefinition :
* - type Name ImplementsInterfaces? Directives? { FieldDefinition+ }
*/
function parseObjectTypeDefinition(lexer) {
var start = lexer.token;
expectKeyword(lexer, 'type');
var name = parseName(lexer);
var interfaces = parseImplementsInterfaces(lexer);
var directives = parseDirectives(lexer);
var fields = any(lexer, _lexer.TokenKind.BRACE_L, parseFieldDefinition, _lexer.TokenKind.BRACE_R);
return {
kind: _kinds.OBJECT_TYPE_DEFINITION,
name: name,
interfaces: interfaces,
directives: directives,
fields: fields,
loc: loc(lexer, start)
};
}
/**
* ImplementsInterfaces : implements NamedType+
*/
function parseImplementsInterfaces(lexer) {
var types = [];
if (lexer.token.value === 'implements') {
lexer.advance();
do {
types.push(parseNamedType(lexer));
} while (peek(lexer, _lexer.TokenKind.NAME));
}
return types;
}
/**
* FieldDefinition : Name ArgumentsDefinition? : Type Directives?
*/
function parseFieldDefinition(lexer) {
var start = lexer.token;
var name = parseName(lexer);
var args = parseArgumentDefs(lexer);
expect(lexer, _lexer.TokenKind.COLON);
var type = parseTypeReference(lexer);
var directives = parseDirectives(lexer);
return {
kind: _kinds.FIELD_DEFINITION,
name: name,
arguments: args,
type: type,
directives: directives,
loc: loc(lexer, start)
};
}
/**
* ArgumentsDefinition : ( InputValueDefinition+ )
*/
function parseArgumentDefs(lexer) {
if (!peek(lexer, _lexer.TokenKind.PAREN_L)) {
return [];
}
return many(lexer, _lexer.TokenKind.PAREN_L, parseInputValueDef, _lexer.TokenKind.PAREN_R);
}
/**
* InputValueDefinition : Name : Type DefaultValue? Directives?
*/
function parseInputValueDef(lexer) {
var start = lexer.token;
var name = parseName(lexer);
expect(lexer, _lexer.TokenKind.COLON);
var type = parseTypeReference(lexer);
var defaultValue = null;
if (skip(lexer, _lexer.TokenKind.EQUALS)) {
defaultValue = parseConstValue(lexer);
}
var directives = parseDirectives(lexer);
return {
kind: _kinds.INPUT_VALUE_DEFINITION,
name: name,
type: type,
defaultValue: defaultValue,
directives: directives,
loc: loc(lexer, start)
};
}
/**
* InterfaceTypeDefinition : interface Name Directives? { FieldDefinition+ }
*/
function parseInterfaceTypeDefinition(lexer) {
var start = lexer.token;
expectKeyword(lexer, 'interface');
var name = parseName(lexer);
var directives = parseDirectives(lexer);
var fields = any(lexer, _lexer.TokenKind.BRACE_L, parseFieldDefinition, _lexer.TokenKind.BRACE_R);
return {
kind: _kinds.INTERFACE_TYPE_DEFINITION,
name: name,
directives: directives,
fields: fields,
loc: loc(lexer, start)
};
}
/**
* UnionTypeDefinition : union Name Directives? = UnionMembers
*/
function parseUnionTypeDefinition(lexer) {
var start = lexer.token;
expectKeyword(lexer, 'union');
var name = parseName(lexer);
var directives = parseDirectives(lexer);
expect(lexer, _lexer.TokenKind.EQUALS);
var types = parseUnionMembers(lexer);
return {
kind: _kinds.UNION_TYPE_DEFINITION,
name: name,
directives: directives,
types: types,
loc: loc(lexer, start)
};
}
/**
* UnionMembers :
* - `|`? NamedType
* - UnionMembers | NamedType
*/
function parseUnionMembers(lexer) {
// Optional leading pipe
skip(lexer, _lexer.TokenKind.PIPE);
var members = [];
do {
members.push(parseNamedType(lexer));
} while (skip(lexer, _lexer.TokenKind.PIPE));
return members;
}
/**
* EnumTypeDefinition : enum Name Directives? { EnumValueDefinition+ }
*/
function parseEnumTypeDefinition(lexer) {
var start = lexer.token;
expectKeyword(lexer, 'enum');
var name = parseName(lexer);
var directives = parseDirectives(lexer);
var values = many(lexer, _lexer.TokenKind.BRACE_L, parseEnumValueDefinition, _lexer.TokenKind.BRACE_R);
return {
kind: _kinds.ENUM_TYPE_DEFINITION,
name: name,
directives: directives,
values: values,
loc: loc(lexer, start)
};
}
/**
* EnumValueDefinition : EnumValue Directives?
*
* EnumValue : Name
*/
function parseEnumValueDefinition(lexer) {
var start = lexer.token;
var name = parseName(lexer);
var directives = parseDirectives(lexer);
return {
kind: _kinds.ENUM_VALUE_DEFINITION,
name: name,
directives: directives,
loc: loc(lexer, start)
};
}
/**
* InputObjectTypeDefinition : input Name Directives? { InputValueDefinition+ }
*/
function parseInputObjectTypeDefinition(lexer) {
var start = lexer.token;
expectKeyword(lexer, 'input');
var name = parseName(lexer);
var directives = parseDirectives(lexer);
var fields = any(lexer, _lexer.TokenKind.BRACE_L, parseInputValueDef, _lexer.TokenKind.BRACE_R);
return {
kind: _kinds.INPUT_OBJECT_TYPE_DEFINITION,
name: name,
directives: directives,
fields: fields,
loc: loc(lexer, start)
};
}
/**
* TypeExtensionDefinition : extend ObjectTypeDefinition
*/
function parseTypeExtensionDefinition(lexer) {
var start = lexer.token;
expectKeyword(lexer, 'extend');
var definition = parseObjectTypeDefinition(lexer);
return {
kind: _kinds.TYPE_EXTENSION_DEFINITION,
definition: definition,
loc: loc(lexer, start)
};
}
/**
* DirectiveDefinition :
* - directive @ Name ArgumentsDefinition? on DirectiveLocations
*/
function parseDirectiveDefinition(lexer) {
var start = lexer.token;
expectKeyword(lexer, 'directive');
expect(lexer, _lexer.TokenKind.AT);
var name = parseName(lexer);
var args = parseArgumentDefs(lexer);
expectKeyword(lexer, 'on');
var locations = parseDirectiveLocations(lexer);
return {
kind: _kinds.DIRECTIVE_DEFINITION,
name: name,
arguments: args,
locations: locations,
loc: loc(lexer, start)
};
}
/**
* DirectiveLocations :
* - `|`? Name
* - DirectiveLocations | Name
*/
function parseDirectiveLocations(lexer) {
// Optional leading pipe
skip(lexer, _lexer.TokenKind.PIPE);
var locations = [];
do {
locations.push(parseName(lexer));
} while (skip(lexer, _lexer.TokenKind.PIPE));
return locations;
}
// Core parsing utility functions
/**
* Returns a location object, used to identify the place in
* the source that created a given parsed object.
*/
function loc(lexer, startToken) {
if (!lexer.options.noLocation) {
return new Loc(startToken, lexer.lastToken, lexer.source);
}
}
function Loc(startToken, endToken, source) {
this.start = startToken.start;
this.end = endToken.end;
this.startToken = startToken;
this.endToken = endToken;
this.source = source;
}
// Print a simplified form when appearing in JSON/util.inspect.
Loc.prototype.toJSON = Loc.prototype.inspect = function toJSON() {
return { start: this.start, end: this.end };
};
/**
* Determines if the next token is of a given kind
*/
function peek(lexer, kind) {
return lexer.token.kind === kind;
}
/**
* If the next token is of the given kind, return true after advancing
* the lexer. Otherwise, do not change the parser state and return false.
*/
function skip(lexer, kind) {
var match = lexer.token.kind === kind;
if (match) {
lexer.advance();
}
return match;
}
/**
* If the next token is of the given kind, return that token after advancing
* the lexer. Otherwise, do not change the parser state and throw an error.
*/
function expect(lexer, kind) {
var token = lexer.token;
if (token.kind === kind) {
lexer.advance();
return token;
}
throw (0, _error.syntaxError)(lexer.source, token.start, 'Expected ' + kind + ', found ' + (0, _lexer.getTokenDesc)(token));
}
/**
* If the next token is a keyword with the given value, return that token after
* advancing the lexer. Otherwise, do not change the parser state and return
* false.
*/
function expectKeyword(lexer, value) {
var token = lexer.token;
if (token.kind === _lexer.TokenKind.NAME && token.value === value) {
lexer.advance();
return token;
}
throw (0, _error.syntaxError)(lexer.source, token.start, 'Expected "' + value + '", found ' + (0, _lexer.getTokenDesc)(token));
}
/**
* Helper function for creating an error when an unexpected lexed token
* is encountered.
*/
function unexpected(lexer, atToken) {
var token = atToken || lexer.token;
return (0, _error.syntaxError)(lexer.source, token.start, 'Unexpected ' + (0, _lexer.getTokenDesc)(token));
}
/**
* Returns a possibly empty list of parse nodes, determined by
* the parseFn. This list begins with a lex token of openKind
* and ends with a lex token of closeKind. Advances the parser
* to the next lex token after the closing token.
*/
function any(lexer, openKind, parseFn, closeKind) {
expect(lexer, openKind);
var nodes = [];
while (!skip(lexer, closeKind)) {
nodes.push(parseFn(lexer));
}
return nodes;
}
/**
* Returns a non-empty list of parse nodes, determined by
* the parseFn. This list begins with a lex token of openKind
* and ends with a lex token of closeKind. Advances the parser
* to the next lex token after the closing token.
*/
function many(lexer, openKind, parseFn, closeKind) {
expect(lexer, openKind);
var nodes = [parseFn(lexer)];
while (!skip(lexer, closeKind)) {
nodes.push(parseFn(lexer));
}
return nodes;
}
},{"../error":13,"./kinds":23,"./lexer":24,"./source":28}],27:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.print = print;
var _visitor = require('./visitor');
/**
* Converts an AST into a string, using one set of reasonable
* formatting rules.
*/
function print(ast) {
return (0, _visitor.visit)(ast, { leave: printDocASTReducer });
} /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var printDocASTReducer = {
Name: function Name(node) {
return node.value;
},
Variable: function Variable(node) {
return '$' + node.name;
},
// Document
Document: function Document(node) {
return join(node.definitions, '\n\n') + '\n';
},
OperationDefinition: function OperationDefinition(node) {
var op = node.operation;
var name = node.name;
var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');
var directives = join(node.directives, ' ');
var selectionSet = node.selectionSet;
// Anonymous queries with no directives or variable definitions can use
// the query short form.
return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' ');
},
VariableDefinition: function VariableDefinition(_ref) {
var variable = _ref.variable,
type = _ref.type,
defaultValue = _ref.defaultValue;
return variable + ': ' + type + wrap(' = ', defaultValue);
},
SelectionSet: function SelectionSet(_ref2) {
var selections = _ref2.selections;
return block(selections);
},
Field: function Field(_ref3) {
var alias = _ref3.alias,
name = _ref3.name,
args = _ref3.arguments,
directives = _ref3.directives,
selectionSet = _ref3.selectionSet;
return join([wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), join(directives, ' '), selectionSet], ' ');
},
Argument: function Argument(_ref4) {
var name = _ref4.name,
value = _ref4.value;
return name + ': ' + value;
},
// Fragments
FragmentSpread: function FragmentSpread(_ref5) {
var name = _ref5.name,
directives = _ref5.directives;
return '...' + name + wrap(' ', join(directives, ' '));
},
InlineFragment: function InlineFragment(_ref6) {
var typeCondition = _ref6.typeCondition,
directives = _ref6.directives,
selectionSet = _ref6.selectionSet;
return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ');
},
FragmentDefinition: function FragmentDefinition(_ref7) {
var name = _ref7.name,
typeCondition = _ref7.typeCondition,
directives = _ref7.directives,
selectionSet = _ref7.selectionSet;
return 'fragment ' + name + ' on ' + typeCondition + ' ' + wrap('', join(directives, ' '), ' ') + selectionSet;
},
// Value
IntValue: function IntValue(_ref8) {
var value = _ref8.value;
return value;
},
FloatValue: function FloatValue(_ref9) {
var value = _ref9.value;
return value;
},
StringValue: function StringValue(_ref10) {
var value = _ref10.value;
return JSON.stringify(value);
},
BooleanValue: function BooleanValue(_ref11) {
var value = _ref11.value;
return JSON.stringify(value);
},
NullValue: function NullValue() {
return 'null';
},
EnumValue: function EnumValue(_ref12) {
var value = _ref12.value;
return value;
},
ListValue: function ListValue(_ref13) {
var values = _ref13.values;
return '[' + join(values, ', ') + ']';
},
ObjectValue: function ObjectValue(_ref14) {
var fields = _ref14.fields;
return '{' + join(fields, ', ') + '}';
},
ObjectField: function ObjectField(_ref15) {
var name = _ref15.name,
value = _ref15.value;
return name + ': ' + value;
},
// Directive
Directive: function Directive(_ref16) {
var name = _ref16.name,
args = _ref16.arguments;
return '@' + name + wrap('(', join(args, ', '), ')');
},
// Type
NamedType: function NamedType(_ref17) {
var name = _ref17.name;
return name;
},
ListType: function ListType(_ref18) {
var type = _ref18.type;
return '[' + type + ']';
},
NonNullType: function NonNullType(_ref19) {
var type = _ref19.type;
return type + '!';
},
// Type System Definitions
SchemaDefinition: function SchemaDefinition(_ref20) {
var directives = _ref20.directives,
operationTypes = _ref20.operationTypes;
return join(['schema', join(directives, ' '), block(operationTypes)], ' ');
},
OperationTypeDefinition: function OperationTypeDefinition(_ref21) {
var operation = _ref21.operation,
type = _ref21.type;
return operation + ': ' + type;
},
ScalarTypeDefinition: function ScalarTypeDefinition(_ref22) {
var name = _ref22.name,
directives = _ref22.directives;
return join(['scalar', name, join(directives, ' ')], ' ');
},
ObjectTypeDefinition: function ObjectTypeDefinition(_ref23) {
var name = _ref23.name,
interfaces = _ref23.interfaces,
directives = _ref23.directives,
fields = _ref23.fields;
return join(['type', name, wrap('implements ', join(interfaces, ', ')), join(directives, ' '), block(fields)], ' ');
},
FieldDefinition: function FieldDefinition(_ref24) {
var name = _ref24.name,
args = _ref24.arguments,
type = _ref24.type,
directives = _ref24.directives;
return name + wrap('(', join(args, ', '), ')') + ': ' + type + wrap(' ', join(directives, ' '));
},
InputValueDefinition: function InputValueDefinition(_ref25) {
var name = _ref25.name,
type = _ref25.type,
defaultValue = _ref25.defaultValue,
directives = _ref25.directives;
return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' ');
},
InterfaceTypeDefinition: function InterfaceTypeDefinition(_ref26) {
var name = _ref26.name,
directives = _ref26.directives,
fields = _ref26.fields;
return join(['interface', name, join(directives, ' '), block(fields)], ' ');
},
UnionTypeDefinition: function UnionTypeDefinition(_ref27) {
var name = _ref27.name,
directives = _ref27.directives,
types = _ref27.types;
return join(['union', name, join(directives, ' '), '= ' + join(types, ' | ')], ' ');
},
EnumTypeDefinition: function EnumTypeDefinition(_ref28) {
var name = _ref28.name,
directives = _ref28.directives,
values = _ref28.values;
return join(['enum', name, join(directives, ' '), block(values)], ' ');
},
EnumValueDefinition: function EnumValueDefinition(_ref29) {
var name = _ref29.name,
directives = _ref29.directives;
return join([name, join(directives, ' ')], ' ');
},
InputObjectTypeDefinition: function InputObjectTypeDefinition(_ref30) {
var name = _ref30.name,
directives = _ref30.directives,
fields = _ref30.fields;
return join(['input', name, join(directives, ' '), block(fields)], ' ');
},
TypeExtensionDefinition: function TypeExtensionDefinition(_ref31) {
var definition = _ref31.definition;
return 'extend ' + definition;
},
DirectiveDefinition: function DirectiveDefinition(_ref32) {
var name = _ref32.name,
args = _ref32.arguments,
locations = _ref32.locations;
return 'directive @' + name + wrap('(', join(args, ', '), ')') + ' on ' + join(locations, ' | ');
}
};
/**
* Given maybeArray, print an empty string if it is null or empty, otherwise
* print all items together separated by separator if provided
*/
function join(maybeArray, separator) {
return maybeArray ? maybeArray.filter(function (x) {
return x;
}).join(separator || '') : '';
}
/**
* Given array, print each item on its own line, wrapped in an
* indented "{ }" block.
*/
function block(array) {
return array && array.length !== 0 ? indent('{\n' + join(array, '\n')) + '\n}' : '{}';
}
/**
* If maybeString is not null or empty, then wrap with start and end, otherwise
* print an empty string.
*/
function wrap(start, maybeString, end) {
return maybeString ? start + maybeString + (end || '') : '';
}
function indent(maybeString) {
return maybeString && maybeString.replace(/\n/g, '\n ');
}
},{"./visitor":29}],28:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/**
* A representation of source input to GraphQL. The name is optional,
* but is mostly useful for clients who store GraphQL documents in
* source files; for example, if the GraphQL input is in a file Foo.graphql,
* it might be useful for name to be "Foo.graphql".
*/
var Source = exports.Source = function Source(body, name) {
_classCallCheck(this, Source);
this.body = body;
this.name = name || 'GraphQL request';
};
},{}],29:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.visit = visit;
exports.visitInParallel = visitInParallel;
exports.visitWithTypeInfo = visitWithTypeInfo;
exports.getVisitFn = getVisitFn;
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var QueryDocumentKeys = exports.QueryDocumentKeys = {
Name: [],
Document: ['definitions'],
OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'],
VariableDefinition: ['variable', 'type', 'defaultValue'],
Variable: ['name'],
SelectionSet: ['selections'],
Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
Argument: ['name', 'value'],
FragmentSpread: ['name', 'directives'],
InlineFragment: ['typeCondition', 'directives', 'selectionSet'],
FragmentDefinition: ['name', 'typeCondition', 'directives', 'selectionSet'],
IntValue: [],
FloatValue: [],
StringValue: [],
BooleanValue: [],
NullValue: [],
EnumValue: [],
ListValue: ['values'],
ObjectValue: ['fields'],
ObjectField: ['name', 'value'],
Directive: ['name', 'arguments'],
NamedType: ['name'],
ListType: ['type'],
NonNullType: ['type'],
SchemaDefinition: ['directives', 'operationTypes'],
OperationTypeDefinition: ['type'],
ScalarTypeDefinition: ['name', 'directives'],
ObjectTypeDefinition: ['name', 'interfaces', 'directives', 'fields'],
FieldDefinition: ['name', 'arguments', 'type', 'directives'],
InputValueDefinition: ['name', 'type', 'defaultValue', 'directives'],
InterfaceTypeDefinition: ['name', 'directives', 'fields'],
UnionTypeDefinition: ['name', 'directives', 'types'],
EnumTypeDefinition: ['name', 'directives', 'values'],
EnumValueDefinition: ['name', 'directives'],
InputObjectTypeDefinition: ['name', 'directives', 'fields'],
TypeExtensionDefinition: ['definition'],
DirectiveDefinition: ['name', 'arguments', 'locations']
};
var BREAK = exports.BREAK = {};
/**
* visit() will walk through an AST using a depth first traversal, calling
* the visitor's enter function at each node in the traversal, and calling the
* leave function after visiting that node and all of its child nodes.
*
* By returning different values from the enter and leave functions, the
* behavior of the visitor can be altered, including skipping over a sub-tree of
* the AST (by returning false), editing the AST by returning a value or null
* to remove the value, or to stop the whole traversal by returning BREAK.
*
* When using visit() to edit an AST, the original AST will not be modified, and
* a new version of the AST with the changes applied will be returned from the
* visit function.
*
* const editedAST = visit(ast, {
* enter(node, key, parent, path, ancestors) {
* // @return
* // undefined: no action
* // false: skip visiting this node
* // visitor.BREAK: stop visiting altogether
* // null: delete this node
* // any value: replace this node with the returned value
* },
* leave(node, key, parent, path, ancestors) {
* // @return
* // undefined: no action
* // false: no action
* // visitor.BREAK: stop visiting altogether
* // null: delete this node
* // any value: replace this node with the returned value
* }
* });
*
* Alternatively to providing enter() and leave() functions, a visitor can
* instead provide functions named the same as the kinds of AST nodes, or
* enter/leave visitors at a named key, leading to four permutations of
* visitor API:
*
* 1) Named visitors triggered when entering a node a specific kind.
*
* visit(ast, {
* Kind(node) {
* // enter the "Kind" node
* }
* })
*
* 2) Named visitors that trigger upon entering and leaving a node of
* a specific kind.
*
* visit(ast, {
* Kind: {
* enter(node) {
* // enter the "Kind" node
* }
* leave(node) {
* // leave the "Kind" node
* }
* }
* })
*
* 3) Generic visitors that trigger upon entering and leaving any node.
*
* visit(ast, {
* enter(node) {
* // enter any node
* },
* leave(node) {
* // leave any node
* }
* })
*
* 4) Parallel visitors for entering and leaving nodes of a specific kind.
*
* visit(ast, {
* enter: {
* Kind(node) {
* // enter the "Kind" node
* }
* },
* leave: {
* Kind(node) {
* // leave the "Kind" node
* }
* }
* })
*/
function visit(root, visitor, keyMap) {
var visitorKeys = keyMap || QueryDocumentKeys;
var stack = void 0;
var inArray = Array.isArray(root);
var keys = [root];
var index = -1;
var edits = [];
var parent = void 0;
var path = [];
var ancestors = [];
var newRoot = root;
do {
index++;
var isLeaving = index === keys.length;
var key = void 0;
var node = void 0;
var isEdited = isLeaving && edits.length !== 0;
if (isLeaving) {
key = ancestors.length === 0 ? undefined : path.pop();
node = parent;
parent = ancestors.pop();
if (isEdited) {
if (inArray) {
node = node.slice();
} else {
var clone = {};
for (var k in node) {
if (node.hasOwnProperty(k)) {
clone[k] = node[k];
}
}
node = clone;
}
var editOffset = 0;
for (var ii = 0; ii < edits.length; ii++) {
var editKey = edits[ii][0];
var editValue = edits[ii][1];
if (inArray) {
editKey -= editOffset;
}
if (inArray && editValue === null) {
node.splice(editKey, 1);
editOffset++;
} else {
node[editKey] = editValue;
}
}
}
index = stack.index;
keys = stack.keys;
edits = stack.edits;
inArray = stack.inArray;
stack = stack.prev;
} else {
key = parent ? inArray ? index : keys[index] : undefined;
node = parent ? parent[key] : newRoot;
if (node === null || node === undefined) {
continue;
}
if (parent) {
path.push(key);
}
}
var result = void 0;
if (!Array.isArray(node)) {
if (!isNode(node)) {
throw new Error('Invalid AST Node: ' + JSON.stringify(node));
}
var visitFn = getVisitFn(visitor, node.kind, isLeaving);
if (visitFn) {
result = visitFn.call(visitor, node, key, parent, path, ancestors);
if (result === BREAK) {
break;
}
if (result === false) {
if (!isLeaving) {
path.pop();
continue;
}
} else if (result !== undefined) {
edits.push([key, result]);
if (!isLeaving) {
if (isNode(result)) {
node = result;
} else {
path.pop();
continue;
}
}
}
}
}
if (result === undefined && isEdited) {
edits.push([key, node]);
}
if (!isLeaving) {
stack = { inArray: inArray, index: index, keys: keys, edits: edits, prev: stack };
inArray = Array.isArray(node);
keys = inArray ? node : visitorKeys[node.kind] || [];
index = -1;
edits = [];
if (parent) {
ancestors.push(parent);
}
parent = node;
}
} while (stack !== undefined);
if (edits.length !== 0) {
newRoot = edits[edits.length - 1][1];
}
return newRoot;
}
function isNode(maybeNode) {
return maybeNode && typeof maybeNode.kind === 'string';
}
/**
* Creates a new visitor instance which delegates to many visitors to run in
* parallel. Each visitor will be visited for each node before moving on.
*
* If a prior visitor edits a node, no following visitors will see that node.
*/
function visitInParallel(visitors) {
var skipping = new Array(visitors.length);
return {
enter: function enter(node) {
for (var i = 0; i < visitors.length; i++) {
if (!skipping[i]) {
var fn = getVisitFn(visitors[i], node.kind, /* isLeaving */false);
if (fn) {
var result = fn.apply(visitors[i], arguments);
if (result === false) {
skipping[i] = node;
} else if (result === BREAK) {
skipping[i] = BREAK;
} else if (result !== undefined) {
return result;
}
}
}
}
},
leave: function leave(node) {
for (var i = 0; i < visitors.length; i++) {
if (!skipping[i]) {
var fn = getVisitFn(visitors[i], node.kind, /* isLeaving */true);
if (fn) {
var result = fn.apply(visitors[i], arguments);
if (result === BREAK) {
skipping[i] = BREAK;
} else if (result !== undefined && result !== false) {
return result;
}
}
} else if (skipping[i] === node) {
skipping[i] = null;
}
}
}
};
}
/**
* Creates a new visitor instance which maintains a provided TypeInfo instance
* along with visiting visitor.
*/
function visitWithTypeInfo(typeInfo, visitor) {
return {
enter: function enter(node) {
typeInfo.enter(node);
var fn = getVisitFn(visitor, node.kind, /* isLeaving */false);
if (fn) {
var result = fn.apply(visitor, arguments);
if (result !== undefined) {
typeInfo.leave(node);
if (isNode(result)) {
typeInfo.enter(result);
}
}
return result;
}
},
leave: function leave(node) {
var fn = getVisitFn(visitor, node.kind, /* isLeaving */true);
var result = void 0;
if (fn) {
result = fn.apply(visitor, arguments);
}
typeInfo.leave(node);
return result;
}
};
}
/**
* Given a visitor instance, if it is leaving or not, and a node kind, return
* the function the visitor runtime should call.
*/
function getVisitFn(visitor, kind, isLeaving) {
var kindVisitor = visitor[kind];
if (kindVisitor) {
if (!isLeaving && typeof kindVisitor === 'function') {
// { Kind() {} }
return kindVisitor;
}
var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter;
if (typeof kindSpecificVisitor === 'function') {
// { Kind: { enter() {}, leave() {} } }
return kindSpecificVisitor;
}
} else {
var specificVisitor = isLeaving ? visitor.leave : visitor.enter;
if (specificVisitor) {
if (typeof specificVisitor === 'function') {
// { enter() {}, leave() {} }
return specificVisitor;
}
var specificKindVisitor = specificVisitor[kind];
if (typeof specificKindVisitor === 'function') {
// { enter: { Kind() {} }, leave: { Kind() {} } }
return specificKindVisitor;
}
}
}
}
},{}],30:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GraphQLNonNull = exports.GraphQLList = exports.GraphQLInputObjectType = exports.GraphQLEnumType = exports.GraphQLUnionType = exports.GraphQLInterfaceType = exports.GraphQLObjectType = exports.GraphQLScalarType = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.isType = isType;
exports.assertType = assertType;
exports.isInputType = isInputType;
exports.assertInputType = assertInputType;
exports.isOutputType = isOutputType;
exports.assertOutputType = assertOutputType;
exports.isLeafType = isLeafType;
exports.assertLeafType = assertLeafType;
exports.isCompositeType = isCompositeType;
exports.assertCompositeType = assertCompositeType;
exports.isAbstractType = isAbstractType;
exports.assertAbstractType = assertAbstractType;
exports.getNullableType = getNullableType;
exports.isNamedType = isNamedType;
exports.assertNamedType = assertNamedType;
exports.getNamedType = getNamedType;
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _isNullish = require('../jsutils/isNullish');
var _isNullish2 = _interopRequireDefault(_isNullish);
var _kinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_kinds);
var _assertValidName = require('../utilities/assertValidName');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
// Predicates & Assertions
/**
* These are all of the possible kinds of types.
*/
function isType(type) {
return type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType || type instanceof GraphQLList || type instanceof GraphQLNonNull;
}
function assertType(type) {
(0, _invariant2.default)(isType(type), 'Expected ' + String(type) + ' to be a GraphQL type.');
return type;
}
/**
* These types may be used as input types for arguments and directives.
*/
function isInputType(type) {
return type instanceof GraphQLScalarType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType || type instanceof GraphQLNonNull && isInputType(type.ofType) || type instanceof GraphQLList && isInputType(type.ofType);
}
function assertInputType(type) {
(0, _invariant2.default)(isInputType(type), 'Expected ' + String(type) + ' to be a GraphQL input type.');
return type;
}
/**
* These types may be used as output types as the result of fields.
*/
function isOutputType(type) {
return type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLNonNull && isOutputType(type.ofType) || type instanceof GraphQLList && isOutputType(type.ofType);
}
function assertOutputType(type) {
(0, _invariant2.default)(isOutputType(type), 'Expected ' + String(type) + ' to be a GraphQL output type.');
return type;
}
/**
* These types may describe types which may be leaf values.
*/
function isLeafType(type) {
return type instanceof GraphQLScalarType || type instanceof GraphQLEnumType;
}
function assertLeafType(type) {
(0, _invariant2.default)(isLeafType(type), 'Expected ' + String(type) + ' to be a GraphQL leaf type.');
return type;
}
/**
* These types may describe the parent context of a selection set.
*/
function isCompositeType(type) {
return type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType;
}
function assertCompositeType(type) {
(0, _invariant2.default)(isCompositeType(type), 'Expected ' + String(type) + ' to be a GraphQL composite type.');
return type;
}
/**
* These types may describe the parent context of a selection set.
*/
function isAbstractType(type) {
return type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType;
}
function assertAbstractType(type) {
(0, _invariant2.default)(isAbstractType(type), 'Expected ' + String(type) + ' to be a GraphQL abstract type.');
return type;
}
/**
* These types can all accept null as a value.
*/
function getNullableType(type) {
return type instanceof GraphQLNonNull ? type.ofType : type;
}
/**
* These named types do not include modifiers like List or NonNull.
*/
function isNamedType(type) {
return type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType;
}
function assertNamedType(type) {
(0, _invariant2.default)(isNamedType(type), 'Expected ' + String(type) + ' to be a GraphQL named type.');
return type;
}
/* eslint-disable no-redeclare */
function getNamedType(type) {
/* eslint-enable no-redeclare */
if (type) {
var unmodifiedType = type;
while (unmodifiedType instanceof GraphQLList || unmodifiedType instanceof GraphQLNonNull) {
unmodifiedType = unmodifiedType.ofType;
}
return unmodifiedType;
}
}
/**
* Used while defining GraphQL types to allow for circular references in
* otherwise immutable type definitions.
*/
function resolveThunk(thunk) {
return typeof thunk === 'function' ? thunk() : thunk;
}
/**
* Scalar Type Definition
*
* The leaf values of any request and input values to arguments are
* Scalars (or Enums) and are defined with a name and a series of functions
* used to parse input from ast or variables and to ensure validity.
*
* Example:
*
* const OddType = new GraphQLScalarType({
* name: 'Odd',
* serialize(value) {
* return value % 2 === 1 ? value : null;
* }
* });
*
*/
var GraphQLScalarType = exports.GraphQLScalarType = function () {
function GraphQLScalarType(config) {
_classCallCheck(this, GraphQLScalarType);
(0, _assertValidName.assertValidName)(config.name);
this.name = config.name;
this.description = config.description;
(0, _invariant2.default)(typeof config.serialize === 'function', this.name + ' must provide "serialize" function. If this custom Scalar ' + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.');
if (config.parseValue || config.parseLiteral) {
(0, _invariant2.default)(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function', this.name + ' must provide both "parseValue" and "parseLiteral" ' + 'functions.');
}
this._scalarConfig = config;
}
// Serializes an internal value to include in a response.
GraphQLScalarType.prototype.serialize = function serialize(value) {
var serializer = this._scalarConfig.serialize;
return serializer(value);
};
// Determines if an internal value is valid for this type.
// Equivalent to checking for if the parsedValue is nullish.
GraphQLScalarType.prototype.isValidValue = function isValidValue(value) {
return !(0, _isNullish2.default)(this.parseValue(value));
};
// Parses an externally provided value to use as an input.
GraphQLScalarType.prototype.parseValue = function parseValue(value) {
var parser = this._scalarConfig.parseValue;
return parser && !(0, _isNullish2.default)(value) ? parser(value) : undefined;
};
// Determines if an internal value is valid for this type.
// Equivalent to checking for if the parsedLiteral is nullish.
GraphQLScalarType.prototype.isValidLiteral = function isValidLiteral(valueNode) {
return !(0, _isNullish2.default)(this.parseLiteral(valueNode));
};
// Parses an externally provided literal value to use as an input.
GraphQLScalarType.prototype.parseLiteral = function parseLiteral(valueNode) {
var parser = this._scalarConfig.parseLiteral;
return parser ? parser(valueNode) : undefined;
};
GraphQLScalarType.prototype.toString = function toString() {
return this.name;
};
return GraphQLScalarType;
}();
// Also provide toJSON and inspect aliases for toString.
GraphQLScalarType.prototype.toJSON = GraphQLScalarType.prototype.inspect = GraphQLScalarType.prototype.toString;
/**
* Object Type Definition
*
* Almost all of the GraphQL types you define will be object types. Object types
* have a name, but most importantly describe their fields.
*
* Example:
*
* const AddressType = new GraphQLObjectType({
* name: 'Address',
* fields: {
* street: { type: GraphQLString },
* number: { type: GraphQLInt },
* formatted: {
* type: GraphQLString,
* resolve(obj) {
* return obj.number + ' ' + obj.street
* }
* }
* }
* });
*
* When two types need to refer to each other, or a type needs to refer to
* itself in a field, you can use a function expression (aka a closure or a
* thunk) to supply the fields lazily.
*
* Example:
*
* const PersonType = new GraphQLObjectType({
* name: 'Person',
* fields: () => ({
* name: { type: GraphQLString },
* bestFriend: { type: PersonType },
* })
* });
*
*/
var GraphQLObjectType = exports.GraphQLObjectType = function () {
function GraphQLObjectType(config) {
_classCallCheck(this, GraphQLObjectType);
(0, _assertValidName.assertValidName)(config.name, config.isIntrospection);
this.name = config.name;
this.description = config.description;
if (config.isTypeOf) {
(0, _invariant2.default)(typeof config.isTypeOf === 'function', this.name + ' must provide "isTypeOf" as a function.');
}
this.isTypeOf = config.isTypeOf;
this._typeConfig = config;
}
GraphQLObjectType.prototype.getFields = function getFields() {
return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields));
};
GraphQLObjectType.prototype.getInterfaces = function getInterfaces() {
return this._interfaces || (this._interfaces = defineInterfaces(this, this._typeConfig.interfaces));
};
GraphQLObjectType.prototype.toString = function toString() {
return this.name;
};
return GraphQLObjectType;
}();
// Also provide toJSON and inspect aliases for toString.
GraphQLObjectType.prototype.toJSON = GraphQLObjectType.prototype.inspect = GraphQLObjectType.prototype.toString;
function defineInterfaces(type, interfacesThunk) {
var interfaces = resolveThunk(interfacesThunk);
if (!interfaces) {
return [];
}
(0, _invariant2.default)(Array.isArray(interfaces), type.name + ' interfaces must be an Array or a function which returns ' + 'an Array.');
var implementedTypeNames = Object.create(null);
interfaces.forEach(function (iface) {
(0, _invariant2.default)(iface instanceof GraphQLInterfaceType, type.name + ' may only implement Interface types, it cannot ' + ('implement: ' + String(iface) + '.'));
(0, _invariant2.default)(!implementedTypeNames[iface.name], type.name + ' may declare it implements ' + iface.name + ' only once.');
implementedTypeNames[iface.name] = true;
if (typeof iface.resolveType !== 'function') {
(0, _invariant2.default)(typeof type.isTypeOf === 'function', 'Interface Type ' + iface.name + ' does not provide a "resolveType" ' + ('function and implementing Type ' + type.name + ' does not provide a ') + '"isTypeOf" function. There is no way to resolve this implementing ' + 'type during execution.');
}
});
return interfaces;
}
function defineFieldMap(type, fieldsThunk) {
var fieldMap = resolveThunk(fieldsThunk);
(0, _invariant2.default)(isPlainObj(fieldMap), type.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');
var fieldNames = Object.keys(fieldMap);
(0, _invariant2.default)(fieldNames.length > 0, type.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');
var resultFieldMap = Object.create(null);
fieldNames.forEach(function (fieldName) {
(0, _assertValidName.assertValidName)(fieldName);
var fieldConfig = fieldMap[fieldName];
(0, _invariant2.default)(isPlainObj(fieldConfig), type.name + '.' + fieldName + ' field config must be an object');
(0, _invariant2.default)(!fieldConfig.hasOwnProperty('isDeprecated'), type.name + '.' + fieldName + ' should provide "deprecationReason" instead ' + 'of "isDeprecated".');
var field = _extends({}, fieldConfig, {
isDeprecated: Boolean(fieldConfig.deprecationReason),
name: fieldName
});
(0, _invariant2.default)(isOutputType(field.type), type.name + '.' + fieldName + ' field type must be Output Type but ' + ('got: ' + String(field.type) + '.'));
(0, _invariant2.default)(isValidResolver(field.resolve), type.name + '.' + fieldName + ' field resolver must be a function if ' + ('provided, but got: ' + String(field.resolve) + '.'));
var argsConfig = fieldConfig.args;
if (!argsConfig) {
field.args = [];
} else {
(0, _invariant2.default)(isPlainObj(argsConfig), type.name + '.' + fieldName + ' args must be an object with argument ' + 'names as keys.');
field.args = Object.keys(argsConfig).map(function (argName) {
(0, _assertValidName.assertValidName)(argName);
var arg = argsConfig[argName];
(0, _invariant2.default)(isInputType(arg.type), type.name + '.' + fieldName + '(' + argName + ':) argument type must be ' + ('Input Type but got: ' + String(arg.type) + '.'));
return {
name: argName,
description: arg.description === undefined ? null : arg.description,
type: arg.type,
defaultValue: arg.defaultValue
};
});
}
resultFieldMap[fieldName] = field;
});
return resultFieldMap;
}
function isPlainObj(obj) {
return obj && typeof obj === 'object' && !Array.isArray(obj);
}
// If a resolver is defined, it must be a function.
function isValidResolver(resolver) {
return resolver == null || typeof resolver === 'function';
}
/**
* Interface Type Definition
*
* When a field can return one of a heterogeneous set of types, a Interface type
* is used to describe what types are possible, what fields are in common across
* all types, as well as a function to determine which type is actually used
* when the field is resolved.
*
* Example:
*
* const EntityType = new GraphQLInterfaceType({
* name: 'Entity',
* fields: {
* name: { type: GraphQLString }
* }
* });
*
*/
var GraphQLInterfaceType = exports.GraphQLInterfaceType = function () {
function GraphQLInterfaceType(config) {
_classCallCheck(this, GraphQLInterfaceType);
(0, _assertValidName.assertValidName)(config.name);
this.name = config.name;
this.description = config.description;
if (config.resolveType) {
(0, _invariant2.default)(typeof config.resolveType === 'function', this.name + ' must provide "resolveType" as a function.');
}
this.resolveType = config.resolveType;
this._typeConfig = config;
}
GraphQLInterfaceType.prototype.getFields = function getFields() {
return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields));
};
GraphQLInterfaceType.prototype.toString = function toString() {
return this.name;
};
return GraphQLInterfaceType;
}();
// Also provide toJSON and inspect aliases for toString.
GraphQLInterfaceType.prototype.toJSON = GraphQLInterfaceType.prototype.inspect = GraphQLInterfaceType.prototype.toString;
/**
* Union Type Definition
*
* When a field can return one of a heterogeneous set of types, a Union type
* is used to describe what types are possible as well as providing a function
* to determine which type is actually used when the field is resolved.
*
* Example:
*
* const PetType = new GraphQLUnionType({
* name: 'Pet',
* types: [ DogType, CatType ],
* resolveType(value) {
* if (value instanceof Dog) {
* return DogType;
* }
* if (value instanceof Cat) {
* return CatType;
* }
* }
* });
*
*/
var GraphQLUnionType = exports.GraphQLUnionType = function () {
function GraphQLUnionType(config) {
_classCallCheck(this, GraphQLUnionType);
(0, _assertValidName.assertValidName)(config.name);
this.name = config.name;
this.description = config.description;
if (config.resolveType) {
(0, _invariant2.default)(typeof config.resolveType === 'function', this.name + ' must provide "resolveType" as a function.');
}
this.resolveType = config.resolveType;
this._typeConfig = config;
}
GraphQLUnionType.prototype.getTypes = function getTypes() {
return this._types || (this._types = defineTypes(this, this._typeConfig.types));
};
GraphQLUnionType.prototype.toString = function toString() {
return this.name;
};
return GraphQLUnionType;
}();
// Also provide toJSON and inspect aliases for toString.
GraphQLUnionType.prototype.toJSON = GraphQLUnionType.prototype.inspect = GraphQLUnionType.prototype.toString;
function defineTypes(unionType, typesThunk) {
var types = resolveThunk(typesThunk);
(0, _invariant2.default)(Array.isArray(types) && types.length > 0, 'Must provide Array of types or a function which returns ' + ('such an array for Union ' + unionType.name + '.'));
var includedTypeNames = Object.create(null);
types.forEach(function (objType) {
(0, _invariant2.default)(objType instanceof GraphQLObjectType, unionType.name + ' may only contain Object types, it cannot contain: ' + (String(objType) + '.'));
(0, _invariant2.default)(!includedTypeNames[objType.name], unionType.name + ' can include ' + objType.name + ' type only once.');
includedTypeNames[objType.name] = true;
if (typeof unionType.resolveType !== 'function') {
(0, _invariant2.default)(typeof objType.isTypeOf === 'function', 'Union type "' + unionType.name + '" does not provide a "resolveType" ' + ('function and possible type "' + objType.name + '" does not provide an ') + '"isTypeOf" function. There is no way to resolve this possible type ' + 'during execution.');
}
});
return types;
}
/**
* Enum Type Definition
*
* Some leaf values of requests and input values are Enums. GraphQL serializes
* Enum values as strings, however internally Enums can be represented by any
* kind of type, often integers.
*
* Example:
*
* const RGBType = new GraphQLEnumType({
* name: 'RGB',
* values: {
* RED: { value: 0 },
* GREEN: { value: 1 },
* BLUE: { value: 2 }
* }
* });
*
* Note: If a value is not provided in a definition, the name of the enum value
* will be used as its internal value.
*/
var GraphQLEnumType /* <T> */ = exports.GraphQLEnumType = function () {
function GraphQLEnumType(config /* <T> */) {
_classCallCheck(this, GraphQLEnumType);
this.name = config.name;
(0, _assertValidName.assertValidName)(config.name, config.isIntrospection);
this.description = config.description;
this._values = defineEnumValues(this, config.values);
this._enumConfig = config;
}
GraphQLEnumType.prototype.getValues = function getValues() {
return this._values;
};
GraphQLEnumType.prototype.getValue = function getValue(name) {
return this._getNameLookup()[name];
};
GraphQLEnumType.prototype.serialize = function serialize(value /* T */) {
var enumValue = this._getValueLookup().get(value);
return enumValue ? enumValue.name : null;
};
GraphQLEnumType.prototype.isValidValue = function isValidValue(value) {
return typeof value === 'string' && this._getNameLookup()[value] !== undefined;
};
GraphQLEnumType.prototype.parseValue = function parseValue(value) /* T */{
if (typeof value === 'string') {
var enumValue = this._getNameLookup()[value];
if (enumValue) {
return enumValue.value;
}
}
};
GraphQLEnumType.prototype.isValidLiteral = function isValidLiteral(valueNode) {
return valueNode.kind === Kind.ENUM && this._getNameLookup()[valueNode.value] !== undefined;
};
GraphQLEnumType.prototype.parseLiteral = function parseLiteral(valueNode) /* T */{
if (valueNode.kind === Kind.ENUM) {
var enumValue = this._getNameLookup()[valueNode.value];
if (enumValue) {
return enumValue.value;
}
}
};
GraphQLEnumType.prototype._getValueLookup = function _getValueLookup() {
if (!this._valueLookup) {
var lookup = new Map();
this.getValues().forEach(function (value) {
lookup.set(value.value, value);
});
this._valueLookup = lookup;
}
return this._valueLookup;
};
GraphQLEnumType.prototype._getNameLookup = function _getNameLookup() {
if (!this._nameLookup) {
var lookup = Object.create(null);
this.getValues().forEach(function (value) {
lookup[value.name] = value;
});
this._nameLookup = lookup;
}
return this._nameLookup;
};
GraphQLEnumType.prototype.toString = function toString() {
return this.name;
};
return GraphQLEnumType;
}();
// Also provide toJSON and inspect aliases for toString.
GraphQLEnumType.prototype.toJSON = GraphQLEnumType.prototype.inspect = GraphQLEnumType.prototype.toString;
function defineEnumValues(type, valueMap /* <T> */
) {
(0, _invariant2.default)(isPlainObj(valueMap), type.name + ' values must be an object with value names as keys.');
var valueNames = Object.keys(valueMap);
(0, _invariant2.default)(valueNames.length > 0, type.name + ' values must be an object with value names as keys.');
return valueNames.map(function (valueName) {
(0, _assertValidName.assertValidName)(valueName);
(0, _invariant2.default)(['true', 'false', 'null'].indexOf(valueName) === -1, 'Name "' + valueName + '" can not be used as an Enum value.');
var value = valueMap[valueName];
(0, _invariant2.default)(isPlainObj(value), type.name + '.' + valueName + ' must refer to an object with a "value" key ' + ('representing an internal value but got: ' + String(value) + '.'));
(0, _invariant2.default)(!value.hasOwnProperty('isDeprecated'), type.name + '.' + valueName + ' should provide "deprecationReason" instead ' + 'of "isDeprecated".');
return {
name: valueName,
description: value.description,
isDeprecated: Boolean(value.deprecationReason),
deprecationReason: value.deprecationReason,
value: value.hasOwnProperty('value') ? value.value : valueName
};
});
} /* <T> */
/**
* Input Object Type Definition
*
* An input object defines a structured collection of fields which may be
* supplied to a field argument.
*
* Using `NonNull` will ensure that a value must be provided by the query
*
* Example:
*
* const GeoPoint = new GraphQLInputObjectType({
* name: 'GeoPoint',
* fields: {
* lat: { type: new GraphQLNonNull(GraphQLFloat) },
* lon: { type: new GraphQLNonNull(GraphQLFloat) },
* alt: { type: GraphQLFloat, defaultValue: 0 },
* }
* });
*
*/
var GraphQLInputObjectType = exports.GraphQLInputObjectType = function () {
function GraphQLInputObjectType(config) {
_classCallCheck(this, GraphQLInputObjectType);
(0, _assertValidName.assertValidName)(config.name);
this.name = config.name;
this.description = config.description;
this._typeConfig = config;
}
GraphQLInputObjectType.prototype.getFields = function getFields() {
return this._fields || (this._fields = this._defineFieldMap());
};
GraphQLInputObjectType.prototype._defineFieldMap = function _defineFieldMap() {
var _this = this;
var fieldMap = resolveThunk(this._typeConfig.fields);
(0, _invariant2.default)(isPlainObj(fieldMap), this.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');
var fieldNames = Object.keys(fieldMap);
(0, _invariant2.default)(fieldNames.length > 0, this.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');
var resultFieldMap = Object.create(null);
fieldNames.forEach(function (fieldName) {
(0, _assertValidName.assertValidName)(fieldName);
var field = _extends({}, fieldMap[fieldName], {
name: fieldName
});
(0, _invariant2.default)(isInputType(field.type), _this.name + '.' + fieldName + ' field type must be Input Type but ' + ('got: ' + String(field.type) + '.'));
(0, _invariant2.default)(field.resolve == null, _this.name + '.' + fieldName + ' field type has a resolve property, but ' + 'Input Types cannot define resolvers.');
resultFieldMap[fieldName] = field;
});
return resultFieldMap;
};
GraphQLInputObjectType.prototype.toString = function toString() {
return this.name;
};
return GraphQLInputObjectType;
}();
// Also provide toJSON and inspect aliases for toString.
GraphQLInputObjectType.prototype.toJSON = GraphQLInputObjectType.prototype.inspect = GraphQLInputObjectType.prototype.toString;
/**
* List Modifier
*
* A list is a kind of type marker, a wrapping type which points to another
* type. Lists are often created within the context of defining the fields of
* an object type.
*
* Example:
*
* const PersonType = new GraphQLObjectType({
* name: 'Person',
* fields: () => ({
* parents: { type: new GraphQLList(Person) },
* children: { type: new GraphQLList(Person) },
* })
* })
*
*/
var GraphQLList = exports.GraphQLList = function () {
function GraphQLList(type) {
_classCallCheck(this, GraphQLList);
(0, _invariant2.default)(isType(type), 'Can only create List of a GraphQLType but got: ' + String(type) + '.');
this.ofType = type;
}
GraphQLList.prototype.toString = function toString() {
return '[' + String(this.ofType) + ']';
};
return GraphQLList;
}();
// Also provide toJSON and inspect aliases for toString.
GraphQLList.prototype.toJSON = GraphQLList.prototype.inspect = GraphQLList.prototype.toString;
/**
* Non-Null Modifier
*
* A non-null is a kind of type marker, a wrapping type which points to another
* type. Non-null types enforce that their values are never null and can ensure
* an error is raised if this ever occurs during a request. It is useful for
* fields which you can make a strong guarantee on non-nullability, for example
* usually the id field of a database row will never be null.
*
* Example:
*
* const RowType = new GraphQLObjectType({
* name: 'Row',
* fields: () => ({
* id: { type: new GraphQLNonNull(GraphQLString) },
* })
* })
*
* Note: the enforcement of non-nullability occurs within the executor.
*/
var GraphQLNonNull = exports.GraphQLNonNull = function () {
function GraphQLNonNull(type) {
_classCallCheck(this, GraphQLNonNull);
(0, _invariant2.default)(isType(type) && !(type instanceof GraphQLNonNull), 'Can only create NonNull of a Nullable GraphQLType but got: ' + (String(type) + '.'));
this.ofType = type;
}
GraphQLNonNull.prototype.toString = function toString() {
return this.ofType.toString() + '!';
};
return GraphQLNonNull;
}();
// Also provide toJSON and inspect aliases for toString.
GraphQLNonNull.prototype.toJSON = GraphQLNonNull.prototype.inspect = GraphQLNonNull.prototype.toString;
},{"../jsutils/invariant":18,"../jsutils/isNullish":20,"../language/kinds":23,"../utilities/assertValidName":35}],31:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.specifiedDirectives = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = exports.DirectiveLocation = undefined;
var _definition = require('./definition');
var _scalars = require('./scalars');
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _assertValidName = require('../utilities/assertValidName');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var DirectiveLocation = exports.DirectiveLocation = {
// Operations
QUERY: 'QUERY',
MUTATION: 'MUTATION',
SUBSCRIPTION: 'SUBSCRIPTION',
FIELD: 'FIELD',
FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION',
FRAGMENT_SPREAD: 'FRAGMENT_SPREAD',
INLINE_FRAGMENT: 'INLINE_FRAGMENT',
// Schema Definitions
SCHEMA: 'SCHEMA',
SCALAR: 'SCALAR',
OBJECT: 'OBJECT',
FIELD_DEFINITION: 'FIELD_DEFINITION',
ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION',
INTERFACE: 'INTERFACE',
UNION: 'UNION',
ENUM: 'ENUM',
ENUM_VALUE: 'ENUM_VALUE',
INPUT_OBJECT: 'INPUT_OBJECT',
INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION'
};
// eslint-disable-line
/**
* Directives are used by the GraphQL runtime as a way of modifying execution
* behavior. Type system creators will usually not create these directly.
*/
var GraphQLDirective = exports.GraphQLDirective = function GraphQLDirective(config) {
_classCallCheck(this, GraphQLDirective);
(0, _invariant2.default)(config.name, 'Directive must be named.');
(0, _assertValidName.assertValidName)(config.name);
(0, _invariant2.default)(Array.isArray(config.locations), 'Must provide locations for directive.');
this.name = config.name;
this.description = config.description;
this.locations = config.locations;
var args = config.args;
if (!args) {
this.args = [];
} else {
(0, _invariant2.default)(!Array.isArray(args), '@' + config.name + ' args must be an object with argument names as keys.');
this.args = Object.keys(args).map(function (argName) {
(0, _assertValidName.assertValidName)(argName);
var arg = args[argName];
(0, _invariant2.default)((0, _definition.isInputType)(arg.type), '@' + config.name + '(' + argName + ':) argument type must be ' + ('Input Type but got: ' + String(arg.type) + '.'));
return {
name: argName,
description: arg.description === undefined ? null : arg.description,
type: arg.type,
defaultValue: arg.defaultValue
};
});
}
};
/**
* Used to conditionally include fields or fragments.
*/
var GraphQLIncludeDirective = exports.GraphQLIncludeDirective = new GraphQLDirective({
name: 'include',
description: 'Directs the executor to include this field or fragment only when ' + 'the `if` argument is true.',
locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT],
args: {
'if': {
type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),
description: 'Included when true.'
}
}
});
/**
* Used to conditionally skip (exclude) fields or fragments.
*/
var GraphQLSkipDirective = exports.GraphQLSkipDirective = new GraphQLDirective({
name: 'skip',
description: 'Directs the executor to skip this field or fragment when the `if` ' + 'argument is true.',
locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT],
args: {
'if': {
type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),
description: 'Skipped when true.'
}
}
});
/**
* Constant string used for default reason for a deprecation.
*/
var DEFAULT_DEPRECATION_REASON = exports.DEFAULT_DEPRECATION_REASON = 'No longer supported';
/**
* Used to declare element of a GraphQL schema as deprecated.
*/
var GraphQLDeprecatedDirective = exports.GraphQLDeprecatedDirective = new GraphQLDirective({
name: 'deprecated',
description: 'Marks an element of a GraphQL schema as no longer supported.',
locations: [DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.ENUM_VALUE],
args: {
reason: {
type: _scalars.GraphQLString,
description: 'Explains why this element was deprecated, usually also including a ' + 'suggestion for how to access supported similar data. Formatted ' + 'in [Markdown](https://daringfireball.net/projects/markdown/).',
defaultValue: DEFAULT_DEPRECATION_REASON
}
}
});
/**
* The full list of specified directives.
*/
var specifiedDirectives = exports.specifiedDirectives = [GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective];
},{"../jsutils/invariant":18,"../utilities/assertValidName":35,"./definition":30,"./scalars":33}],32:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.SchemaMetaFieldDef = exports.__TypeKind = exports.TypeKind = exports.__EnumValue = exports.__InputValue = exports.__Field = exports.__Type = exports.__DirectiveLocation = exports.__Directive = exports.__Schema = undefined;
var _isInvalid = require('../jsutils/isInvalid');
var _isInvalid2 = _interopRequireDefault(_isInvalid);
var _astFromValue = require('../utilities/astFromValue');
var _printer = require('../language/printer');
var _definition = require('./definition');
var _scalars = require('./scalars');
var _directives = require('./directives');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var __Schema = exports.__Schema = new _definition.GraphQLObjectType({
name: '__Schema',
isIntrospection: true,
description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It ' + 'exposes all available types and directives on the server, as well as ' + 'the entry points for query, mutation, and subscription operations.',
fields: function fields() {
return {
types: {
description: 'A list of all types supported by this server.',
type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type))),
resolve: function resolve(schema) {
var typeMap = schema.getTypeMap();
return Object.keys(typeMap).map(function (key) {
return typeMap[key];
});
}
},
queryType: {
description: 'The type that query operations will be rooted at.',
type: new _definition.GraphQLNonNull(__Type),
resolve: function resolve(schema) {
return schema.getQueryType();
}
},
mutationType: {
description: 'If this server supports mutation, the type that ' + 'mutation operations will be rooted at.',
type: __Type,
resolve: function resolve(schema) {
return schema.getMutationType();
}
},
subscriptionType: {
description: 'If this server support subscription, the type that ' + 'subscription operations will be rooted at.',
type: __Type,
resolve: function resolve(schema) {
return schema.getSubscriptionType();
}
},
directives: {
description: 'A list of all directives supported by this server.',
type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Directive))),
resolve: function resolve(schema) {
return schema.getDirectives();
}
}
};
}
});
var __Directive = exports.__Directive = new _definition.GraphQLObjectType({
name: '__Directive',
isIntrospection: true,
description: 'A Directive provides a way to describe alternate runtime execution and ' + 'type validation behavior in a GraphQL document.' + '\n\nIn some cases, you need to provide options to alter GraphQL\'s ' + 'execution behavior in ways field arguments will not suffice, such as ' + 'conditionally including or skipping a field. Directives provide this by ' + 'describing additional information to the executor.',
fields: function fields() {
return {
name: { type: new _definition.GraphQLNonNull(_scalars.GraphQLString) },
description: { type: _scalars.GraphQLString },
locations: {
type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__DirectiveLocation)))
},
args: {
type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))),
resolve: function resolve(directive) {
return directive.args || [];
}
},
// NOTE: the following three fields are deprecated and are no longer part
// of the GraphQL specification.
onOperation: {
deprecationReason: 'Use `locations`.',
type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),
resolve: function resolve(d) {
return d.locations.indexOf(_directives.DirectiveLocation.QUERY) !== -1 || d.locations.indexOf(_directives.DirectiveLocation.MUTATION) !== -1 || d.locations.indexOf(_directives.DirectiveLocation.SUBSCRIPTION) !== -1;
}
},
onFragment: {
deprecationReason: 'Use `locations`.',
type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),
resolve: function resolve(d) {
return d.locations.indexOf(_directives.DirectiveLocation.FRAGMENT_SPREAD) !== -1 || d.locations.indexOf(_directives.DirectiveLocation.INLINE_FRAGMENT) !== -1 || d.locations.indexOf(_directives.DirectiveLocation.FRAGMENT_DEFINITION) !== -1;
}
},
onField: {
deprecationReason: 'Use `locations`.',
type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),
resolve: function resolve(d) {
return d.locations.indexOf(_directives.DirectiveLocation.FIELD) !== -1;
}
}
};
}
});
var __DirectiveLocation = exports.__DirectiveLocation = new _definition.GraphQLEnumType({
name: '__DirectiveLocation',
isIntrospection: true,
description: 'A Directive can be adjacent to many parts of the GraphQL language, a ' + '__DirectiveLocation describes one such possible adjacencies.',
values: {
QUERY: {
value: _directives.DirectiveLocation.QUERY,
description: 'Location adjacent to a query operation.'
},
MUTATION: {
value: _directives.DirectiveLocation.MUTATION,
description: 'Location adjacent to a mutation operation.'
},
SUBSCRIPTION: {
value: _directives.DirectiveLocation.SUBSCRIPTION,
description: 'Location adjacent to a subscription operation.'
},
FIELD: {
value: _directives.DirectiveLocation.FIELD,
description: 'Location adjacent to a field.'
},
FRAGMENT_DEFINITION: {
value: _directives.DirectiveLocation.FRAGMENT_DEFINITION,
description: 'Location adjacent to a fragment definition.'
},
FRAGMENT_SPREAD: {
value: _directives.DirectiveLocation.FRAGMENT_SPREAD,
description: 'Location adjacent to a fragment spread.'
},
INLINE_FRAGMENT: {
value: _directives.DirectiveLocation.INLINE_FRAGMENT,
description: 'Location adjacent to an inline fragment.'
},
SCHEMA: {
value: _directives.DirectiveLocation.SCHEMA,
description: 'Location adjacent to a schema definition.'
},
SCALAR: {
value: _directives.DirectiveLocation.SCALAR,
description: 'Location adjacent to a scalar definition.'
},
OBJECT: {
value: _directives.DirectiveLocation.OBJECT,
description: 'Location adjacent to an object type definition.'
},
FIELD_DEFINITION: {
value: _directives.DirectiveLocation.FIELD_DEFINITION,
description: 'Location adjacent to a field definition.'
},
ARGUMENT_DEFINITION: {
value: _directives.DirectiveLocation.ARGUMENT_DEFINITION,
description: 'Location adjacent to an argument definition.'
},
INTERFACE: {
value: _directives.DirectiveLocation.INTERFACE,
description: 'Location adjacent to an interface definition.'
},
UNION: {
value: _directives.DirectiveLocation.UNION,
description: 'Location adjacent to a union definition.'
},
ENUM: {
value: _directives.DirectiveLocation.ENUM,
description: 'Location adjacent to an enum definition.'
},
ENUM_VALUE: {
value: _directives.DirectiveLocation.ENUM_VALUE,
description: 'Location adjacent to an enum value definition.'
},
INPUT_OBJECT: {
value: _directives.DirectiveLocation.INPUT_OBJECT,
description: 'Location adjacent to an input object type definition.'
},
INPUT_FIELD_DEFINITION: {
value: _directives.DirectiveLocation.INPUT_FIELD_DEFINITION,
description: 'Location adjacent to an input object field definition.'
}
}
});
var __Type = exports.__Type = new _definition.GraphQLObjectType({
name: '__Type',
isIntrospection: true,
description: 'The fundamental unit of any GraphQL Schema is the type. There are ' + 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' + '\n\nDepending on the kind of a type, certain fields describe ' + 'information about that type. Scalar types provide no information ' + 'beyond a name and description, while Enum types provide their values. ' + 'Object and Interface types provide the fields they describe. Abstract ' + 'types, Union and Interface, provide the Object types possible ' + 'at runtime. List and NonNull types compose other types.',
fields: function fields() {
return {
kind: {
type: new _definition.GraphQLNonNull(__TypeKind),
resolve: function resolve(type) {
if (type instanceof _definition.GraphQLScalarType) {
return TypeKind.SCALAR;
} else if (type instanceof _definition.GraphQLObjectType) {
return TypeKind.OBJECT;
} else if (type instanceof _definition.GraphQLInterfaceType) {
return TypeKind.INTERFACE;
} else if (type instanceof _definition.GraphQLUnionType) {
return TypeKind.UNION;
} else if (type instanceof _definition.GraphQLEnumType) {
return TypeKind.ENUM;
} else if (type instanceof _definition.GraphQLInputObjectType) {
return TypeKind.INPUT_OBJECT;
} else if (type instanceof _definition.GraphQLList) {
return TypeKind.LIST;
} else if (type instanceof _definition.GraphQLNonNull) {
return TypeKind.NON_NULL;
}
throw new Error('Unknown kind of type: ' + type);
}
},
name: { type: _scalars.GraphQLString },
description: { type: _scalars.GraphQLString },
fields: {
type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Field)),
args: {
includeDeprecated: { type: _scalars.GraphQLBoolean, defaultValue: false }
},
resolve: function resolve(type, _ref) {
var includeDeprecated = _ref.includeDeprecated;
if (type instanceof _definition.GraphQLObjectType || type instanceof _definition.GraphQLInterfaceType) {
var fieldMap = type.getFields();
var fields = Object.keys(fieldMap).map(function (fieldName) {
return fieldMap[fieldName];
});
if (!includeDeprecated) {
fields = fields.filter(function (field) {
return !field.deprecationReason;
});
}
return fields;
}
return null;
}
},
interfaces: {
type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)),
resolve: function resolve(type) {
if (type instanceof _definition.GraphQLObjectType) {
return type.getInterfaces();
}
}
},
possibleTypes: {
type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)),
resolve: function resolve(type, args, context, _ref2) {
var schema = _ref2.schema;
if ((0, _definition.isAbstractType)(type)) {
return schema.getPossibleTypes(type);
}
}
},
enumValues: {
type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__EnumValue)),
args: {
includeDeprecated: { type: _scalars.GraphQLBoolean, defaultValue: false }
},
resolve: function resolve(type, _ref3) {
var includeDeprecated = _ref3.includeDeprecated;
if (type instanceof _definition.GraphQLEnumType) {
var values = type.getValues();
if (!includeDeprecated) {
values = values.filter(function (value) {
return !value.deprecationReason;
});
}
return values;
}
}
},
inputFields: {
type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue)),
resolve: function resolve(type) {
if (type instanceof _definition.GraphQLInputObjectType) {
var fieldMap = type.getFields();
return Object.keys(fieldMap).map(function (fieldName) {
return fieldMap[fieldName];
});
}
}
},
ofType: { type: __Type }
};
}
});
var __Field = exports.__Field = new _definition.GraphQLObjectType({
name: '__Field',
isIntrospection: true,
description: 'Object and Interface types are described by a list of Fields, each of ' + 'which has a name, potentially a list of arguments, and a return type.',
fields: function fields() {
return {
name: { type: new _definition.GraphQLNonNull(_scalars.GraphQLString) },
description: { type: _scalars.GraphQLString },
args: {
type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))),
resolve: function resolve(field) {
return field.args || [];
}
},
type: { type: new _definition.GraphQLNonNull(__Type) },
isDeprecated: { type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean) },
deprecationReason: {
type: _scalars.GraphQLString
}
};
}
});
var __InputValue = exports.__InputValue = new _definition.GraphQLObjectType({
name: '__InputValue',
isIntrospection: true,
description: 'Arguments provided to Fields or Directives and the input fields of an ' + 'InputObject are represented as Input Values which describe their type ' + 'and optionally a default value.',
fields: function fields() {
return {
name: { type: new _definition.GraphQLNonNull(_scalars.GraphQLString) },
description: { type: _scalars.GraphQLString },
type: { type: new _definition.GraphQLNonNull(__Type) },
defaultValue: {
type: _scalars.GraphQLString,
description: 'A GraphQL-formatted string representing the default value for this ' + 'input value.',
resolve: function resolve(inputVal) {
return (0, _isInvalid2.default)(inputVal.defaultValue) ? null : (0, _printer.print)((0, _astFromValue.astFromValue)(inputVal.defaultValue, inputVal.type));
}
}
};
}
});
var __EnumValue = exports.__EnumValue = new _definition.GraphQLObjectType({
name: '__EnumValue',
isIntrospection: true,
description: 'One possible value for a given Enum. Enum values are unique values, not ' + 'a placeholder for a string or numeric value. However an Enum value is ' + 'returned in a JSON response as a string.',
fields: function fields() {
return {
name: { type: new _definition.GraphQLNonNull(_scalars.GraphQLString) },
description: { type: _scalars.GraphQLString },
isDeprecated: { type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean) },
deprecationReason: {
type: _scalars.GraphQLString
}
};
}
});
var TypeKind = exports.TypeKind = {
SCALAR: 'SCALAR',
OBJECT: 'OBJECT',
INTERFACE: 'INTERFACE',
UNION: 'UNION',
ENUM: 'ENUM',
INPUT_OBJECT: 'INPUT_OBJECT',
LIST: 'LIST',
NON_NULL: 'NON_NULL'
};
var __TypeKind = exports.__TypeKind = new _definition.GraphQLEnumType({
name: '__TypeKind',
isIntrospection: true,
description: 'An enum describing what kind of type a given `__Type` is.',
values: {
SCALAR: {
value: TypeKind.SCALAR,
description: 'Indicates this type is a scalar.'
},
OBJECT: {
value: TypeKind.OBJECT,
description: 'Indicates this type is an object. ' + '`fields` and `interfaces` are valid fields.'
},
INTERFACE: {
value: TypeKind.INTERFACE,
description: 'Indicates this type is an interface. ' + '`fields` and `possibleTypes` are valid fields.'
},
UNION: {
value: TypeKind.UNION,
description: 'Indicates this type is a union. ' + '`possibleTypes` is a valid field.'
},
ENUM: {
value: TypeKind.ENUM,
description: 'Indicates this type is an enum. ' + '`enumValues` is a valid field.'
},
INPUT_OBJECT: {
value: TypeKind.INPUT_OBJECT,
description: 'Indicates this type is an input object. ' + '`inputFields` is a valid field.'
},
LIST: {
value: TypeKind.LIST,
description: 'Indicates this type is a list. ' + '`ofType` is a valid field.'
},
NON_NULL: {
value: TypeKind.NON_NULL,
description: 'Indicates this type is a non-null. ' + '`ofType` is a valid field.'
}
}
});
/**
* Note that these are GraphQLField and not GraphQLFieldConfig,
* so the format for args is different.
*/
var SchemaMetaFieldDef = exports.SchemaMetaFieldDef = {
name: '__schema',
type: new _definition.GraphQLNonNull(__Schema),
description: 'Access the current type schema of this server.',
args: [],
resolve: function resolve(source, args, context, _ref4) {
var schema = _ref4.schema;
return schema;
}
};
var TypeMetaFieldDef = exports.TypeMetaFieldDef = {
name: '__type',
type: __Type,
description: 'Request the type information of a single type.',
args: [{ name: 'name', type: new _definition.GraphQLNonNull(_scalars.GraphQLString) }],
resolve: function resolve(source, _ref5, context, _ref6) {
var name = _ref5.name;
var schema = _ref6.schema;
return schema.getType(name);
}
};
var TypeNameMetaFieldDef = exports.TypeNameMetaFieldDef = {
name: '__typename',
type: new _definition.GraphQLNonNull(_scalars.GraphQLString),
description: 'The name of the current Object type at runtime.',
args: [],
resolve: function resolve(source, args, context, _ref7) {
var parentType = _ref7.parentType;
return parentType.name;
}
};
},{"../jsutils/isInvalid":19,"../language/printer":27,"../utilities/astFromValue":36,"./definition":30,"./directives":31,"./scalars":33}],33:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GraphQLID = exports.GraphQLBoolean = exports.GraphQLString = exports.GraphQLFloat = exports.GraphQLInt = undefined;
var _definition = require('./definition');
var _kinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_kinds);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
// As per the GraphQL Spec, Integers are only treated as valid when a valid
// 32-bit signed integer, providing the broadest support across platforms.
//
// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because
// they are internally represented as IEEE 754 doubles.
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var MAX_INT = 2147483647;
var MIN_INT = -2147483648;
function coerceInt(value) {
if (value === '') {
throw new TypeError('Int cannot represent non 32-bit signed integer value: (empty string)');
}
var num = Number(value);
if (num !== num || num > MAX_INT || num < MIN_INT) {
throw new TypeError('Int cannot represent non 32-bit signed integer value: ' + String(value));
}
var int = Math.floor(num);
if (int !== num) {
throw new TypeError('Int cannot represent non-integer value: ' + String(value));
}
return int;
}
var GraphQLInt = exports.GraphQLInt = new _definition.GraphQLScalarType({
name: 'Int',
description: 'The `Int` scalar type represents non-fractional signed whole numeric ' + 'values. Int can represent values between -(2^31) and 2^31 - 1. ',
serialize: coerceInt,
parseValue: coerceInt,
parseLiteral: function parseLiteral(ast) {
if (ast.kind === Kind.INT) {
var num = parseInt(ast.value, 10);
if (num <= MAX_INT && num >= MIN_INT) {
return num;
}
}
return null;
}
});
function coerceFloat(value) {
if (value === '') {
throw new TypeError('Float cannot represent non numeric value: (empty string)');
}
var num = Number(value);
if (num === num) {
return num;
}
throw new TypeError('Float cannot represent non numeric value: ' + String(value));
}
var GraphQLFloat = exports.GraphQLFloat = new _definition.GraphQLScalarType({
name: 'Float',
description: 'The `Float` scalar type represents signed double-precision fractional ' + 'values as specified by ' + '[IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ',
serialize: coerceFloat,
parseValue: coerceFloat,
parseLiteral: function parseLiteral(ast) {
return ast.kind === Kind.FLOAT || ast.kind === Kind.INT ? parseFloat(ast.value) : null;
}
});
var GraphQLString = exports.GraphQLString = new _definition.GraphQLScalarType({
name: 'String',
description: 'The `String` scalar type represents textual data, represented as UTF-8 ' + 'character sequences. The String type is most often used by GraphQL to ' + 'represent free-form human-readable text.',
serialize: String,
parseValue: String,
parseLiteral: function parseLiteral(ast) {
return ast.kind === Kind.STRING ? ast.value : null;
}
});
var GraphQLBoolean = exports.GraphQLBoolean = new _definition.GraphQLScalarType({
name: 'Boolean',
description: 'The `Boolean` scalar type represents `true` or `false`.',
serialize: Boolean,
parseValue: Boolean,
parseLiteral: function parseLiteral(ast) {
return ast.kind === Kind.BOOLEAN ? ast.value : null;
}
});
var GraphQLID = exports.GraphQLID = new _definition.GraphQLScalarType({
name: 'ID',
description: 'The `ID` scalar type represents a unique identifier, often used to ' + 'refetch an object or as key for a cache. The ID type appears in a JSON ' + 'response as a String; however, it is not intended to be human-readable. ' + 'When expected as an input type, any string (such as `"4"`) or integer ' + '(such as `4`) input value will be accepted as an ID.',
serialize: String,
parseValue: String,
parseLiteral: function parseLiteral(ast) {
return ast.kind === Kind.STRING || ast.kind === Kind.INT ? ast.value : null;
}
});
},{"../language/kinds":23,"./definition":30}],34:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GraphQLSchema = undefined;
var _definition = require('./definition');
var _directives = require('./directives');
var _introspection = require('./introspection');
var _find = require('../jsutils/find');
var _find2 = _interopRequireDefault(_find);
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _typeComparators = require('../utilities/typeComparators');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/**
* Schema Definition
*
* A Schema is created by supplying the root types of each type of operation,
* query and mutation (optional). A schema definition is then supplied to the
* validator and executor.
*
* Example:
*
* const MyAppSchema = new GraphQLSchema({
* query: MyAppQueryRootType,
* mutation: MyAppMutationRootType,
* })
*
* Note: If an array of `directives` are provided to GraphQLSchema, that will be
* the exact list of directives represented and allowed. If `directives` is not
* provided then a default set of the specified directives (e.g. @include and
* @skip) will be used. If you wish to provide *additional* directives to these
* specified directives, you must explicitly declare them. Example:
*
* const MyAppSchema = new GraphQLSchema({
* ...
* directives: specifiedDirectives.concat([ myCustomDirective ]),
* })
*
*/
var GraphQLSchema = exports.GraphQLSchema = function () {
function GraphQLSchema(config) {
var _this = this;
_classCallCheck(this, GraphQLSchema);
(0, _invariant2.default)(typeof config === 'object', 'Must provide configuration object.');
(0, _invariant2.default)(config.query instanceof _definition.GraphQLObjectType, 'Schema query must be Object Type but got: ' + String(config.query) + '.');
this._queryType = config.query;
(0, _invariant2.default)(!config.mutation || config.mutation instanceof _definition.GraphQLObjectType, 'Schema mutation must be Object Type if provided but got: ' + String(config.mutation) + '.');
this._mutationType = config.mutation;
(0, _invariant2.default)(!config.subscription || config.subscription instanceof _definition.GraphQLObjectType, 'Schema subscription must be Object Type if provided but got: ' + String(config.subscription) + '.');
this._subscriptionType = config.subscription;
(0, _invariant2.default)(!config.types || Array.isArray(config.types), 'Schema types must be Array if provided but got: ' + String(config.types) + '.');
(0, _invariant2.default)(!config.directives || Array.isArray(config.directives) && config.directives.every(function (directive) {
return directive instanceof _directives.GraphQLDirective;
}), 'Schema directives must be Array<GraphQLDirective> if provided but got: ' + String(config.directives) + '.');
// Provide specified directives (e.g. @include and @skip) by default.
this._directives = config.directives || _directives.specifiedDirectives;
// Build type map now to detect any errors within this schema.
var initialTypes = [this.getQueryType(), this.getMutationType(), this.getSubscriptionType(), _introspection.__Schema];
var types = config.types;
if (types) {
initialTypes = initialTypes.concat(types);
}
this._typeMap = initialTypes.reduce(typeMapReducer, Object.create(null));
// Keep track of all implementations by interface name.
this._implementations = Object.create(null);
Object.keys(this._typeMap).forEach(function (typeName) {
var type = _this._typeMap[typeName];
if (type instanceof _definition.GraphQLObjectType) {
type.getInterfaces().forEach(function (iface) {
var impls = _this._implementations[iface.name];
if (impls) {
impls.push(type);
} else {
_this._implementations[iface.name] = [type];
}
});
}
});
// Enforce correct interface implementations.
Object.keys(this._typeMap).forEach(function (typeName) {
var type = _this._typeMap[typeName];
if (type instanceof _definition.GraphQLObjectType) {
type.getInterfaces().forEach(function (iface) {
return assertObjectImplementsInterface(_this, type, iface);
});
}
});
}
GraphQLSchema.prototype.getQueryType = function getQueryType() {
return this._queryType;
};
GraphQLSchema.prototype.getMutationType = function getMutationType() {
return this._mutationType;
};
GraphQLSchema.prototype.getSubscriptionType = function getSubscriptionType() {
return this._subscriptionType;
};
GraphQLSchema.prototype.getTypeMap = function getTypeMap() {
return this._typeMap;
};
GraphQLSchema.prototype.getType = function getType(name) {
return this.getTypeMap()[name];
};
GraphQLSchema.prototype.getPossibleTypes = function getPossibleTypes(abstractType) {
if (abstractType instanceof _definition.GraphQLUnionType) {
return abstractType.getTypes();
}
(0, _invariant2.default)(abstractType instanceof _definition.GraphQLInterfaceType);
return this._implementations[abstractType.name];
};
GraphQLSchema.prototype.isPossibleType = function isPossibleType(abstractType, possibleType) {
var possibleTypeMap = this._possibleTypeMap;
if (!possibleTypeMap) {
this._possibleTypeMap = possibleTypeMap = Object.create(null);
}
if (!possibleTypeMap[abstractType.name]) {
var possibleTypes = this.getPossibleTypes(abstractType);
(0, _invariant2.default)(Array.isArray(possibleTypes), 'Could not find possible implementing types for ' + abstractType.name + ' ' + 'in schema. Check that schema.types is defined and is an array of ' + 'all possible types in the schema.');
possibleTypeMap[abstractType.name] = possibleTypes.reduce(function (map, type) {
return map[type.name] = true, map;
}, Object.create(null));
}
return Boolean(possibleTypeMap[abstractType.name][possibleType.name]);
};
GraphQLSchema.prototype.getDirectives = function getDirectives() {
return this._directives;
};
GraphQLSchema.prototype.getDirective = function getDirective(name) {
return (0, _find2.default)(this.getDirectives(), function (directive) {
return directive.name === name;
});
};
return GraphQLSchema;
}();
function typeMapReducer(map, type) {
if (!type) {
return map;
}
if (type instanceof _definition.GraphQLList || type instanceof _definition.GraphQLNonNull) {
return typeMapReducer(map, type.ofType);
}
if (map[type.name]) {
(0, _invariant2.default)(map[type.name] === type, 'Schema must contain unique named types but contains multiple ' + ('types named "' + type.name + '".'));
return map;
}
map[type.name] = type;
var reducedMap = map;
if (type instanceof _definition.GraphQLUnionType) {
reducedMap = type.getTypes().reduce(typeMapReducer, reducedMap);
}
if (type instanceof _definition.GraphQLObjectType) {
reducedMap = type.getInterfaces().reduce(typeMapReducer, reducedMap);
}
if (type instanceof _definition.GraphQLObjectType || type instanceof _definition.GraphQLInterfaceType) {
var fieldMap = type.getFields();
Object.keys(fieldMap).forEach(function (fieldName) {
var field = fieldMap[fieldName];
if (field.args) {
var fieldArgTypes = field.args.map(function (arg) {
return arg.type;
});
reducedMap = fieldArgTypes.reduce(typeMapReducer, reducedMap);
}
reducedMap = typeMapReducer(reducedMap, field.type);
});
}
if (type instanceof _definition.GraphQLInputObjectType) {
var _fieldMap = type.getFields();
Object.keys(_fieldMap).forEach(function (fieldName) {
var field = _fieldMap[fieldName];
reducedMap = typeMapReducer(reducedMap, field.type);
});
}
return reducedMap;
}
function assertObjectImplementsInterface(schema, object, iface) {
var objectFieldMap = object.getFields();
var ifaceFieldMap = iface.getFields();
// Assert each interface field is implemented.
Object.keys(ifaceFieldMap).forEach(function (fieldName) {
var objectField = objectFieldMap[fieldName];
var ifaceField = ifaceFieldMap[fieldName];
// Assert interface field exists on object.
(0, _invariant2.default)(objectField, '"' + iface.name + '" expects field "' + fieldName + '" but "' + object.name + '" ' + 'does not provide it.');
// Assert interface field type is satisfied by object field type, by being
// a valid subtype. (covariant)
(0, _invariant2.default)((0, _typeComparators.isTypeSubTypeOf)(schema, objectField.type, ifaceField.type), iface.name + '.' + fieldName + ' expects type "' + String(ifaceField.type) + '" ' + 'but ' + (object.name + '.' + fieldName + ' provides type "' + String(objectField.type) + '".'));
// Assert each interface field arg is implemented.
ifaceField.args.forEach(function (ifaceArg) {
var argName = ifaceArg.name;
var objectArg = (0, _find2.default)(objectField.args, function (arg) {
return arg.name === argName;
});
// Assert interface field arg exists on object field.
(0, _invariant2.default)(objectArg, iface.name + '.' + fieldName + ' expects argument "' + argName + '" but ' + (object.name + '.' + fieldName + ' does not provide it.'));
// Assert interface field arg type matches object field arg type.
// (invariant)
(0, _invariant2.default)((0, _typeComparators.isEqualType)(ifaceArg.type, objectArg.type), iface.name + '.' + fieldName + '(' + argName + ':) expects type ' + ('"' + String(ifaceArg.type) + '" but ') + (object.name + '.' + fieldName + '(' + argName + ':) provides type ') + ('"' + String(objectArg.type) + '".'));
});
// Assert additional arguments must not be required.
objectField.args.forEach(function (objectArg) {
var argName = objectArg.name;
var ifaceArg = (0, _find2.default)(ifaceField.args, function (arg) {
return arg.name === argName;
});
if (!ifaceArg) {
(0, _invariant2.default)(!(objectArg.type instanceof _definition.GraphQLNonNull), object.name + '.' + fieldName + '(' + argName + ':) is of required type ' + ('"' + String(objectArg.type) + '" but is not also provided by the ') + ('interface ' + iface.name + '.' + fieldName + '.'));
}
});
});
}
},{"../jsutils/find":17,"../jsutils/invariant":18,"../utilities/typeComparators":40,"./definition":30,"./directives":31,"./introspection":32}],35:[function(require,module,exports){
(function (process){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.assertValidName = assertValidName;
exports.formatWarning = formatWarning;
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
var ERROR_PREFIX_RX = /^Error: /;
// Silences warnings if an environment flag is enabled
var noNameWarning = Boolean(process && process.env && process.env.GRAPHQL_NO_NAME_WARNING);
// Ensures console warnings are only issued once.
var hasWarnedAboutDunder = false;
/**
* Upholds the spec rules about naming.
*/
function assertValidName(name, isIntrospection) {
if (!name || typeof name !== 'string') {
throw new Error('Must be named. Unexpected name: ' + name + '.');
}
if (!isIntrospection && !hasWarnedAboutDunder && !noNameWarning && name.slice(0, 2) === '__') {
hasWarnedAboutDunder = true;
/* eslint-disable no-console */
if (console && console.warn) {
var error = new Error('Name "' + name + '" must not begin with "__", which is reserved by ' + 'GraphQL introspection. In a future release of graphql this will ' + 'become a hard error.');
console.warn(formatWarning(error));
}
/* eslint-enable no-console */
}
if (!NAME_RX.test(name)) {
throw new Error('Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "' + name + '" does not.');
}
}
/**
* Returns a human-readable warning based an the supplied Error object,
* including stack trace information if available.
*/
function formatWarning(error) {
var formatted = '';
var errorString = String(error).replace(ERROR_PREFIX_RX, '');
var stack = error.stack;
if (stack) {
formatted = stack.replace(ERROR_PREFIX_RX, '');
}
if (formatted.indexOf(errorString) === -1) {
formatted = errorString + '\n' + formatted;
}
return formatted.trim();
}
}).call(this,require('_process'))
},{"_process":66}],36:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.astFromValue = astFromValue;
var _iterall = require('iterall');
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _isNullish = require('../jsutils/isNullish');
var _isNullish2 = _interopRequireDefault(_isNullish);
var _isInvalid = require('../jsutils/isInvalid');
var _isInvalid2 = _interopRequireDefault(_isInvalid);
var _kinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_kinds);
var _definition = require('../type/definition');
var _scalars = require('../type/scalars');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Produces a GraphQL Value AST given a JavaScript value.
*
* A GraphQL type must be provided, which will be used to interpret different
* JavaScript values.
*
* | JSON Value | GraphQL Value |
* | ------------- | -------------------- |
* | Object | Input Object |
* | Array | List |
* | Boolean | Boolean |
* | String | String / Enum Value |
* | Number | Int / Float |
* | Mixed | Enum Value |
* | null | NullValue |
*
*/
function astFromValue(value, type) {
// Ensure flow knows that we treat function params as const.
var _value = value;
if (type instanceof _definition.GraphQLNonNull) {
var astValue = astFromValue(_value, type.ofType);
if (astValue && astValue.kind === Kind.NULL) {
return null;
}
return astValue;
}
// only explicit null, not undefined, NaN
if (_value === null) {
return { kind: Kind.NULL };
}
// undefined, NaN
if ((0, _isInvalid2.default)(_value)) {
return null;
}
// Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
// the value is not an array, convert the value using the list's item type.
if (type instanceof _definition.GraphQLList) {
var itemType = type.ofType;
if ((0, _iterall.isCollection)(_value)) {
var valuesNodes = [];
(0, _iterall.forEach)(_value, function (item) {
var itemNode = astFromValue(item, itemType);
if (itemNode) {
valuesNodes.push(itemNode);
}
});
return { kind: Kind.LIST, values: valuesNodes };
}
return astFromValue(_value, itemType);
}
// Populate the fields of the input object by creating ASTs from each value
// in the JavaScript object according to the fields in the input type.
if (type instanceof _definition.GraphQLInputObjectType) {
if (_value === null || typeof _value !== 'object') {
return null;
}
var fields = type.getFields();
var fieldNodes = [];
Object.keys(fields).forEach(function (fieldName) {
var fieldType = fields[fieldName].type;
var fieldValue = astFromValue(_value[fieldName], fieldType);
if (fieldValue) {
fieldNodes.push({
kind: Kind.OBJECT_FIELD,
name: { kind: Kind.NAME, value: fieldName },
value: fieldValue
});
}
});
return { kind: Kind.OBJECT, fields: fieldNodes };
}
(0, _invariant2.default)(type instanceof _definition.GraphQLScalarType || type instanceof _definition.GraphQLEnumType, 'Must provide Input Type, cannot use: ' + String(type));
// Since value is an internally represented value, it must be serialized
// to an externally represented value before converting into an AST.
var serialized = type.serialize(_value);
if ((0, _isNullish2.default)(serialized)) {
return null;
}
// Others serialize based on their corresponding JavaScript scalar types.
if (typeof serialized === 'boolean') {
return { kind: Kind.BOOLEAN, value: serialized };
}
// JavaScript numbers can be Int or Float values.
if (typeof serialized === 'number') {
var stringNum = String(serialized);
return (/^[0-9]+$/.test(stringNum) ? { kind: Kind.INT, value: stringNum } : { kind: Kind.FLOAT, value: stringNum }
);
}
if (typeof serialized === 'string') {
// Enum types use Enum literals.
if (type instanceof _definition.GraphQLEnumType) {
return { kind: Kind.ENUM, value: serialized };
}
// ID types can use Int literals.
if (type === _scalars.GraphQLID && /^[0-9]+$/.test(serialized)) {
return { kind: Kind.INT, value: serialized };
}
// Use JSON stringify, which uses the same string encoding as GraphQL,
// then remove the quotes.
return {
kind: Kind.STRING,
value: JSON.stringify(serialized).slice(1, -1)
};
}
throw new TypeError('Cannot convert value to AST: ' + String(serialized));
}
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
},{"../jsutils/invariant":18,"../jsutils/isInvalid":19,"../jsutils/isNullish":20,"../language/kinds":23,"../type/definition":30,"../type/scalars":33,"iterall":44}],37:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildASTSchema = buildASTSchema;
exports.getDeprecationReason = getDeprecationReason;
exports.getDescription = getDescription;
exports.buildSchema = buildSchema;
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _keyValMap = require('../jsutils/keyValMap');
var _keyValMap2 = _interopRequireDefault(_keyValMap);
var _valueFromAST = require('./valueFromAST');
var _lexer = require('../language/lexer');
var _parser = require('../language/parser');
var _values = require('../execution/values');
var _kinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_kinds);
var _schema = require('../type/schema');
var _scalars = require('../type/scalars');
var _definition = require('../type/definition');
var _directives = require('../type/directives');
var _introspection = require('../type/introspection');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function buildWrappedType(innerType, inputTypeNode) {
if (inputTypeNode.kind === Kind.LIST_TYPE) {
return new _definition.GraphQLList(buildWrappedType(innerType, inputTypeNode.type));
}
if (inputTypeNode.kind === Kind.NON_NULL_TYPE) {
var wrappedType = buildWrappedType(innerType, inputTypeNode.type);
(0, _invariant2.default)(!(wrappedType instanceof _definition.GraphQLNonNull), 'No nesting nonnull.');
return new _definition.GraphQLNonNull(wrappedType);
}
return innerType;
}
function getNamedTypeNode(typeNode) {
var namedType = typeNode;
while (namedType.kind === Kind.LIST_TYPE || namedType.kind === Kind.NON_NULL_TYPE) {
namedType = namedType.type;
}
return namedType;
}
/**
* This takes the ast of a schema document produced by the parse function in
* src/language/parser.js.
*
* If no schema definition is provided, then it will look for types named Query
* and Mutation.
*
* Given that AST it constructs a GraphQLSchema. The resulting schema
* has no resolve methods, so execution will use default resolvers.
*/
function buildASTSchema(ast) {
if (!ast || ast.kind !== Kind.DOCUMENT) {
throw new Error('Must provide a document ast.');
}
var schemaDef = void 0;
var typeDefs = [];
var nodeMap = Object.create(null);
var directiveDefs = [];
for (var i = 0; i < ast.definitions.length; i++) {
var d = ast.definitions[i];
switch (d.kind) {
case Kind.SCHEMA_DEFINITION:
if (schemaDef) {
throw new Error('Must provide only one schema definition.');
}
schemaDef = d;
break;
case Kind.SCALAR_TYPE_DEFINITION:
case Kind.OBJECT_TYPE_DEFINITION:
case Kind.INTERFACE_TYPE_DEFINITION:
case Kind.ENUM_TYPE_DEFINITION:
case Kind.UNION_TYPE_DEFINITION:
case Kind.INPUT_OBJECT_TYPE_DEFINITION:
var typeName = d.name.value;
if (nodeMap[typeName]) {
throw new Error('Type "' + typeName + '" was defined more than once.');
}
typeDefs.push(d);
nodeMap[typeName] = d;
break;
case Kind.DIRECTIVE_DEFINITION:
directiveDefs.push(d);
break;
}
}
var queryTypeName = void 0;
var mutationTypeName = void 0;
var subscriptionTypeName = void 0;
if (schemaDef) {
schemaDef.operationTypes.forEach(function (operationType) {
var typeName = operationType.type.name.value;
if (operationType.operation === 'query') {
if (queryTypeName) {
throw new Error('Must provide only one query type in schema.');
}
if (!nodeMap[typeName]) {
throw new Error('Specified query type "' + typeName + '" not found in document.');
}
queryTypeName = typeName;
} else if (operationType.operation === 'mutation') {
if (mutationTypeName) {
throw new Error('Must provide only one mutation type in schema.');
}
if (!nodeMap[typeName]) {
throw new Error('Specified mutation type "' + typeName + '" not found in document.');
}
mutationTypeName = typeName;
} else if (operationType.operation === 'subscription') {
if (subscriptionTypeName) {
throw new Error('Must provide only one subscription type in schema.');
}
if (!nodeMap[typeName]) {
throw new Error('Specified subscription type "' + typeName + '" not found in document.');
}
subscriptionTypeName = typeName;
}
});
} else {
if (nodeMap.Query) {
queryTypeName = 'Query';
}
if (nodeMap.Mutation) {
mutationTypeName = 'Mutation';
}
if (nodeMap.Subscription) {
subscriptionTypeName = 'Subscription';
}
}
if (!queryTypeName) {
throw new Error('Must provide schema definition with query type or a type named Query.');
}
var innerTypeMap = {
String: _scalars.GraphQLString,
Int: _scalars.GraphQLInt,
Float: _scalars.GraphQLFloat,
Boolean: _scalars.GraphQLBoolean,
ID: _scalars.GraphQLID,
__Schema: _introspection.__Schema,
__Directive: _introspection.__Directive,
__DirectiveLocation: _introspection.__DirectiveLocation,
__Type: _introspection.__Type,
__Field: _introspection.__Field,
__InputValue: _introspection.__InputValue,
__EnumValue: _introspection.__EnumValue,
__TypeKind: _introspection.__TypeKind
};
var types = typeDefs.map(function (def) {
return typeDefNamed(def.name.value);
});
var directives = directiveDefs.map(getDirective);
// If specified directives were not explicitly declared, add them.
if (!directives.some(function (directive) {
return directive.name === 'skip';
})) {
directives.push(_directives.GraphQLSkipDirective);
}
if (!directives.some(function (directive) {
return directive.name === 'include';
})) {
directives.push(_directives.GraphQLIncludeDirective);
}
if (!directives.some(function (directive) {
return directive.name === 'deprecated';
})) {
directives.push(_directives.GraphQLDeprecatedDirective);
}
return new _schema.GraphQLSchema({
query: getObjectType(nodeMap[queryTypeName]),
mutation: mutationTypeName ? getObjectType(nodeMap[mutationTypeName]) : null,
subscription: subscriptionTypeName ? getObjectType(nodeMap[subscriptionTypeName]) : null,
types: types,
directives: directives
});
function getDirective(directiveNode) {
return new _directives.GraphQLDirective({
name: directiveNode.name.value,
description: getDescription(directiveNode),
locations: directiveNode.locations.map(function (node) {
return node.value;
}),
args: directiveNode.arguments && makeInputValues(directiveNode.arguments)
});
}
function getObjectType(typeNode) {
var type = typeDefNamed(typeNode.name.value);
(0, _invariant2.default)(type instanceof _definition.GraphQLObjectType, 'AST must provide object type.');
return type;
}
function produceType(typeNode) {
var typeName = getNamedTypeNode(typeNode).name.value;
var typeDef = typeDefNamed(typeName);
return buildWrappedType(typeDef, typeNode);
}
function produceInputType(typeNode) {
return (0, _definition.assertInputType)(produceType(typeNode));
}
function produceOutputType(typeNode) {
return (0, _definition.assertOutputType)(produceType(typeNode));
}
function produceObjectType(typeNode) {
var type = produceType(typeNode);
(0, _invariant2.default)(type instanceof _definition.GraphQLObjectType, 'Expected Object type.');
return type;
}
function produceInterfaceType(typeNode) {
var type = produceType(typeNode);
(0, _invariant2.default)(type instanceof _definition.GraphQLInterfaceType, 'Expected Interface type.');
return type;
}
function typeDefNamed(typeName) {
if (innerTypeMap[typeName]) {
return innerTypeMap[typeName];
}
if (!nodeMap[typeName]) {
throw new Error('Type "' + typeName + '" not found in document.');
}
var innerTypeDef = makeSchemaDef(nodeMap[typeName]);
if (!innerTypeDef) {
throw new Error('Nothing constructed for "' + typeName + '".');
}
innerTypeMap[typeName] = innerTypeDef;
return innerTypeDef;
}
function makeSchemaDef(def) {
if (!def) {
throw new Error('def must be defined');
}
switch (def.kind) {
case Kind.OBJECT_TYPE_DEFINITION:
return makeTypeDef(def);
case Kind.INTERFACE_TYPE_DEFINITION:
return makeInterfaceDef(def);
case Kind.ENUM_TYPE_DEFINITION:
return makeEnumDef(def);
case Kind.UNION_TYPE_DEFINITION:
return makeUnionDef(def);
case Kind.SCALAR_TYPE_DEFINITION:
return makeScalarDef(def);
case Kind.INPUT_OBJECT_TYPE_DEFINITION:
return makeInputObjectDef(def);
default:
throw new Error('Type kind "' + def.kind + '" not supported.');
}
}
function makeTypeDef(def) {
var typeName = def.name.value;
return new _definition.GraphQLObjectType({
name: typeName,
description: getDescription(def),
fields: function fields() {
return makeFieldDefMap(def);
},
interfaces: function interfaces() {
return makeImplementedInterfaces(def);
}
});
}
function makeFieldDefMap(def) {
return (0, _keyValMap2.default)(def.fields, function (field) {
return field.name.value;
}, function (field) {
return {
type: produceOutputType(field.type),
description: getDescription(field),
args: makeInputValues(field.arguments),
deprecationReason: getDeprecationReason(field)
};
});
}
function makeImplementedInterfaces(def) {
return def.interfaces && def.interfaces.map(function (iface) {
return produceInterfaceType(iface);
});
}
function makeInputValues(values) {
return (0, _keyValMap2.default)(values, function (value) {
return value.name.value;
}, function (value) {
var type = produceInputType(value.type);
return {
type: type,
description: getDescription(value),
defaultValue: (0, _valueFromAST.valueFromAST)(value.defaultValue, type)
};
});
}
function makeInterfaceDef(def) {
var typeName = def.name.value;
return new _definition.GraphQLInterfaceType({
name: typeName,
description: getDescription(def),
fields: function fields() {
return makeFieldDefMap(def);
},
resolveType: cannotExecuteSchema
});
}
function makeEnumDef(def) {
var enumType = new _definition.GraphQLEnumType({
name: def.name.value,
description: getDescription(def),
values: (0, _keyValMap2.default)(def.values, function (enumValue) {
return enumValue.name.value;
}, function (enumValue) {
return {
description: getDescription(enumValue),
deprecationReason: getDeprecationReason(enumValue)
};
})
});
return enumType;
}
function makeUnionDef(def) {
return new _definition.GraphQLUnionType({
name: def.name.value,
description: getDescription(def),
types: def.types.map(function (t) {
return produceObjectType(t);
}),
resolveType: cannotExecuteSchema
});
}
function makeScalarDef(def) {
return new _definition.GraphQLScalarType({
name: def.name.value,
description: getDescription(def),
serialize: function serialize() {
return null;
},
// Note: validation calls the parse functions to determine if a
// literal value is correct. Returning null would cause use of custom
// scalars to always fail validation. Returning false causes them to
// always pass validation.
parseValue: function parseValue() {
return false;
},
parseLiteral: function parseLiteral() {
return false;
}
});
}
function makeInputObjectDef(def) {
return new _definition.GraphQLInputObjectType({
name: def.name.value,
description: getDescription(def),
fields: function fields() {
return makeInputValues(def.fields);
}
});
}
}
/**
* Given a field or enum value node, returns the string value for the
* deprecation reason.
*/
function getDeprecationReason(node) {
var deprecated = (0, _values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective, node);
return deprecated && deprecated.reason;
}
/**
* Given an ast node, returns its string description based on a contiguous
* block full-line of comments preceding it.
*/
function getDescription(node) {
var loc = node.loc;
if (!loc) {
return;
}
var comments = [];
var minSpaces = void 0;
var token = loc.startToken.prev;
while (token && token.kind === _lexer.TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) {
var value = String(token.value);
var spaces = leadingSpaces(value);
if (minSpaces === undefined || spaces < minSpaces) {
minSpaces = spaces;
}
comments.push(value);
token = token.prev;
}
return comments.reverse().map(function (comment) {
return comment.slice(minSpaces);
}).join('\n');
}
/**
* A helper function to build a GraphQLSchema directly from a source
* document.
*/
function buildSchema(source) {
return buildASTSchema((0, _parser.parse)(source));
}
// Count the number of spaces on the starting side of a string.
function leadingSpaces(str) {
var i = 0;
for (; i < str.length; i++) {
if (str[i] !== ' ') {
break;
}
}
return i;
}
function cannotExecuteSchema() {
throw new Error('Generated Schema cannot use Interface or Union types for execution.');
}
},{"../execution/values":16,"../jsutils/invariant":18,"../jsutils/keyValMap":22,"../language/kinds":23,"../language/lexer":24,"../language/parser":26,"../type/definition":30,"../type/directives":31,"../type/introspection":32,"../type/scalars":33,"../type/schema":34,"./valueFromAST":42}],38:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isValidJSValue = isValidJSValue;
var _iterall = require('iterall');
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _isNullish = require('../jsutils/isNullish');
var _isNullish2 = _interopRequireDefault(_isNullish);
var _definition = require('../type/definition');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Given a JavaScript value and a GraphQL type, determine if the value will be
* accepted for that type. This is primarily useful for validating the
* runtime values of query variables.
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function isValidJSValue(value, type) {
// A value must be provided if the type is non-null.
if (type instanceof _definition.GraphQLNonNull) {
if ((0, _isNullish2.default)(value)) {
return ['Expected "' + String(type) + '", found null.'];
}
return isValidJSValue(value, type.ofType);
}
if ((0, _isNullish2.default)(value)) {
return [];
}
// Lists accept a non-list value as a list of one.
if (type instanceof _definition.GraphQLList) {
var itemType = type.ofType;
if ((0, _iterall.isCollection)(value)) {
var errors = [];
(0, _iterall.forEach)(value, function (item, index) {
errors.push.apply(errors, isValidJSValue(item, itemType).map(function (error) {
return 'In element #' + index + ': ' + error;
}));
});
return errors;
}
return isValidJSValue(value, itemType);
}
// Input objects check each defined field.
if (type instanceof _definition.GraphQLInputObjectType) {
if (typeof value !== 'object' || value === null) {
return ['Expected "' + type.name + '", found not an object.'];
}
var fields = type.getFields();
var _errors = [];
// Ensure every provided field is defined.
Object.keys(value).forEach(function (providedField) {
if (!fields[providedField]) {
_errors.push('In field "' + providedField + '": Unknown field.');
}
});
// Ensure every defined field is valid.
Object.keys(fields).forEach(function (fieldName) {
var newErrors = isValidJSValue(value[fieldName], fields[fieldName].type);
_errors.push.apply(_errors, newErrors.map(function (error) {
return 'In field "' + fieldName + '": ' + error;
}));
});
return _errors;
}
(0, _invariant2.default)(type instanceof _definition.GraphQLScalarType || type instanceof _definition.GraphQLEnumType, 'Must be input type');
// Scalar/Enum input checks to ensure the type can parse the value to
// a non-null value.
try {
var parseResult = type.parseValue(value);
if ((0, _isNullish2.default)(parseResult) && !type.isValidValue(value)) {
return ['Expected type "' + type.name + '", found ' + JSON.stringify(value) + '.'];
}
} catch (error) {
return ['Expected type "' + type.name + '", found ' + JSON.stringify(value) + ': ' + error.message];
}
return [];
}
},{"../jsutils/invariant":18,"../jsutils/isNullish":20,"../type/definition":30,"iterall":44}],39:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isValidLiteralValue = isValidLiteralValue;
var _printer = require('../language/printer');
var _kinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_kinds);
var _definition = require('../type/definition');
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _keyMap = require('../jsutils/keyMap');
var _keyMap2 = _interopRequireDefault(_keyMap);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* Utility for validators which determines if a value literal node is valid
* given an input type.
*
* Note that this only validates literal values, variables are assumed to
* provide values of the correct type.
*/
function isValidLiteralValue(type, valueNode) {
// A value must be provided if the type is non-null.
if (type instanceof _definition.GraphQLNonNull) {
if (!valueNode || valueNode.kind === Kind.NULL) {
return ['Expected "' + String(type) + '", found null.'];
}
return isValidLiteralValue(type.ofType, valueNode);
}
if (!valueNode || valueNode.kind === Kind.NULL) {
return [];
}
// This function only tests literals, and assumes variables will provide
// values of the correct type.
if (valueNode.kind === Kind.VARIABLE) {
return [];
}
// Lists accept a non-list value as a list of one.
if (type instanceof _definition.GraphQLList) {
var itemType = type.ofType;
if (valueNode.kind === Kind.LIST) {
return valueNode.values.reduce(function (acc, item, index) {
var errors = isValidLiteralValue(itemType, item);
return acc.concat(errors.map(function (error) {
return 'In element #' + index + ': ' + error;
}));
}, []);
}
return isValidLiteralValue(itemType, valueNode);
}
// Input objects check each defined field and look for undefined fields.
if (type instanceof _definition.GraphQLInputObjectType) {
if (valueNode.kind !== Kind.OBJECT) {
return ['Expected "' + type.name + '", found not an object.'];
}
var fields = type.getFields();
var errors = [];
// Ensure every provided field is defined.
var fieldNodes = valueNode.fields;
fieldNodes.forEach(function (providedFieldNode) {
if (!fields[providedFieldNode.name.value]) {
errors.push('In field "' + providedFieldNode.name.value + '": Unknown field.');
}
});
// Ensure every defined field is valid.
var fieldNodeMap = (0, _keyMap2.default)(fieldNodes, function (fieldNode) {
return fieldNode.name.value;
});
Object.keys(fields).forEach(function (fieldName) {
var result = isValidLiteralValue(fields[fieldName].type, fieldNodeMap[fieldName] && fieldNodeMap[fieldName].value);
errors.push.apply(errors, result.map(function (error) {
return 'In field "' + fieldName + '": ' + error;
}));
});
return errors;
}
(0, _invariant2.default)(type instanceof _definition.GraphQLScalarType || type instanceof _definition.GraphQLEnumType, 'Must be input type');
// Scalars determine if a literal values is valid.
if (!type.isValidLiteral(valueNode)) {
return ['Expected type "' + type.name + '", found ' + (0, _printer.print)(valueNode) + '.'];
}
return [];
}
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
},{"../jsutils/invariant":18,"../jsutils/keyMap":21,"../language/kinds":23,"../language/printer":27,"../type/definition":30}],40:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isEqualType = isEqualType;
exports.isTypeSubTypeOf = isTypeSubTypeOf;
exports.doTypesOverlap = doTypesOverlap;
var _definition = require('../type/definition');
/**
* Provided two types, return true if the types are equal (invariant).
*/
function isEqualType(typeA, typeB) {
// Equivalent types are equal.
if (typeA === typeB) {
return true;
}
// If either type is non-null, the other must also be non-null.
if (typeA instanceof _definition.GraphQLNonNull && typeB instanceof _definition.GraphQLNonNull) {
return isEqualType(typeA.ofType, typeB.ofType);
}
// If either type is a list, the other must also be a list.
if (typeA instanceof _definition.GraphQLList && typeB instanceof _definition.GraphQLList) {
return isEqualType(typeA.ofType, typeB.ofType);
}
// Otherwise the types are not equal.
return false;
}
/**
* Provided a type and a super type, return true if the first type is either
* equal or a subset of the second super type (covariant).
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function isTypeSubTypeOf(schema, maybeSubType, superType) {
// Equivalent type is a valid subtype
if (maybeSubType === superType) {
return true;
}
// If superType is non-null, maybeSubType must also be non-null.
if (superType instanceof _definition.GraphQLNonNull) {
if (maybeSubType instanceof _definition.GraphQLNonNull) {
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
}
return false;
} else if (maybeSubType instanceof _definition.GraphQLNonNull) {
// If superType is nullable, maybeSubType may be non-null or nullable.
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);
}
// If superType type is a list, maybeSubType type must also be a list.
if (superType instanceof _definition.GraphQLList) {
if (maybeSubType instanceof _definition.GraphQLList) {
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
}
return false;
} else if (maybeSubType instanceof _definition.GraphQLList) {
// If superType is not a list, maybeSubType must also be not a list.
return false;
}
// If superType type is an abstract type, maybeSubType type may be a currently
// possible object type.
if ((0, _definition.isAbstractType)(superType) && maybeSubType instanceof _definition.GraphQLObjectType && schema.isPossibleType(superType, maybeSubType)) {
return true;
}
// Otherwise, the child type is not a valid subtype of the parent type.
return false;
}
/**
* Provided two composite types, determine if they "overlap". Two composite
* types overlap when the Sets of possible concrete types for each intersect.
*
* This is often used to determine if a fragment of a given type could possibly
* be visited in a context of another type.
*
* This function is commutative.
*/
function doTypesOverlap(schema, typeA, typeB) {
// So flow is aware this is constant
var _typeB = typeB;
// Equivalent types overlap
if (typeA === _typeB) {
return true;
}
if ((0, _definition.isAbstractType)(typeA)) {
if ((0, _definition.isAbstractType)(_typeB)) {
// If both types are abstract, then determine if there is any intersection
// between possible concrete types of each.
return schema.getPossibleTypes(typeA).some(function (type) {
return schema.isPossibleType(_typeB, type);
});
}
// Determine if the latter type is a possible concrete type of the former.
return schema.isPossibleType(typeA, _typeB);
}
if ((0, _definition.isAbstractType)(_typeB)) {
// Determine if the former type is a possible concrete type of the latter.
return schema.isPossibleType(_typeB, typeA);
}
// Otherwise the types do not overlap.
return false;
}
},{"../type/definition":30}],41:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.typeFromAST = undefined;
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _kinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_kinds);
var _definition = require('../type/definition');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Given a Schema and an AST node describing a type, return a GraphQLType
* definition which applies to that type. For example, if provided the parsed
* AST node for `[User]`, a GraphQLList instance will be returned, containing
* the type called "User" found in the schema. If a type called "User" is not
* found in the schema, then undefined will be returned.
*/
/* eslint-disable no-redeclare */
function typeFromASTImpl(schema, typeNode) {
/* eslint-enable no-redeclare */
var innerType = void 0;
if (typeNode.kind === Kind.LIST_TYPE) {
innerType = typeFromAST(schema, typeNode.type);
return innerType && new _definition.GraphQLList(innerType);
}
if (typeNode.kind === Kind.NON_NULL_TYPE) {
innerType = typeFromAST(schema, typeNode.type);
return innerType && new _definition.GraphQLNonNull(innerType);
}
(0, _invariant2.default)(typeNode.kind === Kind.NAMED_TYPE, 'Must be a named type.');
return schema.getType(typeNode.name.value);
}
// This will export typeFromAST with the correct type, but currently exposes
// ~26 errors: https://gist.github.com/4a29403a99a8186fcb15064d69c5f3ae
// export var typeFromAST: typeof typeFromASTType = typeFromASTImpl;
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var typeFromAST = exports.typeFromAST = typeFromASTImpl;
},{"../jsutils/invariant":18,"../language/kinds":23,"../type/definition":30}],42:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.valueFromAST = valueFromAST;
var _keyMap = require('../jsutils/keyMap');
var _keyMap2 = _interopRequireDefault(_keyMap);
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _isNullish = require('../jsutils/isNullish');
var _isNullish2 = _interopRequireDefault(_isNullish);
var _isInvalid = require('../jsutils/isInvalid');
var _isInvalid2 = _interopRequireDefault(_isInvalid);
var _kinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_kinds);
var _definition = require('../type/definition');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Produces a JavaScript value given a GraphQL Value AST.
*
* A GraphQL type must be provided, which will be used to interpret different
* GraphQL Value literals.
*
* Returns `undefined` when the value could not be validly coerced according to
* the provided type.
*
* | GraphQL Value | JSON Value |
* | -------------------- | ------------- |
* | Input Object | Object |
* | List | Array |
* | Boolean | Boolean |
* | String | String |
* | Int / Float | Number |
* | Enum Value | Mixed |
* | NullValue | null |
*
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function valueFromAST(valueNode, type, variables) {
if (!valueNode) {
// When there is no node, then there is also no value.
// Importantly, this is different from returning the value null.
return;
}
if (type instanceof _definition.GraphQLNonNull) {
if (valueNode.kind === Kind.NULL) {
return; // Invalid: intentionally return no value.
}
return valueFromAST(valueNode, type.ofType, variables);
}
if (valueNode.kind === Kind.NULL) {
// This is explicitly returning the value null.
return null;
}
if (valueNode.kind === Kind.VARIABLE) {
var variableName = valueNode.name.value;
if (!variables || (0, _isInvalid2.default)(variables[variableName])) {
// No valid return value.
return;
}
// Note: we're not doing any checking that this variable is correct. We're
// assuming that this query has been validated and the variable usage here
// is of the correct type.
return variables[variableName];
}
if (type instanceof _definition.GraphQLList) {
var itemType = type.ofType;
if (valueNode.kind === Kind.LIST) {
var coercedValues = [];
var itemNodes = valueNode.values;
for (var i = 0; i < itemNodes.length; i++) {
if (isMissingVariable(itemNodes[i], variables)) {
// If an array contains a missing variable, it is either coerced to
// null or if the item type is non-null, it considered invalid.
if (itemType instanceof _definition.GraphQLNonNull) {
return; // Invalid: intentionally return no value.
}
coercedValues.push(null);
} else {
var itemValue = valueFromAST(itemNodes[i], itemType, variables);
if ((0, _isInvalid2.default)(itemValue)) {
return; // Invalid: intentionally return no value.
}
coercedValues.push(itemValue);
}
}
return coercedValues;
}
var coercedValue = valueFromAST(valueNode, itemType, variables);
if ((0, _isInvalid2.default)(coercedValue)) {
return; // Invalid: intentionally return no value.
}
return [coercedValue];
}
if (type instanceof _definition.GraphQLInputObjectType) {
if (valueNode.kind !== Kind.OBJECT) {
return; // Invalid: intentionally return no value.
}
var coercedObj = Object.create(null);
var fields = type.getFields();
var fieldNodes = (0, _keyMap2.default)(valueNode.fields, function (field) {
return field.name.value;
});
var fieldNames = Object.keys(fields);
for (var _i = 0; _i < fieldNames.length; _i++) {
var fieldName = fieldNames[_i];
var field = fields[fieldName];
var fieldNode = fieldNodes[fieldName];
if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {
if (!(0, _isInvalid2.default)(field.defaultValue)) {
coercedObj[fieldName] = field.defaultValue;
} else if (field.type instanceof _definition.GraphQLNonNull) {
return; // Invalid: intentionally return no value.
}
continue;
}
var fieldValue = valueFromAST(fieldNode.value, field.type, variables);
if ((0, _isInvalid2.default)(fieldValue)) {
return; // Invalid: intentionally return no value.
}
coercedObj[fieldName] = fieldValue;
}
return coercedObj;
}
(0, _invariant2.default)(type instanceof _definition.GraphQLScalarType || type instanceof _definition.GraphQLEnumType, 'Must be input type');
var parsed = type.parseLiteral(valueNode);
if ((0, _isNullish2.default)(parsed) && !type.isValidLiteral(valueNode)) {
// Invalid values represent a failure to parse correctly, in which case
// no value is returned.
return;
}
return parsed;
}
// Returns true if the provided valueNode is a variable which is not defined
// in the set of variables.
function isMissingVariable(valueNode, variables) {
return valueNode.kind === Kind.VARIABLE && (!variables || (0, _isInvalid2.default)(variables[valueNode.name.value]));
}
},{"../jsutils/invariant":18,"../jsutils/isInvalid":19,"../jsutils/isNullish":20,"../jsutils/keyMap":21,"../language/kinds":23,"../type/definition":30}],43:[function(require,module,exports){
// the whatwg-fetch polyfill installs the fetch() function
// on the global object (window or self)
//
// Return that as the export for use in Webpack, Browserify etc.
require('whatwg-fetch');
module.exports = self.fetch.bind(self);
},{"whatwg-fetch":65}],44:[function(require,module,exports){
/**
* Copyright (c) 2016, Lee Byron
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @ignore
*/
/**
* [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator)
* is a *protocol* which describes a standard way to produce a sequence of
* values, typically the values of the Iterable represented by this Iterator.
*
* While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface)
* it can be utilized by any version of JavaScript.
*
* @typedef {Object} Iterator
* @template T The type of each iterated value
* @property {function (): { value: T, done: boolean }} next
* A method which produces either the next value in a sequence or a result
* where the `done` property is `true` indicating the end of the Iterator.
*/
/**
* [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
* is a *protocol* which when implemented allows a JavaScript object to define
* their iteration behavior, such as what values are looped over in a `for..of`
* loop or `iterall`'s `forEach` function. Many [built-in types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables)
* implement the Iterable protocol, including `Array` and `Map`.
*
* While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface)
* it can be utilized by any version of JavaScript.
*
* @typedef {Object} Iterable
* @template T The type of each iterated value
* @property {function (): Iterator<T>} Symbol.iterator
* A method which produces an Iterator for this Iterable.
*/
// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator
var SYMBOL_ITERATOR = typeof Symbol === 'function' && Symbol.iterator
/**
* A property name to be used as the name of an Iterable's method responsible
* for producing an Iterator, referred to as `@@iterator`. Typically represents
* the value `Symbol.iterator` but falls back to the string `"@@iterator"` when
* `Symbol.iterator` is not defined.
*
* Use `$$iterator` for defining new Iterables instead of `Symbol.iterator`,
* but do not use it for accessing existing Iterables, instead use
* `getIterator()` or `isIterable()`.
*
* @example
*
* var $$iterator = require('iterall').$$iterator
*
* function Counter (to) {
* this.to = to
* }
*
* Counter.prototype[$$iterator] = function () {
* return {
* to: this.to,
* num: 0,
* next () {
* if (this.num >= this.to) {
* return { value: undefined, done: true }
* }
* return { value: this.num++, done: false }
* }
* }
* }
*
* var counter = new Counter(3)
* for (var number of counter) {
* console.log(number) // 0 ... 1 ... 2
* }
*
* @type {Symbol|string}
*/
var $$iterator = SYMBOL_ITERATOR || '@@iterator'
exports.$$iterator = $$iterator
/**
* Returns true if the provided object implements the Iterator protocol via
* either implementing a `Symbol.iterator` or `"@@iterator"` method.
*
* @example
*
* var isIterable = require('iterall').isIterable
* isIterable([ 1, 2, 3 ]) // true
* isIterable('ABC') // true
* isIterable({ length: 1, 0: 'Alpha' }) // false
* isIterable({ key: 'value' }) // false
* isIterable(new Map()) // true
*
* @param obj
* A value which might implement the Iterable protocol.
* @return {boolean} true if Iterable.
*/
function isIterable(obj) {
return !!getIteratorMethod(obj)
}
exports.isIterable = isIterable
/**
* Returns true if the provided object implements the Array-like protocol via
* defining a positive-integer `length` property.
*
* @example
*
* var isArrayLike = require('iterall').isArrayLike
* isArrayLike([ 1, 2, 3 ]) // true
* isArrayLike('ABC') // true
* isArrayLike({ length: 1, 0: 'Alpha' }) // true
* isArrayLike({ key: 'value' }) // false
* isArrayLike(new Map()) // false
*
* @param obj
* A value which might implement the Array-like protocol.
* @return {boolean} true if Array-like.
*/
function isArrayLike(obj) {
var length = obj != null && obj.length
return typeof length === 'number' && length >= 0 && length % 1 === 0
}
exports.isArrayLike = isArrayLike
/**
* Returns true if the provided object is an Object (i.e. not a string literal)
* and is either Iterable or Array-like.
*
* This may be used in place of [Array.isArray()][isArray] to determine if an
* object should be iterated-over. It always excludes string literals and
* includes Arrays (regardless of if it is Iterable). It also includes other
* Array-like objects such as NodeList, TypedArray, and Buffer.
*
* @example
*
* var isCollection = require('iterall').isCollection
* isCollection([ 1, 2, 3 ]) // true
* isCollection('ABC') // false
* isCollection({ length: 1, 0: 'Alpha' }) // true
* isCollection({ key: 'value' }) // false
* isCollection(new Map()) // true
*
* @example
*
* var forEach = require('iterall').forEach
* if (isCollection(obj)) {
* forEach(obj, function (value) {
* console.log(value)
* })
* }
*
* @param obj
* An Object value which might implement the Iterable or Array-like protocols.
* @return {boolean} true if Iterable or Array-like Object.
*/
function isCollection(obj) {
return Object(obj) === obj && (isArrayLike(obj) || isIterable(obj))
}
exports.isCollection = isCollection
/**
* If the provided object implements the Iterator protocol, its Iterator object
* is returned. Otherwise returns undefined.
*
* @example
*
* var getIterator = require('iterall').getIterator
* var iterator = getIterator([ 1, 2, 3 ])
* iterator.next() // { value: 1, done: false }
* iterator.next() // { value: 2, done: false }
* iterator.next() // { value: 3, done: false }
* iterator.next() // { value: undefined, done: true }
*
* @template T the type of each iterated value
* @param {Iterable<T>} iterable
* An Iterable object which is the source of an Iterator.
* @return {Iterator<T>} new Iterator instance.
*/
function getIterator(iterable) {
var method = getIteratorMethod(iterable)
if (method) {
return method.call(iterable)
}
}
exports.getIterator = getIterator
/**
* If the provided object implements the Iterator protocol, the method
* responsible for producing its Iterator object is returned.
*
* This is used in rare cases for performance tuning. This method must be called
* with obj as the contextual this-argument.
*
* @example
*
* var getIteratorMethod = require('iterall').getIteratorMethod
* var myArray = [ 1, 2, 3 ]
* var method = getIteratorMethod(myArray)
* if (method) {
* var iterator = method.call(myArray)
* }
*
* @template T the type of each iterated value
* @param {Iterable<T>} iterable
* An Iterable object which defines an `@@iterator` method.
* @return {function(): Iterator<T>} `@@iterator` method.
*/
function getIteratorMethod(iterable) {
if (iterable != null) {
var method =
(SYMBOL_ITERATOR && iterable[SYMBOL_ITERATOR]) || iterable['@@iterator']
if (typeof method === 'function') {
return method
}
}
}
exports.getIteratorMethod = getIteratorMethod
/**
* Similar to `getIterator()`, this method returns a new Iterator given an
* Iterable. However it will also create an Iterator for a non-Iterable
* Array-like collection, such as Array in a non-ES2015 environment.
*
* `createIterator` is complimentary to `forEach`, but allows a "pull"-based
* iteration as opposed to `forEach`'s "push"-based iteration.
*
* `createIterator` produces an Iterator for Array-likes with the same behavior
* as ArrayIteratorPrototype described in the ECMAScript specification, and
* does *not* skip over "holes".
*
* @example
*
* var createIterator = require('iterall').createIterator
*
* var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' }
* var iterator = createIterator(myArraylike)
* iterator.next() // { value: 'Alpha', done: false }
* iterator.next() // { value: 'Bravo', done: false }
* iterator.next() // { value: 'Charlie', done: false }
* iterator.next() // { value: undefined, done: true }
*
* @template T the type of each iterated value
* @param {Iterable<T>|{ length: number }} collection
* An Iterable or Array-like object to produce an Iterator.
* @return {Iterator<T>} new Iterator instance.
*/
function createIterator(collection) {
if (collection != null) {
var iterator = getIterator(collection)
if (iterator) {
return iterator
}
if (isArrayLike(collection)) {
return new ArrayLikeIterator(collection)
}
}
}
exports.createIterator = createIterator
// When the object provided to `createIterator` is not Iterable but is
// Array-like, this simple Iterator is created.
function ArrayLikeIterator(obj) {
this._o = obj
this._i = 0
}
// Note: all Iterators are themselves Iterable.
ArrayLikeIterator.prototype[$$iterator] = function() {
return this
}
// A simple state-machine determines the IteratorResult returned, yielding
// each value in the Array-like object in order of their indicies.
ArrayLikeIterator.prototype.next = function() {
if (this._o === void 0 || this._i >= this._o.length) {
this._o = void 0
return { value: void 0, done: true }
}
return { value: this._o[this._i++], done: false }
}
/**
* Given an object which either implements the Iterable protocol or is
* Array-like, iterate over it, calling the `callback` at each iteration.
*
* Use `forEach` where you would expect to use a `for ... of` loop in ES6.
* However `forEach` adheres to the behavior of [Array#forEach][] described in
* the ECMAScript specification, skipping over "holes" in Array-likes. It will
* also delegate to a `forEach` method on `collection` if one is defined,
* ensuring native performance for `Arrays`.
*
* Similar to [Array#forEach][], the `callback` function accepts three
* arguments, and is provided with `thisArg` as the calling context.
*
* Note: providing an infinite Iterator to forEach will produce an error.
*
* [Array#forEach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
*
* @example
*
* var forEach = require('iterall').forEach
*
* forEach(myIterable, function (value, index, iterable) {
* console.log(value, index, iterable === myIterable)
* })
*
* @example
*
* // ES6:
* for (let value of myIterable) {
* console.log(value)
* }
*
* // Any JavaScript environment:
* forEach(myIterable, function (value) {
* console.log(value)
* })
*
* @template T the type of each iterated value
* @param {Iterable<T>|{ length: number }} collection
* The Iterable or array to iterate over.
* @param {function(T, number, object)} callback
* Function to execute for each iteration, taking up to three arguments
* @param [thisArg]
* Optional. Value to use as `this` when executing `callback`.
*/
function forEach(collection, callback, thisArg) {
if (collection != null) {
if (typeof collection.forEach === 'function') {
return collection.forEach(callback, thisArg)
}
var i = 0
var iterator = getIterator(collection)
if (iterator) {
var step
while (!(step = iterator.next()).done) {
callback.call(thisArg, step.value, i++, collection)
// Infinite Iterators could cause forEach to run forever.
// After a very large number of iterations, produce an error.
/* istanbul ignore if */
if (i > 9999999) {
throw new TypeError('Near-infinite iteration.')
}
}
} else if (isArrayLike(collection)) {
for (; i < collection.length; i++) {
if (collection.hasOwnProperty(i)) {
callback.call(thisArg, collection[i], i, collection)
}
}
}
}
}
exports.forEach = forEach
/////////////////////////////////////////////////////
// //
// ASYNC ITERATORS //
// //
/////////////////////////////////////////////////////
/**
* [AsyncIterator](https://tc39.github.io/proposal-async-iteration/)
* is a *protocol* which describes a standard way to produce and consume an
* asynchronous sequence of values, typically the values of the AsyncIterable
* represented by this AsyncIterator.
*
* AsyncIterator is similar to Observable or Stream.
*
* While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/)
* it can be utilized by any version of JavaScript.
*
* @typedef {Object} AsyncIterator
* @template T The type of each iterated value
* @property {function (): Promise<{ value: T, done: boolean }>} next
* A method which produces a Promise which resolves to either the next value
* in a sequence or a result where the `done` property is `true` indicating
* the end of the sequence of values. It may also produce a Promise which
* becomes rejected, indicating a failure.
*/
/**
* AsyncIterable is a *protocol* which when implemented allows a JavaScript
* object to define their asynchronous iteration behavior, such as what values
* are looped over in a `for-await-of` loop or `iterall`'s `forAwaitEach`
* function.
*
* While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/)
* it can be utilized by any version of JavaScript.
*
* @typedef {Object} AsyncIterable
* @template T The type of each iterated value
* @property {function (): AsyncIterator<T>} Symbol.asyncIterator
* A method which produces an AsyncIterator for this AsyncIterable.
*/
// In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator
var SYMBOL_ASYNC_ITERATOR = typeof Symbol === 'function' && Symbol.asyncIterator
/**
* A property name to be used as the name of an AsyncIterable's method
* responsible for producing an Iterator, referred to as `@@asyncIterator`.
* Typically represents the value `Symbol.asyncIterator` but falls back to the
* string `"@@asyncIterator"` when `Symbol.asyncIterator` is not defined.
*
* Use `$$asyncIterator` for defining new AsyncIterables instead of
* `Symbol.asyncIterator`, but do not use it for accessing existing Iterables,
* instead use `getAsyncIterator()` or `isAsyncIterable()`.
*
* @example
*
* var $$asyncIterator = require('iterall').$$asyncIterator
*
* function Chirper (to) {
* this.to = to
* }
*
* Chirper.prototype[$$asyncIterator] = function () {
* return {
* to: this.to,
* num: 0,
* next () {
* return new Promise(function (resolve) {
* if (this.num >= this.to) {
* resolve({ value: undefined, done: true })
* } else {
* setTimeout(function () {
* resolve({ value: this.num++, done: false })
* }, 1000)
* }
* }
* }
* }
* }
*
* var chirper = new Chirper(3)
* for await (var number of chirper) {
* console.log(number) // 0 ...wait... 1 ...wait... 2
* }
*
* @type {Symbol|string}
*/
var $$asyncIterator = SYMBOL_ASYNC_ITERATOR || '@@asyncIterator'
exports.$$asyncIterator = $$asyncIterator
/**
* Returns true if the provided object implements the AsyncIterator protocol via
* either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method.
*
* @example
*
* var isAsyncIterable = require('iterall').isAsyncIterable
* isAsyncIterable(myStream) // true
* isAsyncIterable('ABC') // false
*
* @param obj
* A value which might implement the AsyncIterable protocol.
* @return {boolean} true if AsyncIterable.
*/
function isAsyncIterable(obj) {
return !!getAsyncIteratorMethod(obj)
}
exports.isAsyncIterable = isAsyncIterable
/**
* If the provided object implements the AsyncIterator protocol, its
* AsyncIterator object is returned. Otherwise returns undefined.
*
* @example
*
* var getAsyncIterator = require('iterall').getAsyncIterator
* var asyncIterator = getAsyncIterator(myStream)
* asyncIterator.next().then(console.log) // { value: 1, done: false }
* asyncIterator.next().then(console.log) // { value: 2, done: false }
* asyncIterator.next().then(console.log) // { value: 3, done: false }
* asyncIterator.next().then(console.log) // { value: undefined, done: true }
*
* @template T the type of each iterated value
* @param {AsyncIterable<T>} asyncIterable
* An AsyncIterable object which is the source of an AsyncIterator.
* @return {AsyncIterator<T>} new AsyncIterator instance.
*/
function getAsyncIterator(asyncIterable) {
var method = getAsyncIteratorMethod(asyncIterable)
if (method) {
return method.call(asyncIterable)
}
}
exports.getAsyncIterator = getAsyncIterator
/**
* If the provided object implements the AsyncIterator protocol, the method
* responsible for producing its AsyncIterator object is returned.
*
* This is used in rare cases for performance tuning. This method must be called
* with obj as the contextual this-argument.
*
* @example
*
* var getAsyncIteratorMethod = require('iterall').getAsyncIteratorMethod
* var method = getAsyncIteratorMethod(myStream)
* if (method) {
* var asyncIterator = method.call(myStream)
* }
*
* @template T the type of each iterated value
* @param {AsyncIterable<T>} asyncIterable
* An AsyncIterable object which defines an `@@asyncIterator` method.
* @return {function(): AsyncIterator<T>} `@@asyncIterator` method.
*/
function getAsyncIteratorMethod(asyncIterable) {
if (asyncIterable != null) {
var method =
(SYMBOL_ASYNC_ITERATOR && asyncIterable[SYMBOL_ASYNC_ITERATOR]) ||
asyncIterable['@@asyncIterator']
if (typeof method === 'function') {
return method
}
}
}
exports.getAsyncIteratorMethod = getAsyncIteratorMethod
/**
* Similar to `getAsyncIterator()`, this method returns a new AsyncIterator
* given an AsyncIterable. However it will also create an AsyncIterator for a
* non-async Iterable as well as non-Iterable Array-like collection, such as
* Array in a pre-ES2015 environment.
*
* `createAsyncIterator` is complimentary to `forAwaitEach`, but allows a
* buffering "pull"-based iteration as opposed to `forAwaitEach`'s
* "push"-based iteration.
*
* `createAsyncIterator` produces an AsyncIterator for non-async Iterables as
* described in the ECMAScript proposal [Async-from-Sync Iterator Objects](https://tc39.github.io/proposal-async-iteration/#sec-async-from-sync-iterator-objects).
*
* > Note: Creating `AsyncIterator`s requires the existence of `Promise`.
* > While `Promise` has been available in modern browsers for a number of
* > years, legacy browsers (like IE 11) may require a polyfill.
*
* @example
*
* var createAsyncIterator = require('iterall').createAsyncIterator
*
* var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' }
* var iterator = createAsyncIterator(myArraylike)
* iterator.next().then(console.log) // { value: 'Alpha', done: false }
* iterator.next().then(console.log) // { value: 'Bravo', done: false }
* iterator.next().then(console.log) // { value: 'Charlie', done: false }
* iterator.next().then(console.log) // { value: undefined, done: true }
*
* @template T the type of each iterated value
* @param {AsyncIterable<T>|Iterable<T>|{ length: number }} source
* An AsyncIterable, Iterable, or Array-like object to produce an Iterator.
* @return {AsyncIterator<T>} new AsyncIterator instance.
*/
function createAsyncIterator(source) {
if (source != null) {
var asyncIterator = getAsyncIterator(source)
if (asyncIterator) {
return asyncIterator
}
var iterator = createIterator(source)
if (iterator) {
return new AsyncFromSyncIterator(iterator)
}
}
}
exports.createAsyncIterator = createAsyncIterator
// When the object provided to `createAsyncIterator` is not AsyncIterable but is
// sync Iterable, this simple wrapper is created.
function AsyncFromSyncIterator(iterator) {
this._i = iterator
}
// Note: all AsyncIterators are themselves AsyncIterable.
AsyncFromSyncIterator.prototype[$$asyncIterator] = function() {
return this
}
// A simple state-machine determines the IteratorResult returned, yielding
// each value in the Array-like object in order of their indicies.
AsyncFromSyncIterator.prototype.next = function() {
var step = this._i.next()
return Promise.resolve(step.value).then(function(value) {
return { value: value, done: step.done }
})
}
/**
* Given an object which either implements the AsyncIterable protocol or is
* Array-like, iterate over it, calling the `callback` at each iteration.
*
* Use `forAwaitEach` where you would expect to use a `for-await-of` loop.
*
* Similar to [Array#forEach][], the `callback` function accepts three
* arguments, and is provided with `thisArg` as the calling context.
*
* > Note: Using `forAwaitEach` requires the existence of `Promise`.
* > While `Promise` has been available in modern browsers for a number of
* > years, legacy browsers (like IE 11) may require a polyfill.
*
* @example
*
* var forAwaitEach = require('iterall').forAwaitEach
*
* forAwaitEach(myIterable, function (value, index, iterable) {
* console.log(value, index, iterable === myIterable)
* })
*
* @example
*
* // ES2017:
* for await (let value of myAsyncIterable) {
* console.log(await doSomethingAsync(value))
* }
* console.log('done')
*
* // Any JavaScript environment:
* forAwaitEach(myAsyncIterable, function (value) {
* return doSomethingAsync(value).then(console.log)
* }).then(function () {
* console.log('done')
* })
*
* @template T the type of each iterated value
* @param {AsyncIterable<T>|Iterable<Promise<T> | T>|{ length: number }} source
* The AsyncIterable or array to iterate over.
* @param {function(T, number, object)} callback
* Function to execute for each iteration, taking up to three arguments
* @param [thisArg]
* Optional. Value to use as `this` when executing `callback`.
*/
function forAwaitEach(source, callback, thisArg) {
var asyncIterator = createAsyncIterator(source)
if (asyncIterator) {
var i = 0
function next() {
return asyncIterator.next().then(function(step) {
if (!step.done) {
return Promise.resolve(
callback.call(thisArg, step.value, i++, source)
).then(next)
}
})
}
return next()
}
}
exports.forAwaitEach = forAwaitEach
},{}],45:[function(require,module,exports){
var root = require('./_root');
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
},{"./_root":52}],46:[function(require,module,exports){
var Symbol = require('./_Symbol'),
getRawTag = require('./_getRawTag'),
objectToString = require('./_objectToString');
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
module.exports = baseGetTag;
},{"./_Symbol":45,"./_getRawTag":49,"./_objectToString":50}],47:[function(require,module,exports){
(function (global){
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
module.exports = freeGlobal;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],48:[function(require,module,exports){
var overArg = require('./_overArg');
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
module.exports = getPrototype;
},{"./_overArg":51}],49:[function(require,module,exports){
var Symbol = require('./_Symbol');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
module.exports = getRawTag;
},{"./_Symbol":45}],50:[function(require,module,exports){
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
module.exports = objectToString;
},{}],51:[function(require,module,exports){
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
},{}],52:[function(require,module,exports){
var freeGlobal = require('./_freeGlobal');
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;
},{"./_freeGlobal":47}],53:[function(require,module,exports){
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
module.exports = isObjectLike;
},{}],54:[function(require,module,exports){
var baseGetTag = require('./_baseGetTag'),
getPrototype = require('./_getPrototype'),
isObjectLike = require('./isObjectLike');
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
module.exports = isPlainObject;
},{"./_baseGetTag":46,"./_getPrototype":48,"./isObjectLike":53}],55:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = applyMiddleware;
var _compose = require('./compose');
var _compose2 = _interopRequireDefault(_compose);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Creates a store enhancer that applies middleware to the dispatch method
* of the Redux store. This is handy for a variety of tasks, such as expressing
* asynchronous actions in a concise manner, or logging every action payload.
*
* See `redux-thunk` package as an example of the Redux middleware.
*
* Because middleware is potentially asynchronous, this should be the first
* store enhancer in the composition chain.
*
* Note that each middleware will be given the `dispatch` and `getState` functions
* as named arguments.
*
* @param {...Function} middlewares The middleware chain to be applied.
* @returns {Function} A store enhancer applying the middleware.
*/
function applyMiddleware() {
for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
return function (createStore) {
return function (reducer, preloadedState, enhancer) {
var store = createStore(reducer, preloadedState, enhancer);
var _dispatch = store.dispatch;
var chain = [];
var middlewareAPI = {
getState: store.getState,
dispatch: function dispatch(action) {
return _dispatch(action);
}
};
chain = middlewares.map(function (middleware) {
return middleware(middlewareAPI);
});
_dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch);
return _extends({}, store, {
dispatch: _dispatch
});
};
};
}
},{"./compose":58}],56:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports['default'] = bindActionCreators;
function bindActionCreator(actionCreator, dispatch) {
return function () {
return dispatch(actionCreator.apply(undefined, arguments));
};
}
/**
* Turns an object whose values are action creators, into an object with the
* same keys, but with every function wrapped into a `dispatch` call so they
* may be invoked directly. This is just a convenience method, as you can call
* `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
*
* For convenience, you can also pass a single function as the first argument,
* and get a function in return.
*
* @param {Function|Object} actionCreators An object whose values are action
* creator functions. One handy way to obtain it is to use ES6 `import * as`
* syntax. You may also pass a single function.
*
* @param {Function} dispatch The `dispatch` function available on your Redux
* store.
*
* @returns {Function|Object} The object mimicking the original object, but with
* every action creator wrapped into the `dispatch` call. If you passed a
* function as `actionCreators`, the return value will also be a single
* function.
*/
function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch);
}
if (typeof actionCreators !== 'object' || actionCreators === null) {
throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');
}
var keys = Object.keys(actionCreators);
var boundActionCreators = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var actionCreator = actionCreators[key];
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
}
}
return boundActionCreators;
}
},{}],57:[function(require,module,exports){
(function (process){
'use strict';
exports.__esModule = true;
exports['default'] = combineReducers;
var _createStore = require('./createStore');
var _isPlainObject = require('lodash/isPlainObject');
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _warning = require('./utils/warning');
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function getUndefinedStateErrorMessage(key, action) {
var actionType = action && action.type;
var actionName = actionType && '"' + actionType.toString() + '"' || 'an action';
return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state. ' + 'If you want this reducer to hold no value, you can return null instead of undefined.';
}
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
var reducerKeys = Object.keys(reducers);
var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
if (reducerKeys.length === 0) {
return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
}
if (!(0, _isPlainObject2['default'])(inputState)) {
return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"');
}
var unexpectedKeys = Object.keys(inputState).filter(function (key) {
return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
});
unexpectedKeys.forEach(function (key) {
unexpectedKeyCache[key] = true;
});
if (unexpectedKeys.length > 0) {
return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.');
}
}
function assertReducerShape(reducers) {
Object.keys(reducers).forEach(function (key) {
var reducer = reducers[key];
var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT });
if (typeof initialState === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined. If you don\'t want to set a value for this reducer, ' + 'you can use null instead of undefined.');
}
var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
if (typeof reducer(undefined, { type: type }) === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined, but can be null.');
}
});
}
/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @param {Object} reducers An object whose values correspond to different
* reducer functions that need to be combined into one. One handy way to obtain
* it is to use ES6 `import * as reducers` syntax. The reducers may never return
* undefined for any action. Instead, they should return their initial state
* if the state passed to them was undefined, and the current state for any
* unrecognized action.
*
* @returns {Function} A reducer function that invokes every reducer inside the
* passed object, and builds a state object with the same shape.
*/
function combineReducers(reducers) {
var reducerKeys = Object.keys(reducers);
var finalReducers = {};
for (var i = 0; i < reducerKeys.length; i++) {
var key = reducerKeys[i];
if (process.env.NODE_ENV !== 'production') {
if (typeof reducers[key] === 'undefined') {
(0, _warning2['default'])('No reducer provided for key "' + key + '"');
}
}
if (typeof reducers[key] === 'function') {
finalReducers[key] = reducers[key];
}
}
var finalReducerKeys = Object.keys(finalReducers);
var unexpectedKeyCache = void 0;
if (process.env.NODE_ENV !== 'production') {
unexpectedKeyCache = {};
}
var shapeAssertionError = void 0;
try {
assertReducerShape(finalReducers);
} catch (e) {
shapeAssertionError = e;
}
return function combination() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments[1];
if (shapeAssertionError) {
throw shapeAssertionError;
}
if (process.env.NODE_ENV !== 'production') {
var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
if (warningMessage) {
(0, _warning2['default'])(warningMessage);
}
}
var hasChanged = false;
var nextState = {};
for (var _i = 0; _i < finalReducerKeys.length; _i++) {
var _key = finalReducerKeys[_i];
var reducer = finalReducers[_key];
var previousStateForKey = state[_key];
var nextStateForKey = reducer(previousStateForKey, action);
if (typeof nextStateForKey === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(_key, action);
throw new Error(errorMessage);
}
nextState[_key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
}
return hasChanged ? nextState : state;
};
}
}).call(this,require('_process'))
},{"./createStore":59,"./utils/warning":61,"_process":66,"lodash/isPlainObject":54}],58:[function(require,module,exports){
"use strict";
exports.__esModule = true;
exports["default"] = compose;
/**
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
* the resulting composite function.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing the argument functions
* from right to left. For example, compose(f, g, h) is identical to doing
* (...args) => f(g(h(...args))).
*/
function compose() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
if (funcs.length === 0) {
return function (arg) {
return arg;
};
}
if (funcs.length === 1) {
return funcs[0];
}
return funcs.reduce(function (a, b) {
return function () {
return a(b.apply(undefined, arguments));
};
});
}
},{}],59:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports.ActionTypes = undefined;
exports['default'] = createStore;
var _isPlainObject = require('lodash/isPlainObject');
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _symbolObservable = require('symbol-observable');
var _symbolObservable2 = _interopRequireDefault(_symbolObservable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* These are private action types reserved by Redux.
* For any unknown actions, you must return the current state.
* If the current state is undefined, you must return the initial state.
* Do not reference these action types directly in your code.
*/
var ActionTypes = exports.ActionTypes = {
INIT: '@@redux/INIT'
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several reducers
* into a single reducer function by using `combineReducers`.
*
* @param {Function} reducer A function that returns the next state tree, given
* the current state tree and the action to handle.
*
* @param {any} [preloadedState] The initial state. You may optionally specify it
* to hydrate the state from the server in universal apps, or to restore a
* previously serialized user session.
* If you use `combineReducers` to produce the root reducer function, this must be
* an object with the same shape as `combineReducers` keys.
*
* @param {Function} [enhancer] The store enhancer. You may optionally specify it
* to enhance the store with third-party capabilities such as middleware,
* time travel, persistence, etc. The only store enhancer that ships with Redux
* is `applyMiddleware()`.
*
* @returns {Store} A Redux store that lets you read the state, dispatch actions
* and subscribe to changes.
*/
};function createStore(reducer, preloadedState, enhancer) {
var _ref2;
if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
enhancer = preloadedState;
preloadedState = undefined;
}
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.');
}
return enhancer(createStore)(reducer, preloadedState);
}
if (typeof reducer !== 'function') {
throw new Error('Expected the reducer to be a function.');
}
var currentReducer = reducer;
var currentState = preloadedState;
var currentListeners = [];
var nextListeners = currentListeners;
var isDispatching = false;
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice();
}
}
/**
* Reads the state tree managed by the store.
*
* @returns {any} The current state tree of your application.
*/
function getState() {
return currentState;
}
/**
* Adds a change listener. It will be called any time an action is dispatched,
* and some part of the state tree may potentially have changed. You may then
* call `getState()` to read the current state tree inside the callback.
*
* You may call `dispatch()` from a change listener, with the following
* caveats:
*
* 1. The subscriptions are snapshotted just before every `dispatch()` call.
* If you subscribe or unsubscribe while the listeners are being invoked, this
* will not have any effect on the `dispatch()` that is currently in progress.
* However, the next `dispatch()` call, whether nested or not, will use a more
* recent snapshot of the subscription list.
*
* 2. The listener should not expect to see all state changes, as the state
* might have been updated multiple times during a nested `dispatch()` before
* the listener is called. It is, however, guaranteed that all subscribers
* registered before the `dispatch()` started will be called with the latest
* state by the time it exits.
*
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected listener to be a function.');
}
var isSubscribed = true;
ensureCanMutateNextListeners();
nextListeners.push(listener);
return function unsubscribe() {
if (!isSubscribed) {
return;
}
isSubscribed = false;
ensureCanMutateNextListeners();
var index = nextListeners.indexOf(listener);
nextListeners.splice(index, 1);
};
}
/**
* Dispatches an action. It is the only way to trigger a state change.
*
* The `reducer` function, used to create the store, will be called with the
* current state tree and the given `action`. Its return value will
* be considered the **next** state of the tree, and the change listeners
* will be notified.
*
* The base implementation only supports plain object actions. If you want to
* dispatch a Promise, an Observable, a thunk, or something else, you need to
* wrap your store creating function into the corresponding middleware. For
* example, see the documentation for the `redux-thunk` package. Even the
* middleware will eventually dispatch plain object actions using this method.
*
* @param {Object} action A plain object representing “what changed”. It is
* a good idea to keep actions serializable so you can record and replay user
* sessions, or use the time travelling `redux-devtools`. An action must have
* a `type` property which may not be `undefined`. It is a good idea to use
* string constants for action types.
*
* @returns {Object} For convenience, the same action object you dispatched.
*
* Note that, if you use a custom middleware, it may wrap `dispatch()` to
* return something else (for example, a Promise you can await).
*/
function dispatch(action) {
if (!(0, _isPlainObject2['default'])(action)) {
throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
}
if (typeof action.type === 'undefined') {
throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
}
if (isDispatching) {
throw new Error('Reducers may not dispatch actions.');
}
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
var listeners = currentListeners = nextListeners;
for (var i = 0; i < listeners.length; i++) {
var listener = listeners[i];
listener();
}
return action;
}
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param {Function} nextReducer The reducer for the store to use instead.
* @returns {void}
*/
function replaceReducer(nextReducer) {
if (typeof nextReducer !== 'function') {
throw new Error('Expected the nextReducer to be a function.');
}
currentReducer = nextReducer;
dispatch({ type: ActionTypes.INIT });
}
/**
* Interoperability point for observable/reactive libraries.
* @returns {observable} A minimal observable of state changes.
* For more information, see the observable proposal:
* https://github.com/tc39/proposal-observable
*/
function observable() {
var _ref;
var outerSubscribe = subscribe;
return _ref = {
/**
* The minimal observable subscription method.
* @param {Object} observer Any object that can be used as an observer.
* The observer object should have a `next` method.
* @returns {subscription} An object with an `unsubscribe` method that can
* be used to unsubscribe the observable from the store, and prevent further
* emission of values from the observable.
*/
subscribe: function subscribe(observer) {
if (typeof observer !== 'object') {
throw new TypeError('Expected the observer to be an object.');
}
function observeState() {
if (observer.next) {
observer.next(getState());
}
}
observeState();
var unsubscribe = outerSubscribe(observeState);
return { unsubscribe: unsubscribe };
}
}, _ref[_symbolObservable2['default']] = function () {
return this;
}, _ref;
}
// When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
dispatch({ type: ActionTypes.INIT });
return _ref2 = {
dispatch: dispatch,
subscribe: subscribe,
getState: getState,
replaceReducer: replaceReducer
}, _ref2[_symbolObservable2['default']] = observable, _ref2;
}
},{"lodash/isPlainObject":54,"symbol-observable":62}],60:[function(require,module,exports){
(function (process){
'use strict';
exports.__esModule = true;
exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined;
var _createStore = require('./createStore');
var _createStore2 = _interopRequireDefault(_createStore);
var _combineReducers = require('./combineReducers');
var _combineReducers2 = _interopRequireDefault(_combineReducers);
var _bindActionCreators = require('./bindActionCreators');
var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators);
var _applyMiddleware = require('./applyMiddleware');
var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware);
var _compose = require('./compose');
var _compose2 = _interopRequireDefault(_compose);
var _warning = require('./utils/warning');
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/*
* This is a dummy function to check if the function name has been altered by minification.
* If the function has been minified and NODE_ENV !== 'production', warn the user.
*/
function isCrushed() {}
if (process.env.NODE_ENV !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
(0, _warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.');
}
exports.createStore = _createStore2['default'];
exports.combineReducers = _combineReducers2['default'];
exports.bindActionCreators = _bindActionCreators2['default'];
exports.applyMiddleware = _applyMiddleware2['default'];
exports.compose = _compose2['default'];
}).call(this,require('_process'))
},{"./applyMiddleware":55,"./bindActionCreators":56,"./combineReducers":57,"./compose":58,"./createStore":59,"./utils/warning":61,"_process":66}],61:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports['default'] = warning;
/**
* Prints a warning in the console if it exists.
*
* @param {String} message The warning message.
* @returns {void}
*/
function warning(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that if you enable
// "break on all exceptions" in your console,
// it would pause the execution at this line.
throw new Error(message);
/* eslint-disable no-empty */
} catch (e) {}
/* eslint-enable no-empty */
}
},{}],62:[function(require,module,exports){
module.exports = require('./lib/index');
},{"./lib/index":63}],63:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ponyfill = require('./ponyfill');
var _ponyfill2 = _interopRequireDefault(_ponyfill);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var root; /* global window */
if (typeof self !== 'undefined') {
root = self;
} else if (typeof window !== 'undefined') {
root = window;
} else if (typeof global !== 'undefined') {
root = global;
} else if (typeof module !== 'undefined') {
root = module;
} else {
root = Function('return this')();
}
var result = (0, _ponyfill2['default'])(root);
exports['default'] = result;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./ponyfill":64}],64:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = symbolObservablePonyfill;
function symbolObservablePonyfill(root) {
var result;
var _Symbol = root.Symbol;
if (typeof _Symbol === 'function') {
if (_Symbol.observable) {
result = _Symbol.observable;
} else {
result = _Symbol('observable');
_Symbol.observable = result;
}
} else {
result = '@@observable';
}
return result;
};
},{}],65:[function(require,module,exports){
(function(self) {
'use strict';
if (self.fetch) {
return
}
var support = {
searchParams: 'URLSearchParams' in self,
iterable: 'Symbol' in self && 'iterator' in Symbol,
blob: 'FileReader' in self && 'Blob' in self && (function() {
try {
new Blob()
return true
} catch(e) {
return false
}
})(),
formData: 'FormData' in self,
arrayBuffer: 'ArrayBuffer' in self
}
if (support.arrayBuffer) {
var viewClasses = [
'[object Int8Array]',
'[object Uint8Array]',
'[object Uint8ClampedArray]',
'[object Int16Array]',
'[object Uint16Array]',
'[object Int32Array]',
'[object Uint32Array]',
'[object Float32Array]',
'[object Float64Array]'
]
var isDataView = function(obj) {
return obj && DataView.prototype.isPrototypeOf(obj)
}
var isArrayBufferView = ArrayBuffer.isView || function(obj) {
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
}
}
function normalizeName(name) {
if (typeof name !== 'string') {
name = String(name)
}
if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
throw new TypeError('Invalid character in header field name')
}
return name.toLowerCase()
}
function normalizeValue(value) {
if (typeof value !== 'string') {
value = String(value)
}
return value
}
// Build a destructive iterator for the value list
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift()
return {done: value === undefined, value: value}
}
}
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator
}
}
return iterator
}
function Headers(headers) {
this.map = {}
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value)
}, this)
} else if (Array.isArray(headers)) {
headers.forEach(function(header) {
this.append(header[0], header[1])
}, this)
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function(name) {
this.append(name, headers[name])
}, this)
}
}
Headers.prototype.append = function(name, value) {
name = normalizeName(name)
value = normalizeValue(value)
var oldValue = this.map[name]
this.map[name] = oldValue ? oldValue+','+value : value
}
Headers.prototype['delete'] = function(name) {
delete this.map[normalizeName(name)]
}
Headers.prototype.get = function(name) {
name = normalizeName(name)
return this.has(name) ? this.map[name] : null
}
Headers.prototype.has = function(name) {
return this.map.hasOwnProperty(normalizeName(name))
}
Headers.prototype.set = function(name, value) {
this.map[normalizeName(name)] = normalizeValue(value)
}
Headers.prototype.forEach = function(callback, thisArg) {
for (var name in this.map) {
if (this.map.hasOwnProperty(name)) {
callback.call(thisArg, this.map[name], name, this)
}
}
}
Headers.prototype.keys = function() {
var items = []
this.forEach(function(value, name) { items.push(name) })
return iteratorFor(items)
}
Headers.prototype.values = function() {
var items = []
this.forEach(function(value) { items.push(value) })
return iteratorFor(items)
}
Headers.prototype.entries = function() {
var items = []
this.forEach(function(value, name) { items.push([name, value]) })
return iteratorFor(items)
}
if (support.iterable) {
Headers.prototype[Symbol.iterator] = Headers.prototype.entries
}
function consumed(body) {
if (body.bodyUsed) {
return Promise.reject(new TypeError('Already read'))
}
body.bodyUsed = true
}
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result)
}
reader.onerror = function() {
reject(reader.error)
}
})
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader()
var promise = fileReaderReady(reader)
reader.readAsArrayBuffer(blob)
return promise
}
function readBlobAsText(blob) {
var reader = new FileReader()
var promise = fileReaderReady(reader)
reader.readAsText(blob)
return promise
}
function readArrayBufferAsText(buf) {
var view = new Uint8Array(buf)
var chars = new Array(view.length)
for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i])
}
return chars.join('')
}
function bufferClone(buf) {
if (buf.slice) {
return buf.slice(0)
} else {
var view = new Uint8Array(buf.byteLength)
view.set(new Uint8Array(buf))
return view.buffer
}
}
function Body() {
this.bodyUsed = false
this._initBody = function(body) {
this._bodyInit = body
if (!body) {
this._bodyText = ''
} else if (typeof body === 'string') {
this._bodyText = body
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString()
} else if (support.arrayBuffer && support.blob && isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer)
// IE 10-11 can't handle a DataView body.
this._bodyInit = new Blob([this._bodyArrayBuffer])
} else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
this._bodyArrayBuffer = bufferClone(body)
} else {
throw new Error('unsupported BodyInit type')
}
if (!this.headers.get('content-type')) {
if (typeof body === 'string') {
this.headers.set('content-type', 'text/plain;charset=UTF-8')
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set('content-type', this._bodyBlob.type)
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
}
}
}
if (support.blob) {
this.blob = function() {
var rejected = consumed(this)
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as blob')
} else {
return Promise.resolve(new Blob([this._bodyText]))
}
}
this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
} else {
return this.blob().then(readBlobAsArrayBuffer)
}
}
}
this.text = function() {
var rejected = consumed(this)
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as text')
} else {
return Promise.resolve(this._bodyText)
}
}
if (support.formData) {
this.formData = function() {
return this.text().then(decode)
}
}
this.json = function() {
return this.text().then(JSON.parse)
}
return this
}
// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']
function normalizeMethod(method) {
var upcased = method.toUpperCase()
return (methods.indexOf(upcased) > -1) ? upcased : method
}
function Request(input, options) {
options = options || {}
var body = options.body
if (input instanceof Request) {
if (input.bodyUsed) {
throw new TypeError('Already read')
}
this.url = input.url
this.credentials = input.credentials
if (!options.headers) {
this.headers = new Headers(input.headers)
}
this.method = input.method
this.mode = input.mode
if (!body && input._bodyInit != null) {
body = input._bodyInit
input.bodyUsed = true
}
} else {
this.url = String(input)
}
this.credentials = options.credentials || this.credentials || 'omit'
if (options.headers || !this.headers) {
this.headers = new Headers(options.headers)
}
this.method = normalizeMethod(options.method || this.method || 'GET')
this.mode = options.mode || this.mode || null
this.referrer = null
if ((this.method === 'GET' || this.method === 'HEAD') && body) {
throw new TypeError('Body not allowed for GET or HEAD requests')
}
this._initBody(body)
}
Request.prototype.clone = function() {
return new Request(this, { body: this._bodyInit })
}
function decode(body) {
var form = new FormData()
body.trim().split('&').forEach(function(bytes) {
if (bytes) {
var split = bytes.split('=')
var name = split.shift().replace(/\+/g, ' ')
var value = split.join('=').replace(/\+/g, ' ')
form.append(decodeURIComponent(name), decodeURIComponent(value))
}
})
return form
}
function parseHeaders(rawHeaders) {
var headers = new Headers()
rawHeaders.split(/\r?\n/).forEach(function(line) {
var parts = line.split(':')
var key = parts.shift().trim()
if (key) {
var value = parts.join(':').trim()
headers.append(key, value)
}
})
return headers
}
Body.call(Request.prototype)
function Response(bodyInit, options) {
if (!options) {
options = {}
}
this.type = 'default'
this.status = 'status' in options ? options.status : 200
this.ok = this.status >= 200 && this.status < 300
this.statusText = 'statusText' in options ? options.statusText : 'OK'
this.headers = new Headers(options.headers)
this.url = options.url || ''
this._initBody(bodyInit)
}
Body.call(Response.prototype)
Response.prototype.clone = function() {
return new Response(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers(this.headers),
url: this.url
})
}
Response.error = function() {
var response = new Response(null, {status: 0, statusText: ''})
response.type = 'error'
return response
}
var redirectStatuses = [301, 302, 303, 307, 308]
Response.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError('Invalid status code')
}
return new Response(null, {status: status, headers: {location: url}})
}
self.Headers = Headers
self.Request = Request
self.Response = Response
self.fetch = function(input, init) {
return new Promise(function(resolve, reject) {
var request = new Request(input, init)
var xhr = new XMLHttpRequest()
xhr.onload = function() {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || '')
}
options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
var body = 'response' in xhr ? xhr.response : xhr.responseText
resolve(new Response(body, options))
}
xhr.onerror = function() {
reject(new TypeError('Network request failed'))
}
xhr.ontimeout = function() {
reject(new TypeError('Network request failed'))
}
xhr.open(request.method, request.url, true)
if (request.credentials === 'include') {
xhr.withCredentials = true
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob'
}
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value)
})
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
})
}
self.fetch.polyfill = true
})(typeof self !== 'undefined' ? self : this);
},{}],66:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}]},{},[1]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment