chore: add mobile app

This commit is contained in:
2026-02-07 22:33:02 +01:00
parent db34640acc
commit e89384ad4e
29327 changed files with 3886944 additions and 12 deletions
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2018–2020 Formidable,
Copyright (c) urql GraphQL Team and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+5
View File
@@ -0,0 +1,5 @@
# @urql/core
> The shared core for the highly customizable and versatile GraphQL client, urql
More documentation is available at [formidable.com/open-source/urql](https://formidable.com/open-source/urql/).
File diff suppressed because it is too large Load Diff
+894
View File
@@ -0,0 +1,894 @@
var graphql_web = require('@0no-co/graphql.web');
var wonka = require('wonka');
var generateErrorMessage = (networkErr, graphQlErrs) => {
var error = '';
if (networkErr) return `[Network] ${networkErr.message}`;
if (graphQlErrs) {
for (var i = 0, l = graphQlErrs.length; i < l; i++) {
if (error) error += '\n';
error += `[GraphQL] ${graphQlErrs[i].message}`;
}
}
return error;
};
var rehydrateGraphQlError = error => {
if (error && typeof error.message === 'string' && (error.extensions || error.name === 'GraphQLError')) {
return error;
} else if (typeof error === 'object' && typeof error.message === 'string') {
return new graphql_web.GraphQLError(error.message, error.nodes, error.source, error.positions, error.path, error, error.extensions || {});
} else {
return new graphql_web.GraphQLError(error);
}
};
/** An abstracted `Error` that provides either a `networkError` or `graphQLErrors`.
*
* @remarks
* During a GraphQL request, either the request can fail entirely, causing a network error,
* or the GraphQL execution or fields can fail, which will cause an {@link ExecutionResult}
* to contain an array of GraphQL errors.
*
* The `CombinedError` abstracts and normalizes both failure cases. When {@link OperationResult.error}
* is set to this error, the `CombinedError` abstracts all errors, making it easier to handle only
* a subset of error cases.
*
* @see {@link https://urql.dev/goto/docs/basics/errors} for more information on handling
* GraphQL errors and the `CombinedError`.
*/
class CombinedError extends Error {
/** A list of GraphQL errors rehydrated from a {@link ExecutionResult}.
*
* @remarks
* If an {@link ExecutionResult} received from the API contains a list of errors,
* the `CombinedError` will rehydrate them, normalize them to
* {@link GraphQLError | GraphQLErrors} and list them here.
* An empty list indicates that no GraphQL error has been sent by the API.
*/
/** Set to an error, if a GraphQL request has failed outright.
*
* @remarks
* A GraphQL over HTTP request may fail and not reach the API. Any error that
* prevents a GraphQl request outright, will be considered a “network error” and
* set here.
*/
/** Set to the {@link Response} object a fetch exchange received.
*
* @remarks
* If a built-in fetch {@link Exchange} is used in `urql`, this may
* be set to the {@link Response} object of the Fetch API response.
* However, since `urql` doesn’t assume that all users will use HTTP
* as the only or exclusive transport for GraphQL this property is
* neither typed nor guaranteed and may be re-used for other purposes
* by non-fetch exchanges.
*
* Hint: It can be useful to use `response.status` here, however, if
* you plan on relying on this being a {@link Response} in your app,
* which it is by default, then make sure you add some extra checks
* before blindly assuming so!
*/
constructor(input) {
var normalizedGraphQLErrors = (input.graphQLErrors || []).map(rehydrateGraphQlError);
var message = generateErrorMessage(input.networkError, normalizedGraphQLErrors);
super(message);
this.name = 'CombinedError';
this.message = message;
this.graphQLErrors = normalizedGraphQLErrors;
this.networkError = input.networkError;
this.response = input.response;
}
toString() {
return this.message;
}
}
/** A hash value as computed by {@link phash}.
*
* @remarks
* Typically `HashValue`s are used as hashes and keys of GraphQL documents,
* variables, and combined, for GraphQL requests.
*/
/** Computes a djb2 hash of the given string.
*
* @param x - the string to be hashed
* @param seed - optionally a prior hash for progressive hashing
* @returns a hash value, i.e. a number
*
* @remark
* This is the hashing function used throughout `urql`, primarily to compute
* {@link Operation.key}.
*
* @see {@link http://www.cse.yorku.ca/~oz/hash.html#djb2} for a further description of djb2.
*/
var phash = (x, seed) => {
var h = (seed || 5381) | 0;
for (var i = 0, l = x.length | 0; i < l; i++) h = (h << 5) + h + x.charCodeAt(i);
return h;
};
var seen = new Set();
var cache = new WeakMap();
var stringify = (x, includeFiles) => {
if (x === null || seen.has(x)) {
return 'null';
} else if (typeof x !== 'object') {
return JSON.stringify(x) || '';
} else if (x.toJSON) {
return stringify(x.toJSON(), includeFiles);
} else if (Array.isArray(x)) {
var _out = '[';
for (var i = 0, l = x.length; i < l; i++) {
if (_out.length > 1) _out += ',';
_out += stringify(x[i], includeFiles) || 'null';
}
_out += ']';
return _out;
} else if (!includeFiles && (FileConstructor !== NoopConstructor && x instanceof FileConstructor || BlobConstructor !== NoopConstructor && x instanceof BlobConstructor)) {
return 'null';
}
var keys = Object.keys(x).sort();
if (!keys.length && x.constructor && Object.getPrototypeOf(x).constructor !== Object.prototype.constructor) {
var key = cache.get(x) || Math.random().toString(36).slice(2);
cache.set(x, key);
return stringify({
__key: key
}, includeFiles);
}
seen.add(x);
var out = '{';
for (var _i = 0, _l = keys.length; _i < _l; _i++) {
var value = stringify(x[keys[_i]], includeFiles);
if (value) {
if (out.length > 1) out += ',';
out += stringify(keys[_i], includeFiles) + ':' + value;
}
}
seen.delete(x);
out += '}';
return out;
};
var extract = (map, path, x) => {
if (x == null || typeof x !== 'object' || x.toJSON || seen.has(x)) ; else if (Array.isArray(x)) {
for (var i = 0, l = x.length; i < l; i++) extract(map, `${path}.${i}`, x[i]);
} else if (x instanceof FileConstructor || x instanceof BlobConstructor) {
map.set(path, x);
} else {
seen.add(x);
for (var key in x) extract(map, `${path}.${key}`, x[key]);
}
};
/** A stable stringifier for GraphQL variables objects.
*
* @param x - any JSON-like data.
* @return A JSON string.
*
* @remarks
* This utility creates a stable JSON string from any passed data,
* and protects itself from throwing.
*
* The JSON string is stable insofar as objects’ keys are sorted,
* and instances of non-plain objects are replaced with random keys
* replacing their values, which remain stable for the objects’
* instance.
*/
var stringifyVariables = (x, includeFiles) => {
seen.clear();
return stringify(x, includeFiles || false);
};
class NoopConstructor {}
var FileConstructor = typeof File !== 'undefined' ? File : NoopConstructor;
var BlobConstructor = typeof Blob !== 'undefined' ? Blob : NoopConstructor;
var extractFiles = x => {
var map = new Map();
if (FileConstructor !== NoopConstructor || BlobConstructor !== NoopConstructor) {
seen.clear();
extract(map, 'variables', x);
}
return map;
};
/** A `DocumentNode` annotated with its hashed key.
* @internal
*/
var SOURCE_NAME = 'gql';
var GRAPHQL_STRING_RE = /("{3}[\s\S]*"{3}|"(?:\\.|[^"])*")/g;
var REPLACE_CHAR_RE = /(?:#[^\n\r]+)?(?:[\r\n]+|$)/g;
var replaceOutsideStrings = (str, idx) => idx % 2 === 0 ? str.replace(REPLACE_CHAR_RE, '\n') : str;
/** Sanitizes a GraphQL document string by replacing comments and redundant newlines in it. */
var sanitizeDocument = node => node.split(GRAPHQL_STRING_RE).map(replaceOutsideStrings).join('').trim();
var prints = new Map();
var docs = new Map();
/** A cached printing function for GraphQL documents.
*
* @param node - A string of a document or a {@link DocumentNode}
* @returns A normalized printed string of the passed GraphQL document.
*
* @remarks
* This function accepts a GraphQL query string or {@link DocumentNode},
* then prints and sanitizes it. The sanitizer takes care of removing
* comments, which otherwise alter the key of the document although the
* document is otherwise equivalent to another.
*
* When a {@link DocumentNode} is passed to this function, it caches its
* output by modifying the `loc.source.body` property on the GraphQL node.
*/
var stringifyDocument = node => {
var printed;
if (typeof node === 'string') {
printed = sanitizeDocument(node);
} else if (node.loc && docs.get(node.__key) === node) {
printed = node.loc.source.body;
} else {
printed = prints.get(node) || sanitizeDocument(graphql_web.print(node));
prints.set(node, printed);
}
if (typeof node !== 'string' && !node.loc) {
node.loc = {
start: 0,
end: printed.length,
source: {
body: printed,
name: SOURCE_NAME,
locationOffset: {
line: 1,
column: 1
}
}
};
}
return printed;
};
/** Computes the hash for a document's string using {@link stringifyDocument}'s output.
*
* @param node - A string of a document or a {@link DocumentNode}
* @returns A {@link HashValue}
*
* @privateRemarks
* This function adds the operation name of the document to the hash, since sometimes
* a merged document with multiple operations may be used. Although `urql` requires a
* `DocumentNode` to only contain a single operation, when the cached `loc.source.body`
* of a `DocumentNode` is used, this string may still contain multiple operations and
* the resulting hash should account for only one at a time.
*/
var hashDocument = node => {
var key;
if (node.documentId) {
key = phash(node.documentId);
} else {
key = phash(stringifyDocument(node));
// Add the operation name to the produced hash
if (node.definitions) {
var operationName = getOperationName(node);
if (operationName) key = phash(`\n# ${operationName}`, key);
}
}
return key;
};
/** Returns a canonical version of the passed `DocumentNode` with an added hash key.
*
* @param node - A string of a document or a {@link DocumentNode}
* @returns A {@link KeyedDocumentNode}
*
* @remarks
* `urql` will always avoid unnecessary work, no matter whether a user passes `DocumentNode`s
* or strings of GraphQL documents to its APIs.
*
* This function will return a canonical version of a {@link KeyedDocumentNode} no matter
* which kind of input is passed, avoiding parsing or hashing of passed data as needed.
*/
var keyDocument = node => {
var key;
var query;
if (typeof node === 'string') {
key = hashDocument(node);
query = docs.get(key) || graphql_web.parse(node, {
noLocation: true
});
} else {
key = node.__key || hashDocument(node);
query = docs.get(key) || node;
}
// Add location information if it's missing
if (!query.loc) stringifyDocument(query);
query.__key = key;
docs.set(key, query);
return query;
};
/** Creates a `GraphQLRequest` from the passed parameters.
*
* @param q - A string of a document or a {@link DocumentNode}
* @param variables - A variables object for the defined GraphQL operation.
* @returns A {@link GraphQLRequest}
*
* @remarks
* `createRequest` creates a {@link GraphQLRequest} from the passed parameters,
* while replacing the document as needed with a canonical version of itself,
* to avoid parsing, printing, or hashing the same input multiple times.
*
* If no variables are passed, canonically it'll default to an empty object,
* which is removed from the resulting hash key.
*/
var createRequest = (_query, _variables, extensions) => {
var variables = _variables || {};
var query = keyDocument(_query);
var printedVars = stringifyVariables(variables, true);
var key = query.__key;
if (printedVars !== '{}') key = phash(printedVars, key);
return {
key,
query,
variables,
extensions
};
};
/** Returns the name of the `DocumentNode`'s operation, if any.
* @param query - A {@link DocumentNode}
* @returns the operation's name contained within the document, or `undefined`
*/
var getOperationName = query => {
for (var i = 0, l = query.definitions.length; i < l; i++) {
var node = query.definitions[i];
if (node.kind === graphql_web.Kind.OPERATION_DEFINITION) {
return node.name ? node.name.value : undefined;
}
}
};
/** Returns the type of the `DocumentNode`'s operation, if any.
* @param query - A {@link DocumentNode}
* @returns the operation's type contained within the document, or `undefined`
*/
var getOperationType = query => {
for (var i = 0, l = query.definitions.length; i < l; i++) {
var node = query.definitions[i];
if (node.kind === graphql_web.Kind.OPERATION_DEFINITION) {
return node.operation;
}
}
};
/** Converts the `ExecutionResult` received for a given `Operation` to an `OperationResult`.
*
* @param operation - The {@link Operation} for which the API’s result is for.
* @param result - The GraphQL API’s {@link ExecutionResult}.
* @param response - Optionally, a raw object representing the API’s result (Typically a {@link Response}).
* @returns An {@link OperationResult}.
*
* @remarks
* This utility can be used to create {@link OperationResult | OperationResults} in the shape
* that `urql` expects and defines, and should be used rather than creating the results manually.
*
* @throws
* If no data, or errors are contained within the result, or the result is instead an incremental
* response containing a `path` property, a “No Content” error is thrown.
*
* @see {@link ExecutionResult} for the type definition of GraphQL API results.
*/
var makeResult = (operation, result, response) => {
if (!('data' in result) && (!('errors' in result) || !Array.isArray(result.errors))) {
throw new Error('No Content');
}
var defaultHasNext = operation.kind === 'subscription';
return {
operation,
data: result.data,
error: Array.isArray(result.errors) ? new CombinedError({
graphQLErrors: result.errors,
response
}) : undefined,
extensions: result.extensions ? {
...result.extensions
} : undefined,
hasNext: result.hasNext == null ? defaultHasNext : result.hasNext,
stale: false
};
};
var deepMerge = (target, source) => {
if (typeof target === 'object' && target != null) {
if (Array.isArray(target)) {
target = [...target];
for (var i = 0, l = source.length; i < l; i++) target[i] = deepMerge(target[i], source[i]);
return target;
}
if (!target.constructor || target.constructor === Object) {
target = {
...target
};
for (var key in source) target[key] = deepMerge(target[key], source[key]);
return target;
}
}
return source;
};
/** Merges an incrementally delivered `ExecutionResult` into a previous `OperationResult`.
*
* @param prevResult - The {@link OperationResult} that preceded this result.
* @param path - The GraphQL API’s {@link ExecutionResult} that should be patching the `prevResult`.
* @param response - Optionally, a raw object representing the API’s result (Typically a {@link Response}).
* @returns A new {@link OperationResult} patched with the incremental result.
*
* @remarks
* This utility should be used to merge subsequent {@link ExecutionResult | ExecutionResults} of
* incremental responses into a prior {@link OperationResult}.
*
* When directives like `@defer`, `@stream`, and `@live` are used, GraphQL may deliver new
* results that modify previous results. In these cases, it'll set a `path` property to modify
* the result it sent last. This utility is built to handle these cases and merge these payloads
* into existing {@link OperationResult | OperationResults}.
*
* @see {@link ExecutionResult} for the type definition of GraphQL API results.
*/
var mergeResultPatch = (prevResult, nextResult, response, pending) => {
var errors = prevResult.error ? prevResult.error.graphQLErrors : [];
var hasExtensions = !!prevResult.extensions || !!(nextResult.payload || nextResult).extensions;
var extensions = {
...prevResult.extensions,
...(nextResult.payload || nextResult).extensions
};
var incremental = nextResult.incremental;
// NOTE: We handle the old version of the incremental delivery payloads as well
if ('path' in nextResult) {
incremental = [nextResult];
}
var withData = {
data: prevResult.data
};
if (incremental) {
var _loop = function () {
var patch = incremental[i];
if (Array.isArray(patch.errors)) {
errors.push(...patch.errors);
}
if (patch.extensions) {
Object.assign(extensions, patch.extensions);
hasExtensions = true;
}
var prop = 'data';
var part = withData;
var path = [];
if (patch.path) {
path = patch.path;
} else if (pending) {
var res = pending.find(pendingRes => pendingRes.id === patch.id);
if (patch.subPath) {
path = [...res.path, ...patch.subPath];
} else {
path = res.path;
}
}
for (var _i = 0, _l = path.length; _i < _l; prop = path[_i++]) {
part = part[prop] = Array.isArray(part[prop]) ? [...part[prop]] : {
...part[prop]
};
}
if (patch.items) {
var startIndex = +prop >= 0 ? prop : 0;
for (var _i2 = 0, _l2 = patch.items.length; _i2 < _l2; _i2++) part[startIndex + _i2] = deepMerge(part[startIndex + _i2], patch.items[_i2]);
} else if (patch.data !== undefined) {
part[prop] = deepMerge(part[prop], patch.data);
}
};
for (var i = 0, l = incremental.length; i < l; i++) {
_loop();
}
} else {
withData.data = (nextResult.payload || nextResult).data || prevResult.data;
errors = nextResult.errors || nextResult.payload && nextResult.payload.errors || errors;
}
return {
operation: prevResult.operation,
data: withData.data,
error: errors.length ? new CombinedError({
graphQLErrors: errors,
response
}) : undefined,
extensions: hasExtensions ? extensions : undefined,
hasNext: nextResult.hasNext != null ? nextResult.hasNext : prevResult.hasNext,
stale: false
};
};
/** Creates an `OperationResult` containing a network error for requests that encountered unexpected errors.
*
* @param operation - The {@link Operation} for which the API’s result is for.
* @param error - The network-like error that prevented an API result from being delivered.
* @param response - Optionally, a raw object representing the API’s result (Typically a {@link Response}).
* @returns An {@link OperationResult} containing only a {@link CombinedError}.
*
* @remarks
* This utility can be used to create {@link OperationResult | OperationResults} in the shape
* that `urql` expects and defines, and should be used rather than creating the results manually.
* This function should be used for when the {@link CombinedError.networkError} property is
* populated and no GraphQL execution actually occurred.
*/
var makeErrorResult = (operation, error, response) => ({
operation,
data: undefined,
error: new CombinedError({
networkError: error,
response
}),
extensions: undefined,
hasNext: false,
stale: false
});
/** Abstract definition of the JSON data sent during GraphQL HTTP POST requests. */
/** Creates a GraphQL over HTTP compliant JSON request body.
* @param request - An object containing a `query` document and `variables`.
* @returns A {@link FetchBody}
* @see {@link https://github.com/graphql/graphql-over-http} for the GraphQL over HTTP spec.
*/
function makeFetchBody(request) {
var body = {
query: undefined,
documentId: undefined,
operationName: getOperationName(request.query),
variables: request.variables || undefined,
extensions: request.extensions
};
if ('documentId' in request.query && request.query.documentId && (
// NOTE: We have to check that the document will definitely be sent
// as a persisted document to avoid breaking changes
!request.query.definitions || !request.query.definitions.length)) {
body.documentId = request.query.documentId;
} else if (!request.extensions || !request.extensions.persistedQuery || !!request.extensions.persistedQuery.miss) {
body.query = stringifyDocument(request.query);
}
return body;
}
/** Creates a URL that will be called for a GraphQL HTTP request.
*
* @param operation - An {@link Operation} for which to make the request.
* @param body - A {@link FetchBody} which may be replaced with a URL.
*
* @remarks
* Creates the URL that’ll be called as part of a GraphQL HTTP request.
* Built-in fetch exchanges support sending GET requests, even for
* non-persisted full requests, which this function supports by being
* able to serialize GraphQL requests into the URL.
*/
var makeFetchURL = (operation, body) => {
var useGETMethod = operation.kind === 'query' && operation.context.preferGetMethod;
if (!useGETMethod || !body) return operation.context.url;
var urlParts = splitOutSearchParams(operation.context.url);
for (var key in body) {
var value = body[key];
if (value) {
urlParts[1].set(key, typeof value === 'object' ? stringifyVariables(value) : value);
}
}
var finalUrl = urlParts.join('?');
if (finalUrl.length > 2047 && useGETMethod !== 'force') {
operation.context.preferGetMethod = false;
return operation.context.url;
}
return finalUrl;
};
var splitOutSearchParams = url => {
var start = url.indexOf('?');
return start > -1 ? [url.slice(0, start), new URLSearchParams(url.slice(start + 1))] : [url, new URLSearchParams()];
};
/** Serializes a {@link FetchBody} into a {@link RequestInit.body} format. */
var serializeBody = (operation, body) => {
var omitBody = operation.kind === 'query' && !!operation.context.preferGetMethod;
if (body && !omitBody) {
var json = stringifyVariables(body);
var files = extractFiles(body.variables);
if (files.size) {
var form = new FormData();
form.append('operations', json);
form.append('map', stringifyVariables({
...[...files.keys()].map(value => [value])
}));
var index = 0;
for (var file of files.values()) form.append(`${index++}`, file);
return form;
}
return json;
}
};
var isHeaders = headers => 'has' in headers && !Object.keys(headers).length;
/** Creates a `RequestInit` object for a given `Operation`.
*
* @param operation - An {@link Operation} for which to make the request.
* @param body - A {@link FetchBody} which is added to the options, if the request isn’t a GET request.
*
* @remarks
* Creates the fetch options {@link RequestInit} object that’ll be passed to the Fetch API
* as part of a GraphQL over HTTP request. It automatically sets a default `Content-Type`
* header.
*
* @see {@link https://github.com/graphql/graphql-over-http} for the GraphQL over HTTP spec.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API} for the Fetch API spec.
*/
var makeFetchOptions = (operation, body) => {
var headers = {
accept: operation.kind === 'subscription' ? 'text/event-stream, multipart/mixed' : 'application/graphql-response+json, application/graphql+json, application/json, text/event-stream, multipart/mixed'
};
var extraOptions = (typeof operation.context.fetchOptions === 'function' ? operation.context.fetchOptions() : operation.context.fetchOptions) || {};
if (extraOptions.headers) {
if (isHeaders(extraOptions.headers)) {
extraOptions.headers.forEach((value, key) => {
headers[key] = value;
});
} else if (Array.isArray(extraOptions.headers)) {
extraOptions.headers.forEach((value, key) => {
if (Array.isArray(value)) {
if (headers[value[0]]) {
headers[value[0]] = `${headers[value[0]]},${value[1]}`;
} else {
headers[value[0]] = value[1];
}
} else {
headers[key] = value;
}
});
} else {
for (var key in extraOptions.headers) {
headers[key.toLowerCase()] = extraOptions.headers[key];
}
}
}
var serializedBody = serializeBody(operation, body);
if (typeof serializedBody === 'string' && !headers['content-type']) headers['content-type'] = 'application/json';
return {
...extraOptions,
method: serializedBody ? 'POST' : 'GET',
body: serializedBody,
headers
};
};
/* Summary: This file handles the HTTP transport via GraphQL over HTTP
* See: https://graphql.github.io/graphql-over-http/draft/
*
* `@urql/core`, by default, implements several RFC'd protocol extensions
* on top of this. As such, this implementation supports:
* - [Incremental Delivery](https://github.com/graphql/graphql-over-http/blob/main/rfcs/IncrementalDelivery.md)
* - [GraphQL over SSE](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverSSE.md)
*
* This also supports the "Defer Stream" payload format.
* See: https://github.com/graphql/graphql-wg/blob/main/rfcs/DeferStream.md
* Implementation for this is located in `../utils/result.ts` in `mergeResultPatch`
*
* And; this also supports the GraphQL Multipart spec for file uploads.
* See: https://github.com/jaydenseric/graphql-multipart-request-spec
* Implementation for this is located in `../utils/variables.ts` in `extractFiles`,
* and `./fetchOptions.ts` in `serializeBody`.
*
* And; this also supports GET requests (and hence; automatic persisted queries)
* via the `@urql/exchange-persisted` package.
*
* This implementation DOES NOT support Batching.
* See: https://github.com/graphql/graphql-over-http/blob/main/rfcs/Batching.md
* Which is deemed out-of-scope, as it's sufficiently unnecessary given
* modern handling of HTTP requests being in parallel.
*
* The implementation in this file needs to make certain accommodations for:
* - The Web Fetch API
* - Non-browser or polyfill Fetch APIs
* - Node.js-like Fetch implementations
*
* GraphQL over SSE has a reference implementation, which supports non-HTTP/2
* modes and is a faithful implementation of the spec.
* See: https://github.com/enisdenjo/graphql-sse
*
* GraphQL Inremental Delivery (aka “GraphQL Multipart Responses”) has a
* reference implementation, which a prior implementation of this file heavily
* leaned on (See prior attribution comments)
* See: https://github.com/maraisr/meros
*
* This file merges support for all three GraphQL over HTTP response formats
* via async generators and Wonka’s `fromAsyncIterable`. As part of this, `streamBody`
* and `split` are the common, cross-compatible base implementations.
*/
var boundaryHeaderRe = /boundary="?([^=";]+)"?/i;
var eventStreamRe = /data: ?([^\n]+)/;
async function* streamBody(response) {
if (response.body[Symbol.asyncIterator]) {
for await (var chunk of response.body) yield chunk;
} else {
var reader = response.body.getReader();
var result;
try {
while (!(result = await reader.read()).done) yield result.value;
} finally {
reader.cancel();
}
}
}
async function* streamToBoundedChunks(chunks, boundary) {
var decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder() : null;
var buffer = '';
var boundaryIndex;
for await (var chunk of chunks) {
// NOTE: We're avoiding referencing the `Buffer` global here to prevent
// auto-polyfilling in Webpack
buffer += chunk.constructor.name === 'Buffer' ? chunk.toString() : decoder.decode(chunk, {
stream: true
});
while ((boundaryIndex = buffer.indexOf(boundary)) > -1) {
yield buffer.slice(0, boundaryIndex);
buffer = buffer.slice(boundaryIndex + boundary.length);
}
}
}
async function* parseJSON(response) {
yield JSON.parse(await response.text());
}
async function* parseEventStream(response) {
var payload;
for await (var chunk of streamToBoundedChunks(streamBody(response), '\n\n')) {
var match = chunk.match(eventStreamRe);
if (match) {
var _chunk = match[1];
try {
yield payload = JSON.parse(_chunk);
} catch (error) {
if (!payload) throw error;
}
if (payload && payload.hasNext === false) break;
}
}
if (payload && payload.hasNext !== false) {
yield {
hasNext: false
};
}
}
async function* parseMultipartMixed(contentType, response) {
var boundaryHeader = contentType.match(boundaryHeaderRe);
var boundary = '--' + (boundaryHeader ? boundaryHeader[1] : '-');
var isPreamble = true;
var payload;
for await (var chunk of streamToBoundedChunks(streamBody(response), '\r\n' + boundary)) {
if (isPreamble) {
isPreamble = false;
var preambleIndex = chunk.indexOf(boundary);
if (preambleIndex > -1) {
chunk = chunk.slice(preambleIndex + boundary.length);
} else {
continue;
}
}
try {
yield payload = JSON.parse(chunk.slice(chunk.indexOf('\r\n\r\n') + 4));
} catch (error) {
if (!payload) throw error;
}
if (payload && payload.hasNext === false) break;
}
if (payload && payload.hasNext !== false) {
yield {
hasNext: false
};
}
}
async function* parseMaybeJSON(response) {
var text = await response.text();
try {
var result = JSON.parse(text);
if (process.env.NODE_ENV !== 'production') {
console.warn(`Found response with content-type "text/plain" but it had a valid "application/json" response.`);
}
yield result;
} catch (e) {
throw new Error(text);
}
}
async function* fetchOperation(operation, url, fetchOptions) {
var networkMode = true;
var result = null;
var response;
try {
// Delay for a tick to give the Client a chance to cancel the request
// if a teardown comes in immediately
yield await Promise.resolve();
response = await (operation.context.fetch || fetch)(url, fetchOptions);
var contentType = response.headers.get('Content-Type') || '';
var results;
if (/multipart\/mixed/i.test(contentType)) {
results = parseMultipartMixed(contentType, response);
} else if (/text\/event-stream/i.test(contentType)) {
results = parseEventStream(response);
} else if (!/text\//i.test(contentType)) {
results = parseJSON(response);
} else {
results = parseMaybeJSON(response);
}
var pending;
for await (var payload of results) {
if (payload.pending && !result) {
pending = payload.pending;
} else if (payload.pending) {
pending = [...pending, ...payload.pending];
}
result = result ? mergeResultPatch(result, payload, response, pending) : makeResult(operation, payload, response);
networkMode = false;
yield result;
networkMode = true;
}
if (!result) {
yield result = makeResult(operation, {}, response);
}
} catch (error) {
if (!networkMode) {
throw error;
}
yield makeErrorResult(operation, response && (response.status < 200 || response.status >= 300) && response.statusText ? new Error(response.statusText) : error, response);
}
}
/** Makes a GraphQL HTTP request to a given API by wrapping around the Fetch API.
*
* @param operation - The {@link Operation} that should be sent via GraphQL over HTTP.
* @param url - The endpoint URL for the GraphQL HTTP API.
* @param fetchOptions - The {@link RequestInit} fetch options for the request.
* @returns A Wonka {@link Source} of {@link OperationResult | OperationResults}.
*
* @remarks
* This utility defines how all built-in fetch exchanges make GraphQL HTTP requests,
* supporting multipart incremental responses, cancellation and other smaller
* implementation details.
*
* If you’re implementing a modified fetch exchange for a GraphQL over HTTP API
* it’s recommended you use this utility.
*
* Hint: This function does not use the passed `operation` to create or modify the
* `fetchOptions` and instead expects that the options have already been created
* using {@link makeFetchOptions} and modified as needed.
*
* @throws
* If the `fetch` polyfill or globally available `fetch` function doesn’t support
* streamed multipart responses while trying to handle a `multipart/mixed` GraphQL response,
* the source will throw “Streaming requests unsupported”.
* This shouldn’t happen in modern browsers and Node.js.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API} for the Fetch API spec.
*/
function makeFetchSource(operation, url, fetchOptions) {
var abortController;
if (typeof AbortController !== 'undefined') {
fetchOptions.signal = (abortController = new AbortController()).signal;
}
return wonka.onEnd(() => {
if (abortController) abortController.abort();
})(wonka.filter(result => !!result)(wonka.fromAsyncIterable(fetchOperation(operation, url, fetchOptions))));
}
exports.CombinedError = CombinedError;
exports.createRequest = createRequest;
exports.getOperationName = getOperationName;
exports.getOperationType = getOperationType;
exports.keyDocument = keyDocument;
exports.makeErrorResult = makeErrorResult;
exports.makeFetchBody = makeFetchBody;
exports.makeFetchOptions = makeFetchOptions;
exports.makeFetchSource = makeFetchSource;
exports.makeFetchURL = makeFetchURL;
exports.makeResult = makeResult;
exports.mergeResultPatch = mergeResultPatch;
exports.stringifyDocument = stringifyDocument;
exports.stringifyVariables = stringifyVariables;
//# sourceMappingURL=urql-core-chunk.js.map
File diff suppressed because one or more lines are too long
+624
View File
@@ -0,0 +1,624 @@
import { GraphQLError as e, print as r, Kind as t, parse as a } from "@0no-co/graphql.web";
import { onEnd as n, filter as o, fromAsyncIterable as s } from "wonka";
var rehydrateGraphQlError = r => {
if (r && "string" == typeof r.message && (r.extensions || "GraphQLError" === r.name)) {
return r;
} else if ("object" == typeof r && "string" == typeof r.message) {
return new e(r.message, r.nodes, r.source, r.positions, r.path, r, r.extensions || {});
} else {
return new e(r);
}
};
class CombinedError extends Error {
constructor(e) {
var r = (e.graphQLErrors || []).map(rehydrateGraphQlError);
var t = ((e, r) => {
var t = "";
if (e) {
return `[Network] ${e.message}`;
}
if (r) {
for (var a = 0, n = r.length; a < n; a++) {
if (t) {
t += "\n";
}
t += `[GraphQL] ${r[a].message}`;
}
}
return t;
})(e.networkError, r);
super(t);
this.name = "CombinedError";
this.message = t;
this.graphQLErrors = r;
this.networkError = e.networkError;
this.response = e.response;
}
toString() {
return this.message;
}
}
var phash = (e, r) => {
var t = 0 | (r || 5381);
for (var a = 0, n = 0 | e.length; a < n; a++) {
t = (t << 5) + t + e.charCodeAt(a);
}
return t;
};
var i = new Set;
var f = new WeakMap;
var stringify = (e, r) => {
if (null === e || i.has(e)) {
return "null";
} else if ("object" != typeof e) {
return JSON.stringify(e) || "";
} else if (e.toJSON) {
return stringify(e.toJSON(), r);
} else if (Array.isArray(e)) {
var t = "[";
for (var a = 0, n = e.length; a < n; a++) {
if (t.length > 1) {
t += ",";
}
t += stringify(e[a], r) || "null";
}
return t += "]";
} else if (!r && (d !== NoopConstructor && e instanceof d || l !== NoopConstructor && e instanceof l)) {
return "null";
}
var o = Object.keys(e).sort();
if (!o.length && e.constructor && Object.getPrototypeOf(e).constructor !== Object.prototype.constructor) {
var s = f.get(e) || Math.random().toString(36).slice(2);
f.set(e, s);
return stringify({
__key: s
}, r);
}
i.add(e);
var c = "{";
for (var v = 0, u = o.length; v < u; v++) {
var p = stringify(e[o[v]], r);
if (p) {
if (c.length > 1) {
c += ",";
}
c += stringify(o[v], r) + ":" + p;
}
}
i.delete(e);
return c += "}";
};
var extract = (e, r, t) => {
if (null == t || "object" != typeof t || t.toJSON || i.has(t)) {} else if (Array.isArray(t)) {
for (var a = 0, n = t.length; a < n; a++) {
extract(e, `${r}.${a}`, t[a]);
}
} else if (t instanceof d || t instanceof l) {
e.set(r, t);
} else {
i.add(t);
for (var o in t) {
extract(e, `${r}.${o}`, t[o]);
}
}
};
var stringifyVariables = (e, r) => {
i.clear();
return stringify(e, r || !1);
};
class NoopConstructor {}
var d = "undefined" != typeof File ? File : NoopConstructor;
var l = "undefined" != typeof Blob ? Blob : NoopConstructor;
var c = /("{3}[\s\S]*"{3}|"(?:\\.|[^"])*")/g;
var v = /(?:#[^\n\r]+)?(?:[\r\n]+|$)/g;
var replaceOutsideStrings = (e, r) => r % 2 == 0 ? e.replace(v, "\n") : e;
var sanitizeDocument = e => e.split(c).map(replaceOutsideStrings).join("").trim();
var u = new Map;
var p = new Map;
var stringifyDocument = e => {
var t;
if ("string" == typeof e) {
t = sanitizeDocument(e);
} else if (e.loc && p.get(e.__key) === e) {
t = e.loc.source.body;
} else {
t = u.get(e) || sanitizeDocument(r(e));
u.set(e, t);
}
if ("string" != typeof e && !e.loc) {
e.loc = {
start: 0,
end: t.length,
source: {
body: t,
name: "gql",
locationOffset: {
line: 1,
column: 1
}
}
};
}
return t;
};
var hashDocument = e => {
var r;
if (e.documentId) {
r = phash(e.documentId);
} else {
r = phash(stringifyDocument(e));
if (e.definitions) {
var t = getOperationName(e);
if (t) {
r = phash(`\n# ${t}`, r);
}
}
}
return r;
};
var keyDocument = e => {
var r;
var t;
if ("string" == typeof e) {
r = hashDocument(e);
t = p.get(r) || a(e, {
noLocation: !0
});
} else {
r = e.__key || hashDocument(e);
t = p.get(r) || e;
}
if (!t.loc) {
stringifyDocument(t);
}
t.__key = r;
p.set(r, t);
return t;
};
var createRequest = (e, r, t) => {
var a = r || {};
var n = keyDocument(e);
var o = stringifyVariables(a, !0);
var s = n.__key;
if ("{}" !== o) {
s = phash(o, s);
}
return {
key: s,
query: n,
variables: a,
extensions: t
};
};
var getOperationName = e => {
for (var r = 0, a = e.definitions.length; r < a; r++) {
var n = e.definitions[r];
if (n.kind === t.OPERATION_DEFINITION) {
return n.name ? n.name.value : void 0;
}
}
};
var getOperationType = e => {
for (var r = 0, a = e.definitions.length; r < a; r++) {
var n = e.definitions[r];
if (n.kind === t.OPERATION_DEFINITION) {
return n.operation;
}
}
};
var makeResult = (e, r, t) => {
if (!("data" in r || "errors" in r && Array.isArray(r.errors))) {
throw new Error("No Content");
}
var a = "subscription" === e.kind;
return {
operation: e,
data: r.data,
error: Array.isArray(r.errors) ? new CombinedError({
graphQLErrors: r.errors,
response: t
}) : void 0,
extensions: r.extensions ? {
...r.extensions
} : void 0,
hasNext: null == r.hasNext ? a : r.hasNext,
stale: !1
};
};
var deepMerge = (e, r) => {
if ("object" == typeof e && null != e) {
if (Array.isArray(e)) {
e = [ ...e ];
for (var t = 0, a = r.length; t < a; t++) {
e[t] = deepMerge(e[t], r[t]);
}
return e;
}
if (!e.constructor || e.constructor === Object) {
e = {
...e
};
for (var n in r) {
e[n] = deepMerge(e[n], r[n]);
}
return e;
}
}
return r;
};
var mergeResultPatch = (e, r, t, a) => {
var n = e.error ? e.error.graphQLErrors : [];
var o = !!e.extensions || !!(r.payload || r).extensions;
var s = {
...e.extensions,
...(r.payload || r).extensions
};
var i = r.incremental;
if ("path" in r) {
i = [ r ];
}
var f = {
data: e.data
};
if (i) {
var _loop = function() {
var e = i[d];
if (Array.isArray(e.errors)) {
n.push(...e.errors);
}
if (e.extensions) {
Object.assign(s, e.extensions);
o = !0;
}
var r = "data";
var t = f;
var l = [];
if (e.path) {
l = e.path;
} else if (a) {
var c = a.find((r => r.id === e.id));
if (e.subPath) {
l = [ ...c.path, ...e.subPath ];
} else {
l = c.path;
}
}
for (var v = 0, u = l.length; v < u; r = l[v++]) {
t = t[r] = Array.isArray(t[r]) ? [ ...t[r] ] : {
...t[r]
};
}
if (e.items) {
var p = +r >= 0 ? r : 0;
for (var h = 0, y = e.items.length; h < y; h++) {
t[p + h] = deepMerge(t[p + h], e.items[h]);
}
} else if (void 0 !== e.data) {
t[r] = deepMerge(t[r], e.data);
}
};
for (var d = 0, l = i.length; d < l; d++) {
_loop();
}
} else {
f.data = (r.payload || r).data || e.data;
n = r.errors || r.payload && r.payload.errors || n;
}
return {
operation: e.operation,
data: f.data,
error: n.length ? new CombinedError({
graphQLErrors: n,
response: t
}) : void 0,
extensions: o ? s : void 0,
hasNext: null != r.hasNext ? r.hasNext : e.hasNext,
stale: !1
};
};
var makeErrorResult = (e, r, t) => ({
operation: e,
data: void 0,
error: new CombinedError({
networkError: r,
response: t
}),
extensions: void 0,
hasNext: !1,
stale: !1
});
function makeFetchBody(e) {
var r = {
query: void 0,
documentId: void 0,
operationName: getOperationName(e.query),
variables: e.variables || void 0,
extensions: e.extensions
};
if ("documentId" in e.query && e.query.documentId && (!e.query.definitions || !e.query.definitions.length)) {
r.documentId = e.query.documentId;
} else if (!e.extensions || !e.extensions.persistedQuery || e.extensions.persistedQuery.miss) {
r.query = stringifyDocument(e.query);
}
return r;
}
var makeFetchURL = (e, r) => {
var t = "query" === e.kind && e.context.preferGetMethod;
if (!t || !r) {
return e.context.url;
}
var a = splitOutSearchParams(e.context.url);
for (var n in r) {
var o = r[n];
if (o) {
a[1].set(n, "object" == typeof o ? stringifyVariables(o) : o);
}
}
var s = a.join("?");
if (s.length > 2047 && "force" !== t) {
e.context.preferGetMethod = !1;
return e.context.url;
}
return s;
};
var splitOutSearchParams = e => {
var r = e.indexOf("?");
return r > -1 ? [ e.slice(0, r), new URLSearchParams(e.slice(r + 1)) ] : [ e, new URLSearchParams ];
};
var serializeBody = (e, r) => {
if (r && !("query" === e.kind && !!e.context.preferGetMethod)) {
var t = stringifyVariables(r);
var a = (e => {
var r = new Map;
if (d !== NoopConstructor || l !== NoopConstructor) {
i.clear();
extract(r, "variables", e);
}
return r;
})(r.variables);
if (a.size) {
var n = new FormData;
n.append("operations", t);
n.append("map", stringifyVariables({
...[ ...a.keys() ].map((e => [ e ]))
}));
var o = 0;
for (var s of a.values()) {
n.append("" + o++, s);
}
return n;
}
return t;
}
};
var makeFetchOptions = (e, r) => {
var t = {
accept: "subscription" === e.kind ? "text/event-stream, multipart/mixed" : "application/graphql-response+json, application/graphql+json, application/json, text/event-stream, multipart/mixed"
};
var a = ("function" == typeof e.context.fetchOptions ? e.context.fetchOptions() : e.context.fetchOptions) || {};
if (a.headers) {
if ((e => "has" in e && !Object.keys(e).length)(a.headers)) {
a.headers.forEach(((e, r) => {
t[r] = e;
}));
} else if (Array.isArray(a.headers)) {
a.headers.forEach(((e, r) => {
if (Array.isArray(e)) {
if (t[e[0]]) {
t[e[0]] = `${t[e[0]]},${e[1]}`;
} else {
t[e[0]] = e[1];
}
} else {
t[r] = e;
}
}));
} else {
for (var n in a.headers) {
t[n.toLowerCase()] = a.headers[n];
}
}
}
var o = serializeBody(e, r);
if ("string" == typeof o && !t["content-type"]) {
t["content-type"] = "application/json";
}
return {
...a,
method: o ? "POST" : "GET",
body: o,
headers: t
};
};
var h = /boundary="?([^=";]+)"?/i;
var y = /data: ?([^\n]+)/;
async function* streamBody(e) {
if (e.body[Symbol.asyncIterator]) {
for await (var r of e.body) {
yield r;
}
} else {
var t = e.body.getReader();
var a;
try {
while (!(a = await t.read()).done) {
yield a.value;
}
} finally {
t.cancel();
}
}
}
async function* streamToBoundedChunks(e, r) {
var t = "undefined" != typeof TextDecoder ? new TextDecoder : null;
var a = "";
var n;
for await (var o of e) {
a += "Buffer" === o.constructor.name ? o.toString() : t.decode(o, {
stream: !0
});
while ((n = a.indexOf(r)) > -1) {
yield a.slice(0, n);
a = a.slice(n + r.length);
}
}
}
async function* fetchOperation(e, r, t) {
var a = !0;
var n = null;
var o;
try {
yield await Promise.resolve();
var s = (o = await (e.context.fetch || fetch)(r, t)).headers.get("Content-Type") || "";
var i;
if (/multipart\/mixed/i.test(s)) {
i = async function* parseMultipartMixed(e, r) {
var t = e.match(h);
var a = "--" + (t ? t[1] : "-");
var n = !0;
var o;
for await (var s of streamToBoundedChunks(streamBody(r), "\r\n" + a)) {
if (n) {
n = !1;
var i = s.indexOf(a);
if (i > -1) {
s = s.slice(i + a.length);
} else {
continue;
}
}
try {
yield o = JSON.parse(s.slice(s.indexOf("\r\n\r\n") + 4));
} catch (e) {
if (!o) {
throw e;
}
}
if (o && !1 === o.hasNext) {
break;
}
}
if (o && !1 !== o.hasNext) {
yield {
hasNext: !1
};
}
}(s, o);
} else if (/text\/event-stream/i.test(s)) {
i = async function* parseEventStream(e) {
var r;
for await (var t of streamToBoundedChunks(streamBody(e), "\n\n")) {
var a = t.match(y);
if (a) {
var n = a[1];
try {
yield r = JSON.parse(n);
} catch (e) {
if (!r) {
throw e;
}
}
if (r && !1 === r.hasNext) {
break;
}
}
}
if (r && !1 !== r.hasNext) {
yield {
hasNext: !1
};
}
}(o);
} else if (!/text\//i.test(s)) {
i = async function* parseJSON(e) {
yield JSON.parse(await e.text());
}(o);
} else {
i = async function* parseMaybeJSON(e) {
var r = await e.text();
try {
var t = JSON.parse(r);
if ("production" !== process.env.NODE_ENV) {
console.warn('Found response with content-type "text/plain" but it had a valid "application/json" response.');
}
yield t;
} catch (e) {
throw new Error(r);
}
}(o);
}
var f;
for await (var d of i) {
if (d.pending && !n) {
f = d.pending;
} else if (d.pending) {
f = [ ...f, ...d.pending ];
}
n = n ? mergeResultPatch(n, d, o, f) : makeResult(e, d, o);
a = !1;
yield n;
a = !0;
}
if (!n) {
yield n = makeResult(e, {}, o);
}
} catch (r) {
if (!a) {
throw r;
}
yield makeErrorResult(e, o && (o.status < 200 || o.status >= 300) && o.statusText ? new Error(o.statusText) : r, o);
}
}
function makeFetchSource(e, r, t) {
var a;
if ("undefined" != typeof AbortController) {
t.signal = (a = new AbortController).signal;
}
return n((() => {
if (a) {
a.abort();
}
}))(o((e => !!e))(s(fetchOperation(e, r, t))));
}
export { CombinedError as C, makeFetchBody as a, makeErrorResult as b, mergeResultPatch as c, makeFetchURL as d, makeFetchOptions as e, makeFetchSource as f, getOperationType as g, createRequest as h, stringifyVariables as i, getOperationName as j, keyDocument as k, makeResult as m, stringifyDocument as s };
//# sourceMappingURL=urql-core-chunk.mjs.map
File diff suppressed because one or more lines are too long
+36
View File
@@ -0,0 +1,36 @@
import { Operation, OperationResult } from './urql-core-chunk.js';
export { FetchBody, makeFetchBody, makeFetchOptions, makeFetchURL } from './urql-core-chunk.js';
import { Source } from 'wonka';
/** Makes a GraphQL HTTP request to a given API by wrapping around the Fetch API.
*
* @param operation - The {@link Operation} that should be sent via GraphQL over HTTP.
* @param url - The endpoint URL for the GraphQL HTTP API.
* @param fetchOptions - The {@link RequestInit} fetch options for the request.
* @returns A Wonka {@link Source} of {@link OperationResult | OperationResults}.
*
* @remarks
* This utility defines how all built-in fetch exchanges make GraphQL HTTP requests,
* supporting multipart incremental responses, cancellation and other smaller
* implementation details.
*
* If you’re implementing a modified fetch exchange for a GraphQL over HTTP API
* it’s recommended you use this utility.
*
* Hint: This function does not use the passed `operation` to create or modify the
* `fetchOptions` and instead expects that the options have already been created
* using {@link makeFetchOptions} and modified as needed.
*
* @throws
* If the `fetch` polyfill or globally available `fetch` function doesn’t support
* streamed multipart responses while trying to handle a `multipart/mixed` GraphQL response,
* the source will throw “Streaming requests unsupported”.
* This shouldn’t happen in modern browsers and Node.js.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API} for the Fetch API spec.
*/
declare function makeFetchSource(operation: Operation, url: string, fetchOptions: RequestInit): Source<OperationResult>;
export { makeFetchSource };
+11
View File
@@ -0,0 +1,11 @@
Object.defineProperty(exports, '__esModule', { value: true });
var urqlCoreInternal = require('./urql-core-chunk.js');
exports.makeFetchBody = urqlCoreInternal.makeFetchBody;
exports.makeFetchOptions = urqlCoreInternal.makeFetchOptions;
exports.makeFetchSource = urqlCoreInternal.makeFetchSource;
exports.makeFetchURL = urqlCoreInternal.makeFetchURL;
//# sourceMappingURL=urql-core-internal.js.map
@@ -0,0 +1 @@
{"version":3,"file":"urql-core-internal.js","sources":[],"sourcesContent":null,"names":[],"mappings":";;;;;;;;;"}
+2
View File
@@ -0,0 +1,2 @@
export { a as makeFetchBody, e as makeFetchOptions, f as makeFetchSource, d as makeFetchURL } from "./urql-core-chunk.mjs";
//# sourceMappingURL=urql-core-internal.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"urql-core-internal.mjs","sources":[],"sourcesContent":null,"names":[],"mappings":""}
+563
View File
@@ -0,0 +1,563 @@
import { AnyVariables, TypedDocumentNode, DocumentNode, GraphQLError, Exchange, FetchBody, Operation, ExecutionResult, DefinitionNode, DocumentInput, RequestExtensions, GraphQLRequest, OperationResult, FormattedNode, OperationType, OperationContext, CombinedError } from './urql-core-chunk.js';
export { CacheOutcome, Client, ClientOptions, DebugEvent, DebugEventArg, DebugEventTypes, ErrorLike, ExchangeIO, ExchangeInput, GraphQLRequestParams, IncrementalPayload, OperationDebugMeta, OperationInstance, OperationResultSource, PersistedDocument, PersistedRequestExtensions, RequestPolicy, createClient } from './urql-core-chunk.js';
/** A GraphQL parse function, which may be called as a tagged template literal, returning a parsed {@link DocumentNode}.
*
* @remarks
* The `gql` tag or function is used to parse a GraphQL query document into a {@link DocumentNode}.
*
* When used as a tagged template, `gql` will automatically merge fragment definitions into the resulting
* document and deduplicate them.
*
* It enforces that all fragments have a unique name. When fragments with different definitions share a name,
* it will log a warning in development.
*
* Hint: It’s recommended to use this `gql` function over other GraphQL parse functions, since it puts the parsed
* results directly into `@urql/core`’s internal caches and prevents further unnecessary work.
*
* @example
* ```ts
* const AuthorFragment = gql`
* fragment AuthorDisplayComponent on Author {
* id
* name
* }
* `;
*
* const BookFragment = gql`
* fragment ListBookComponent on Book {
* id
* title
* author {
* ...AuthorDisplayComponent
* }
* }
*
* ${AuthorFragment}
* `;
*
* const BookQuery = gql`
* query Book($id: ID!) {
* book(id: $id) {
* ...BookFragment
* }
* }
*
* ${BookFragment}
* `;
* ```
*/
declare function gql<Data = any, Variables extends AnyVariables = AnyVariables>(strings: TemplateStringsArray, ...interpolations: Array<TypedDocumentNode | DocumentNode | string>): TypedDocumentNode<Data, Variables>;
declare function gql<Data = any, Variables extends AnyVariables = AnyVariables>(string: string): TypedDocumentNode<Data, Variables>;
/** A serialized version of an {@link OperationResult}.
*
* @remarks
* All properties are serialized separately as JSON strings, except for the
* {@link CombinedError} to speed up JS parsing speed, even if a result doesn’t
* end up being used.
*
* @internal
*/
interface SerializedResult {
hasNext?: boolean;
/** JSON-serialized version of {@link OperationResult.data}. */
data?: string | undefined;
/** JSON-serialized version of {@link OperationResult.extensions}. */
extensions?: string | undefined;
/** JSON version of {@link CombinedError}. */
error?: {
graphQLErrors: Array<Partial<GraphQLError> | string>;
networkError?: string;
};
}
/** A dictionary of {@link Operation.key} keys to serializable {@link SerializedResult} objects.
*
* @remarks
* It’s not recommended to modify the serialized data manually, however, multiple payloads of
* this dictionary may safely be merged and combined.
*/
interface SSRData {
[key: string]: SerializedResult;
}
/** Options for the `ssrExchange` allowing it to either operate on the server- or client-side. */
interface SSRExchangeParams {
/** Indicates to the {@link SSRExchange} whether it's currently in server-side or client-side mode.
*
* @remarks
* Depending on this option, the {@link SSRExchange} will either capture or replay results.
* When `true`, it’s in client-side mode and results will be serialized. When `false`, it’ll
* use its deserialized data and replay results from it.
*/
isClient?: boolean;
/** May be used on the client-side to pass the {@link SSRExchange} serialized data from the server-side.
*
* @remarks
* Alternatively, {@link SSRExchange.restoreData} may be called to imperatively add serialized data to
* the exchange.
*
* Hint: This method also works on the server-side to add to the initial serialized data, which enables
* you to combine multiple {@link SSRExchange} results, as needed.
*/
initialState?: SSRData;
/** Forces a new API request to be sent in the background after replaying the deserialized result.
*
* @remarks
* Similarly to the `cache-and-network` {@link RequestPolicy}, this option tells the {@link SSRExchange}
* to send a new API request for the {@link Operation} after replaying a serialized result.
*
* Hint: This is useful when you're caching SSR results and need the client-side to update itself after
* rendering the initial serialized SSR results.
*/
staleWhileRevalidate?: boolean;
/** Forces {@link OperationResult.extensions} to be serialized alongside the rest of a result.
*
* @remarks
* Entries in the `extension` object of a GraphQL result are often non-standard metdata, and many
* APIs use it for data that changes between every request. As such, the {@link SSRExchange} will
* not serialize this data by default, unless this flag is set.
*/
includeExtensions?: boolean;
}
/** An `SSRExchange` either in server-side mode, serializing results, or client-side mode, deserializing and replaying results..
*
* @remarks
* This same {@link Exchange} is used in your code both for the client-side and server-side as it’s “universal”
* and can be put into either client-side or server-side mode using the {@link SSRExchangeParams.isClient} flag.
*
* In server-side mode, the `ssrExchange` will “record” results it sees from your API and provide them for you
* to send to the client-side using the {@link SSRExchange.extractData} method.
*
* In client-side mode, the `ssrExchange` will use these serialized results, rehydrated either using
* {@link SSRExchange.restoreData} or {@link SSRexchangeParams.initialState}, to replay results the
* server-side has seen and sent before.
*
* Each serialized result will only be replayed once, as it’s assumed that your cache exchange will have the
* results cached afterwards.
*/
interface SSRExchange extends Exchange {
/** Client-side method to add serialized results to the {@link SSRExchange}.
* @param data - {@link SSRData},
*/
restoreData(data: SSRData): void;
/** Server-side method to get all serialized results the {@link SSRExchange} has captured.
* @returns an {@link SSRData} dictionary.
*/
extractData(): SSRData;
}
/** Creates a server-side rendering `Exchange` that either captures responses on the server-side or replays them on the client-side.
*
* @param params - An {@link SSRExchangeParams} configuration object.
* @returns the created {@link SSRExchange}
*
* @remarks
* When dealing with server-side rendering, we essentially have two {@link Client | Clients} making requests,
* the server-side client, and the client-side one. The `ssrExchange` helps implementing a tiny cache on both
* sides that:
*
* - captures results on the server-side which it can serialize,
* - replays results on the client-side that it deserialized from the server-side.
*
* Hint: The `ssrExchange` is basically an exchange that acts like a replacement for any fetch exchange
* temporarily. As such, you should place it after your cache exchange but in front of any fetch exchange.
*/
declare const ssrExchange: (params?: SSRExchangeParams) => SSRExchange;
/** Default document cache exchange.
*
* @remarks
* The default document cache in `urql` avoids sending the same GraphQL request
* multiple times by caching it using the {@link Operation.key}. It will invalidate
* query results automatically whenever it sees a mutation responses with matching
* `__typename`s in their responses.
*
* The document cache will get the introspected `__typename` fields by modifying
* your GraphQL operation documents using the {@link formatDocument} utility.
*
* This automatic invalidation strategy can fail if your query or mutation don’t
* contain matching typenames, for instance, because the query contained an
* empty list.
* You can manually add hints for this exchange by specifying a list of
* {@link OperationContext.additionalTypenames} for queries and mutations that
* should invalidate one another.
*
* @see {@link https://urql.dev/goto/docs/basics/document-caching} for more information on this cache.
*/
declare const cacheExchange: Exchange;
/** An abstract observer-like interface.
*
* @remarks
* Observer-like interfaces are passed to {@link ObservableLike.subscribe} to provide them
* with callbacks for their events.
*
* @see {@link https://github.com/tc39/proposal-observable} for the full TC39 Observable proposal.
*/
interface ObserverLike<T> {
/** Callback for values an {@link ObservableLike} emits. */
next: (value: T) => void;
/** Callback for an error an {@link ObservableLike} emits, which ends the subscription. */
error: (err: any) => void;
/** Callback for the completion of an {@link ObservableLike}, which ends the subscription. */
complete: () => void;
}
/** An abstract observable-like interface.
*
* @remarks
* Observable, or Observable-like interfaces, are often used by GraphQL transports to abstract
* how they send {@link ExecutionResult | ExecutionResults} to consumers. These generally contain
* a `subscribe` method accepting an {@link ObserverLike} structure.
*
* @see {@link https://github.com/tc39/proposal-observable} for the full TC39 Observable proposal.
*/
interface ObservableLike<T> {
/** Start the Observable-like subscription and returns a subscription handle.
*
* @param observer - an {@link ObserverLike} object with result, error, and completion callbacks.
* @returns a subscription handle providing an `unsubscribe` method to stop the subscription.
*/
subscribe(observer: ObserverLike<T>): {
unsubscribe: () => void;
};
}
/** A more cross-compatible version of the {@link GraphQLRequest} structure.
* {@link FetchBody} for more details
*/
type SubscriptionOperation = FetchBody;
/** A subscription forwarding function, which must accept a {@link SubscriptionOperation}.
*
* @param operation - A {@link SubscriptionOperation}
* @returns An {@link ObservableLike} object issuing {@link ExecutionResult | ExecutionResults}.
*/
type SubscriptionForwarder = (request: FetchBody, operation: Operation) => ObservableLike<ExecutionResult>;
/** This is called to create a subscription and needs to be hooked up to a transport client. */
interface SubscriptionExchangeOpts {
/** A subscription forwarding function, which must accept a {@link SubscriptionOperation}.
*
* @param operation - A {@link SubscriptionOperation}
* @returns An {@link ObservableLike} object issuing {@link ExecutionResult | ExecutionResults}.
*
* @remarks
* This callback is called for each {@link Operation} that this `subscriptionExchange` will
* handle. It receives the {@link SubscriptionOperation}, which is a more compatible version
* of the raw {@link Operation} objects and must return an {@link ObservableLike} of results.
*/
forwardSubscription: SubscriptionForwarder;
/** Flag to enable this exchange to handle all types of GraphQL operations.
*
* @remarks
* When you aren’t using fetch exchanges and GraphQL over HTTP as a transport for your GraphQL requests,
* or you have a third-party GraphQL transport implementation, which must also be used for queries and
* mutations, this flag may be used to allow this exchange to handle all kinds of GraphQL operations.
*
* By default, this flag is `false` and the exchange will only handle GraphQL subscription operations.
*/
enableAllOperations?: boolean;
/** A predicate function that causes an operation to be handled by this `subscriptionExchange` if `true` is returned.
*
* @param operation - an {@link Operation}
* @returns true when the operation is handled by this exchange.
*
* @remarks
* In some cases, a `subscriptionExchange` will be used to only handle some {@link Operation | Operations},
* e.g. all that contain `@live` directive. For these cases, this function may be passed to precisely
* determine which `Operation`s this exchange should handle, instead of forwarding.
*
* When specified, the {@link SubscriptionExchangeOpts.enableAllOperations} flag is disregarded.
*/
isSubscriptionOperation?: (operation: Operation) => boolean;
}
/** Generic subscription exchange factory used to either create an exchange handling just subscriptions or all operation kinds.
*
* @remarks
* `subscriptionExchange` can be used to create an {@link Exchange} that either
* handles just GraphQL subscription operations, or optionally all operations,
* when the {@link SubscriptionExchangeOpts.enableAllOperations} flag is passed.
*
* The {@link SubscriptionExchangeOpts.forwardSubscription} function must
* be provided and provides a generic input that's based on {@link Operation}
* but is compatible with many libraries implementing GraphQL request or
* subscription interfaces.
*/
declare const subscriptionExchange: ({ forwardSubscription, enableAllOperations, isSubscriptionOperation, }: SubscriptionExchangeOpts) => Exchange;
/** Simple log debugger exchange.
*
* @remarks
* An exchange that logs incoming {@link Operation | Operations} and
* {@link OperationResult | OperationResults} in development.
*
* This exchange is a no-op in production and often used in issue reporting
* to understand certain usage patterns of `urql` without having access to
* the original source code.
*
* Hint: When you report an issue you’re having with `urql`, adding
* this as your first exchange and posting its output can speed up
* issue triaging a lot!
*/
declare const debugExchange: Exchange;
/** Default GraphQL over HTTP fetch exchange.
*
* @remarks
* The default fetch exchange in `urql` supports sending GraphQL over HTTP
* requests, can optionally send GraphQL queries as GET requests, and
* handles incremental multipart responses.
*
* This exchange does not handle persisted queries or multipart uploads.
* Support for the former can be added using `@urql/exchange-persisted-fetch`
* and the latter using `@urql/exchange-multipart-fetch`.
*
* Hint: The `fetchExchange` and the two other exchanges all use the built-in fetch
* utilities in `@urql/core/internal`, which you can also use to implement
* a customized fetch exchange.
*
* @see {@link makeFetchSource} for the shared utility calling the Fetch API.
*/
declare const fetchExchange: Exchange;
/** Composes an array of Exchanges into a single one.
*
* @param exchanges - An array of {@link Exchange | Exchanges}.
* @returns - A composed {@link Exchange}.
*
* @remarks
* `composeExchanges` returns an {@link Exchange} that when instantiated
* composes the array of passed `Exchange`s into one, calling them from
* right to left, with the prior `Exchange`’s {@link ExchangeIO} function
* as the {@link ExchangeInput.forward} input.
*
* This simply merges all exchanges into one and is used by the {@link Client}
* to merge the `exchanges` option it receives.
*
* @throws
* In development, if {@link ExchangeInput.forward} is called repeatedly
* by an {@link Exchange} an error is thrown, since `forward()` must only
* be called once per `Exchange`.
*/
declare const composeExchanges: (exchanges: Exchange[]) => Exchange;
/** A cached printing function for GraphQL documents.
*
* @param node - A string of a document or a {@link DocumentNode}
* @returns A normalized printed string of the passed GraphQL document.
*
* @remarks
* This function accepts a GraphQL query string or {@link DocumentNode},
* then prints and sanitizes it. The sanitizer takes care of removing
* comments, which otherwise alter the key of the document although the
* document is otherwise equivalent to another.
*
* When a {@link DocumentNode} is passed to this function, it caches its
* output by modifying the `loc.source.body` property on the GraphQL node.
*/
declare const stringifyDocument: (node: string | DefinitionNode | DocumentNode) => string;
/** Creates a `GraphQLRequest` from the passed parameters.
*
* @param q - A string of a document or a {@link DocumentNode}
* @param variables - A variables object for the defined GraphQL operation.
* @returns A {@link GraphQLRequest}
*
* @remarks
* `createRequest` creates a {@link GraphQLRequest} from the passed parameters,
* while replacing the document as needed with a canonical version of itself,
* to avoid parsing, printing, or hashing the same input multiple times.
*
* If no variables are passed, canonically it'll default to an empty object,
* which is removed from the resulting hash key.
*/
declare const createRequest: <Data = any, Variables extends AnyVariables = AnyVariables>(_query: DocumentInput<Data, Variables>, _variables: Variables, extensions?: RequestExtensions | undefined) => GraphQLRequest<Data, Variables>;
/** Returns the name of the `DocumentNode`'s operation, if any.
* @param query - A {@link DocumentNode}
* @returns the operation's name contained within the document, or `undefined`
*/
declare const getOperationName: (query: DocumentNode) => string | undefined;
/** Converts the `ExecutionResult` received for a given `Operation` to an `OperationResult`.
*
* @param operation - The {@link Operation} for which the API’s result is for.
* @param result - The GraphQL API’s {@link ExecutionResult}.
* @param response - Optionally, a raw object representing the API’s result (Typically a {@link Response}).
* @returns An {@link OperationResult}.
*
* @remarks
* This utility can be used to create {@link OperationResult | OperationResults} in the shape
* that `urql` expects and defines, and should be used rather than creating the results manually.
*
* @throws
* If no data, or errors are contained within the result, or the result is instead an incremental
* response containing a `path` property, a “No Content” error is thrown.
*
* @see {@link ExecutionResult} for the type definition of GraphQL API results.
*/
declare const makeResult: (operation: Operation, result: ExecutionResult, response?: any) => OperationResult;
/** Merges an incrementally delivered `ExecutionResult` into a previous `OperationResult`.
*
* @param prevResult - The {@link OperationResult} that preceded this result.
* @param path - The GraphQL API’s {@link ExecutionResult} that should be patching the `prevResult`.
* @param response - Optionally, a raw object representing the API’s result (Typically a {@link Response}).
* @returns A new {@link OperationResult} patched with the incremental result.
*
* @remarks
* This utility should be used to merge subsequent {@link ExecutionResult | ExecutionResults} of
* incremental responses into a prior {@link OperationResult}.
*
* When directives like `@defer`, `@stream`, and `@live` are used, GraphQL may deliver new
* results that modify previous results. In these cases, it'll set a `path` property to modify
* the result it sent last. This utility is built to handle these cases and merge these payloads
* into existing {@link OperationResult | OperationResults}.
*
* @see {@link ExecutionResult} for the type definition of GraphQL API results.
*/
declare const mergeResultPatch: (prevResult: OperationResult, nextResult: ExecutionResult, response?: any, pending?: ExecutionResult["pending"]) => OperationResult;
/** Creates an `OperationResult` containing a network error for requests that encountered unexpected errors.
*
* @param operation - The {@link Operation} for which the API’s result is for.
* @param error - The network-like error that prevented an API result from being delivered.
* @param response - Optionally, a raw object representing the API’s result (Typically a {@link Response}).
* @returns An {@link OperationResult} containing only a {@link CombinedError}.
*
* @remarks
* This utility can be used to create {@link OperationResult | OperationResults} in the shape
* that `urql` expects and defines, and should be used rather than creating the results manually.
* This function should be used for when the {@link CombinedError.networkError} property is
* populated and no GraphQL execution actually occurred.
*/
declare const makeErrorResult: (operation: Operation, error: Error, response?: any) => OperationResult;
/** A stable stringifier for GraphQL variables objects.
*
* @param x - any JSON-like data.
* @return A JSON string.
*
* @remarks
* This utility creates a stable JSON string from any passed data,
* and protects itself from throwing.
*
* The JSON string is stable insofar as objects’ keys are sorted,
* and instances of non-plain objects are replaced with random keys
* replacing their values, which remain stable for the objects’
* instance.
*/
declare const stringifyVariables: (x: any, includeFiles?: boolean) => string;
/** Formats a GraphQL document to add `__typename` fields and process client-side directives.
*
* @param node - a {@link DocumentNode}.
* @returns a {@link FormattedDocument}
*
* @remarks
* Cache {@link Exchange | Exchanges} will require typename introspection to
* recognize types in a GraphQL response. To retrieve these typenames,
* this function is used to add the `__typename` fields to non-root
* selection sets of a GraphQL document.
*
* Additionally, this utility will process directives, filter out client-side
* directives starting with an `_` underscore, and place a `_directives` dictionary
* on selection nodes.
*
* This utility also preserves the internally computed key of the
* document as created by {@link createRequest} to avoid any
* formatting from being duplicated.
*
* @see {@link https://spec.graphql.org/October2021/#sec-Type-Name-Introspection} for more information
* on typename introspection via the `__typename` field.
*/
declare const formatDocument: <T extends TypedDocumentNode<any, any>>(node: T) => FormattedNode<T>;
/** Creates a {@link Operation} from the given parameters.
*
* @param kind - The {@link OperationType} of GraphQL operation, i.e. `query`, `mutation`, or `subscription`.
* @param request - The {@link GraphQLRequest} or {@link Operation} used as a template for the new `Operation`.
* @param context - The {@link OperationContext} `context` data for the `Operation`.
* @returns A new {@link Operation}.
*
* @remarks
* This method is both used to create new {@link Operation | Operations} as well as copy and modify existing
* operations. While it’s not required to use this function to copy an `Operation`, it is recommended, in case
* additional dynamic logic is added to them in the future.
*
* Hint: When an {@link Operation} is passed to the `request` argument, the `context` argument does not have to be
* a complete {@link OperationContext} and will instead be combined with passed {@link Operation.context}.
*
* @example
* An example of copying an existing `Operation` to modify its `context`:
*
* ```ts
* makeOperation(
* operation.kind,
* operation,
* { requestPolicy: 'cache-first' },
* );
* ```
*/
declare function makeOperation<Data = any, Variables extends AnyVariables = AnyVariables>(kind: OperationType, request: GraphQLRequest<Data, Variables>, context: OperationContext): Operation<Data, Variables>;
declare function makeOperation<Data = any, Variables extends AnyVariables = AnyVariables>(kind: OperationType, request: Operation<Data, Variables>, context?: Partial<OperationContext>): Operation<Data, Variables>;
/** Options for the `mapExchange` allowing it to react to incoming operations, results, or errors. */
interface MapExchangeOpts {
/** Accepts a callback for incoming `Operation`s.
*
* @param operation - An {@link Operation} that the {@link mapExchange} received.
* @returns optionally a new {@link Operation} replacing the original.
*
* @remarks
* You may return new {@link Operation | Operations} from this function replacing
* the original that the {@link mapExchange} received.
* It’s recommended that you use the {@link makeOperation} utility to create a copy
* of the original when you do this. (However, this isn’t required)
*
* Hint: The callback may also be promisified and return a new {@link Operation} asynchronously,
* provided you place your {@link mapExchange} after all synchronous {@link Exchange | Exchanges},
* like after your `cacheExchange`.
*/
onOperation?(operation: Operation): Promise<Operation> | Operation | void;
/** Accepts a callback for incoming `OperationResult`s.
*
* @param result - An {@link OperationResult} that the {@link mapExchange} received.
* @returns optionally a new {@link OperationResult} replacing the original.
*
* @remarks
* This callback may optionally return a new {@link OperationResult} that replaces the original,
* which you can use to modify incoming API results.
*
* Hint: The callback may also be promisified and return a new {@link Operation} asynchronously,
* provided you place your {@link mapExchange} after all synchronous {@link Exchange | Exchanges},
* like after your `cacheExchange`.
*/
onResult?(result: OperationResult): Promise<OperationResult> | OperationResult | void;
/** Accepts a callback for incoming `CombinedError`s.
*
* @param error - A {@link CombinedError} that an incoming {@link OperationResult} contained.
* @param operation - The {@link Operation} of the incoming {@link OperationResult}.
*
* @remarks
* The callback may also be promisified and return a new {@link Operation} asynchronously,
* provided you place your {@link mapExchange} after all synchronous {@link Exchange | Exchanges},
* like after your `cacheExchange`.
*/
onError?(error: CombinedError, operation: Operation): void;
}
/** Creates an `Exchange` mapping over incoming operations, results, and/or errors.
*
* @param opts - A {@link MapExchangeOpts} configuration object, containing the callbacks the `mapExchange` will use.
* @returns the created {@link Exchange}
*
* @remarks
* The `mapExchange` may be used to react to or modify incoming {@link Operation | Operations}
* and {@link OperationResult | OperationResults}. Optionally, it can also modify these
* asynchronously, when a promise is returned from the callbacks.
*
* This is useful to, for instance, add an authentication token to a given request, when
* the `@urql/exchange-auth` package would be overkill.
*
* It can also accept an `onError` callback, which can be used to react to incoming
* {@link CombinedError | CombinedErrors} on results, and trigger side-effects.
*
*/
declare const mapExchange: ({ onOperation, onResult, onError, }: MapExchangeOpts) => Exchange;
export { AnyVariables, CombinedError, DocumentInput, Exchange, ExecutionResult, FormattedNode, GraphQLRequest, MapExchangeOpts, Operation, OperationContext, OperationResult, OperationType, RequestExtensions, SSRData, SSRExchange, SSRExchangeParams, SerializedResult, SubscriptionExchangeOpts, SubscriptionForwarder, SubscriptionOperation, TypedDocumentNode, cacheExchange, composeExchanges, createRequest, debugExchange, mapExchange as errorExchange, fetchExchange, formatDocument, getOperationName, gql, makeErrorResult, makeOperation, makeResult, mapExchange, mergeResultPatch, ssrExchange, stringifyDocument, stringifyVariables, subscriptionExchange };
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+742
View File
@@ -0,0 +1,742 @@
import { Kind as e } from "@0no-co/graphql.web";
import { k as r, s as t, m as n, C as a, a as o, b as s, c, d as u, e as p, f as d, g as v, h as l } from "./urql-core-chunk.mjs";
export { j as getOperationName, i as stringifyVariables } from "./urql-core-chunk.mjs";
import { toPromise as f, take as h, filter as k, subscribe as y, map as m, tap as x, merge as g, mergeMap as w, takeUntil as O, make as E, onPush as b, share as N, fromPromise as q, fromValue as _, makeSubject as D, lazy as S, onStart as P, switchMap as R, publish as V, takeWhile as A, onEnd as M } from "wonka";
var collectTypes = (e, r) => {
if (Array.isArray(e)) {
for (var t = 0, n = e.length; t < n; t++) {
collectTypes(e[t], r);
}
} else if ("object" == typeof e && null !== e) {
for (var a in e) {
if ("__typename" === a && "string" == typeof e[a]) {
r.add(e[a]);
} else {
collectTypes(e[a], r);
}
}
}
return r;
};
var formatNode = r => {
if ("definitions" in r) {
var t = [];
for (var n = 0, a = r.definitions.length; n < a; n++) {
var i = formatNode(r.definitions[n]);
t.push(i);
}
return {
...r,
definitions: t
};
}
if ("directives" in r && r.directives && r.directives.length) {
var o = [];
var s = {};
for (var c = 0, u = r.directives.length; c < u; c++) {
var p = r.directives[c];
var d = p.name.value;
if ("_" !== d[0]) {
o.push(p);
} else {
d = d.slice(1);
}
s[d] = p;
}
r = {
...r,
directives: o,
_directives: s
};
}
if ("selectionSet" in r) {
var v = [];
var l = r.kind === e.OPERATION_DEFINITION;
if (r.selectionSet) {
for (var f = 0, h = r.selectionSet.selections.length; f < h; f++) {
var k = r.selectionSet.selections[f];
l = l || k.kind === e.FIELD && "__typename" === k.name.value && !k.alias;
var y = formatNode(k);
v.push(y);
}
if (!l) {
v.push({
kind: e.FIELD,
name: {
kind: e.NAME,
value: "__typename"
},
_generated: !0
});
}
return {
...r,
selectionSet: {
...r.selectionSet,
selections: v
}
};
}
}
return r;
};
var I = new Map;
var formatDocument = e => {
var t = r(e);
var n = I.get(t.__key);
if (!n) {
I.set(t.__key, n = formatNode(t));
Object.defineProperty(n, "__key", {
value: t.__key,
enumerable: !1
});
}
return n;
};
function withPromise(e) {
var source$ = r => e(r);
source$.toPromise = () => f(h(1)(k((e => !e.stale && !e.hasNext))(source$)));
source$.then = (e, r) => source$.toPromise().then(e, r);
source$.subscribe = e => y(e)(source$);
return source$;
}
function makeOperation(e, r, t) {
return {
...r,
kind: e,
context: r.context ? {
...r.context,
...t
} : t || r.context
};
}
var addMetadata = (e, r) => makeOperation(e.kind, e, {
meta: {
...e.context.meta,
...r
}
});
var noop = () => {};
function gql(n) {
var a = new Map;
var i = [];
var o = [];
var s = Array.isArray(n) ? n[0] : n || "";
for (var c = 1; c < arguments.length; c++) {
var u = arguments[c];
if (u && u.definitions) {
o.push(u);
} else {
s += u;
}
s += arguments[0][c];
}
o.unshift(r(s));
for (var p = 0; p < o.length; p++) {
for (var d = 0; d < o[p].definitions.length; d++) {
var v = o[p].definitions[d];
if (v.kind === e.FRAGMENT_DEFINITION) {
var l = v.name.value;
var f = t(v);
if (!a.has(l)) {
a.set(l, f);
i.push(v);
} else if ("production" !== process.env.NODE_ENV && a.get(l) !== f) {
console.warn("[WARNING: Duplicate Fragment] A fragment with name `" + l + "` already exists in this document.\nWhile fragment names may not be unique across your source, each name must be unique per document.");
}
} else {
i.push(v);
}
}
}
return r({
kind: e.DOCUMENT,
definitions: i
});
}
var shouldSkip = ({kind: e}) => "mutation" !== e && "query" !== e;
var mapTypeNames = e => {
var r = formatDocument(e.query);
if (r !== e.query) {
var t = makeOperation(e.kind, e);
t.query = r;
return t;
} else {
return e;
}
};
var cacheExchange = ({forward: e, client: r, dispatchDebug: t}) => {
var a = new Map;
var i = new Map;
var isOperationCached = e => "query" === e.kind && "network-only" !== e.context.requestPolicy && ("cache-only" === e.context.requestPolicy || a.has(e.key));
return o => {
var s = m((e => {
var i = a.get(e.key);
"production" !== process.env.NODE_ENV && t({
operation: e,
...i ? {
type: "cacheHit",
message: "The result was successfully retrieved from the cache"
} : {
type: "cacheMiss",
message: "The result could not be retrieved from the cache"
},
source: "cacheExchange"
});
var o = i || n(e, {
data: null
});
o = {
...o,
operation: addMetadata(e, {
cacheOutcome: i ? "hit" : "miss"
})
};
if ("cache-and-network" === e.context.requestPolicy) {
o.stale = !0;
reexecuteOperation(r, e);
}
return o;
}))(k((e => !shouldSkip(e) && isOperationCached(e)))(o));
var c = x((e => {
var {operation: n} = e;
if (!n) {
return;
}
var o = n.context.additionalTypenames || [];
if ("subscription" !== e.operation.kind) {
o = (e => [ ...collectTypes(e, new Set) ])(e.data).concat(o);
}
if ("mutation" === e.operation.kind || "subscription" === e.operation.kind) {
var s = new Set;
"production" !== process.env.NODE_ENV && t({
type: "cacheInvalidation",
message: `The following typenames have been invalidated: ${o}`,
operation: n,
data: {
typenames: o,
response: e
},
source: "cacheExchange"
});
for (var c = 0; c < o.length; c++) {
var u = o[c];
var p = i.get(u);
if (!p) {
i.set(u, p = new Set);
}
for (var d of p.values()) {
s.add(d);
}
p.clear();
}
for (var v of s.values()) {
if (a.has(v)) {
n = a.get(v).operation;
a.delete(v);
reexecuteOperation(r, n);
}
}
} else if ("query" === n.kind && e.data) {
a.set(n.key, e);
for (var l = 0; l < o.length; l++) {
var f = o[l];
var h = i.get(f);
if (!h) {
i.set(f, h = new Set);
}
h.add(n.key);
}
}
}))(e(k((e => "query" !== e.kind || "cache-only" !== e.context.requestPolicy))(m((e => addMetadata(e, {
cacheOutcome: "miss"
})))(g([ m(mapTypeNames)(k((e => !shouldSkip(e) && !isOperationCached(e)))(o)), k((e => shouldSkip(e)))(o) ])))));
return g([ s, c ]);
};
};
var reexecuteOperation = (e, r) => e.reexecuteOperation(makeOperation(r.kind, r, {
requestPolicy: "network-only"
}));
var T = new Set;
var ssrExchange = (e = {}) => {
var r = !!e.staleWhileRevalidate;
var t = !!e.includeExtensions;
var n = {};
var i = [];
var invalidate = e => {
i.push(e.operation.key);
if (1 === i.length) {
Promise.resolve().then((() => {
var e;
while (e = i.shift()) {
n[e] = null;
}
}));
}
};
var ssr = ({client: i, forward: o}) => s => {
var c = e && "boolean" == typeof e.isClient ? !!e.isClient : !i.suspense;
var u = o(m(mapTypeNames)(k((e => "teardown" === e.kind || !n[e.key] || !!n[e.key].hasNext || "network-only" === e.context.requestPolicy))(s)));
var p = m((e => {
var o = ((e, r, t) => ({
operation: e,
data: r.data ? JSON.parse(r.data) : void 0,
extensions: t && r.extensions ? JSON.parse(r.extensions) : void 0,
error: r.error ? new a({
networkError: r.error.networkError ? new Error(r.error.networkError) : void 0,
graphQLErrors: r.error.graphQLErrors
}) : void 0,
stale: !1,
hasNext: !!r.hasNext
}))(e, n[e.key], t);
if (r && !T.has(e.key)) {
o.stale = !0;
T.add(e.key);
reexecuteOperation(i, e);
}
return {
...o,
operation: addMetadata(e, {
cacheOutcome: "hit"
})
};
}))(k((e => "teardown" !== e.kind && !!n[e.key] && "network-only" !== e.context.requestPolicy))(s));
if (!c) {
u = x((e => {
var {operation: r} = e;
if ("mutation" !== r.kind) {
var a = ((e, r) => {
var t = {
hasNext: e.hasNext
};
if (void 0 !== e.data) {
t.data = JSON.stringify(e.data);
}
if (r && void 0 !== e.extensions) {
t.extensions = JSON.stringify(e.extensions);
}
if (e.error) {
t.error = {
graphQLErrors: e.error.graphQLErrors.map((e => {
if (!e.path && !e.extensions) {
return e.message;
}
return {
message: e.message,
path: e.path,
extensions: e.extensions
};
}))
};
if (e.error.networkError) {
t.error.networkError = "" + e.error.networkError;
}
}
return t;
})(e, t);
n[r.key] = a;
}
}))(u);
} else {
p = x(invalidate)(p);
}
return g([ u, p ]);
};
ssr.restoreData = e => {
for (var r in e) {
if (null !== n[r]) {
n[r] = e[r];
}
}
};
ssr.extractData = () => {
var e = {};
for (var r in n) {
if (null != n[r]) {
e[r] = n[r];
}
}
return e;
};
if (e && e.initialState) {
ssr.restoreData(e.initialState);
}
return ssr;
};
var subscriptionExchange = ({forwardSubscription: e, enableAllOperations: r, isSubscriptionOperation: t}) => ({client: a, forward: i}) => {
var u = t || (e => "subscription" === e.kind || !!r && ("query" === e.kind || "mutation" === e.kind));
return r => {
var t = w((t => {
var {key: i} = t;
var u = k((e => "teardown" === e.kind && e.key === i))(r);
return O(u)((r => {
var t = e(o(r), r);
return E((e => {
var i = !1;
var o;
var u;
function nextResult(t) {
e.next(u = u ? c(u, t) : n(r, t));
}
Promise.resolve().then((() => {
if (i) {
return;
}
o = t.subscribe({
next: nextResult,
error(t) {
if (Array.isArray(t)) {
nextResult({
errors: t
});
} else {
e.next(s(r, t));
}
e.complete();
},
complete() {
if (!i) {
i = !0;
if ("subscription" === r.kind) {
a.reexecuteOperation(makeOperation("teardown", r, r.context));
}
if (u && u.hasNext) {
nextResult({
hasNext: !1
});
}
e.complete();
}
}
});
}));
return () => {
i = !0;
if (o) {
o.unsubscribe();
}
};
}));
})(t));
}))(k((e => "teardown" !== e.kind && u(e)))(r));
var p = i(k((e => "teardown" === e.kind || !u(e)))(r));
return g([ t, p ]);
};
};
var debugExchange = ({forward: e}) => {
if ("production" === process.env.NODE_ENV) {
return r => e(r);
} else {
return r => x((e => console.debug("[Exchange debug]: Completed operation: ", e)))(e(x((e => console.debug("[Exchange debug]: Incoming operation: ", e)))(r)));
}
};
var fetchExchange = ({forward: e, dispatchDebug: r}) => t => {
var n = w((e => {
var n = o(e);
var a = u(e, n);
var i = p(e, n);
"production" !== process.env.NODE_ENV && r({
type: "fetchRequest",
message: "A fetch request is being executed.",
operation: e,
data: {
url: a,
fetchOptions: i
},
source: "fetchExchange"
});
var s = O(k((r => "teardown" === r.kind && r.key === e.key))(t))(d(e, a, i));
if ("production" !== process.env.NODE_ENV) {
return b((t => {
var n = !t.data ? t.error : void 0;
"production" !== process.env.NODE_ENV && r({
type: n ? "fetchError" : "fetchSuccess",
message: `A ${n ? "failed" : "successful"} fetch response has been returned.`,
operation: e,
data: {
url: a,
fetchOptions: i,
value: n || t
},
source: "fetchExchange"
});
}))(s);
}
return s;
}))(k((e => "teardown" !== e.kind && ("subscription" !== e.kind || !!e.context.fetchSubscriptions)))(t));
var a = e(k((e => "teardown" === e.kind || "subscription" === e.kind && !e.context.fetchSubscriptions))(t));
return g([ n, a ]);
};
var composeExchanges = e => ({client: r, forward: t, dispatchDebug: n}) => e.reduceRight(((e, t) => {
var a = !1;
return t({
client: r,
forward(r) {
if ("production" !== process.env.NODE_ENV) {
if (a) {
throw new Error("forward() must only be called once in each Exchange.");
}
a = !0;
}
return N(e(N(r)));
},
dispatchDebug(e) {
"production" !== process.env.NODE_ENV && n({
timestamp: Date.now(),
source: t.name,
...e
});
}
});
}), t);
var mapExchange = ({onOperation: e, onResult: r, onError: t}) => ({forward: n}) => a => w((e => {
if (t && e.error) {
t(e.error, e.operation);
}
var n = r && r(e) || e;
return "then" in n ? q(n) : _(n);
}))(n(w((r => {
var t = e && e(r) || r;
return "then" in t ? q(t) : _(t);
}))(a)));
var fallbackExchange = ({dispatchDebug: e}) => r => {
if ("production" !== process.env.NODE_ENV) {
r = x((r => {
if ("teardown" !== r.kind && "production" !== process.env.NODE_ENV) {
var t = `No exchange has handled operations of kind "${r.kind}". Check whether you've added an exchange responsible for these operations.`;
"production" !== process.env.NODE_ENV && e({
type: "fallbackCatch",
message: t,
operation: r,
source: "fallbackExchange"
});
console.warn(t);
}
}))(r);
}
return k((e => !1))(r);
};
var C = function Client(e) {
if ("production" !== process.env.NODE_ENV && !e.url) {
throw new Error("You are creating an urql-client without a url.");
}
var r = 0;
var t = new Map;
var n = new Map;
var a = new Set;
var i = [];
var o = {
url: e.url,
fetchSubscriptions: e.fetchSubscriptions,
fetchOptions: e.fetchOptions,
fetch: e.fetch,
preferGetMethod: e.preferGetMethod,
requestPolicy: e.requestPolicy || "cache-first"
};
var s = D();
function nextOperation(e) {
if ("mutation" === e.kind || "teardown" === e.kind || !a.has(e.key)) {
if ("teardown" === e.kind) {
a.delete(e.key);
} else if ("mutation" !== e.kind) {
a.add(e.key);
}
s.next(e);
}
}
var c = !1;
function dispatchOperation(e) {
if (e) {
nextOperation(e);
}
if (!c) {
c = !0;
while (c && (e = i.shift())) {
nextOperation(e);
}
c = !1;
}
}
var makeResultSource = e => {
var r = O(k((r => "teardown" === r.kind && r.key === e.key))(s.source))(k((r => r.operation.kind === e.kind && r.operation.key === e.key && (!r.operation.context._instance || r.operation.context._instance === e.context._instance)))(E));
if ("query" !== e.kind) {
r = A((e => !!e.hasNext), !0)(r);
} else {
r = R((r => {
var t = _(r);
return r.stale || r.hasNext ? t : g([ t, m((() => {
r.stale = !0;
return r;
}))(h(1)(k((r => r.key === e.key))(s.source))) ]);
}))(r);
}
if ("mutation" !== e.kind) {
r = M((() => {
a.delete(e.key);
t.delete(e.key);
n.delete(e.key);
c = !1;
for (var r = i.length - 1; r >= 0; r--) {
if (i[r].key === e.key) {
i.splice(r, 1);
}
}
nextOperation(makeOperation("teardown", e, e.context));
}))(b((r => {
if (r.stale) {
if (!r.hasNext) {
a.delete(e.key);
} else {
for (var n = 0; n < i.length; n++) {
var o = i[n];
if (o.key === r.operation.key) {
a.delete(o.key);
break;
}
}
}
} else if (!r.hasNext) {
a.delete(e.key);
}
t.set(e.key, r);
}))(r));
} else {
r = P((() => {
nextOperation(e);
}))(r);
}
return N(r);
};
var u = this instanceof Client ? this : Object.create(Client.prototype);
var p = Object.assign(u, {
suspense: !!e.suspense,
operations$: s.source,
reexecuteOperation(e) {
if ("teardown" === e.kind) {
dispatchOperation(e);
} else if ("mutation" === e.kind) {
i.push(e);
Promise.resolve().then(dispatchOperation);
} else if (n.has(e.key)) {
var r = !1;
for (var t = 0; t < i.length; t++) {
if (i[t].key === e.key) {
i[t] = e;
r = !0;
}
}
if (!(r || a.has(e.key) && "network-only" !== e.context.requestPolicy)) {
i.push(e);
Promise.resolve().then(dispatchOperation);
} else {
a.delete(e.key);
Promise.resolve().then(dispatchOperation);
}
}
},
createRequestOperation(e, t, n) {
if (!n) {
n = {};
}
var a;
if ("production" !== process.env.NODE_ENV && "teardown" !== e && (a = v(t.query)) !== e) {
throw new Error(`Expected operation of type "${e}" but found "${a}"`);
}
return makeOperation(e, t, {
_instance: "mutation" === e ? r = r + 1 | 0 : void 0,
...o,
...n,
requestPolicy: n.requestPolicy || o.requestPolicy,
suspense: n.suspense || !1 !== n.suspense && p.suspense
});
},
executeRequestOperation(e) {
if ("mutation" === e.kind) {
return withPromise(makeResultSource(e));
}
return withPromise(S((() => {
var r = n.get(e.key);
if (!r) {
n.set(e.key, r = makeResultSource(e));
}
r = P((() => {
dispatchOperation(e);
}))(r);
var a = t.get(e.key);
if ("query" === e.kind && a && (a.stale || a.hasNext)) {
return R(_)(g([ r, k((r => r === t.get(e.key)))(_(a)) ]));
} else {
return r;
}
})));
},
executeQuery(e, r) {
var t = p.createRequestOperation("query", e, r);
return p.executeRequestOperation(t);
},
executeSubscription(e, r) {
var t = p.createRequestOperation("subscription", e, r);
return p.executeRequestOperation(t);
},
executeMutation(e, r) {
var t = p.createRequestOperation("mutation", e, r);
return p.executeRequestOperation(t);
},
readQuery(e, r, t) {
var n = null;
y((e => {
n = e;
}))(p.query(e, r, t)).unsubscribe();
return n;
},
query: (e, r, t) => p.executeQuery(l(e, r), t),
subscription: (e, r, t) => p.executeSubscription(l(e, r), t),
mutation: (e, r, t) => p.executeMutation(l(e, r), t)
});
var d = noop;
if ("production" !== process.env.NODE_ENV) {
var {next: f, source: x} = D();
p.subscribeToDebugTarget = e => y(e)(x);
d = f;
}
var w = composeExchanges(e.exchanges);
var E = N(w({
client: p,
dispatchDebug: d,
forward: fallbackExchange({
dispatchDebug: d
})
})(s.source));
V(E);
return p;
};
var Q = C;
export { C as Client, a as CombinedError, cacheExchange, composeExchanges, Q as createClient, l as createRequest, debugExchange, mapExchange as errorExchange, fetchExchange, formatDocument, gql, s as makeErrorResult, makeOperation, n as makeResult, mapExchange, c as mergeResultPatch, ssrExchange, t as stringifyDocument, subscriptionExchange };
//# sourceMappingURL=urql-core.mjs.map
File diff suppressed because one or more lines are too long
+18
View File
@@ -0,0 +1,18 @@
{
"name": "urql-core-internal",
"private": true,
"version": "0.0.0",
"main": "../dist/urql-core-internal",
"module": "../dist/urql-core-internal.mjs",
"types": "../dist/urql-core-internal.d.ts",
"source": "../src/internal/index.ts",
"exports": {
".": {
"types": "../dist/urql-core-internal.d.ts",
"import": "../dist/urql-core-internal.mjs",
"require": "../dist/urql-core-internal.js",
"source": "../src/internal/index.ts"
},
"./package.json": "./package.json"
}
}
+63
View File
@@ -0,0 +1,63 @@
{
"name": "@urql/core",
"version": "5.2.0",
"description": "The shared core for the highly customizable and versatile GraphQL client",
"sideEffects": false,
"homepage": "https://formidable.com/open-source/urql/docs/",
"bugs": "https://github.com/urql-graphql/urql/issues",
"license": "MIT",
"author": "urql GraphQL Contributors",
"repository": {
"type": "git",
"url": "https://github.com/urql-graphql/urql.git",
"directory": "packages/core"
},
"keywords": [
"graphql",
"graphql client",
"state management",
"cache",
"exchanges"
],
"main": "dist/urql-core",
"module": "dist/urql-core.mjs",
"types": "dist/urql-core.d.ts",
"source": "src/index.ts",
"exports": {
".": {
"types": "./dist/urql-core.d.ts",
"import": "./dist/urql-core.mjs",
"require": "./dist/urql-core.js",
"source": "./src/index.ts"
},
"./package.json": "./package.json",
"./internal": {
"types": "./dist/urql-core-internal.d.ts",
"import": "./dist/urql-core-internal.mjs",
"require": "./dist/urql-core-internal.js",
"source": "./src/internal/index.ts"
}
},
"files": [
"LICENSE",
"README.md",
"dist/",
"internal/"
],
"dependencies": {
"@0no-co/graphql.web": "^1.0.13",
"wonka": "^6.3.2"
},
"publishConfig": {
"access": "public",
"provenance": true
},
"scripts": {
"test": "vitest",
"clean": "rimraf dist",
"check": "tsc --noEmit",
"lint": "eslint --ext=js,jsx,ts,tsx .",
"build": "rollup -c ../../scripts/rollup/config.mjs",
"jsr": "jsr publish"
}
}
+225
View File
@@ -0,0 +1,225 @@
# Changelog
## 1.3.2
### Patch Changes
- Mark options argument as optional (`retryExchange()`)
Submitted by [@jtomaszewski](https://github.com/jtomaszewski) (See [#3775](https://github.com/urql-graphql/urql/pull/3775))
- Updated dependencies (See [#3773](https://github.com/urql-graphql/urql/pull/3773), [#3767](https://github.com/urql-graphql/urql/pull/3767), [#3730](https://github.com/urql-graphql/urql/pull/3730), and [#3770](https://github.com/urql-graphql/urql/pull/3770))
- @urql/core@5.1.2
## 1.3.1
### Patch Changes
- Omit minified files and sourcemaps' `sourcesContent` in published packages
Submitted by [@kitten](https://github.com/kitten) (See [#3755](https://github.com/urql-graphql/urql/pull/3755))
- Updated dependencies (See [#3755](https://github.com/urql-graphql/urql/pull/3755))
- @urql/core@5.1.1
## 1.3.0
### Minor Changes
- Mark `@urql/core` as a peer dependency as well as a regular dependency
Submitted by [@kitten](https://github.com/kitten) (See [#3579](https://github.com/urql-graphql/urql/pull/3579))
## 1.2.1
### Patch Changes
---
Fixed the delay amount not increasing as retry count increases
Submitted by [@DoisKoh](https://github.com/DoisKoh) (See [#3478](https://github.com/urql-graphql/urql/pull/3478))
## 1.2.0
### Minor Changes
- Reset `retryExchange`’s previous attempts and delay if an operation succeeds. This prevents the exchange from keeping its old retry count and delay if the operation delivered a result in the meantime. This is important for it to help recover from failing subscriptions
Submitted by [@kitten](https://github.com/kitten) (See [#3229](https://github.com/urql-graphql/urql/pull/3229))
## 1.1.1
### Patch Changes
- Publish with npm provenance
Submitted by [@kitten](https://github.com/kitten) (See [#3180](https://github.com/urql-graphql/urql/pull/3180))
## 1.1.0
### Minor Changes
- Update exchanges to drop redundant `share` calls, since `@urql/core`’s `composeExchanges` utility now automatically does so for us
Submitted by [@kitten](https://github.com/kitten) (See [#3082](https://github.com/urql-graphql/urql/pull/3082))
### Patch Changes
- Upgrade to `wonka@^6.3.0`
Submitted by [@kitten](https://github.com/kitten) (See [#3104](https://github.com/urql-graphql/urql/pull/3104))
- Add TSDocs for all exchanges, documenting API internals
Submitted by [@kitten](https://github.com/kitten) (See [#3072](https://github.com/urql-graphql/urql/pull/3072))
- Updated dependencies (See [#3101](https://github.com/urql-graphql/urql/pull/3101), [#3033](https://github.com/urql-graphql/urql/pull/3033), [#3054](https://github.com/urql-graphql/urql/pull/3054), [#3053](https://github.com/urql-graphql/urql/pull/3053), [#3060](https://github.com/urql-graphql/urql/pull/3060), [#3081](https://github.com/urql-graphql/urql/pull/3081), [#3039](https://github.com/urql-graphql/urql/pull/3039), [#3104](https://github.com/urql-graphql/urql/pull/3104), [#3082](https://github.com/urql-graphql/urql/pull/3082), [#3097](https://github.com/urql-graphql/urql/pull/3097), [#3061](https://github.com/urql-graphql/urql/pull/3061), [#3055](https://github.com/urql-graphql/urql/pull/3055), [#3085](https://github.com/urql-graphql/urql/pull/3085), [#3079](https://github.com/urql-graphql/urql/pull/3079), [#3087](https://github.com/urql-graphql/urql/pull/3087), [#3059](https://github.com/urql-graphql/urql/pull/3059), [#3055](https://github.com/urql-graphql/urql/pull/3055), [#3057](https://github.com/urql-graphql/urql/pull/3057), [#3050](https://github.com/urql-graphql/urql/pull/3050), [#3062](https://github.com/urql-graphql/urql/pull/3062), [#3051](https://github.com/urql-graphql/urql/pull/3051), [#3043](https://github.com/urql-graphql/urql/pull/3043), [#3063](https://github.com/urql-graphql/urql/pull/3063), [#3054](https://github.com/urql-graphql/urql/pull/3054), [#3102](https://github.com/urql-graphql/urql/pull/3102), [#3097](https://github.com/urql-graphql/urql/pull/3097), [#3106](https://github.com/urql-graphql/urql/pull/3106), [#3058](https://github.com/urql-graphql/urql/pull/3058), and [#3062](https://github.com/urql-graphql/urql/pull/3062))
- @urql/core@4.0.0
## 1.0.0
### Major Changes
- **Goodbye IE11!** 👋 This major release removes support for IE11. All code that is shipped will be transpiled much less and will _not_ be ES5-compatible anymore, by [@kitten](https://github.com/kitten) (See [#2504](https://github.com/FormidableLabs/urql/pull/2504))
- Upgrade to [Wonka v6](https://github.com/0no-co/wonka) (`wonka@^6.0.0`), which has no breaking changes but is built to target ES2015 and comes with other minor improvements.
The library has fully been migrated to TypeScript which will hopefully help with making contributions easier!, by [@kitten](https://github.com/kitten) (See [#2504](https://github.com/FormidableLabs/urql/pull/2504))
### Patch Changes
- make `randomDelay` work correctly, by [@JoviDeCroock](https://github.com/JoviDeCroock) (See [#2615](https://github.com/FormidableLabs/urql/pull/2615))
- Updated dependencies (See [#2551](https://github.com/FormidableLabs/urql/pull/2551), [#2504](https://github.com/FormidableLabs/urql/pull/2504), [#2619](https://github.com/FormidableLabs/urql/pull/2619), [#2607](https://github.com/FormidableLabs/urql/pull/2607), and [#2504](https://github.com/FormidableLabs/urql/pull/2504))
- @urql/core@3.0.0
## 0.3.3
### Patch Changes
- Export `RetryExchangeOption` type from top level export, by [@KoltonG](https://github.com/KoltonG) (See [#2351](https://github.com/FormidableLabs/urql/pull/2351))
- Updated dependencies (See [#2384](https://github.com/FormidableLabs/urql/pull/2384) and [#2386](https://github.com/FormidableLabs/urql/pull/2386))
- @urql/core@2.4.4
## 0.3.2
### Patch Changes
- Extend peer dependency range of `graphql` to include `^16.0.0`.
As always when upgrading across many packages of `urql`, especially including `@urql/core` we recommend you to deduplicate dependencies after upgrading, using `npm dedupe` or `npx yarn-deduplicate`, by [@kitten](https://github.com/kitten) (See [#2133](https://github.com/FormidableLabs/urql/pull/2133))
- Updated dependencies (See [#2133](https://github.com/FormidableLabs/urql/pull/2133))
- @urql/core@2.3.6
## 0.3.1
### Patch Changes
- ⚠️ Fix operations sometimes not being executed after a retry is supposed to be triggered, due to a `setTimeout` reordering issue when the timer isn't as predictable as it should be, by [@kitten](https://github.com/kitten) (See [#2124](https://github.com/FormidableLabs/urql/pull/2124))
## 0.3.0
### Minor Changes
- Add a new `retryWith` option which allows operations to be updated when a request is being retried, by [@kitten](https://github.com/kitten) (See [#1881](https://github.com/FormidableLabs/urql/pull/1881))
### Patch Changes
- Updated dependencies (See [#1870](https://github.com/FormidableLabs/urql/pull/1870) and [#1880](https://github.com/FormidableLabs/urql/pull/1880))
- @urql/core@2.3.1
## 0.2.1
### Patch Changes
- Remove closure-compiler from the build step (See [#1570](https://github.com/FormidableLabs/urql/pull/1570))
- Updated dependencies (See [#1570](https://github.com/FormidableLabs/urql/pull/1570), [#1509](https://github.com/FormidableLabs/urql/pull/1509), [#1600](https://github.com/FormidableLabs/urql/pull/1600), and [#1515](https://github.com/FormidableLabs/urql/pull/1515))
- @urql/core@2.1.0
## 0.2.0
### Minor Changes
- Add a second `Operation` input argument to the `retryIf` predicate, so that retrying can be actively avoided for specific types of operations, e.g. mutations or subscriptions, in certain user-defined cases, by [@kitten](https://github.com/kitten) (See [#1117](https://github.com/FormidableLabs/urql/pull/1117))
### Patch Changes
- Updated dependencies (See [#1119](https://github.com/FormidableLabs/urql/pull/1119), [#1113](https://github.com/FormidableLabs/urql/pull/1113), [#1104](https://github.com/FormidableLabs/urql/pull/1104), and [#1123](https://github.com/FormidableLabs/urql/pull/1123))
- @urql/core@1.15.0
## 0.1.10
### Patch Changes
- ⚠️ Fix the production build overwriting the development build. Specifically in the previous release we mistakenly replaced all development bundles with production bundles. This doesn't have any direct influence on how these packages work, but prevented development warnings from being logged or full errors from being thrown, by [@kitten](https://github.com/kitten) (See [#1097](https://github.com/FormidableLabs/urql/pull/1097))
- Updated dependencies (See [#1097](https://github.com/FormidableLabs/urql/pull/1097))
- @urql/core@1.14.1
## 0.1.9
### Patch Changes
- Deprecate the `Operation.operationName` property in favor of `Operation.kind`. This name was
previously confusing as `operationName` was effectively referring to two different things. You can
safely upgrade to this new version, however to mute all deprecation warnings you will have to
**upgrade** all `urql` packages you use. If you have custom exchanges that spread operations, please
use [the new `makeOperation` helper
function](https://formidable.com/open-source/urql/docs/api/core/#makeoperation) instead, by [@bkonkle](https://github.com/bkonkle) (See [#1045](https://github.com/FormidableLabs/urql/pull/1045))
- Updated dependencies (See [#1094](https://github.com/FormidableLabs/urql/pull/1094) and [#1045](https://github.com/FormidableLabs/urql/pull/1045))
- @urql/core@1.14.0
## 0.1.8
### Patch Changes
- Upgrade to a minimum version of wonka@^4.0.14 to work around issues with React Native's minification builds, which use uglify-es and could lead to broken bundles, by [@kitten](https://github.com/kitten) (See [#842](https://github.com/FormidableLabs/urql/pull/842))
- Updated dependencies (See [#838](https://github.com/FormidableLabs/urql/pull/838) and [#842](https://github.com/FormidableLabs/urql/pull/842))
- @urql/core@1.12.0
## 0.1.7
### Patch Changes
- Add `source` debug name to all `dispatchDebug` calls during build time to identify events by which exchange dispatched them, by [@JoviDeCroock](https://github.com/JoviDeCroock) (See [#780](https://github.com/FormidableLabs/urql/pull/780))
- Updated dependencies (See [#780](https://github.com/FormidableLabs/urql/pull/780))
- @urql/core@1.11.7
## 0.1.6
### Patch Changes
- Add a `"./package.json"` entry to the `package.json`'s `"exports"` field for Node 14. This seems to be required by packages like `rollup-plugin-svelte` to function properly, by [@JoviDeCroock](https://github.com/JoviDeCroock) (See [#771](https://github.com/FormidableLabs/urql/pull/771))
- Updated dependencies (See [#771](https://github.com/FormidableLabs/urql/pull/771))
- @urql/core@1.11.6
## 0.1.5
### Patch Changes
- Add debugging events to exchanges that add more detailed information on what is happening
internally, which will be displayed by devtools like the urql [Chrome / Firefox extension](https://github.com/FormidableLabs/urql-devtools), by [@andyrichardson](https://github.com/andyrichardson) (See [#608](https://github.com/FormidableLabs/urql/pull/608))
- Updated dependencies (See [#608](https://github.com/FormidableLabs/urql/pull/608), [#718](https://github.com/FormidableLabs/urql/pull/718), and [#722](https://github.com/FormidableLabs/urql/pull/722))
- @urql/core@1.11.0
## 0.1.4
### Patch Changes
- Add graphql@^15.0.0 to peer dependency range, by [@kitten](https://github.com/kitten) (See [#688](https://github.com/FormidableLabs/urql/pull/688))
- Updated dependencies (See [#688](https://github.com/FormidableLabs/urql/pull/688) and [#678](https://github.com/FormidableLabs/urql/pull/678))
- @urql/core@1.10.8
## 0.1.3
### Patch Changes
- ⚠️ Fix node resolution when using Webpack, which experiences a bug where it only resolves
`package.json:main` instead of `module` when an `.mjs` file imports a package, by [@JoviDeCroock](https://github.com/JoviDeCroock) (See [#642](https://github.com/FormidableLabs/urql/pull/642))
- Updated dependencies (See [#642](https://github.com/FormidableLabs/urql/pull/642))
- @urql/core@1.10.4
## 0.1.2
### Patch Changes
- ⚠️ Fix Node.js Module support for v13 (experimental-modules) and v14. If your bundler doesn't support
`.mjs` files and fails to resolve the new version, please double check your configuration for
Webpack, or similar tools, by [@JoviDeCroock](https://github.com/JoviDeCroock) (See [#637](https://github.com/FormidableLabs/urql/pull/637))
- Updated dependencies (See [#637](https://github.com/FormidableLabs/urql/pull/637))
- @urql/core@1.10.3
## 0.1.1
### Patch Changes
- ⚠️ Fix Rollup bundle output being written to .es.js instead of .esm.js, by [@kitten](https://github.com/kitten) (See [#609](https://github.com/FormidableLabs/urql/pull/609))
- Updated dependencies (See [#609](https://github.com/FormidableLabs/urql/pull/609))
- @urql/core@1.10.1
## v0.1.0
**Initial Release**
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2018–2020 Formidable,
Copyright (c) urql GraphQL Team and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+15
View File
@@ -0,0 +1,15 @@
# @urql/exchange-retry (Exchange factory)
`@urql/exchange-retry` is an exchange for the [`urql`](../../README.md) GraphQL client that allows operations (queries, mutations, subscriptions) to be retried based on an `options` parameter.
## Quick Start Guide
First install `@urql/exchange-retry` alongside `urql`:
```sh
yarn add @urql/exchange-retry
# or
npm install --save @urql/exchange-retry
```
Read more about the [retry exchange](https://formidable.com/open-source/urql/docs/advanced/retry-operations).
@@ -0,0 +1,92 @@
import { CombinedError, Operation, Exchange } from '@urql/core';
/** Input parameters for the {@link retryExchange}. */
interface RetryExchangeOptions {
/** Specify the minimum time to wait until retrying.
*
* @remarks
* `initialDelayMs` specifies the minimum time (in milliseconds) to wait
* until a failed operation is retried.
*
* @defaultValue `1_000` - one second
*/
initialDelayMs?: number;
/** Specifies the maximum time to wait until retrying.
*
* @remarks
* `maxDelayMs` specifies the maximum time (in milliseconds) to wait
* until a failed operation is retried. While `initialDelayMs`
* specifies the minimum amount of time, `randomDelay` may cause
* the delay to increase over multiple attempts.
*
* @defaultValue `15_000` - 15 seconds
*/
maxDelayMs?: number;
/** Enables a random exponential backoff to increase the delay over multiple retries.
*
* @remarks
* `randomDelay`, unless disabled, increases the time until a failed
* operation is retried over multiple attempts. It increases the time
* starting at `initialDelayMs` by 1.5x with an added factor of 0–1,
* until `maxDelayMs` is reached.
*
* @defaultValue `true` - enables random exponential backoff
*/
randomDelay?: boolean;
/** Specifies the maximum times an operation should be sent to the API.
*
* @remarks
* `maxNumberAttempts` defines the number of attempts an operation should
* be retried until it's considered failed.
*
* @defaultValue `2` - Retry once, i.e. two attempts
*/
maxNumberAttempts?: number;
/** Predicate allowing you to selectively not retry `Operation`s.
*
* @remarks
* `retryIf` is called with a {@link CombinedError} and the {@link Operation} that
* failed. If this function returns false the failed `Operation` is not retried.
*
* @defaultValue `(error) => !!error.networkError` - retries only on network errors.
*/
retryIf?(error: CombinedError, operation: Operation): boolean;
/** Transform function allowing you to selectively replace a retried `Operation` or return nullish value.
*
* @remarks
* `retryWhen` is called with a {@link CombinedError} and the {@link Operation} that
* failed. If this function returns an `Operation`, `retryExchange` will replace the
* failed `Operation` and retry. It won't retry the `Operation` if a nullish value
* is returned.
*
* The `retryIf` function, if defined, takes precedence and overrides this option.
*/
retryWith?(error: CombinedError, operation: Operation): Operation | null | undefined;
}
/** Exchange factory that retries failed operations.
*
* @param options - A {@link RetriesExchangeOptions} configuration object.
* @returns the created retry {@link Exchange}.
*
* @remarks
* The `retryExchange` retries failed operations with specified delays
* and exponential backoff.
*
* You may define a {@link RetryExchangeOptions.retryIf} or
* {@link RetryExchangeOptions.retryWhen} function to only retry
* certain kinds of operations, e.g. only queries.
*
* @example
* ```ts
* retryExchange({
* initialDelayMs: 1000,
* maxDelayMs: 15000,
* randomDelay: true,
* maxNumberAttempts: 2,
* retryIf: err => err && err.networkError,
* });
* ```
*/
declare const retryExchange: (options?: RetryExchangeOptions) => Exchange;
export { RetryExchangeOptions, retryExchange };
@@ -0,0 +1,133 @@
Object.defineProperty(exports, '__esModule', { value: true });
var wonka = require('wonka');
var core = require('@urql/core');
/** Input parameters for the {@link retryExchange}. */
/** Exchange factory that retries failed operations.
*
* @param options - A {@link RetriesExchangeOptions} configuration object.
* @returns the created retry {@link Exchange}.
*
* @remarks
* The `retryExchange` retries failed operations with specified delays
* and exponential backoff.
*
* You may define a {@link RetryExchangeOptions.retryIf} or
* {@link RetryExchangeOptions.retryWhen} function to only retry
* certain kinds of operations, e.g. only queries.
*
* @example
* ```ts
* retryExchange({
* initialDelayMs: 1000,
* maxDelayMs: 15000,
* randomDelay: true,
* maxNumberAttempts: 2,
* retryIf: err => err && err.networkError,
* });
* ```
*/
var retryExchange = (options = {}) => {
var {
retryIf,
retryWith
} = options;
var MIN_DELAY = options.initialDelayMs || 1000;
var MAX_DELAY = options.maxDelayMs || 15_000;
var MAX_ATTEMPTS = options.maxNumberAttempts || 2;
var RANDOM_DELAY = options.randomDelay != null ? !!options.randomDelay : true;
return ({
forward,
dispatchDebug
}) => operations$ => {
var {
source: retry$,
next: nextRetryOperation
} = wonka.makeSubject();
var retryWithBackoff$ = wonka.mergeMap(operation => {
var retry = operation.context.retry || {
count: 0,
delay: null
};
var retryCount = ++retry.count;
var delayAmount = retry.delay || MIN_DELAY;
var backoffFactor = Math.random() + 1.5;
if (RANDOM_DELAY) {
// if randomDelay is enabled and it won't exceed the max delay, apply a random
// amount to the delay to avoid thundering herd problem
if (delayAmount * backoffFactor < MAX_DELAY) {
delayAmount *= backoffFactor;
} else {
delayAmount = MAX_DELAY;
}
} else {
// otherwise, increase the delay proportionately by the initial delay
delayAmount = Math.min(retryCount * MIN_DELAY, MAX_DELAY);
}
// ensure the delay is carried over to the next context
retry.delay = delayAmount;
// We stop the retries if a teardown event for this operation comes in
// But if this event comes through regularly we also stop the retries, since it's
// basically the query retrying itself, no backoff should be added!
var teardown$ = wonka.filter(op => {
return (op.kind === 'query' || op.kind === 'teardown') && op.key === operation.key;
})(operations$);
process.env.NODE_ENV !== 'production' ? dispatchDebug({
type: 'retryAttempt',
message: `The operation has failed and a retry has been triggered (${retryCount} / ${MAX_ATTEMPTS})`,
operation,
data: {
retryCount,
delayAmount
},
"source": "retryExchange"
}) : undefined;
// Add new retryDelay and retryCount to operation
return (
// Stop retry if a teardown comes in
wonka.takeUntil(teardown$)(wonka.debounce(() => delayAmount)(wonka.fromValue(core.makeOperation(operation.kind, operation, {
...operation.context,
retry
}))))
);
})(retry$);
return wonka.filter(res => {
var retry = res.operation.context.retry;
// Only retry if the error passes the conditional retryIf function (if passed)
// or if the error contains a networkError
if (!res.error || (retryIf ? !retryIf(res.error, res.operation) : !retryWith && !res.error.networkError)) {
// Reset the delay state for a successful operation
if (retry) {
retry.count = 0;
retry.delay = null;
}
return true;
}
var maxNumberAttemptsExceeded = (retry && retry.count || 0) >= MAX_ATTEMPTS - 1;
if (!maxNumberAttemptsExceeded) {
var _operation = retryWith ? retryWith(res.error, res.operation) : res.operation;
if (!_operation) return true;
// Send failed responses to be retried by calling next on the retry$ subject
// Exclude operations that have been retried more than the specified max
nextRetryOperation(_operation);
return false;
}
process.env.NODE_ENV !== 'production' ? dispatchDebug({
type: 'retryExhausted',
message: 'Maximum number of retries has been reached. No further retries will be performed.',
operation: res.operation,
"source": "retryExchange"
}) : undefined;
return true;
})(forward(wonka.merge([operations$, retryWithBackoff$])));
};
};
exports.retryExchange = retryExchange;
//# sourceMappingURL=urql-exchange-retry.js.map
@@ -0,0 +1 @@
{"version":3,"file":"urql-exchange-retry.js","sources":["../src/retryExchange.ts"],"sourcesContent":null,"names":["retryExchange","options","retryIf","retryWith","MIN_DELAY","initialDelayMs","MAX_DELAY","maxDelayMs","MAX_ATTEMPTS","maxNumberAttempts","RANDOM_DELAY","randomDelay","forward","dispatchDebug","operations$","source","retry$","next","nextRetryOperation","makeSubject","retryWithBackoff$","mergeMap","operation","retry","context","count","delay","retryCount","delayAmount","backoffFactor","Math","random","min","teardown$","filter","op","kind","key","process","env","NODE_ENV","type","message","data","undefined","takeUntil","debounce","fromValue","makeOperation","res","error","networkError","maxNumberAttemptsExceeded","merge"],"mappings":";;;;;AAcA;;AAwEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,IAAMA,aAAa,GAAGA,CAACC,OAA6B,GAAG,EAAE,KAAe;EAC7E,IAAM;IAAEC,OAAO;AAAEC,IAAAA,SAAAA;AAAU,GAAC,GAAGF,OAAO,CAAA;AACtC,EAAA,IAAMG,SAAS,GAAGH,OAAO,CAACI,cAAc,IAAI,IAAI,CAAA;AAChD,EAAA,IAAMC,SAAS,GAAGL,OAAO,CAACM,UAAU,IAAI,MAAM,CAAA;AAC9C,EAAA,IAAMC,YAAY,GAAGP,OAAO,CAACQ,iBAAiB,IAAI,CAAC,CAAA;AACnD,EAAA,IAAMC,YAAY,GAChBT,OAAO,CAACU,WAAW,IAAI,IAAI,GAAG,CAAC,CAACV,OAAO,CAACU,WAAW,GAAG,IAAI,CAAA;AAE5D,EAAA,OAAO,CAAC;IAAEC,OAAO;AAAEC,IAAAA,aAAAA;GAAe,KAChCC,WAAW,IAAI;IACb,IAAM;AAAEC,MAAAA,MAAM,EAAEC,MAAM;AAAEC,MAAAA,IAAI,EAAEC,kBAAAA;KAAoB,GAChDC,iBAAW,EAAa,CAAA;AAE1B,IAAA,IAAMC,iBAAiB,GAErBC,cAAQ,CAAEC,SAAoB,IAAK;AACjC,MAAA,IAAMC,KAAiB,GAAGD,SAAS,CAACE,OAAO,CAACD,KAAK,IAAI;AACnDE,QAAAA,KAAK,EAAE,CAAC;AACRC,QAAAA,KAAK,EAAE,IAAA;OACR,CAAA;AAED,MAAA,IAAMC,UAAU,GAAG,EAAEJ,KAAK,CAACE,KAAK,CAAA;AAChC,MAAA,IAAIG,WAAW,GAAGL,KAAK,CAACG,KAAK,IAAItB,SAAS,CAAA;MAE1C,IAAMyB,aAAa,GAAGC,IAAI,CAACC,MAAM,EAAE,GAAG,GAAG,CAAA;AACzC,MAAA,IAAIrB,YAAY,EAAE;AAChB;AACA;AACA,QAAA,IAAIkB,WAAW,GAAGC,aAAa,GAAGvB,SAAS,EAAE;AAC3CsB,UAAAA,WAAW,IAAIC,aAAa,CAAA;AAC9B,SAAC,MAAM;AACLD,UAAAA,WAAW,GAAGtB,SAAS,CAAA;AACzB,SAAA;AACF,OAAC,MAAM;AACL;QACAsB,WAAW,GAAGE,IAAI,CAACE,GAAG,CAACL,UAAU,GAAGvB,SAAS,EAAEE,SAAS,CAAC,CAAA;AAC3D,OAAA;;AAEA;MACAiB,KAAK,CAACG,KAAK,GAAGE,WAAW,CAAA;;AAEzB;AACA;AACA;AACA,MAAA,IAAMK,SAAS,GAEbC,YAAM,CAACC,EAAE,IAAI;AACX,QAAA,OACE,CAACA,EAAE,CAACC,IAAI,KAAK,OAAO,IAAID,EAAE,CAACC,IAAI,KAAK,UAAU,KAC9CD,EAAE,CAACE,GAAG,KAAKf,SAAS,CAACe,GAAG,CAAA;OAE3B,CAAC,CANFvB,WAAW,CAOZ,CAAA;AAEDwB,MAAAA,OAAA,CAAAC,GAAA,CAAAC,QAAA,KAAA,YAAA,GAAA3B,aAAa,CAAC;AACZ4B,QAAAA,IAAI,EAAE,cAAc;AACpBC,QAAAA,OAAO,EAAE,CAAA,yDAAA,EAA4Df,UAAU,CAAA,GAAA,EAAMnB,YAAY,CAAG,CAAA,CAAA;QACpGc,SAAS;AACTqB,QAAAA,IAAI,EAAE;UACJhB,UAAU;AACVC,UAAAA,WAAAA;SACD;AAAA,QAAA,QAAA,EAAA,eAAA;OACF,CAAC,GAAAgB,SAAA,CAAA;;AAEF;AACA,MAAA;AAQE;AACAC,QAAAA,eAAS,CAACZ,SAAS,CAAC,CAFpBa,cAAQ,CAAC,MAAMlB,WAAW,CAAC,CAN3BmB,eAAS,CACPC,kBAAa,CAAC1B,SAAS,CAACc,IAAI,EAAEd,SAAS,EAAE;UACvC,GAAGA,SAAS,CAACE,OAAO;AACpBD,UAAAA,KAAAA;AACF,SAAC,CACH,CAAC,CAAA,CAAA;AAAA,QAAA;KAKJ,CAAC,CA9DFP,MAAM,CA+DP,CAAA;IAED,OAGEkB,YAAM,CAACe,GAAG,IAAI;MACZ,IAAM1B,KAAK,GAAG0B,GAAG,CAAC3B,SAAS,CAACE,OAAO,CAACD,KAA+B,CAAA;AACnE;AACA;AACA,MAAA,IACE,CAAC0B,GAAG,CAACC,KAAK,KACThD,OAAO,GACJ,CAACA,OAAO,CAAC+C,GAAG,CAACC,KAAK,EAAED,GAAG,CAAC3B,SAAS,CAAC,GAClC,CAACnB,SAAS,IAAI,CAAC8C,GAAG,CAACC,KAAK,CAACC,YAAY,CAAC,EAC1C;AACA;AACA,QAAA,IAAI5B,KAAK,EAAE;UACTA,KAAK,CAACE,KAAK,GAAG,CAAC,CAAA;UACfF,KAAK,CAACG,KAAK,GAAG,IAAI,CAAA;AACpB,SAAA;AACA,QAAA,OAAO,IAAI,CAAA;AACb,OAAA;AAEA,MAAA,IAAM0B,yBAAyB,GAC7B,CAAE7B,KAAK,IAAIA,KAAK,CAACE,KAAK,IAAK,CAAC,KAAKjB,YAAY,GAAG,CAAC,CAAA;MACnD,IAAI,CAAC4C,yBAAyB,EAAE;AAC9B,QAAA,IAAM9B,UAAS,GAAGnB,SAAS,GACvBA,SAAS,CAAC8C,GAAG,CAACC,KAAK,EAAED,GAAG,CAAC3B,SAAS,CAAC,GACnC2B,GAAG,CAAC3B,SAAS,CAAA;AACjB,QAAA,IAAI,CAACA,UAAS,EAAE,OAAO,IAAI,CAAA;;AAE3B;AACA;QACAJ,kBAAkB,CAACI,UAAS,CAAC,CAAA;AAC7B,QAAA,OAAO,KAAK,CAAA;AACd,OAAA;AAEAgB,MAAAA,OAAA,CAAAC,GAAA,CAAAC,QAAA,KAAA,YAAA,GAAA3B,aAAa,CAAC;AACZ4B,QAAAA,IAAI,EAAE,gBAAgB;AACtBC,QAAAA,OAAO,EACL,mFAAmF;QACrFpB,SAAS,EAAE2B,GAAG,CAAC3B,SAAS;AAAA,QAAA,QAAA,EAAA,eAAA;OACzB,CAAC,GAAAsB,SAAA,CAAA;AAEF,MAAA,OAAO,IAAI,CAAA;KACZ,CAAC,CAzCFhC,OAAO,CADPyC,WAAK,CAAC,CAACvC,WAAW,EAAEM,iBAAiB,CAAC,CAAC,CAAA,CAAA,CAAA;GA4C1C,CAAA;AACL;;;;"}
@@ -0,0 +1,76 @@
import { makeSubject as r, mergeMap as e, filter as t, takeUntil as a, debounce as o, fromValue as n, merge as i } from "wonka";
import { makeOperation as u } from "@urql/core";
var retryExchange = (y = {}) => {
var {retryIf: d, retryWith: s} = y;
var l = y.initialDelayMs || 1e3;
var p = y.maxDelayMs || 15e3;
var m = y.maxNumberAttempts || 2;
var c = null != y.randomDelay ? !!y.randomDelay : !0;
return ({forward: y, dispatchDebug: v}) => f => {
var {source: h, next: x} = r();
var E = e((r => {
var e = r.context.retry || {
count: 0,
delay: null
};
var i = ++e.count;
var y = e.delay || l;
var d = Math.random() + 1.5;
if (c) {
if (y * d < p) {
y *= d;
} else {
y = p;
}
} else {
y = Math.min(i * l, p);
}
e.delay = y;
var s = t((e => ("query" === e.kind || "teardown" === e.kind) && e.key === r.key))(f);
"production" !== process.env.NODE_ENV && v({
type: "retryAttempt",
message: `The operation has failed and a retry has been triggered (${i} / ${m})`,
operation: r,
data: {
retryCount: i,
delayAmount: y
},
source: "retryExchange"
});
return a(s)(o((() => y))(n(u(r.kind, r, {
...r.context,
retry: e
}))));
}))(h);
return t((r => {
var e = r.operation.context.retry;
if (!(r.error && (d ? d(r.error, r.operation) : s || r.error.networkError))) {
if (e) {
e.count = 0;
e.delay = null;
}
return !0;
}
if (!((e && e.count || 0) >= m - 1)) {
var t = s ? s(r.error, r.operation) : r.operation;
if (!t) {
return !0;
}
x(t);
return !1;
}
"production" !== process.env.NODE_ENV && v({
type: "retryExhausted",
message: "Maximum number of retries has been reached. No further retries will be performed.",
operation: r.operation,
source: "retryExchange"
});
return !0;
}))(y(i([ f, E ])));
};
};
export { retryExchange };
//# sourceMappingURL=urql-exchange-retry.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"urql-exchange-retry.mjs","sources":["../src/retryExchange.ts"],"sourcesContent":null,"names":["retryExchange","options","retryIf","retryWith","MIN_DELAY","initialDelayMs","MAX_DELAY","maxDelayMs","MAX_ATTEMPTS","maxNumberAttempts","RANDOM_DELAY","randomDelay","forward","dispatchDebug","operations$","source","retry$","next","nextRetryOperation","makeSubject","retryWithBackoff$","mergeMap","operation","retry","context","count","delay","retryCount","delayAmount","backoffFactor","Math","random","min","teardown$","filter","op","kind","key","process","env","NODE_ENV","type","message","data","takeUntil","debounce","fromValue","makeOperation","res","error","networkError","merge"],"mappings":";;;;AA8GO,IAAMA,gBAAgBA,CAACC,IAAgC;EAC5D,KAAMC,SAAEA,GAAOC,WAAEA,KAAcF;EAC/B,IAAMG,IAAYH,EAAQI,kBAAkB;EAC5C,IAAMC,IAAYL,EAAQM,cAAc;EACxC,IAAMC,IAAeP,EAAQQ,qBAAqB;EAClD,IAAMC,IACmB,QAAvBT,EAAQU,gBAAwBV,EAAQU,eAAc;EAExD,OAAO,EAAGC,YAASC,sBACjBC;IACE,KAAQC,QAAQC,GAAQC,MAAMC,KAC5BC;IAEF,IAAMC,IAEJC,GAAUC;MACR,IAAMC,IAAoBD,EAAUE,QAAQD,SAAS;QACnDE,OAAO;QACPC,OAAO;;MAGT,IAAMC,MAAeJ,EAAME;MAC3B,IAAIG,IAAcL,EAAMG,SAAStB;MAEjC,IAAMyB,IAAgBC,KAAKC,WAAW;MACtC,IAAIrB;QAGF,IAAIkB,IAAcC,IAAgBvB;UAChCsB,KAAeC;;UAEfD,IAActB;;;QAIhBsB,IAAcE,KAAKE,IAAIL,IAAavB,GAAWE;;MAIjDiB,EAAMG,QAAQE;MAKd,IAAMK,IAEJC,GAAOC,MAEU,YAAZA,EAAGC,QAAgC,eAAZD,EAAGC,SAC3BD,EAAGE,QAAQf,EAAUe,KAHzBH,CADApB;MASF,iBAAAwB,QAAAC,IAAAC,YAAA3B,EAAc;QACZ4B,MAAM;QACNC,SAAS,4DAA4Df,OAAgBnB;QACrFc;QACAqB,MAAM;UACJhB;UACAC;;QACDb,QAAA;;MAIH,OASE6B,EAAUX,EATZ,CAOEY,GAAS,MAAMjB,GAAfiB,CANAC,EACEC,EAAczB,EAAUc,MAAMd,GAAW;WACpCA,EAAUE;QACbD;;AAEH,OAxDLF,CADAL;IAiEF,OAGEkB,GAAOc;MACL,IAAMzB,IAAQyB,EAAI1B,UAAUE,QAAQD;MAGpC,MACGyB,EAAIC,UACJ/C,IACIA,EAAQ8C,EAAIC,OAAOD,EAAI1B,aACvBnB,KAAc6C,EAAIC,MAAMC,gBAC7B;QAEA,IAAI3B,GAAO;UACTA,EAAME,QAAQ;UACdF,EAAMG,QAAQ;AAChB;QACA,QAAO;AACT;MAIA,OADIH,KAASA,EAAME,SAAU,MAAMjB,IAAe,IAClB;QAC9B,IAAMc,IAAYnB,IACdA,EAAU6C,EAAIC,OAAOD,EAAI1B,aACzB0B,EAAI1B;QACR,KAAKA;UAAW,QAAO;;QAIvBJ,EAAmBI;QACnB,QAAO;AACT;MAEA,iBAAAgB,QAAAC,IAAAC,YAAA3B,EAAc;QACZ4B,MAAM;QACNC,SACE;QACFpB,WAAW0B,EAAI1B;QAASP,QAAA;;MAG1B,QAAO;AAAI,OAvCbmB,CADAtB,EADAuC,EAAM,EAACrC,GAAaM;AAAmB;AA4C1C;;"}
+63
View File
@@ -0,0 +1,63 @@
{
"name": "@urql/exchange-retry",
"version": "1.3.2",
"description": "An exchange for operation retry support in urql",
"sideEffects": false,
"homepage": "https://formidable.com/open-source/urql/docs/",
"bugs": "https://github.com/urql-graphql/urql/issues",
"license": "MIT",
"author": "urql GraphQL Contributors",
"repository": {
"type": "git",
"url": "https://github.com/urql-graphql/urql.git",
"directory": "exchanges/retry"
},
"keywords": [
"urql",
"graphql client",
"graphql",
"exchanges",
"retry"
],
"main": "dist/urql-exchange-retry",
"module": "dist/urql-exchange-retry.mjs",
"types": "dist/urql-exchange-retry.d.ts",
"source": "src/index.ts",
"exports": {
".": {
"types": "./dist/urql-exchange-retry.d.ts",
"import": "./dist/urql-exchange-retry.mjs",
"require": "./dist/urql-exchange-retry.js",
"source": "./src/index.ts"
},
"./package.json": "./package.json"
},
"files": [
"LICENSE",
"CHANGELOG.md",
"README.md",
"dist/"
],
"devDependencies": {
"graphql": "^16.0.0",
"@urql/core": "5.1.2"
},
"peerDependencies": {
"@urql/core": "^5.0.0"
},
"dependencies": {
"@urql/core": "^5.1.2",
"wonka": "^6.3.2"
},
"publishConfig": {
"access": "public",
"provenance": true
},
"scripts": {
"test": "vitest",
"clean": "rimraf dist",
"check": "tsc --noEmit",
"lint": "eslint --ext=js,jsx,ts,tsx .",
"build": "rollup -c ../../scripts/rollup/config.mjs"
}
}