Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@swan-io/graphql-client

Package Overview
Dependencies
Maintainers
1
Versions
45
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@swan-io/graphql-client - npm Package Compare versions

Comparing version 0.1.0-alpha to 0.1.0-alpha10

17

dist/cache/cache.d.ts

@@ -1,3 +0,5 @@

import { DocumentNode, OperationDefinitionNode } from "@0no-co/graphql.web";
import { Option, Result } from "@swan-io/boxed";
import * as graphql from 'graphql';
import { OperationDefinitionNode, DocumentNode } from '@0no-co/graphql.web';
import { Option, Result } from '@swan-io/boxed';
type CacheEntry = {

@@ -7,7 +9,7 @@ requestedKeys: Set<symbol>;

};
export declare const getCacheKeyFromJson: (json: unknown) => Option<symbol>;
export declare const getCacheKeyFromOperationNode: (operationNode: OperationDefinitionNode) => Option<symbol>;
export declare class ClientCache {
declare const getCacheKeyFromJson: (json: unknown) => Option<symbol>;
declare const getCacheKeyFromOperationNode: (operationNode: OperationDefinitionNode) => Option<symbol>;
declare class ClientCache {
cache: Map<symbol, CacheEntry>;
operationCache: Map<import("graphql").DocumentNode, Map<string, Option<Result<unknown, unknown>>>>;
operationCache: Map<graphql.DocumentNode, Map<string, Option<Result<unknown, unknown>>>>;
dump(): Map<symbol, CacheEntry>;

@@ -32,2 +34,3 @@ getOperationFromCache(documentNode: DocumentNode, variables: Record<string, unknown>): Option<Result<unknown, unknown>>;

}
export {};
export { ClientCache, getCacheKeyFromJson, getCacheKeyFromOperationNode };

@@ -1,5 +0,9 @@

import { DocumentNode } from "@0no-co/graphql.web";
import { Option, Result } from "@swan-io/boxed";
import { ClientCache } from "./cache";
export declare const readOperationFromCache: (cache: ClientCache, document: DocumentNode, variables: Record<string, unknown>) => Option<Result<unknown, unknown>>;
export declare const optimizeQuery: (cache: ClientCache, document: DocumentNode, variables: Record<string, unknown>) => Option<DocumentNode>;
import { DocumentNode } from '@0no-co/graphql.web';
import { Option, Result } from '@swan-io/boxed';
import { ClientCache } from './cache.js';
import 'graphql';
declare const readOperationFromCache: (cache: ClientCache, document: DocumentNode, variables: Record<string, unknown>) => Option<Result<unknown, unknown>>;
declare const optimizeQuery: (cache: ClientCache, document: DocumentNode, variables: Record<string, unknown>) => Option<DocumentNode>;
export { optimizeQuery, readOperationFromCache };

@@ -1,3 +0,8 @@

import { DocumentNode } from "@0no-co/graphql.web";
import { ClientCache } from "./cache";
export declare const writeOperationToCache: (cache: ClientCache, document: DocumentNode, response: unknown, variables: Record<string, unknown>) => ClientCache;
import { DocumentNode } from '@0no-co/graphql.web';
import { ClientCache } from './cache.js';
import 'graphql';
import '@swan-io/boxed';
declare const writeOperationToCache: (cache: ClientCache, document: DocumentNode, response: unknown, variables: Record<string, unknown>) => ClientCache;
export { writeOperationToCache };

@@ -1,7 +0,9 @@

import { DocumentNode } from "@0no-co/graphql.web";
import { Future, Option, Result } from "@swan-io/boxed";
import { BadStatusError, EmptyResponseError, NetworkError, TimeoutError } from "@swan-io/request";
import { ClientCache } from "./cache/cache";
import { ClientError } from "./errors";
import { TypedDocumentNode } from "./types";
import * as graphql from 'graphql';
import { DocumentNode } from '@0no-co/graphql.web';
import { Future, Result, Option } from '@swan-io/boxed';
import { ClientCache } from './cache/cache.js';
import { ClientError } from './errors.js';
import { TypedDocumentNode } from './types.js';
import '@swan-io/request';
type RequestConfig = {

@@ -14,9 +16,7 @@ url: string;

};
export type MakeRequest = (config: RequestConfig) => Future<Result<unknown, NetworkError | TimeoutError | BadStatusError | EmptyResponseError>>;
export type ParseResponse = (payload: unknown) => Result<unknown, ClientError>;
export type ClientConfig = {
type MakeRequest = (config: RequestConfig) => Future<Result<unknown, ClientError>>;
type ClientConfig = {
url: string;
headers?: Record<string, string>;
makeRequest?: MakeRequest;
parseResponse?: ParseResponse;
};

@@ -26,3 +26,3 @@ type RequestOptions = {

};
export declare class Client {
declare class Client {
url: string;

@@ -32,3 +32,2 @@ headers: Record<string, string>;

makeRequest: MakeRequest;
parseResponse: ParseResponse;
subscribers: Set<() => void>;

@@ -38,4 +37,4 @@ transformedDocuments: Map<DocumentNode, DocumentNode>;

constructor(config: ClientConfig);
getTransformedDocument(document: DocumentNode): import("graphql").DocumentNode;
getTransformedDocumentsForRequest(document: DocumentNode): import("graphql").DocumentNode;
getTransformedDocument(document: DocumentNode): graphql.DocumentNode;
getTransformedDocumentsForRequest(document: DocumentNode): graphql.DocumentNode;
subscribe(func: () => void): () => boolean;

@@ -47,2 +46,3 @@ request<Data, Variables>(document: TypedDocumentNode<Data, Variables>, variables: Variables, { optimize }?: RequestOptions): Future<Result<Data, ClientError>>;

}
export {};
export { Client, type ClientConfig, type MakeRequest, type RequestConfig };

@@ -1,12 +0,15 @@

import { GraphQLError } from "@0no-co/graphql.web";
import { BadStatusError, EmptyResponseError, NetworkError, TimeoutError } from "@swan-io/request";
export type ClientError = NetworkError | TimeoutError | BadStatusError | EmptyResponseError | InvalidGraphQLResponseError | GraphQLError[];
export declare class InvalidGraphQLResponseError extends Error {
import { GraphQLError } from '@0no-co/graphql.web';
import { NetworkError, TimeoutError, BadStatusError, EmptyResponseError } from '@swan-io/request';
declare class InvalidGraphQLResponseError extends Error {
response: unknown;
constructor(response: unknown);
}
export declare const parseGraphQLError: (error: unknown) => GraphQLError;
export declare const ClientError: {
toArray: (clientError: ClientError) => GraphQLError[] | (NetworkError | TimeoutError | BadStatusError | EmptyResponseError | InvalidGraphQLResponseError)[];
declare const parseGraphQLError: (error: unknown) => GraphQLError;
type ClientError = NetworkError | TimeoutError | BadStatusError | EmptyResponseError | InvalidGraphQLResponseError | GraphQLError[];
declare const ClientError: {
toArray: (clientError: ClientError) => (GraphQLError | NetworkError | TimeoutError | BadStatusError | EmptyResponseError | InvalidGraphQLResponseError)[];
forEach: (clientError: ClientError, func: (error: NetworkError | TimeoutError | BadStatusError | EmptyResponseError | InvalidGraphQLResponseError | GraphQLError, index?: number) => void) => void;
};
export { ClientError, InvalidGraphQLResponseError, parseGraphQLError };

@@ -1,3 +0,4 @@

import { DocumentNode, FieldNode, OperationDefinitionNode, SelectionSetNode } from "@0no-co/graphql.web";
import { Option } from "@swan-io/boxed";
import { FieldNode, OperationDefinitionNode, DocumentNode, SelectionSetNode } from '@0no-co/graphql.web';
import { Option } from '@swan-io/boxed';
/**

@@ -13,3 +14,3 @@ * Returns a Set<string> with all keys selected within the direct selection sets

*/
export declare const getSelectedKeys: (fieldNode: FieldNode | OperationDefinitionNode, variables: Record<string, unknown>) => Set<symbol>;
declare const getSelectedKeys: (fieldNode: FieldNode | OperationDefinitionNode, variables: Record<string, unknown>) => Set<symbol>;
/**

@@ -31,3 +32,3 @@ * Serializes the field name and arguments as a symbol.

*/
export declare const getFieldNameWithArguments: (fieldNode: FieldNode, variables: Record<string, unknown>) => symbol;
declare const getFieldNameWithArguments: (fieldNode: FieldNode, variables: Record<string, unknown>) => symbol;
/**

@@ -40,3 +41,3 @@ * Returns a record representation of the arguments passed to a given field

*/
export declare const extractArguments: (fieldNode: FieldNode, variables: Record<string, unknown>) => Record<string, unknown>;
declare const extractArguments: (fieldNode: FieldNode, variables: Record<string, unknown>) => Record<string, unknown>;
/**

@@ -48,3 +49,3 @@ * Gets the field name in the response payload from its AST definition

*/
export declare const getFieldName: (fieldNode: FieldNode) => string;
declare const getFieldName: (fieldNode: FieldNode) => string;
/**

@@ -56,3 +57,3 @@ * Simplifies the query for internal processing by inlining all fragments.

*/
export declare const inlineFragments: (documentNode: DocumentNode) => DocumentNode;
declare const inlineFragments: (documentNode: DocumentNode) => DocumentNode;
/**

@@ -64,4 +65,6 @@ * Adds `__typename` to all selection sets in the document

*/
export declare const addTypenames: (documentNode: DocumentNode) => DocumentNode;
export declare const getExecutableOperationName: (document: DocumentNode) => Option<string>;
export declare const addIdIfPreviousSelected: (oldSelectionSet: SelectionSetNode, newSelectionSet: SelectionSetNode) => SelectionSetNode;
declare const addTypenames: (documentNode: DocumentNode) => DocumentNode;
declare const getExecutableOperationName: (document: DocumentNode) => Option<string>;
declare const addIdIfPreviousSelected: (oldSelectionSet: SelectionSetNode, newSelectionSet: SelectionSetNode) => SelectionSetNode;
export { addIdIfPreviousSelected, addTypenames, extractArguments, getExecutableOperationName, getFieldName, getFieldNameWithArguments, getSelectedKeys, inlineFragments };

@@ -1,4 +0,7 @@

import { ASTNode } from "@0no-co/graphql.web";
export declare const printString: (string: string) => string;
export declare const printBlockString: (string: string) => string;
export declare const print: (node: ASTNode) => string;
import { ASTNode } from '@0no-co/graphql.web';
declare const printString: (string: string) => string;
declare const printBlockString: (string: string) => string;
declare const print: (node: ASTNode) => string;
export { print, printBlockString, printString };

@@ -1,7 +0,15 @@

export * from "./client";
export { ClientError } from "./errors";
export * from "./react/ClientContext";
export * from "./react/useDeferredQuery";
export * from "./react/useMutation";
export * from "./react/usePagination";
export * from "./react/useQuery";
export { Client, ClientConfig, MakeRequest, RequestConfig } from './client.js';
export { ClientError, InvalidGraphQLResponseError, parseGraphQLError } from './errors.js';
export { print } from './graphql/print.js';
export { ClientContext } from './react/ClientContext.js';
export { DeferredQuery, DeferredQueryConfig, useDeferredQuery } from './react/useDeferredQuery.js';
export { Mutation, useMutation } from './react/useMutation.js';
export { Connection, Edge, useBackwardPagination, useForwardPagination } from './react/usePagination.js';
export { Query, QueryConfig, useQuery } from './react/useQuery.js';
import 'graphql';
import '@0no-co/graphql.web';
import '@swan-io/boxed';
import './cache/cache.js';
import './types.js';
import '@swan-io/request';
import 'react';

@@ -1,2 +0,1232 @@

var e=require("@swan-io/boxed"),t=require("@swan-io/request"),n=require("ts-pattern"),r=require("@0no-co/graphql.web"),i=require("react");function o(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(o=function(){return!!e})()}function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u.apply(this,arguments)}function a(e){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},a(e)}function c(e,t){return c=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},c(e,t)}function s(e){var t="function"==typeof Map?new Map:void 0;return s=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(o())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&c(i,n.prototype),i}(e,arguments,a(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),c(n,e)},s(e)}var f=Symbol.for("DEEP_MERGE_DELETE"),l=function e(t,n){var r=Array.isArray(t)?Array(t.length):Array.isArray(n)?Array(n.length):{};return Object.getOwnPropertyNames(t).forEach(function(e){n[e]!==f&&(r[e]=t[e])}),Object.getOwnPropertySymbols(t).forEach(function(e){n[e]!==f&&(r[e]=t[e])}),Object.getOwnPropertyNames(n).forEach(function(t){n[t]!==f&&(r[t]=p(r[t])&&p(n[t])?e(r[t],n[t]):n[t])}),Object.getOwnPropertySymbols(n).forEach(function(t){n[t]!==f&&(r[t]=p(r[t])&&p(n[t])?e(r[t],n[t]):n[t])}),r},p=function(e){return null!=e&&"object"==typeof e},m=Object.prototype.hasOwnProperty,h=function e(t,n){if(Object.is(t,n))return!0;if("object"!=typeof t||null===t||"object"!=typeof n||null===n)return!1;var r=Object.keys(t),i=Object.keys(n);if(r.length!==i.length)return!1;for(var o=0,u=r;o<u.length;o++){var a=u[o];if(!m.call(n,a)||!e(t[a],n[a]))return!1}return!0},d=function(e){return JSON.stringify(e)},v=function(t){return n.match(t).with({__typename:n.P.select(n.P.union("Query","Mutation","Subscription"))},function(t){return e.Option.Some(Symbol.for(t))}).with({__typename:n.P.select("name",n.P.string),id:n.P.select("id",n.P.string)},function(t){return e.Option.Some(Symbol.for(t.name+"<"+t.id+">"))}).otherwise(function(){return e.Option.None()})},y=function(t){return n.match(t.operation).with(r.OperationTypeNode.QUERY,function(){return e.Option.Some(Symbol.for("Query"))}).with(r.OperationTypeNode.SUBSCRIPTION,function(){return e.Option.Some(Symbol.for("Subscription"))}).otherwise(function(){return e.Option.None()})},g=function(e,t){return{requestedKeys:new Set([].concat(e.requestedKeys.values(),t.requestedKeys.values())),value:l(e.value,t.value)}},O=/*#__PURE__*/function(){function t(){this.cache=new Map,this.operationCache=new Map}var r=t.prototype;return r.dump=function(){return this.cache},r.getOperationFromCache=function(t,n){var r=d(n);return e.Option.fromNullable(this.operationCache.get(t)).flatMap(function(t){return e.Option.fromNullable(t.get(r))}).flatMap(function(e){return e})},r.setOperationInCache=function(t,n,r){var i=d(n),o=e.Option.fromNullable(this.operationCache.get(t)).getWithDefault(new Map);o.set(i,e.Option.Some(r)),this.operationCache.set(t,o)},r.getFromCache=function(t,n){return this.get(t).flatMap(function(t){return r=t.requestedKeys,[].concat(n.values()).every(function(e){return r.has(e)})?e.Option.Some(t.value):e.Option.None();var r})},r.getFromCacheWithoutKey=function(t){return this.get(t).flatMap(function(t){return e.Option.Some(t.value)})},r.get=function(t){return this.cache.has(t)?e.Option.Some(this.cache.get(t)):e.Option.None()},r.getOrDefault=function(e){return this.cache.has(e)?this.cache.get(e):{requestedKeys:new Set,value:{}}},r.set=function(e,t){this.cache.set(e,t)},r.cacheIfEligible=function(t,r){var i=this;return n.match(v(t)).with(e.Option.P.Some(n.P.select()),function(e){var n=i.getOrDefault(e);return i.set(e,g(n,{requestedKeys:r,value:t})),e}).otherwise(function(){return t})},r.updateFieldInClosestCachedAncestor=function(e){for(var t,n=e.originalFieldName,r=e.fieldNameWithArguments,i=e.value,o=e.path,a=e.variables,c=e.rootTypename,s=e.ancestors.concat(),l=o.concat(),m=[];t=s.pop();){var h=v(0===s.length?u({},t,{__typename:c}):t);if(h.isSome()){var d,y=h.get(),O=this.getOrDefault(y);p(i)&&"string"==typeof i.__typename&&i.__typename.endsWith("Connection")&&(i.__connectionArguments=a);var S=m.reduce(function(e,t){var n;return(n={})[t]=e,n},((d={})[n]=f,d[r]=i,d));this.set(y,g(O,{requestedKeys:new Set,value:S}));break}m.push(l.pop())}},t}(),S=function(e,t){var n=new Set;return e.selectionSet&&function e(i){i.selections.forEach(function(i){if(i.kind===r.Kind.FIELD){var o=N(i,t);n.add(o)}else i.kind===r.Kind.INLINE_FRAGMENT&&e(i.selectionSet)})}(e.selectionSet),n},N=function(e,t){var n=w(e),r=b(e,t);return 0===Object.keys(r).length?Symbol.for(n):Symbol.for(n+"("+JSON.stringify(r)+")")},b=function(e,t){var n,r=null!=(n=e.arguments)?n:[];return Object.fromEntries(r.map(function(e){return[e.name.value,E(e.value,t)]}))},E=function e(t,i){return n.match(t).with({kind:r.Kind.NULL},function(){return null}).with({kind:n.P.union(r.Kind.INT,r.Kind.FLOAT,r.Kind.STRING,r.Kind.BOOLEAN,r.Kind.ENUM)},function(e){return e.value}).with({kind:r.Kind.LIST},function(t){return t.values.map(function(t){return e(t,i)})}).with({kind:r.Kind.OBJECT},function(e){return Object.fromEntries(e.fields.map(function(e){return[e.name.value,e.value]}))}).with({kind:r.Kind.VARIABLE},function(e){return i[e.name.value]}).exhaustive()},w=function(e){return e.alias?e.alias.value:e.name.value},A={kind:r.Kind.FIELD,name:{kind:r.Kind.NAME,value:"__typename"}},I=function(e){var t;return r.visit(e,((t={})[r.Kind.SELECTION_SET]=function(e){return e.selections.find(function(e){return e.kind===r.Kind.FIELD&&"__typename"===e.name.value})?e:u({},e,{selections:[A].concat(e.selections)})},t))},D=function t(i){return n.match(i).with({kind:r.Kind.FIELD},function(t){return"id"===t.name.value?e.Option.Some(t):e.Option.None()}).with({kind:r.Kind.INLINE_FRAGMENT},function(n){return e.Array.findMap(n.selectionSet.selections,t)}).otherwise(function(){return e.Option.None()})},P=function(t,n){var r=e.Array.findMap(t.selections,D);return e.Array.findMap(n.selections,D).isSome()?n:r.map(function(e){return u({},n,{selections:[e].concat(n.selections)})}).getWithDefault(n)},C=function(t,n,r){return"symbol"==typeof n?t.getFromCache(n,r).flatMap(e.Option.fromNullable):e.Option.Some(n)},F=function(t,n){return"symbol"==typeof n?t.getFromCacheWithoutKey(n).flatMap(e.Option.fromNullable):e.Option.Some(n)},T=new WeakMap,M=function(t,i,o){var a=function i(a,c){return a.selections.reduce(function(a,c){return a.flatMap(function(a){return n.match(c).with({kind:r.Kind.FIELD},function(n){var r=w(n),c=N(n,o);if(null==a)return e.Option.None();if(!m.call(a,c))return e.Option.None();var s,f=a[c];if(null==f)return e.Option.Some(u({},a,((s={})[r]=f,s)));if(e.Array.isArray(f)){var l=S(n,o);return e.Option.all(f.map(function(r){return C(t,r,l).flatMap(function(t){return p(t)&&null!=n.selectionSet?i(n.selectionSet,t):e.Option.Some(t)})})).map(function(e){var t;return u({},a,((t={})[r]=e,t))})}var h=S(n,o);return C(t,f,h).flatMap(function(t){return p(t)&&null!=n.selectionSet?i(n.selectionSet,t).map(function(e){var t;return u({},a,((t={})[r]=e,t))}):e.Option.Some(u({},a,((o={})[r]=t,o)));var o})}).with({kind:r.Kind.INLINE_FRAGMENT},function(e){return i(e.selectionSet,a)}).with({kind:r.Kind.FRAGMENT_SPREAD},function(){return e.Option.None()}).exhaustive()})},e.Option.Some(c))};return e.Array.findMap(i.definitions,function(t){return t.kind===r.Kind.OPERATION_DEFINITION?e.Option.Some(t):e.Option.None()}).flatMap(function(e){return y(e).map(function(t){return{operation:e,cacheKey:t}})}).flatMap(function(e){var n=e.operation;return t.getFromCache(e.cacheKey,S(n,o)).map(function(e){return{cache:e,operation:n}})}).flatMap(function(e){return a(e.operation.selectionSet,e.cache)}).map(function(e){return JSON.parse(JSON.stringify(e))}).flatMap(function(t){var n=d(o),r=e.Option.fromNullable(T.get(i)).flatMap(function(t){return e.Option.fromNullable(t.get(n))}).flatMap(function(e){return e});if(r.flatMap(function(e){return e.toOption()}).map(function(e){return h(t,e)}).getWithDefault(!1))return r;var u,a=e.Option.Some(e.Result.Ok(t)),c=null!=(u=T.get(i))?u:new Map;return c.set(n,a),T.set(i,c),a})},k=function(e,t,i,o){var a=function t(i,u,a,c){void 0===a&&(a=[]),i.selections.forEach(function(i){n.match(i).with({kind:r.Kind.FIELD},function(n){var r=w(n),i=N(n,o),s=b(n,o),f=u.at(-1),l=f[r],m=S(n,o);if(null!=l)if(Array.isArray(l))l.forEach(function(o,f){var h=e.cacheIfEligible(o,m),d=Array(l.length);d[f]=h,e.updateFieldInClosestCachedAncestor({originalFieldName:r,fieldNameWithArguments:i,value:d,path:a,ancestors:u,variables:s,rootTypename:c}),p(o)&&!Array.isArray(o)&&t(n.selectionSet,[].concat(u,[l,o]),[].concat(a,[i,f.toString()]),c)});else{var h=e.cacheIfEligible(l,m);e.updateFieldInClosestCachedAncestor({originalFieldName:r,fieldNameWithArguments:i,value:h,path:a,ancestors:u,variables:s,rootTypename:c}),p(l)&&null!=n.selectionSet&&t(n.selectionSet,[].concat(u,[l]),[].concat(a,[i]),c)}else r in f&&e.updateFieldInClosestCachedAncestor({originalFieldName:r,fieldNameWithArguments:i,value:l,path:a,ancestors:u,variables:s,rootTypename:c})}).with({kind:r.Kind.INLINE_FRAGMENT},function(e){t(e.selectionSet,u,a,c)}).with({kind:r.Kind.FRAGMENT_SPREAD},function(){}).exhaustive()})};return t.definitions.forEach(function(t){if(t.kind===r.Kind.OPERATION_DEFINITION){var c=n.match(t.operation).with(r.OperationTypeNode.QUERY,function(){return"Query"}).with(r.OperationTypeNode.SUBSCRIPTION,function(){return"Subscription"}).with(r.OperationTypeNode.MUTATION,function(){return"Mutation"}).exhaustive();e.cacheIfEligible(p(i)?u({},i,{__typename:c}):i,S(t,o)),a(t.selectionSet,[i],[],c)}}),e},R=/*#__PURE__*/function(e){function t(n){var r;return(r=e.call(this,"Received an invalid GraphQL response")||this).response=void 0,r.name=r.constructor.name,r.response=n,Object.setPrototypeOf(r,t.prototype),r}var n,r;return r=e,(n=t).prototype=Object.create(r.prototype),n.prototype.constructor=n,c(n,r),t}(/*#__PURE__*/s(Error)),_=function(e){return n.match(e).with({message:n.P.string,nodes:n.P.optional(n.P.any),source:n.P.optional(n.P.any),positions:n.P.optional(n.P.any),path:n.P.optional(n.P.any),error:n.P.optional(n.P.any),extensions:n.P.optional(n.P.any)},function(e){var t=e.message,i=e.nodes,o=e.source,u=e.positions,a=e.path,c=e.extensions,s=n.match(e.error).with({message:n.P.string},function(e){return new Error(e.message)}).otherwise(function(){});return new r.GraphQLError(t,i,o,u,a,s,c)}).otherwise(function(e){return new r.GraphQLError(JSON.stringify(e))})},K={toArray:function(e){return Array.isArray(e)?e:[e]},forEach:function(e,t){K.toArray(e).forEach(t)}},j=function(e){return Boolean(e&&e.length)},q={OperationDefinition:function(e){if("query"===e.operation&&!e.name&&!j(e.variableDefinitions)&&!j(e.directives))return q.SelectionSet(e.selectionSet);var t=e.operation;return e.name&&(t+=" "+e.name.value),j(e.variableDefinitions)&&(e.name||(t+=" "),t+="("+e.variableDefinitions.map(q.VariableDefinition).join(", ")+")"),j(e.directives)&&(t+=" "+e.directives.map(q.Directive).join(" ")),t+" "+q.SelectionSet(e.selectionSet)},VariableDefinition:function(e){var t=q.Variable(e.variable)+": "+L(e.type);return e.defaultValue&&(t+=" = "+L(e.defaultValue)),j(e.directives)&&(t+=" "+e.directives.map(q.Directive).join(" ")),t},Field:function(e){var t=(e.alias?e.alias.value+": ":"")+e.name.value;if(j(e.arguments)){var n=e.arguments.map(q.Argument),r=t+"("+n.join(", ")+")";t=r.length>80?t+"("+n.join(" ")+")":r}return j(e.directives)&&(t+=" "+e.directives.map(q.Directive).join(" ")),e.selectionSet?t+" "+q.SelectionSet(e.selectionSet):t},StringValue:function(e){return e.block?'"""'+e.value.replace(/"""/g,'\\"""')+'"""':JSON.stringify(e.value)},BooleanValue:function(e){return String(e.value)},NullValue:function(){return"null"},IntValue:function(e){return e.value},FloatValue:function(e){return e.value},EnumValue:function(e){return e.value},Name:function(e){return e.value},Variable:function(e){return"$"+e.name.value},ListValue:function(e){return"["+e.values.map(L).join(", ")+"]"},ObjectValue:function(e){return"{"+e.fields.map(q.ObjectField).join(", ")+"}"},ObjectField:function(e){return e.name.value+": "+L(e.value)},Document:function(e){return j(e.definitions)?e.definitions.map(L).join(" "):""},SelectionSet:function(e){return"{"+e.selections.map(L).join(" ")+"}"},Argument:function(e){return e.name.value+": "+L(e.value)},FragmentSpread:function(e){var t="..."+e.name.value;return j(e.directives)&&(t+=" "+e.directives.map(q.Directive).join(" ")),t},InlineFragment:function(e){var t="...";return e.typeCondition&&(t+=" on "+e.typeCondition.name.value),j(e.directives)&&(t+=" "+e.directives.map(q.Directive).join(" ")),t+" "+L(e.selectionSet)},FragmentDefinition:function(e){var t="fragment "+e.name.value;return t+=" on "+e.typeCondition.name.value,j(e.directives)&&(t+=" "+e.directives.map(q.Directive).join(" ")),t+" "+L(e.selectionSet)},Directive:function(e){var t="@"+e.name.value;return j(e.arguments)&&(t+="("+e.arguments.map(q.Argument).join(", ")+")"),t},NamedType:function(e){return e.name.value},ListType:function(e){return"["+L(e.type)+"]"},NonNullType:function(e){return L(e.type)+"!"}},L=function(e){return"function"==typeof q[e.kind]?q[e.kind](e):""},x=function(t){return n.match(t).returnType().with({errors:n.P.select(n.P.array())},function(t){return e.Result.Error(t.map(_))}).with({data:n.P.select(n.P.not(n.P.nullish))},function(t){return e.Result.Ok(t)}).otherwise(function(t){return e.Result.Error(new R(t))})},G=function(e){var n=e.variables;return t.Request.make({url:e.url,method:"POST",responseType:"json",headers:e.headers,body:JSON.stringify({operationName:e.operationName,query:L(e.document),variables:n})}).mapOkToResult(t.badStatusToError).mapOkToResult(t.emptyToError)},V=/*#__PURE__*/function(){function t(e){var t,n,r;this.url=void 0,this.headers=void 0,this.cache=void 0,this.makeRequest=void 0,this.parseResponse=void 0,this.subscribers=void 0,this.transformedDocuments=void 0,this.transformedDocumentsForRequest=void 0,this.url=e.url,this.headers=null!=(t=e.headers)?t:{"Content-Type":"application/json"},this.cache=new O,this.makeRequest=null!=(n=e.makeRequest)?n:G,this.parseResponse=null!=(r=e.parseResponse)?r:x,this.subscribers=new Set,this.transformedDocuments=new Map,this.transformedDocumentsForRequest=new Map}var i=t.prototype;return i.getTransformedDocument=function(e){if(this.transformedDocuments.has(e))return this.transformedDocuments.get(e);var t,n,i,o,a=(t=I(e),o={},r.visit(t,((n={})[r.Kind.FRAGMENT_DEFINITION]=function(e){o[e.name.value]=e},n)),r.visit(t,((i={})[r.Kind.FRAGMENT_DEFINITION]=function(){return null},i.enter=function e(t){if(t.kind===r.Kind.FRAGMENT_SPREAD){var n=t.name.value,i=o[n];if(!i)throw new Error('Fragment "'+n+'" is not defined.');return{kind:r.Kind.INLINE_FRAGMENT,typeCondition:i.typeCondition,selectionSet:i.selectionSet}}return t.kind===r.Kind.SELECTION_SET?u({},t,{selections:t.selections.map(function(t){return e(t)})}):"selectionSet"in t&&null!=t.selectionSet?u({},t,{selectionSet:e(t.selectionSet)}):t},i)));return this.transformedDocuments.set(e,a),a},i.getTransformedDocumentsForRequest=function(e){if(this.transformedDocumentsForRequest.has(e))return this.transformedDocumentsForRequest.get(e);var t=I(e);return this.transformedDocumentsForRequest.set(e,t),t},i.subscribe=function(e){var t=this;return this.subscribers.add(e),function(){return t.subscribers.delete(e)}},i.request=function(t,i,o){var a=this,c=(void 0===o?{}:o).optimize,s=void 0!==c&&c,f=this.getTransformedDocument(t),l=this.getTransformedDocumentsForRequest(t),p=function(t){return e.Array.findMap(t.definitions,function(t){return t.kind===r.Kind.OPERATION_DEFINITION?e.Option.fromNullable(t.name).map(function(e){return e.value}):e.Option.None()})}(f).getWithDefault("Untitled"),h=i,d=s?function(t,i,o){var a=function i(a,c,s){var f=e.Array.filterMap(a.selections,function(a){return n.match(a).with({kind:r.Kind.FIELD},function(n){var r=N(n,o);if(null==c)return e.Option.Some(n);if(!m.call(c,r))return e.Option.Some(n);if(s.has(r)){var a=c[r],f=S(n,o);if(e.Array.isArray(a))return a.reduce(function(r,o){var a=F(t,o);if(a.isNone())return e.Option.Some(n);var c=n.selectionSet;return null!=c?i(c,a.get(),f).map(function(e){return u({},n,{selectionSet:P(c,e)})}):r},e.Option.None());var l=F(t,a);if(l.isNone())return e.Option.Some(n);var p=n.selectionSet;return null!=p?i(p,l.get(),f).map(function(e){return u({},n,{selectionSet:P(p,e)})}):e.Option.None()}return e.Option.Some(n)}).with({kind:r.Kind.INLINE_FRAGMENT},function(e){return i(e.selectionSet,c,s).map(function(t){return u({},e,{selectionSet:t})})}).with({kind:r.Kind.FRAGMENT_SPREAD},function(){return e.Option.None()}).exhaustive()});return f.length>0?e.Option.Some(u({},a,{selections:f})):e.Option.None()};return e.Array.findMap(i.definitions,function(t){return t.kind===r.Kind.OPERATION_DEFINITION?e.Option.Some(t):e.Option.None()}).flatMap(function(e){return y(e).map(function(t){return{operation:e,cacheKey:t}})}).flatMap(function(e){var n=e.operation,r=e.cacheKey,i=S(n,o);return t.getFromCache(r,i).map(function(e){return{cache:e,operation:n,selectedKeys:i}})}).flatMap(function(e){var t=e.operation;return a(t.selectionSet,e.cache,e.selectedKeys).map(function(e){return u({},i,{definitions:[u({},t,{selectionSet:e})]})})})}(this.cache,f,h).map(I):e.Option.Some(l);if(d.isNone()){var v=M(this.cache,f,h);if(v.isSome())return e.Future.value(v.get())}return this.makeRequest({url:this.url,headers:this.headers,operationName:p,document:d.getWithDefault(l),variables:h}).mapOkToResult(this.parseResponse).mapOk(function(e){return e}).tapOk(function(e){k(a.cache,f,e,h)}).tap(function(e){a.cache.setOperationInCache(f,h,e),a.subscribers.forEach(function(e){e()})})},i.readFromCache=function(t,r){var i=this,o=r,u=this.getTransformedDocument(t);return n.match(this.cache.getOperationFromCache(u,o)).with(e.Option.P.Some(e.Result.P.Error(n.P._)),function(e){return e}).otherwise(function(){return M(i.cache,u,o)})},i.query=function(e,t,n){return this.request(e,t,n)},i.commitMutation=function(e,t,n){return this.request(e,t,n)},t}(),W=i.createContext(new V({url:"/graphql"})),B=function(e){return function(t){var r,o,a,c=i.useRef(t);return c.current=(r=c.current,a=e,null==(o=t)||null==r||"__connectionArguments"in o&&p(o.__connectionArguments)&&null==o.__connectionArguments[a]?o:"after"===a&&o.pageInfo.endCursor===r.pageInfo.endCursor||"before"===a&&o.pageInfo.startCursor===r.pageInfo.startCursor?r:u({},o,{edges:n.match(a).with("before",function(){var e,t;return[].concat(null!=(e=o.edges)?e:[],null!=(t=r.edges)?t:[])}).with("after",function(){var e,t;return[].concat(null!=(e=r.edges)?e:[],null!=(t=o.edges)?t:[])}).exhaustive(),pageInfo:n.match(a).with("before",function(){return{hasPreviousPage:o.pageInfo.hasPreviousPage,startCursor:o.pageInfo.startCursor,hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor}}).with("after",function(){return{hasPreviousPage:r.pageInfo.hasPreviousPage,startCursor:r.pageInfo.startCursor,hasNextPage:o.pageInfo.hasNextPage,endCursor:o.pageInfo.endCursor}}).exhaustive()})),c.current}},Q=B("after"),J=B("before");exports.Client=V,exports.ClientContext=W,exports.ClientError=K,exports.useBackwardPagination=J,exports.useDeferredQuery=function(t,n){var r=(void 0===n?{}:n).optimize,o=void 0!==r&&r,u=i.useContext(W),a=i.useState(t)[0],c=i.useState(e.Option.None()),s=c[0],f=c[1],l=i.useCallback(function(){return s.flatMap(function(e){return u.readFromCache(a,e)})},[u,a,s]),p=i.useSyncExternalStore(function(e){return u.subscribe(e)},l),m=i.useMemo(function(){return p.map(function(t){return e.AsyncData.Done(t)}).getWithDefault(e.AsyncData.NotAsked())},[p]),d=i.useState(!1),v=d[0],y=d[1],g=i.useCallback(function(t){return f(function(n){return n.match({None:function(){return e.Option.Some(t)},Some:function(r){return h(r,t)?n:e.Option.Some(t)}})}),y(!0),u.request(a,t,{optimize:o}).tap(function(){return y(!1)})},[u,a,o]);return[v?e.AsyncData.Loading():m,g]},exports.useForwardPagination=Q,exports.useMutation=function(t){var n=i.useContext(W),r=i.useState(t)[0],o=i.useState(e.AsyncData.NotAsked()),u=o[0],a=o[1];return[i.useCallback(function(t){return a(e.AsyncData.Loading()),n.commitMutation(r,t).tap(function(t){return a(e.AsyncData.Done(t))})},[n,r]),u]},exports.useQuery=function(t,n,r){var o=void 0===r?{}:r,u=o.suspense,a=void 0!==u&&u,c=o.optimize,s=void 0!==c&&c,f=i.useContext(W),l=i.useState(t)[0],p=i.useState(n),m=p[0],d=p[1];i.useEffect(function(){h(m,n)||d(n)},[m,n]);var v,y,g=i.useCallback(function(){return f.readFromCache(l,m)},[f,l,m]),O=i.useSyncExternalStore(function(e){return f.subscribe(e)},g),S=i.useMemo(function(){return O.map(function(t){return e.AsyncData.Done(t)}).getWithDefault(e.AsyncData.Loading())},[O]),N=(y=i.useRef(v=S),i.useEffect(function(){y.current=v},[v]),y.current),b=i.useRef(!0);i.useEffect(function(){if(!a||!b.current){var e=f.query(l,m,{optimize:s});return function(){return e.cancel()}}b.current=!1},[f,a,s,l,m]);var E=i.useState(!1),w=E[0],A=E[1],I=i.useCallback(function(){return A(!0),f.request(l,m).tap(function(){return A(!1)})},[f,l,m]),D=i.useState(!1),P=D[0],C=D[1],F=i.useCallback(function(){return C(!0),f.request(l,m).tap(function(){return C(!1)})},[f,l,m]),T=w||P||S.isLoading(),M=P?e.AsyncData.Loading():T?N:S;if(a&&M.isLoading())throw f.query(l,m,{optimize:s}).toPromise();return[M,{isLoading:T,refresh:I,reload:F}]};
//# sourceMappingURL=index.js.map
'use strict';
var boxed = require('@swan-io/boxed');
var request = require('@swan-io/request');
var tsPattern = require('ts-pattern');
var graphql_web = require('@0no-co/graphql.web');
var react = require('react');
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// src/utils.ts
var DEEP_MERGE_DELETE = Symbol.for("DEEP_MERGE_DELETE");
var deepMerge = (target, source) => {
const next = Array.isArray(target) ? Array(target.length) : Array.isArray(source) ? Array(source.length) : {};
Object.getOwnPropertyNames(target).forEach((name) => {
if (source[name] !== DEEP_MERGE_DELETE) {
next[name] = target[name];
}
});
Object.getOwnPropertySymbols(target).forEach((name) => {
if (source[name] !== DEEP_MERGE_DELETE) {
next[name] = target[name];
}
});
Object.getOwnPropertyNames(source).forEach((name) => {
if (source[name] !== DEEP_MERGE_DELETE) {
if (isRecord(next[name]) && isRecord(source[name])) {
next[name] = deepMerge(next[name], source[name]);
} else {
next[name] = source[name];
}
}
});
Object.getOwnPropertySymbols(source).forEach((name) => {
if (source[name] !== DEEP_MERGE_DELETE) {
if (isRecord(next[name]) && isRecord(source[name])) {
next[name] = deepMerge(next[name], source[name]);
} else {
next[name] = source[name];
}
}
});
return next;
};
var containsAll = (a, b) => {
const keys = [...b.values()];
return keys.every((key) => a.has(key));
};
var isRecord = (value) => {
return value != null && typeof value === "object";
};
var hasOwnProperty = Object.prototype.hasOwnProperty;
var deepEqual = (a, b) => {
if (Object.is(a, b)) {
return true;
}
if (typeof a !== "object" || a === null || typeof b !== "object" || b === null) {
return false;
}
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
for (const key of aKeys) {
if (!hasOwnProperty.call(b, key) || !deepEqual(a[key], b[key])) {
return false;
}
}
return true;
};
var serializeVariables = (variables) => {
return JSON.stringify(variables);
};
// src/cache/cache.ts
var getCacheKeyFromJson = (json) => {
return tsPattern.match(json).with(
{ __typename: tsPattern.P.select(tsPattern.P.union("Query", "Mutation", "Subscription")) },
(name) => boxed.Option.Some(Symbol.for(name))
).with(
{ __typename: tsPattern.P.select("name", tsPattern.P.string), id: tsPattern.P.select("id", tsPattern.P.string) },
({ name, id }) => boxed.Option.Some(Symbol.for("".concat(name, "<").concat(id, ">")))
).otherwise(() => boxed.Option.None());
};
var getCacheKeyFromOperationNode = (operationNode) => {
return tsPattern.match(operationNode.operation).with(graphql_web.OperationTypeNode.QUERY, () => boxed.Option.Some(Symbol.for("Query"))).with(
graphql_web.OperationTypeNode.SUBSCRIPTION,
() => boxed.Option.Some(Symbol.for("Subscription"))
).otherwise(() => boxed.Option.None());
};
var mergeCacheEntries = (a, b) => {
return {
requestedKeys: /* @__PURE__ */ new Set([...a.requestedKeys, ...b.requestedKeys]),
value: deepMerge(a.value, b.value)
};
};
var ClientCache = class {
constructor() {
__publicField(this, "cache", /* @__PURE__ */ new Map());
__publicField(this, "operationCache", /* @__PURE__ */ new Map());
}
dump() {
return this.cache;
}
getOperationFromCache(documentNode, variables) {
const serializedVariables = serializeVariables(variables);
return boxed.Option.fromNullable(this.operationCache.get(documentNode)).flatMap((cache) => boxed.Option.fromNullable(cache.get(serializedVariables))).flatMap((value) => value);
}
setOperationInCache(documentNode, variables, data) {
const serializedVariables = serializeVariables(variables);
const documentCache = boxed.Option.fromNullable(
this.operationCache.get(documentNode)
).getWithDefault(/* @__PURE__ */ new Map());
documentCache.set(serializedVariables, boxed.Option.Some(data));
this.operationCache.set(documentNode, documentCache);
}
getFromCache(cacheKey, requestedKeys) {
return this.get(cacheKey).flatMap((entry) => {
if (containsAll(entry.requestedKeys, requestedKeys)) {
return boxed.Option.Some(entry.value);
} else {
return boxed.Option.None();
}
});
}
getFromCacheWithoutKey(cacheKey) {
return this.get(cacheKey).flatMap((entry) => {
return boxed.Option.Some(entry.value);
});
}
get(cacheKey) {
if (this.cache.has(cacheKey)) {
return boxed.Option.Some(this.cache.get(cacheKey));
} else {
return boxed.Option.None();
}
}
getOrDefault(cacheKey) {
if (this.cache.has(cacheKey)) {
return this.cache.get(cacheKey);
} else {
return {
requestedKeys: /* @__PURE__ */ new Set(),
value: {}
};
}
}
set(cacheKey, entry) {
this.cache.set(cacheKey, entry);
}
cacheIfEligible(value, requestedKeys) {
return tsPattern.match(getCacheKeyFromJson(value)).with(boxed.Option.P.Some(tsPattern.P.select()), (cacheKey) => {
const existingEntry = this.getOrDefault(cacheKey);
this.set(
cacheKey,
mergeCacheEntries(existingEntry, {
requestedKeys,
value
})
);
return cacheKey;
}).otherwise(() => value);
}
updateFieldInClosestCachedAncestor({
originalFieldName,
fieldNameWithArguments,
value,
path,
ancestors,
variables,
rootTypename
}) {
const ancestorsCopy = ancestors.concat();
const pathCopy = path.concat();
const writePath = [];
let ancestor;
while (ancestor = ancestorsCopy.pop()) {
const maybeCacheKey = getCacheKeyFromJson(
ancestorsCopy.length === 0 ? { ...ancestor, __typename: rootTypename } : ancestor
);
if (maybeCacheKey.isSome()) {
const cacheKey = maybeCacheKey.get();
const existingEntry = this.getOrDefault(cacheKey);
if (isRecord(value) && typeof value.__typename === "string" && value.__typename.endsWith("Connection")) {
value.__connectionArguments = variables;
}
const deepUpdate = writePath.reduce(
(acc, key) => {
return {
[key]: acc
};
},
// remote original field
{
[originalFieldName]: DEEP_MERGE_DELETE,
[fieldNameWithArguments]: value
}
);
this.set(
cacheKey,
mergeCacheEntries(existingEntry, {
requestedKeys: /* @__PURE__ */ new Set(),
value: deepUpdate
})
);
break;
}
writePath.push(pathCopy.pop());
}
}
};
var getSelectedKeys = (fieldNode, variables) => {
const selectedKeys = /* @__PURE__ */ new Set();
const traverse = (selections) => {
selections.selections.forEach((selection) => {
if (selection.kind === graphql_web.Kind.FIELD) {
const fieldNameWithArguments = getFieldNameWithArguments(
selection,
variables
);
selectedKeys.add(fieldNameWithArguments);
} else if (selection.kind === graphql_web.Kind.INLINE_FRAGMENT) {
traverse(selection.selectionSet);
}
});
};
if (fieldNode.selectionSet) {
traverse(fieldNode.selectionSet);
}
return selectedKeys;
};
var getFieldNameWithArguments = (fieldNode, variables) => {
const fieldName = getFieldName(fieldNode);
const args = extractArguments(fieldNode, variables);
if (Object.keys(args).length === 0) {
return Symbol.for(fieldName);
}
return Symbol.for("".concat(fieldName, "(").concat(JSON.stringify(args), ")"));
};
var extractArguments = (fieldNode, variables) => {
var _a;
const args = (_a = fieldNode.arguments) != null ? _a : [];
return Object.fromEntries(
args.map(({ name: { value: name }, value }) => [
name,
extractValue(value, variables)
])
);
};
var extractValue = (valueNode, variables) => {
return tsPattern.match(valueNode).with({ kind: graphql_web.Kind.NULL }, () => null).with(
{
kind: tsPattern.P.union(
graphql_web.Kind.INT,
graphql_web.Kind.FLOAT,
graphql_web.Kind.STRING,
graphql_web.Kind.BOOLEAN,
graphql_web.Kind.ENUM
)
},
({ value }) => value
).with(
{ kind: graphql_web.Kind.LIST },
({ values }) => values.map((value) => extractValue(value, variables))
).with(
{ kind: graphql_web.Kind.OBJECT },
({ fields }) => Object.fromEntries(
fields.map(({ name: { value: name }, value }) => [name, value])
)
).with(
{ kind: graphql_web.Kind.VARIABLE },
({ name: { value: name } }) => variables[name]
).exhaustive();
};
var getFieldName = (fieldNode) => {
return fieldNode.alias ? fieldNode.alias.value : fieldNode.name.value;
};
var inlineFragments = (documentNode) => {
const fragmentMap = {};
graphql_web.visit(documentNode, {
[graphql_web.Kind.FRAGMENT_DEFINITION](node) {
fragmentMap[node.name.value] = node;
}
});
const inline = (node) => {
if (node.kind === graphql_web.Kind.FRAGMENT_SPREAD) {
const fragmentName = node.name.value;
const fragmentNode = fragmentMap[fragmentName];
if (!fragmentNode) {
throw new Error('Fragment "'.concat(fragmentName, '" is not defined.'));
}
const nextNode = {
kind: graphql_web.Kind.INLINE_FRAGMENT,
typeCondition: fragmentNode.typeCondition,
selectionSet: fragmentNode.selectionSet
};
return nextNode;
}
if (node.kind === graphql_web.Kind.SELECTION_SET) {
return {
...node,
selections: node.selections.map(
(selection) => inline(selection)
)
};
}
if ("selectionSet" in node && node.selectionSet != null) {
return {
...node,
selectionSet: inline(node.selectionSet)
};
}
return node;
};
return graphql_web.visit(documentNode, {
[graphql_web.Kind.FRAGMENT_DEFINITION]: () => null,
enter: inline
});
};
var TYPENAME_NODE = {
kind: graphql_web.Kind.FIELD,
name: {
kind: graphql_web.Kind.NAME,
value: "__typename"
}
};
var addTypenames = (documentNode) => {
return graphql_web.visit(documentNode, {
[graphql_web.Kind.SELECTION_SET]: (selectionSet) => {
if (selectionSet.selections.find(
(selection) => selection.kind === graphql_web.Kind.FIELD && selection.name.value === "__typename"
)) {
return selectionSet;
} else {
return {
...selectionSet,
selections: [TYPENAME_NODE, ...selectionSet.selections]
};
}
}
});
};
var getExecutableOperationName = (document) => {
return boxed.Array.findMap(document.definitions, (definition) => {
if (definition.kind === graphql_web.Kind.OPERATION_DEFINITION) {
return boxed.Option.fromNullable(definition.name).map((name) => name.value);
} else {
return boxed.Option.None();
}
});
};
var getIdFieldNode = (selection) => {
return tsPattern.match(selection).with(
{ kind: graphql_web.Kind.FIELD },
(fieldNode) => fieldNode.name.value === "id" ? boxed.Option.Some(fieldNode) : boxed.Option.None()
).with({ kind: graphql_web.Kind.INLINE_FRAGMENT }, (inlineFragmentNode) => {
return boxed.Array.findMap(
inlineFragmentNode.selectionSet.selections,
getIdFieldNode
);
}).otherwise(() => boxed.Option.None());
};
var addIdIfPreviousSelected = (oldSelectionSet, newSelectionSet) => {
const idSelection = boxed.Array.findMap(oldSelectionSet.selections, getIdFieldNode);
const idSelectionInNew = boxed.Array.findMap(
newSelectionSet.selections,
getIdFieldNode
);
if (idSelectionInNew.isSome()) {
return newSelectionSet;
}
return idSelection.map((selection) => ({
...newSelectionSet,
selections: [
selection,
...newSelectionSet.selections
]
})).getWithDefault(newSelectionSet);
};
// src/cache/read.ts
var getFromCacheOrReturnValue = (cache, valueOrKey, selectedKeys) => {
return typeof valueOrKey === "symbol" ? cache.getFromCache(valueOrKey, selectedKeys).flatMap(boxed.Option.fromNullable) : boxed.Option.Some(valueOrKey);
};
var getFromCacheOrReturnValueWithoutKeyFilter = (cache, valueOrKey) => {
return typeof valueOrKey === "symbol" ? cache.getFromCacheWithoutKey(valueOrKey).flatMap(boxed.Option.fromNullable) : boxed.Option.Some(valueOrKey);
};
var STABILITY_CACHE = /* @__PURE__ */ new WeakMap();
var readOperationFromCache = (cache, document, variables) => {
const traverse = (selections, data) => {
return selections.selections.reduce((data2, selection) => {
return data2.flatMap(
(data3) => tsPattern.match(selection).with({ kind: graphql_web.Kind.FIELD }, (fieldNode) => {
const originalFieldName = getFieldName(fieldNode);
const fieldNameWithArguments = getFieldNameWithArguments(
fieldNode,
variables
);
if (data3 == void 0) {
return boxed.Option.None();
}
const cacheHasKey = hasOwnProperty.call(
data3,
fieldNameWithArguments
);
if (!cacheHasKey) {
return boxed.Option.None();
}
const valueOrKeyFromCache = data3[fieldNameWithArguments];
if (valueOrKeyFromCache == void 0) {
return boxed.Option.Some({
...data3,
[originalFieldName]: valueOrKeyFromCache
});
}
if (boxed.Array.isArray(valueOrKeyFromCache)) {
const selectedKeys = getSelectedKeys(fieldNode, variables);
return boxed.Option.all(
valueOrKeyFromCache.map((valueOrKey) => {
const value = getFromCacheOrReturnValue(
cache,
valueOrKey,
selectedKeys
);
return value.flatMap((value2) => {
if (isRecord(value2) && fieldNode.selectionSet != void 0) {
return traverse(fieldNode.selectionSet, value2);
} else {
return boxed.Option.Some(value2);
}
});
})
).map((result) => ({
...data3,
[originalFieldName]: result
}));
} else {
const selectedKeys = getSelectedKeys(fieldNode, variables);
const value = getFromCacheOrReturnValue(
cache,
valueOrKeyFromCache,
selectedKeys
);
return value.flatMap((value2) => {
if (isRecord(value2) && fieldNode.selectionSet != void 0) {
return traverse(
fieldNode.selectionSet,
value2
).map((result) => ({
...data3,
[originalFieldName]: result
}));
} else {
return boxed.Option.Some({ ...data3, [originalFieldName]: value2 });
}
});
}
}).with({ kind: graphql_web.Kind.INLINE_FRAGMENT }, (inlineFragmentNode) => {
var _a;
const typeCondition = (_a = inlineFragmentNode.typeCondition) == null ? void 0 : _a.name.value;
const dataTypename = tsPattern.match(data3).with({ __typename: tsPattern.P.select(tsPattern.P.string) }, (name) => name).with(
{ __typename: tsPattern.P.array({ __typename: tsPattern.P.select(tsPattern.P.string) }) },
(name) => name
).otherwise(() => void 0);
if (typeCondition != null && dataTypename != null) {
if (dataTypename === typeCondition) {
return traverse(
inlineFragmentNode.selectionSet,
data3
);
} else {
if (inlineFragmentNode.selectionSet.selections.some(
(selection2) => selection2.kind === graphql_web.Kind.INLINE_FRAGMENT
)) {
return traverse(
{
...inlineFragmentNode.selectionSet,
selections: inlineFragmentNode.selectionSet.selections.filter(
(selection2) => {
var _a2;
if (selection2.kind === graphql_web.Kind.INLINE_FRAGMENT) {
const typeCondition2 = (_a2 = selection2.typeCondition) == null ? void 0 : _a2.name.value;
return typeCondition2 === dataTypename;
}
return true;
}
)
},
data3
);
} else {
return boxed.Option.Some(data3);
}
}
}
return traverse(
inlineFragmentNode.selectionSet,
data3
);
}).with({ kind: graphql_web.Kind.FRAGMENT_SPREAD }, () => {
return boxed.Option.None();
}).exhaustive()
);
}, boxed.Option.Some(data));
};
return boxed.Array.findMap(
document.definitions,
(definition) => definition.kind === graphql_web.Kind.OPERATION_DEFINITION ? boxed.Option.Some(definition) : boxed.Option.None()
).flatMap(
(operation) => getCacheKeyFromOperationNode(operation).map((cacheKey) => ({
operation,
cacheKey
}))
).flatMap(({ operation, cacheKey }) => {
return cache.getFromCache(cacheKey, getSelectedKeys(operation, variables)).map((cache2) => ({ cache: cache2, operation }));
}).flatMap(({ operation, cache: cache2 }) => {
return traverse(
operation.selectionSet,
cache2
);
}).map((data) => JSON.parse(JSON.stringify(data))).flatMap((value) => {
var _a;
const serializedVariables = serializeVariables(variables);
const previous = boxed.Option.fromNullable(STABILITY_CACHE.get(document)).flatMap(
(byVariable) => boxed.Option.fromNullable(byVariable.get(serializedVariables))
).flatMap((value2) => value2);
if (previous.flatMap((previous2) => previous2.toOption()).map((previous2) => deepEqual(value, previous2)).getWithDefault(false)) {
return previous;
} else {
const valueToCache = boxed.Option.Some(boxed.Result.Ok(value));
const documentCache = (_a = STABILITY_CACHE.get(document)) != null ? _a : /* @__PURE__ */ new Map();
documentCache.set(serializedVariables, valueToCache);
STABILITY_CACHE.set(document, documentCache);
return valueToCache;
}
});
};
var optimizeQuery = (cache, document, variables) => {
const traverse = (selections, data, parentSelectedKeys) => {
const nextSelections = boxed.Array.filterMap(
selections.selections,
(selection) => {
return tsPattern.match(selection).with({ kind: graphql_web.Kind.FIELD }, (fieldNode) => {
const fieldNameWithArguments = getFieldNameWithArguments(
fieldNode,
variables
);
if (data == void 0) {
return boxed.Option.Some(fieldNode);
}
const cacheHasKey = hasOwnProperty.call(
data,
fieldNameWithArguments
);
if (!cacheHasKey) {
return boxed.Option.Some(fieldNode);
}
if (parentSelectedKeys.has(fieldNameWithArguments)) {
const valueOrKeyFromCache = data[fieldNameWithArguments];
const subFieldSelectedKeys = getSelectedKeys(
fieldNode,
variables
);
if (boxed.Array.isArray(valueOrKeyFromCache)) {
return valueOrKeyFromCache.reduce((acc, valueOrKey) => {
const value = getFromCacheOrReturnValueWithoutKeyFilter(
cache,
valueOrKey
);
if (value.isNone()) {
return boxed.Option.Some(fieldNode);
}
const originalSelectionSet = fieldNode.selectionSet;
if (originalSelectionSet != null) {
return traverse(
originalSelectionSet,
value.get(),
subFieldSelectedKeys
).map((selectionSet) => ({
...fieldNode,
selectionSet: addIdIfPreviousSelected(
originalSelectionSet,
selectionSet
)
}));
} else {
return acc;
}
}, boxed.Option.None());
} else {
const value = getFromCacheOrReturnValueWithoutKeyFilter(
cache,
valueOrKeyFromCache
);
if (value.isNone()) {
return boxed.Option.Some(fieldNode);
}
const originalSelectionSet = fieldNode.selectionSet;
if (originalSelectionSet != null) {
return traverse(
originalSelectionSet,
value.get(),
subFieldSelectedKeys
).map((selectionSet) => ({
...fieldNode,
selectionSet: addIdIfPreviousSelected(
originalSelectionSet,
selectionSet
)
}));
} else {
return boxed.Option.None();
}
}
} else {
return boxed.Option.Some(fieldNode);
}
}).with({ kind: graphql_web.Kind.INLINE_FRAGMENT }, (inlineFragmentNode) => {
return traverse(
inlineFragmentNode.selectionSet,
data,
parentSelectedKeys
).map(
(selectionSet) => ({ ...inlineFragmentNode, selectionSet })
);
}).with({ kind: graphql_web.Kind.FRAGMENT_SPREAD }, () => {
return boxed.Option.None();
}).exhaustive();
}
);
if (nextSelections.length > 0) {
return boxed.Option.Some({ ...selections, selections: nextSelections });
} else {
return boxed.Option.None();
}
};
return boxed.Array.findMap(
document.definitions,
(definition) => definition.kind === graphql_web.Kind.OPERATION_DEFINITION ? boxed.Option.Some(definition) : boxed.Option.None()
).flatMap(
(operation) => getCacheKeyFromOperationNode(operation).map((cacheKey) => ({
operation,
cacheKey
}))
).flatMap(({ operation, cacheKey }) => {
const selectedKeys = getSelectedKeys(operation, variables);
return cache.getFromCache(cacheKey, selectedKeys).map((cache2) => ({ cache: cache2, operation, selectedKeys }));
}).flatMap(({ operation, cache: cache2, selectedKeys }) => {
return traverse(
operation.selectionSet,
cache2,
selectedKeys
).map((selectionSet) => ({
...document,
definitions: [
{
...operation,
selectionSet
}
]
}));
});
};
var writeOperationToCache = (cache, document, response, variables) => {
const traverse = (selections, data, path = [], rootTypename) => {
selections.selections.forEach((selection) => {
tsPattern.match(selection).with({ kind: graphql_web.Kind.FIELD }, (fieldNode) => {
const originalFieldName = getFieldName(fieldNode);
const fieldNameWithArguments = getFieldNameWithArguments(
fieldNode,
variables
);
const fieldArguments = extractArguments(fieldNode, variables);
const parent = data.at(-1);
const fieldValue = parent[originalFieldName];
const selectedKeys = getSelectedKeys(fieldNode, variables);
if (fieldValue != void 0) {
if (Array.isArray(fieldValue)) {
cache.updateFieldInClosestCachedAncestor({
originalFieldName,
fieldNameWithArguments,
value: fieldValue,
path,
ancestors: data,
variables: fieldArguments,
rootTypename
});
fieldValue.forEach((item, index) => {
const value = cache.cacheIfEligible(item, selectedKeys);
const nextValue = Array(fieldValue.length);
nextValue[index] = value;
cache.updateFieldInClosestCachedAncestor({
originalFieldName,
fieldNameWithArguments,
value: nextValue,
path,
ancestors: data,
variables: fieldArguments,
rootTypename
});
if (isRecord(item) && !Array.isArray(item)) {
traverse(
fieldNode.selectionSet,
[...data, fieldValue, item],
[...path, fieldNameWithArguments, index.toString()],
rootTypename
);
}
});
} else {
const value = cache.cacheIfEligible(fieldValue, selectedKeys);
cache.updateFieldInClosestCachedAncestor({
originalFieldName,
fieldNameWithArguments,
value,
path,
ancestors: data,
variables: fieldArguments,
rootTypename
});
if (isRecord(fieldValue) && fieldNode.selectionSet != void 0) {
traverse(
fieldNode.selectionSet,
[...data, fieldValue],
[...path, fieldNameWithArguments],
rootTypename
);
}
}
} else {
if (originalFieldName in parent) {
cache.updateFieldInClosestCachedAncestor({
originalFieldName,
fieldNameWithArguments,
value: fieldValue,
path,
ancestors: data,
variables: fieldArguments,
rootTypename
});
}
}
}).with({ kind: graphql_web.Kind.INLINE_FRAGMENT }, (inlineFragmentNode) => {
traverse(inlineFragmentNode.selectionSet, data, path, rootTypename);
}).with({ kind: graphql_web.Kind.FRAGMENT_SPREAD }, () => {
}).exhaustive();
});
};
document.definitions.forEach((definition) => {
if (definition.kind === graphql_web.Kind.OPERATION_DEFINITION) {
const rootTypename = tsPattern.match(definition.operation).with(graphql_web.OperationTypeNode.QUERY, () => "Query").with(graphql_web.OperationTypeNode.SUBSCRIPTION, () => "Subscription").with(graphql_web.OperationTypeNode.MUTATION, () => "Mutation").exhaustive();
cache.cacheIfEligible(
isRecord(response) ? {
...response,
__typename: rootTypename
} : response,
getSelectedKeys(definition, variables)
);
traverse(definition.selectionSet, [response], [], rootTypename);
}
});
return cache;
};
exports.InvalidGraphQLResponseError = class _InvalidGraphQLResponseError extends Error {
constructor(response) {
super("Received an invalid GraphQL response");
__publicField(this, "response");
this.name = this.constructor.name;
this.response = response;
Object.setPrototypeOf(this, _InvalidGraphQLResponseError.prototype);
}
};
exports.parseGraphQLError = (error) => {
return tsPattern.match(error).with(
{
message: tsPattern.P.string,
nodes: tsPattern.P.optional(tsPattern.P.any),
source: tsPattern.P.optional(tsPattern.P.any),
positions: tsPattern.P.optional(tsPattern.P.any),
path: tsPattern.P.optional(tsPattern.P.any),
error: tsPattern.P.optional(tsPattern.P.any),
extensions: tsPattern.P.optional(tsPattern.P.any)
},
({ message, nodes: nodes2, source, positions, path, error: error2, extensions }) => {
const originalError = tsPattern.match(error2).with({ message: tsPattern.P.string }, ({ message: message2 }) => new Error(message2)).otherwise(() => void 0);
return new graphql_web.GraphQLError(
message,
nodes2,
source,
positions,
path,
originalError,
extensions
);
}
).otherwise((error2) => new graphql_web.GraphQLError(JSON.stringify(error2)));
};
exports.ClientError = {
toArray: (clientError) => {
return Array.isArray(clientError) ? clientError : [clientError];
},
forEach: (clientError, func) => {
exports.ClientError.toArray(clientError).forEach(func);
}
};
// src/graphql/print.ts
var printString = (string) => {
return JSON.stringify(string);
};
var printBlockString = (string) => {
return '"""' + string.replace(/"""/g, '\\"""') + '"""';
};
var hasItems = (array) => Boolean(array && array.length);
var MAX_LINE_LENGTH = 80;
var nodes = {
OperationDefinition(node) {
if (node.operation === "query" && !node.name && !hasItems(node.variableDefinitions) && !hasItems(node.directives)) {
return nodes.SelectionSet(node.selectionSet);
}
let out = node.operation;
if (node.name)
out += " " + node.name.value;
if (hasItems(node.variableDefinitions)) {
if (!node.name)
out += " ";
out += "(" + node.variableDefinitions.map(nodes.VariableDefinition).join(", ") + ")";
}
if (hasItems(node.directives))
out += " " + node.directives.map(nodes.Directive).join(" ");
return out + " " + nodes.SelectionSet(node.selectionSet);
},
VariableDefinition(node) {
let out = nodes.Variable(node.variable) + ": " + exports.print(node.type);
if (node.defaultValue)
out += " = " + exports.print(node.defaultValue);
if (hasItems(node.directives))
out += " " + node.directives.map(nodes.Directive).join(" ");
return out;
},
Field(node) {
let out = (node.alias ? node.alias.value + ": " : "") + node.name.value;
if (hasItems(node.arguments)) {
const args = node.arguments.map(nodes.Argument);
const argsLine = out + "(" + args.join(", ") + ")";
out = argsLine.length > MAX_LINE_LENGTH ? out + "(" + args.join(" ") + ")" : argsLine;
}
if (hasItems(node.directives))
out += " " + node.directives.map(nodes.Directive).join(" ");
return node.selectionSet ? out + " " + nodes.SelectionSet(node.selectionSet) : out;
},
StringValue(node) {
return node.block ? printBlockString(node.value) : printString(node.value);
},
BooleanValue(node) {
return String(node.value);
},
NullValue() {
return "null";
},
IntValue(node) {
return node.value;
},
FloatValue(node) {
return node.value;
},
EnumValue(node) {
return node.value;
},
Name(node) {
return node.value;
},
Variable(node) {
return "$" + node.name.value;
},
ListValue(node) {
return "[" + node.values.map(exports.print).join(", ") + "]";
},
ObjectValue(node) {
return "{" + node.fields.map(nodes.ObjectField).join(", ") + "}";
},
ObjectField(node) {
return node.name.value + ": " + exports.print(node.value);
},
Document(node) {
return hasItems(node.definitions) ? node.definitions.map(exports.print).join(" ") : "";
},
SelectionSet(node) {
return "{" + node.selections.map(exports.print).join(" ") + "}";
},
Argument(node) {
return node.name.value + ": " + exports.print(node.value);
},
FragmentSpread(node) {
let out = "..." + node.name.value;
if (hasItems(node.directives))
out += " " + node.directives.map(nodes.Directive).join(" ");
return out;
},
InlineFragment(node) {
let out = "...";
if (node.typeCondition)
out += " on " + node.typeCondition.name.value;
if (hasItems(node.directives))
out += " " + node.directives.map(nodes.Directive).join(" ");
return out + " " + exports.print(node.selectionSet);
},
FragmentDefinition(node) {
let out = "fragment " + node.name.value;
out += " on " + node.typeCondition.name.value;
if (hasItems(node.directives))
out += " " + node.directives.map(nodes.Directive).join(" ");
return out + " " + exports.print(node.selectionSet);
},
Directive(node) {
let out = "@" + node.name.value;
if (hasItems(node.arguments))
out += "(" + node.arguments.map(nodes.Argument).join(", ") + ")";
return out;
},
NamedType(node) {
return node.name.value;
},
ListType(node) {
return "[" + exports.print(node.type) + "]";
},
NonNullType(node) {
return exports.print(node.type) + "!";
}
};
exports.print = (node) => {
return typeof nodes[node.kind] == "function" ? nodes[node.kind](node) : "";
};
// src/client.ts
var defaultMakeRequest = ({
url,
headers,
operationName,
document,
variables
}) => {
return request.Request.make({
url,
method: "POST",
responseType: "json",
headers,
body: JSON.stringify({
operationName,
query: exports.print(document),
variables
})
}).mapOkToResult(request.badStatusToError).mapOkToResult(request.emptyToError).mapOkToResult(
(payload) => tsPattern.match(payload).returnType().with(
{ errors: tsPattern.P.select(tsPattern.P.array()) },
(errors) => boxed.Result.Error(errors.map(exports.parseGraphQLError))
).with({ data: tsPattern.P.select(tsPattern.P.nonNullable) }, (data) => boxed.Result.Ok(data)).otherwise(
(response) => boxed.Result.Error(new exports.InvalidGraphQLResponseError(response))
)
);
};
exports.Client = class Client {
constructor(config) {
__publicField(this, "url");
__publicField(this, "headers");
__publicField(this, "cache");
__publicField(this, "makeRequest");
__publicField(this, "subscribers");
__publicField(this, "transformedDocuments");
__publicField(this, "transformedDocumentsForRequest");
var _a, _b;
this.url = config.url;
this.headers = (_a = config.headers) != null ? _a : { "Content-Type": "application/json" };
this.cache = new ClientCache();
this.makeRequest = (_b = config.makeRequest) != null ? _b : defaultMakeRequest;
this.subscribers = /* @__PURE__ */ new Set();
this.transformedDocuments = /* @__PURE__ */ new Map();
this.transformedDocumentsForRequest = /* @__PURE__ */ new Map();
}
getTransformedDocument(document) {
if (this.transformedDocuments.has(document)) {
return this.transformedDocuments.get(document);
} else {
const transformedDocument = inlineFragments(addTypenames(document));
this.transformedDocuments.set(document, transformedDocument);
return transformedDocument;
}
}
getTransformedDocumentsForRequest(document) {
if (this.transformedDocumentsForRequest.has(document)) {
return this.transformedDocumentsForRequest.get(document);
} else {
const transformedDocument = addTypenames(document);
this.transformedDocumentsForRequest.set(document, transformedDocument);
return transformedDocument;
}
}
subscribe(func) {
this.subscribers.add(func);
return () => this.subscribers.delete(func);
}
request(document, variables, { optimize = false } = {}) {
const transformedDocument = this.getTransformedDocument(document);
const transformedDocumentsForRequest = this.getTransformedDocumentsForRequest(document);
const operationName = getExecutableOperationName(transformedDocument).getWithDefault(
"Untitled"
);
const variablesAsRecord = variables;
const possiblyOptimizedQuery = optimize ? optimizeQuery(this.cache, transformedDocument, variablesAsRecord).map(
addTypenames
) : boxed.Option.Some(transformedDocumentsForRequest);
if (possiblyOptimizedQuery.isNone()) {
const operationResult = readOperationFromCache(
this.cache,
transformedDocument,
variablesAsRecord
);
if (operationResult.isSome()) {
return boxed.Future.value(operationResult.get());
}
}
return this.makeRequest({
url: this.url,
headers: this.headers,
operationName,
document: possiblyOptimizedQuery.getWithDefault(
transformedDocumentsForRequest
),
variables: variablesAsRecord
}).mapOk((data) => data).tapOk((data) => {
writeOperationToCache(
this.cache,
transformedDocument,
data,
variablesAsRecord
);
}).tap((result) => {
this.cache.setOperationInCache(
transformedDocument,
variablesAsRecord,
result
);
this.subscribers.forEach((func) => {
func();
});
});
}
readFromCache(document, variables) {
const variablesAsRecord = variables;
const transformedDocument = this.getTransformedDocument(document);
return tsPattern.match(
this.cache.getOperationFromCache(transformedDocument, variablesAsRecord)
).with(boxed.Option.P.Some(boxed.Result.P.Error(tsPattern.P._)), (value) => value).otherwise(
() => readOperationFromCache(
this.cache,
transformedDocument,
variablesAsRecord
)
);
}
query(document, variables, requestOptions) {
return this.request(document, variables, requestOptions);
}
commitMutation(document, variables, requestOptions) {
return this.request(document, variables, requestOptions);
}
};
exports.ClientContext = react.createContext(new exports.Client({ url: "/graphql" }));
exports.useDeferredQuery = (query, { optimize = false } = {}) => {
const client = react.useContext(exports.ClientContext);
const [stableQuery] = react.useState(query);
const [stableVariables, setStableVariables] = react.useState(
boxed.Option.None()
);
const getSnapshot = react.useCallback(() => {
return stableVariables.flatMap(
(variables) => client.readFromCache(stableQuery, variables)
);
}, [client, stableQuery, stableVariables]);
const data = react.useSyncExternalStore(
(func) => client.subscribe(func),
getSnapshot
);
const asyncData = react.useMemo(() => {
return data.map((value) => boxed.AsyncData.Done(value)).getWithDefault(boxed.AsyncData.NotAsked());
}, [data]);
const [isQuerying, setIsQuerying] = react.useState(false);
const runQuery = react.useCallback(
(variables) => {
setStableVariables(
(stableVariables2) => stableVariables2.match({
None: () => boxed.Option.Some(variables),
Some: (prevVariables) => deepEqual(prevVariables, variables) ? stableVariables2 : boxed.Option.Some(variables)
})
);
setIsQuerying(true);
return client.request(stableQuery, variables, { optimize }).tap(() => setIsQuerying(false));
},
[client, stableQuery, optimize]
);
const asyncDataToExpose = isQuerying ? boxed.AsyncData.Loading() : asyncData;
return [asyncDataToExpose, runQuery];
};
exports.useMutation = (mutation) => {
const client = react.useContext(exports.ClientContext);
const [stableMutation] = react.useState(mutation);
const [data, setData] = react.useState(
boxed.AsyncData.NotAsked()
);
const commitMutation = react.useCallback(
(variables) => {
setData(boxed.AsyncData.Loading());
return client.commitMutation(stableMutation, variables).tap((result) => setData(boxed.AsyncData.Done(result)));
},
[client, stableMutation]
);
return [commitMutation, data];
};
var mergeConnection = (previous, next, mode) => {
if (next == null) {
return next;
}
if (previous == null) {
return next;
}
if ("__connectionArguments" in next && isRecord(next.__connectionArguments)) {
if (next.__connectionArguments[mode] == null) {
return next;
}
}
if (mode === "after" && next.pageInfo.endCursor === previous.pageInfo.endCursor) {
return previous;
}
if (mode === "before" && next.pageInfo.startCursor === previous.pageInfo.startCursor) {
return previous;
}
return {
...next,
edges: tsPattern.match(mode).with("before", () => {
var _a, _b;
return [...(_a = next.edges) != null ? _a : [], ...(_b = previous.edges) != null ? _b : []];
}).with("after", () => {
var _a, _b;
return [...(_a = previous.edges) != null ? _a : [], ...(_b = next.edges) != null ? _b : []];
}).exhaustive(),
pageInfo: tsPattern.match(mode).with("before", () => ({
hasPreviousPage: next.pageInfo.hasPreviousPage,
startCursor: next.pageInfo.startCursor,
hasNextPage: previous.pageInfo.hasNextPage,
endCursor: previous.pageInfo.endCursor
})).with("after", () => ({
hasPreviousPage: previous.pageInfo.hasPreviousPage,
startCursor: previous.pageInfo.startCursor,
hasNextPage: next.pageInfo.hasNextPage,
endCursor: next.pageInfo.endCursor
})).exhaustive()
};
};
var createPaginationHook = (direction) => {
return (connection) => {
const connectionRef = react.useRef(connection);
connectionRef.current = mergeConnection(
connectionRef.current,
connection,
direction
);
return connectionRef.current;
};
};
exports.useForwardPagination = createPaginationHook("after");
exports.useBackwardPagination = createPaginationHook("before");
var usePreviousValue = (value) => {
const previousRef = react.useRef(value);
react.useEffect(() => {
previousRef.current = value;
}, [value]);
return previousRef.current;
};
exports.useQuery = (query, variables, { suspense = false, optimize = false } = {}) => {
const client = react.useContext(exports.ClientContext);
const [stableQuery] = react.useState(query);
const [stableVariables, setStableVariables] = react.useState(variables);
react.useEffect(() => {
if (!deepEqual(stableVariables, variables)) {
setStableVariables(variables);
}
}, [stableVariables, variables]);
const getSnapshot = react.useCallback(() => {
return client.readFromCache(stableQuery, stableVariables);
}, [client, stableQuery, stableVariables]);
const data = react.useSyncExternalStore(
(func) => client.subscribe(func),
getSnapshot
);
const asyncData = react.useMemo(() => {
return data.map((value) => boxed.AsyncData.Done(value)).getWithDefault(boxed.AsyncData.Loading());
}, [data]);
const previousAsyncData = usePreviousValue(asyncData);
const isSuspenseFirstFetch = react.useRef(true);
react.useEffect(() => {
if (suspense && isSuspenseFirstFetch.current) {
isSuspenseFirstFetch.current = false;
return;
}
const request = client.query(stableQuery, stableVariables, { optimize });
return () => request.cancel();
}, [client, suspense, optimize, stableQuery, stableVariables]);
const [isRefreshing, setIsRefreshing] = react.useState(false);
const refresh = react.useCallback(() => {
setIsRefreshing(true);
return client.request(stableQuery, stableVariables).tap(() => setIsRefreshing(false));
}, [client, stableQuery, stableVariables]);
const [isReloading, setIsReloading] = react.useState(false);
const reload = react.useCallback(() => {
setIsReloading(true);
return client.request(stableQuery, stableVariables).tap(() => setIsReloading(false));
}, [client, stableQuery, stableVariables]);
const isLoading = isRefreshing || isReloading || asyncData.isLoading();
const asyncDataToExpose = isReloading ? boxed.AsyncData.Loading() : isLoading ? previousAsyncData : asyncData;
if (suspense && asyncDataToExpose.isLoading()) {
throw client.query(stableQuery, stableVariables, { optimize }).toPromise();
}
return [asyncDataToExpose, { isLoading, refresh, reload }];
};
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.js.map

@@ -1,3 +0,13 @@

/// <reference types="react" />
import { Client } from "../client";
export declare const ClientContext: import("react").Context<Client>;
import * as react from 'react';
import { Client } from '../client.js';
import 'graphql';
import '@0no-co/graphql.web';
import '@swan-io/boxed';
import '../cache/cache.js';
import '../errors.js';
import '@swan-io/request';
import '../types.js';
declare const ClientContext: react.Context<Client>;
export { ClientContext };

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

import { AsyncData, Future, Result } from "@swan-io/boxed";
import { ClientError } from "../errors";
import { TypedDocumentNode } from "../types";
export type DeferredQueryConfig = {
import { AsyncData, Result, Future } from '@swan-io/boxed';
import { ClientError } from '../errors.js';
import { TypedDocumentNode } from '../types.js';
import '@0no-co/graphql.web';
import '@swan-io/request';
type DeferredQueryConfig = {
optimize?: boolean;
};
export type DeferredQuery<Data, Variables> = readonly [
type DeferredQuery<Data, Variables> = readonly [
AsyncData<Result<Data, ClientError>>,
(variables: Variables) => Future<Result<Data, ClientError>>
];
export declare const useDeferredQuery: <Data, Variables>(query: TypedDocumentNode<Data, Variables>, { optimize }?: DeferredQueryConfig) => DeferredQuery<Data, Variables>;
declare const useDeferredQuery: <Data, Variables>(query: TypedDocumentNode<Data, Variables>, { optimize }?: DeferredQueryConfig) => DeferredQuery<Data, Variables>;
export { type DeferredQuery, type DeferredQueryConfig, useDeferredQuery };

@@ -1,8 +0,13 @@

import { AsyncData, Future, Result } from "@swan-io/boxed";
import { ClientError } from "../errors";
import { TypedDocumentNode } from "../types";
export type Mutation<Data, Variables> = readonly [
import { Future, Result, AsyncData } from '@swan-io/boxed';
import { ClientError } from '../errors.js';
import { TypedDocumentNode } from '../types.js';
import '@0no-co/graphql.web';
import '@swan-io/request';
type Mutation<Data, Variables> = readonly [
(variables: Variables) => Future<Result<Data, ClientError>>,
AsyncData<Result<Data, ClientError>>
];
export declare const useMutation: <Data, Variables>(mutation: TypedDocumentNode<Data, Variables>) => Mutation<Data, Variables>;
declare const useMutation: <Data, Variables>(mutation: TypedDocumentNode<Data, Variables>) => Mutation<Data, Variables>;
export { type Mutation, useMutation };

@@ -14,4 +14,5 @@ type Edge<T> = {

} | null | undefined;
export declare const useForwardPagination: <A, T extends Connection<A>>(connection: T) => T;
export declare const useBackwardPagination: <A, T extends Connection<A>>(connection: T) => T;
export {};
declare const useForwardPagination: <A, T extends Connection<A>>(connection: T) => T;
declare const useBackwardPagination: <A, T extends Connection<A>>(connection: T) => T;
export { type Connection, type Edge, useBackwardPagination, useForwardPagination };

@@ -1,9 +0,12 @@

import { AsyncData, Future, Result } from "@swan-io/boxed";
import { ClientError } from "../errors";
import { TypedDocumentNode } from "../types";
export type QueryConfig = {
import { AsyncData, Result, Future } from '@swan-io/boxed';
import { ClientError } from '../errors.js';
import { TypedDocumentNode } from '../types.js';
import '@0no-co/graphql.web';
import '@swan-io/request';
type QueryConfig = {
suspense?: boolean;
optimize?: boolean;
};
export type Query<Data> = readonly [
type Query<Data> = readonly [
AsyncData<Result<Data, ClientError>>,

@@ -16,2 +19,4 @@ {

];
export declare const useQuery: <Data, Variables>(query: TypedDocumentNode<Data, Variables>, variables: Variables, { suspense, optimize }?: QueryConfig) => Query<Data>;
declare const useQuery: <Data, Variables>(query: TypedDocumentNode<Data, Variables>, variables: Variables, { suspense, optimize }?: QueryConfig) => Query<Data>;
export { type Query, type QueryConfig, useQuery };

@@ -1,3 +0,4 @@

import { DocumentNode } from "@0no-co/graphql.web";
export interface DocumentTypeDecoration<TResult, TVariables> {
import { DocumentNode } from '@0no-co/graphql.web';
interface DocumentTypeDecoration<TResult, TVariables> {
/**

@@ -10,3 +11,3 @@ * This type is used to ensure that the variables you pass in to the query are assignable to Variables

}
export interface TypedDocumentNode<TResult = {
interface TypedDocumentNode<TResult = {
[key: string]: any;

@@ -17,1 +18,3 @@ }, TVariables = {

}
export type { DocumentTypeDecoration, TypedDocumentNode };

@@ -1,7 +0,9 @@

export declare const DEEP_MERGE_DELETE: unique symbol;
export declare const deepMerge: (target: any, source: any) => any;
export declare const containsAll: <T>(a: Set<T>, b: Set<T>) => boolean;
export declare const isRecord: (value: unknown) => value is Record<PropertyKey, unknown>;
export declare const hasOwnProperty: (v: PropertyKey) => boolean;
export declare const deepEqual: (a: any, b: any) => boolean;
export declare const serializeVariables: (variables: Record<string, unknown>) => string;
declare const DEEP_MERGE_DELETE: unique symbol;
declare const deepMerge: (target: any, source: any) => any;
declare const containsAll: <T>(a: Set<T>, b: Set<T>) => boolean;
declare const isRecord: (value: unknown) => value is Record<PropertyKey, unknown>;
declare const hasOwnProperty: (v: PropertyKey) => boolean;
declare const deepEqual: (a: any, b: any) => boolean;
declare const serializeVariables: (variables: Record<string, unknown>) => string;
export { DEEP_MERGE_DELETE, containsAll, deepEqual, deepMerge, hasOwnProperty, isRecord, serializeVariables };
{
"name": "@swan-io/graphql-client",
"version": "0.1.0-alpha",
"version": "0.1.0-alpha10",
"license": "MIT",

@@ -33,3 +33,2 @@ "description": "A simple, typesafe GraphQL client for React",

"scripts": {
"clean": "rm -rf dist",
"lint": "eslint 'src/**/*.{ts,tsx}'",

@@ -40,3 +39,3 @@ "example": "vite example --config vite.config.mjs",

"typecheck": "tsc --noEmit",
"build": "yarn clean && microbundle -f cjs,es --tsconfig tsconfig.build.json",
"build": "tsup",
"prepack": "yarn typecheck && yarn test && yarn build",

@@ -51,6 +50,6 @@ "codegen": "graphql-codegen --config codegen.ts"

"dependencies": {
"@0no-co/graphql.web": "^1.0.4",
"@0no-co/graphql.web": "^1.0.6",
"@swan-io/boxed": "^2.1.1",
"@swan-io/request": "^1.0.2",
"ts-pattern": "^5.0.8"
"ts-pattern": "^5.1.0"
},

@@ -61,9 +60,9 @@ "peerDependencies": {

"devDependencies": {
"@0no-co/graphqlsp": "^1.6.0",
"@0no-co/graphqlsp": "^1.7.1",
"@graphql-codegen/cli": "^5.0.2",
"@types/node": "^20.11.30",
"@types/react": "^18.2.67",
"@types/react-dom": "^18.2.22",
"@typescript-eslint/eslint-plugin": "^7.3.1",
"@typescript-eslint/parser": "^7.3.1",
"@types/node": "^20.12.3",
"@types/react": "^18.2.74",
"@types/react-dom": "^18.2.23",
"@typescript-eslint/eslint-plugin": "^7.5.0",
"@typescript-eslint/parser": "^7.5.0",
"@vitejs/plugin-basic-ssl": "^1.1.0",

@@ -73,5 +72,5 @@ "eslint": "^8.57.0",

"eslint-plugin-react-hooks": "^4.6.0",
"gql.tada": "^1.3.6",
"gql.tada": "^1.4.1",
"graphql": "^16.8.1",
"jsdom": "^24.0.0",
"microbundle": "^0.15.1",
"prettier": "^3.2.5",

@@ -81,7 +80,8 @@ "prettier-plugin-organize-imports": "^3.2.4",

"react-dom": "^18.2.0",
"tsup": "^8.0.2",
"tsx": "^4.7.1",
"typescript": "^5.4.2",
"vite": "^5.2.2",
"typescript": "^5.4.3",
"vite": "^5.2.7",
"vitest": "^1.4.0"
}
}

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

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc