@urql/exchange-graphcache
Advanced tools
Comparing version 1.0.0-rc.11 to 1.0.0
@@ -11,2 +11,23 @@ # Changelog | ||
## [v1.0.0](https://github.com/FormidableLabs/urql-exchange-graphcache/compare/v1.0.0-rc.11...v1.0.0) | ||
> **Note:** The minimum required version of `urql` for this release is now `1.5.1`! | ||
**Hooray it's `v1.0.0` time!** This doesn't mean that we won't be changing little things anymore, but we're so far happy with our API and trust Graphcache to work correctly. We will further iterate on this version with some **planned features**, like "fragment invalidation", garbage collection, and more. | ||
This version refactors the **cache resolvers** and adds some new special powers to them! You can now return almost anything from cache resolvers and trust that it'll do the right thing: | ||
- You can return entity keys, which will resolve the cached entities | ||
- You can return keyable entities, which will also be resolved from cache | ||
- You may also return unkeyable entities, which will be partially resolved from cache, with your resolved values taking precedence | ||
This can also be nested, so that unkeyable entities can eventually lead back to normal, cached entities! | ||
This has enabled us to expose the `relayPagination()` helper! This is a resolver that you can just drop into the `cacheExchange`'s `resolvers` config. It automatically does Relay-style pagination, which is now possible due to our more powerful resolvers! You can import it from `@urql/exchange-graphcache/extras`. | ||
- ✨ Add full cache resolver traversal (see [#91](https://github.com/FormidableLabs/urql-exchange-graphcache/pull/91)) | ||
- ✨ Add a new `relayPagination` helper (see [#91](https://github.com/FormidableLabs/urql-exchange-graphcache/pull/91)) | ||
- Add a `Cache` interface with all methods (that are safe for userland) having documentation (see [#91](https://github.com/FormidableLabs/urql-exchange-graphcache/pull/91)) | ||
- ⚠ Fix non-default root keys (that aren't just `Query`) not being respected (see [#87](https://github.com/FormidableLabs/urql-exchange-graphcache/pull/87)) | ||
## [v1.0.0-rc.11](https://github.com/FormidableLabs/urql-exchange-graphcache/compare/v1.0.0-rc.10...v1.0.0-rc.11) | ||
@@ -13,0 +34,0 @@ |
import { DocumentNode } from 'graphql'; | ||
import * as Pessimism from 'pessimism'; | ||
import { EntityField, Link, ResolverConfig, DataField, Variables, Data, UpdatesConfig, OptimisticMutationConfig, KeyingConfig } from './types'; | ||
import { Cache, EntityField, Link, Connection, ResolverConfig, DataField, Variables, Data, QueryInput, UpdatesConfig, OptimisticMutationConfig, KeyingConfig } from './types'; | ||
import { SchemaPredicates } from './ast/schemaPredicates'; | ||
@@ -10,8 +10,5 @@ export declare const initStoreState: (optimisticKey: number | null) => void; | ||
declare type RootField = 'query' | 'mutation' | 'subscription'; | ||
interface QueryInput { | ||
query: string | DocumentNode; | ||
variables?: Variables; | ||
} | ||
export declare class Store { | ||
export declare class Store implements Cache { | ||
records: Pessimism.Map<EntityField>; | ||
connections: Pessimism.Map<Connection[]>; | ||
links: Pessimism.Map<Link>; | ||
@@ -43,10 +40,9 @@ resolvers: ResolverConfig; | ||
writeLink(link: Link, key: string): Pessimism.Map<Link<string>>; | ||
writeConnection(key: string, linkKey: string, args: Variables | null): Pessimism.Map<[Variables, string][]>; | ||
resolveValueOrLink(fieldKey: string): DataField; | ||
resolve(entity: Data | string, field: string, args?: Variables): DataField; | ||
invalidateQuery(dataQuery: DocumentNode, variables: Variables): void; | ||
resolve(entity: Data | string | null, field: string, args?: Variables): DataField; | ||
resolveConnections(entity: Data | string | null, field: string): Connection[]; | ||
invalidateQuery(query: string | DocumentNode, variables?: Variables): void; | ||
hasField(key: string): boolean; | ||
updateQuery(input: { | ||
query: string | DocumentNode; | ||
variables?: Variables; | ||
}, updater: (data: Data | null) => null | Data): void; | ||
updateQuery(input: QueryInput, updater: (data: Data | null) => Data | null): void; | ||
readQuery(input: QueryInput): Data | null; | ||
@@ -53,0 +49,0 @@ readFragment(dataFragment: DocumentNode, entity: string | Data, variables?: Variables): Data | null; |
import { DocumentNode, FragmentDefinitionNode, SelectionNode } from 'graphql'; | ||
import { Store } from './store'; | ||
export declare type NullArray<T> = Array<null | T>; | ||
@@ -24,8 +23,9 @@ export declare type SelectionSet = ReadonlyArray<SelectionNode>; | ||
} | ||
export interface Variables { | ||
[name: string]: Scalar | Scalar[] | Variables | NullArray<Variables>; | ||
} | ||
export declare type Data = SystemFields & DataFields; | ||
export declare type Link<Key = string> = null | Key | NullArray<Key>; | ||
export declare type ResolvedLink = Link<Data>; | ||
export interface Variables { | ||
[name: string]: Scalar | Scalar[] | Variables | NullArray<Variables>; | ||
} | ||
export declare type Connection = [Variables, string]; | ||
export interface OperationRequest { | ||
@@ -36,6 +36,36 @@ query: DocumentNode; | ||
export interface ResolveInfo { | ||
parentTypeName: string; | ||
parentKey: string; | ||
parentFieldKey: string; | ||
fieldName: string; | ||
fragments: Fragments; | ||
variables: Variables; | ||
partial?: boolean; | ||
optimistic?: boolean; | ||
} | ||
export declare type Resolver = (parent: Data, args: Variables, cache: Store, info: ResolveInfo) => DataField; | ||
export interface QueryInput { | ||
query: string | DocumentNode; | ||
variables?: Variables; | ||
} | ||
export interface Cache { | ||
/** keyOfEntity() returns the key for an entity or null if it's unkeyable */ | ||
keyOfEntity(data: Data): string | null; | ||
/** resolve() retrieves the value (or link) of a field on any entity, given a partial/keyable entity or an entity key */ | ||
resolve(entity: Data | string | null, fieldName: string, args?: Variables): DataField; | ||
/** resolveValueOrLink() returns a field's value on an entity, given that field's key */ | ||
resolveValueOrLink(fieldKey: string): DataField; | ||
/** resolveConnections() retrieves all known connections (arguments and links) for a given field on an entity */ | ||
resolveConnections(entity: Data | string | null, fieldName: string): Connection[]; | ||
/** invalidateQuery() invalidates all data of a given query */ | ||
invalidateQuery(query: DocumentNode, variables?: Variables): void; | ||
/** updateQuery() can be used to update the data of a given query using an updater function */ | ||
updateQuery(input: QueryInput, updater: (data: Data | null) => Data | null): void; | ||
/** readQuery() retrieves the data for a given query */ | ||
readQuery(input: QueryInput): Data | null; | ||
/** readFragment() retrieves the data for a given fragment, given a partial/keyable entity or an entity key */ | ||
readFragment(fragment: DocumentNode, entity: string | Data, variables?: Variables): Data | null; | ||
/** writeFragment() can be used to update the data of a given fragment, given an entity that is supposed to be written using the fragment */ | ||
writeFragment(fragment: DocumentNode, data: Data, variables?: Variables): void; | ||
} | ||
export declare type Resolver = (parent: Data, args: Variables, cache: Cache, info: ResolveInfo) => DataField | undefined; | ||
export interface ResolverConfig { | ||
@@ -46,3 +76,3 @@ [typeName: string]: { | ||
} | ||
export declare type UpdateResolver = (result: Data, args: Variables, cache: Store, info: ResolveInfo) => void; | ||
export declare type UpdateResolver = (result: Data, args: Variables, cache: Cache, info: ResolveInfo) => void; | ||
export declare type KeyGenerator = (data: Data) => null | string; | ||
@@ -57,3 +87,3 @@ export interface UpdatesConfig { | ||
} | ||
export declare type OptimisticMutationResolver = (vars: Variables, cache: Store, info: ResolveInfo) => null | Data | NullArray<Data>; | ||
export declare type OptimisticMutationResolver = (vars: Variables, cache: Cache, info: ResolveInfo) => null | Data | NullArray<Data>; | ||
export interface OptimisticMutationConfig { | ||
@@ -60,0 +90,0 @@ [mutationFieldName: string]: OptimisticMutationResolver; |
import { Kind, valueFromASTUntyped, buildClientSchema, isNullableType, isNonNullType, isListType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType } from "graphql"; | ||
import { createRequest, formatDocument } from "urql"; | ||
import { stringifyVariables, createRequest, formatDocument } from "urql"; | ||
import { asMutable, make, clearOptimistic, get, setOptimistic, remove } from "pessimism"; | ||
import stringify from "fast-json-stable-stringify"; | ||
import { pipe, map, tap, share, filter, merge } from "wonka"; | ||
@@ -85,3 +83,3 @@ | ||
var args = input || {}; | ||
return node.variableDefinitions.reduce(function(vars, def) { | ||
return node.variableDefinitions.reduce((function(vars, def) { | ||
var name = getName(def.variable); | ||
@@ -98,3 +96,3 @@ var value = args[name]; | ||
return vars; | ||
}, Object.create(null)); | ||
}), Object.create(null)); | ||
}; | ||
@@ -115,5 +113,5 @@ | ||
var argIndex = 0; | ||
(error = new Error(format.replace(/%s/g, function() { | ||
(error = new Error(format.replace(/%s/g, (function() { | ||
return args[argIndex++]; | ||
}))).name = "Invariant Violation"; | ||
})))).name = "Invariant Violation"; | ||
} | ||
@@ -174,3 +172,3 @@ error.framesToPop = 1; | ||
var keyOfField = function(fieldName, args) { | ||
return args ? fieldName + "(" + stringify(args) + ")" : fieldName; | ||
return args ? fieldName + "(" + stringifyVariables(args) + ")" : fieldName; | ||
}; | ||
@@ -191,3 +189,3 @@ | ||
"production" !== process.env.NODE_ENV && warning(!1, "Heuristic Fragment Matching: A fragment is trying to match against the `" + typename + "` type, but the type condition is `" + typeCondition + "`. Since GraphQL allows for interfaces `" + typeCondition + "` may be aninterface.\nA schema needs to be defined for this match to be deterministic, otherwise the fragment will be matched heuristically!"); | ||
return !getSelectionSet(node).some(function(node) { | ||
return !getSelectionSet(node).some((function(node) { | ||
if (!isFieldNode(node)) { | ||
@@ -200,3 +198,3 @@ return !1; | ||
return !ctx.store.hasField(joinKeys(entityKey, fieldKey)); | ||
}); | ||
})); | ||
}; | ||
@@ -262,3 +260,9 @@ | ||
}; | ||
var select = getSelectionSet(operation); | ||
var operationName = store.getRootKey(operation.operation); | ||
var ctx = { | ||
parentTypeName: operationName, | ||
parentKey: operationName, | ||
parentFieldKey: "", | ||
fieldName: "", | ||
variables: normalizeVariables(operation, request.variables), | ||
@@ -270,4 +274,2 @@ fragments: getFragments(request.query), | ||
}; | ||
var select = getSelectionSet(operation); | ||
var operationName = ctx.store.getRootKey(operation.operation); | ||
if (operationName === ctx.store.getRootKey("query")) { | ||
@@ -287,3 +289,10 @@ writeSelection(ctx, operationName, select, data); | ||
}; | ||
var mutationRootKey = store.getRootKey("mutation"); | ||
var operationName = store.getRootKey(operation.operation); | ||
"production" !== process.env.NODE_ENV && browser(operationName === mutationRootKey, "writeOptimistic(...) was called with an operation that is not a mutation.\nThis case is unsupported and should never occur."); | ||
var ctx = { | ||
parentTypeName: mutationRootKey, | ||
parentKey: mutationRootKey, | ||
parentFieldKey: "", | ||
fieldName: "", | ||
variables: normalizeVariables(operation, request.variables), | ||
@@ -294,7 +303,4 @@ fragments: getFragments(request.query), | ||
schemaPredicates: store.schemaPredicates, | ||
isOptimistic: !0 | ||
optimistic: !0 | ||
}; | ||
var mutationRootKey = ctx.store.getRootKey("mutation"); | ||
var operationName = ctx.store.getRootKey(operation.operation); | ||
"production" !== process.env.NODE_ENV && browser(operationName === mutationRootKey, "writeOptimistic(...) was called with an operation that is not a mutation.\nThis case is unsupported and should never occur."); | ||
var select = getSelectionSet(operation); | ||
@@ -309,2 +315,3 @@ var data = Object.create(null); | ||
if (void 0 !== resolver) { | ||
ctx.fieldName = fieldName; | ||
var fieldArgs = getFieldArguments(node, ctx.variables); | ||
@@ -344,2 +351,6 @@ var fieldSelect = getSelectionSet(node); | ||
var ctx = { | ||
parentTypeName: typename, | ||
parentKey: entityKey, | ||
parentFieldKey: "", | ||
fieldName: "", | ||
variables: variables || {}, | ||
@@ -377,3 +388,3 @@ fragments: fragments, | ||
if (void 0 === fieldValue) { | ||
"production" !== process.env.NODE_ENV && warning(!1, "Invalid value: The field at `" + fieldKey + "` is `undefined`, but the GraphQL query expects a " + (void 0 === node.selectionSet ? "scalar (number, boolean, etc)" : "selection set") + " for this field." + (ctx.isOptimistic ? "\nYour optimistic result may be missing a field!" : "")); | ||
"production" !== process.env.NODE_ENV && warning(!1, "Invalid value: The field at `" + fieldKey + "` is `undefined`, but the GraphQL query expects a " + (void 0 === node.selectionSet ? "scalar (number, boolean, etc)" : "selection set") + " for this field." + (ctx.optimistic ? "\nYour optimistic result may be missing a field!" : "")); | ||
continue; | ||
@@ -388,4 +399,6 @@ } else if (ctx.schemaPredicates && typename) { | ||
var fieldSelect = getSelectionSet(node); | ||
var connectionKey = joinKeys(entityKey, fieldName); | ||
var link = writeField(ctx, fieldKey, fieldSelect, fieldValue); | ||
store.writeLink(link, fieldKey); | ||
store.writeConnection(connectionKey, fieldKey, fieldArgs); | ||
store.removeRecord(fieldKey); | ||
@@ -416,3 +429,3 @@ } else { | ||
var typename = data.__typename; | ||
"production" !== process.env.NODE_ENV && warning(typename.endsWith("Connection") || typename.endsWith("Edge"), "Invalid key: The GraphQL query at the field at `" + parentFieldKey + "` has a selection set, but no key could be generated for the data at this field.\nYou have to request `id` or `_id` fields for all selection sets or create a custom `keys` config for `" + typename + "`.\nEntities without keys will be embedded directly on the parent entity. If this is intentional, create a `keys` config for `" + typename + "` that always returns null."); | ||
"production" !== process.env.NODE_ENV && warning(typename.endsWith("Connection") || typename.endsWith("Edge") || "PageInfo" === typename, "Invalid key: The GraphQL query at the field at `" + parentFieldKey + "` has a selection set, but no key could be generated for the data at this field.\nYou have to request `id` or `_id` fields for all selection sets or create a custom `keys` config for `" + typename + "`.\nEntities without keys will be embedded directly on the parent entity. If this is intentional, create a `keys` config for `" + typename + "` that always returns null."); | ||
} | ||
@@ -437,2 +450,7 @@ writeSelection(ctx, key, select, data); | ||
if (isRootField) { | ||
var fieldKey = joinKeys(typename, keyOfField(fieldName, fieldArgs)); | ||
ctx.parentTypeName = typename; | ||
ctx.parentKey = typename; | ||
ctx.parentFieldKey = fieldKey; | ||
ctx.fieldName = fieldName; | ||
var updater = ctx.store.updates[typename][fieldName]; | ||
@@ -524,3 +542,3 @@ if (void 0 !== updater) { | ||
var initStoreState = function(optimisticKey) { | ||
currentDependencies.current = new Set(); | ||
currentDependencies.current = new Set; | ||
currentOptimisticKey.current = optimisticKey; | ||
@@ -557,2 +575,3 @@ }; | ||
this.records = asMutable(make()); | ||
this.connections = asMutable(make()); | ||
this.links = asMutable(make()); | ||
@@ -624,2 +643,3 @@ this.resolvers = resolvers || {}; | ||
this.records = clearOptimistic(this.records, optimisticKey); | ||
this.connections = clearOptimistic(this.connections, optimisticKey); | ||
this.links = clearOptimistic(this.links, optimisticKey); | ||
@@ -662,2 +682,21 @@ }; | ||
Store.prototype.writeConnection = function writeConnection(key, linkKey, args) { | ||
if (null === args) { | ||
return this.connections; | ||
} | ||
var connections = get(this.connections, key); | ||
var connection = [ args, linkKey ]; | ||
if (void 0 === connections) { | ||
connections = [ connection ]; | ||
} else { | ||
for (var i = 0, l = connections.length; i < l; i++) { | ||
if (connections[i][1] === linkKey) { | ||
return this.connections; | ||
} | ||
} | ||
(connections = connections.slice()).push(connection); | ||
} | ||
return this.connections = mapSet(this.connections, key, connections); | ||
}; | ||
Store.prototype.resolveValueOrLink = function resolveValueOrLink(fieldKey) { | ||
@@ -673,3 +712,5 @@ var fieldValue = this.getRecord(fieldKey); | ||
Store.prototype.resolve = function resolve(entity, field, args) { | ||
if ("string" == typeof entity) { | ||
if (null === entity) { | ||
return null; | ||
} else if ("string" == typeof entity) { | ||
addDependency(entity); | ||
@@ -687,3 +728,17 @@ return this.resolveValueOrLink(joinKeys(entity, keyOfField(field, args))); | ||
Store.prototype.invalidateQuery = function invalidateQuery(dataQuery, variables) { | ||
Store.prototype.resolveConnections = function resolveConnections(entity, field) { | ||
var connections; | ||
if ("string" == typeof entity) { | ||
connections = get(this.connections, joinKeys(entity, field)); | ||
} else if (null !== entity) { | ||
var entityKey = this.keyOfEntity(entity); | ||
if (null !== entityKey) { | ||
addDependency(entityKey); | ||
connections = get(this.connections, joinKeys(entityKey, field)); | ||
} | ||
} | ||
return void 0 !== connections ? connections : []; | ||
}; | ||
Store.prototype.invalidateQuery = function invalidateQuery(query, variables) { | ||
!function(store, request) { | ||
@@ -700,6 +755,3 @@ initStoreState(0); | ||
clearStoreState(); | ||
}(this, { | ||
query: dataQuery, | ||
variables: variables | ||
}); | ||
}(this, createRequest(query, variables)); | ||
}; | ||
@@ -743,2 +795,6 @@ | ||
var ctx = { | ||
parentTypeName: rootKey, | ||
parentKey: rootKey, | ||
parentFieldKey: "", | ||
fieldName: "", | ||
variables: normalizeVariables(operation, request.variables), | ||
@@ -751,3 +807,3 @@ fragments: getFragments(request.query), | ||
var data = input || Object.create(null); | ||
data = "Query" !== rootKey ? readRoot(ctx, rootKey, rootSelect, data) : readSelection(ctx, rootKey, rootSelect, data); | ||
data = rootKey !== ctx.store.getRootKey("query") ? readRoot(ctx, rootKey, rootSelect, data) : readSelection(ctx, rootKey, rootSelect, data); | ||
return { | ||
@@ -820,2 +876,6 @@ dependencies: getCurrentDependencies(), | ||
return readSelection({ | ||
parentTypeName: typename, | ||
parentKey: entityKey, | ||
parentFieldKey: "", | ||
fieldName: "", | ||
variables: variables || {}, | ||
@@ -861,2 +921,6 @@ fragments: fragments, | ||
if (void 0 !== resolvers && "function" == typeof resolvers[fieldName]) { | ||
ctx.parentTypeName = typename; | ||
ctx.parentKey = entityKey; | ||
ctx.parentFieldKey = fieldKey; | ||
ctx.fieldName = fieldName; | ||
if (void 0 !== fieldValue) { | ||
@@ -867,9 +931,7 @@ data[fieldAlias] = fieldValue; | ||
if (void 0 !== node.selectionSet) { | ||
resolverValue = resolveResolverResult(ctx, resolverValue, typename, fieldName, fieldKey, getSelectionSet(node), data[fieldAlias]); | ||
} | ||
var isNull = null == resolverValue; | ||
if (isNull && void 0 !== schemaPredicates) { | ||
dataFieldValue = void 0; | ||
var fieldSelect = getSelectionSet(node); | ||
var prevData = data[fieldAlias] || Object.create(null); | ||
dataFieldValue = resolveResolverResult(ctx, typename, fieldName, fieldKey, fieldSelect, prevData, resolverValue); | ||
} else { | ||
dataFieldValue = isNull ? null : resolverValue; | ||
dataFieldValue = void 0 === resolverValue && void 0 === schemaPredicates ? null : resolverValue; | ||
} | ||
@@ -879,6 +941,5 @@ } else if (void 0 === node.selectionSet) { | ||
} else { | ||
var fieldSelect = getSelectionSet(node); | ||
var link = store.getLink(fieldKey); | ||
if (void 0 !== link) { | ||
dataFieldValue = resolveLink(ctx, link, typename, fieldName, fieldSelect, data[fieldAlias]); | ||
dataFieldValue = resolveLink(ctx, link, typename, fieldName, getSelectionSet(node), data[fieldAlias]); | ||
} else if ("object" == typeof fieldValue && null !== fieldValue) { | ||
@@ -904,27 +965,83 @@ dataFieldValue = fieldValue; | ||
var resolveResolverResult = function(ctx, result, typename, fieldName, key, select, prevData) { | ||
var resolveResolverResult = function(ctx, typename, fieldName, key, select, prevData, result) { | ||
if (Array.isArray(result)) { | ||
var schemaPredicates = ctx.schemaPredicates; | ||
var isListNullable = void 0 !== schemaPredicates && schemaPredicates.isListNullable(typename, fieldName); | ||
var newResult = new Array(result.length); | ||
var isListNullable = void 0 === schemaPredicates || schemaPredicates.isListNullable(typename, fieldName); | ||
var data = new Array(result.length); | ||
for (var i = 0, l = result.length; i < l; i++) { | ||
var data = void 0 !== prevData ? prevData[i] : void 0; | ||
var childKey = joinKeys(key, "" + i); | ||
var childResult = resolveResolverResult(ctx, result[i], typename, fieldName, childKey, select, data); | ||
var innerResult = result[i]; | ||
var innerPrevData = void 0 !== prevData ? prevData[i] : void 0; | ||
var childResult = resolveResolverResult(ctx, typename, fieldName, joinKeys(key, "" + i), select, innerPrevData, innerResult); | ||
if (void 0 === childResult && !isListNullable) { | ||
return; | ||
} else { | ||
result[i] = void 0 !== childResult ? childResult : null; | ||
data[i] = void 0 !== childResult ? childResult : null; | ||
} | ||
} | ||
return newResult; | ||
} else if (null === result) { | ||
return data; | ||
} else if (null == result) { | ||
return null; | ||
} else if (isDataOrKey(result)) { | ||
var data$1 = void 0 === prevData ? Object.create(null) : prevData; | ||
var childKey$1 = ("string" == typeof result ? result : ctx.store.keyOfEntity(result)) || key; | ||
return readSelection(ctx, childKey$1, select, data$1); | ||
return "string" == typeof result ? readSelection(ctx, result, select, data$1) : function(ctx, key, select, data, result) { | ||
var store = ctx.store; | ||
var variables = ctx.variables; | ||
var schemaPredicates = ctx.schemaPredicates; | ||
var entityKey = store.keyOfEntity(result) || key; | ||
addDependency(entityKey); | ||
var resolvedTypename = result.__typename; | ||
var typename = store.getField(entityKey, "__typename") || resolvedTypename; | ||
if ("string" != typeof typename || resolvedTypename && typename !== resolvedTypename) { | ||
"production" !== process.env.NODE_ENV && warning(!1, "Invalid resolver value: The resolver at `" + entityKey + "` returned an invalid typename that could not be reconciled with the cache."); | ||
return; | ||
} | ||
data.__typename = typename; | ||
var iter = new SelectionIterator(typename, entityKey, select, ctx); | ||
var node; | ||
var hasFields = !1; | ||
var hasPartials = !1; | ||
while (void 0 !== (node = iter.next())) { | ||
var fieldName = getName(node); | ||
var fieldArgs = getFieldArguments(node, variables); | ||
var fieldAlias = getFieldAlias(node); | ||
var fieldKey = joinKeys(entityKey, keyOfField(fieldName, fieldArgs)); | ||
var fieldValue = store.getRecord(fieldKey); | ||
var resultValue = result[fieldName]; | ||
if ("production" !== process.env.NODE_ENV && schemaPredicates && typename) { | ||
schemaPredicates.isFieldAvailableOnType(typename, fieldName); | ||
} | ||
var dataFieldValue = void 0; | ||
if (void 0 !== resultValue && void 0 === node.selectionSet) { | ||
dataFieldValue = resultValue; | ||
} else if (void 0 === node.selectionSet) { | ||
dataFieldValue = fieldValue; | ||
} else if (void 0 !== resultValue) { | ||
dataFieldValue = resolveResolverResult(ctx, typename, fieldName, fieldKey, getSelectionSet(node), data[fieldAlias], resultValue); | ||
} else { | ||
var link = store.getLink(fieldKey); | ||
if (void 0 !== link) { | ||
dataFieldValue = resolveLink(ctx, link, typename, fieldName, getSelectionSet(node), data[fieldAlias]); | ||
} else if ("object" == typeof fieldValue && null !== fieldValue) { | ||
dataFieldValue = fieldValue; | ||
} | ||
} | ||
if (void 0 === dataFieldValue && void 0 !== schemaPredicates && schemaPredicates.isFieldNullable(typename, fieldName)) { | ||
hasPartials = !0; | ||
data[fieldAlias] = null; | ||
} else if (void 0 === dataFieldValue) { | ||
return; | ||
} else { | ||
hasFields = !0; | ||
data[fieldAlias] = dataFieldValue; | ||
} | ||
} | ||
if (hasPartials) { | ||
ctx.partial = !0; | ||
} | ||
return !hasFields ? void 0 : data; | ||
}(ctx, key, select, data$1, result); | ||
} else { | ||
"production" !== process.env.NODE_ENV && warning(!1, "Invalid resolver value: The field at `" + key + "` is a scalar (number, boolean, etc), but the GraphQL query expects a selection set for this field."); | ||
return; | ||
} | ||
"production" !== process.env.NODE_ENV && warning(!1, "Invalid resolver value: The resolver at `" + key + "` returned a scalar (number, boolean, etc), but the GraphQL query expects a selection set for this field.\nIf necessary, use Cache.resolve() to resolve a link or entity from the cache."); | ||
return; | ||
}; | ||
@@ -955,3 +1072,3 @@ | ||
var isDataOrKey = function(x) { | ||
return "string" == typeof x || "object" == typeof x && null !== x && "string" == typeof x.__typename; | ||
return "string" == typeof x || "object" == typeof x && "string" == typeof x.__typename; | ||
}; | ||
@@ -1023,5 +1140,5 @@ | ||
var addCacheOutcome = function(op, outcome) { | ||
return _extends({}, op, { | ||
context: _extends({}, op.context, { | ||
meta: _extends({}, op.context.meta, { | ||
return _extends(_extends({}, op), { | ||
context: _extends(_extends({}, op.context), { | ||
meta: _extends(_extends({}, op.context.meta), { | ||
cacheOutcome: outcome | ||
@@ -1034,3 +1151,3 @@ }) | ||
var addTypeNames = function(op) { | ||
return _extends({}, op, { | ||
return _extends(_extends({}, op), { | ||
query: formatDocument(op.query) | ||
@@ -1054,4 +1171,4 @@ }); | ||
var toRequestPolicy = function(operation, requestPolicy) { | ||
return _extends({}, operation, { | ||
context: _extends({}, operation.context, { | ||
return _extends(_extends({}, operation), { | ||
context: _extends(_extends({}, operation.context), { | ||
requestPolicy: requestPolicy | ||
@@ -1090,19 +1207,21 @@ }) | ||
var store = new Store(opts.schema ? new SchemaPredicates(opts.schema) : void 0, opts.resolvers, opts.updates, opts.optimistic, opts.keys); | ||
var optimisticKeys = new Set(); | ||
var ops = new Map(); | ||
var optimisticKeys = new Set; | ||
var ops = new Map; | ||
var deps = Object.create(null); | ||
var processDependencies = function(triggerOp, dependencies) { | ||
var pendingOperations = new Set(); | ||
function _ref(key) { | ||
return pendingOperations.add(key); | ||
var collectPendingOperations = function(pendingOperations, dependencies) { | ||
if (void 0 !== dependencies) { | ||
dependencies.forEach((function _ref(dep) { | ||
var keys = deps[dep]; | ||
if (void 0 !== keys) { | ||
deps[dep] = []; | ||
for (var i = 0, l = keys.length; i < l; i++) { | ||
pendingOperations.add(keys[i]); | ||
} | ||
} | ||
})); | ||
} | ||
dependencies.forEach(function(dep) { | ||
var keys = deps[dep]; | ||
if (void 0 !== keys) { | ||
deps[dep] = []; | ||
keys.forEach(_ref); | ||
} | ||
}); | ||
pendingOperations.forEach(function(key) { | ||
if (key !== triggerOp.key) { | ||
}; | ||
var executePendingOperations = function(operation, pendingOperations) { | ||
pendingOperations.forEach((function(key) { | ||
if (key !== operation.key) { | ||
var op = ops.get(key); | ||
@@ -1115,3 +1234,3 @@ if (void 0 !== op) { | ||
} | ||
}); | ||
})); | ||
}; | ||
@@ -1126,3 +1245,5 @@ var optimisticUpdate = function(operation) { | ||
optimisticKeys.add(key); | ||
processDependencies(operation, dependencies); | ||
var pendingOperations = new Set; | ||
collectPendingOperations(pendingOperations, dependencies); | ||
executePendingOperations(operation, pendingOperations); | ||
} | ||
@@ -1133,3 +1254,3 @@ } | ||
var updateDependencies = function(op, dependencies) { | ||
dependencies.forEach(function(dep) { | ||
dependencies.forEach((function(dep) { | ||
(deps[dep] || (deps[dep] = [])).push(op.key); | ||
@@ -1139,3 +1260,3 @@ if (!ops.has(op.key)) { | ||
} | ||
}); | ||
})); | ||
}; | ||
@@ -1182,5 +1303,8 @@ var operationResultFromCache = function(operation) { | ||
} | ||
if (void 0 !== writeDependencies) { | ||
processDependencies(result.operation, writeDependencies); | ||
var pendingOperations = new Set; | ||
collectPendingOperations(pendingOperations, writeDependencies); | ||
if (isQuery) { | ||
collectPendingOperations(pendingOperations, queryDependencies); | ||
} | ||
executePendingOperations(result.operation, pendingOperations); | ||
if (isQuery && void 0 !== queryDependencies) { | ||
@@ -1187,0 +1311,0 @@ updateDependencies(result.operation, queryDependencies); |
@@ -1,2 +0,2 @@ | ||
import{Kind as e,valueFromASTUntyped as t,buildClientSchema as r,isNullableType as n,isNonNullType as i,isListType as o}from"graphql";import{createRequest as a,formatDocument as u}from"urql";import{asMutable as s,make as c,clearOptimistic as l,get as f,setOptimistic as v,remove as d}from"pessimism";import y from"fast-json-stable-stringify";import{pipe as p,map as h,tap as m,share as g,filter as k,merge as b}from"wonka";function _(){return(_=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}var O=function(e){return e.name.value},w=function(e){return e.typeCondition.name.value},x=function(e){return void 0!==e.alias?e.alias.value:O(e)},S=function(e){return void 0!==e.selectionSet?e.selectionSet.selections:[]},R=function(e){var t=e.typeCondition;return void 0!==t?O(t):null},q=function(t){return t.kind===e.FIELD},P=function(t){return t.kind===e.INLINE_FRAGMENT},A=function(e,r){if(void 0===e.arguments||0===e.arguments.length)return null;for(var n=Object.create(null),i=0,o=0,a=e.arguments.length;o<a;o++){var u=e.arguments[o],s=t(u.value,r);null!=s&&(n[O(u)]=s,i++)}return i>0?n:null},F=function(e,r){if(void 0===e.variableDefinitions)return{};var n=r||{};return e.variableDefinitions.reduce(function(e,r){var i=O(r.variable),o=n[i];if(void 0===o){if(void 0===r.defaultValue)return e;o=t(r.defaultValue,n)}return e[i]=o,e},Object.create(null))},N=function(t){return t.kind===e.FRAGMENT_DEFINITION};function E(t){return t.kind===e.OPERATION_DEFINITION}var j=function(e){return e.definitions.find(E)};function L(e,t){return e[O(t)]=t,e}var T=function(e){return e.definitions.filter(N).reduce(L,{})},K=function(e,r){if(void 0===e.directives)return!0;for(var n=e.directives,i=0,o=n.length;i<o;i++){var a=n[i],u=O(a),s="include"===u;if(s||"skip"===u){var c=a.arguments?a.arguments[0]:null;if(c&&"if"===O(c)){var l=t(c.value,r);if("boolean"==typeof l||null===l)return s?!!l:!l}}}return!0},I=function(e,t){return t?e+"("+y(t)+")":e},M=function(e,t){return e+"."+t},Q=function(e,t,r,n){return!(!t||t!==R(e)&&S(e).some(function(e){if(!q(e))return!1;var t=O(e),i=A(e,n.variables),o=I(t,i);return!n.store.hasField(M(r,o))}))},D=function(e,t,r,n){this.typename=e,this.entityKey=t,this.context=n,this.indexStack=[0],this.selectionStack=[r]};D.prototype.next=function(){for(;0!==this.indexStack.length;){var e=this.indexStack[this.indexStack.length-1]++,t=this.selectionStack[this.selectionStack.length-1];if(e>=t.length)this.indexStack.pop(),this.selectionStack.pop();else{var r=t[e];if(K(r,this.context.variables)){if(q(r)){if("__typename"===O(r))continue;return r}var n=P(r)?r:this.context.fragments[O(r)];void 0!==n&&(void 0!==this.context.schemaPredicates?this.context.schemaPredicates.isInterfaceOfType(R(n),this.typename):Q(n,this.typename,this.entityKey,this.context))&&(this.indexStack.push(0),this.selectionStack.push(S(n)))}}}};var V=function(e){return Array.isArray(e)?e.some(V):"object"!=typeof e||null!==e&&"string"!=typeof e.__typename},C=function(e,t,r){$(0);var n=G(e,t,r);return ee(),n},G=function(e,t,r){var n=j(t.query),i={dependencies:te()},o={variables:F(n,t.variables),fragments:T(t.query),result:i,store:e,schemaPredicates:e.schemaPredicates},a=S(n),u=o.store.getRootKey(n.operation);return u===o.store.getRootKey("query")?H(o,u,a,r):U(o,u,a,r),i},z=function(e,t,r){$(r);for(var n,i=j(t.query),o={dependencies:te()},a={variables:F(i,t.variables),fragments:T(t.query),result:o,store:e,schemaPredicates:e.schemaPredicates,isOptimistic:!0},u=a.store.getRootKey("mutation"),s=a.store.getRootKey(i.operation),c=S(i),l=Object.create(null),f=new D(s,s,c,a);void 0!==(n=f.next());)if(void 0!==n.selectionSet){var v=O(n),d=a.store.optimisticMutations[v];if(void 0!==d){var y=A(n,a.variables),p=S(n),h=d(y||{},a.store,a);V(h)||W(a,h,p),l[v]=h;var m=a.store.updates[u][v];void 0!==m&&m(l,y||{},a.store,a)}}return ee(),o},B=function(e,t,r,n){var i=T(t),o=i[Object.keys(i)[0]];if(void 0!==o){var a=S(o),u=_({__typename:w(o)},r),s=e.keyOfEntity(u);if(s){var c={variables:n||{},fragments:i,result:{dependencies:te()},store:e,schemaPredicates:e.schemaPredicates};H(c,s,a,u)}}},H=function(e,t,r,n){var i=e.store,o=e.variables,a=t===e.store.getRootKey("query"),u=n.__typename;a||re(t),i.writeField(a?t:u,t,"__typename");for(var s,c=new D(u,t,r,e);void 0!==(s=c.next());){var l=O(s),f=A(s,o),v=M(t,I(l,f)),d=n[x(s)];if(a&&re(v),void 0===s.selectionSet)i.writeRecord(d,v);else if(V(d))i.writeRecord(d,v);else{var y=S(s),p=J(e,v,y,d);i.writeLink(p,v),i.removeRecord(v)}}},J=function(e,t,r,n){if(Array.isArray(n)){for(var i=new Array(n.length),o=0,a=n.length;o<a;o++){var u=n[o],s=M(t,""+o),c=J(e,s,r,u);i[o]=c}return i}if(null===n)return null;var l=e.store.keyOfEntity(n),f=null!==l?l:t;return H(e,f,r,n),f},U=function(e,t,r,n){for(var i,o=t===e.store.getRootKey("mutation")||t===e.store.getRootKey("subscription"),a=new D(t,t,r,e);void 0!==(i=a.next());){var u=O(i),s=x(i),c=A(i,e.variables),l=n[s];if(void 0!==i.selectionSet&&null!==l&&!V(l)){var f=S(i);W(e,l,f)}if(o){var v=e.store.updates[t][u];void 0!==v&&v(n,c||{},e.store,e)}}},W=function(e,t,r){if(Array.isArray(t)){for(var n=new Array(t.length),i=0,o=t.length;i<o;i++)n[i]=W(e,t[i],r);return n}if(null!==t){var a=e.store.keyOfEntity(t);null!==a?H(e,a,r,t):U(e,t.__typename,r,t)}},X=function(e,t,r){var n,i=e.store,o=e.variables,a="Query"===t;if(a)n=t;else{if(re(t),"string"!=typeof(n=i.getField(t,"__typename")))return;i.removeRecord(M(t,I("__typename")))}for(var u,s=new D(n,t,r,e);void 0!==(u=s.next());){var c=O(u),l=A(u,o),f=M(t,I(c,l));if(a&&re(f),void 0===u.selectionSet)i.removeRecord(f);else{var v=S(u),d=i.getLink(f);if(i.removeLink(f),void 0===d)void 0!==i.getRecord(f)&&i.removeRecord(f);else if(Array.isArray(d))for(var y=0,p=d.length;y<p;y++){var h=d[y];null!==h&&X(e,h,v)}else null!==d&&X(e,d,v)}}},Y={current:null},Z={current:null},$=function(e){Y.current=new Set,Z.current=e},ee=function(){Y.current=null,Z.current=null},te=function(){return Y.current},re=function(e){Y.current.add(e)},ne=function(e,t,r){return v(e,t,r,Z.current||0)},ie=function(e,t){var r=Z.current||0;return r?v(e,t,void 0,r):d(e,t)},oe=function(e,t,r,n,i){var o;if(this.records=s(c()),this.links=s(c()),this.resolvers=t||{},this.optimisticMutations=n||{},this.keys=i||{},this.schemaPredicates=e,this.updates={Mutation:r&&r.Mutation||{},Subscription:r&&r.Subscription||{}},e){var a=e.schema,u=a.getQueryType(),l=a.getMutationType(),f=a.getSubscriptionType(),v=u?u.name:"Query",d=l?l.name:"Mutation",y=f?f.name:"Subscription";this.rootFields={query:v,mutation:d,subscription:y},this.rootNames=((o={})[v]="query",o[d]="mutation",o[y]="subscription",o)}else this.rootFields={query:"Query",mutation:"Mutation",subscription:"Subscription"},this.rootNames={Query:"query",Mutation:"mutation",Subscription:"subscription"}};oe.prototype.getRootKey=function(e){return this.rootFields[e]},oe.prototype.keyOfEntity=function(e){var t,r=e.__typename,n=e.id,i=e._id;if(!r)return null;if(this.rootNames[r])return this.rootNames[r];if(this.keys[r])t=this.keys[r](e);else if(null!=n)t=""+n;else{if(null==i)return null;t=""+i}return t?r+":"+t:null},oe.prototype.clearOptimistic=function(e){this.records=l(this.records,e),this.links=l(this.links,e)},oe.prototype.getRecord=function(e){return f(this.records,e)},oe.prototype.removeRecord=function(e){return this.records=ie(this.records,e)},oe.prototype.writeRecord=function(e,t){return this.records=ne(this.records,t,e)},oe.prototype.getField=function(e,t,r){var n=M(e,I(t,r));return this.getRecord(n)},oe.prototype.writeField=function(e,t,r,n){var i=M(t,I(r,n));return this.records=ne(this.records,i,e)},oe.prototype.getLink=function(e){return f(this.links,e)},oe.prototype.removeLink=function(e){return this.links=ie(this.links,e)},oe.prototype.writeLink=function(e,t){return this.links=ne(this.links,t,e)},oe.prototype.resolveValueOrLink=function(e){var t=this.getRecord(e);return void 0!==t?t:this.getLink(e)||null},oe.prototype.resolve=function(e,t,r){if("string"==typeof e)return re(e),this.resolveValueOrLink(M(e,I(t,r)));var n=this.keyOfEntity(e);return null===n?null:(re(n),this.resolveValueOrLink(M(n,I(t,r))))},oe.prototype.invalidateQuery=function(e,t){!function(e,t){$(0);var r=j(t.query),n={variables:F(r,t.variables),fragments:T(t.query),store:e,schemaPredicates:e.schemaPredicates};X(n,n.store.getRootKey("query"),S(r)),ee()}(this,{query:e,variables:t})},oe.prototype.hasField=function(e){return void 0!==this.getRecord(e)||void 0!==this.getLink(e)},oe.prototype.updateQuery=function(e,t){var r=a(e.query,e.variables),n=t(this.readQuery(r));null!==n&&G(this,r,n)},oe.prototype.readQuery=function(e){return ue(this,a(e.query,e.variables)).data},oe.prototype.readFragment=function(e,t,r){return le(this,e,t,r)},oe.prototype.writeFragment=function(e,t,r){B(this,e,t,r)};var ae=function(e,t,r){$(0);var n=ue(e,t,r);return ee(),n},ue=function(e,t,r){var n=j(t.query),i=e.getRootKey(n.operation),o=S(n),a={variables:F(n,t.variables),fragments:T(t.query),partial:!1,store:e,schemaPredicates:e.schemaPredicates},u=r||Object.create(null);return u="Query"!==i?se(a,i,o,u):fe(a,i,o,u),{dependencies:te(),partial:void 0!==u&&a.partial,data:void 0===u?null:u}},se=function(e,t,r,n){if("string"!=typeof n.__typename)return n;var i=Object.create(null);i.__typename=n.__typename;for(var o,a=new D(t,t,r,e);void 0!==(o=a.next());){var u=x(o),s=n[u];i[u]=void 0===o.selectionSet||null===s||V(s)?s:ce(e,S(o),s)}return i},ce=function(e,t,r){if(Array.isArray(r)){for(var n=new Array(r.length),i=0,o=r.length;i<o;i++)n[i]=ce(e,t,r[i]);return n}if(null===r)return null;var a=e.store.keyOfEntity(r);if(null!==a){var u=Object.create(null),s=fe(e,a,t,u);return void 0===s?null:s}return se(e,r.__typename,t,r)},le=function(e,t,r,n){var i=T(t),o=i[Object.keys(i)[0]];if(void 0===o)return null;var a=S(o),u=w(o);"string"==typeof r||r.__typename||(r.__typename=u);var s="string"!=typeof r?e.keyOfEntity(_({__typename:u},r)):r;return s&&fe({variables:n||{},fragments:i,partial:!1,store:e,schemaPredicates:e.schemaPredicates},s,a,Object.create(null))||null},fe=function(e,t,r,n){var i=e.store,o=e.variables,a=e.schemaPredicates,u=t===i.getRootKey("query");u||re(t);var s=u?t:i.getField(t,"__typename");if("string"==typeof s){n.__typename=s;for(var c,l=new D(s,t,r,e),f=!1,v=!1;void 0!==(c=l.next());){var d=O(c),y=A(c,o),p=x(c),h=M(t,I(d,y)),m=i.getRecord(h);u&&re(h);var g=void 0,k=i.resolvers[s];if(void 0!==k&&"function"==typeof k[d]){void 0!==m&&(n[p]=m);var b=k[d](n,y||{},i,e);void 0!==c.selectionSet&&(b=ve(e,b,s,d,h,S(c),n[p]));var _=null==b;g=_&&void 0!==a?void 0:_?null:b}else if(void 0===c.selectionSet)g=m;else{var w=S(c),R=i.getLink(h);void 0!==R?g=de(e,R,s,d,w,n[p]):"object"==typeof m&&null!==m&&(g=m)}if(void 0===g&&void 0!==a&&a.isFieldNullable(s,d))v=!0,n[p]=null;else{if(void 0===g)return;f=!0,n[p]=g}}return v&&(e.partial=!0),u&&v&&!f?void 0:n}},ve=function(e,t,r,n,i,o,a){if(Array.isArray(t)){for(var u=e.schemaPredicates,s=void 0!==u&&u.isListNullable(r,n),c=new Array(t.length),l=0,f=t.length;l<f;l++){var v=void 0!==a?a[l]:void 0,d=M(i,""+l),y=ve(e,t[l],r,n,d,o,v);if(void 0===y&&!s)return;t[l]=void 0!==y?y:null}return c}if(null===t)return null;if(ye(t)){var p=void 0===a?Object.create(null):a,h=("string"==typeof t?t:e.store.keyOfEntity(t))||i;return fe(e,h,o,p)}},de=function(e,t,r,n,i,o){if(Array.isArray(t)){for(var a=e.schemaPredicates,u=void 0!==a&&a.isListNullable(r,n),s=new Array(t.length),c=0,l=t.length;c<l;c++){var f=de(e,t[c],r,n,i,void 0!==o?o[c]:void 0);if(void 0===f&&!u)return;s[c]=void 0!==f?f:null}return s}if(null===t)return null;var v=void 0===o?Object.create(null):o;return fe(e,t,i,v)},ye=function(e){return"string"==typeof e||"object"==typeof e&&null!==e&&"string"==typeof e.__typename},pe=function(e){this.schema=r(e)};pe.prototype.isFieldNullable=function(e,t){var r=he(this.schema,e,t);return void 0!==r&&n(r.type)},pe.prototype.isListNullable=function(e,t){var r=he(this.schema,e,t);if(void 0===r)return!1;var a=i(r.type)?r.type.ofType:r.type;return o(a)&&n(a.ofType)},pe.prototype.isFieldAvailableOnType=function(e,t){return!!he(this.schema,e,t)},pe.prototype.isInterfaceOfType=function(e,t){if(!t||!e)return!1;if(t===e)return!0;var r=this.schema.getType(e),n=this.schema.getType(t);return this.schema.isPossibleType(r,n)};var he=function(e,t,r){var n=e.getType(t);if(void 0!==n){var i=n.getFields()[r];if(void 0!==i)return i}},me=function(e,t){return _({},e,{context:_({},e.context,{meta:_({},e.context.meta,{cacheOutcome:t})})})},ge=function(e){return _({},e,{query:u(e.query)})},ke=function(e){return e.context.requestPolicy},be=function(e){return"query"===e.operationName},_e=function(e){var t=ke(e);return be(e)&&"network-only"!==t},Oe=function(e,t){return _({},e,{context:_({},e.context,{requestPolicy:t})})};function we(e){return _e(e)}function xe(e){return"miss"===e.outcome}function Se(e){return me(e.operation,e.outcome)}function Re(e){return"miss"!==e.outcome}function qe(e){return!_e(e)}var Pe=function(e){return function(t){var r=t.forward,n=t.client;e||(e={});var i=new oe(e.schema?new pe(e.schema):void 0,e.resolvers,e.updates,e.optimistic,e.keys),o=new Set,a=new Map,u=Object.create(null),s=function(e,t){var r=new Set;function i(e){return r.add(e)}t.forEach(function(e){var t=u[e];void 0!==t&&(u[e]=[],t.forEach(i))}),r.forEach(function(t){if(t!==e.key){var r=a.get(t);if(void 0!==r){a.delete(t);var i=Oe(r,"cache-first");n.reexecuteOperation(i)}}})},c=function(e){if(a=ke(n=e),function(e){return"mutation"===e.operationName}(n)&&"network-only"!==a){var t=e.key,r=z(i,e,t).dependencies;0!==r.size&&(o.add(t),s(e,r))}var n,a},l=function(e,t){t.forEach(function(t){(u[t]||(u[t]=[])).push(e.key),a.has(e.key)||a.set(e.key,"network-only"===e.context.requestPolicy?Oe(e,"cache-and-network"):e)})},f=function(e){var t,r=ke(e),n=ae(i,e),o=n.data,a=n.partial;return null===o?t="miss":(l(e,n.dependencies),t=a&&"cache-only"!==r?"partial":"hit"),{outcome:t,operation:e,data:o}},v=function(e){var t,r,n=e.operation,a=e.error,u=e.extensions,c=be(n),f=e.data,v=n.key;if(o.has(v)&&(o.delete(v),i.clearOptimistic(v)),null!=f)if(t=C(i,n,f).dependencies,c){var d=ae(i,n);f=d.data,r=d.dependencies}else f=ae(i,n,f).data;return void 0!==t&&s(e.operation,t),c&&void 0!==r&&l(e.operation,r),{data:f,error:a,extensions:u,operation:n}};function d(e){var t=e.operation,r=e.outcome,i=ke(t);if("cache-and-network"===i||"cache-first"===i&&"partial"===r){var o=Oe(t,"network-only");n.reexecuteOperation(o)}return{operation:me(t,r),data:e.data,error:e.error,extensions:e.extensions}}return function(e){var t=p(e,h(ge),m(c),g),n=p(t,k(we),h(f),g),i=p(n,k(xe),h(Se)),o=p(n,k(Re),h(d)),a=p(r(b([p(t,k(qe)),i])),h(v));return b([a,o])}}};export{oe as Store,Pe as cacheExchange,ae as query,ue as read,C as write,B as writeFragment,z as writeOptimistic}; | ||
import{Kind as e,valueFromASTUntyped as t,buildClientSchema as r,isNullableType as n,isNonNullType as i,isListType as o}from"graphql";import{stringifyVariables as a,createRequest as s,formatDocument as u}from"urql";import{asMutable as c,make as l,clearOptimistic as f,get as v,setOptimistic as d,remove as p}from"pessimism";import{pipe as y,map as h,tap as m,share as g,filter as k,merge as b}from"wonka";function _(){return(_=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}var O=function(e){return e.name.value},w=function(e){return e.typeCondition.name.value},N=function(e){return void 0!==e.alias?e.alias.value:O(e)},x=function(e){return void 0!==e.selectionSet?e.selectionSet.selections:[]},S=function(e){var t=e.typeCondition;return void 0!==t?O(t):null},F=function(t){return t.kind===e.FIELD},R=function(t){return t.kind===e.INLINE_FRAGMENT},K=function(e,r){if(void 0===e.arguments||0===e.arguments.length)return null;for(var n=Object.create(null),i=0,o=0,a=e.arguments.length;o<a;o++){var s=e.arguments[o],u=t(s.value,r);null!=u&&(n[O(s)]=u,i++)}return i>0?n:null},q=function(e,r){if(void 0===e.variableDefinitions)return{};var n=r||{};return e.variableDefinitions.reduce((function(e,r){var i=O(r.variable),o=n[i];if(void 0===o){if(void 0===r.defaultValue)return e;o=t(r.defaultValue,n)}return e[i]=o,e}),Object.create(null))},P=function(t){return t.kind===e.FRAGMENT_DEFINITION};function T(t){return t.kind===e.OPERATION_DEFINITION}var A=function(e){return e.definitions.find(T)};function j(e,t){return e[O(t)]=t,e}var E=function(e){return e.definitions.filter(P).reduce(j,{})},L=function(e,r){if(void 0===e.directives)return!0;for(var n=e.directives,i=0,o=n.length;i<o;i++){var a=n[i],s=O(a),u="include"===s;if(u||"skip"===s){var c=a.arguments?a.arguments[0]:null;if(c&&"if"===O(c)){var l=t(c.value,r);if("boolean"==typeof l||null===l)return u?!!l:!l}}}return!0},I=function(e,t){return t?e+"("+a(t)+")":e},M=function(e,t){return e+"."+t},Q=function(e,t,r,n){return!(!t||t!==S(e)&&x(e).some((function(e){if(!F(e))return!1;var t=O(e),i=K(e,n.variables),o=I(t,i);return!n.store.hasField(M(r,o))})))},C=function(e,t,r,n){this.typename=e,this.entityKey=t,this.context=n,this.indexStack=[0],this.selectionStack=[r]};C.prototype.next=function(){for(;0!==this.indexStack.length;){var e=this.indexStack[this.indexStack.length-1]++,t=this.selectionStack[this.selectionStack.length-1];if(e>=t.length)this.indexStack.pop(),this.selectionStack.pop();else{var r=t[e];if(L(r,this.context.variables)){if(F(r)){if("__typename"===O(r))continue;return r}var n=R(r)?r:this.context.fragments[O(r)];void 0!==n&&(void 0!==this.context.schemaPredicates?this.context.schemaPredicates.isInterfaceOfType(S(n),this.typename):Q(n,this.typename,this.entityKey,this.context))&&(this.indexStack.push(0),this.selectionStack.push(x(n)))}}}};var D=function(e){return Array.isArray(e)?e.some(D):"object"!=typeof e||null!==e&&"string"!=typeof e.__typename},V=function(e,t,r){$(0);var n=G(e,t,r);return ee(),n},G=function(e,t,r){var n=A(t.query),i={dependencies:te()},o=x(n),a=e.getRootKey(n.operation),s={parentTypeName:a,parentKey:a,parentFieldKey:"",fieldName:"",variables:q(n,t.variables),fragments:E(t.query),result:i,store:e,schemaPredicates:e.schemaPredicates};return a===s.store.getRootKey("query")?H(s,a,o,r):U(s,a,o,r),i},z=function(e,t,r){$(r);for(var n,i=A(t.query),o={dependencies:te()},a=e.getRootKey("mutation"),s=e.getRootKey(i.operation),u={parentTypeName:a,parentKey:a,parentFieldKey:"",fieldName:"",variables:q(i,t.variables),fragments:E(t.query),result:o,store:e,schemaPredicates:e.schemaPredicates,optimistic:!0},c=x(i),l=Object.create(null),f=new C(s,s,c,u);void 0!==(n=f.next());)if(void 0!==n.selectionSet){var v=O(n),d=u.store.optimisticMutations[v];if(void 0!==d){u.fieldName=v;var p=K(n,u.variables),y=x(n),h=d(p||{},u.store,u);D(h)||W(u,h,y),l[v]=h;var m=u.store.updates[a][v];void 0!==m&&m(l,p||{},u.store,u)}}return ee(),o},B=function(e,t,r,n){var i=E(t),o=i[Object.keys(i)[0]];if(void 0!==o){var a=x(o),s=w(o),u=_({__typename:s},r),c=e.keyOfEntity(u);if(c){var l={parentTypeName:s,parentKey:c,parentFieldKey:"",fieldName:"",variables:n||{},fragments:i,result:{dependencies:te()},store:e,schemaPredicates:e.schemaPredicates};H(l,c,a,u)}}},H=function(e,t,r,n){var i=e.store,o=e.variables,a=t===e.store.getRootKey("query"),s=n.__typename;a||re(t),i.writeField(a?t:s,t,"__typename");for(var u,c=new C(s,t,r,e);void 0!==(u=c.next());){var l=O(u),f=K(u,o),v=M(t,I(l,f)),d=n[N(u)];if(a&&re(v),void 0===u.selectionSet)i.writeRecord(d,v);else if(D(d))i.writeRecord(d,v);else{var p=x(u),y=M(t,l),h=J(e,v,p,d);i.writeLink(h,v),i.writeConnection(y,v,f),i.removeRecord(v)}}},J=function(e,t,r,n){if(Array.isArray(n)){for(var i=new Array(n.length),o=0,a=n.length;o<a;o++){var s=n[o],u=M(t,""+o),c=J(e,u,r,s);i[o]=c}return i}if(null===n)return null;var l=e.store.keyOfEntity(n),f=null!==l?l:t;return H(e,f,r,n),f},U=function(e,t,r,n){for(var i,o=t===e.store.getRootKey("mutation")||t===e.store.getRootKey("subscription"),a=new C(t,t,r,e);void 0!==(i=a.next());){var s=O(i),u=N(i),c=K(i,e.variables),l=n[u];if(void 0!==i.selectionSet&&null!==l&&!D(l)){var f=x(i);W(e,l,f)}if(o){var v=M(t,I(s,c));e.parentTypeName=t,e.parentKey=t,e.parentFieldKey=v,e.fieldName=s;var d=e.store.updates[t][s];void 0!==d&&d(n,c||{},e.store,e)}}},W=function(e,t,r){if(Array.isArray(t)){for(var n=new Array(t.length),i=0,o=t.length;i<o;i++)n[i]=W(e,t[i],r);return n}if(null!==t){var a=e.store.keyOfEntity(t);null!==a?H(e,a,r,t):U(e,t.__typename,r,t)}},X=function(e,t,r){var n,i=e.store,o=e.variables,a="Query"===t;if(a)n=t;else{if(re(t),"string"!=typeof(n=i.getField(t,"__typename")))return;i.removeRecord(M(t,I("__typename")))}for(var s,u=new C(n,t,r,e);void 0!==(s=u.next());){var c=O(s),l=K(s,o),f=M(t,I(c,l));if(a&&re(f),void 0===s.selectionSet)i.removeRecord(f);else{var v=x(s),d=i.getLink(f);if(i.removeLink(f),void 0===d)void 0!==i.getRecord(f)&&i.removeRecord(f);else if(Array.isArray(d))for(var p=0,y=d.length;p<y;p++){var h=d[p];null!==h&&X(e,h,v)}else null!==d&&X(e,d,v)}}},Y={current:null},Z={current:null},$=function(e){Y.current=new Set,Z.current=e},ee=function(){Y.current=null,Z.current=null},te=function(){return Y.current},re=function(e){Y.current.add(e)},ne=function(e,t,r){return d(e,t,r,Z.current||0)},ie=function(e,t){var r=Z.current||0;return r?d(e,t,void 0,r):p(e,t)},oe=function(e,t,r,n,i){var o;if(this.records=c(l()),this.connections=c(l()),this.links=c(l()),this.resolvers=t||{},this.optimisticMutations=n||{},this.keys=i||{},this.schemaPredicates=e,this.updates={Mutation:r&&r.Mutation||{},Subscription:r&&r.Subscription||{}},e){var a=e.schema,s=a.getQueryType(),u=a.getMutationType(),f=a.getSubscriptionType(),v=s?s.name:"Query",d=u?u.name:"Mutation",p=f?f.name:"Subscription";this.rootFields={query:v,mutation:d,subscription:p},this.rootNames=((o={})[v]="query",o[d]="mutation",o[p]="subscription",o)}else this.rootFields={query:"Query",mutation:"Mutation",subscription:"Subscription"},this.rootNames={Query:"query",Mutation:"mutation",Subscription:"subscription"}};oe.prototype.getRootKey=function(e){return this.rootFields[e]},oe.prototype.keyOfEntity=function(e){var t,r=e.__typename,n=e.id,i=e._id;if(!r)return null;if(this.rootNames[r])return this.rootNames[r];if(this.keys[r])t=this.keys[r](e);else if(null!=n)t=""+n;else{if(null==i)return null;t=""+i}return t?r+":"+t:null},oe.prototype.clearOptimistic=function(e){this.records=f(this.records,e),this.connections=f(this.connections,e),this.links=f(this.links,e)},oe.prototype.getRecord=function(e){return v(this.records,e)},oe.prototype.removeRecord=function(e){return this.records=ie(this.records,e)},oe.prototype.writeRecord=function(e,t){return this.records=ne(this.records,t,e)},oe.prototype.getField=function(e,t,r){var n=M(e,I(t,r));return this.getRecord(n)},oe.prototype.writeField=function(e,t,r,n){var i=M(t,I(r,n));return this.records=ne(this.records,i,e)},oe.prototype.getLink=function(e){return v(this.links,e)},oe.prototype.removeLink=function(e){return this.links=ie(this.links,e)},oe.prototype.writeLink=function(e,t){return this.links=ne(this.links,t,e)},oe.prototype.writeConnection=function(e,t,r){if(null===r)return this.connections;var n=v(this.connections,e),i=[r,t];if(void 0===n)n=[i];else{for(var o=0,a=n.length;o<a;o++)if(n[o][1]===t)return this.connections;(n=n.slice()).push(i)}return this.connections=ne(this.connections,e,n)},oe.prototype.resolveValueOrLink=function(e){var t=this.getRecord(e);return void 0!==t?t:this.getLink(e)||null},oe.prototype.resolve=function(e,t,r){if(null===e)return null;if("string"==typeof e)return re(e),this.resolveValueOrLink(M(e,I(t,r)));var n=this.keyOfEntity(e);return null===n?null:(re(n),this.resolveValueOrLink(M(n,I(t,r))))},oe.prototype.resolveConnections=function(e,t){var r;if("string"==typeof e)r=v(this.connections,M(e,t));else if(null!==e){var n=this.keyOfEntity(e);null!==n&&(re(n),r=v(this.connections,M(n,t)))}return void 0!==r?r:[]},oe.prototype.invalidateQuery=function(e,t){!function(e,t){$(0);var r=A(t.query),n={variables:q(r,t.variables),fragments:E(t.query),store:e,schemaPredicates:e.schemaPredicates};X(n,n.store.getRootKey("query"),x(r)),ee()}(this,s(e,t))},oe.prototype.hasField=function(e){return void 0!==this.getRecord(e)||void 0!==this.getLink(e)},oe.prototype.updateQuery=function(e,t){var r=s(e.query,e.variables),n=t(this.readQuery(r));null!==n&&G(this,r,n)},oe.prototype.readQuery=function(e){return se(this,s(e.query,e.variables)).data},oe.prototype.readFragment=function(e,t,r){return le(this,e,t,r)},oe.prototype.writeFragment=function(e,t,r){B(this,e,t,r)};var ae=function(e,t,r){$(0);var n=se(e,t,r);return ee(),n},se=function(e,t,r){var n=A(t.query),i=e.getRootKey(n.operation),o=x(n),a={parentTypeName:i,parentKey:i,parentFieldKey:"",fieldName:"",variables:q(n,t.variables),fragments:E(t.query),partial:!1,store:e,schemaPredicates:e.schemaPredicates},s=r||Object.create(null);return s=i!==a.store.getRootKey("query")?ue(a,i,o,s):fe(a,i,o,s),{dependencies:te(),partial:void 0!==s&&a.partial,data:void 0===s?null:s}},ue=function(e,t,r,n){if("string"!=typeof n.__typename)return n;var i=Object.create(null);i.__typename=n.__typename;for(var o,a=new C(t,t,r,e);void 0!==(o=a.next());){var s=N(o),u=n[s];i[s]=void 0===o.selectionSet||null===u||D(u)?u:ce(e,x(o),u)}return i},ce=function(e,t,r){if(Array.isArray(r)){for(var n=new Array(r.length),i=0,o=r.length;i<o;i++)n[i]=ce(e,t,r[i]);return n}if(null===r)return null;var a=e.store.keyOfEntity(r);if(null!==a){var s=Object.create(null),u=fe(e,a,t,s);return void 0===u?null:u}return ue(e,r.__typename,t,r)},le=function(e,t,r,n){var i=E(t),o=i[Object.keys(i)[0]];if(void 0===o)return null;var a=x(o),s=w(o);"string"==typeof r||r.__typename||(r.__typename=s);var u="string"!=typeof r?e.keyOfEntity(_({__typename:s},r)):r;return u&&fe({parentTypeName:s,parentKey:u,parentFieldKey:"",fieldName:"",variables:n||{},fragments:i,partial:!1,store:e,schemaPredicates:e.schemaPredicates},u,a,Object.create(null))||null},fe=function(e,t,r,n){var i=e.store,o=e.variables,a=e.schemaPredicates,s=t===i.getRootKey("query");s||re(t);var u=s?t:i.getField(t,"__typename");if("string"==typeof u){n.__typename=u;for(var c,l=new C(u,t,r,e),f=!1,v=!1;void 0!==(c=l.next());){var d=O(c),p=K(c,o),y=N(c),h=M(t,I(d,p)),m=i.getRecord(h);s&&re(h);var g=void 0,k=i.resolvers[u];if(void 0!==k&&"function"==typeof k[d]){e.parentTypeName=u,e.parentKey=t,e.parentFieldKey=h,e.fieldName=d,void 0!==m&&(n[y]=m);var b=k[d](n,p||{},i,e);if(void 0!==c.selectionSet){var _=x(c),w=n[y]||Object.create(null);g=ve(e,u,d,h,_,w,b)}else g=void 0===b&&void 0===a?null:b}else if(void 0===c.selectionSet)g=m;else{var S=i.getLink(h);void 0!==S?g=de(e,S,u,d,x(c),n[y]):"object"==typeof m&&null!==m&&(g=m)}if(void 0===g&&void 0!==a&&a.isFieldNullable(u,d))v=!0,n[y]=null;else{if(void 0===g)return;f=!0,n[y]=g}}return v&&(e.partial=!0),s&&v&&!f?void 0:n}},ve=function(e,t,r,n,i,o,a){if(Array.isArray(a)){for(var s=e.schemaPredicates,u=void 0===s||s.isListNullable(t,r),c=new Array(a.length),l=0,f=a.length;l<f;l++){var v=a[l],d=void 0!==o?o[l]:void 0,p=ve(e,t,r,M(n,""+l),i,d,v);if(void 0===p&&!u)return;c[l]=void 0!==p?p:null}return c}if(null==a)return null;if(pe(a)){var y=void 0===o?Object.create(null):o;return"string"==typeof a?fe(e,a,i,y):function(e,t,r,n,i){var o=e.store,a=e.variables,s=e.schemaPredicates,u=o.keyOfEntity(i)||t;re(u);var c=i.__typename,l=o.getField(u,"__typename")||c;if(!("string"!=typeof l||c&&l!==c)){n.__typename=l;for(var f,v=new C(l,u,r,e),d=!1,p=!1;void 0!==(f=v.next());){var y=O(f),h=K(f,a),m=N(f),g=M(u,I(y,h)),k=o.getRecord(g),b=i[y],_=void 0;if(void 0!==b&&void 0===f.selectionSet)_=b;else if(void 0===f.selectionSet)_=k;else if(void 0!==b)_=ve(e,l,y,g,x(f),n[m],b);else{var w=o.getLink(g);void 0!==w?_=de(e,w,l,y,x(f),n[m]):"object"==typeof k&&null!==k&&(_=k)}if(void 0===_&&void 0!==s&&s.isFieldNullable(l,y))p=!0,n[m]=null;else{if(void 0===_)return;d=!0,n[m]=_}}return p&&(e.partial=!0),d?n:void 0}}(e,n,i,y,a)}},de=function(e,t,r,n,i,o){if(Array.isArray(t)){for(var a=e.schemaPredicates,s=void 0!==a&&a.isListNullable(r,n),u=new Array(t.length),c=0,l=t.length;c<l;c++){var f=de(e,t[c],r,n,i,void 0!==o?o[c]:void 0);if(void 0===f&&!s)return;u[c]=void 0!==f?f:null}return u}if(null===t)return null;var v=void 0===o?Object.create(null):o;return fe(e,t,i,v)},pe=function(e){return"string"==typeof e||"object"==typeof e&&"string"==typeof e.__typename},ye=function(e){this.schema=r(e)};ye.prototype.isFieldNullable=function(e,t){var r=he(this.schema,e,t);return void 0!==r&&n(r.type)},ye.prototype.isListNullable=function(e,t){var r=he(this.schema,e,t);if(void 0===r)return!1;var a=i(r.type)?r.type.ofType:r.type;return o(a)&&n(a.ofType)},ye.prototype.isFieldAvailableOnType=function(e,t){return!!he(this.schema,e,t)},ye.prototype.isInterfaceOfType=function(e,t){if(!t||!e)return!1;if(t===e)return!0;var r=this.schema.getType(e),n=this.schema.getType(t);return this.schema.isPossibleType(r,n)};var he=function(e,t,r){var n=e.getType(t);if(void 0!==n){var i=n.getFields()[r];if(void 0!==i)return i}},me=function(e,t){return _(_({},e),{context:_(_({},e.context),{meta:_(_({},e.context.meta),{cacheOutcome:t})})})},ge=function(e){return _(_({},e),{query:u(e.query)})},ke=function(e){return e.context.requestPolicy},be=function(e){return"query"===e.operationName},_e=function(e){var t=ke(e);return be(e)&&"network-only"!==t},Oe=function(e,t){return _(_({},e),{context:_(_({},e.context),{requestPolicy:t})})};function we(e){return _e(e)}function Ne(e){return"miss"===e.outcome}function xe(e){return me(e.operation,e.outcome)}function Se(e){return"miss"!==e.outcome}function Fe(e){return!_e(e)}var Re=function(e){return function(t){var r=t.forward,n=t.client;e||(e={});var i=new oe(e.schema?new ye(e.schema):void 0,e.resolvers,e.updates,e.optimistic,e.keys),o=new Set,a=new Map,s=Object.create(null),u=function(e,t){void 0!==t&&t.forEach((function(t){var r=s[t];if(void 0!==r){s[t]=[];for(var n=0,i=r.length;n<i;n++)e.add(r[n])}}))},c=function(e,t){t.forEach((function(t){if(t!==e.key){var r=a.get(t);if(void 0!==r){a.delete(t);var i=Oe(r,"cache-first");n.reexecuteOperation(i)}}}))},l=function(e){if(s=ke(a=e),function(e){return"mutation"===e.operationName}(a)&&"network-only"!==s){var t=e.key,r=z(i,e,t).dependencies;if(0!==r.size){o.add(t);var n=new Set;u(n,r),c(e,n)}}var a,s},f=function(e,t){t.forEach((function(t){(s[t]||(s[t]=[])).push(e.key),a.has(e.key)||a.set(e.key,"network-only"===e.context.requestPolicy?Oe(e,"cache-and-network"):e)}))},v=function(e){var t,r=ke(e),n=ae(i,e),o=n.data,a=n.partial;return null===o?t="miss":(f(e,n.dependencies),t=a&&"cache-only"!==r?"partial":"hit"),{outcome:t,operation:e,data:o}},d=function(e){var t,r,n=e.operation,a=e.error,s=e.extensions,l=be(n),v=e.data,d=n.key;if(o.has(d)&&(o.delete(d),i.clearOptimistic(d)),null!=v)if(t=V(i,n,v).dependencies,l){var p=ae(i,n);v=p.data,r=p.dependencies}else v=ae(i,n,v).data;var y=new Set;return u(y,t),l&&u(y,r),c(e.operation,y),l&&void 0!==r&&f(e.operation,r),{data:v,error:a,extensions:s,operation:n}};function p(e){var t=e.operation,r=e.outcome,i=ke(t);if("cache-and-network"===i||"cache-first"===i&&"partial"===r){var o=Oe(t,"network-only");n.reexecuteOperation(o)}return{operation:me(t,r),data:e.data,error:e.error,extensions:e.extensions}}return function(e){var t=y(e,h(ge),m(l),g),n=y(t,k(we),h(v),g),i=y(n,k(Ne),h(xe)),o=y(n,k(Se),h(p)),a=y(r(b([y(t,k(Fe)),i])),h(d));return b([a,o])}}};export{oe as Store,Re as cacheExchange,ae as query,se as read,V as write,B as writeFragment,z as writeOptimistic}; | ||
//# sourceMappingURL=urql-exchange-graphcache.es.min.js.map |
@@ -9,6 +9,2 @@ "use strict"; | ||
var stringify = function _interopDefault(ex) { | ||
return ex && "object" == typeof ex && "default" in ex ? ex.default : ex; | ||
}(require("fast-json-stable-stringify")); | ||
var wonka = require("wonka"); | ||
@@ -90,3 +86,3 @@ | ||
var args = input || {}; | ||
return node.variableDefinitions.reduce(function(vars, def) { | ||
return node.variableDefinitions.reduce((function(vars, def) { | ||
var name = getName(def.variable); | ||
@@ -103,3 +99,3 @@ var value = args[name]; | ||
return vars; | ||
}, Object.create(null)); | ||
}), Object.create(null)); | ||
}; | ||
@@ -120,5 +116,5 @@ | ||
var argIndex = 0; | ||
(error = new Error(format.replace(/%s/g, function() { | ||
(error = new Error(format.replace(/%s/g, (function() { | ||
return args[argIndex++]; | ||
}))).name = "Invariant Violation"; | ||
})))).name = "Invariant Violation"; | ||
} | ||
@@ -179,3 +175,3 @@ error.framesToPop = 1; | ||
var keyOfField = function(fieldName, args) { | ||
return args ? fieldName + "(" + stringify(args) + ")" : fieldName; | ||
return args ? fieldName + "(" + urql.stringifyVariables(args) + ")" : fieldName; | ||
}; | ||
@@ -196,3 +192,3 @@ | ||
"production" !== process.env.NODE_ENV && warning(!1, "Heuristic Fragment Matching: A fragment is trying to match against the `" + typename + "` type, but the type condition is `" + typeCondition + "`. Since GraphQL allows for interfaces `" + typeCondition + "` may be aninterface.\nA schema needs to be defined for this match to be deterministic, otherwise the fragment will be matched heuristically!"); | ||
return !getSelectionSet(node).some(function(node) { | ||
return !getSelectionSet(node).some((function(node) { | ||
if (!isFieldNode(node)) { | ||
@@ -205,3 +201,3 @@ return !1; | ||
return !ctx.store.hasField(joinKeys(entityKey, fieldKey)); | ||
}); | ||
})); | ||
}; | ||
@@ -267,3 +263,9 @@ | ||
}; | ||
var select = getSelectionSet(operation); | ||
var operationName = store.getRootKey(operation.operation); | ||
var ctx = { | ||
parentTypeName: operationName, | ||
parentKey: operationName, | ||
parentFieldKey: "", | ||
fieldName: "", | ||
variables: normalizeVariables(operation, request.variables), | ||
@@ -275,4 +277,2 @@ fragments: getFragments(request.query), | ||
}; | ||
var select = getSelectionSet(operation); | ||
var operationName = ctx.store.getRootKey(operation.operation); | ||
if (operationName === ctx.store.getRootKey("query")) { | ||
@@ -292,3 +292,10 @@ writeSelection(ctx, operationName, select, data); | ||
}; | ||
var mutationRootKey = store.getRootKey("mutation"); | ||
var operationName = store.getRootKey(operation.operation); | ||
"production" !== process.env.NODE_ENV && browser(operationName === mutationRootKey, "writeOptimistic(...) was called with an operation that is not a mutation.\nThis case is unsupported and should never occur."); | ||
var ctx = { | ||
parentTypeName: mutationRootKey, | ||
parentKey: mutationRootKey, | ||
parentFieldKey: "", | ||
fieldName: "", | ||
variables: normalizeVariables(operation, request.variables), | ||
@@ -299,7 +306,4 @@ fragments: getFragments(request.query), | ||
schemaPredicates: store.schemaPredicates, | ||
isOptimistic: !0 | ||
optimistic: !0 | ||
}; | ||
var mutationRootKey = ctx.store.getRootKey("mutation"); | ||
var operationName = ctx.store.getRootKey(operation.operation); | ||
"production" !== process.env.NODE_ENV && browser(operationName === mutationRootKey, "writeOptimistic(...) was called with an operation that is not a mutation.\nThis case is unsupported and should never occur."); | ||
var select = getSelectionSet(operation); | ||
@@ -314,2 +318,3 @@ var data = Object.create(null); | ||
if (void 0 !== resolver) { | ||
ctx.fieldName = fieldName; | ||
var fieldArgs = getFieldArguments(node, ctx.variables); | ||
@@ -349,2 +354,6 @@ var fieldSelect = getSelectionSet(node); | ||
var ctx = { | ||
parentTypeName: typename, | ||
parentKey: entityKey, | ||
parentFieldKey: "", | ||
fieldName: "", | ||
variables: variables || {}, | ||
@@ -382,3 +391,3 @@ fragments: fragments, | ||
if (void 0 === fieldValue) { | ||
"production" !== process.env.NODE_ENV && warning(!1, "Invalid value: The field at `" + fieldKey + "` is `undefined`, but the GraphQL query expects a " + (void 0 === node.selectionSet ? "scalar (number, boolean, etc)" : "selection set") + " for this field." + (ctx.isOptimistic ? "\nYour optimistic result may be missing a field!" : "")); | ||
"production" !== process.env.NODE_ENV && warning(!1, "Invalid value: The field at `" + fieldKey + "` is `undefined`, but the GraphQL query expects a " + (void 0 === node.selectionSet ? "scalar (number, boolean, etc)" : "selection set") + " for this field." + (ctx.optimistic ? "\nYour optimistic result may be missing a field!" : "")); | ||
continue; | ||
@@ -393,4 +402,6 @@ } else if (ctx.schemaPredicates && typename) { | ||
var fieldSelect = getSelectionSet(node); | ||
var connectionKey = joinKeys(entityKey, fieldName); | ||
var link = writeField(ctx, fieldKey, fieldSelect, fieldValue); | ||
store.writeLink(link, fieldKey); | ||
store.writeConnection(connectionKey, fieldKey, fieldArgs); | ||
store.removeRecord(fieldKey); | ||
@@ -421,3 +432,3 @@ } else { | ||
var typename = data.__typename; | ||
"production" !== process.env.NODE_ENV && warning(typename.endsWith("Connection") || typename.endsWith("Edge"), "Invalid key: The GraphQL query at the field at `" + parentFieldKey + "` has a selection set, but no key could be generated for the data at this field.\nYou have to request `id` or `_id` fields for all selection sets or create a custom `keys` config for `" + typename + "`.\nEntities without keys will be embedded directly on the parent entity. If this is intentional, create a `keys` config for `" + typename + "` that always returns null."); | ||
"production" !== process.env.NODE_ENV && warning(typename.endsWith("Connection") || typename.endsWith("Edge") || "PageInfo" === typename, "Invalid key: The GraphQL query at the field at `" + parentFieldKey + "` has a selection set, but no key could be generated for the data at this field.\nYou have to request `id` or `_id` fields for all selection sets or create a custom `keys` config for `" + typename + "`.\nEntities without keys will be embedded directly on the parent entity. If this is intentional, create a `keys` config for `" + typename + "` that always returns null."); | ||
} | ||
@@ -442,2 +453,7 @@ writeSelection(ctx, key, select, data); | ||
if (isRootField) { | ||
var fieldKey = joinKeys(typename, keyOfField(fieldName, fieldArgs)); | ||
ctx.parentTypeName = typename; | ||
ctx.parentKey = typename; | ||
ctx.parentFieldKey = fieldKey; | ||
ctx.fieldName = fieldName; | ||
var updater = ctx.store.updates[typename][fieldName]; | ||
@@ -529,3 +545,3 @@ if (void 0 !== updater) { | ||
var initStoreState = function(optimisticKey) { | ||
currentDependencies.current = new Set(); | ||
currentDependencies.current = new Set; | ||
currentOptimisticKey.current = optimisticKey; | ||
@@ -562,2 +578,3 @@ }; | ||
this.records = Pessimism.asMutable(Pessimism.make()); | ||
this.connections = Pessimism.asMutable(Pessimism.make()); | ||
this.links = Pessimism.asMutable(Pessimism.make()); | ||
@@ -629,2 +646,3 @@ this.resolvers = resolvers || {}; | ||
this.records = Pessimism.clearOptimistic(this.records, optimisticKey); | ||
this.connections = Pessimism.clearOptimistic(this.connections, optimisticKey); | ||
this.links = Pessimism.clearOptimistic(this.links, optimisticKey); | ||
@@ -667,2 +685,21 @@ }; | ||
Store.prototype.writeConnection = function writeConnection(key, linkKey, args) { | ||
if (null === args) { | ||
return this.connections; | ||
} | ||
var connections = Pessimism.get(this.connections, key); | ||
var connection = [ args, linkKey ]; | ||
if (void 0 === connections) { | ||
connections = [ connection ]; | ||
} else { | ||
for (var i = 0, l = connections.length; i < l; i++) { | ||
if (connections[i][1] === linkKey) { | ||
return this.connections; | ||
} | ||
} | ||
(connections = connections.slice()).push(connection); | ||
} | ||
return this.connections = mapSet(this.connections, key, connections); | ||
}; | ||
Store.prototype.resolveValueOrLink = function resolveValueOrLink(fieldKey) { | ||
@@ -678,3 +715,5 @@ var fieldValue = this.getRecord(fieldKey); | ||
Store.prototype.resolve = function resolve(entity, field, args) { | ||
if ("string" == typeof entity) { | ||
if (null === entity) { | ||
return null; | ||
} else if ("string" == typeof entity) { | ||
addDependency(entity); | ||
@@ -692,3 +731,17 @@ return this.resolveValueOrLink(joinKeys(entity, keyOfField(field, args))); | ||
Store.prototype.invalidateQuery = function invalidateQuery(dataQuery, variables) { | ||
Store.prototype.resolveConnections = function resolveConnections(entity, field) { | ||
var connections; | ||
if ("string" == typeof entity) { | ||
connections = Pessimism.get(this.connections, joinKeys(entity, field)); | ||
} else if (null !== entity) { | ||
var entityKey = this.keyOfEntity(entity); | ||
if (null !== entityKey) { | ||
addDependency(entityKey); | ||
connections = Pessimism.get(this.connections, joinKeys(entityKey, field)); | ||
} | ||
} | ||
return void 0 !== connections ? connections : []; | ||
}; | ||
Store.prototype.invalidateQuery = function invalidateQuery(query, variables) { | ||
!function(store, request) { | ||
@@ -705,6 +758,3 @@ initStoreState(0); | ||
clearStoreState(); | ||
}(this, { | ||
query: dataQuery, | ||
variables: variables | ||
}); | ||
}(this, urql.createRequest(query, variables)); | ||
}; | ||
@@ -748,2 +798,6 @@ | ||
var ctx = { | ||
parentTypeName: rootKey, | ||
parentKey: rootKey, | ||
parentFieldKey: "", | ||
fieldName: "", | ||
variables: normalizeVariables(operation, request.variables), | ||
@@ -756,3 +810,3 @@ fragments: getFragments(request.query), | ||
var data = input || Object.create(null); | ||
data = "Query" !== rootKey ? readRoot(ctx, rootKey, rootSelect, data) : readSelection(ctx, rootKey, rootSelect, data); | ||
data = rootKey !== ctx.store.getRootKey("query") ? readRoot(ctx, rootKey, rootSelect, data) : readSelection(ctx, rootKey, rootSelect, data); | ||
return { | ||
@@ -825,2 +879,6 @@ dependencies: getCurrentDependencies(), | ||
return readSelection({ | ||
parentTypeName: typename, | ||
parentKey: entityKey, | ||
parentFieldKey: "", | ||
fieldName: "", | ||
variables: variables || {}, | ||
@@ -866,2 +924,6 @@ fragments: fragments, | ||
if (void 0 !== resolvers && "function" == typeof resolvers[fieldName]) { | ||
ctx.parentTypeName = typename; | ||
ctx.parentKey = entityKey; | ||
ctx.parentFieldKey = fieldKey; | ||
ctx.fieldName = fieldName; | ||
if (void 0 !== fieldValue) { | ||
@@ -872,9 +934,7 @@ data[fieldAlias] = fieldValue; | ||
if (void 0 !== node.selectionSet) { | ||
resolverValue = resolveResolverResult(ctx, resolverValue, typename, fieldName, fieldKey, getSelectionSet(node), data[fieldAlias]); | ||
} | ||
var isNull = null == resolverValue; | ||
if (isNull && void 0 !== schemaPredicates) { | ||
dataFieldValue = void 0; | ||
var fieldSelect = getSelectionSet(node); | ||
var prevData = data[fieldAlias] || Object.create(null); | ||
dataFieldValue = resolveResolverResult(ctx, typename, fieldName, fieldKey, fieldSelect, prevData, resolverValue); | ||
} else { | ||
dataFieldValue = isNull ? null : resolverValue; | ||
dataFieldValue = void 0 === resolverValue && void 0 === schemaPredicates ? null : resolverValue; | ||
} | ||
@@ -884,6 +944,5 @@ } else if (void 0 === node.selectionSet) { | ||
} else { | ||
var fieldSelect = getSelectionSet(node); | ||
var link = store.getLink(fieldKey); | ||
if (void 0 !== link) { | ||
dataFieldValue = resolveLink(ctx, link, typename, fieldName, fieldSelect, data[fieldAlias]); | ||
dataFieldValue = resolveLink(ctx, link, typename, fieldName, getSelectionSet(node), data[fieldAlias]); | ||
} else if ("object" == typeof fieldValue && null !== fieldValue) { | ||
@@ -909,27 +968,83 @@ dataFieldValue = fieldValue; | ||
var resolveResolverResult = function(ctx, result, typename, fieldName, key, select, prevData) { | ||
var resolveResolverResult = function(ctx, typename, fieldName, key, select, prevData, result) { | ||
if (Array.isArray(result)) { | ||
var schemaPredicates = ctx.schemaPredicates; | ||
var isListNullable = void 0 !== schemaPredicates && schemaPredicates.isListNullable(typename, fieldName); | ||
var newResult = new Array(result.length); | ||
var isListNullable = void 0 === schemaPredicates || schemaPredicates.isListNullable(typename, fieldName); | ||
var data = new Array(result.length); | ||
for (var i = 0, l = result.length; i < l; i++) { | ||
var data = void 0 !== prevData ? prevData[i] : void 0; | ||
var childKey = joinKeys(key, "" + i); | ||
var childResult = resolveResolverResult(ctx, result[i], typename, fieldName, childKey, select, data); | ||
var innerResult = result[i]; | ||
var innerPrevData = void 0 !== prevData ? prevData[i] : void 0; | ||
var childResult = resolveResolverResult(ctx, typename, fieldName, joinKeys(key, "" + i), select, innerPrevData, innerResult); | ||
if (void 0 === childResult && !isListNullable) { | ||
return; | ||
} else { | ||
result[i] = void 0 !== childResult ? childResult : null; | ||
data[i] = void 0 !== childResult ? childResult : null; | ||
} | ||
} | ||
return newResult; | ||
} else if (null === result) { | ||
return data; | ||
} else if (null == result) { | ||
return null; | ||
} else if (isDataOrKey(result)) { | ||
var data$1 = void 0 === prevData ? Object.create(null) : prevData; | ||
var childKey$1 = ("string" == typeof result ? result : ctx.store.keyOfEntity(result)) || key; | ||
return readSelection(ctx, childKey$1, select, data$1); | ||
return "string" == typeof result ? readSelection(ctx, result, select, data$1) : function(ctx, key, select, data, result) { | ||
var store = ctx.store; | ||
var variables = ctx.variables; | ||
var schemaPredicates = ctx.schemaPredicates; | ||
var entityKey = store.keyOfEntity(result) || key; | ||
addDependency(entityKey); | ||
var resolvedTypename = result.__typename; | ||
var typename = store.getField(entityKey, "__typename") || resolvedTypename; | ||
if ("string" != typeof typename || resolvedTypename && typename !== resolvedTypename) { | ||
"production" !== process.env.NODE_ENV && warning(!1, "Invalid resolver value: The resolver at `" + entityKey + "` returned an invalid typename that could not be reconciled with the cache."); | ||
return; | ||
} | ||
data.__typename = typename; | ||
var iter = new SelectionIterator(typename, entityKey, select, ctx); | ||
var node; | ||
var hasFields = !1; | ||
var hasPartials = !1; | ||
while (void 0 !== (node = iter.next())) { | ||
var fieldName = getName(node); | ||
var fieldArgs = getFieldArguments(node, variables); | ||
var fieldAlias = getFieldAlias(node); | ||
var fieldKey = joinKeys(entityKey, keyOfField(fieldName, fieldArgs)); | ||
var fieldValue = store.getRecord(fieldKey); | ||
var resultValue = result[fieldName]; | ||
if ("production" !== process.env.NODE_ENV && schemaPredicates && typename) { | ||
schemaPredicates.isFieldAvailableOnType(typename, fieldName); | ||
} | ||
var dataFieldValue = void 0; | ||
if (void 0 !== resultValue && void 0 === node.selectionSet) { | ||
dataFieldValue = resultValue; | ||
} else if (void 0 === node.selectionSet) { | ||
dataFieldValue = fieldValue; | ||
} else if (void 0 !== resultValue) { | ||
dataFieldValue = resolveResolverResult(ctx, typename, fieldName, fieldKey, getSelectionSet(node), data[fieldAlias], resultValue); | ||
} else { | ||
var link = store.getLink(fieldKey); | ||
if (void 0 !== link) { | ||
dataFieldValue = resolveLink(ctx, link, typename, fieldName, getSelectionSet(node), data[fieldAlias]); | ||
} else if ("object" == typeof fieldValue && null !== fieldValue) { | ||
dataFieldValue = fieldValue; | ||
} | ||
} | ||
if (void 0 === dataFieldValue && void 0 !== schemaPredicates && schemaPredicates.isFieldNullable(typename, fieldName)) { | ||
hasPartials = !0; | ||
data[fieldAlias] = null; | ||
} else if (void 0 === dataFieldValue) { | ||
return; | ||
} else { | ||
hasFields = !0; | ||
data[fieldAlias] = dataFieldValue; | ||
} | ||
} | ||
if (hasPartials) { | ||
ctx.partial = !0; | ||
} | ||
return !hasFields ? void 0 : data; | ||
}(ctx, key, select, data$1, result); | ||
} else { | ||
"production" !== process.env.NODE_ENV && warning(!1, "Invalid resolver value: The field at `" + key + "` is a scalar (number, boolean, etc), but the GraphQL query expects a selection set for this field."); | ||
return; | ||
} | ||
"production" !== process.env.NODE_ENV && warning(!1, "Invalid resolver value: The resolver at `" + key + "` returned a scalar (number, boolean, etc), but the GraphQL query expects a selection set for this field.\nIf necessary, use Cache.resolve() to resolve a link or entity from the cache."); | ||
return; | ||
}; | ||
@@ -960,3 +1075,3 @@ | ||
var isDataOrKey = function(x) { | ||
return "string" == typeof x || "object" == typeof x && null !== x && "string" == typeof x.__typename; | ||
return "string" == typeof x || "object" == typeof x && "string" == typeof x.__typename; | ||
}; | ||
@@ -1028,5 +1143,5 @@ | ||
var addCacheOutcome = function(op, outcome) { | ||
return _extends({}, op, { | ||
context: _extends({}, op.context, { | ||
meta: _extends({}, op.context.meta, { | ||
return _extends(_extends({}, op), { | ||
context: _extends(_extends({}, op.context), { | ||
meta: _extends(_extends({}, op.context.meta), { | ||
cacheOutcome: outcome | ||
@@ -1039,3 +1154,3 @@ }) | ||
var addTypeNames = function(op) { | ||
return _extends({}, op, { | ||
return _extends(_extends({}, op), { | ||
query: urql.formatDocument(op.query) | ||
@@ -1059,4 +1174,4 @@ }); | ||
var toRequestPolicy = function(operation, requestPolicy) { | ||
return _extends({}, operation, { | ||
context: _extends({}, operation.context, { | ||
return _extends(_extends({}, operation), { | ||
context: _extends(_extends({}, operation.context), { | ||
requestPolicy: requestPolicy | ||
@@ -1097,19 +1212,21 @@ }) | ||
var store = new Store(opts.schema ? new SchemaPredicates(opts.schema) : void 0, opts.resolvers, opts.updates, opts.optimistic, opts.keys); | ||
var optimisticKeys = new Set(); | ||
var ops = new Map(); | ||
var optimisticKeys = new Set; | ||
var ops = new Map; | ||
var deps = Object.create(null); | ||
var processDependencies = function(triggerOp, dependencies) { | ||
var pendingOperations = new Set(); | ||
function _ref(key) { | ||
return pendingOperations.add(key); | ||
var collectPendingOperations = function(pendingOperations, dependencies) { | ||
if (void 0 !== dependencies) { | ||
dependencies.forEach((function _ref(dep) { | ||
var keys = deps[dep]; | ||
if (void 0 !== keys) { | ||
deps[dep] = []; | ||
for (var i = 0, l = keys.length; i < l; i++) { | ||
pendingOperations.add(keys[i]); | ||
} | ||
} | ||
})); | ||
} | ||
dependencies.forEach(function(dep) { | ||
var keys = deps[dep]; | ||
if (void 0 !== keys) { | ||
deps[dep] = []; | ||
keys.forEach(_ref); | ||
} | ||
}); | ||
pendingOperations.forEach(function(key) { | ||
if (key !== triggerOp.key) { | ||
}; | ||
var executePendingOperations = function(operation, pendingOperations) { | ||
pendingOperations.forEach((function(key) { | ||
if (key !== operation.key) { | ||
var op = ops.get(key); | ||
@@ -1122,3 +1239,3 @@ if (void 0 !== op) { | ||
} | ||
}); | ||
})); | ||
}; | ||
@@ -1133,3 +1250,5 @@ var optimisticUpdate = function(operation) { | ||
optimisticKeys.add(key); | ||
processDependencies(operation, dependencies); | ||
var pendingOperations = new Set; | ||
collectPendingOperations(pendingOperations, dependencies); | ||
executePendingOperations(operation, pendingOperations); | ||
} | ||
@@ -1140,3 +1259,3 @@ } | ||
var updateDependencies = function(op, dependencies) { | ||
dependencies.forEach(function(dep) { | ||
dependencies.forEach((function(dep) { | ||
(deps[dep] || (deps[dep] = [])).push(op.key); | ||
@@ -1146,3 +1265,3 @@ if (!ops.has(op.key)) { | ||
} | ||
}); | ||
})); | ||
}; | ||
@@ -1189,5 +1308,8 @@ var operationResultFromCache = function(operation) { | ||
} | ||
if (void 0 !== writeDependencies) { | ||
processDependencies(result.operation, writeDependencies); | ||
var pendingOperations = new Set; | ||
collectPendingOperations(pendingOperations, writeDependencies); | ||
if (isQuery) { | ||
collectPendingOperations(pendingOperations, queryDependencies); | ||
} | ||
executePendingOperations(result.operation, pendingOperations); | ||
if (isQuery && void 0 !== queryDependencies) { | ||
@@ -1194,0 +1316,0 @@ updateDependencies(result.operation, queryDependencies); |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("graphql"),r=require("urql"),n=require("pessimism"),i=(e=require("fast-json-stable-stringify"))&&"object"==typeof e&&"default"in e?e.default:e,o=require("wonka");function a(){return(a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}var u=function(e){return e.name.value},s=function(e){return e.typeCondition.name.value},c=function(e){return void 0!==e.alias?e.alias.value:u(e)},l=function(e){return void 0!==e.selectionSet?e.selectionSet.selections:[]},f=function(e){var t=e.typeCondition;return void 0!==t?u(t):null},v=function(e){return e.kind===t.Kind.FIELD},p=function(e){return e.kind===t.Kind.INLINE_FRAGMENT},d=function(e,r){if(void 0===e.arguments||0===e.arguments.length)return null;for(var n=Object.create(null),i=0,o=0,a=e.arguments.length;o<a;o++){var s=e.arguments[o],c=t.valueFromASTUntyped(s.value,r);null!=c&&(n[u(s)]=c,i++)}return i>0?n:null},y=function(e,r){if(void 0===e.variableDefinitions)return{};var n=r||{};return e.variableDefinitions.reduce(function(e,r){var i=u(r.variable),o=n[i];if(void 0===o){if(void 0===r.defaultValue)return e;o=t.valueFromASTUntyped(r.defaultValue,n)}return e[i]=o,e},Object.create(null))},h=function(e){return e.kind===t.Kind.FRAGMENT_DEFINITION};function m(e){return e.kind===t.Kind.OPERATION_DEFINITION}var g=function(e){return e.definitions.find(m)};function b(e,t){return e[u(t)]=t,e}var k=function(e){return e.definitions.filter(h).reduce(b,{})},O=function(e,r){if(void 0===e.directives)return!0;for(var n=e.directives,i=0,o=n.length;i<o;i++){var a=n[i],s=u(a),c="include"===s;if(c||"skip"===s){var l=a.arguments?a.arguments[0]:null;if(l&&"if"===u(l)){var f=t.valueFromASTUntyped(l.value,r);if("boolean"==typeof f||null===f)return c?!!f:!f}}}return!0},_=function(e,t){return t?e+"("+i(t)+")":e},x=function(e,t){return e+"."+t},w=function(e,t,r,n){return!(!t||t!==f(e)&&l(e).some(function(e){if(!v(e))return!1;var t=u(e),i=d(e,n.variables),o=_(t,i);return!n.store.hasField(x(r,o))}))},q=function(e,t,r,n){this.typename=e,this.entityKey=t,this.context=n,this.indexStack=[0],this.selectionStack=[r]};q.prototype.next=function(){for(;0!==this.indexStack.length;){var e=this.indexStack[this.indexStack.length-1]++,t=this.selectionStack[this.selectionStack.length-1];if(e>=t.length)this.indexStack.pop(),this.selectionStack.pop();else{var r=t[e];if(O(r,this.context.variables)){if(v(r)){if("__typename"===u(r))continue;return r}var n=p(r)?r:this.context.fragments[u(r)];void 0!==n&&(void 0!==this.context.schemaPredicates?this.context.schemaPredicates.isInterfaceOfType(f(n),this.typename):w(n,this.typename,this.entityKey,this.context))&&(this.indexStack.push(0),this.selectionStack.push(l(n)))}}}};var S=function(e){return Array.isArray(e)?e.some(S):"object"!=typeof e||null!==e&&"string"!=typeof e.__typename},R=function(e,t,r){I(0);var n=A(e,t,r);return Q(),n},A=function(e,t,r){var n=g(t.query),i={dependencies:D()},o={variables:y(n,t.variables),fragments:k(t.query),result:i,store:e,schemaPredicates:e.schemaPredicates},a=l(n),u=o.store.getRootKey(n.operation);return u===o.store.getRootKey("query")?N(o,u,a,r):j(o,u,a,r),i},F=function(e,t,r){I(r);for(var n,i=g(t.query),o={dependencies:D()},a={variables:y(i,t.variables),fragments:k(t.query),result:o,store:e,schemaPredicates:e.schemaPredicates,isOptimistic:!0},s=a.store.getRootKey("mutation"),c=a.store.getRootKey(i.operation),f=l(i),v=Object.create(null),p=new q(c,c,f,a);void 0!==(n=p.next());)if(void 0!==n.selectionSet){var h=u(n),m=a.store.optimisticMutations[h];if(void 0!==m){var b=d(n,a.variables),O=l(n),_=m(b||{},a.store,a);S(_)||E(a,_,O),v[h]=_;var x=a.store.updates[s][h];void 0!==x&&x(v,b||{},a.store,a)}}return Q(),o},P=function(e,t,r,n){var i=k(t),o=i[Object.keys(i)[0]];if(void 0!==o){var u=l(o),c=a({__typename:s(o)},r),f=e.keyOfEntity(c);if(f){var v={variables:n||{},fragments:i,result:{dependencies:D()},store:e,schemaPredicates:e.schemaPredicates};N(v,f,u,c)}}},N=function(e,t,r,n){var i=e.store,o=e.variables,a=t===e.store.getRootKey("query"),s=n.__typename;a||V(t),i.writeField(a?t:s,t,"__typename");for(var f,v=new q(s,t,r,e);void 0!==(f=v.next());){var p=u(f),y=d(f,o),h=x(t,_(p,y)),m=n[c(f)];if(a&&V(h),void 0===f.selectionSet)i.writeRecord(m,h);else if(S(m))i.writeRecord(m,h);else{var g=l(f),b=T(e,h,g,m);i.writeLink(b,h),i.removeRecord(h)}}},T=function(e,t,r,n){if(Array.isArray(n)){for(var i=new Array(n.length),o=0,a=n.length;o<a;o++){var u=n[o],s=x(t,""+o),c=T(e,s,r,u);i[o]=c}return i}if(null===n)return null;var l=e.store.keyOfEntity(n),f=null!==l?l:t;return N(e,f,r,n),f},j=function(e,t,r,n){for(var i,o=t===e.store.getRootKey("mutation")||t===e.store.getRootKey("subscription"),a=new q(t,t,r,e);void 0!==(i=a.next());){var s=u(i),f=c(i),v=d(i,e.variables),p=n[f];if(void 0!==i.selectionSet&&null!==p&&!S(p)){var y=l(i);E(e,p,y)}if(o){var h=e.store.updates[t][s];void 0!==h&&h(n,v||{},e.store,e)}}},E=function(e,t,r){if(Array.isArray(t)){for(var n=new Array(t.length),i=0,o=t.length;i<o;i++)n[i]=E(e,t[i],r);return n}if(null!==t){var a=e.store.keyOfEntity(t);null!==a?N(e,a,r,t):j(e,t.__typename,r,t)}},L=function(e,t,r){var n,i=e.store,o=e.variables,a="Query"===t;if(a)n=t;else{if(V(t),"string"!=typeof(n=i.getField(t,"__typename")))return;i.removeRecord(x(t,_("__typename")))}for(var s,c=new q(n,t,r,e);void 0!==(s=c.next());){var f=u(s),v=d(s,o),p=x(t,_(f,v));if(a&&V(p),void 0===s.selectionSet)i.removeRecord(p);else{var y=l(s),h=i.getLink(p);if(i.removeLink(p),void 0===h)void 0!==i.getRecord(p)&&i.removeRecord(p);else if(Array.isArray(h))for(var m=0,g=h.length;m<g;m++){var b=h[m];null!==b&&L(e,b,y)}else null!==h&&L(e,h,y)}}},K={current:null},M={current:null},I=function(e){K.current=new Set,M.current=e},Q=function(){K.current=null,M.current=null},D=function(){return K.current},V=function(e){K.current.add(e)},C=function(e,t,r){return n.setOptimistic(e,t,r,M.current||0)},U=function(e,t){var r=M.current||0;return r?n.setOptimistic(e,t,void 0,r):n.remove(e,t)},G=function(e,t,r,i,o){var a;if(this.records=n.asMutable(n.make()),this.links=n.asMutable(n.make()),this.resolvers=t||{},this.optimisticMutations=i||{},this.keys=o||{},this.schemaPredicates=e,this.updates={Mutation:r&&r.Mutation||{},Subscription:r&&r.Subscription||{}},e){var u=e.schema,s=u.getQueryType(),c=u.getMutationType(),l=u.getSubscriptionType(),f=s?s.name:"Query",v=c?c.name:"Mutation",p=l?l.name:"Subscription";this.rootFields={query:f,mutation:v,subscription:p},this.rootNames=((a={})[f]="query",a[v]="mutation",a[p]="subscription",a)}else this.rootFields={query:"Query",mutation:"Mutation",subscription:"Subscription"},this.rootNames={Query:"query",Mutation:"mutation",Subscription:"subscription"}};G.prototype.getRootKey=function(e){return this.rootFields[e]},G.prototype.keyOfEntity=function(e){var t,r=e.__typename,n=e.id,i=e._id;if(!r)return null;if(this.rootNames[r])return this.rootNames[r];if(this.keys[r])t=this.keys[r](e);else if(null!=n)t=""+n;else{if(null==i)return null;t=""+i}return t?r+":"+t:null},G.prototype.clearOptimistic=function(e){this.records=n.clearOptimistic(this.records,e),this.links=n.clearOptimistic(this.links,e)},G.prototype.getRecord=function(e){return n.get(this.records,e)},G.prototype.removeRecord=function(e){return this.records=U(this.records,e)},G.prototype.writeRecord=function(e,t){return this.records=C(this.records,t,e)},G.prototype.getField=function(e,t,r){var n=x(e,_(t,r));return this.getRecord(n)},G.prototype.writeField=function(e,t,r,n){var i=x(t,_(r,n));return this.records=C(this.records,i,e)},G.prototype.getLink=function(e){return n.get(this.links,e)},G.prototype.removeLink=function(e){return this.links=U(this.links,e)},G.prototype.writeLink=function(e,t){return this.links=C(this.links,t,e)},G.prototype.resolveValueOrLink=function(e){var t=this.getRecord(e);return void 0!==t?t:this.getLink(e)||null},G.prototype.resolve=function(e,t,r){if("string"==typeof e)return V(e),this.resolveValueOrLink(x(e,_(t,r)));var n=this.keyOfEntity(e);return null===n?null:(V(n),this.resolveValueOrLink(x(n,_(t,r))))},G.prototype.invalidateQuery=function(e,t){!function(e,t){I(0);var r=g(t.query),n={variables:y(r,t.variables),fragments:k(t.query),store:e,schemaPredicates:e.schemaPredicates};L(n,n.store.getRootKey("query"),l(r)),Q()}(this,{query:e,variables:t})},G.prototype.hasField=function(e){return void 0!==this.getRecord(e)||void 0!==this.getLink(e)},G.prototype.updateQuery=function(e,t){var n=r.createRequest(e.query,e.variables),i=t(this.readQuery(n));null!==i&&A(this,n,i)},G.prototype.readQuery=function(e){return B(this,r.createRequest(e.query,e.variables)).data},G.prototype.readFragment=function(e,t,r){return W(this,e,t,r)},G.prototype.writeFragment=function(e,t,r){P(this,e,t,r)};var z=function(e,t,r){I(0);var n=B(e,t,r);return Q(),n},B=function(e,t,r){var n=g(t.query),i=e.getRootKey(n.operation),o=l(n),a={variables:y(n,t.variables),fragments:k(t.query),partial:!1,store:e,schemaPredicates:e.schemaPredicates},u=r||Object.create(null);return u="Query"!==i?H(a,i,o,u):X(a,i,o,u),{dependencies:D(),partial:void 0!==u&&a.partial,data:void 0===u?null:u}},H=function(e,t,r,n){if("string"!=typeof n.__typename)return n;var i=Object.create(null);i.__typename=n.__typename;for(var o,a=new q(t,t,r,e);void 0!==(o=a.next());){var u=c(o),s=n[u];i[u]=void 0===o.selectionSet||null===s||S(s)?s:J(e,l(o),s)}return i},J=function(e,t,r){if(Array.isArray(r)){for(var n=new Array(r.length),i=0,o=r.length;i<o;i++)n[i]=J(e,t,r[i]);return n}if(null===r)return null;var a=e.store.keyOfEntity(r);if(null!==a){var u=Object.create(null),s=X(e,a,t,u);return void 0===s?null:s}return H(e,r.__typename,t,r)},W=function(e,t,r,n){var i=k(t),o=i[Object.keys(i)[0]];if(void 0===o)return null;var u=l(o),c=s(o);"string"==typeof r||r.__typename||(r.__typename=c);var f="string"!=typeof r?e.keyOfEntity(a({__typename:c},r)):r;return f&&X({variables:n||{},fragments:i,partial:!1,store:e,schemaPredicates:e.schemaPredicates},f,u,Object.create(null))||null},X=function(e,t,r,n){var i=e.store,o=e.variables,a=e.schemaPredicates,s=t===i.getRootKey("query");s||V(t);var f=s?t:i.getField(t,"__typename");if("string"==typeof f){n.__typename=f;for(var v,p=new q(f,t,r,e),y=!1,h=!1;void 0!==(v=p.next());){var m=u(v),g=d(v,o),b=c(v),k=x(t,_(m,g)),O=i.getRecord(k);s&&V(k);var w=void 0,S=i.resolvers[f];if(void 0!==S&&"function"==typeof S[m]){void 0!==O&&(n[b]=O);var R=S[m](n,g||{},i,e);void 0!==v.selectionSet&&(R=Y(e,R,f,m,k,l(v),n[b]));var A=null==R;w=A&&void 0!==a?void 0:A?null:R}else if(void 0===v.selectionSet)w=O;else{var F=l(v),P=i.getLink(k);void 0!==P?w=Z(e,P,f,m,F,n[b]):"object"==typeof O&&null!==O&&(w=O)}if(void 0===w&&void 0!==a&&a.isFieldNullable(f,m))h=!0,n[b]=null;else{if(void 0===w)return;y=!0,n[b]=w}}return h&&(e.partial=!0),s&&h&&!y?void 0:n}},Y=function(e,t,r,n,i,o,a){if(Array.isArray(t)){for(var u=e.schemaPredicates,s=void 0!==u&&u.isListNullable(r,n),c=new Array(t.length),l=0,f=t.length;l<f;l++){var v=void 0!==a?a[l]:void 0,p=x(i,""+l),d=Y(e,t[l],r,n,p,o,v);if(void 0===d&&!s)return;t[l]=void 0!==d?d:null}return c}if(null===t)return null;if($(t)){var y=void 0===a?Object.create(null):a,h=("string"==typeof t?t:e.store.keyOfEntity(t))||i;return X(e,h,o,y)}},Z=function(e,t,r,n,i,o){if(Array.isArray(t)){for(var a=e.schemaPredicates,u=void 0!==a&&a.isListNullable(r,n),s=new Array(t.length),c=0,l=t.length;c<l;c++){var f=Z(e,t[c],r,n,i,void 0!==o?o[c]:void 0);if(void 0===f&&!u)return;s[c]=void 0!==f?f:null}return s}if(null===t)return null;var v=void 0===o?Object.create(null):o;return X(e,t,i,v)},$=function(e){return"string"==typeof e||"object"==typeof e&&null!==e&&"string"==typeof e.__typename},ee=function(e){this.schema=t.buildClientSchema(e)};ee.prototype.isFieldNullable=function(e,r){var n=te(this.schema,e,r);return void 0!==n&&t.isNullableType(n.type)},ee.prototype.isListNullable=function(e,r){var n=te(this.schema,e,r);if(void 0===n)return!1;var i=t.isNonNullType(n.type)?n.type.ofType:n.type;return t.isListType(i)&&t.isNullableType(i.ofType)},ee.prototype.isFieldAvailableOnType=function(e,t){return!!te(this.schema,e,t)},ee.prototype.isInterfaceOfType=function(e,t){if(!t||!e)return!1;if(t===e)return!0;var r=this.schema.getType(e),n=this.schema.getType(t);return this.schema.isPossibleType(r,n)};var te=function(e,t,r){var n=e.getType(t);if(void 0!==n){var i=n.getFields()[r];if(void 0!==i)return i}},re=function(e,t){return a({},e,{context:a({},e.context,{meta:a({},e.context.meta,{cacheOutcome:t})})})},ne=function(e){return a({},e,{query:r.formatDocument(e.query)})},ie=function(e){return e.context.requestPolicy},oe=function(e){return"query"===e.operationName},ae=function(e){var t=ie(e);return oe(e)&&"network-only"!==t},ue=function(e,t){return a({},e,{context:a({},e.context,{requestPolicy:t})})};function se(e){return ae(e)}function ce(e){return"miss"===e.outcome}function le(e){return re(e.operation,e.outcome)}function fe(e){return"miss"!==e.outcome}function ve(e){return!ae(e)}exports.Store=G,exports.cacheExchange=function(e){return function(t){var r=t.forward,n=t.client;e||(e={});var i=new G(e.schema?new ee(e.schema):void 0,e.resolvers,e.updates,e.optimistic,e.keys),a=new Set,u=new Map,s=Object.create(null),c=function(e,t){var r=new Set;function i(e){return r.add(e)}t.forEach(function(e){var t=s[e];void 0!==t&&(s[e]=[],t.forEach(i))}),r.forEach(function(t){if(t!==e.key){var r=u.get(t);if(void 0!==r){u.delete(t);var i=ue(r,"cache-first");n.reexecuteOperation(i)}}})},l=function(e){if(o=ie(n=e),function(e){return"mutation"===e.operationName}(n)&&"network-only"!==o){var t=e.key,r=F(i,e,t).dependencies;0!==r.size&&(a.add(t),c(e,r))}var n,o},f=function(e,t){t.forEach(function(t){(s[t]||(s[t]=[])).push(e.key),u.has(e.key)||u.set(e.key,"network-only"===e.context.requestPolicy?ue(e,"cache-and-network"):e)})},v=function(e){var t,r=ie(e),n=z(i,e),o=n.data,a=n.partial;return null===o?t="miss":(f(e,n.dependencies),t=a&&"cache-only"!==r?"partial":"hit"),{outcome:t,operation:e,data:o}},p=function(e){var t,r,n=e.operation,o=e.error,u=e.extensions,s=oe(n),l=e.data,v=n.key;if(a.has(v)&&(a.delete(v),i.clearOptimistic(v)),null!=l)if(t=R(i,n,l).dependencies,s){var p=z(i,n);l=p.data,r=p.dependencies}else l=z(i,n,l).data;return void 0!==t&&c(e.operation,t),s&&void 0!==r&&f(e.operation,r),{data:l,error:o,extensions:u,operation:n}};function d(e){var t=e.operation,r=e.outcome,i=ie(t);if("cache-and-network"===i||"cache-first"===i&&"partial"===r){var o=ue(t,"network-only");n.reexecuteOperation(o)}return{operation:re(t,r),data:e.data,error:e.error,extensions:e.extensions}}return function(e){var t=o.pipe(e,o.map(ne),o.tap(l),o.share),n=o.pipe(t,o.filter(se),o.map(v),o.share),i=o.pipe(n,o.filter(ce),o.map(le)),a=o.pipe(n,o.filter(fe),o.map(d)),u=o.pipe(r(o.merge([o.pipe(t,o.filter(ve)),i])),o.map(p));return o.merge([u,a])}}},exports.query=z,exports.read=B,exports.write=R,exports.writeFragment=P,exports.writeOptimistic=F; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("graphql"),t=require("urql"),r=require("pessimism"),n=require("wonka");function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}var o=function(e){return e.name.value},a=function(e){return e.typeCondition.name.value},s=function(e){return void 0!==e.alias?e.alias.value:o(e)},u=function(e){return void 0!==e.selectionSet?e.selectionSet.selections:[]},c=function(e){var t=e.typeCondition;return void 0!==t?o(t):null},l=function(t){return t.kind===e.Kind.FIELD},f=function(t){return t.kind===e.Kind.INLINE_FRAGMENT},p=function(t,r){if(void 0===t.arguments||0===t.arguments.length)return null;for(var n=Object.create(null),i=0,a=0,s=t.arguments.length;a<s;a++){var u=t.arguments[a],c=e.valueFromASTUntyped(u.value,r);null!=c&&(n[o(u)]=c,i++)}return i>0?n:null},v=function(t,r){if(void 0===t.variableDefinitions)return{};var n=r||{};return t.variableDefinitions.reduce((function(t,r){var i=o(r.variable),a=n[i];if(void 0===a){if(void 0===r.defaultValue)return t;a=e.valueFromASTUntyped(r.defaultValue,n)}return t[i]=a,t}),Object.create(null))},d=function(t){return t.kind===e.Kind.FRAGMENT_DEFINITION};function y(t){return t.kind===e.Kind.OPERATION_DEFINITION}var h=function(e){return e.definitions.find(y)};function m(e,t){return e[o(t)]=t,e}var g=function(e){return e.definitions.filter(d).reduce(m,{})},b=function(t,r){if(void 0===t.directives)return!0;for(var n=t.directives,i=0,a=n.length;i<a;i++){var s=n[i],u=o(s),c="include"===u;if(c||"skip"===u){var l=s.arguments?s.arguments[0]:null;if(l&&"if"===o(l)){var f=e.valueFromASTUntyped(l.value,r);if("boolean"==typeof f||null===f)return c?!!f:!f}}}return!0},k=function(e,r){return r?e+"("+t.stringifyVariables(r)+")":e},_=function(e,t){return e+"."+t},O=function(e,t,r,n){return!(!t||t!==c(e)&&u(e).some((function(e){if(!l(e))return!1;var t=o(e),i=p(e,n.variables),a=k(t,i);return!n.store.hasField(_(r,a))})))},x=function(e,t,r,n){this.typename=e,this.entityKey=t,this.context=n,this.indexStack=[0],this.selectionStack=[r]};x.prototype.next=function(){for(;0!==this.indexStack.length;){var e=this.indexStack[this.indexStack.length-1]++,t=this.selectionStack[this.selectionStack.length-1];if(e>=t.length)this.indexStack.pop(),this.selectionStack.pop();else{var r=t[e];if(b(r,this.context.variables)){if(l(r)){if("__typename"===o(r))continue;return r}var n=f(r)?r:this.context.fragments[o(r)];void 0!==n&&(void 0!==this.context.schemaPredicates?this.context.schemaPredicates.isInterfaceOfType(c(n),this.typename):O(n,this.typename,this.entityKey,this.context))&&(this.indexStack.push(0),this.selectionStack.push(u(n)))}}}};var w=function(e){return Array.isArray(e)?e.some(w):"object"!=typeof e||null!==e&&"string"!=typeof e.__typename},N=function(e,t,r){L(0);var n=S(e,t,r);return M(),n},S=function(e,t,r){var n=h(t.query),i={dependencies:I()},o=u(n),a=e.getRootKey(n.operation),s={parentTypeName:a,parentKey:a,parentFieldKey:"",fieldName:"",variables:v(n,t.variables),fragments:g(t.query),result:i,store:e,schemaPredicates:e.schemaPredicates};return a===s.store.getRootKey("query")?R(s,a,o,r):T(s,a,o,r),i},q=function(e,t,r){L(r);for(var n,i=h(t.query),a={dependencies:I()},s=e.getRootKey("mutation"),c=e.getRootKey(i.operation),l={parentTypeName:s,parentKey:s,parentFieldKey:"",fieldName:"",variables:v(i,t.variables),fragments:g(t.query),result:a,store:e,schemaPredicates:e.schemaPredicates,optimistic:!0},f=u(i),d=Object.create(null),y=new x(c,c,f,l);void 0!==(n=y.next());)if(void 0!==n.selectionSet){var m=o(n),b=l.store.optimisticMutations[m];if(void 0!==b){l.fieldName=m;var k=p(n,l.variables),_=u(n),O=b(k||{},l.store,l);w(O)||A(l,O,_),d[m]=O;var N=l.store.updates[s][m];void 0!==N&&N(d,k||{},l.store,l)}}return M(),a},F=function(e,t,r,n){var o=g(t),s=o[Object.keys(o)[0]];if(void 0!==s){var c=u(s),l=a(s),f=i({__typename:l},r),p=e.keyOfEntity(f);if(p){var v={parentTypeName:l,parentKey:p,parentFieldKey:"",fieldName:"",variables:n||{},fragments:o,result:{dependencies:I()},store:e,schemaPredicates:e.schemaPredicates};R(v,p,c,f)}}},R=function(e,t,r,n){var i=e.store,a=e.variables,c=t===e.store.getRootKey("query"),l=n.__typename;c||Q(t),i.writeField(c?t:l,t,"__typename");for(var f,v=new x(l,t,r,e);void 0!==(f=v.next());){var d=o(f),y=p(f,a),h=_(t,k(d,y)),m=n[s(f)];if(c&&Q(h),void 0===f.selectionSet)i.writeRecord(m,h);else if(w(m))i.writeRecord(m,h);else{var g=u(f),b=_(t,d),O=K(e,h,g,m);i.writeLink(O,h),i.writeConnection(b,h,y),i.removeRecord(h)}}},K=function(e,t,r,n){if(Array.isArray(n)){for(var i=new Array(n.length),o=0,a=n.length;o<a;o++){var s=n[o],u=_(t,""+o),c=K(e,u,r,s);i[o]=c}return i}if(null===n)return null;var l=e.store.keyOfEntity(n),f=null!==l?l:t;return R(e,f,r,n),f},T=function(e,t,r,n){for(var i,a=t===e.store.getRootKey("mutation")||t===e.store.getRootKey("subscription"),c=new x(t,t,r,e);void 0!==(i=c.next());){var l=o(i),f=s(i),v=p(i,e.variables),d=n[f];if(void 0!==i.selectionSet&&null!==d&&!w(d)){var y=u(i);A(e,d,y)}if(a){var h=_(t,k(l,v));e.parentTypeName=t,e.parentKey=t,e.parentFieldKey=h,e.fieldName=l;var m=e.store.updates[t][l];void 0!==m&&m(n,v||{},e.store,e)}}},A=function(e,t,r){if(Array.isArray(t)){for(var n=new Array(t.length),i=0,o=t.length;i<o;i++)n[i]=A(e,t[i],r);return n}if(null!==t){var a=e.store.keyOfEntity(t);null!==a?R(e,a,r,t):T(e,t.__typename,r,t)}},P=function(e,t,r){var n,i=e.store,a=e.variables,s="Query"===t;if(s)n=t;else{if(Q(t),"string"!=typeof(n=i.getField(t,"__typename")))return;i.removeRecord(_(t,k("__typename")))}for(var c,l=new x(n,t,r,e);void 0!==(c=l.next());){var f=o(c),v=p(c,a),d=_(t,k(f,v));if(s&&Q(d),void 0===c.selectionSet)i.removeRecord(d);else{var y=u(c),h=i.getLink(d);if(i.removeLink(d),void 0===h)void 0!==i.getRecord(d)&&i.removeRecord(d);else if(Array.isArray(h))for(var m=0,g=h.length;m<g;m++){var b=h[m];null!==b&&P(e,b,y)}else null!==h&&P(e,h,y)}}},j={current:null},E={current:null},L=function(e){j.current=new Set,E.current=e},M=function(){j.current=null,E.current=null},I=function(){return j.current},Q=function(e){j.current.add(e)},C=function(e,t,n){return r.setOptimistic(e,t,n,E.current||0)},D=function(e,t){var n=E.current||0;return n?r.setOptimistic(e,t,void 0,n):r.remove(e,t)},V=function(e,t,n,i,o){var a;if(this.records=r.asMutable(r.make()),this.connections=r.asMutable(r.make()),this.links=r.asMutable(r.make()),this.resolvers=t||{},this.optimisticMutations=i||{},this.keys=o||{},this.schemaPredicates=e,this.updates={Mutation:n&&n.Mutation||{},Subscription:n&&n.Subscription||{}},e){var s=e.schema,u=s.getQueryType(),c=s.getMutationType(),l=s.getSubscriptionType(),f=u?u.name:"Query",p=c?c.name:"Mutation",v=l?l.name:"Subscription";this.rootFields={query:f,mutation:p,subscription:v},this.rootNames=((a={})[f]="query",a[p]="mutation",a[v]="subscription",a)}else this.rootFields={query:"Query",mutation:"Mutation",subscription:"Subscription"},this.rootNames={Query:"query",Mutation:"mutation",Subscription:"subscription"}};V.prototype.getRootKey=function(e){return this.rootFields[e]},V.prototype.keyOfEntity=function(e){var t,r=e.__typename,n=e.id,i=e._id;if(!r)return null;if(this.rootNames[r])return this.rootNames[r];if(this.keys[r])t=this.keys[r](e);else if(null!=n)t=""+n;else{if(null==i)return null;t=""+i}return t?r+":"+t:null},V.prototype.clearOptimistic=function(e){this.records=r.clearOptimistic(this.records,e),this.connections=r.clearOptimistic(this.connections,e),this.links=r.clearOptimistic(this.links,e)},V.prototype.getRecord=function(e){return r.get(this.records,e)},V.prototype.removeRecord=function(e){return this.records=D(this.records,e)},V.prototype.writeRecord=function(e,t){return this.records=C(this.records,t,e)},V.prototype.getField=function(e,t,r){var n=_(e,k(t,r));return this.getRecord(n)},V.prototype.writeField=function(e,t,r,n){var i=_(t,k(r,n));return this.records=C(this.records,i,e)},V.prototype.getLink=function(e){return r.get(this.links,e)},V.prototype.removeLink=function(e){return this.links=D(this.links,e)},V.prototype.writeLink=function(e,t){return this.links=C(this.links,t,e)},V.prototype.writeConnection=function(e,t,n){if(null===n)return this.connections;var i=r.get(this.connections,e),o=[n,t];if(void 0===i)i=[o];else{for(var a=0,s=i.length;a<s;a++)if(i[a][1]===t)return this.connections;(i=i.slice()).push(o)}return this.connections=C(this.connections,e,i)},V.prototype.resolveValueOrLink=function(e){var t=this.getRecord(e);return void 0!==t?t:this.getLink(e)||null},V.prototype.resolve=function(e,t,r){if(null===e)return null;if("string"==typeof e)return Q(e),this.resolveValueOrLink(_(e,k(t,r)));var n=this.keyOfEntity(e);return null===n?null:(Q(n),this.resolveValueOrLink(_(n,k(t,r))))},V.prototype.resolveConnections=function(e,t){var n;if("string"==typeof e)n=r.get(this.connections,_(e,t));else if(null!==e){var i=this.keyOfEntity(e);null!==i&&(Q(i),n=r.get(this.connections,_(i,t)))}return void 0!==n?n:[]},V.prototype.invalidateQuery=function(e,r){!function(e,t){L(0);var r=h(t.query),n={variables:v(r,t.variables),fragments:g(t.query),store:e,schemaPredicates:e.schemaPredicates};P(n,n.store.getRootKey("query"),u(r)),M()}(this,t.createRequest(e,r))},V.prototype.hasField=function(e){return void 0!==this.getRecord(e)||void 0!==this.getLink(e)},V.prototype.updateQuery=function(e,r){var n=t.createRequest(e.query,e.variables),i=r(this.readQuery(n));null!==i&&S(this,n,i)},V.prototype.readQuery=function(e){return G(this,t.createRequest(e.query,e.variables)).data},V.prototype.readFragment=function(e,t,r){return H(this,e,t,r)},V.prototype.writeFragment=function(e,t,r){F(this,e,t,r)};var U=function(e,t,r){L(0);var n=G(e,t,r);return M(),n},G=function(e,t,r){var n=h(t.query),i=e.getRootKey(n.operation),o=u(n),a={parentTypeName:i,parentKey:i,parentFieldKey:"",fieldName:"",variables:v(n,t.variables),fragments:g(t.query),partial:!1,store:e,schemaPredicates:e.schemaPredicates},s=r||Object.create(null);return s=i!==a.store.getRootKey("query")?z(a,i,o,s):J(a,i,o,s),{dependencies:I(),partial:void 0!==s&&a.partial,data:void 0===s?null:s}},z=function(e,t,r,n){if("string"!=typeof n.__typename)return n;var i=Object.create(null);i.__typename=n.__typename;for(var o,a=new x(t,t,r,e);void 0!==(o=a.next());){var c=s(o),l=n[c];i[c]=void 0===o.selectionSet||null===l||w(l)?l:B(e,u(o),l)}return i},B=function(e,t,r){if(Array.isArray(r)){for(var n=new Array(r.length),i=0,o=r.length;i<o;i++)n[i]=B(e,t,r[i]);return n}if(null===r)return null;var a=e.store.keyOfEntity(r);if(null!==a){var s=Object.create(null),u=J(e,a,t,s);return void 0===u?null:u}return z(e,r.__typename,t,r)},H=function(e,t,r,n){var o=g(t),s=o[Object.keys(o)[0]];if(void 0===s)return null;var c=u(s),l=a(s);"string"==typeof r||r.__typename||(r.__typename=l);var f="string"!=typeof r?e.keyOfEntity(i({__typename:l},r)):r;return f&&J({parentTypeName:l,parentKey:f,parentFieldKey:"",fieldName:"",variables:n||{},fragments:o,partial:!1,store:e,schemaPredicates:e.schemaPredicates},f,c,Object.create(null))||null},J=function(e,t,r,n){var i=e.store,a=e.variables,c=e.schemaPredicates,l=t===i.getRootKey("query");l||Q(t);var f=l?t:i.getField(t,"__typename");if("string"==typeof f){n.__typename=f;for(var v,d=new x(f,t,r,e),y=!1,h=!1;void 0!==(v=d.next());){var m=o(v),g=p(v,a),b=s(v),O=_(t,k(m,g)),w=i.getRecord(O);l&&Q(O);var N=void 0,S=i.resolvers[f];if(void 0!==S&&"function"==typeof S[m]){e.parentTypeName=f,e.parentKey=t,e.parentFieldKey=O,e.fieldName=m,void 0!==w&&(n[b]=w);var q=S[m](n,g||{},i,e);if(void 0!==v.selectionSet){var F=u(v),R=n[b]||Object.create(null);N=W(e,f,m,O,F,R,q)}else N=void 0===q&&void 0===c?null:q}else if(void 0===v.selectionSet)N=w;else{var K=i.getLink(O);void 0!==K?N=X(e,K,f,m,u(v),n[b]):"object"==typeof w&&null!==w&&(N=w)}if(void 0===N&&void 0!==c&&c.isFieldNullable(f,m))h=!0,n[b]=null;else{if(void 0===N)return;y=!0,n[b]=N}}return h&&(e.partial=!0),l&&h&&!y?void 0:n}},W=function(e,t,r,n,i,a,c){if(Array.isArray(c)){for(var l=e.schemaPredicates,f=void 0===l||l.isListNullable(t,r),v=new Array(c.length),d=0,y=c.length;d<y;d++){var h=c[d],m=void 0!==a?a[d]:void 0,g=W(e,t,r,_(n,""+d),i,m,h);if(void 0===g&&!f)return;v[d]=void 0!==g?g:null}return v}if(null==c)return null;if(Y(c)){var b=void 0===a?Object.create(null):a;return"string"==typeof c?J(e,c,i,b):function(e,t,r,n,i){var a=e.store,c=e.variables,l=e.schemaPredicates,f=a.keyOfEntity(i)||t;Q(f);var v=i.__typename,d=a.getField(f,"__typename")||v;if(!("string"!=typeof d||v&&d!==v)){n.__typename=d;for(var y,h=new x(d,f,r,e),m=!1,g=!1;void 0!==(y=h.next());){var b=o(y),O=p(y,c),w=s(y),N=_(f,k(b,O)),S=a.getRecord(N),q=i[b],F=void 0;if(void 0!==q&&void 0===y.selectionSet)F=q;else if(void 0===y.selectionSet)F=S;else if(void 0!==q)F=W(e,d,b,N,u(y),n[w],q);else{var R=a.getLink(N);void 0!==R?F=X(e,R,d,b,u(y),n[w]):"object"==typeof S&&null!==S&&(F=S)}if(void 0===F&&void 0!==l&&l.isFieldNullable(d,b))g=!0,n[w]=null;else{if(void 0===F)return;m=!0,n[w]=F}}return g&&(e.partial=!0),m?n:void 0}}(e,n,i,b,c)}},X=function(e,t,r,n,i,o){if(Array.isArray(t)){for(var a=e.schemaPredicates,s=void 0!==a&&a.isListNullable(r,n),u=new Array(t.length),c=0,l=t.length;c<l;c++){var f=X(e,t[c],r,n,i,void 0!==o?o[c]:void 0);if(void 0===f&&!s)return;u[c]=void 0!==f?f:null}return u}if(null===t)return null;var p=void 0===o?Object.create(null):o;return J(e,t,i,p)},Y=function(e){return"string"==typeof e||"object"==typeof e&&"string"==typeof e.__typename},Z=function(t){this.schema=e.buildClientSchema(t)};Z.prototype.isFieldNullable=function(t,r){var n=$(this.schema,t,r);return void 0!==n&&e.isNullableType(n.type)},Z.prototype.isListNullable=function(t,r){var n=$(this.schema,t,r);if(void 0===n)return!1;var i=e.isNonNullType(n.type)?n.type.ofType:n.type;return e.isListType(i)&&e.isNullableType(i.ofType)},Z.prototype.isFieldAvailableOnType=function(e,t){return!!$(this.schema,e,t)},Z.prototype.isInterfaceOfType=function(e,t){if(!t||!e)return!1;if(t===e)return!0;var r=this.schema.getType(e),n=this.schema.getType(t);return this.schema.isPossibleType(r,n)};var $=function(e,t,r){var n=e.getType(t);if(void 0!==n){var i=n.getFields()[r];if(void 0!==i)return i}},ee=function(e,t){return i(i({},e),{context:i(i({},e.context),{meta:i(i({},e.context.meta),{cacheOutcome:t})})})},te=function(e){return i(i({},e),{query:t.formatDocument(e.query)})},re=function(e){return e.context.requestPolicy},ne=function(e){return"query"===e.operationName},ie=function(e){var t=re(e);return ne(e)&&"network-only"!==t},oe=function(e,t){return i(i({},e),{context:i(i({},e.context),{requestPolicy:t})})};function ae(e){return ie(e)}function se(e){return"miss"===e.outcome}function ue(e){return ee(e.operation,e.outcome)}function ce(e){return"miss"!==e.outcome}function le(e){return!ie(e)}exports.Store=V,exports.cacheExchange=function(e){return function(t){var r=t.forward,i=t.client;e||(e={});var o=new V(e.schema?new Z(e.schema):void 0,e.resolvers,e.updates,e.optimistic,e.keys),a=new Set,s=new Map,u=Object.create(null),c=function(e,t){void 0!==t&&t.forEach((function(t){var r=u[t];if(void 0!==r){u[t]=[];for(var n=0,i=r.length;n<i;n++)e.add(r[n])}}))},l=function(e,t){t.forEach((function(t){if(t!==e.key){var r=s.get(t);if(void 0!==r){s.delete(t);var n=oe(r,"cache-first");i.reexecuteOperation(n)}}}))},f=function(e){if(s=re(i=e),function(e){return"mutation"===e.operationName}(i)&&"network-only"!==s){var t=e.key,r=q(o,e,t).dependencies;if(0!==r.size){a.add(t);var n=new Set;c(n,r),l(e,n)}}var i,s},p=function(e,t){t.forEach((function(t){(u[t]||(u[t]=[])).push(e.key),s.has(e.key)||s.set(e.key,"network-only"===e.context.requestPolicy?oe(e,"cache-and-network"):e)}))},v=function(e){var t,r=re(e),n=U(o,e),i=n.data,a=n.partial;return null===i?t="miss":(p(e,n.dependencies),t=a&&"cache-only"!==r?"partial":"hit"),{outcome:t,operation:e,data:i}},d=function(e){var t,r,n=e.operation,i=e.error,s=e.extensions,u=ne(n),f=e.data,v=n.key;if(a.has(v)&&(a.delete(v),o.clearOptimistic(v)),null!=f)if(t=N(o,n,f).dependencies,u){var d=U(o,n);f=d.data,r=d.dependencies}else f=U(o,n,f).data;var y=new Set;return c(y,t),u&&c(y,r),l(e.operation,y),u&&void 0!==r&&p(e.operation,r),{data:f,error:i,extensions:s,operation:n}};function y(e){var t=e.operation,r=e.outcome,n=re(t);if("cache-and-network"===n||"cache-first"===n&&"partial"===r){var o=oe(t,"network-only");i.reexecuteOperation(o)}return{operation:ee(t,r),data:e.data,error:e.error,extensions:e.extensions}}return function(e){var t=n.pipe(e,n.map(te),n.tap(f),n.share),i=n.pipe(t,n.filter(ae),n.map(v),n.share),o=n.pipe(i,n.filter(se),n.map(ue)),a=n.pipe(i,n.filter(ce),n.map(y)),s=n.pipe(r(n.merge([n.pipe(t,n.filter(le)),o])),n.map(d));return n.merge([s,a])}}},exports.query=U,exports.read=G,exports.write=N,exports.writeFragment=F,exports.writeOptimistic=q; | ||
//# sourceMappingURL=urql-exchange-graphcache.min.js.map |
{ | ||
"name": "@urql/exchange-graphcache", | ||
"version": "1.0.0-rc.11", | ||
"version": "1.0.0", | ||
"description": "A normalized and configurable cache exchange for urql", | ||
@@ -30,3 +30,4 @@ "repository": "https://github.com/FormidableLabs/urql-exchange-graphcache", | ||
"lint": "eslint . --ext .ts,.tsx", | ||
"prepublishOnly": "run-s clean test build", | ||
"prepare:extras": "./scripts/prepare-extras.js", | ||
"prepublishOnly": "run-s clean test build prepare:extras", | ||
"codecov": "codecov" | ||
@@ -79,3 +80,2 @@ }, | ||
"dependencies": { | ||
"fast-json-stable-stringify": "^2.0.0", | ||
"pessimism": "^1.1.4", | ||
@@ -87,34 +87,33 @@ "tiny-invariant": "^1.0.6", | ||
"graphql": "^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0", | ||
"urql": ">= 1.3.0" | ||
"urql": ">= 1.5.1" | ||
}, | ||
"devDependencies": { | ||
"@babel/core": "^7.5.5", | ||
"@babel/core": "^7.6.2", | ||
"@babel/plugin-transform-object-assign": "^7.2.0", | ||
"@babel/plugin-transform-react-jsx": "^7.3.0", | ||
"@testing-library/react": "^9.1.3", | ||
"@testing-library/react": "^9.1.4", | ||
"@types/enzyme": "3.10.3", | ||
"@types/fast-json-stable-stringify": "^2.0.0", | ||
"@types/graphql": "^14.5.0", | ||
"@types/jest": "^24.0.18", | ||
"@types/react": "16.9.2", | ||
"@types/react": "16.9.3", | ||
"@types/react-test-renderer": "16.9.0", | ||
"@types/warning": "^3.0.0", | ||
"@typescript-eslint/eslint-plugin": "^2.0.0", | ||
"@typescript-eslint/parser": "^2.0.0", | ||
"@typescript-eslint/eslint-plugin": "^2.3.1", | ||
"@typescript-eslint/parser": "^2.3.1", | ||
"babel-plugin-closure-elimination": "^1.3.0", | ||
"babel-plugin-transform-async-to-promises": "^0.8.14", | ||
"codecov": "^3.5.0", | ||
"codecov": "^3.6.1", | ||
"enzyme": "^3.10.0", | ||
"enzyme-adapter-react-16": "^1.14.0", | ||
"enzyme-to-json": "^3.4.0", | ||
"eslint": "^6.2.2", | ||
"eslint-config-prettier": "^6.1.0", | ||
"eslint": "^6.4.0", | ||
"eslint-config-prettier": "^6.3.0", | ||
"eslint-plugin-import": "^2.18.2", | ||
"eslint-plugin-react": "^7.14.3", | ||
"eslint-plugin-react-hooks": "^2.0.1", | ||
"graphql": "^14.5.3", | ||
"graphql": "^14.5.8", | ||
"graphql-tag": "^2.10.1", | ||
"husky": "^3.0.4", | ||
"jest": "^24.9.0", | ||
"lint-staged": "^9.2.5", | ||
"lint-staged": "^9.4.0", | ||
"npm-run-all": "^4.1.5", | ||
@@ -126,6 +125,6 @@ "prettier": "^1.17.1", | ||
"react-is": "^16.9.0", | ||
"react-ssr-prepass": "^1.0.6", | ||
"react-ssr-prepass": "^1.0.7", | ||
"react-test-renderer": "^16.9.0", | ||
"rimraf": "^3.0.0", | ||
"rollup": "^1.20.2", | ||
"rollup": "^1.21.4", | ||
"rollup-plugin-babel": "^4.3.3", | ||
@@ -136,9 +135,9 @@ "rollup-plugin-buble": "^0.19.8", | ||
"rollup-plugin-replace": "^2.2.0", | ||
"rollup-plugin-terser": "^5.1.1", | ||
"rollup-plugin-typescript2": "^0.23.0", | ||
"terser": "^4.2.1", | ||
"ts-jest": "^24.0.2", | ||
"typescript": "^3.5.3", | ||
"urql": "^1.5.0" | ||
"rollup-plugin-terser": "^5.1.2", | ||
"rollup-plugin-typescript2": "^0.24.2", | ||
"terser": "^4.3.2", | ||
"ts-jest": "^24.1.0", | ||
"typescript": "^3.6.3", | ||
"urql": "^1.5.1" | ||
} | ||
} |
@@ -109,2 +109,4 @@ <h2 align="center">@urql/exchange-graphcache</h2> | ||
Read more about the [architecture](./docs/architecture.md) | ||
## Usage | ||
@@ -111,0 +113,0 @@ |
@@ -111,23 +111,27 @@ import { | ||
// This accepts an array of dependencies and reexecutes all known operations | ||
// against the mapping of dependencies to operations | ||
// The passed triggerOp is ignored however | ||
const processDependencies = ( | ||
triggerOp: Operation, | ||
dependencies: Set<string> | ||
const collectPendingOperations = ( | ||
pendingOperations: Set<number>, | ||
dependencies: void | Set<string> | ||
) => { | ||
const pendingOperations = new Set<number>(); | ||
if (dependencies !== undefined) { | ||
// Collect operations that will be updated due to cache changes | ||
dependencies.forEach(dep => { | ||
const keys = deps[dep]; | ||
if (keys !== undefined) { | ||
deps[dep] = []; | ||
for (let i = 0, l = keys.length; i < l; i++) { | ||
pendingOperations.add(keys[i]); | ||
} | ||
} | ||
}); | ||
} | ||
}; | ||
// Collect operations that will be updated due to cache changes | ||
dependencies.forEach(dep => { | ||
const keys = deps[dep]; | ||
if (keys !== undefined) { | ||
deps[dep] = []; | ||
keys.forEach(key => pendingOperations.add(key)); | ||
} | ||
}); | ||
const executePendingOperations = ( | ||
operation: Operation, | ||
pendingOperations: Set<number> | ||
) => { | ||
// Reexecute collected operations and delete them from the mapping | ||
pendingOperations.forEach(key => { | ||
if (key !== triggerOp.key) { | ||
if (key !== operation.key) { | ||
const op = ops.get(key); | ||
@@ -150,3 +154,5 @@ if (op !== undefined) { | ||
optimisticKeys.add(key); | ||
processDependencies(operation, dependencies); | ||
const pendingOperations = new Set<number>(); | ||
collectPendingOperations(pendingOperations, dependencies); | ||
executePendingOperations(operation, pendingOperations); | ||
} | ||
@@ -221,7 +227,12 @@ } | ||
if (writeDependencies !== undefined) { | ||
// Update operations that depend on the updated data (except the current one) | ||
processDependencies(result.operation, writeDependencies); | ||
// Collect all write dependencies and query dependencies for queries | ||
const pendingOperations = new Set<number>(); | ||
collectPendingOperations(pendingOperations, writeDependencies); | ||
if (isQuery) { | ||
collectPendingOperations(pendingOperations, queryDependencies); | ||
} | ||
// Execute all pending operations related to changed dependencies | ||
executePendingOperations(result.operation, pendingOperations); | ||
// Update this operation's dependencies if it's a query | ||
@@ -228,0 +239,0 @@ if (isQuery && queryDependencies !== undefined) { |
@@ -1,8 +0,8 @@ | ||
import stringify from 'fast-json-stable-stringify'; | ||
import { stringifyVariables } from 'urql'; | ||
import { Variables } from '../types'; | ||
export const keyOfField = (fieldName: string, args?: null | Variables) => | ||
args ? `${fieldName}(${stringify(args)})` : fieldName; | ||
args ? `${fieldName}(${stringifyVariables(args)})` : fieldName; | ||
export const joinKeys = (parentKey: string, key: string) => | ||
`${parentKey}.${key}`; |
@@ -25,3 +25,3 @@ import { Store } from '../store'; | ||
describe('Query', () => { | ||
let schema, store; | ||
let schema, store, alteredRoot; | ||
const spy: { console?: any } = {}; | ||
@@ -31,2 +31,3 @@ | ||
schema = require('../test-utils/simple_schema.json'); | ||
alteredRoot = require('../test-utils/altered_root_schema.json'); | ||
}); | ||
@@ -145,2 +146,33 @@ | ||
}); | ||
it('should respect altered root types', () => { | ||
const QUERY = gql` | ||
query getTodos { | ||
todos { | ||
id | ||
text | ||
} | ||
} | ||
`; | ||
const store = new Store(new SchemaPredicates(alteredRoot)); | ||
let { data } = query(store, { query: QUERY }); | ||
expect(data).toEqual(null); | ||
write( | ||
store, | ||
{ query: QUERY }, | ||
{ | ||
todos: [{ __typename: 'Todo', id: '0', text: 'Solve bug' }], | ||
__typename: 'query_root', | ||
} | ||
); | ||
({ data } = query(store, { query: QUERY })); | ||
expect(data).toEqual({ | ||
__typename: 'query_root', | ||
todos: [{ __typename: 'Todo', id: '0', text: 'Solve bug' }], | ||
}); | ||
}); | ||
}); |
@@ -45,2 +45,6 @@ import { warning } from '../helpers/warning'; | ||
interface Context { | ||
parentTypeName: string; | ||
parentKey: string; | ||
parentFieldKey: string; | ||
fieldName: string; | ||
partial: boolean; | ||
@@ -74,2 +78,6 @@ store: Store; | ||
const ctx: Context = { | ||
parentTypeName: rootKey, | ||
parentKey: rootKey, | ||
parentFieldKey: '', | ||
fieldName: '', | ||
variables: normalizeVariables(operation, request.variables), | ||
@@ -84,3 +92,3 @@ fragments: getFragments(request.query), | ||
data = | ||
rootKey !== 'Query' | ||
rootKey !== ctx.store.getRootKey('query') | ||
? readRoot(ctx, rootKey, rootSelect, data) | ||
@@ -201,2 +209,6 @@ : readSelection(ctx, rootKey, rootSelect, data); | ||
const ctx: Context = { | ||
parentTypeName: typename, | ||
parentKey: entityKey, | ||
parentFieldKey: '', | ||
fieldName: '', | ||
variables: variables || {}, | ||
@@ -256,2 +268,9 @@ fragments, | ||
if (resolvers !== undefined && typeof resolvers[fieldName] === 'function') { | ||
// We have to update the information in context to reflect the info | ||
// that the resolver will receive | ||
ctx.parentTypeName = typename; | ||
ctx.parentKey = entityKey; | ||
ctx.parentFieldKey = fieldKey; | ||
ctx.fieldName = fieldName; | ||
// We have a resolver for this field. | ||
@@ -263,3 +282,3 @@ // Prepare the actual fieldValue, so that the resolver can use it | ||
let resolverValue: DataField | undefined = resolvers[fieldName]( | ||
const resolverValue: DataField | undefined = resolvers[fieldName]( | ||
data, | ||
@@ -274,20 +293,20 @@ fieldArgs || {}, | ||
// subselection. This can either be a list or an object. | ||
resolverValue = resolveResolverResult( | ||
const fieldSelect = getSelectionSet(node); | ||
const prevData = (data[fieldAlias] as Data) || Object.create(null); | ||
dataFieldValue = resolveResolverResult( | ||
ctx, | ||
resolverValue, | ||
typename, | ||
fieldName, | ||
fieldKey, | ||
getSelectionSet(node), | ||
data[fieldAlias] as Data | Data[] | ||
fieldSelect, | ||
prevData, | ||
resolverValue | ||
); | ||
} | ||
// When we have a schema we check for a user's resolver whether the field is nullable | ||
// Otherwise we trust the resolver and assume that it is | ||
const isNull = resolverValue === undefined || resolverValue === null; | ||
if (isNull && schemaPredicates !== undefined) { | ||
dataFieldValue = undefined; | ||
} else { | ||
dataFieldValue = isNull ? null : resolverValue; | ||
// Otherwise we set the resolverValue, and normalise it to null when there's | ||
// no schema data to check with whether this field is nullable | ||
dataFieldValue = | ||
resolverValue === undefined && schemaPredicates === undefined | ||
? null | ||
: resolverValue; | ||
} | ||
@@ -299,7 +318,4 @@ } else if (node.selectionSet === undefined) { | ||
// We have a selection set which means that we'll be checking for links | ||
const fieldSelect = getSelectionSet(node); | ||
const link = store.getLink(fieldKey); | ||
if (link !== undefined) { | ||
const prevData = data[fieldAlias] as Data; | ||
dataFieldValue = resolveLink( | ||
@@ -310,4 +326,4 @@ ctx, | ||
fieldName, | ||
fieldSelect, | ||
prevData | ||
getSelectionSet(node), | ||
data[fieldAlias] as Data | ||
); | ||
@@ -346,5 +362,118 @@ } else if (typeof fieldValue === 'object' && fieldValue !== null) { | ||
const readResolverResult = ( | ||
ctx: Context, | ||
key: string, | ||
select: SelectionSet, | ||
data: Data, | ||
result: Data | ||
): Data | undefined => { | ||
const { store, variables, schemaPredicates } = ctx; | ||
const entityKey = store.keyOfEntity(result) || key; | ||
addDependency(entityKey); | ||
const resolvedTypename = result.__typename; | ||
const typename = store.getField(entityKey, '__typename') || resolvedTypename; | ||
if ( | ||
typeof typename !== 'string' || | ||
(resolvedTypename && typename !== resolvedTypename) | ||
) { | ||
warning( | ||
false, | ||
'Invalid resolver value: The resolver at `' + | ||
entityKey + | ||
'` returned an ' + | ||
'invalid typename that could not be reconciled with the cache.' | ||
); | ||
return undefined; | ||
} | ||
// The following closely mirrors readSelection, but differs only slightly for the | ||
// sake of resolving from an existing resolver result | ||
data.__typename = typename; | ||
const iter = new SelectionIterator(typename, entityKey, select, ctx); | ||
let node; | ||
let hasFields = false; | ||
let hasPartials = false; | ||
while ((node = iter.next()) !== undefined) { | ||
// Derive the needed data from our node. | ||
const fieldName = getName(node); | ||
const fieldArgs = getFieldArguments(node, variables); | ||
const fieldAlias = getFieldAlias(node); | ||
const fieldKey = joinKeys(entityKey, keyOfField(fieldName, fieldArgs)); | ||
const fieldValue = store.getRecord(fieldKey); | ||
const resultValue = result[fieldName]; | ||
if (process.env.NODE_ENV !== 'production' && schemaPredicates && typename) { | ||
schemaPredicates.isFieldAvailableOnType(typename, fieldName); | ||
} | ||
// We temporarily store the data field in here, but undefined | ||
// means that the value is missing from the cache | ||
let dataFieldValue: void | DataField; | ||
if (resultValue !== undefined && node.selectionSet === undefined) { | ||
// The field is a scalar and can be retrieved directly from the result | ||
dataFieldValue = resultValue; | ||
} else if (node.selectionSet === undefined) { | ||
// The field is a scalar but isn't on the result, so it's retrieved from the cache | ||
dataFieldValue = fieldValue; | ||
} else if (resultValue !== undefined) { | ||
// We start walking the nested resolver result here | ||
dataFieldValue = resolveResolverResult( | ||
ctx, | ||
typename, | ||
fieldName, | ||
fieldKey, | ||
getSelectionSet(node), | ||
data[fieldAlias] as Data, | ||
resultValue | ||
); | ||
} else { | ||
// Otherwise we attempt to get the missing field from the cache | ||
const link = store.getLink(fieldKey); | ||
if (link !== undefined) { | ||
dataFieldValue = resolveLink( | ||
ctx, | ||
link, | ||
typename, | ||
fieldName, | ||
getSelectionSet(node), | ||
data[fieldAlias] as Data | ||
); | ||
} else if (typeof fieldValue === 'object' && fieldValue !== null) { | ||
// The entity on the field was invalid but can still be recovered | ||
dataFieldValue = fieldValue; | ||
} | ||
} | ||
// Now that dataFieldValue has been retrieved it'll be set on data | ||
// If it's uncached (undefined) but nullable we can continue assembling | ||
// a partial query result | ||
if ( | ||
dataFieldValue === undefined && | ||
schemaPredicates !== undefined && | ||
schemaPredicates.isFieldNullable(typename, fieldName) | ||
) { | ||
// The field is uncached but we have a schema that says it's nullable | ||
// Set the field to null and continue | ||
hasPartials = true; | ||
data[fieldAlias] = null; | ||
} else if (dataFieldValue === undefined) { | ||
// The field is uncached and not nullable; return undefined | ||
return undefined; | ||
} else { | ||
// Otherwise continue as usual | ||
hasFields = true; | ||
data[fieldAlias] = dataFieldValue; | ||
} | ||
} | ||
if (hasPartials) ctx.partial = true; | ||
return !hasFields ? undefined : data; | ||
}; | ||
const resolveResolverResult = ( | ||
ctx: Context, | ||
result: DataField, | ||
typename: string, | ||
@@ -354,54 +483,54 @@ fieldName: string, | ||
select: SelectionSet, | ||
prevData: void | Data | Data[] | ||
prevData: void | Data | Data[], | ||
result: void | DataField | ||
): DataField | undefined => { | ||
// When we are dealing with a list we have to call this method again. | ||
if (Array.isArray(result)) { | ||
const { schemaPredicates } = ctx; | ||
// Check whether values of the list may be null; for resolvers we assume | ||
// that they can be, since it's user-provided data | ||
const isListNullable = | ||
schemaPredicates !== undefined && | ||
schemaPredicates === undefined || | ||
schemaPredicates.isListNullable(typename, fieldName); | ||
const newResult = new Array(result.length); | ||
const data = new Array(result.length); | ||
for (let i = 0, l = result.length; i < l; i++) { | ||
const data = prevData !== undefined ? prevData[i] : undefined; | ||
const childKey = joinKeys(key, `${i}`); | ||
const innerResult = result[i]; | ||
// Get the inner previous data from prevData | ||
const innerPrevData = prevData !== undefined ? prevData[i] : undefined; | ||
// Recursively read resolver result | ||
const childResult = resolveResolverResult( | ||
ctx, | ||
result[i], | ||
typename, | ||
fieldName, | ||
childKey, | ||
joinKeys(key, `${i}`), | ||
select, | ||
data | ||
innerPrevData, | ||
innerResult | ||
); | ||
if (childResult === undefined && !isListNullable) { | ||
return undefined; | ||
} else { | ||
result[i] = childResult !== undefined ? childResult : null; | ||
data[i] = childResult !== undefined ? childResult : null; | ||
} | ||
} | ||
return newResult; | ||
} else if (result === null) { | ||
return data; | ||
} else if (result === null || result === undefined) { | ||
return null; | ||
} else if (isDataOrKey(result)) { | ||
// We don't need to read the entity after exiting a resolver | ||
// we can just go on and read the selection further. | ||
const data = prevData === undefined ? Object.create(null) : prevData; | ||
const childKey = | ||
(typeof result === 'string' ? result : ctx.store.keyOfEntity(result)) || | ||
key; | ||
// TODO: Copy over fields from result but check against schema whether that's safe | ||
return readSelection(ctx, childKey, select, data); | ||
return typeof result === 'string' | ||
? readSelection(ctx, result, select, data) | ||
: readResolverResult(ctx, key, select, data, result); | ||
} else { | ||
warning( | ||
false, | ||
'Invalid resolver value: The field at `' + | ||
key + | ||
'` is a scalar (number, boolean, etc)' + | ||
', but the GraphQL query expects a selection set for this field.' | ||
); | ||
return undefined; | ||
} | ||
warning( | ||
false, | ||
'Invalid resolver value: The resolver at `' + | ||
key + | ||
'` returned a scalar (number, boolean, etc)' + | ||
', but the GraphQL query expects a selection set for this field.\n' + | ||
'If necessary, use Cache.resolve() to resolve a link or entity from the cache.' | ||
); | ||
return undefined; | ||
}; | ||
@@ -425,5 +554,6 @@ | ||
const innerPrevData = prevData !== undefined ? prevData[i] : undefined; | ||
const innerLink = link[i]; | ||
const childLink = resolveLink( | ||
ctx, | ||
link[i], | ||
innerLink, | ||
typename, | ||
@@ -452,4 +582,2 @@ fieldName, | ||
typeof x === 'string' || | ||
(typeof x === 'object' && | ||
x !== null && | ||
typeof (x as any).__typename === 'string'); | ||
(typeof x === 'object' && typeof (x as any).__typename === 'string'); |
@@ -43,2 +43,6 @@ import invariant from 'invariant'; | ||
interface Context { | ||
parentTypeName: string; | ||
parentKey: string; | ||
parentFieldKey: string; | ||
fieldName: string; | ||
result: WriteResult; | ||
@@ -48,3 +52,3 @@ store: Store; | ||
fragments: Fragments; | ||
isOptimistic?: boolean; | ||
optimistic?: boolean; | ||
schemaPredicates?: SchemaPredicates; | ||
@@ -73,3 +77,10 @@ } | ||
const select = getSelectionSet(operation); | ||
const operationName = store.getRootKey(operation.operation); | ||
const ctx: Context = { | ||
parentTypeName: operationName, | ||
parentKey: operationName, | ||
parentFieldKey: '', | ||
fieldName: '', | ||
variables: normalizeVariables(operation, request.variables), | ||
@@ -82,5 +93,2 @@ fragments: getFragments(request.query), | ||
const select = getSelectionSet(operation); | ||
const operationName = ctx.store.getRootKey(operation.operation); | ||
if (operationName === ctx.store.getRootKey('query')) { | ||
@@ -105,3 +113,15 @@ writeSelection(ctx, operationName, select, data); | ||
const mutationRootKey = store.getRootKey('mutation'); | ||
const operationName = store.getRootKey(operation.operation); | ||
invariant( | ||
operationName === mutationRootKey, | ||
'writeOptimistic(...) was called with an operation that is not a mutation.\n' + | ||
'This case is unsupported and should never occur.' | ||
); | ||
const ctx: Context = { | ||
parentTypeName: mutationRootKey, | ||
parentKey: mutationRootKey, | ||
parentFieldKey: '', | ||
fieldName: '', | ||
variables: normalizeVariables(operation, request.variables), | ||
@@ -112,13 +132,5 @@ fragments: getFragments(request.query), | ||
schemaPredicates: store.schemaPredicates, | ||
isOptimistic: true, | ||
optimistic: true, | ||
}; | ||
const mutationRootKey = ctx.store.getRootKey('mutation'); | ||
const operationName = ctx.store.getRootKey(operation.operation); | ||
invariant( | ||
operationName === mutationRootKey, | ||
'writeOptimistic(...) was called with an operation that is not a mutation.\n' + | ||
'This case is unsupported and should never occur.' | ||
); | ||
const select = getSelectionSet(operation); | ||
@@ -134,2 +146,5 @@ const data = Object.create(null); | ||
if (resolver !== undefined) { | ||
// We have to update the context to reflect up-to-date ResolveInfo | ||
ctx.fieldName = fieldName; | ||
const fieldArgs = getFieldArguments(node, ctx.variables); | ||
@@ -188,2 +203,6 @@ const fieldSelect = getSelectionSet(node); | ||
const ctx: Context = { | ||
parentTypeName: typename, | ||
parentKey: entityKey, | ||
parentFieldKey: '', | ||
fieldName: '', | ||
variables: variables || {}, | ||
@@ -225,3 +244,3 @@ fragments, | ||
if (fieldValue === undefined) { | ||
const advice = ctx.isOptimistic | ||
const advice = ctx.optimistic | ||
? '\nYour optimistic result may be missing a field!' | ||
@@ -257,4 +276,6 @@ : ''; | ||
const fieldSelect = getSelectionSet(node); | ||
const connectionKey = joinKeys(entityKey, fieldName); | ||
const link = writeField(ctx, fieldKey, fieldSelect, fieldValue); | ||
store.writeLink(link, fieldKey); | ||
store.writeConnection(connectionKey, fieldKey, fieldArgs); | ||
store.removeRecord(fieldKey); | ||
@@ -310,3 +331,5 @@ } else { | ||
warning( | ||
typename.endsWith('Connection') || typename.endsWith('Edge'), | ||
typename.endsWith('Connection') || | ||
typename.endsWith('Edge') || | ||
typename === 'PageInfo', | ||
'Invalid key: The GraphQL query at the field at `' + | ||
@@ -361,2 +384,9 @@ parentFieldKey + | ||
if (isRootField) { | ||
const fieldKey = joinKeys(typename, keyOfField(fieldName, fieldArgs)); | ||
// We have to update the context to reflect up-to-date ResolveInfo | ||
ctx.parentTypeName = typename; | ||
ctx.parentKey = typename; | ||
ctx.parentFieldKey = fieldKey; | ||
ctx.fieldName = fieldName; | ||
// We run side-effect updates after the default, normalized updates | ||
@@ -363,0 +393,0 @@ // so that the data is already available in-store if necessary |
@@ -7,4 +7,6 @@ import invariant from 'invariant'; | ||
import { | ||
Cache, | ||
EntityField, | ||
Link, | ||
Connection, | ||
ResolverConfig, | ||
@@ -14,2 +16,3 @@ DataField, | ||
Data, | ||
QueryInput, | ||
UpdatesConfig, | ||
@@ -79,9 +82,5 @@ OptimisticMutationConfig, | ||
interface QueryInput { | ||
query: string | DocumentNode; | ||
variables?: Variables; | ||
} | ||
export class Store { | ||
export class Store implements Cache { | ||
records: Pessimism.Map<EntityField>; | ||
connections: Pessimism.Map<Connection[]>; | ||
links: Pessimism.Map<Link>; | ||
@@ -106,3 +105,5 @@ | ||
this.records = Pessimism.asMutable(Pessimism.make()); | ||
this.connections = Pessimism.asMutable(Pessimism.make()); | ||
this.links = Pessimism.asMutable(Pessimism.make()); | ||
this.resolvers = resolvers || {}; | ||
@@ -184,2 +185,6 @@ this.optimisticMutations = optimisticMutations || {}; | ||
this.records = Pessimism.clearOptimistic(this.records, optimisticKey); | ||
this.connections = Pessimism.clearOptimistic( | ||
this.connections, | ||
optimisticKey | ||
); | ||
this.links = Pessimism.clearOptimistic(this.links, optimisticKey); | ||
@@ -231,2 +236,19 @@ } | ||
writeConnection(key: string, linkKey: string, args: Variables | null) { | ||
if (args === null) return this.connections; | ||
let connections = Pessimism.get(this.connections, key); | ||
const connection: Connection = [args, linkKey]; | ||
if (connections === undefined) { | ||
connections = [connection]; | ||
} else { | ||
for (let i = 0, l = connections.length; i < l; i++) | ||
if (connections[i][1] === linkKey) return this.connections; | ||
connections = connections.slice(); | ||
connections.push(connection); | ||
} | ||
return (this.connections = mapSet(this.connections, key, connections)); | ||
} | ||
resolveValueOrLink(fieldKey: string): DataField { | ||
@@ -243,8 +265,13 @@ const fieldValue = this.getRecord(fieldKey); | ||
resolve(entity: Data | string, field: string, args?: Variables): DataField { | ||
if (typeof entity === 'string') { | ||
resolve( | ||
entity: Data | string | null, | ||
field: string, | ||
args?: Variables | ||
): DataField { | ||
if (entity === null) { | ||
return null; | ||
} else if (typeof entity === 'string') { | ||
addDependency(entity); | ||
return this.resolveValueOrLink(joinKeys(entity, keyOfField(field, args))); | ||
} else { | ||
// This gives us __typename:key | ||
const entityKey = this.keyOfEntity(entity); | ||
@@ -259,6 +286,27 @@ if (entityKey === null) return null; | ||
invalidateQuery(dataQuery: DocumentNode, variables: Variables) { | ||
invalidate(this, { query: dataQuery, variables }); | ||
resolveConnections( | ||
entity: Data | string | null, | ||
field: string | ||
): Connection[] { | ||
let connections: undefined | Connection[]; | ||
if (typeof entity === 'string') { | ||
connections = Pessimism.get(this.connections, joinKeys(entity, field)); | ||
} else if (entity !== null) { | ||
const entityKey = this.keyOfEntity(entity); | ||
if (entityKey !== null) { | ||
addDependency(entityKey); | ||
connections = Pessimism.get( | ||
this.connections, | ||
joinKeys(entityKey, field) | ||
); | ||
} | ||
} | ||
return connections !== undefined ? connections : []; | ||
} | ||
invalidateQuery(query: string | DocumentNode, variables?: Variables) { | ||
invalidate(this, createRequest(query, variables)); | ||
} | ||
hasField(key: string): boolean { | ||
@@ -269,4 +317,4 @@ return this.getRecord(key) !== undefined || this.getLink(key) !== undefined; | ||
updateQuery( | ||
input: { query: string | DocumentNode; variables?: Variables }, | ||
updater: (data: Data | null) => null | Data | ||
input: QueryInput, | ||
updater: (data: Data | null) => Data | null | ||
): void { | ||
@@ -273,0 +321,0 @@ const request = createRequest(input.query, input.variables); |
@@ -18,2 +18,13 @@ import gql from 'graphql-tag'; | ||
const Todo = gql` | ||
query($id: ID!) { | ||
__typename | ||
todo(id: $id) { | ||
id | ||
text | ||
complete | ||
} | ||
} | ||
`; | ||
const ToggleTodo = gql` | ||
@@ -154,2 +165,33 @@ mutation($id: ID!) { | ||
it('should link entities', () => { | ||
const store = new Store(undefined, { | ||
Query: { | ||
todo: (_parent, args) => { | ||
return { __typename: 'Todo', ...args }; | ||
}, | ||
}, | ||
}); | ||
const todosData = { | ||
__typename: 'Query', | ||
todos: [ | ||
{ id: '0', text: 'Go to the shops', complete: false, __typename: 'Todo' }, | ||
{ id: '1', text: 'Pick up the kids', complete: true, __typename: 'Todo' }, | ||
{ id: '2', text: 'Install urql', complete: false, __typename: 'Todo' }, | ||
], | ||
}; | ||
write(store, { query: Todos }, todosData); | ||
const res = query(store, { query: Todo, variables: { id: '0' } }); | ||
expect(res.data).toEqual({ | ||
__typename: 'Query', | ||
todo: { | ||
id: '0', | ||
text: 'Go to the shops', | ||
complete: false, | ||
__typename: 'Todo', | ||
}, | ||
}); | ||
}); | ||
it('respects property-level resolvers when given', () => { | ||
@@ -215,3 +257,3 @@ const store = new Store(undefined, { | ||
it('respects property-level resolvers when given', () => { | ||
it('respects Mutation update functions', () => { | ||
const store = new Store(undefined, undefined, { | ||
@@ -218,0 +260,0 @@ Mutation: { |
import { DocumentNode, FragmentDefinitionNode, SelectionNode } from 'graphql'; | ||
import { Store } from './store'; | ||
@@ -36,10 +35,11 @@ // Helper types | ||
export interface Variables { | ||
[name: string]: Scalar | Scalar[] | Variables | NullArray<Variables>; | ||
} | ||
export type Data = SystemFields & DataFields; | ||
export type Link<Key = string> = null | Key | NullArray<Key>; | ||
export type ResolvedLink = Link<Data>; | ||
export type Connection = [Variables, string]; | ||
export interface Variables { | ||
[name: string]: Scalar | Scalar[] | Variables | NullArray<Variables>; | ||
} | ||
// This is an input operation | ||
@@ -52,6 +52,64 @@ export interface OperationRequest { | ||
export interface ResolveInfo { | ||
parentTypeName: string; | ||
parentKey: string; | ||
parentFieldKey: string; | ||
fieldName: string; | ||
fragments: Fragments; | ||
variables: Variables; | ||
partial?: boolean; | ||
optimistic?: boolean; | ||
} | ||
export interface QueryInput { | ||
query: string | DocumentNode; | ||
variables?: Variables; | ||
} | ||
export interface Cache { | ||
/** keyOfEntity() returns the key for an entity or null if it's unkeyable */ | ||
keyOfEntity(data: Data): string | null; | ||
/** resolve() retrieves the value (or link) of a field on any entity, given a partial/keyable entity or an entity key */ | ||
resolve( | ||
entity: Data | string | null, | ||
fieldName: string, | ||
args?: Variables | ||
): DataField; | ||
/** resolveValueOrLink() returns a field's value on an entity, given that field's key */ | ||
resolveValueOrLink(fieldKey: string): DataField; | ||
/** resolveConnections() retrieves all known connections (arguments and links) for a given field on an entity */ | ||
resolveConnections( | ||
entity: Data | string | null, | ||
fieldName: string | ||
): Connection[]; | ||
/** invalidateQuery() invalidates all data of a given query */ | ||
invalidateQuery(query: DocumentNode, variables?: Variables): void; | ||
/** updateQuery() can be used to update the data of a given query using an updater function */ | ||
updateQuery( | ||
input: QueryInput, | ||
updater: (data: Data | null) => Data | null | ||
): void; | ||
/** readQuery() retrieves the data for a given query */ | ||
readQuery(input: QueryInput): Data | null; | ||
/** readFragment() retrieves the data for a given fragment, given a partial/keyable entity or an entity key */ | ||
readFragment( | ||
fragment: DocumentNode, | ||
entity: string | Data, | ||
variables?: Variables | ||
): Data | null; | ||
/** writeFragment() can be used to update the data of a given fragment, given an entity that is supposed to be written using the fragment */ | ||
writeFragment( | ||
fragment: DocumentNode, | ||
data: Data, | ||
variables?: Variables | ||
): void; | ||
} | ||
// Cache resolvers are user-defined to overwrite an entity field result | ||
@@ -61,5 +119,5 @@ export type Resolver = ( | ||
args: Variables, | ||
cache: Store, | ||
cache: Cache, | ||
info: ResolveInfo | ||
) => DataField; | ||
) => DataField | undefined; | ||
@@ -75,3 +133,3 @@ export interface ResolverConfig { | ||
args: Variables, | ||
cache: Store, | ||
cache: Cache, | ||
info: ResolveInfo | ||
@@ -93,3 +151,3 @@ ) => void; | ||
vars: Variables, | ||
cache: Store, | ||
cache: Cache, | ||
info: ResolveInfo | ||
@@ -96,0 +154,0 @@ ) => null | Data | NullArray<Data>; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
695453
5
49
67
8338
1
163
45
- Removedfast-json-stable-stringify@^2.0.0
- Removedfast-json-stable-stringify@2.1.0(transitive)