Socket
Socket
Sign inDemoInstall

graphql-hooks

Package Overview
Dependencies
19
Maintainers
8
Versions
85
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 6.1.0 to 6.2.0

163

dist/graphql-hooks.js

@@ -5,3 +5,3 @@ (function (global, factory) {

(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.GraphQLHooks = {}, global.React, global.EventEmitter));
}(this, (function (exports, React, EventEmitter) { 'use strict';
})(this, (function (exports, React, EventEmitter) { 'use strict';

@@ -13,3 +13,3 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

const ClientContext = React__default['default'].createContext(null);
const ClientContext = React__default["default"].createContext(null);
ClientContext.displayName = "ClientContext";

@@ -51,3 +51,2 @@

*/
var ReactNativeFile_1 = class ReactNativeFile {

@@ -63,5 +62,6 @@ constructor({

}
};
var ReactNativeFile = ReactNativeFile_1;
/**

@@ -91,8 +91,9 @@ * Checks if a value is an [extractable file]{@link ExtractableFile}.

*/
var isExtractableFile = function isExtractableFile(value) {
return typeof File !== 'undefined' && value instanceof File || typeof Blob !== 'undefined' && value instanceof Blob || value instanceof ReactNativeFile_1;
return typeof File !== 'undefined' && value instanceof File || typeof Blob !== 'undefined' && value instanceof Blob || value instanceof ReactNativeFile;
};
var isExtractableFile$1 = isExtractableFile;
var defaultIsExtractableFile = isExtractableFile;
/**

@@ -161,11 +162,11 @@ * Clones a value, recursively extracting

*/
var extractFiles = function extractFiles(value, path = '', isExtractableFile = defaultIsExtractableFile) {
// Map of extracted files and their object paths within the input value.
const files = new Map();
var extractFiles = function extractFiles(value, path = '', isExtractableFile$1 = isExtractableFile) {
// Map of extracted files and their object paths within the input value.
const files = new Map(); // Map of arrays and objects recursed within the input value and their clones,
// Map of arrays and objects recursed within the input value and their clones,
// for reusing clones of values that are referenced multiple times within the
// input value.
const clones = new Map();
const clones = new Map();
/**

@@ -181,7 +182,5 @@ * Recursively clones the value, extracting files.

*/
function recurse(value, path, recursed) {
let clone = value;
if (isExtractableFile$1(value)) {
if (isExtractableFile(value)) {
clone = null;

@@ -193,3 +192,2 @@ const filePaths = files.get(value);

const isObject = value && value.constructor === Object;
if (isList || isObject) {

@@ -201,10 +199,7 @@ const hasClone = clones.has(value);

}
if (!recursed.has(value)) {
const pathPrefix = path ? `${path}.` : '';
const recursedDeeper = new Set(recursed).add(value);
if (isList) {
let index = 0;
for (const item of value) {

@@ -221,6 +216,4 @@ const itemClone = recurse(item, pathPrefix + index++, recursedDeeper);

}
return clone;
}
return {

@@ -231,2 +224,3 @@ clone: recurse(value, path, new Set()),

};
var extractFiles$1 = extractFiles;

@@ -237,3 +231,7 @@ var canUseDOM = (function () {

const isExtractableFileEnhanced = (value) => isExtractableFile(value) || value !== null && typeof value === "object" && typeof value.pipe === "function" || value !== null && typeof value === "object" && typeof value.stream === "function";
const isExtractableFileEnhanced = (value) => isExtractableFile$1(value) || // Check if stream
// https://github.com/sindresorhus/is-stream/blob/3750505b0727f6df54324784fe369365ef78841e/index.js#L3
value !== null && typeof value === "object" && typeof value.pipe === "function" || // Check if formdata-node File
// https://github.com/octet-stream/form-data/blob/14a6708f0ae28a5ffded8b6f8156394ba1d1244e/lib/File.ts#L29
value !== null && typeof value === "object" && typeof value.stream === "function";

@@ -248,15 +246,10 @@ function _unsupportedIterableToArray(o, minLen) {

}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (it) return (it = it.call(o)).next.bind(it);
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {

@@ -275,3 +268,2 @@ if (it) o = it;

}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");

@@ -283,3 +275,2 @@ }

var _this = this;
if (fns.length === 0) {

@@ -290,10 +281,7 @@ fns.push(function (_, next) {

}
var _loop = function _loop() {
var fn = _step.value;
if (typeof fn !== "function") {
throw new Error("GraphQLClient Middleware: middleware has to be of type `function`");
}
_this.run = function (stack) {

@@ -307,3 +295,2 @@ return function (opts, next) {

};
for (var _iterator = _createForOfIteratorHelperLoose(fns), _step; !(_step = _iterator()).done;) {

@@ -313,9 +300,15 @@ _loop();

}
/**
* Run middleware
* @param {opts.client} GraphQLClient instance
* @param {opts.operation} Operation object with properties such as query and variables
* @param {opts.resolve} Used to early resolve the request
* @param {opts.addResponseHook} Hook that accepts a function that will be run after response is fetched
* @param {opts.reject} User to early reject the request
* @param {function} next
*/
var _proto = Middleware.prototype;
_proto.run = function run(opts, next) {
next.apply(this, opts);
};
return Middleware;

@@ -375,4 +368,5 @@ }();

this.middleware = new Middleware(config.middleware || []);
this.mutationsEmitter = new EventEmitter__default['default']();
this.mutationsEmitter = new EventEmitter__default["default"]();
}
/** Checks that the given config has the correct required options */
verifyConfig(config) {

@@ -412,2 +406,3 @@ if (!config.url) {

}
/* eslint-disable no-console */
logErrorResult({ result, operation }) {

@@ -439,2 +434,3 @@ console.error("GraphQL Hooks Error");

}
/* eslint-enable no-console */
generateResult({

@@ -471,2 +467,4 @@ fetchError,

}
// Kudos to Jayden Seric (@jaydenseric) for this piece of code.
// See original source: https://github.com/jaydenseric/graphql-react/blob/82d576b5fe6664c4a01cd928d79f33ddc3f7bbfd/src/universal/graphqlFetchOptions.mjs.
getFetchOptions(operation, fetchOptionsOverrides = {}) {

@@ -480,3 +478,3 @@ const fetchOptions = __spreadValues$5(__spreadValues$5({

}
const { clone, files } = extractFiles(
const { clone, files } = extractFiles$1(
operation,

@@ -567,3 +565,6 @@ "",

graphQLErrors: errors,
data: typeof options.responseReducer === "function" && options.responseReducer(data, response) || data
data: (
// enrich data with responseReducer if defined
typeof options.responseReducer === "function" && options.responseReducer(data, response) || data
)
});

@@ -717,3 +718,2 @@ });

var has = Object.prototype.hasOwnProperty;
function find(iter, tar, key) {

@@ -724,11 +724,8 @@ for (key of iter.keys()) {

}
function dequal(foo, bar) {
var ctor, len, tmp;
if (foo === bar) return true;
if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
if (ctor === Date) return foo.getTime() === bar.getTime();
if (ctor === RegExp) return foo.toString() === bar.toString();
if (ctor === Array) {

@@ -738,6 +735,4 @@ if ((len = foo.length) === bar.length) {

}
return len === -1;
}
if (ctor === Set) {

@@ -747,6 +742,4 @@ if (foo.size !== bar.size) {

}
for (len of foo) {
tmp = len;
if (tmp && typeof tmp === 'object') {

@@ -756,9 +749,6 @@ tmp = find(bar, tmp);

}
if (!bar.has(tmp)) return false;
}
return true;
}
if (ctor === Map) {

@@ -768,6 +758,4 @@ if (foo.size !== bar.size) {

}
for (len of foo) {
tmp = len[0];
if (tmp && typeof tmp === 'object') {

@@ -777,3 +765,2 @@ tmp = find(bar, tmp);

}
if (!dequal(len[1], bar.get(tmp))) {

@@ -783,6 +770,4 @@ return false;

}
return true;
}
if (ctor === ArrayBuffer) {

@@ -795,6 +780,4 @@ foo = new Uint8Array(foo);

}
return len === -1;
}
if (ArrayBuffer.isView(foo)) {

@@ -804,9 +787,6 @@ if ((len = foo.byteLength) === bar.byteLength) {

}
return len === -1;
}
if (!ctor || typeof foo === 'object') {
len = 0;
for (ctor in foo) {

@@ -816,7 +796,5 @@ if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;

}
return Object.keys(bar).length === len;
}
}
return foo !== foo && bar !== bar;

@@ -889,7 +867,7 @@ }

function useDeepCompareCallback(callback, deps) {
const ref = React__default['default'].useRef();
const ref = React__default["default"].useRef();
if (!dequal(deps, ref.current)) {
ref.current = deps;
}
return React__default['default'].useCallback(callback, ref.current);
return React__default["default"].useCallback(callback, ref.current);
}

@@ -902,3 +880,3 @@ function useClientRequest(query, initialOpts = {}) {

}
const contextClient = React__default['default'].useContext(ClientContext);
const contextClient = React__default["default"].useContext(ClientContext);
const client = initialOpts.client || contextClient;

@@ -910,4 +888,4 @@ if (client === null || client === void 0) {

}
const isMounted = React__default['default'].useRef(true);
const activeCacheKey = React__default['default'].useRef(null);
const isMounted = React__default["default"].useRef(true);
const activeCacheKey = React__default["default"].useRef(null);
const operation = {

@@ -931,5 +909,5 @@ query,

});
const [state, dispatch] = React__default['default'].useReducer(reducer, initialState);
const [state, dispatch] = React__default["default"].useReducer(reducer, initialState);
const stringifiedCacheKey = JSON.stringify(cacheKey);
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
if (!initialOpts.updateData) {

@@ -939,3 +917,3 @@ dispatch({ type: actionTypes.RESET_STATE, initialState });

}, [stringifiedCacheKey]);
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
isMounted.current = true;

@@ -1016,3 +994,3 @@ return () => {

);
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
if (state.useCache && !client.ssrMode) {

@@ -1026,3 +1004,3 @@ client.saveCache(state.cacheKey, state);

});
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
const handleEvents = (payload, actionType) => {

@@ -1036,10 +1014,13 @@ dispatch({

const dataUpdatedCallback = (payload) => handleEvents(payload, actionTypes.CACHE_HIT);
client.mutationsEmitter.on(Events.DATA_INVALIDATED, dataInvalidatedCallback);
client.mutationsEmitter.on(Events.DATA_UPDATED, dataUpdatedCallback);
const mutationsEmitter = client.mutationsEmitter;
mutationsEmitter.on(Events.DATA_INVALIDATED, dataInvalidatedCallback);
mutationsEmitter.on(Events.DATA_UPDATED, dataUpdatedCallback);
return () => {
client.mutationsEmitter.off(
Events.DATA_INVALIDATED,
dataInvalidatedCallback
);
client.mutationsEmitter.off(Events.DATA_UPDATED, dataUpdatedCallback);
if (mutationsEmitter) {
mutationsEmitter.removeListener(
Events.DATA_INVALIDATED,
dataInvalidatedCallback
);
mutationsEmitter.removeListener(Events.DATA_UPDATED, dataUpdatedCallback);
}
};

@@ -1056,3 +1037,2 @@ }, []);

var paramType = typeof mutationInfo;
if (paramType === "string") {

@@ -1062,5 +1042,5 @@ result[mutationInfo] = {};

var filter = mutationInfo.filter,
mutation = mutationInfo.mutation,
_mutationInfo$refetch = mutationInfo.refetchOnMutationError,
refetchOnMutationError = _mutationInfo$refetch === void 0 ? true : _mutationInfo$refetch;
mutation = mutationInfo.mutation,
_mutationInfo$refetch = mutationInfo.refetchOnMutationError,
refetchOnMutationError = _mutationInfo$refetch === void 0 ? true : _mutationInfo$refetch;
result[mutation] = {

@@ -1101,5 +1081,5 @@ filter: filter,

const allOpts = __spreadValues$2(__spreadValues$2({}, defaultOpts), opts);
const contextClient = React__default['default'].useContext(ClientContext);
const contextClient = React__default["default"].useContext(ClientContext);
const client = opts.client || contextClient;
const [calledDuringSSR, setCalledDuringSSR] = React__default['default'].useState(false);
const [calledDuringSSR, setCalledDuringSSR] = React__default["default"].useState(false);
const [queryReq, state] = useClientRequest(query, allOpts);

@@ -1119,3 +1099,3 @@ if (!client) {

const stringifiedAllOpts = JSON.stringify(allOpts);
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
if (allOpts.skip) {

@@ -1126,3 +1106,3 @@ return;

}, [query, stringifiedAllOpts]);
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
if (state.error && allOpts.throwErrors) {

@@ -1132,5 +1112,8 @@ throw state.error;

}, [state.error, allOpts.throwErrors]);
const refetch = React__default['default'].useCallback(
const refetch = React__default["default"].useCallback(
(options = {}) => queryReq(__spreadValues$2({
skipCache: true,
// don't call the updateData that has been passed into useQuery here
// reset to the default behaviour of returning the raw query result
// this can be overridden in refetch options
updateData: (_, data) => data

@@ -1140,3 +1123,3 @@ }, options)),

);
React__default['default'].useEffect(
React__default["default"].useEffect(
function subscribeToMutationsAndRefetch() {

@@ -1258,2 +1241,2 @@ const mutationsMap = createRefetchMutationsMap(opts.refetchAfterMutations);

})));
}));

@@ -1,1 +0,1 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("events")):"function"==typeof define&&define.amd?define(["exports","react","events"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GraphQLHooks={},e.React,e.EventEmitter)}(this,(function(e,t,r){"use strict";function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(t),i=o(r);const s=n.default.createContext(null);s.displayName="ClientContext";var a=function(e){return"undefined"!=typeof File&&e instanceof File||"undefined"!=typeof Blob&&e instanceof Blob||e instanceof class{constructor({uri:e,name:t,type:r}){this.uri=e,this.name=t,this.type=r}}};const u=e=>a(e)||null!==e&&"object"==typeof e&&"function"==typeof e.pipe||null!==e&&"object"==typeof e&&"function"==typeof e.stream;function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,o=Array(t);t>r;r++)o[r]=e[r];return o}function l(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return c(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?c(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var o=0;return function(){return e.length>o?{done:!1,value:e[o++]}:{done:!0}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var f=function(){function e(e){var t=this;0===e.length&&e.push((function(e,t){return t()}));for(var r,o=function(){var e,o=r.value;if("function"!=typeof o)throw Error("GraphQLClient Middleware: middleware has to be of type `function`");t.run=(e=t.run,function(r,n){e(r,(function(){o.call(t,r,n.bind.call(n,null,r))}))})},n=l(e);!(r=n()).done;)o()}return e.prototype.run=function(e,t){t.apply(this,e)},e}();var h=(e=>(e.DATA_INVALIDATED="DATA_INVALIDATED",e.DATA_UPDATED="DATA_UPDATED",e))(h||{}),p=Object.defineProperty,d=Object.defineProperties,y=Object.getOwnPropertyDescriptors,b=Object.getOwnPropertySymbols,E=Object.prototype.hasOwnProperty,m=Object.prototype.propertyIsEnumerable,g=(e,t,r)=>t in e?p(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,v=(e,t)=>{for(var r in t||(t={}))E.call(t,r)&&g(e,r,t[r]);if(b)for(var r of b(t))m.call(t,r)&&g(e,r,t[r]);return e};class O{constructor(e){if(!e)throw Error("GraphQLClient: config is required as first parameter");this.fullWsTransport=e.fullWsTransport,this.subscriptionClient="function"==typeof e.subscriptionClient?e.subscriptionClient():e.subscriptionClient,this.verifyConfig(e),this.cache=e.cache,this.headers=e.headers||{},this.ssrMode=e.ssrMode,this.ssrPromises=[],this.url=e.url,this.fetch=e.fetch||("undefined"!=typeof fetch&&fetch?fetch.bind(void 0):void 0),this.fetchOptions=e.fetchOptions||{},this.FormData=e.FormData||("undefined"!=typeof FormData?FormData:void 0),this.logErrors=void 0===e.logErrors||e.logErrors,this.onError=e.onError,this.useGETForQueries=!0===e.useGETForQueries,this.middleware=new f(e.middleware||[]),this.mutationsEmitter=new i.default}verifyConfig(e){if(!e.url){if(!this.fullWsTransport)throw Error("GraphQLClient: config.url is required");if(!this.subscriptionClient)throw Error("GraphQLClient: subscriptionClient is required")}if(e.fetch&&"function"!=typeof e.fetch)throw Error("GraphQLClient: config.fetch must be a function");if(("undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement||e.ssrMode)&&!e.fetch&&"function"!=typeof fetch)throw Error("GraphQLClient: fetch must be polyfilled or passed in new GraphQLClient({ fetch })");if(e.ssrMode&&!e.cache)throw Error("GraphQLClient: config.cache is required when in ssrMode")}setHeader(e,t){return this.headers[e]=t,this}setHeaders(e){return this.headers=e,this}removeHeader(e){return delete this.headers[e],this}logErrorResult({result:e,operation:t}){console.error("GraphQL Hooks Error"),console.groupCollapsed("---\x3e Full Error Details"),console.groupCollapsed("Operation:"),console.log(t),console.groupEnd();const r=e.error;r&&(r.fetchError&&(console.groupCollapsed("FETCH ERROR:"),console.log(r.fetchError),console.groupEnd()),r.httpError&&(console.groupCollapsed("HTTP ERROR:"),console.log(r.httpError),console.groupEnd()),r.graphQLErrors&&r.graphQLErrors.length>0&&(console.groupCollapsed("GRAPHQL ERROR:"),r.graphQLErrors.forEach((e=>console.log(e))),console.groupEnd())),console.groupEnd()}generateResult({fetchError:e,httpError:t,graphQLErrors:r,data:o}){return!!(r&&r.length>0||e||t)?{data:o,error:{fetchError:e,httpError:t,graphQLErrors:r}}:{data:o}}getCacheKey(e,t={}){return{operation:e,fetchOptions:v(v({},this.fetchOptions),t.fetchOptionsOverrides)}}getCache(e){const t=this.cache?this.cache.get(e):null;if(t)return t}saveCache(e,t){this.cache&&this.cache.set(e,t)}removeCache(e){var t;null==(t=this.cache)||t.delete(e)}getFetchOptions(e,t={}){const r=v(v({method:"POST",headers:v({},this.headers)},this.fetchOptions),t);if("GET"===r.method)return r;const{clone:o,files:n}=function(e,t="",r=a){const o=new Map,n=new Map;return{clone:function e(t,i,s){let a=t;if(r(t)){a=null;const e=o.get(t);e?e.push(i):o.set(t,[i])}else{const r=Array.isArray(t)||"undefined"!=typeof FileList&&t instanceof FileList,o=t&&t.constructor===Object;if(r||o){const o=n.has(t);if(o?a=n.get(t):(a=r?[]:{},n.set(t,a)),!s.has(t)){const n=i?i+".":"",u=new Set(s).add(t);if(r){let r=0;for(const i of t){const t=e(i,n+r++,u);o||a.push(t)}}else for(const r in t){const i=e(t[r],n+r,u);o||(a[r]=i)}}}}return a}(e,t,new Set),files:o}}(e,"",u),i=JSON.stringify(o);if(n.size){if(!this.FormData)throw Error("GraphQLClient: FormData must be polyfilled or passed in new GraphQLClient({ FormData })");const e=new this.FormData;e.append("operations",i);const t={};let o=0;n.forEach((e=>{t[++o]=e})),e.append("map",JSON.stringify(t)),o=0,n.forEach(((t,r)=>{e.append(""+ ++o,r,r.name)})),r.body=e}else r.headers["Content-Type"]="application/json",r.body=i;return r}request(e,t){const r=[],o=e=>r.push(e);return new Promise(((n,i)=>this.middleware.run({operation:e,client:this,addResponseHook:o,resolve:n,reject:i},(({operation:e})=>{const o=e=>{return r.length>0?(t=r,e=>t.reduce(((e,t)=>e.then(t)),Promise.resolve(e)))(e):e;var t};return this.fullWsTransport?this.requestViaWS(e).then(o).then(n).catch(i):this.url?this.requestViaHttp(e,t).then(o).then(n).catch(i):void i(Error("GraphQLClient: config.url is required"))}))))}requestViaHttp(e,t={}){let r=this.url;const o=this.getFetchOptions(e,t.fetchOptionsOverrides);if("GET"===o.method){r=r+"?"+Object.entries(e).filter((([,e])=>!!e)).map((([e,t])=>("variables"!==e&&"extensions"!==e||(t=JSON.stringify(t)),`${e}=${encodeURIComponent(t)}`))).join("&")}return this.fetch(r,o).then((e=>e.ok?e.json().then((({errors:r,data:o})=>this.generateResult({graphQLErrors:r,data:"function"==typeof t.responseReducer&&t.responseReducer(o,e)||o}))):e.text().then((t=>{const{status:r,statusText:o}=e;return this.generateResult({httpError:{status:r,statusText:o,body:t}})})))).catch((e=>this.generateResult({fetchError:e}))).then((t=>(t.error&&(this.logErrors&&this.logErrorResult({result:t,operation:e}),this.onError&&this.onError({result:t,operation:e})),t)))}requestViaWS(e){return new Promise(((t,r)=>{let o;try{const n=this.createSubscription(e).subscribe({next:e=>{o=e},error:r,complete:()=>{n.unsubscribe(),t(o)}})}catch(e){r(e)}}))}createSubscription(e){if(!this.subscriptionClient)throw Error("No SubscriptionClient! Please set in the constructor.");return"function"==typeof this.subscriptionClient.subscribe?{subscribe:t=>({unsubscribe:this.subscriptionClient.subscribe(e,t)})}:this.subscriptionClient.request(e)}invalidateQuery(e){const t="string"==typeof e?{query:e}:e,r=this.getCacheKey(t);this.cache&&r&&(this.removeCache(r),this.request(t).then((e=>{this.mutationsEmitter.emit(h.DATA_INVALIDATED,e)})).catch((e=>console.error(e))))}setQueryData(e,t){const r=this.getCacheKey("string"==typeof e?{query:e}:e);if(this.cache&&r){const e=this.cache.get(r),i=(o=v({},e),n={data:t(e.data||null)},d(o,y(n)));this.saveCache(r,i),this.mutationsEmitter.emit(h.DATA_UPDATED,i)}var o,n}}class C{constructor(e){this.fetchError=e.fetchError,this.httpError=e.httpError,this.graphQLErrors=e.graphQLErrors}}var w=Object.defineProperty,D=Object.getOwnPropertySymbols,A=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable,T=(e,t,r)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var L=Object.prototype.hasOwnProperty;function S(e,t,r){for(r of e.keys())if(P(r,t))return r}function P(e,t){var r,o,n;if(e===t)return!0;if(e&&t&&(r=e.constructor)===t.constructor){if(r===Date)return e.getTime()===t.getTime();if(r===RegExp)return""+e==""+t;if(r===Array){if((o=e.length)===t.length)for(;o--&&P(e[o],t[o]););return-1===o}if(r===Set){if(e.size!==t.size)return!1;for(o of e){if((n=o)&&"object"==typeof n&&!(n=S(t,n)))return!1;if(!t.has(n))return!1}return!0}if(r===Map){if(e.size!==t.size)return!1;for(o of e){if((n=o[0])&&"object"==typeof n&&!(n=S(t,n)))return!1;if(!P(o[1],t.get(n)))return!1}return!0}if(r===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(r===DataView){if((o=e.byteLength)===t.byteLength)for(;o--&&e.getInt8(o)===t.getInt8(o););return-1===o}if(ArrayBuffer.isView(e)){if((o=e.byteLength)===t.byteLength)for(;o--&&e[o]===t[o];);return-1===o}if(!r||"object"==typeof e){for(r in o=0,e){if(L.call(e,r)&&++o&&!L.call(t,r))return!1;if(!(r in t)||!P(e[r],t[r]))return!1}return Object.keys(t).length===o}}return e!=e&&t!=t}var Q=Object.defineProperty,q=Object.defineProperties,R=Object.getOwnPropertyDescriptors,M=Object.getOwnPropertySymbols,G=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable,x=(e,t,r)=>t in e?Q(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,k=(e,t)=>{for(var r in t||(t={}))G.call(t,r)&&x(e,r,t[r]);if(M)for(var r of M(t))I.call(t,r)&&x(e,r,t[r]);return e},F=(e,t)=>q(e,R(t));const N="RESET_STATE",H="LOADING",_="CACHE_HIT",U="REQUEST_RESULT";function V(e,t){switch(t.type){case N:return e.loading?e:t.initialState;case H:return e.error?F(k({},t.initialState),{data:e.data,loading:!0}):e.loading?e:F(k({},e),{loading:!0});case _:return e.cacheHit&&!t.resetState?e:F(k({},t.result),{cacheHit:!0,loading:!1});case U:return F(k({},t.result),{data:e.data&&t.result.data&&t.updateData?t.updateData(e.data,t.result.data):t.result.data,cacheHit:!1,loading:!1});default:return e}}function K(e,t={}){if("string"!=typeof e)throw Error("Your query must be a string. If you are using the `gql` template literal from graphql-tag, remove it from your query.");const r=n.default.useContext(s),o=t.client||r;if(null==o)throw Error("A client must be provided in order to use the useClientRequest hook.");const i=n.default.useRef(!0),a=n.default.useRef(null),u={query:e,variables:t.variables,operationName:t.operationName,persisted:t.persisted};(t.persisted||o.useGETForQueries&&!t.isMutation)&&(t.fetchOptionsOverrides=F(k({},t.fetchOptionsOverrides),{method:"GET"}));const c=o.getCacheKey(u,t),l=t.isMutation||t.isManual||t.skip,f=!t.skipCache&&o.cache&&c?o.cache.get(c):null,p=F(k({},f),{cacheHit:!!f,loading:!l&&!f}),[d,y]=n.default.useReducer(V,p),b=JSON.stringify(c);n.default.useEffect((()=>{t.updateData||y({type:N,initialState:p})}),[b]),n.default.useEffect((()=>(i.current=!0,()=>{i.current=!1})),[]);const E=function(e,t){const r=n.default.useRef();return P(t,r.current)||(r.current=t),n.default.useCallback(e,r.current)}((r=>{const n=k(k({},t),r),s=F(k({},u),{variables:n.variables,operationName:n.operationName});if(!i.current)return Promise.resolve({error:{fetchError:Error("fetchData should not be called after hook unmounted")},loading:!1,cacheHit:!1});const c=o.getCacheKey(s,n);a.current=c;const l=n.skipCache?null:o.getCache(c);return l?(y({type:_,result:l,resetState:b!==JSON.stringify(d.cacheKey)}),Promise.resolve(l)):(y({type:H,initialState:p}),o.request(s,n).then((r=>{if(n.updateData&&"function"!=typeof n.updateData)throw Error("options.updateData must be a function");const u=k({},r);if(n.useCache&&(u.useCache=!0,u.cacheKey=c,o.ssrMode)){const e={error:u.error,data:n.updateData?n.updateData(d.data,u.data):u.data};o.saveCache(c,e)}if(i.current&&c===a.current&&y({type:U,updateData:n.updateData,result:u}),t.isMutation&&o.mutationsEmitter.emit(e,F(k({},s),{mutation:e,result:u})),!(null==r?void 0:r.error)&&n.onSuccess){if("function"!=typeof n.onSuccess)throw Error("options.onSuccess must be a function");n.onSuccess(r,s.variables)}return r})))}),[o,t,u]);n.default.useEffect((()=>{d.useCache&&!o.ssrMode&&o.saveCache(d.cacheKey,d)}),[o,d]);return n.default.useEffect((()=>{const e=(e,t)=>{y({type:t,result:e})},t=t=>e(t,U),r=t=>e(t,_);return o.mutationsEmitter.on(h.DATA_INVALIDATED,t),o.mutationsEmitter.on(h.DATA_UPDATED,r),()=>{o.mutationsEmitter.off(h.DATA_INVALIDATED,t),o.mutationsEmitter.off(h.DATA_UPDATED,r)}}),[]),[E,d,(e={})=>y({type:N,initialState:k(k({},p),e)})]}var J=Object.defineProperty,W=Object.defineProperties,z=Object.getOwnPropertyDescriptors,B=Object.getOwnPropertySymbols,$=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable,X=(e,t,r)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Z=(e,t)=>{for(var r in t||(t={}))$.call(t,r)&&X(e,r,t[r]);if(B)for(var r of B(t))Y.call(t,r)&&X(e,r,t[r]);return e};const ee={useCache:!0,skip:!1,throwErrors:!1};var te=Object.defineProperty,re=Object.getOwnPropertySymbols,oe=Object.prototype.hasOwnProperty,ne=Object.prototype.propertyIsEnumerable,ie=(e,t,r)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var se=Object.defineProperty,ae=Object.getOwnPropertySymbols,ue=Object.prototype.hasOwnProperty,ce=Object.prototype.propertyIsEnumerable,le=(e,t,r)=>t in e?se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;e.ClientContext=s,e.GraphQLClient=O,e.LocalGraphQLClient=class extends O{constructor(e){if(super(((e,t)=>{for(var r in t||(t={}))A.call(t,r)&&T(e,r,t[r]);if(D)for(var r of D(t))j.call(t,r)&&T(e,r,t[r]);return e})({url:""},e)),this.localQueries=e.localQueries,this.requestDelayMs=e.requestDelayMs||0,!this.localQueries)throw Error("LocalGraphQLClient: `localQueries` object required in the constructor options")}verifyConfig(){}request(e){if(!this.localQueries[e.query])throw Error("LocalGraphQLClient: no query match for: "+e.query);return(t=this.requestDelayMs,new Promise((e=>{setTimeout(e,t)}))).then((()=>Promise.resolve(this.localQueries[e.query](e.variables,e.operationName)))).then((e=>e instanceof C?{error:e}:{data:e}));var t}},e.LocalGraphQLError=C,e.useClientRequest=K,e.useManualQuery=(e,t={})=>K(e,((e,t)=>{for(var r in t||(t={}))ue.call(t,r)&&le(e,r,t[r]);if(ae)for(var r of ae(t))ce.call(t,r)&&le(e,r,t[r]);return e})({useCache:!0,isManual:!0},t)),e.useMutation=(e,t={})=>K(e,((e,t)=>{for(var r in t||(t={}))oe.call(t,r)&&ie(e,r,t[r]);if(re)for(var r of re(t))ne.call(t,r)&&ie(e,r,t[r]);return e})({isMutation:!0},t)),e.useQuery=function(e,t={}){const r=Z(Z({},ee),t),o=n.default.useContext(s),i=t.client||o,[a,u]=n.default.useState(!1),[c,l]=K(e,r);if(!i)throw Error("useQuery() requires a client to be passed in the options or as a context value");if(i.ssrMode&&!1!==t.ssr&&!a&&!t.skipCache&&!t.skip){if(!l.data&&!l.error){const e=c();i.ssrPromises.push(e)}u(!0)}const f=JSON.stringify(r);n.default.useEffect((()=>{r.skip||c()}),[e,f]),n.default.useEffect((()=>{if(l.error&&r.throwErrors)throw l.error}),[l.error,r.throwErrors]);const h=n.default.useCallback(((e={})=>c(Z({skipCache:!0,updateData:(e,t)=>t},e))),[c]);return n.default.useEffect((function(){const e=(o={},(Array.isArray(r=t.refetchAfterMutations)?r:[r]).forEach((function(e){if(null!=e){var t=typeof e;if("string"===t)o[e]={};else if("object"===t){var r=e.refetchOnMutationError;o[e.mutation]={filter:e.filter,refetchOnMutationError:void 0===r||r}}}})),o);var r,o;const n=Object.keys(e),s=({mutation:t,variables:r,result:o})=>{const{filter:n,refetchOnMutationError:i}=e[t];(!n||r&&n(r))&&(i||!o.error)&&h()};return n.forEach((e=>{i.mutationsEmitter.on(e,s)})),()=>{n.forEach((e=>{i.mutationsEmitter.removeListener(e,s)}))}}),[t.refetchAfterMutations,h,i.mutationsEmitter]),p=Z({},l),W(p,z({refetch:h}));var p},e.useQueryClient=function(){return t.useContext(s)},e.useSubscription=function(e,r){const o=t.useRef(r);o.current=r;const n=t.useContext(s),i=e.client||n;if(!i)throw Error("useSubscription() requires a client to be passed in the options or as a context value");const a={query:e.query,variables:e.variables};t.useEffect((()=>{const e=i.createSubscription(a).subscribe({next:e=>{o.current(e)},error:e=>{o.current({errors:e})},complete:()=>{e.unsubscribe()}});return()=>{e.unsubscribe()}}),[])},Object.defineProperty(e,"__esModule",{value:!0})}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("events")):"function"==typeof define&&define.amd?define(["exports","react","events"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GraphQLHooks={},e.React,e.EventEmitter)}(this,(function(e,t,r){"use strict";function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(t),i=o(r);const s=n.default.createContext(null);s.displayName="ClientContext";var a=class{constructor({uri:e,name:t,type:r}){this.uri=e,this.name=t,this.type=r}},u=function(e){return"undefined"!=typeof File&&e instanceof File||"undefined"!=typeof Blob&&e instanceof Blob||e instanceof a},c=u,l=u,f=function(e,t="",r=l){const o=new Map,n=new Map;return{clone:function e(t,i,s){let a=t;if(r(t)){a=null;const e=o.get(t);e?e.push(i):o.set(t,[i])}else{const r=Array.isArray(t)||"undefined"!=typeof FileList&&t instanceof FileList;if(r||t&&t.constructor===Object){const o=n.has(t);if(o?a=n.get(t):(a=r?[]:{},n.set(t,a)),!s.has(t)){const n=i?i+".":"",u=new Set(s).add(t);if(r){let r=0;for(const i of t){const t=e(i,n+r++,u);o||a.push(t)}}else for(const r in t){const i=e(t[r],n+r,u);o||(a[r]=i)}}}}return a}(e,t,new Set),files:o}};const h=e=>c(e)||null!==e&&"object"==typeof e&&"function"==typeof e.pipe||null!==e&&"object"==typeof e&&"function"==typeof e.stream;function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,o=Array(t);t>r;r++)o[r]=e[r];return o}function d(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return p(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?p(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var o=0;return function(){return e.length>o?{done:!1,value:e[o++]}:{done:!0}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var y=function(){function e(e){var t=this;0===e.length&&e.push((function(e,t){return t()}));for(var r,o=function(){var e,o=r.value;if("function"!=typeof o)throw Error("GraphQLClient Middleware: middleware has to be of type `function`");t.run=(e=t.run,function(r,n){e(r,(function(){o.call(t,r,n.bind.call(n,null,r))}))})},n=d(e);!(r=n()).done;)o()}return e.prototype.run=function(e,t){t.apply(this,e)},e}();var b=(e=>(e.DATA_INVALIDATED="DATA_INVALIDATED",e.DATA_UPDATED="DATA_UPDATED",e))(b||{}),E=Object.defineProperty,m=Object.defineProperties,g=Object.getOwnPropertyDescriptors,v=Object.getOwnPropertySymbols,O=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable,w=(e,t,r)=>t in e?E(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,T=(e,t)=>{for(var r in t||(t={}))O.call(t,r)&&w(e,r,t[r]);if(v)for(var r of v(t))C.call(t,r)&&w(e,r,t[r]);return e};class A{constructor(e){if(!e)throw Error("GraphQLClient: config is required as first parameter");this.fullWsTransport=e.fullWsTransport,this.subscriptionClient="function"==typeof e.subscriptionClient?e.subscriptionClient():e.subscriptionClient,this.verifyConfig(e),this.cache=e.cache,this.headers=e.headers||{},this.ssrMode=e.ssrMode,this.ssrPromises=[],this.url=e.url,this.fetch=e.fetch||("undefined"!=typeof fetch&&fetch?fetch.bind(void 0):void 0),this.fetchOptions=e.fetchOptions||{},this.FormData=e.FormData||("undefined"!=typeof FormData?FormData:void 0),this.logErrors=void 0===e.logErrors||e.logErrors,this.onError=e.onError,this.useGETForQueries=!0===e.useGETForQueries,this.middleware=new y(e.middleware||[]),this.mutationsEmitter=new i.default}verifyConfig(e){if(!e.url){if(!this.fullWsTransport)throw Error("GraphQLClient: config.url is required");if(!this.subscriptionClient)throw Error("GraphQLClient: subscriptionClient is required")}if(e.fetch&&"function"!=typeof e.fetch)throw Error("GraphQLClient: config.fetch must be a function");if(("undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement||e.ssrMode)&&!e.fetch&&"function"!=typeof fetch)throw Error("GraphQLClient: fetch must be polyfilled or passed in new GraphQLClient({ fetch })");if(e.ssrMode&&!e.cache)throw Error("GraphQLClient: config.cache is required when in ssrMode")}setHeader(e,t){return this.headers[e]=t,this}setHeaders(e){return this.headers=e,this}removeHeader(e){return delete this.headers[e],this}logErrorResult({result:e,operation:t}){console.error("GraphQL Hooks Error"),console.groupCollapsed("---\x3e Full Error Details"),console.groupCollapsed("Operation:"),console.log(t),console.groupEnd();const r=e.error;r&&(r.fetchError&&(console.groupCollapsed("FETCH ERROR:"),console.log(r.fetchError),console.groupEnd()),r.httpError&&(console.groupCollapsed("HTTP ERROR:"),console.log(r.httpError),console.groupEnd()),r.graphQLErrors&&r.graphQLErrors.length>0&&(console.groupCollapsed("GRAPHQL ERROR:"),r.graphQLErrors.forEach((e=>console.log(e))),console.groupEnd())),console.groupEnd()}generateResult({fetchError:e,httpError:t,graphQLErrors:r,data:o}){return!!(r&&r.length>0||e||t)?{data:o,error:{fetchError:e,httpError:t,graphQLErrors:r}}:{data:o}}getCacheKey(e,t={}){return{operation:e,fetchOptions:T(T({},this.fetchOptions),t.fetchOptionsOverrides)}}getCache(e){const t=this.cache?this.cache.get(e):null;if(t)return t}saveCache(e,t){this.cache&&this.cache.set(e,t)}removeCache(e){var t;null==(t=this.cache)||t.delete(e)}getFetchOptions(e,t={}){const r=T(T({method:"POST",headers:T({},this.headers)},this.fetchOptions),t);if("GET"===r.method)return r;const{clone:o,files:n}=f(e,"",h),i=JSON.stringify(o);if(n.size){if(!this.FormData)throw Error("GraphQLClient: FormData must be polyfilled or passed in new GraphQLClient({ FormData })");const e=new this.FormData;e.append("operations",i);const t={};let o=0;n.forEach((e=>{t[++o]=e})),e.append("map",JSON.stringify(t)),o=0,n.forEach(((t,r)=>{e.append(""+ ++o,r,r.name)})),r.body=e}else r.headers["Content-Type"]="application/json",r.body=i;return r}request(e,t){const r=[],o=e=>r.push(e);return new Promise(((n,i)=>this.middleware.run({operation:e,client:this,addResponseHook:o,resolve:n,reject:i},(({operation:e})=>{const o=e=>{return r.length>0?(t=r,e=>t.reduce(((e,t)=>e.then(t)),Promise.resolve(e)))(e):e;var t};return this.fullWsTransport?this.requestViaWS(e).then(o).then(n).catch(i):this.url?this.requestViaHttp(e,t).then(o).then(n).catch(i):void i(Error("GraphQLClient: config.url is required"))}))))}requestViaHttp(e,t={}){let r=this.url;const o=this.getFetchOptions(e,t.fetchOptionsOverrides);if("GET"===o.method){r=r+"?"+Object.entries(e).filter((([,e])=>!!e)).map((([e,t])=>("variables"!==e&&"extensions"!==e||(t=JSON.stringify(t)),`${e}=${encodeURIComponent(t)}`))).join("&")}return this.fetch(r,o).then((e=>e.ok?e.json().then((({errors:r,data:o})=>this.generateResult({graphQLErrors:r,data:"function"==typeof t.responseReducer&&t.responseReducer(o,e)||o}))):e.text().then((t=>{const{status:r,statusText:o}=e;return this.generateResult({httpError:{status:r,statusText:o,body:t}})})))).catch((e=>this.generateResult({fetchError:e}))).then((t=>(t.error&&(this.logErrors&&this.logErrorResult({result:t,operation:e}),this.onError&&this.onError({result:t,operation:e})),t)))}requestViaWS(e){return new Promise(((t,r)=>{let o;try{const n=this.createSubscription(e).subscribe({next:e=>{o=e},error:r,complete:()=>{n.unsubscribe(),t(o)}})}catch(e){r(e)}}))}createSubscription(e){if(!this.subscriptionClient)throw Error("No SubscriptionClient! Please set in the constructor.");return"function"==typeof this.subscriptionClient.subscribe?{subscribe:t=>({unsubscribe:this.subscriptionClient.subscribe(e,t)})}:this.subscriptionClient.request(e)}invalidateQuery(e){const t="string"==typeof e?{query:e}:e,r=this.getCacheKey(t);this.cache&&r&&(this.removeCache(r),this.request(t).then((e=>{this.mutationsEmitter.emit(b.DATA_INVALIDATED,e)})).catch((e=>console.error(e))))}setQueryData(e,t){const r=this.getCacheKey("string"==typeof e?{query:e}:e);if(this.cache&&r){const e=this.cache.get(r),i=(o=T({},e),n={data:t(e.data||null)},m(o,g(n)));this.saveCache(r,i),this.mutationsEmitter.emit(b.DATA_UPDATED,i)}var o,n}}class D{constructor(e){this.fetchError=e.fetchError,this.httpError=e.httpError,this.graphQLErrors=e.graphQLErrors}}var S=Object.defineProperty,L=Object.getOwnPropertySymbols,j=Object.prototype.hasOwnProperty,Q=Object.prototype.propertyIsEnumerable,P=(e,t,r)=>t in e?S(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var R=Object.prototype.hasOwnProperty;function q(e,t,r){for(r of e.keys())if(I(r,t))return r}function I(e,t){var r,o,n;if(e===t)return!0;if(e&&t&&(r=e.constructor)===t.constructor){if(r===Date)return e.getTime()===t.getTime();if(r===RegExp)return""+e==""+t;if(r===Array){if((o=e.length)===t.length)for(;o--&&I(e[o],t[o]););return-1===o}if(r===Set){if(e.size!==t.size)return!1;for(o of e){if((n=o)&&"object"==typeof n&&!(n=q(t,n)))return!1;if(!t.has(n))return!1}return!0}if(r===Map){if(e.size!==t.size)return!1;for(o of e){if((n=o[0])&&"object"==typeof n&&!(n=q(t,n)))return!1;if(!I(o[1],t.get(n)))return!1}return!0}if(r===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(r===DataView){if((o=e.byteLength)===t.byteLength)for(;o--&&e.getInt8(o)===t.getInt8(o););return-1===o}if(ArrayBuffer.isView(e)){if((o=e.byteLength)===t.byteLength)for(;o--&&e[o]===t[o];);return-1===o}if(!r||"object"==typeof e){for(r in o=0,e){if(R.call(e,r)&&++o&&!R.call(t,r))return!1;if(!(r in t)||!I(e[r],t[r]))return!1}return Object.keys(t).length===o}}return e!=e&&t!=t}var M=Object.defineProperty,G=Object.defineProperties,_=Object.getOwnPropertyDescriptors,H=Object.getOwnPropertySymbols,x=Object.prototype.hasOwnProperty,N=Object.prototype.propertyIsEnumerable,k=(e,t,r)=>t in e?M(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,F=(e,t)=>{for(var r in t||(t={}))x.call(t,r)&&k(e,r,t[r]);if(H)for(var r of H(t))N.call(t,r)&&k(e,r,t[r]);return e},U=(e,t)=>G(e,_(t));const V={RESET_STATE:"RESET_STATE",LOADING:"LOADING",CACHE_HIT:"CACHE_HIT",REQUEST_RESULT:"REQUEST_RESULT"};function K(e,t){switch(t.type){case V.RESET_STATE:return e.loading?e:t.initialState;case V.LOADING:return e.error?U(F({},t.initialState),{data:e.data,loading:!0}):e.loading?e:U(F({},e),{loading:!0});case V.CACHE_HIT:return e.cacheHit&&!t.resetState?e:U(F({},t.result),{cacheHit:!0,loading:!1});case V.REQUEST_RESULT:return U(F({},t.result),{data:e.data&&t.result.data&&t.updateData?t.updateData(e.data,t.result.data):t.result.data,cacheHit:!1,loading:!1});default:return e}}function J(e,t={}){if("string"!=typeof e)throw Error("Your query must be a string. If you are using the `gql` template literal from graphql-tag, remove it from your query.");const r=n.default.useContext(s),o=t.client||r;if(null==o)throw Error("A client must be provided in order to use the useClientRequest hook.");const i=n.default.useRef(!0),a=n.default.useRef(null),u={query:e,variables:t.variables,operationName:t.operationName,persisted:t.persisted};(t.persisted||o.useGETForQueries&&!t.isMutation)&&(t.fetchOptionsOverrides=U(F({},t.fetchOptionsOverrides),{method:"GET"}));const c=o.getCacheKey(u,t),l=t.isMutation||t.isManual||t.skip,f=!t.skipCache&&o.cache&&c?o.cache.get(c):null,h=U(F({},f),{cacheHit:!!f,loading:!l&&!f}),[p,d]=n.default.useReducer(K,h),y=JSON.stringify(c);n.default.useEffect((()=>{t.updateData||d({type:V.RESET_STATE,initialState:h})}),[y]),n.default.useEffect((()=>(i.current=!0,()=>{i.current=!1})),[]);const E=function(e,t){const r=n.default.useRef();return I(t,r.current)||(r.current=t),n.default.useCallback(e,r.current)}((r=>{const n=F(F({},t),r),s=U(F({},u),{variables:n.variables,operationName:n.operationName});if(!i.current)return Promise.resolve({error:{fetchError:Error("fetchData should not be called after hook unmounted")},loading:!1,cacheHit:!1});const c=o.getCacheKey(s,n);a.current=c;const l=n.skipCache?null:o.getCache(c);return l?(d({type:V.CACHE_HIT,result:l,resetState:y!==JSON.stringify(p.cacheKey)}),Promise.resolve(l)):(d({type:V.LOADING,initialState:h}),o.request(s,n).then((r=>{if(n.updateData&&"function"!=typeof n.updateData)throw Error("options.updateData must be a function");const u=F({},r);if(n.useCache&&(u.useCache=!0,u.cacheKey=c,o.ssrMode)){const e={error:u.error,data:n.updateData?n.updateData(p.data,u.data):u.data};o.saveCache(c,e)}if(i.current&&c===a.current&&d({type:V.REQUEST_RESULT,updateData:n.updateData,result:u}),t.isMutation&&o.mutationsEmitter.emit(e,U(F({},s),{mutation:e,result:u})),!(null==r?void 0:r.error)&&n.onSuccess){if("function"!=typeof n.onSuccess)throw Error("options.onSuccess must be a function");n.onSuccess(r,s.variables)}return r})))}),[o,t,u]);n.default.useEffect((()=>{p.useCache&&!o.ssrMode&&o.saveCache(p.cacheKey,p)}),[o,p]);return n.default.useEffect((()=>{const e=(e,t)=>{d({type:t,result:e})},t=t=>e(t,V.REQUEST_RESULT),r=t=>e(t,V.CACHE_HIT),n=o.mutationsEmitter;return n.on(b.DATA_INVALIDATED,t),n.on(b.DATA_UPDATED,r),()=>{n&&(n.removeListener(b.DATA_INVALIDATED,t),n.removeListener(b.DATA_UPDATED,r))}}),[]),[E,p,(e={})=>d({type:V.RESET_STATE,initialState:F(F({},h),e)})]}var W=Object.defineProperty,z=Object.defineProperties,B=Object.getOwnPropertyDescriptors,$=Object.getOwnPropertySymbols,Y=Object.prototype.hasOwnProperty,X=Object.prototype.propertyIsEnumerable,Z=(e,t,r)=>t in e?W(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ee=(e,t)=>{for(var r in t||(t={}))Y.call(t,r)&&Z(e,r,t[r]);if($)for(var r of $(t))X.call(t,r)&&Z(e,r,t[r]);return e},te=(e,t)=>z(e,B(t));const re={useCache:!0,skip:!1,throwErrors:!1};var oe=Object.defineProperty,ne=Object.getOwnPropertySymbols,ie=Object.prototype.hasOwnProperty,se=Object.prototype.propertyIsEnumerable,ae=(e,t,r)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ue=Object.defineProperty,ce=Object.getOwnPropertySymbols,le=Object.prototype.hasOwnProperty,fe=Object.prototype.propertyIsEnumerable,he=(e,t,r)=>t in e?ue(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;e.ClientContext=s,e.GraphQLClient=A,e.LocalGraphQLClient=class extends A{constructor(e){if(super(((e,t)=>{for(var r in t||(t={}))j.call(t,r)&&P(e,r,t[r]);if(L)for(var r of L(t))Q.call(t,r)&&P(e,r,t[r]);return e})({url:""},e)),this.localQueries=e.localQueries,this.requestDelayMs=e.requestDelayMs||0,!this.localQueries)throw Error("LocalGraphQLClient: `localQueries` object required in the constructor options")}verifyConfig(){}request(e){if(!this.localQueries[e.query])throw Error("LocalGraphQLClient: no query match for: "+e.query);return(t=this.requestDelayMs,new Promise((e=>{setTimeout(e,t)}))).then((()=>Promise.resolve(this.localQueries[e.query](e.variables,e.operationName)))).then((e=>e instanceof D?{error:e}:{data:e}));var t}},e.LocalGraphQLError=D,e.useClientRequest=J,e.useManualQuery=(e,t={})=>J(e,((e,t)=>{for(var r in t||(t={}))le.call(t,r)&&he(e,r,t[r]);if(ce)for(var r of ce(t))fe.call(t,r)&&he(e,r,t[r]);return e})({useCache:!0,isManual:!0},t)),e.useMutation=(e,t={})=>J(e,((e,t)=>{for(var r in t||(t={}))ie.call(t,r)&&ae(e,r,t[r]);if(ne)for(var r of ne(t))se.call(t,r)&&ae(e,r,t[r]);return e})({isMutation:!0},t)),e.useQuery=function(e,t={}){const r=ee(ee({},re),t),o=n.default.useContext(s),i=t.client||o,[a,u]=n.default.useState(!1),[c,l]=J(e,r);if(!i)throw Error("useQuery() requires a client to be passed in the options or as a context value");if(i.ssrMode&&!1!==t.ssr&&!a&&!t.skipCache&&!t.skip){if(!l.data&&!l.error){const e=c();i.ssrPromises.push(e)}u(!0)}const f=JSON.stringify(r);n.default.useEffect((()=>{r.skip||c()}),[e,f]),n.default.useEffect((()=>{if(l.error&&r.throwErrors)throw l.error}),[l.error,r.throwErrors]);const h=n.default.useCallback(((e={})=>c(ee({skipCache:!0,updateData:(e,t)=>t},e))),[c]);return n.default.useEffect((function(){const e=(o={},(Array.isArray(r=t.refetchAfterMutations)?r:[r]).forEach((function(e){if(null!=e){var t=typeof e;if("string"===t)o[e]={};else if("object"===t){var r=e.refetchOnMutationError;o[e.mutation]={filter:e.filter,refetchOnMutationError:void 0===r||r}}}})),o);var r,o;const n=Object.keys(e),s=({mutation:t,variables:r,result:o})=>{const{filter:n,refetchOnMutationError:i}=e[t];(!n||r&&n(r))&&(i||!o.error)&&h()};return n.forEach((e=>{i.mutationsEmitter.on(e,s)})),()=>{n.forEach((e=>{i.mutationsEmitter.removeListener(e,s)}))}}),[t.refetchAfterMutations,h,i.mutationsEmitter]),te(ee({},l),{refetch:h})},e.useQueryClient=function(){return t.useContext(s)},e.useSubscription=function(e,r){const o=t.useRef(r);o.current=r;const n=t.useContext(s),i=e.client||n;if(!i)throw Error("useSubscription() requires a client to be passed in the options or as a context value");const a={query:e.query,variables:e.variables};t.useEffect((()=>{const e=i.createSubscription(a).subscribe({next:e=>{o.current(e)},error:e=>{o.current({errors:e})},complete:()=>{e.unsubscribe()}});return()=>{e.unsubscribe()}}),[])},Object.defineProperty(e,"__esModule",{value:!0})}));

@@ -13,3 +13,7 @@ import React, { useContext, useRef, useEffect } from 'react';

const isExtractableFileEnhanced = (value) => isExtractableFile(value) || value !== null && typeof value === "object" && typeof value.pipe === "function" || value !== null && typeof value === "object" && typeof value.stream === "function";
const isExtractableFileEnhanced = (value) => isExtractableFile(value) || // Check if stream
// https://github.com/sindresorhus/is-stream/blob/3750505b0727f6df54324784fe369365ef78841e/index.js#L3
value !== null && typeof value === "object" && typeof value.pipe === "function" || // Check if formdata-node File
// https://github.com/octet-stream/form-data/blob/14a6708f0ae28a5ffded8b6f8156394ba1d1244e/lib/File.ts#L29
value !== null && typeof value === "object" && typeof value.stream === "function";

@@ -24,15 +28,10 @@ function _unsupportedIterableToArray(o, minLen) {

}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (it) return (it = it.call(o)).next.bind(it);
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {

@@ -51,3 +50,2 @@ if (it) o = it;

}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");

@@ -59,3 +57,2 @@ }

var _this = this;
if (fns.length === 0) {

@@ -66,10 +63,7 @@ fns.push(function (_, next) {

}
var _loop = function _loop() {
var fn = _step.value;
if (typeof fn !== "function") {
throw new Error("GraphQLClient Middleware: middleware has to be of type `function`");
}
_this.run = function (stack) {

@@ -83,3 +77,2 @@ return function (opts, next) {

};
for (var _iterator = _createForOfIteratorHelperLoose(fns), _step; !(_step = _iterator()).done;) {

@@ -89,9 +82,15 @@ _loop();

}
/**
* Run middleware
* @param {opts.client} GraphQLClient instance
* @param {opts.operation} Operation object with properties such as query and variables
* @param {opts.resolve} Used to early resolve the request
* @param {opts.addResponseHook} Hook that accepts a function that will be run after response is fetched
* @param {opts.reject} User to early reject the request
* @param {function} next
*/
var _proto = Middleware.prototype;
_proto.run = function run(opts, next) {
next.apply(this, opts);
};
return Middleware;

@@ -153,2 +152,3 @@ }();

}
/** Checks that the given config has the correct required options */
verifyConfig(config) {

@@ -188,2 +188,3 @@ if (!config.url) {

}
/* eslint-disable no-console */
logErrorResult({ result, operation }) {

@@ -215,2 +216,3 @@ console.error("GraphQL Hooks Error");

}
/* eslint-enable no-console */
generateResult({

@@ -247,2 +249,4 @@ fetchError,

}
// Kudos to Jayden Seric (@jaydenseric) for this piece of code.
// See original source: https://github.com/jaydenseric/graphql-react/blob/82d576b5fe6664c4a01cd928d79f33ddc3f7bbfd/src/universal/graphqlFetchOptions.mjs.
getFetchOptions(operation, fetchOptionsOverrides = {}) {

@@ -342,3 +346,6 @@ const fetchOptions = __spreadValues$5(__spreadValues$5({

graphQLErrors: errors,
data: typeof options.responseReducer === "function" && options.responseReducer(data, response) || data
data: (
// enrich data with responseReducer if defined
typeof options.responseReducer === "function" && options.responseReducer(data, response) || data
)
});

@@ -695,10 +702,13 @@ });

const dataUpdatedCallback = (payload) => handleEvents(payload, actionTypes.CACHE_HIT);
client.mutationsEmitter.on(Events.DATA_INVALIDATED, dataInvalidatedCallback);
client.mutationsEmitter.on(Events.DATA_UPDATED, dataUpdatedCallback);
const mutationsEmitter = client.mutationsEmitter;
mutationsEmitter.on(Events.DATA_INVALIDATED, dataInvalidatedCallback);
mutationsEmitter.on(Events.DATA_UPDATED, dataUpdatedCallback);
return () => {
client.mutationsEmitter.off(
Events.DATA_INVALIDATED,
dataInvalidatedCallback
);
client.mutationsEmitter.off(Events.DATA_UPDATED, dataUpdatedCallback);
if (mutationsEmitter) {
mutationsEmitter.removeListener(
Events.DATA_INVALIDATED,
dataInvalidatedCallback
);
mutationsEmitter.removeListener(Events.DATA_UPDATED, dataUpdatedCallback);
}
};

@@ -715,3 +725,2 @@ }, []);

var paramType = typeof mutationInfo;
if (paramType === "string") {

@@ -721,5 +730,5 @@ result[mutationInfo] = {};

var filter = mutationInfo.filter,
mutation = mutationInfo.mutation,
_mutationInfo$refetch = mutationInfo.refetchOnMutationError,
refetchOnMutationError = _mutationInfo$refetch === void 0 ? true : _mutationInfo$refetch;
mutation = mutationInfo.mutation,
_mutationInfo$refetch = mutationInfo.refetchOnMutationError,
refetchOnMutationError = _mutationInfo$refetch === void 0 ? true : _mutationInfo$refetch;
result[mutation] = {

@@ -791,2 +800,5 @@ filter: filter,

skipCache: true,
// don't call the updateData that has been passed into useQuery here
// reset to the default behaviour of returning the raw query result
// this can be overridden in refetch options
updateData: (_, data) => data

@@ -793,0 +805,0 @@ }, options)),

@@ -15,3 +15,3 @@ 'use strict';

const ClientContext = React__default['default'].createContext(null);
const ClientContext = React__default["default"].createContext(null);
ClientContext.displayName = "ClientContext";

@@ -23,3 +23,7 @@

const isExtractableFileEnhanced = (value) => extractFiles.isExtractableFile(value) || value !== null && typeof value === "object" && typeof value.pipe === "function" || value !== null && typeof value === "object" && typeof value.stream === "function";
const isExtractableFileEnhanced = (value) => extractFiles.isExtractableFile(value) || // Check if stream
// https://github.com/sindresorhus/is-stream/blob/3750505b0727f6df54324784fe369365ef78841e/index.js#L3
value !== null && typeof value === "object" && typeof value.pipe === "function" || // Check if formdata-node File
// https://github.com/octet-stream/form-data/blob/14a6708f0ae28a5ffded8b6f8156394ba1d1244e/lib/File.ts#L29
value !== null && typeof value === "object" && typeof value.stream === "function";

@@ -34,15 +38,10 @@ function _unsupportedIterableToArray(o, minLen) {

}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (it) return (it = it.call(o)).next.bind(it);
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {

@@ -61,3 +60,2 @@ if (it) o = it;

}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");

@@ -69,3 +67,2 @@ }

var _this = this;
if (fns.length === 0) {

@@ -76,10 +73,7 @@ fns.push(function (_, next) {

}
var _loop = function _loop() {
var fn = _step.value;
if (typeof fn !== "function") {
throw new Error("GraphQLClient Middleware: middleware has to be of type `function`");
}
_this.run = function (stack) {

@@ -93,3 +87,2 @@ return function (opts, next) {

};
for (var _iterator = _createForOfIteratorHelperLoose(fns), _step; !(_step = _iterator()).done;) {

@@ -99,9 +92,15 @@ _loop();

}
/**
* Run middleware
* @param {opts.client} GraphQLClient instance
* @param {opts.operation} Operation object with properties such as query and variables
* @param {opts.resolve} Used to early resolve the request
* @param {opts.addResponseHook} Hook that accepts a function that will be run after response is fetched
* @param {opts.reject} User to early reject the request
* @param {function} next
*/
var _proto = Middleware.prototype;
_proto.run = function run(opts, next) {
next.apply(this, opts);
};
return Middleware;

@@ -161,4 +160,5 @@ }();

this.middleware = new Middleware(config.middleware || []);
this.mutationsEmitter = new EventEmitter__default['default']();
this.mutationsEmitter = new EventEmitter__default["default"]();
}
/** Checks that the given config has the correct required options */
verifyConfig(config) {

@@ -198,2 +198,3 @@ if (!config.url) {

}
/* eslint-disable no-console */
logErrorResult({ result, operation }) {

@@ -225,2 +226,3 @@ console.error("GraphQL Hooks Error");

}
/* eslint-enable no-console */
generateResult({

@@ -257,2 +259,4 @@ fetchError,

}
// Kudos to Jayden Seric (@jaydenseric) for this piece of code.
// See original source: https://github.com/jaydenseric/graphql-react/blob/82d576b5fe6664c4a01cd928d79f33ddc3f7bbfd/src/universal/graphqlFetchOptions.mjs.
getFetchOptions(operation, fetchOptionsOverrides = {}) {

@@ -352,3 +356,6 @@ const fetchOptions = __spreadValues$5(__spreadValues$5({

graphQLErrors: errors,
data: typeof options.responseReducer === "function" && options.responseReducer(data, response) || data
data: (
// enrich data with responseReducer if defined
typeof options.responseReducer === "function" && options.responseReducer(data, response) || data
)
});

@@ -565,7 +572,7 @@ });

function useDeepCompareCallback(callback, deps) {
const ref = React__default['default'].useRef();
const ref = React__default["default"].useRef();
if (!dequal.dequal(deps, ref.current)) {
ref.current = deps;
}
return React__default['default'].useCallback(callback, ref.current);
return React__default["default"].useCallback(callback, ref.current);
}

@@ -578,3 +585,3 @@ function useClientRequest(query, initialOpts = {}) {

}
const contextClient = React__default['default'].useContext(ClientContext);
const contextClient = React__default["default"].useContext(ClientContext);
const client = initialOpts.client || contextClient;

@@ -586,4 +593,4 @@ if (client === null || client === void 0) {

}
const isMounted = React__default['default'].useRef(true);
const activeCacheKey = React__default['default'].useRef(null);
const isMounted = React__default["default"].useRef(true);
const activeCacheKey = React__default["default"].useRef(null);
const operation = {

@@ -607,5 +614,5 @@ query,

});
const [state, dispatch] = React__default['default'].useReducer(reducer, initialState);
const [state, dispatch] = React__default["default"].useReducer(reducer, initialState);
const stringifiedCacheKey = JSON.stringify(cacheKey);
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
if (!initialOpts.updateData) {

@@ -615,3 +622,3 @@ dispatch({ type: actionTypes.RESET_STATE, initialState });

}, [stringifiedCacheKey]);
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
isMounted.current = true;

@@ -692,3 +699,3 @@ return () => {

);
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
if (state.useCache && !client.ssrMode) {

@@ -702,3 +709,3 @@ client.saveCache(state.cacheKey, state);

});
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
const handleEvents = (payload, actionType) => {

@@ -712,10 +719,13 @@ dispatch({

const dataUpdatedCallback = (payload) => handleEvents(payload, actionTypes.CACHE_HIT);
client.mutationsEmitter.on(Events.DATA_INVALIDATED, dataInvalidatedCallback);
client.mutationsEmitter.on(Events.DATA_UPDATED, dataUpdatedCallback);
const mutationsEmitter = client.mutationsEmitter;
mutationsEmitter.on(Events.DATA_INVALIDATED, dataInvalidatedCallback);
mutationsEmitter.on(Events.DATA_UPDATED, dataUpdatedCallback);
return () => {
client.mutationsEmitter.off(
Events.DATA_INVALIDATED,
dataInvalidatedCallback
);
client.mutationsEmitter.off(Events.DATA_UPDATED, dataUpdatedCallback);
if (mutationsEmitter) {
mutationsEmitter.removeListener(
Events.DATA_INVALIDATED,
dataInvalidatedCallback
);
mutationsEmitter.removeListener(Events.DATA_UPDATED, dataUpdatedCallback);
}
};

@@ -732,3 +742,2 @@ }, []);

var paramType = typeof mutationInfo;
if (paramType === "string") {

@@ -738,5 +747,5 @@ result[mutationInfo] = {};

var filter = mutationInfo.filter,
mutation = mutationInfo.mutation,
_mutationInfo$refetch = mutationInfo.refetchOnMutationError,
refetchOnMutationError = _mutationInfo$refetch === void 0 ? true : _mutationInfo$refetch;
mutation = mutationInfo.mutation,
_mutationInfo$refetch = mutationInfo.refetchOnMutationError,
refetchOnMutationError = _mutationInfo$refetch === void 0 ? true : _mutationInfo$refetch;
result[mutation] = {

@@ -777,5 +786,5 @@ filter: filter,

const allOpts = __spreadValues$2(__spreadValues$2({}, defaultOpts), opts);
const contextClient = React__default['default'].useContext(ClientContext);
const contextClient = React__default["default"].useContext(ClientContext);
const client = opts.client || contextClient;
const [calledDuringSSR, setCalledDuringSSR] = React__default['default'].useState(false);
const [calledDuringSSR, setCalledDuringSSR] = React__default["default"].useState(false);
const [queryReq, state] = useClientRequest(query, allOpts);

@@ -795,3 +804,3 @@ if (!client) {

const stringifiedAllOpts = JSON.stringify(allOpts);
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
if (allOpts.skip) {

@@ -802,3 +811,3 @@ return;

}, [query, stringifiedAllOpts]);
React__default['default'].useEffect(() => {
React__default["default"].useEffect(() => {
if (state.error && allOpts.throwErrors) {

@@ -808,5 +817,8 @@ throw state.error;

}, [state.error, allOpts.throwErrors]);
const refetch = React__default['default'].useCallback(
const refetch = React__default["default"].useCallback(
(options = {}) => queryReq(__spreadValues$2({
skipCache: true,
// don't call the updateData that has been passed into useQuery here
// reset to the default behaviour of returning the raw query result
// this can be overridden in refetch options
updateData: (_, data) => data

@@ -816,3 +828,3 @@ }, options)),

);
React__default['default'].useEffect(
React__default["default"].useEffect(
function subscribeToMutationsAndRefetch() {

@@ -819,0 +831,0 @@ const mutationsMap = createRefetchMutationsMap(opts.refetchAfterMutations);

@@ -6,3 +6,3 @@ /// <reference types="node" />

import Middleware from './Middleware';
import type { UseClientRequestOptions, Cache, ClientOptions, FetchFunction, GenerateResultOptions, OnErrorFunction, Operation, RequestOptions, Result, GraphQLResponseError, CacheKeyObject } from './types/common-types';
import type { UseClientRequestOptions, Cache, ClientOptions, FetchFunction, GenerateResultOptions, OnErrorFunction, Operation, RequestOptions, Result, CacheKeyObject } from './types/common-types';
declare class GraphQLClient {

@@ -36,3 +36,3 @@ url: string;

}): void;
generateResult<ResponseData = any>({ fetchError, httpError, graphQLErrors, data }: GenerateResultOptions<ResponseData, GraphQLResponseError>): Result<ResponseData, GraphQLResponseError>;
generateResult<ResponseData = any, TGraphQLError = object>({ fetchError, httpError, graphQLErrors, data }: GenerateResultOptions<ResponseData, TGraphQLError>): Result<ResponseData, TGraphQLError>;
getCacheKey<Variables = object>(operation: Operation, options?: UseClientRequestOptions<any, Variables>): CacheKeyObject;

@@ -39,0 +39,0 @@ getCache(cacheKey: any): object | undefined;

import GraphQLClient from './GraphQLClient';
import LocalGraphQLError from './LocalGraphQLError';
import { LocalClientOptions, LocalQueries } from './types/common-types';
import { LocalClientOptions, LocalQueries, Result } from './types/common-types';
/** Local version of the GraphQLClient which only returns specified queries

@@ -29,10 +28,4 @@ * Meant to be used as a way to easily mock and test queries during development. This client never contacts any actual server.

verifyConfig(): void;
request(operation: any): Promise<{
error: LocalGraphQLError<any>;
data?: undefined;
} | {
data: any;
error?: undefined;
}>;
request<ResponseData = any, TGraphQLError = object, TVariables = object>(operation: any): Promise<Result<any, TGraphQLError>>;
}
export default LocalGraphQLClient;

@@ -1,11 +0,11 @@

import { APIError, GraphQLResponseError, HttpError } from './types/common-types';
import { APIError, HttpError } from './types/common-types';
/** Used to easily mock a query returning an error when using the `LocalGraphQLClient`.
* This is a class so that the local mock client can use `instanceof` to detect it.
*/
declare class LocalGraphQLError<TGraphQLError = GraphQLResponseError> implements APIError<TGraphQLError> {
declare class LocalGraphQLError<TGraphQLError = object> implements APIError<TGraphQLError> {
fetchError?: Error;
httpError?: HttpError;
graphQLErrors?: GraphQLResponseError[];
graphQLErrors?: TGraphQLError[];
constructor(error: APIError<TGraphQLError>);
}
export default LocalGraphQLError;
import { MiddlewareFunction } from '../types/common-types';
export declare function sha256(query: any): Promise<string>;
declare type APQExtension = {
type APQExtension = {
persistedQuery: {

@@ -5,0 +5,0 @@ version: number;

@@ -14,8 +14,8 @@ import { Client as GraphQLWsClient } from 'graphql-ws';

}
export declare type FetchFunction = (input: RequestInfo, init?: RequestInit) => Promise<Response>;
export declare type OnErrorFunction<TVariables = any> = ({ result, operation }: {
export type FetchFunction = (input: RequestInfo, init?: RequestInit) => Promise<Response>;
export type OnErrorFunction<ResponseData = any, TGraphQLError = GraphQLResponseError, TVariables = any> = ({ result, operation }: {
operation: Operation<TVariables>;
result: Result;
result: Result<ResponseData, TGraphQLError>;
}) => void;
export declare type MiddlewareOptions<T> = {
export type MiddlewareOptions<T> = {
client: GraphQLClient;

@@ -27,3 +27,3 @@ operation: Operation<object, T>;

};
export declare type MiddlewareFunction<TExtension = any> = (options: MiddlewareOptions<TExtension>, next: () => void) => any;
export type MiddlewareFunction<TExtension = any> = (options: MiddlewareOptions<TExtension>, next: () => void) => any;
export interface ClientOptions {

@@ -55,7 +55,7 @@ url: string;

}
export declare type ResetFunction = (desiredState?: object) => void;
export declare type Headers = {
export type ResetFunction = (desiredState?: object) => void;
export type Headers = {
[k: string]: string;
};
export declare type LocalQueries = {
export type LocalQueries = {
[q: string]: (variables: any, operationName?: string) => any;

@@ -86,3 +86,3 @@ };

httpError?: HttpError;
graphQLErrors?: GraphQLResponseError[];
graphQLErrors?: TGraphQLError[];
}

@@ -119,3 +119,3 @@ export interface Result<ResponseData = any, TGraphQLError = GraphQLResponseError> {

}
export declare type RefetchAfterMutationItem = {
export type RefetchAfterMutationItem = {
mutation: string;

@@ -125,3 +125,3 @@ refetchOnMutationError?: boolean;

};
export declare type RefetchAfterMutationsData = string | RefetchAfterMutationItem | (string | RefetchAfterMutationItem)[];
export type RefetchAfterMutationsData = string | RefetchAfterMutationItem | (string | RefetchAfterMutationItem)[];
export interface UseQueryOptions<ResponseData = any, Variables = object> extends UseClientRequestOptions<ResponseData, Variables> {

@@ -146,3 +146,3 @@ ssr?: boolean;

}
export declare type FetchData<ResponseData, Variables = object, TGraphQLError = GraphQLResponseError> = (options?: UseClientRequestOptions<ResponseData, Variables>) => Promise<UseClientRequestResult<ResponseData, TGraphQLError>>;
export type FetchData<ResponseData, Variables = object, TGraphQLError = GraphQLResponseError> = (options?: UseClientRequestOptions<ResponseData, Variables>) => Promise<UseClientRequestResult<ResponseData, TGraphQLError>>;
export interface CacheKeyObject {

@@ -149,0 +149,0 @@ operation: Operation;

{
"name": "graphql-hooks",
"version": "6.1.0",
"version": "6.2.0",
"description": "Graphql Hooks",

@@ -39,3 +39,3 @@ "main": "lib/graphql-hooks.js",

"dependencies": {
"@aws-crypto/sha256-browser": "^2.0.1",
"@aws-crypto/sha256-browser": "^3.0.0",
"buffer": "^6.0.3",

@@ -68,3 +68,3 @@ "dequal": "^2.0.0",

"homepage": "https://github.com/nearform/graphql-hooks#readme",
"gitHead": "51e4a25734ecd45bd34e844f896e1abd1498037a"
"gitHead": "78823da32b5c8c849e93c5deadd5f3829443b90e"
}

@@ -132,2 +132,3 @@ # graphql-hooks

- [Request interceptors](#request-interceptors)
- [AbortController](#abortController)

@@ -1262,2 +1263,36 @@ ## API

### AbortController
if you wish to abort a fetch it is possible to pass an AbortController signal to the `fetchOptionsOverrides` option of the fetch function. This is not `graphql-hooks` specific functionality, rather just an example of how to use it with the library.
```js
import { useManualQuery } from 'graphql-hooks'
function AbortControllerExample() {
const abortControllerRef = useRef()
const [fetchData, { loading }] = useManualQuery(`...`)
const handleFetch = () => {
abortControllerRef.current = new AbortController()
const { signal } = abortControllerRef.current
fetchData({
fetchOptionsOverrides: {
signal
}
})
}
const handleAbort = () => {
abortControllerRef.current?.abort()
}
return (
<>
<button onClick={handleFetch}>Fetch Data</button>
{loading && <button onClick={handleAbort}>Abort</button>}
</>
)
}
```
## Community

@@ -1264,0 +1299,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc