Server: Phase 2 (REVIEW not respected yet)
This commit is contained in:
1 parent
5d16ded553
commit
142b47674d
4271 files changed
+1203269
No files matched your search
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-present Tanner Linsley
|
||||
|
||||
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.
|
||||
Generated
Vendored
+56
@@ -0,0 +1,56 @@
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/checkPrivateRedeclaration.js
|
||||
function _checkPrivateRedeclaration(e, t) {
|
||||
if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
|
||||
}
|
||||
//#endregion
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldInitSpec.js
|
||||
function _classPrivateFieldInitSpec(e, t, a) {
|
||||
_checkPrivateRedeclaration(e, t), t.set(e, a);
|
||||
}
|
||||
//#endregion
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/assertClassBrand.js
|
||||
function _assertClassBrand(e, t, n) {
|
||||
if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
|
||||
throw new TypeError("Private element is not present on this object");
|
||||
}
|
||||
//#endregion
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldGet2.js
|
||||
function _classPrivateFieldGet2(s, a) {
|
||||
return s.get(_assertClassBrand(s, a));
|
||||
}
|
||||
//#endregion
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldSet2.js
|
||||
function _classPrivateFieldSet2(s, a, r) {
|
||||
return s.set(_assertClassBrand(s, a), r), r;
|
||||
}
|
||||
//#endregion
|
||||
Object.defineProperty(exports, "_assertClassBrand", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return _assertClassBrand;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "_checkPrivateRedeclaration", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return _checkPrivateRedeclaration;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "_classPrivateFieldGet2", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return _classPrivateFieldGet2;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "_classPrivateFieldInitSpec", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return _classPrivateFieldInitSpec;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "_classPrivateFieldSet2", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return _classPrivateFieldSet2;
|
||||
}
|
||||
});
|
||||
Generated
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/checkPrivateRedeclaration.js
|
||||
function _checkPrivateRedeclaration(e, t) {
|
||||
if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
|
||||
}
|
||||
//#endregion
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldInitSpec.js
|
||||
function _classPrivateFieldInitSpec(e, t, a) {
|
||||
_checkPrivateRedeclaration(e, t), t.set(e, a);
|
||||
}
|
||||
//#endregion
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/assertClassBrand.js
|
||||
function _assertClassBrand(e, t, n) {
|
||||
if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
|
||||
throw new TypeError("Private element is not present on this object");
|
||||
}
|
||||
//#endregion
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldGet2.js
|
||||
function _classPrivateFieldGet2(s, a) {
|
||||
return s.get(_assertClassBrand(s, a));
|
||||
}
|
||||
//#endregion
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldSet2.js
|
||||
function _classPrivateFieldSet2(s, a, r) {
|
||||
return s.set(_assertClassBrand(s, a), r), r;
|
||||
}
|
||||
//#endregion
|
||||
export { _checkPrivateRedeclaration as a, _classPrivateFieldInitSpec as i, _classPrivateFieldGet2 as n, _assertClassBrand as r, _classPrivateFieldSet2 as t };
|
||||
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
import { a as _checkPrivateRedeclaration } from "./classPrivateFieldSet2-CV7wyte-.js";
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateMethodInitSpec.js
|
||||
function _classPrivateMethodInitSpec(e, a) {
|
||||
_checkPrivateRedeclaration(e, a), a.add(e);
|
||||
}
|
||||
//#endregion
|
||||
export { _classPrivateMethodInitSpec as t };
|
||||
Generated
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
|
||||
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateMethodInitSpec.js
|
||||
function _classPrivateMethodInitSpec(e, a) {
|
||||
require_classPrivateFieldSet2._checkPrivateRedeclaration(e, a), a.add(e);
|
||||
}
|
||||
//#endregion
|
||||
Object.defineProperty(exports, "_classPrivateMethodInitSpec", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return _classPrivateMethodInitSpec;
|
||||
}
|
||||
});
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_utils = require("./utils.cjs");
|
||||
//#region src/environmentManager.ts
|
||||
let isServerFn = () => require_utils.isServer;
|
||||
/**
|
||||
* Returns whether the current runtime should be treated as a server environment.
|
||||
*/
|
||||
const isServer = () => isServerFn();
|
||||
/**
|
||||
* Manages how TanStack Query detects whether the current runtime should be treated as
|
||||
* server-side, which disables scheduling refetch timers and changes the default `retry` count
|
||||
* and `gcTime`. By default, the detection treats a missing `window` (or the presence of a
|
||||
* `Deno` global) as server.
|
||||
*
|
||||
* Override this for runtimes where that default detection would give the wrong answer — for
|
||||
* example, a Service Worker, where `window` is undefined even though the environment should
|
||||
* behave like a client.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { environmentManager } from '@tanstack/query-core'
|
||||
*
|
||||
* environmentManager.setIsServer(() => false)
|
||||
* ```
|
||||
*/
|
||||
const environmentManager = {
|
||||
isServer,
|
||||
/**
|
||||
* Overrides the server check globally.
|
||||
*/
|
||||
setIsServer(isServerValue) {
|
||||
isServerFn = isServerValue;
|
||||
}
|
||||
};
|
||||
//#endregion
|
||||
exports.environmentManager = environmentManager;
|
||||
exports.isServer = isServer;
|
||||
|
||||
//# sourceMappingURL=environmentManager.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"environmentManager.cjs","names":["defaultIsServer"],"sources":["../../src/environmentManager.ts"],"sourcesContent":["import { isServer as defaultIsServer } from './utils'\n\nexport type IsServerValue = () => boolean\n\nlet isServerFn: IsServerValue = () => defaultIsServer\n\n/**\n * Returns whether the current runtime should be treated as a server environment.\n */\nexport const isServer = (): boolean => isServerFn()\n\n/**\n * Manages how TanStack Query detects whether the current runtime should be treated as\n * server-side, which disables scheduling refetch timers and changes the default `retry` count\n * and `gcTime`. By default, the detection treats a missing `window` (or the presence of a\n * `Deno` global) as server.\n *\n * Override this for runtimes where that default detection would give the wrong answer — for\n * example, a Service Worker, where `window` is undefined even though the environment should\n * behave like a client.\n *\n * @example\n * ```ts\n * import { environmentManager } from '@tanstack/query-core'\n *\n * environmentManager.setIsServer(() => false)\n * ```\n */\nexport const environmentManager = {\n isServer,\n /**\n * Overrides the server check globally.\n */\n setIsServer(isServerValue: IsServerValue): void {\n isServerFn = isServerValue\n },\n}\n"],"mappings":";;;AAIA,IAAI,mBAAkCA,cAAAA;;;;AAKtC,MAAa,iBAA0B,WAAW;;;;;;;;;;;;;;;;;;AAmBlD,MAAa,qBAAqB;CAChC;;;;CAIA,YAAY,eAAoC;EAC9C,aAAa;CACf;AACF"}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
//#region src/environmentManager.d.ts
|
||||
type IsServerValue = () => boolean;
|
||||
/**
|
||||
* Returns whether the current runtime should be treated as a server environment.
|
||||
*/
|
||||
declare const isServer: () => boolean;
|
||||
/**
|
||||
* Manages how TanStack Query detects whether the current runtime should be treated as
|
||||
* server-side, which disables scheduling refetch timers and changes the default `retry` count
|
||||
* and `gcTime`. By default, the detection treats a missing `window` (or the presence of a
|
||||
* `Deno` global) as server.
|
||||
*
|
||||
* Override this for runtimes where that default detection would give the wrong answer — for
|
||||
* example, a Service Worker, where `window` is undefined even though the environment should
|
||||
* behave like a client.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { environmentManager } from '@tanstack/query-core'
|
||||
*
|
||||
* environmentManager.setIsServer(() => false)
|
||||
* ```
|
||||
*/
|
||||
declare const environmentManager: {
|
||||
isServer: () => boolean;
|
||||
/**
|
||||
* Overrides the server check globally.
|
||||
*/
|
||||
setIsServer(isServerValue: IsServerValue): void;
|
||||
};
|
||||
//#endregion
|
||||
export { IsServerValue, environmentManager, isServer };
|
||||
//# sourceMappingURL=environmentManager.d.cts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"environmentManager.d.cts","names":[],"sources":["../../src/environmentManager.ts"],"mappings":";KAEY;;;;cAOC;;;;;;;;;;;;;;;;;;cAmBA;EAnBe;;;;EAwBC,YAAA,eAAA"}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
//#region src/environmentManager.d.ts
|
||||
type IsServerValue = () => boolean;
|
||||
/**
|
||||
* Returns whether the current runtime should be treated as a server environment.
|
||||
*/
|
||||
declare const isServer: () => boolean;
|
||||
/**
|
||||
* Manages how TanStack Query detects whether the current runtime should be treated as
|
||||
* server-side, which disables scheduling refetch timers and changes the default `retry` count
|
||||
* and `gcTime`. By default, the detection treats a missing `window` (or the presence of a
|
||||
* `Deno` global) as server.
|
||||
*
|
||||
* Override this for runtimes where that default detection would give the wrong answer — for
|
||||
* example, a Service Worker, where `window` is undefined even though the environment should
|
||||
* behave like a client.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { environmentManager } from '@tanstack/query-core'
|
||||
*
|
||||
* environmentManager.setIsServer(() => false)
|
||||
* ```
|
||||
*/
|
||||
declare const environmentManager: {
|
||||
isServer: () => boolean;
|
||||
/**
|
||||
* Overrides the server check globally.
|
||||
*/
|
||||
setIsServer(isServerValue: IsServerValue): void;
|
||||
};
|
||||
//#endregion
|
||||
export { IsServerValue, environmentManager, isServer };
|
||||
//# sourceMappingURL=environmentManager.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"environmentManager.d.ts","names":[],"sources":["../../src/environmentManager.ts"],"mappings":";KAEY;;;;cAOC;;;;;;;;;;;;;;;;;;cAmBA;EAnBe;;;;EAwBC,YAAA,eAAA"}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { isServer as isServer$1 } from "./utils.js";
|
||||
//#region src/environmentManager.ts
|
||||
let isServerFn = () => isServer$1;
|
||||
/**
|
||||
* Returns whether the current runtime should be treated as a server environment.
|
||||
*/
|
||||
const isServer = () => isServerFn();
|
||||
/**
|
||||
* Manages how TanStack Query detects whether the current runtime should be treated as
|
||||
* server-side, which disables scheduling refetch timers and changes the default `retry` count
|
||||
* and `gcTime`. By default, the detection treats a missing `window` (or the presence of a
|
||||
* `Deno` global) as server.
|
||||
*
|
||||
* Override this for runtimes where that default detection would give the wrong answer — for
|
||||
* example, a Service Worker, where `window` is undefined even though the environment should
|
||||
* behave like a client.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { environmentManager } from '@tanstack/query-core'
|
||||
*
|
||||
* environmentManager.setIsServer(() => false)
|
||||
* ```
|
||||
*/
|
||||
const environmentManager = {
|
||||
isServer,
|
||||
/**
|
||||
* Overrides the server check globally.
|
||||
*/
|
||||
setIsServer(isServerValue) {
|
||||
isServerFn = isServerValue;
|
||||
}
|
||||
};
|
||||
//#endregion
|
||||
export { environmentManager, isServer };
|
||||
|
||||
//# sourceMappingURL=environmentManager.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"environmentManager.js","names":["defaultIsServer"],"sources":["../../src/environmentManager.ts"],"sourcesContent":["import { isServer as defaultIsServer } from './utils'\n\nexport type IsServerValue = () => boolean\n\nlet isServerFn: IsServerValue = () => defaultIsServer\n\n/**\n * Returns whether the current runtime should be treated as a server environment.\n */\nexport const isServer = (): boolean => isServerFn()\n\n/**\n * Manages how TanStack Query detects whether the current runtime should be treated as\n * server-side, which disables scheduling refetch timers and changes the default `retry` count\n * and `gcTime`. By default, the detection treats a missing `window` (or the presence of a\n * `Deno` global) as server.\n *\n * Override this for runtimes where that default detection would give the wrong answer — for\n * example, a Service Worker, where `window` is undefined even though the environment should\n * behave like a client.\n *\n * @example\n * ```ts\n * import { environmentManager } from '@tanstack/query-core'\n *\n * environmentManager.setIsServer(() => false)\n * ```\n */\nexport const environmentManager = {\n isServer,\n /**\n * Overrides the server check globally.\n */\n setIsServer(isServerValue: IsServerValue): void {\n isServerFn = isServerValue\n },\n}\n"],"mappings":";;AAIA,IAAI,mBAAkCA;;;;AAKtC,MAAa,iBAA0B,WAAW;;;;;;;;;;;;;;;;;;AAmBlD,MAAa,qBAAqB;CAChC;;;;CAIA,YAAY,eAAoC;EAC9C,aAAa;CACf;AACF"}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
|
||||
const require_subscribable = require("./subscribable.cjs");
|
||||
//#region src/focusManager.ts
|
||||
var _focused = /* @__PURE__ */ new WeakMap();
|
||||
var _cleanup = /* @__PURE__ */ new WeakMap();
|
||||
var _setup = /* @__PURE__ */ new WeakMap();
|
||||
/**
|
||||
* The `FocusManager` manages the focus state within TanStack Query.
|
||||
*
|
||||
* It can be used to change the default event listeners or to manually change the focus state.
|
||||
*/
|
||||
var FocusManager = class extends require_subscribable.Subscribable {
|
||||
constructor() {
|
||||
super();
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _focused, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _cleanup, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _setup, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_setup, this, (onFocus) => {
|
||||
if (typeof window !== "undefined" && window.addEventListener) {
|
||||
const listener = () => onFocus();
|
||||
window.addEventListener("visibilitychange", listener, false);
|
||||
return () => {
|
||||
window.removeEventListener("visibilitychange", listener);
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
onSubscribe() {
|
||||
if (!require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) this.setEventListener(require_classPrivateFieldSet2._classPrivateFieldGet2(_setup, this));
|
||||
}
|
||||
onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _classPrivateFieldGet2$1;
|
||||
(_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet2$1 === void 0 || _classPrivateFieldGet2$1.call(this);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_cleanup, this, void 0);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* `setEventListener` can be used to set a custom event listener that will
|
||||
* be used to determine the focus state. The provided `setup` function
|
||||
* receives a `setFocused` callback: call it with a `boolean` to manually
|
||||
* set the focus state, or with no arguments to re-evaluate the current
|
||||
* focus state and notify subscribers.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { focusManager } from '@tanstack/query-core'
|
||||
*
|
||||
* focusManager.setEventListener((handleFocus) => {
|
||||
* const listener = () => handleFocus()
|
||||
* // Listen to visibilitychange
|
||||
* if (typeof window !== 'undefined' && window.addEventListener) {
|
||||
* window.addEventListener('visibilitychange', listener, false)
|
||||
* }
|
||||
*
|
||||
* return () => {
|
||||
* // Be sure to unsubscribe if a new handler is set
|
||||
* window.removeEventListener('visibilitychange', listener)
|
||||
* }
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
setEventListener(setup) {
|
||||
var _classPrivateFieldGet3;
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_setup, this, setup);
|
||||
(_classPrivateFieldGet3 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.call(this);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_cleanup, this, setup((focused) => {
|
||||
if (typeof focused === "boolean") this.setFocused(focused);
|
||||
else this.onFocus();
|
||||
}));
|
||||
}
|
||||
/**
|
||||
* `setFocused` can be used to manually set the focus state. Set `undefined`
|
||||
* to fall back to the default focus check.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { focusManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Set focused
|
||||
* focusManager.setFocused(true)
|
||||
*
|
||||
* // Set unfocused
|
||||
* focusManager.setFocused(false)
|
||||
*
|
||||
* // Fallback to the default focus check
|
||||
* focusManager.setFocused(undefined)
|
||||
* ```
|
||||
*/
|
||||
setFocused(focused) {
|
||||
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_focused, this) !== focused) {
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_focused, this, focused);
|
||||
this.onFocus();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* `onFocus` notifies all subscribed listeners with the current focus state.
|
||||
*/
|
||||
onFocus() {
|
||||
const isFocused = this.isFocused();
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(isFocused);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* `isFocused` can be used to get the current focus state.
|
||||
*/
|
||||
isFocused() {
|
||||
var _globalThis$document;
|
||||
if (typeof require_classPrivateFieldSet2._classPrivateFieldGet2(_focused, this) === "boolean") return require_classPrivateFieldSet2._classPrivateFieldGet2(_focused, this);
|
||||
return ((_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.visibilityState) !== "hidden";
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.
|
||||
*/
|
||||
const focusManager = new FocusManager();
|
||||
//#endregion
|
||||
exports.FocusManager = FocusManager;
|
||||
exports.focusManager = focusManager;
|
||||
|
||||
//# sourceMappingURL=focusManager.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"focusManager.cjs","names":["Subscribable"],"sources":["../../src/focusManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (focused: boolean) => void\n\ntype SetupFn = (\n setFocused: (focused?: boolean) => void,\n) => (() => void) | undefined\n\n/**\n * The `FocusManager` manages the focus state within TanStack Query.\n *\n * It can be used to change the default event listeners or to manually change the focus state.\n */\nexport class FocusManager extends Subscribable<Listener> {\n #focused?: boolean\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onFocus) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const listener = () => onFocus()\n // Listen to visibilitychange\n window.addEventListener('visibilitychange', listener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('visibilitychange', listener)\n }\n }\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n /**\n * `setEventListener` can be used to set a custom event listener that will\n * be used to determine the focus state. The provided `setup` function\n * receives a `setFocused` callback: call it with a `boolean` to manually\n * set the focus state, or with no arguments to re-evaluate the current\n * focus state and notify subscribers.\n *\n * @example\n * ```ts\n * import { focusManager } from '@tanstack/query-core'\n *\n * focusManager.setEventListener((handleFocus) => {\n * const listener = () => handleFocus()\n * // Listen to visibilitychange\n * if (typeof window !== 'undefined' && window.addEventListener) {\n * window.addEventListener('visibilitychange', listener, false)\n * }\n *\n * return () => {\n * // Be sure to unsubscribe if a new handler is set\n * window.removeEventListener('visibilitychange', listener)\n * }\n * })\n * ```\n */\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup((focused) => {\n if (typeof focused === 'boolean') {\n this.setFocused(focused)\n } else {\n this.onFocus()\n }\n })\n }\n\n /**\n * `setFocused` can be used to manually set the focus state. Set `undefined`\n * to fall back to the default focus check.\n *\n * @example\n * ```ts\n * import { focusManager } from '@tanstack/query-core'\n *\n * // Set focused\n * focusManager.setFocused(true)\n *\n * // Set unfocused\n * focusManager.setFocused(false)\n *\n * // Fallback to the default focus check\n * focusManager.setFocused(undefined)\n * ```\n */\n setFocused(focused?: boolean): void {\n const changed = this.#focused !== focused\n if (changed) {\n this.#focused = focused\n this.onFocus()\n }\n }\n\n /**\n * `onFocus` notifies all subscribed listeners with the current focus state.\n */\n onFocus(): void {\n const isFocused = this.isFocused()\n this.listeners.forEach((listener) => {\n listener(isFocused)\n })\n }\n\n /**\n * `isFocused` can be used to get the current focus state.\n */\n isFocused(): boolean {\n if (typeof this.#focused === 'boolean') {\n return this.#focused\n }\n\n // document global can be unavailable in react native\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return globalThis.document?.visibilityState !== 'hidden'\n }\n}\n\n/**\n * Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.\n */\nexport const focusManager = new FocusManager()\n"],"mappings":";;;;;;;;;;;;AAaA,IAAa,eAAb,cAAkCA,qBAAAA,aAAuB;CAMvD,cAAc;EACZ,MAAM;;;;EACN,8BAAA,uBAAA,QAAA,OAAe,YAAY;GAGzB,IAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;IAC5D,MAAM,iBAAiB,QAAQ;IAE/B,OAAO,iBAAiB,oBAAoB,UAAU,KAAK;IAE3D,aAAa;KAEX,OAAO,oBAAoB,oBAAoB,QAAQ;IACzD;GACF;EAEF,CAAA;CACF;CAEA,cAA8B;EAC5B,IAAI,CAAA,8BAAA,uBAAA,UAAC,IAAA,GACH,KAAK,iBAAA,8BAAA,uBAAA,QAAiB,IAAA,CAAW;CAErC;CAEA,gBAA0B;EACxB,IAAI,CAAC,KAAK,aAAa,GAAG;;GACxB,CAAA,2BAAA,8BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,6BAAA,KAAA,KAAA,yBAAA,KAAA,IAAgB;GAChB,8BAAA,uBAAA,UAAA,MAAgB,KAAA,CAAA;EAClB;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,iBAAiB,OAAsB;;EACrC,8BAAA,uBAAA,QAAA,MAAc,KAAA;EACd,CAAA,yBAAA,8BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,2BAAA,KAAA,KAAA,uBAAA,KAAA,IAAgB;EAChB,8BAAA,uBAAA,UAAA,MAAgB,OAAO,YAAY;GACjC,IAAI,OAAO,YAAY,WACrB,KAAK,WAAW,OAAO;QAEvB,KAAK,QAAQ;EAEjB,CAAC,CALine truncated
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import { t as Subscribable } from "./subscribable-CbifVTKz.cjs";
|
||||
//#region src/focusManager.d.ts
|
||||
type Listener = (focused: boolean) => void;
|
||||
type SetupFn = (setFocused: (focused?: boolean) => void) => (() => void) | undefined;
|
||||
/**
|
||||
* The `FocusManager` manages the focus state within TanStack Query.
|
||||
*
|
||||
* It can be used to change the default event listeners or to manually change the focus state.
|
||||
*/
|
||||
declare class FocusManager extends Subscribable<Listener> {
|
||||
#private;
|
||||
constructor();
|
||||
protected onSubscribe(): void;
|
||||
protected onUnsubscribe(): void;
|
||||
/**
|
||||
* `setEventListener` can be used to set a custom event listener that will
|
||||
* be used to determine the focus state. The provided `setup` function
|
||||
* receives a `setFocused` callback: call it with a `boolean` to manually
|
||||
* set the focus state, or with no arguments to re-evaluate the current
|
||||
* focus state and notify subscribers.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { focusManager } from '@tanstack/query-core'
|
||||
*
|
||||
* focusManager.setEventListener((handleFocus) => {
|
||||
* const listener = () => handleFocus()
|
||||
* // Listen to visibilitychange
|
||||
* if (typeof window !== 'undefined' && window.addEventListener) {
|
||||
* window.addEventListener('visibilitychange', listener, false)
|
||||
* }
|
||||
*
|
||||
* return () => {
|
||||
* // Be sure to unsubscribe if a new handler is set
|
||||
* window.removeEventListener('visibilitychange', listener)
|
||||
* }
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
setEventListener(setup: SetupFn): void;
|
||||
/**
|
||||
* `setFocused` can be used to manually set the focus state. Set `undefined`
|
||||
* to fall back to the default focus check.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { focusManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Set focused
|
||||
* focusManager.setFocused(true)
|
||||
*
|
||||
* // Set unfocused
|
||||
* focusManager.setFocused(false)
|
||||
*
|
||||
* // Fallback to the default focus check
|
||||
* focusManager.setFocused(undefined)
|
||||
* ```
|
||||
*/
|
||||
setFocused(focused?: boolean): void;
|
||||
/**
|
||||
* `onFocus` notifies all subscribed listeners with the current focus state.
|
||||
*/
|
||||
onFocus(): void;
|
||||
/**
|
||||
* `isFocused` can be used to get the current focus state.
|
||||
*/
|
||||
isFocused(): boolean;
|
||||
}
|
||||
/**
|
||||
* Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.
|
||||
*/
|
||||
declare const focusManager: FocusManager;
|
||||
//#endregion
|
||||
export { FocusManager, focusManager };
|
||||
//# sourceMappingURL=focusManager.d.cts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"focusManager.d.cts","names":[],"sources":["../../src/focusManager.ts"],"mappings":";;KAEK,YAAY;KAEZ,WACH,aAAa;;;;;;cAQF,qBAAqB,aAAa;;;YAyBnC;YAMA;;;;;;;;;;;;;;;;;;;;;;;;;;EAgCV,iBAAiB,OAAO;;;;;;;;;;;;;;;;;;;EA8BxB,WAAW;;;;EAWX;;;;EAUA;;;;;cAcW,cAAY"}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import { t as Subscribable } from "./subscribable-CbifVTKz.js";
|
||||
//#region src/focusManager.d.ts
|
||||
type Listener = (focused: boolean) => void;
|
||||
type SetupFn = (setFocused: (focused?: boolean) => void) => (() => void) | undefined;
|
||||
/**
|
||||
* The `FocusManager` manages the focus state within TanStack Query.
|
||||
*
|
||||
* It can be used to change the default event listeners or to manually change the focus state.
|
||||
*/
|
||||
declare class FocusManager extends Subscribable<Listener> {
|
||||
#private;
|
||||
constructor();
|
||||
protected onSubscribe(): void;
|
||||
protected onUnsubscribe(): void;
|
||||
/**
|
||||
* `setEventListener` can be used to set a custom event listener that will
|
||||
* be used to determine the focus state. The provided `setup` function
|
||||
* receives a `setFocused` callback: call it with a `boolean` to manually
|
||||
* set the focus state, or with no arguments to re-evaluate the current
|
||||
* focus state and notify subscribers.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { focusManager } from '@tanstack/query-core'
|
||||
*
|
||||
* focusManager.setEventListener((handleFocus) => {
|
||||
* const listener = () => handleFocus()
|
||||
* // Listen to visibilitychange
|
||||
* if (typeof window !== 'undefined' && window.addEventListener) {
|
||||
* window.addEventListener('visibilitychange', listener, false)
|
||||
* }
|
||||
*
|
||||
* return () => {
|
||||
* // Be sure to unsubscribe if a new handler is set
|
||||
* window.removeEventListener('visibilitychange', listener)
|
||||
* }
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
setEventListener(setup: SetupFn): void;
|
||||
/**
|
||||
* `setFocused` can be used to manually set the focus state. Set `undefined`
|
||||
* to fall back to the default focus check.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { focusManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Set focused
|
||||
* focusManager.setFocused(true)
|
||||
*
|
||||
* // Set unfocused
|
||||
* focusManager.setFocused(false)
|
||||
*
|
||||
* // Fallback to the default focus check
|
||||
* focusManager.setFocused(undefined)
|
||||
* ```
|
||||
*/
|
||||
setFocused(focused?: boolean): void;
|
||||
/**
|
||||
* `onFocus` notifies all subscribed listeners with the current focus state.
|
||||
*/
|
||||
onFocus(): void;
|
||||
/**
|
||||
* `isFocused` can be used to get the current focus state.
|
||||
*/
|
||||
isFocused(): boolean;
|
||||
}
|
||||
/**
|
||||
* Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.
|
||||
*/
|
||||
declare const focusManager: FocusManager;
|
||||
//#endregion
|
||||
export { FocusManager, focusManager };
|
||||
//# sourceMappingURL=focusManager.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"focusManager.d.ts","names":[],"sources":["../../src/focusManager.ts"],"mappings":";;KAEK,YAAY;KAEZ,WACH,aAAa;;;;;;cAQF,qBAAqB,aAAa;;;YAyBnC;YAMA;;;;;;;;;;;;;;;;;;;;;;;;;;EAgCV,iBAAiB,OAAO;;;;;;;;;;;;;;;;;;;EA8BxB,WAAW;;;;EAWX;;;;EAUA;;;;;cAcW,cAAY"}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
|
||||
import { Subscribable } from "./subscribable.js";
|
||||
//#region src/focusManager.ts
|
||||
var _focused = /* @__PURE__ */ new WeakMap();
|
||||
var _cleanup = /* @__PURE__ */ new WeakMap();
|
||||
var _setup = /* @__PURE__ */ new WeakMap();
|
||||
/**
|
||||
* The `FocusManager` manages the focus state within TanStack Query.
|
||||
*
|
||||
* It can be used to change the default event listeners or to manually change the focus state.
|
||||
*/
|
||||
var FocusManager = class extends Subscribable {
|
||||
constructor() {
|
||||
super();
|
||||
_classPrivateFieldInitSpec(this, _focused, void 0);
|
||||
_classPrivateFieldInitSpec(this, _cleanup, void 0);
|
||||
_classPrivateFieldInitSpec(this, _setup, void 0);
|
||||
_classPrivateFieldSet2(_setup, this, (onFocus) => {
|
||||
if (typeof window !== "undefined" && window.addEventListener) {
|
||||
const listener = () => onFocus();
|
||||
window.addEventListener("visibilitychange", listener, false);
|
||||
return () => {
|
||||
window.removeEventListener("visibilitychange", listener);
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
onSubscribe() {
|
||||
if (!_classPrivateFieldGet2(_cleanup, this)) this.setEventListener(_classPrivateFieldGet2(_setup, this));
|
||||
}
|
||||
onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _classPrivateFieldGet2$1;
|
||||
(_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet2$1 === void 0 || _classPrivateFieldGet2$1.call(this);
|
||||
_classPrivateFieldSet2(_cleanup, this, void 0);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* `setEventListener` can be used to set a custom event listener that will
|
||||
* be used to determine the focus state. The provided `setup` function
|
||||
* receives a `setFocused` callback: call it with a `boolean` to manually
|
||||
* set the focus state, or with no arguments to re-evaluate the current
|
||||
* focus state and notify subscribers.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { focusManager } from '@tanstack/query-core'
|
||||
*
|
||||
* focusManager.setEventListener((handleFocus) => {
|
||||
* const listener = () => handleFocus()
|
||||
* // Listen to visibilitychange
|
||||
* if (typeof window !== 'undefined' && window.addEventListener) {
|
||||
* window.addEventListener('visibilitychange', listener, false)
|
||||
* }
|
||||
*
|
||||
* return () => {
|
||||
* // Be sure to unsubscribe if a new handler is set
|
||||
* window.removeEventListener('visibilitychange', listener)
|
||||
* }
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
setEventListener(setup) {
|
||||
var _classPrivateFieldGet3;
|
||||
_classPrivateFieldSet2(_setup, this, setup);
|
||||
(_classPrivateFieldGet3 = _classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.call(this);
|
||||
_classPrivateFieldSet2(_cleanup, this, setup((focused) => {
|
||||
if (typeof focused === "boolean") this.setFocused(focused);
|
||||
else this.onFocus();
|
||||
}));
|
||||
}
|
||||
/**
|
||||
* `setFocused` can be used to manually set the focus state. Set `undefined`
|
||||
* to fall back to the default focus check.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { focusManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Set focused
|
||||
* focusManager.setFocused(true)
|
||||
*
|
||||
* // Set unfocused
|
||||
* focusManager.setFocused(false)
|
||||
*
|
||||
* // Fallback to the default focus check
|
||||
* focusManager.setFocused(undefined)
|
||||
* ```
|
||||
*/
|
||||
setFocused(focused) {
|
||||
if (_classPrivateFieldGet2(_focused, this) !== focused) {
|
||||
_classPrivateFieldSet2(_focused, this, focused);
|
||||
this.onFocus();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* `onFocus` notifies all subscribed listeners with the current focus state.
|
||||
*/
|
||||
onFocus() {
|
||||
const isFocused = this.isFocused();
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(isFocused);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* `isFocused` can be used to get the current focus state.
|
||||
*/
|
||||
isFocused() {
|
||||
var _globalThis$document;
|
||||
if (typeof _classPrivateFieldGet2(_focused, this) === "boolean") return _classPrivateFieldGet2(_focused, this);
|
||||
return ((_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.visibilityState) !== "hidden";
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.
|
||||
*/
|
||||
const focusManager = new FocusManager();
|
||||
//#endregion
|
||||
export { FocusManager, focusManager };
|
||||
|
||||
//# sourceMappingURL=focusManager.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"focusManager.js","names":[],"sources":["../../src/focusManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (focused: boolean) => void\n\ntype SetupFn = (\n setFocused: (focused?: boolean) => void,\n) => (() => void) | undefined\n\n/**\n * The `FocusManager` manages the focus state within TanStack Query.\n *\n * It can be used to change the default event listeners or to manually change the focus state.\n */\nexport class FocusManager extends Subscribable<Listener> {\n #focused?: boolean\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onFocus) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const listener = () => onFocus()\n // Listen to visibilitychange\n window.addEventListener('visibilitychange', listener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('visibilitychange', listener)\n }\n }\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n /**\n * `setEventListener` can be used to set a custom event listener that will\n * be used to determine the focus state. The provided `setup` function\n * receives a `setFocused` callback: call it with a `boolean` to manually\n * set the focus state, or with no arguments to re-evaluate the current\n * focus state and notify subscribers.\n *\n * @example\n * ```ts\n * import { focusManager } from '@tanstack/query-core'\n *\n * focusManager.setEventListener((handleFocus) => {\n * const listener = () => handleFocus()\n * // Listen to visibilitychange\n * if (typeof window !== 'undefined' && window.addEventListener) {\n * window.addEventListener('visibilitychange', listener, false)\n * }\n *\n * return () => {\n * // Be sure to unsubscribe if a new handler is set\n * window.removeEventListener('visibilitychange', listener)\n * }\n * })\n * ```\n */\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup((focused) => {\n if (typeof focused === 'boolean') {\n this.setFocused(focused)\n } else {\n this.onFocus()\n }\n })\n }\n\n /**\n * `setFocused` can be used to manually set the focus state. Set `undefined`\n * to fall back to the default focus check.\n *\n * @example\n * ```ts\n * import { focusManager } from '@tanstack/query-core'\n *\n * // Set focused\n * focusManager.setFocused(true)\n *\n * // Set unfocused\n * focusManager.setFocused(false)\n *\n * // Fallback to the default focus check\n * focusManager.setFocused(undefined)\n * ```\n */\n setFocused(focused?: boolean): void {\n const changed = this.#focused !== focused\n if (changed) {\n this.#focused = focused\n this.onFocus()\n }\n }\n\n /**\n * `onFocus` notifies all subscribed listeners with the current focus state.\n */\n onFocus(): void {\n const isFocused = this.isFocused()\n this.listeners.forEach((listener) => {\n listener(isFocused)\n })\n }\n\n /**\n * `isFocused` can be used to get the current focus state.\n */\n isFocused(): boolean {\n if (typeof this.#focused === 'boolean') {\n return this.#focused\n }\n\n // document global can be unavailable in react native\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return globalThis.document?.visibilityState !== 'hidden'\n }\n}\n\n/**\n * Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.\n */\nexport const focusManager = new FocusManager()\n"],"mappings":";;;;;;;;;;;AAaA,IAAa,eAAb,cAAkC,aAAuB;CAMvD,cAAc;EACZ,MAAM;;;;EACN,uBAAA,QAAA,OAAe,YAAY;GAGzB,IAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;IAC5D,MAAM,iBAAiB,QAAQ;IAE/B,OAAO,iBAAiB,oBAAoB,UAAU,KAAK;IAE3D,aAAa;KAEX,OAAO,oBAAoB,oBAAoB,QAAQ;IACzD;GACF;EAEF,CAAA;CACF;CAEA,cAA8B;EAC5B,IAAI,CAAA,uBAAA,UAAC,IAAA,GACH,KAAK,iBAAA,uBAAA,QAAiB,IAAA,CAAW;CAErC;CAEA,gBAA0B;EACxB,IAAI,CAAC,KAAK,aAAa,GAAG;;GACxB,CAAA,2BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,6BAAA,KAAA,KAAA,yBAAA,KAAA,IAAgB;GAChB,uBAAA,UAAA,MAAgB,KAAA,CAAA;EAClB;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,iBAAiB,OAAsB;;EACrC,uBAAA,QAAA,MAAc,KAAA;EACd,CAAA,yBAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,2BAAA,KAAA,KAAA,uBAAA,KAAA,IAAgB;EAChB,uBAAA,UAAA,MAAgB,OAAO,YAAY;GACjC,IAAI,OAAO,YAAY,WACrB,KAAK,WAAW,OAAO;QAEvB,KAAK,QAAQ;EAEjB,CAAC,CAAA;CACH;;;;;;;;;;;;;;;;;;;CAoBA,WAAW,SAAyB;EAElC,IAAA,uBAAA,UADgB,IAAA,MLine truncated
|
||||
+2790
File diff suppressed because it is too large.
Load diff
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"hydration-Cq7QYAzB.d.ts","names":[],"sources":["../../src/queryObserver.ts","../../src/query.ts","../../src/mutationObserver.ts","../../src/mutationCache.ts","../../src/mutation.ts","../../src/utils.ts","../../src/queryCache.ts","../../src/queryClient.ts","../../src/retryer.ts","../../src/types.ts","../../src/hydration.ts"],"mappings":";;;KA4BK,sBAAsB,OAAO,WAChC,QAAQ,oBAAoB,OAAO;UAG3B,6BAA6B;EACrC;;;;;;;;;;;;;;;;;;;;;;cAuBW,cACX,wBACA,SAAS,cACT,QAAQ,cACR,aAAa,cACb,kBAAkB,WAAW,kBACrB,aAAa,sBAAsB,OAAO;;EA0BzC,SAAS,qBACd,cACA,QACA,OACA,YACA;EANF,YAAA,QAAQ,aACD,SAAS,qBACd,cACA,QACA,OACA,YACA;YAYM;YAIA;YAcA;;;;;;EAWV;;;;;;EAaA;;;;;;EAaA;;;;;;;;;;;;;;;EAqBA,WACE,SAAS,qBACP,cACA,QACA,OACA,YACA;;;;;;;EAoFJ,oBACE,SAAS,8BACP,cACA,QACA,OACA,YACA,aAED,oBAAoB,OAAO;;;;;;;;;;;;;EAyC9B,oBAAoB,oBAAoB,OAAO;;;;;;;EAU/C,YACE,QAAQ,oBAAoB,OAAO,SACnC,iBAAiB,WAAW,+BAC3B,oBAAoB,OAAO;;;;;;;EAgB9B,UAAU,WAAW;;;;EAOrB,mBAAmB,MAAM,cAAc,QAAQ,YAAY;;;;;;;;;;;EAc3D,aAAa,YAAW,iBAAsB,QAC5C,oBAAoB,OAAO;;;;;;;;;;;;;;;;;EAuB7B,gBACE,SAAS,qBACP,cACA,QACA,OACA,YACA,aAED,QAAQ,oBAAoB,OAAO;YA6C5B,MACR,cAAc,uBACb,QAAQ,oBAAoB,OAAO;YA6G5B,aACR,OAAO,MAAM,cAAc,QAAQ,YAAY,YAC/C,SAAS,qBACP,cACA,QACA,OACA,YACA,aAED,oBAAoB,OAAO;;;;;;EAuK9B;;EA6FA;;;;UC1xBQ,YACR,cACA,QACA,OACA,kBAAkB,WAAW;EAE7B,QAAQ;EACR,UAAU;EACV;EACA,UAAU,aAAa,cAAc,QAAQ,OAAO;EACpD,iBAAiB,aAAa,cAAc,QAAQ,OAAO;EAC3D,QAAQ,WAAW,OAAO;;;;;;UAOX,WAAW,iBAAiB,SAAS;;;;EAIpD,MAAM;;;;EAIN;;;;EAIA;;;;;EAKA,OAAO;;;;EAIP;;;;EAIA;;;;;;EAMA;;;;;EAKA,oBAAoB;;;;;EAKpB,WAAW;;;;;EAKX;;;;;;;EAOA,QAAQ;;;;;;;EAOR,aAAa;;UAGE,aACf,cACA,QACA,OACA,kBAAkB,WAAW;EAE7B,yBAAyB;EACzB,eAAe;EACf,QAAQ;EACR,SAAS,aAAa,cAAc,QAAQ;EAC5C,QAAQ;EACR,UAAU;EACV,OAAO,WAAW,OAAO;;UAGV,cACf,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW;EAE7B,UACE,SAAS,aAAa,cAAc,QAAQ,OAAO,YACnD,OAAO;;KAIC;UAEK;EACf;IAAc,WAAW;;;UAGV,aAAa;EAC5B;EACA,OAAO;EACP,iBAAiB,QAAQ;;UAGjB,eAAa;EACrB;EACA;EACA,OAAO;;UAGC;EACR;EACA,OAAO;;UAGC,gBAAc;EACtB,MAAM;EACN;EACA;EACA;;UAGQ,cAAY;EACpB;EACA,OAAO;;UAGC;EACR;;UAGQ;EACR;;UAGQ;EACR;;UAGQ,eAAe,OAAO;EAC9B;EACA,OAAO,QAAQ,WAAW,OAAO;;KAGvB,SAAO,OAAO,UACtB,mBACA,cAAY,UACZ,eAAa,UACb,cACA,mBACA,gBACA,eAAe,OAAO,UACtB,gBAAc;;;;;;;;;;;;;;;;;;;;cAuBL,MACX,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,kBACrB;;EACR,UAAU;EACV;EACA,SAAU,aAAa,cAAc,QAAQ,OAAO;EACpD,OAAO,WAAW,OAAO;EAQzB,WAAW,MAAM;EAIL,YAAA,QAAQ,YAAY,cAAc,QAAQ,OAAO;;;;MAkBzD,QAAQ;;MAKR;;;;;MAQA,WAAW,QAAQ;;EAKvB,WACE,UAAU,aAAa,cAAc,QAAQ,OAAO;YAsB5C;;EAOV,QACE,SAAS,OACT,UAAU;IAAmB;MAC5B;;;;;;EAmBH,SAAS,OAAO,QAAQ,WAAW,OAAO;;;;;;;;;;;EAc1C,OAAO,UAAU,gBAAgB;;;;;;;;EAajC;;MAOI,cAAc,WAAW,OAAO;;;;;;EASpC;;;;;EASA;;;;;;;;;EAcA;;;;;EAYA;;;;;EAQA;;;;;;;;;;;;;;;;;EA2BA;;;;;;;;;;;;;;;EA0BA,cAAc,YAAW;;EAkBzB;;EAUA;;EAUA,YAAY,UAAU;;EAYtB,eAAe,UAAU;;;;;;;;;;;EAqCzB;;;;;;;;;;;EAcA;;;;;;;;;;;EAgBM,MACJ,UAAU,aAAa,cAAc,QAAQ,OAAO,YACpD,eAAe,aAAa,gBAC3B,QAAQ;;iBA0TG,WACd,cACA,QACA,OACA,kBAAkB,UAElB,MAAM,mBACN,SAAS,aAAa,cAAc,QAAQ,OAAO;;;;;;;;;KCj4BhD,yBAAyB,OAAO,QAAQ,YAAY,oBACvD,QAAQ,uBAAuB,OAAO,QAAQ,YAAY;;;;;;;;;;;;;;;;cAoB/C,iBACX,iBACA,SAAS,cACT,mBACA,mCACQ,aACR,yBAAyB,OAAO,QAAQ,YAAY;;EAEpD,SAAU,wBAAwB,OAAO,QAAQ,YAAY;EAa3D,YAAA,QAAQ,aACR,SAAS,wBACP,OACA,QACA,YACA;YAWM;;;;;;;;;;;;;;;;;EAqBV,WACE,SAAS,wBACP,OACA,QACA,YACA;YA0BM;YAQA;;EAOV,iBACE,QAAQ,OAAO,OAAO,QAAQ,YAAY;;;;;;EAY5C,oBAAoB,uBAClB,OACA,QACA,YACA;;;;;;;;;;;;;;;;;EAqBF;;;;;;;;;;;;;;;;;;;EA2BA,OACE,WAAW,YACX,UAAU,cAAc,OAAO,QAAQ,YAAY,mBAClD,QAAQ;;;;;;;;;;;;UCxLI;;EAEf,WACE,OAAO,cACP,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,aACE,eACA,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,YACE,oBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,aACE,2BACA,OAAO,qBACP,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;UAGG,iCAAiC;EACzC;EACA,UAAU;;UAEF,mCAAmC;EAC3C;EACA,UAAU;;UAGF,yCAAyC;EACjD;EACA,UAAU;EACV,UAAU;;UAGF,2CAA2C;EACnD;EACA,UAAU;EACV,UAAU;;UAGF,kDAAkD;EAC1D;EACA,WAAW;EACX,UAAU;;UAGF,mCAAmC;EAC3C;EACA,UAAU;EACV,QAAQ;;;;;;;KAQE,2BACR,2BACA,6BACA,mCACA,qCACA,4CACA;KAEC,yBAAyB,OAAO;;;;;;;;;;;;;;;cAkBxB,sBAAsB,aAAa;;EAK3B,QAAQ;EAAR,YAAA,SAAQ;;EAQ3B,MAAM,OAAO,QAAQ,YAAY,iBAC/B,QAAQ,aACR,SAAS,gBAAgB,OAAO,QAAQ,YAAY,kBACpD,QAAQ,cAAc,OAAO,QAAQ,YAAY,mBAChD,SAAS,OAAO,QAAQ,YAAY;;EAevC,IAAI,UAAU;;EAed,OAAO,UAAU;;EAwBjB,OAAO,UAAU;;EAkBjB,QAAQ,UAAU,+BAA+B;;;;;;;;;;;EAuBjD;;;;;;;;;;;;;;EAuBA,UAAU,MAAM;;;;;;;;;;;;;;;;EAmBhB,KACE,iBACA,SAAS,cACT,kBACA,2BAEA,SAAS,kBACR,SAAS,OAAO,QAAQ,YAAY;;;;;;;;;;;;;;;;EAuBvC,QAAQ,UAAS,kBAAuB,MAAM;;EAK9C,OAAO,OAAO;;EASd,yBAAyB;;;;UChTjB,eAAe,OAAO,QAAQ,YAAY;EAClD,QAAQ;EACR;EACA,eAAe;EACf,SAAS,gBAAgB,OAAO,QAAQ,YAAY;EACpD,QAAQ,cAAc,OAAO,QAAQ,YAAY;;;;;;UAOlC,cACf,iBACA,SAAS,cACT,sBACA;;;;;EAMA,SAAS;;;;EAIT,MAAM;;;;;EAKN,OAAO;;;;EAIP;;;;EAIA,eAAe;;;;;EAKf;;;;EAIA,QAAQ;;;;EAIR,WAAW;;;;EAIX;;UAGQ,aAAa;EACrB;EACA;EACA,OAAO;;UAGC,cAAc,YAAY;EAClC;EACA;EACA,YAAY;EACZ,UAAU;;UAGF,cAAc;EACtB;EACA,MAAM;;UAGE,YAAY;EACpB;EACA,OAAO;;UAGC;EACR;;UAGQ;EACR;;KAGU,OAAO,OAAO,QAAQ,YAAY,mBAC1C,iBACA,YAAY,UACZ,aAAa,UACb,cAAc,YAAY,mBAC1B,cACA,cAAc;;;;;;;;;;;;;;;;;;cAqBL,SACX,iBACA,SAAS,cACT,sBACA,mCACQ;;EACR,OAAO,cAAc,OAAO,QAAQ,YAAY;EAChD,SAAU,gBAAgB,OAAO,QAAQ,YAAY;WAC5C;EAUP,YAAA,QAAQ,eAAeLine truncated
|
||||
+2790
File diff suppressed because it is too large.
Load diff
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"hydration-DwR10Hi-.d.cts","names":[],"sources":["../../src/queryObserver.ts","../../src/query.ts","../../src/mutationObserver.ts","../../src/mutationCache.ts","../../src/mutation.ts","../../src/utils.ts","../../src/queryCache.ts","../../src/queryClient.ts","../../src/retryer.ts","../../src/types.ts","../../src/hydration.ts"],"mappings":";;;KA4BK,sBAAsB,OAAO,WAChC,QAAQ,oBAAoB,OAAO;UAG3B,6BAA6B;EACrC;;;;;;;;;;;;;;;;;;;;;;cAuBW,cACX,wBACA,SAAS,cACT,QAAQ,cACR,aAAa,cACb,kBAAkB,WAAW,kBACrB,aAAa,sBAAsB,OAAO;;EA0BzC,SAAS,qBACd,cACA,QACA,OACA,YACA;EANF,YAAA,QAAQ,aACD,SAAS,qBACd,cACA,QACA,OACA,YACA;YAYM;YAIA;YAcA;;;;;;EAWV;;;;;;EAaA;;;;;;EAaA;;;;;;;;;;;;;;;EAqBA,WACE,SAAS,qBACP,cACA,QACA,OACA,YACA;;;;;;;EAoFJ,oBACE,SAAS,8BACP,cACA,QACA,OACA,YACA,aAED,oBAAoB,OAAO;;;;;;;;;;;;;EAyC9B,oBAAoB,oBAAoB,OAAO;;;;;;;EAU/C,YACE,QAAQ,oBAAoB,OAAO,SACnC,iBAAiB,WAAW,+BAC3B,oBAAoB,OAAO;;;;;;;EAgB9B,UAAU,WAAW;;;;EAOrB,mBAAmB,MAAM,cAAc,QAAQ,YAAY;;;;;;;;;;;EAc3D,aAAa,YAAW,iBAAsB,QAC5C,oBAAoB,OAAO;;;;;;;;;;;;;;;;;EAuB7B,gBACE,SAAS,qBACP,cACA,QACA,OACA,YACA,aAED,QAAQ,oBAAoB,OAAO;YA6C5B,MACR,cAAc,uBACb,QAAQ,oBAAoB,OAAO;YA6G5B,aACR,OAAO,MAAM,cAAc,QAAQ,YAAY,YAC/C,SAAS,qBACP,cACA,QACA,OACA,YACA,aAED,oBAAoB,OAAO;;;;;;EAuK9B;;EA6FA;;;;UC1xBQ,YACR,cACA,QACA,OACA,kBAAkB,WAAW;EAE7B,QAAQ;EACR,UAAU;EACV;EACA,UAAU,aAAa,cAAc,QAAQ,OAAO;EACpD,iBAAiB,aAAa,cAAc,QAAQ,OAAO;EAC3D,QAAQ,WAAW,OAAO;;;;;;UAOX,WAAW,iBAAiB,SAAS;;;;EAIpD,MAAM;;;;EAIN;;;;EAIA;;;;;EAKA,OAAO;;;;EAIP;;;;EAIA;;;;;;EAMA;;;;;EAKA,oBAAoB;;;;;EAKpB,WAAW;;;;;EAKX;;;;;;;EAOA,QAAQ;;;;;;;EAOR,aAAa;;UAGE,aACf,cACA,QACA,OACA,kBAAkB,WAAW;EAE7B,yBAAyB;EACzB,eAAe;EACf,QAAQ;EACR,SAAS,aAAa,cAAc,QAAQ;EAC5C,QAAQ;EACR,UAAU;EACV,OAAO,WAAW,OAAO;;UAGV,cACf,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW;EAE7B,UACE,SAAS,aAAa,cAAc,QAAQ,OAAO,YACnD,OAAO;;KAIC;UAEK;EACf;IAAc,WAAW;;;UAGV,aAAa;EAC5B;EACA,OAAO;EACP,iBAAiB,QAAQ;;UAGjB,eAAa;EACrB;EACA;EACA,OAAO;;UAGC;EACR;EACA,OAAO;;UAGC,gBAAc;EACtB,MAAM;EACN;EACA;EACA;;UAGQ,cAAY;EACpB;EACA,OAAO;;UAGC;EACR;;UAGQ;EACR;;UAGQ;EACR;;UAGQ,eAAe,OAAO;EAC9B;EACA,OAAO,QAAQ,WAAW,OAAO;;KAGvB,SAAO,OAAO,UACtB,mBACA,cAAY,UACZ,eAAa,UACb,cACA,mBACA,gBACA,eAAe,OAAO,UACtB,gBAAc;;;;;;;;;;;;;;;;;;;;cAuBL,MACX,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,kBACrB;;EACR,UAAU;EACV;EACA,SAAU,aAAa,cAAc,QAAQ,OAAO;EACpD,OAAO,WAAW,OAAO;EAQzB,WAAW,MAAM;EAIL,YAAA,QAAQ,YAAY,cAAc,QAAQ,OAAO;;;;MAkBzD,QAAQ;;MAKR;;;;;MAQA,WAAW,QAAQ;;EAKvB,WACE,UAAU,aAAa,cAAc,QAAQ,OAAO;YAsB5C;;EAOV,QACE,SAAS,OACT,UAAU;IAAmB;MAC5B;;;;;;EAmBH,SAAS,OAAO,QAAQ,WAAW,OAAO;;;;;;;;;;;EAc1C,OAAO,UAAU,gBAAgB;;;;;;;;EAajC;;MAOI,cAAc,WAAW,OAAO;;;;;;EASpC;;;;;EASA;;;;;;;;;EAcA;;;;;EAYA;;;;;EAQA;;;;;;;;;;;;;;;;;EA2BA;;;;;;;;;;;;;;;EA0BA,cAAc,YAAW;;EAkBzB;;EAUA;;EAUA,YAAY,UAAU;;EAYtB,eAAe,UAAU;;;;;;;;;;;EAqCzB;;;;;;;;;;;EAcA;;;;;;;;;;;EAgBM,MACJ,UAAU,aAAa,cAAc,QAAQ,OAAO,YACpD,eAAe,aAAa,gBAC3B,QAAQ;;iBA0TG,WACd,cACA,QACA,OACA,kBAAkB,UAElB,MAAM,mBACN,SAAS,aAAa,cAAc,QAAQ,OAAO;;;;;;;;;KCj4BhD,yBAAyB,OAAO,QAAQ,YAAY,oBACvD,QAAQ,uBAAuB,OAAO,QAAQ,YAAY;;;;;;;;;;;;;;;;cAoB/C,iBACX,iBACA,SAAS,cACT,mBACA,mCACQ,aACR,yBAAyB,OAAO,QAAQ,YAAY;;EAEpD,SAAU,wBAAwB,OAAO,QAAQ,YAAY;EAa3D,YAAA,QAAQ,aACR,SAAS,wBACP,OACA,QACA,YACA;YAWM;;;;;;;;;;;;;;;;;EAqBV,WACE,SAAS,wBACP,OACA,QACA,YACA;YA0BM;YAQA;;EAOV,iBACE,QAAQ,OAAO,OAAO,QAAQ,YAAY;;;;;;EAY5C,oBAAoB,uBAClB,OACA,QACA,YACA;;;;;;;;;;;;;;;;;EAqBF;;;;;;;;;;;;;;;;;;;EA2BA,OACE,WAAW,YACX,UAAU,cAAc,OAAO,QAAQ,YAAY,mBAClD,QAAQ;;;;;;;;;;;;UCxLI;;EAEf,WACE,OAAO,cACP,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,aACE,eACA,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,YACE,oBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,aACE,2BACA,OAAO,qBACP,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;UAGG,iCAAiC;EACzC;EACA,UAAU;;UAEF,mCAAmC;EAC3C;EACA,UAAU;;UAGF,yCAAyC;EACjD;EACA,UAAU;EACV,UAAU;;UAGF,2CAA2C;EACnD;EACA,UAAU;EACV,UAAU;;UAGF,kDAAkD;EAC1D;EACA,WAAW;EACX,UAAU;;UAGF,mCAAmC;EAC3C;EACA,UAAU;EACV,QAAQ;;;;;;;KAQE,2BACR,2BACA,6BACA,mCACA,qCACA,4CACA;KAEC,yBAAyB,OAAO;;;;;;;;;;;;;;;cAkBxB,sBAAsB,aAAa;;EAK3B,QAAQ;EAAR,YAAA,SAAQ;;EAQ3B,MAAM,OAAO,QAAQ,YAAY,iBAC/B,QAAQ,aACR,SAAS,gBAAgB,OAAO,QAAQ,YAAY,kBACpD,QAAQ,cAAc,OAAO,QAAQ,YAAY,mBAChD,SAAS,OAAO,QAAQ,YAAY;;EAevC,IAAI,UAAU;;EAed,OAAO,UAAU;;EAwBjB,OAAO,UAAU;;EAkBjB,QAAQ,UAAU,+BAA+B;;;;;;;;;;;EAuBjD;;;;;;;;;;;;;;EAuBA,UAAU,MAAM;;;;;;;;;;;;;;;;EAmBhB,KACE,iBACA,SAAS,cACT,kBACA,2BAEA,SAAS,kBACR,SAAS,OAAO,QAAQ,YAAY;;;;;;;;;;;;;;;;EAuBvC,QAAQ,UAAS,kBAAuB,MAAM;;EAK9C,OAAO,OAAO;;EASd,yBAAyB;;;;UChTjB,eAAe,OAAO,QAAQ,YAAY;EAClD,QAAQ;EACR;EACA,eAAe;EACf,SAAS,gBAAgB,OAAO,QAAQ,YAAY;EACpD,QAAQ,cAAc,OAAO,QAAQ,YAAY;;;;;;UAOlC,cACf,iBACA,SAAS,cACT,sBACA;;;;;EAMA,SAAS;;;;EAIT,MAAM;;;;;EAKN,OAAO;;;;EAIP;;;;EAIA,eAAe;;;;;EAKf;;;;EAIA,QAAQ;;;;EAIR,WAAW;;;;EAIX;;UAGQ,aAAa;EACrB;EACA;EACA,OAAO;;UAGC,cAAc,YAAY;EAClC;EACA;EACA,YAAY;EACZ,UAAU;;UAGF,cAAc;EACtB;EACA,MAAM;;UAGE,YAAY;EACpB;EACA,OAAO;;UAGC;EACR;;UAGQ;EACR;;KAGU,OAAO,OAAO,QAAQ,YAAY,mBAC1C,iBACA,YAAY,UACZ,aAAa,UACb,cAAc,YAAY,mBAC1B,cACA,cAAc;;;;;;;;;;;;;;;;;;cAqBL,SACX,iBACA,SAAS,cACT,sBACA,mCACQ;;EACR,OAAO,cAAc,OAAO,QAAQ,YAAY;EAChD,SAAU,gBAAgB,OAAO,QAAQ,YAAY;WAC5C;EAUP,YAAA,QAAQ,eAALine truncated
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_utils = require("./utils.cjs");
|
||||
//#region src/hydration.ts
|
||||
function tryResolveSync(promise) {
|
||||
var _thenResult$catch;
|
||||
let data;
|
||||
const thenResult = promise.then((result) => {
|
||||
data = result;
|
||||
return result;
|
||||
}, require_utils.noop);
|
||||
thenResult === null || thenResult === void 0 || (_thenResult$catch = thenResult.catch) === null || _thenResult$catch === void 0 || _thenResult$catch.call(thenResult, require_utils.noop);
|
||||
if (data !== void 0) return { data };
|
||||
}
|
||||
function dehydrateMutation(mutation) {
|
||||
return {
|
||||
mutationKey: mutation.options.mutationKey,
|
||||
state: mutation.state,
|
||||
...mutation.options.scope && { scope: mutation.options.scope },
|
||||
...mutation.meta && { meta: mutation.meta }
|
||||
};
|
||||
}
|
||||
function dehydratePromise(query, serializeData, shouldRedactErrors) {
|
||||
var _query$promise;
|
||||
const promise = (_query$promise = query.promise) === null || _query$promise === void 0 ? void 0 : _query$promise.then(serializeData).catch((error) => {
|
||||
if ((shouldRedactErrors === null || shouldRedactErrors === void 0 ? void 0 : shouldRedactErrors(error)) === false) return Promise.reject(error);
|
||||
if (process.env.NODE_ENV !== "production") console.error(`A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`);
|
||||
return Promise.reject(/* @__PURE__ */ new Error("redacted"));
|
||||
});
|
||||
promise === null || promise === void 0 || promise.catch(require_utils.noop);
|
||||
return promise;
|
||||
}
|
||||
/**
|
||||
* Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot. Note that most query config (e.g.
|
||||
* `queryFn`, `staleTime`) is not dehydrated but instead meant to be configured again when consuming the
|
||||
* de/rehydrated data, typically with `useQuery` on the client. If the query is still `pending`, its in-flight
|
||||
* promise is dehydrated too so it can be resumed on the other side instead of re-fetched.
|
||||
* @param query - The query to dehydrate.
|
||||
* @param serializeData - Optional transform applied to `query.state.data` before it is included in the snapshot.
|
||||
* @param shouldRedactErrors - Optional predicate; if it returns `false` for the promise's rejection error, that
|
||||
* error is kept as-is instead of being redacted.
|
||||
*/
|
||||
function dehydrateQuery(query, serializeData, shouldRedactErrors) {
|
||||
return {
|
||||
dehydratedAt: Date.now(),
|
||||
state: {
|
||||
...query.state,
|
||||
...query.state.data !== void 0 && { data: serializeData ? serializeData(query.state.data) : query.state.data }
|
||||
},
|
||||
queryKey: query.queryKey,
|
||||
queryHash: query.queryHash,
|
||||
...query.state.status === "pending" && { promise: dehydratePromise(query, serializeData, shouldRedactErrors) },
|
||||
...query.meta && { meta: query.meta },
|
||||
...query.queryType && { queryType: query.queryType }
|
||||
};
|
||||
}
|
||||
/**
|
||||
* The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only dehydrates mutations that are
|
||||
* currently paused (e.g. paused by `networkMode` while offline).
|
||||
*/
|
||||
function defaultShouldDehydrateMutation(mutation) {
|
||||
return mutation.state.isPaused;
|
||||
}
|
||||
/**
|
||||
* The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only dehydrates queries whose status is
|
||||
* `'success'`.
|
||||
*/
|
||||
function defaultShouldDehydrateQuery(query) {
|
||||
return query.state.status === "success";
|
||||
}
|
||||
/**
|
||||
* Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain, serializable `DehydratedState`,
|
||||
* typically to embed in server-rendered markup and later restore into a client-side `QueryClient` via `hydrate`.
|
||||
* Which queries/mutations are included, and how their data/errors are transformed, is controlled by `options`,
|
||||
* falling back to the client's `dehydrate` default options, and finally to `defaultShouldDehydrateQuery` /
|
||||
* `defaultShouldDehydrateMutation`.
|
||||
* @example
|
||||
* ```ts
|
||||
* const queryClient = new QueryClient()
|
||||
*
|
||||
* await queryClient.prefetchQuery({
|
||||
* queryKey: ['posts'],
|
||||
* queryFn: getPosts,
|
||||
* })
|
||||
*
|
||||
* const dehydratedState = dehydrate(queryClient)
|
||||
* ```
|
||||
*/
|
||||
function dehydrate(client, options = {}) {
|
||||
var _client$getDefaultOpt, _client$getDefaultOpt2, _client$getDefaultOpt3, _client$getDefaultOpt4;
|
||||
const filterMutation = options.shouldDehydrateMutation ?? ((_client$getDefaultOpt = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt === void 0 ? void 0 : _client$getDefaultOpt.shouldDehydrateMutation) ?? defaultShouldDehydrateMutation;
|
||||
const mutations = client.getMutationCache().getAll().flatMap((mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []);
|
||||
const filterQuery = options.shouldDehydrateQuery ?? ((_client$getDefaultOpt2 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt2 === void 0 ? void 0 : _client$getDefaultOpt2.shouldDehydrateQuery) ?? defaultShouldDehydrateQuery;
|
||||
const shouldRedactErrors = options.shouldRedactErrors ?? ((_client$getDefaultOpt3 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt3 === void 0 ? void 0 : _client$getDefaultOpt3.shouldRedactErrors);
|
||||
const serializeData = options.serializeData ?? ((_client$getDefaultOpt4 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt4 === void 0 ? void 0 : _client$getDefaultOpt4.serializeData);
|
||||
return {
|
||||
mutations,
|
||||
queries: client.getQueryCache().getAll().flatMap((query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : [])
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Restores a `DehydratedState` (as produced by `dehydrate`) into a `QueryClient`'s cache, typically to seed the
|
||||
* client with data already fetched on the server. `mutations` and `queries` are each optional on `dehydratedState`.
|
||||
* Queries not yet in the cache are built from the dehydrated snapshot; queries that already exist are only updated
|
||||
* when the dehydrated data is newer than what's already cached. Newly built queries have their `fetchStatus` reset
|
||||
* to `'idle'` so they don't hydrate stuck in a fetching state. If a dehydrated query still had an in-flight
|
||||
* promise, it is resumed via `query.fetch()` (reusing that promise as `initialPromise`) rather than re-invoking
|
||||
* `queryFn`.
|
||||
* @example
|
||||
* ```ts
|
||||
* // dehydratedState was produced by `dehydrate` on the server
|
||||
* // and sent to the client, e.g. embedded in server-rendered markup.
|
||||
* const queryClient = new QueryClient()
|
||||
*
|
||||
* hydrate(queryClient, dehydratedState)
|
||||
* ```
|
||||
*/
|
||||
function hydrate(client, dehydratedState, options) {
|
||||
var _options$defaultOptio, _client$getDefaultOpt5, _dehydratedState$muta, _dehydratedState$quer;
|
||||
const mutationCache = client.getMutationCache();
|
||||
const queryCache = client.getQueryCache();
|
||||
const deserializeData = (options === null || options === void 0 || (_options$defaultOptio = options.defaultOptions) === null || _options$defaultOptio === void 0 ? void 0 : _options$defaultOptio.deserializeData) ?? ((_client$getDefaultOpt5 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt5 === void 0 ? void 0 : _client$getDefaultOpt5.deserializeData);
|
||||
(_dehydratedState$muta = dehydratedState.mutations) === null || _dehydratedState$muta === void 0 || _dehydratedState$muta.forEach(({ state, ...mutationOptions }) => {
|
||||
var _client$getDefaultOpt6, _options$defaultOptio2;
|
||||
mutationCache.build(client, {
|
||||
...(_client$getDefaultOpt6 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt6 === void 0 ? void 0 : _client$getDefaultOpt6.mutations,
|
||||
...options === null || options === void 0 || (_options$defaultOptio2 = options.defaultOptions) === null || _options$defaultOptio2 === void 0 ? void 0 : _options$defaultOptio2.mutations,
|
||||
...mutationOptions
|
||||
}, state);
|
||||
});
|
||||
(_dehydratedState$quer = dehydratedState.queries) === null || _dehydratedState$quer === void 0 || _dehydratedState$quer.forEach(({ queryKey, state, queryHash, meta, promise, dehydratedAt, queryType }) => {
|
||||
const syncData = promise ? tryResolveSync(promise) : void 0;
|
||||
const rawData = state.data === void 0 ? syncData === null || syncData === void 0 ? void 0 : syncData.data : state.data;
|
||||
const data = rawData === void 0 ? rawData : deserializeData ? deserializeData(rawData) : rawData;
|
||||
let query = queryCache.get(queryHash);
|
||||
const existingQueryIsPending = (query === null || query === void 0 ? void 0 : query.state.status) === "pending";
|
||||
const existingQueryIsFetching = (query === null || query === void 0 ? void 0 : query.state.fetchStatus) === "fetching";
|
||||
if (query) {
|
||||
const hasNewerSyncData = syncData && dehydratedAt > query.state.dataUpdatedAt;
|
||||
if (state.dataUpdatedAt > query.state.dataUpdatedAt || hasNewerSyncData) {
|
||||
const { fetchStatus: _ignored, ...serializedState } = state;
|
||||
query.setState({
|
||||
...serializedState,
|
||||
data,
|
||||
...state.status === "pending" && data !== void 0 && {
|
||||
status: "success",
|
||||
dataUpdatedAt: dehydratedAt,
|
||||
...!existingQueryIsFetching && { fetchStatus: "idle" }
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
var _client$getDefaultOpt7, _options$defaultOptio3;
|
||||
query = queryCache.build(client, {
|
||||
...(_client$getDefaultOpt7 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt7 === void 0 ? void 0 : _client$getDefaultOpt7.queries,
|
||||
...options === null || options === void 0 || (_options$defaultOptio3 = options.defaultOptions) === null || _options$defaultOptio3 === void 0 ? void 0 : _options$defaultOptio3.queries,
|
||||
queryKey,
|
||||
queryHash,
|
||||
meta,
|
||||
_type: queryType
|
||||
}, {
|
||||
...state,
|
||||
data,
|
||||
fetchStatus: "idle",
|
||||
status: state.status === "pending" && data !== void 0 ? "success" : state.status,
|
||||
...state.status === "pending" && data !== void 0 && { dataUpdatedAt: dehydratedAt }
|
||||
});
|
||||
}
|
||||
if (promise && !syncData && !existingQueryIsPending && !existingQueryIsFetching && dehydratedAt > query.state.dataUpdatedAt) query.fetch(void 0, { initialPromise: Promise.resolve(promise).then(deserializeData) }).catch(require_utils.noop);
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
exports.defaultShouldDehydrateMutation = defaultShouldDehydrateMutation;
|
||||
exports.defaultShouldDehydrateQuery = defaultShouldDehydrateQuery;
|
||||
exports.dehydrate = dehydrate;
|
||||
exports.dehydrateQuery = dehydrateQuery;
|
||||
exports.hydrate = hydrate;
|
||||
|
||||
//# sourceMappingURL=hydration.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"hydration.cjs","names":["noop"],"sources":["../../src/hydration.ts"],"sourcesContent":["import { noop } from './utils'\nimport type {\n DefaultError,\n MutationKey,\n MutationMeta,\n MutationOptions,\n MutationScope,\n QueryKey,\n QueryMeta,\n QueryOptions,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Query, QueryState } from './query'\nimport type { Mutation, MutationState } from './mutation'\n\n// TYPES\ntype TransformerFn = (data: any) => any\n\nfunction tryResolveSync(promise: PromiseLike<unknown>) {\n let data: unknown\n\n const thenResult = promise.then((result) => {\n data = result\n return result\n }, noop) as Promise<unknown> | undefined\n\n // .catch can be unavailable on certain kinds of thenable's\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n thenResult?.catch?.(noop)\n\n if (data !== undefined) {\n return { data }\n }\n\n return undefined\n}\n\n/**\n * Options for `dehydrate`, controlling which queries/mutations are included in the resulting `DehydratedState` and\n * how their data/errors are transformed before being serialized (e.g. for embedding in server-rendered markup).\n */\nexport interface DehydrateOptions {\n /** Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. */\n serializeData?: TransformerFn\n /** Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. */\n shouldDehydrateMutation?: (mutation: Mutation) => boolean\n /** Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. */\n shouldDehydrateQuery?: (query: Query) => boolean\n /**\n * Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted\n * (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the\n * given error, in which case the original error is kept.\n */\n shouldRedactErrors?: (error: unknown) => boolean\n}\n\n/**\n * Options for `hydrate`, controlling the default options applied to queries/mutations restored from a\n * `DehydratedState`, and how to reverse any transformation applied by `DehydrateOptions.serializeData`.\n */\nexport interface HydrateOptions {\n defaultOptions?: {\n /** Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. */\n deserializeData?: TransformerFn\n /** Default options merged into every query restored from the dehydrated state. */\n queries?: QueryOptions\n /** Default options merged into every mutation restored from the dehydrated state. */\n mutations?: MutationOptions<unknown, DefaultError, unknown, unknown>\n }\n}\n\ninterface DehydratedMutation {\n mutationKey?: MutationKey\n state: MutationState\n meta?: MutationMeta\n scope?: MutationScope\n}\n\ninterface DehydratedQuery {\n queryHash: string\n queryKey: QueryKey\n state: QueryState\n dehydratedAt: number\n promise?: Promise<unknown>\n meta?: QueryMeta\n queryType?: 'infinite'\n}\n\n/**\n * A serializable snapshot of a `QueryClient`'s cache, as produced by `dehydrate` and consumed by `hydrate`. Typically\n * transported from server to client (e.g. embedded in server-rendered markup) to seed the client's cache with data\n * that has already been fetched, avoiding a redundant fetch on the client.\n */\nexport interface DehydratedState {\n mutations: Array<DehydratedMutation>\n queries: Array<DehydratedQuery>\n}\n\n// FUNCTIONS\n\nfunction dehydrateMutation(mutation: Mutation): DehydratedMutation {\n return {\n mutationKey: mutation.options.mutationKey,\n state: mutation.state,\n ...(mutation.options.scope && { scope: mutation.options.scope }),\n ...(mutation.meta && { meta: mutation.meta }),\n }\n}\n\nfunction dehydratePromise(\n query: Query,\n serializeData?: TransformerFn,\n shouldRedactErrors?: (error: unknown) => boolean,\n): Promise<unknown> | undefined {\n const promise = query.promise?.then(serializeData).catch((error) => {\n if (shouldRedactErrors?.(error) === false) {\n // Reject original error if it should not be redacted\n return Promise.reject(error)\n }\n // If not in production, log original error before rejecting redacted error\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,\n )\n }\n return Promise.reject(new Error('redacted'))\n })\n\n // Avoid unhandled promise rejections\n // We need the promise we dehydrate to reject to get the correct result into\n // the query cache, but we also want to avoid unhandled promise rejections\n // in whatever environment the prefetches are happening in.\n promise?.catch(noop)\n\n return promise\n}\n\n/**\n * Line truncated
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { a as defaultShouldDehydrateQuery, c as hydrate, i as defaultShouldDehydrateMutation, n as DehydratedState, o as dehydrate, r as HydrateOptions, s as dehydrateQuery, t as DehydrateOptions } from "./hydration-DwR10Hi-.cjs";
|
||||
export { DehydrateOptions, DehydratedState, HydrateOptions, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, hydrate };
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { a as defaultShouldDehydrateQuery, c as hydrate, i as defaultShouldDehydrateMutation, n as DehydratedState, o as dehydrate, r as HydrateOptions, s as dehydrateQuery, t as DehydrateOptions } from "./hydration-Cq7QYAzB.js";
|
||||
export { DehydrateOptions, DehydratedState, HydrateOptions, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, hydrate };
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
import { noop } from "./utils.js";
|
||||
//#region src/hydration.ts
|
||||
function tryResolveSync(promise) {
|
||||
var _thenResult$catch;
|
||||
let data;
|
||||
const thenResult = promise.then((result) => {
|
||||
data = result;
|
||||
return result;
|
||||
}, noop);
|
||||
thenResult === null || thenResult === void 0 || (_thenResult$catch = thenResult.catch) === null || _thenResult$catch === void 0 || _thenResult$catch.call(thenResult, noop);
|
||||
if (data !== void 0) return { data };
|
||||
}
|
||||
function dehydrateMutation(mutation) {
|
||||
return {
|
||||
mutationKey: mutation.options.mutationKey,
|
||||
state: mutation.state,
|
||||
...mutation.options.scope && { scope: mutation.options.scope },
|
||||
...mutation.meta && { meta: mutation.meta }
|
||||
};
|
||||
}
|
||||
function dehydratePromise(query, serializeData, shouldRedactErrors) {
|
||||
var _query$promise;
|
||||
const promise = (_query$promise = query.promise) === null || _query$promise === void 0 ? void 0 : _query$promise.then(serializeData).catch((error) => {
|
||||
if ((shouldRedactErrors === null || shouldRedactErrors === void 0 ? void 0 : shouldRedactErrors(error)) === false) return Promise.reject(error);
|
||||
if (process.env.NODE_ENV !== "production") console.error(`A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`);
|
||||
return Promise.reject(/* @__PURE__ */ new Error("redacted"));
|
||||
});
|
||||
promise === null || promise === void 0 || promise.catch(noop);
|
||||
return promise;
|
||||
}
|
||||
/**
|
||||
* Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot. Note that most query config (e.g.
|
||||
* `queryFn`, `staleTime`) is not dehydrated but instead meant to be configured again when consuming the
|
||||
* de/rehydrated data, typically with `useQuery` on the client. If the query is still `pending`, its in-flight
|
||||
* promise is dehydrated too so it can be resumed on the other side instead of re-fetched.
|
||||
* @param query - The query to dehydrate.
|
||||
* @param serializeData - Optional transform applied to `query.state.data` before it is included in the snapshot.
|
||||
* @param shouldRedactErrors - Optional predicate; if it returns `false` for the promise's rejection error, that
|
||||
* error is kept as-is instead of being redacted.
|
||||
*/
|
||||
function dehydrateQuery(query, serializeData, shouldRedactErrors) {
|
||||
return {
|
||||
dehydratedAt: Date.now(),
|
||||
state: {
|
||||
...query.state,
|
||||
...query.state.data !== void 0 && { data: serializeData ? serializeData(query.state.data) : query.state.data }
|
||||
},
|
||||
queryKey: query.queryKey,
|
||||
queryHash: query.queryHash,
|
||||
...query.state.status === "pending" && { promise: dehydratePromise(query, serializeData, shouldRedactErrors) },
|
||||
...query.meta && { meta: query.meta },
|
||||
...query.queryType && { queryType: query.queryType }
|
||||
};
|
||||
}
|
||||
/**
|
||||
* The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only dehydrates mutations that are
|
||||
* currently paused (e.g. paused by `networkMode` while offline).
|
||||
*/
|
||||
function defaultShouldDehydrateMutation(mutation) {
|
||||
return mutation.state.isPaused;
|
||||
}
|
||||
/**
|
||||
* The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only dehydrates queries whose status is
|
||||
* `'success'`.
|
||||
*/
|
||||
function defaultShouldDehydrateQuery(query) {
|
||||
return query.state.status === "success";
|
||||
}
|
||||
/**
|
||||
* Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain, serializable `DehydratedState`,
|
||||
* typically to embed in server-rendered markup and later restore into a client-side `QueryClient` via `hydrate`.
|
||||
* Which queries/mutations are included, and how their data/errors are transformed, is controlled by `options`,
|
||||
* falling back to the client's `dehydrate` default options, and finally to `defaultShouldDehydrateQuery` /
|
||||
* `defaultShouldDehydrateMutation`.
|
||||
* @example
|
||||
* ```ts
|
||||
* const queryClient = new QueryClient()
|
||||
*
|
||||
* await queryClient.prefetchQuery({
|
||||
* queryKey: ['posts'],
|
||||
* queryFn: getPosts,
|
||||
* })
|
||||
*
|
||||
* const dehydratedState = dehydrate(queryClient)
|
||||
* ```
|
||||
*/
|
||||
function dehydrate(client, options = {}) {
|
||||
var _client$getDefaultOpt, _client$getDefaultOpt2, _client$getDefaultOpt3, _client$getDefaultOpt4;
|
||||
const filterMutation = options.shouldDehydrateMutation ?? ((_client$getDefaultOpt = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt === void 0 ? void 0 : _client$getDefaultOpt.shouldDehydrateMutation) ?? defaultShouldDehydrateMutation;
|
||||
const mutations = client.getMutationCache().getAll().flatMap((mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []);
|
||||
const filterQuery = options.shouldDehydrateQuery ?? ((_client$getDefaultOpt2 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt2 === void 0 ? void 0 : _client$getDefaultOpt2.shouldDehydrateQuery) ?? defaultShouldDehydrateQuery;
|
||||
const shouldRedactErrors = options.shouldRedactErrors ?? ((_client$getDefaultOpt3 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt3 === void 0 ? void 0 : _client$getDefaultOpt3.shouldRedactErrors);
|
||||
const serializeData = options.serializeData ?? ((_client$getDefaultOpt4 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt4 === void 0 ? void 0 : _client$getDefaultOpt4.serializeData);
|
||||
return {
|
||||
mutations,
|
||||
queries: client.getQueryCache().getAll().flatMap((query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : [])
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Restores a `DehydratedState` (as produced by `dehydrate`) into a `QueryClient`'s cache, typically to seed the
|
||||
* client with data already fetched on the server. `mutations` and `queries` are each optional on `dehydratedState`.
|
||||
* Queries not yet in the cache are built from the dehydrated snapshot; queries that already exist are only updated
|
||||
* when the dehydrated data is newer than what's already cached. Newly built queries have their `fetchStatus` reset
|
||||
* to `'idle'` so they don't hydrate stuck in a fetching state. If a dehydrated query still had an in-flight
|
||||
* promise, it is resumed via `query.fetch()` (reusing that promise as `initialPromise`) rather than re-invoking
|
||||
* `queryFn`.
|
||||
* @example
|
||||
* ```ts
|
||||
* // dehydratedState was produced by `dehydrate` on the server
|
||||
* // and sent to the client, e.g. embedded in server-rendered markup.
|
||||
* const queryClient = new QueryClient()
|
||||
*
|
||||
* hydrate(queryClient, dehydratedState)
|
||||
* ```
|
||||
*/
|
||||
function hydrate(client, dehydratedState, options) {
|
||||
var _options$defaultOptio, _client$getDefaultOpt5, _dehydratedState$muta, _dehydratedState$quer;
|
||||
const mutationCache = client.getMutationCache();
|
||||
const queryCache = client.getQueryCache();
|
||||
const deserializeData = (options === null || options === void 0 || (_options$defaultOptio = options.defaultOptions) === null || _options$defaultOptio === void 0 ? void 0 : _options$defaultOptio.deserializeData) ?? ((_client$getDefaultOpt5 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt5 === void 0 ? void 0 : _client$getDefaultOpt5.deserializeData);
|
||||
(_dehydratedState$muta = dehydratedState.mutations) === null || _dehydratedState$muta === void 0 || _dehydratedState$muta.forEach(({ state, ...mutationOptions }) => {
|
||||
var _client$getDefaultOpt6, _options$defaultOptio2;
|
||||
mutationCache.build(client, {
|
||||
...(_client$getDefaultOpt6 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt6 === void 0 ? void 0 : _client$getDefaultOpt6.mutations,
|
||||
...options === null || options === void 0 || (_options$defaultOptio2 = options.defaultOptions) === null || _options$defaultOptio2 === void 0 ? void 0 : _options$defaultOptio2.mutations,
|
||||
...mutationOptions
|
||||
}, state);
|
||||
});
|
||||
(_dehydratedState$quer = dehydratedState.queries) === null || _dehydratedState$quer === void 0 || _dehydratedState$quer.forEach(({ queryKey, state, queryHash, meta, promise, dehydratedAt, queryType }) => {
|
||||
const syncData = promise ? tryResolveSync(promise) : void 0;
|
||||
const rawData = state.data === void 0 ? syncData === null || syncData === void 0 ? void 0 : syncData.data : state.data;
|
||||
const data = rawData === void 0 ? rawData : deserializeData ? deserializeData(rawData) : rawData;
|
||||
let query = queryCache.get(queryHash);
|
||||
const existingQueryIsPending = (query === null || query === void 0 ? void 0 : query.state.status) === "pending";
|
||||
const existingQueryIsFetching = (query === null || query === void 0 ? void 0 : query.state.fetchStatus) === "fetching";
|
||||
if (query) {
|
||||
const hasNewerSyncData = syncData && dehydratedAt > query.state.dataUpdatedAt;
|
||||
if (state.dataUpdatedAt > query.state.dataUpdatedAt || hasNewerSyncData) {
|
||||
const { fetchStatus: _ignored, ...serializedState } = state;
|
||||
query.setState({
|
||||
...serializedState,
|
||||
data,
|
||||
...state.status === "pending" && data !== void 0 && {
|
||||
status: "success",
|
||||
dataUpdatedAt: dehydratedAt,
|
||||
...!existingQueryIsFetching && { fetchStatus: "idle" }
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
var _client$getDefaultOpt7, _options$defaultOptio3;
|
||||
query = queryCache.build(client, {
|
||||
...(_client$getDefaultOpt7 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt7 === void 0 ? void 0 : _client$getDefaultOpt7.queries,
|
||||
...options === null || options === void 0 || (_options$defaultOptio3 = options.defaultOptions) === null || _options$defaultOptio3 === void 0 ? void 0 : _options$defaultOptio3.queries,
|
||||
queryKey,
|
||||
queryHash,
|
||||
meta,
|
||||
_type: queryType
|
||||
}, {
|
||||
...state,
|
||||
data,
|
||||
fetchStatus: "idle",
|
||||
status: state.status === "pending" && data !== void 0 ? "success" : state.status,
|
||||
...state.status === "pending" && data !== void 0 && { dataUpdatedAt: dehydratedAt }
|
||||
});
|
||||
}
|
||||
if (promise && !syncData && !existingQueryIsPending && !existingQueryIsFetching && dehydratedAt > query.state.dataUpdatedAt) query.fetch(void 0, { initialPromise: Promise.resolve(promise).then(deserializeData) }).catch(noop);
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
export { defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, hydrate };
|
||||
|
||||
//# sourceMappingURL=hydration.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"hydration.js","names":[],"sources":["../../src/hydration.ts"],"sourcesContent":["import { noop } from './utils'\nimport type {\n DefaultError,\n MutationKey,\n MutationMeta,\n MutationOptions,\n MutationScope,\n QueryKey,\n QueryMeta,\n QueryOptions,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Query, QueryState } from './query'\nimport type { Mutation, MutationState } from './mutation'\n\n// TYPES\ntype TransformerFn = (data: any) => any\n\nfunction tryResolveSync(promise: PromiseLike<unknown>) {\n let data: unknown\n\n const thenResult = promise.then((result) => {\n data = result\n return result\n }, noop) as Promise<unknown> | undefined\n\n // .catch can be unavailable on certain kinds of thenable's\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n thenResult?.catch?.(noop)\n\n if (data !== undefined) {\n return { data }\n }\n\n return undefined\n}\n\n/**\n * Options for `dehydrate`, controlling which queries/mutations are included in the resulting `DehydratedState` and\n * how their data/errors are transformed before being serialized (e.g. for embedding in server-rendered markup).\n */\nexport interface DehydrateOptions {\n /** Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. */\n serializeData?: TransformerFn\n /** Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. */\n shouldDehydrateMutation?: (mutation: Mutation) => boolean\n /** Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. */\n shouldDehydrateQuery?: (query: Query) => boolean\n /**\n * Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted\n * (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the\n * given error, in which case the original error is kept.\n */\n shouldRedactErrors?: (error: unknown) => boolean\n}\n\n/**\n * Options for `hydrate`, controlling the default options applied to queries/mutations restored from a\n * `DehydratedState`, and how to reverse any transformation applied by `DehydrateOptions.serializeData`.\n */\nexport interface HydrateOptions {\n defaultOptions?: {\n /** Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. */\n deserializeData?: TransformerFn\n /** Default options merged into every query restored from the dehydrated state. */\n queries?: QueryOptions\n /** Default options merged into every mutation restored from the dehydrated state. */\n mutations?: MutationOptions<unknown, DefaultError, unknown, unknown>\n }\n}\n\ninterface DehydratedMutation {\n mutationKey?: MutationKey\n state: MutationState\n meta?: MutationMeta\n scope?: MutationScope\n}\n\ninterface DehydratedQuery {\n queryHash: string\n queryKey: QueryKey\n state: QueryState\n dehydratedAt: number\n promise?: Promise<unknown>\n meta?: QueryMeta\n queryType?: 'infinite'\n}\n\n/**\n * A serializable snapshot of a `QueryClient`'s cache, as produced by `dehydrate` and consumed by `hydrate`. Typically\n * transported from server to client (e.g. embedded in server-rendered markup) to seed the client's cache with data\n * that has already been fetched, avoiding a redundant fetch on the client.\n */\nexport interface DehydratedState {\n mutations: Array<DehydratedMutation>\n queries: Array<DehydratedQuery>\n}\n\n// FUNCTIONS\n\nfunction dehydrateMutation(mutation: Mutation): DehydratedMutation {\n return {\n mutationKey: mutation.options.mutationKey,\n state: mutation.state,\n ...(mutation.options.scope && { scope: mutation.options.scope }),\n ...(mutation.meta && { meta: mutation.meta }),\n }\n}\n\nfunction dehydratePromise(\n query: Query,\n serializeData?: TransformerFn,\n shouldRedactErrors?: (error: unknown) => boolean,\n): Promise<unknown> | undefined {\n const promise = query.promise?.then(serializeData).catch((error) => {\n if (shouldRedactErrors?.(error) === false) {\n // Reject original error if it should not be redacted\n return Promise.reject(error)\n }\n // If not in production, log original error before rejecting redacted error\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,\n )\n }\n return Promise.reject(new Error('redacted'))\n })\n\n // Avoid unhandled promise rejections\n // We need the promise we dehydrate to reject to get the correct result into\n // the query cache, but we also want to avoid unhandled promise rejections\n // in whatever environment the prefetches are happening in.\n promise?.catch(noop)\n\n return promise\n}\n\n/**\n * DehydraLine truncated
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_timeoutManager = require("./timeoutManager.cjs");
|
||||
const require_utils = require("./utils.cjs");
|
||||
const require_environmentManager = require("./environmentManager.cjs");
|
||||
const require_focusManager = require("./focusManager.cjs");
|
||||
const require_hydration = require("./hydration.cjs");
|
||||
const require_notifyManager = require("./notifyManager.cjs");
|
||||
const require_onlineManager = require("./onlineManager.cjs");
|
||||
const require_retryer = require("./retryer.cjs");
|
||||
const require_query = require("./query.cjs");
|
||||
const require_queryObserver = require("./queryObserver.cjs");
|
||||
const require_infiniteQueryObserver = require("./infiniteQueryObserver.cjs");
|
||||
const require_mutation = require("./mutation.cjs");
|
||||
const require_mutationCache = require("./mutationCache.cjs");
|
||||
const require_mutationObserver = require("./mutationObserver.cjs");
|
||||
const require_queriesObserver = require("./queriesObserver.cjs");
|
||||
const require_queryCache = require("./queryCache.cjs");
|
||||
const require_queryClient = require("./queryClient.cjs");
|
||||
const require_streamedQuery = require("./streamedQuery.cjs");
|
||||
const require_types = require("./types.cjs");
|
||||
//#region src/index.ts
|
||||
/* istanbul ignore file */
|
||||
//#endregion
|
||||
exports.CancelledError = require_retryer.CancelledError;
|
||||
exports.InfiniteQueryObserver = require_infiniteQueryObserver.InfiniteQueryObserver;
|
||||
exports.Mutation = require_mutation.Mutation;
|
||||
exports.MutationCache = require_mutationCache.MutationCache;
|
||||
exports.MutationObserver = require_mutationObserver.MutationObserver;
|
||||
exports.QueriesObserver = require_queriesObserver.QueriesObserver;
|
||||
exports.Query = require_query.Query;
|
||||
exports.QueryCache = require_queryCache.QueryCache;
|
||||
exports.QueryClient = require_queryClient.QueryClient;
|
||||
exports.QueryObserver = require_queryObserver.QueryObserver;
|
||||
exports.dataTagErrorSymbol = require_types.dataTagErrorSymbol;
|
||||
exports.dataTagSymbol = require_types.dataTagSymbol;
|
||||
exports.defaultScheduler = require_notifyManager.defaultScheduler;
|
||||
exports.defaultShouldDehydrateMutation = require_hydration.defaultShouldDehydrateMutation;
|
||||
exports.defaultShouldDehydrateQuery = require_hydration.defaultShouldDehydrateQuery;
|
||||
exports.dehydrate = require_hydration.dehydrate;
|
||||
exports.dehydrateQuery = require_hydration.dehydrateQuery;
|
||||
exports.environmentManager = require_environmentManager.environmentManager;
|
||||
exports.experimental_streamedQuery = require_streamedQuery.streamedQuery;
|
||||
exports.focusManager = require_focusManager.focusManager;
|
||||
exports.hashKey = require_utils.hashKey;
|
||||
exports.hydrate = require_hydration.hydrate;
|
||||
exports.isCancelledError = require_retryer.isCancelledError;
|
||||
exports.isServer = require_utils.isServer;
|
||||
exports.keepPreviousData = require_utils.keepPreviousData;
|
||||
exports.matchMutation = require_utils.matchMutation;
|
||||
exports.matchQuery = require_utils.matchQuery;
|
||||
exports.noop = require_utils.noop;
|
||||
exports.notifyManager = require_notifyManager.notifyManager;
|
||||
exports.onlineManager = require_onlineManager.onlineManager;
|
||||
exports.partialMatchKey = require_utils.partialMatchKey;
|
||||
exports.replaceEqualDeep = require_utils.replaceEqualDeep;
|
||||
exports.shouldThrowError = require_utils.shouldThrowError;
|
||||
exports.skipToken = require_utils.skipToken;
|
||||
exports.timeoutManager = require_timeoutManager.timeoutManager;
|
||||
exports.unsetMarker = require_types.unsetMarker;
|
||||
|
||||
//# sourceMappingURL=index.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport { focusManager } from './focusManager'\nexport type { FocusManager } from './focusManager'\nexport { environmentManager } from './environmentManager'\nexport {\n defaultShouldDehydrateMutation,\n defaultShouldDehydrateQuery,\n dehydrate,\n dehydrateQuery,\n hydrate,\n} from './hydration'\nexport { InfiniteQueryObserver } from './infiniteQueryObserver'\nexport { MutationCache } from './mutationCache'\nexport type { MutationCacheNotifyEvent } from './mutationCache'\nexport { MutationObserver } from './mutationObserver'\nexport { defaultScheduler, notifyManager } from './notifyManager'\nexport { onlineManager } from './onlineManager'\nexport type { OnlineManager } from './onlineManager'\nexport { QueriesObserver } from './queriesObserver'\nexport { QueryCache } from './queryCache'\nexport type { QueryCacheNotifyEvent } from './queryCache'\nexport { QueryClient } from './queryClient'\nexport { QueryObserver } from './queryObserver'\nexport { CancelledError, isCancelledError } from './retryer'\nexport {\n timeoutManager,\n type ManagedTimerId,\n type TimeoutCallback,\n type TimeoutManager,\n type TimeoutProvider,\n} from './timeoutManager'\nexport {\n hashKey,\n isServer,\n keepPreviousData,\n matchMutation,\n matchQuery,\n noop,\n partialMatchKey,\n replaceEqualDeep,\n shouldThrowError,\n skipToken,\n} from './utils'\nexport type { MutationFilters, QueryFilters, SkipToken, Updater } from './utils'\n\nexport { streamedQuery as experimental_streamedQuery } from './streamedQuery'\n\n// Types\nexport type {\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from './hydration'\nexport { Mutation } from './mutation'\nexport type { MutationState } from './mutation'\nexport type { MutationCacheConfig } from './mutationCache'\nexport type { QueriesObserverOptions } from './queriesObserver'\nexport { Query } from './query'\nexport type { QueryState } from './query'\nexport type { QueryCacheConfig } from './queryCache'\nexport * from './types'\n"],"mappings":""}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { environmentManager } from "./environmentManager.cjs";
|
||||
import { FocusManager, focusManager } from "./focusManager.cjs";
|
||||
import { $ as MutationObserverBaseResult, $n as Query, $t as CancelledError, A as InfiniteData, An as noop, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dn as keepPreviousData, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gn as MutationCacheConfig, Gt as StaleTime, H as InitialDataFunction, Hn as MutationState, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, In as shouldThrowError, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kn as MutationCacheNotifyEvent, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Ln as skipToken, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nn as replaceEqualDeep, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, On as matchMutation, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tn as isServer, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vn as Mutation, Vt as Register, W as InvalidateOptions, Wn as MutationCache, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, a as defaultShouldDehydrateQuery, an as isCancelledError, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, c as hydrate, cn as QueryCacheConfig, ct as MutationStatus, d as DataTag, dn as MutationFilters, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, fn as QueryFilters, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, hn as Updater, ht as Override, i as defaultShouldDehydrateMutation, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jn as partialMatchKey, jt as QueryObserverPendingResult, k as InferErrorFromTag, kn as matchQuery, kt as QueryObserverLoadingResult, l as AnyDataTag, ln as QueryCacheNotifyEvent, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mn as SkipToken, mt as OmitKeyof, n as DehydratedState, nt as MutationObserverLoadingResult, o as dehydrate, on as QueryClient, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qn as MutationObserver, qt as ThrowOnError, r as HydrateOptions, rr as QueryObserver, rt as MutationObserverOptions, s as dehydrateQuery, sn as QueryCache, st as MutationScope, t as DehydrateOptions, tr as QueryState, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xn as hashKey, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-DwR10Hi-.cjs";
|
||||
import { InfiniteQueryObserver } from "./infiniteQueryObserver.cjs";
|
||||
import { defaultScheduler, notifyManager } from "./notifyManager.cjs";
|
||||
import { OnlineManager, onlineManager } from "./onlineManager.cjs";
|
||||
import { QueriesObserver, QueriesObserverOptions } from "./queriesObserver.cjs";
|
||||
import { ManagedTimerId, TimeoutCallback, TimeoutManager, TimeoutProvider, timeoutManager } from "./timeoutManager.cjs";
|
||||
import { streamedQuery } from "./streamedQuery.cjs";
|
||||
export { AnyDataTag, CancelOptions, CancelledError, DataTag, DefaultError, DefaultOptions, DefaultedInfiniteQueryObserverOptions, DefaultedQueryObserverOptions, DefinedInfiniteQueryObserverResult, DefinedQueryObserverResult, type DehydrateOptions, type DehydratedState, DistributiveOmit, EnsureInfiniteQueryDataOptions, EnsureQueryDataOptions, FetchInfiniteQueryOptions, FetchNextPageOptions, FetchPreviousPageOptions, FetchQueryOptions, FetchStatus, type FocusManager, GetNextPageParamFunction, GetPreviousPageParamFunction, type HydrateOptions, InferDataFromTag, InferErrorFromTag, InfiniteData, InfiniteQueryExecuteOptions, InfiniteQueryObserver, InfiniteQueryObserverBaseResult, InfiniteQueryObserverLoadingErrorResult, InfiniteQueryObserverLoadingResult, InfiniteQueryObserverOptions, InfiniteQueryObserverPendingResult, InfiniteQueryObserverPlaceholderResult, InfiniteQueryObserverRefetchErrorResult, InfiniteQueryObserverResult, InfiniteQueryObserverSuccessResult, InfiniteQueryPageParamsOptions, InitialDataFunction, InitialPageParam, InvalidateOptions, InvalidateQueryFilters, type ManagedTimerId, MutateFunction, MutateFunctionRest, MutateOptions, Mutation, MutationCache, type MutationCacheConfig, type MutationCacheNotifyEvent, type MutationFilters, MutationFunction, MutationFunctionContext, MutationKey, MutationMeta, MutationObserver, MutationObserverBaseResult, MutationObserverErrorResult, MutationObserverIdleResult, MutationObserverLoadingResult, MutationObserverOptions, MutationObserverResult, MutationObserverSuccessResult, MutationOptions, MutationScope, type MutationState, MutationStatus, NetworkMode, NonUndefinedGuard, NotifyEvent, NotifyEventType, NotifyOnChangeProps, OmitKeyof, type OnlineManager, Override, PlaceholderDataFunction, QueriesObserver, type QueriesObserverOptions, QueriesPlaceholderDataFunction, Query, QueryBooleanOption, QueryCache, type QueryCacheConfig, type QueryCacheNotifyEvent, QueryClient, QueryClientConfig, QueryExecuteOptions, type QueryFilters, QueryFunction, QueryFunctionContext, QueryKey, QueryKeyHashFunction, QueryKeyWithDataTag, QueryMeta, QueryObserver, QueryObserverBaseResult, QueryObserverLoadingErrorResult, QueryObserverLoadingResult, QueryObserverOptions, QueryObserverPendingResult, QueryObserverPlaceholderResult, QueryObserverRefetchErrorResult, QueryObserverResult, QueryObserverSuccessResult, QueryOptions, QueryPersister, type QueryState, QueryStatus, RefetchOptions, RefetchQueryFilters, Register, ResetOptions, ResultOptions, SetDataOptions, type SkipToken, StaleTime, StaleTimeFunction, ThrowOnError, type TimeoutCallback, type TimeoutManager, type TimeoutProvider, UnsetMarker, type Updater, WithRequired, dataTagErrorSymbol, dataTagSymbol, defaultScheduler, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, environmentManager, streamedQuery as experimental_streamedQuery, focusManager, hashKey, hydrate, isCancelledError, isServer, keepPreviousData, matchMutation, matchQuery, noop, notifyManager, onlineManager, partialMatchKey, replaceEqualDeep, shouldThrowError, skipToken, timeoutManager, unsetMarker };
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { environmentManager } from "./environmentManager.js";
|
||||
import { FocusManager, focusManager } from "./focusManager.js";
|
||||
import { $ as MutationObserverBaseResult, $n as Query, $t as CancelledError, A as InfiniteData, An as noop, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dn as keepPreviousData, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gn as MutationCacheConfig, Gt as StaleTime, H as InitialDataFunction, Hn as MutationState, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, In as shouldThrowError, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kn as MutationCacheNotifyEvent, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Ln as skipToken, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nn as replaceEqualDeep, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, On as matchMutation, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tn as isServer, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vn as Mutation, Vt as Register, W as InvalidateOptions, Wn as MutationCache, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, a as defaultShouldDehydrateQuery, an as isCancelledError, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, c as hydrate, cn as QueryCacheConfig, ct as MutationStatus, d as DataTag, dn as MutationFilters, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, fn as QueryFilters, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, hn as Updater, ht as Override, i as defaultShouldDehydrateMutation, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jn as partialMatchKey, jt as QueryObserverPendingResult, k as InferErrorFromTag, kn as matchQuery, kt as QueryObserverLoadingResult, l as AnyDataTag, ln as QueryCacheNotifyEvent, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mn as SkipToken, mt as OmitKeyof, n as DehydratedState, nt as MutationObserverLoadingResult, o as dehydrate, on as QueryClient, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qn as MutationObserver, qt as ThrowOnError, r as HydrateOptions, rr as QueryObserver, rt as MutationObserverOptions, s as dehydrateQuery, sn as QueryCache, st as MutationScope, t as DehydrateOptions, tr as QueryState, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xn as hashKey, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-Cq7QYAzB.js";
|
||||
import { InfiniteQueryObserver } from "./infiniteQueryObserver.js";
|
||||
import { defaultScheduler, notifyManager } from "./notifyManager.js";
|
||||
import { OnlineManager, onlineManager } from "./onlineManager.js";
|
||||
import { QueriesObserver, QueriesObserverOptions } from "./queriesObserver.js";
|
||||
import { ManagedTimerId, TimeoutCallback, TimeoutManager, TimeoutProvider, timeoutManager } from "./timeoutManager.js";
|
||||
import { streamedQuery } from "./streamedQuery.js";
|
||||
export { AnyDataTag, CancelOptions, CancelledError, DataTag, DefaultError, DefaultOptions, DefaultedInfiniteQueryObserverOptions, DefaultedQueryObserverOptions, DefinedInfiniteQueryObserverResult, DefinedQueryObserverResult, type DehydrateOptions, type DehydratedState, DistributiveOmit, EnsureInfiniteQueryDataOptions, EnsureQueryDataOptions, FetchInfiniteQueryOptions, FetchNextPageOptions, FetchPreviousPageOptions, FetchQueryOptions, FetchStatus, type FocusManager, GetNextPageParamFunction, GetPreviousPageParamFunction, type HydrateOptions, InferDataFromTag, InferErrorFromTag, InfiniteData, InfiniteQueryExecuteOptions, InfiniteQueryObserver, InfiniteQueryObserverBaseResult, InfiniteQueryObserverLoadingErrorResult, InfiniteQueryObserverLoadingResult, InfiniteQueryObserverOptions, InfiniteQueryObserverPendingResult, InfiniteQueryObserverPlaceholderResult, InfiniteQueryObserverRefetchErrorResult, InfiniteQueryObserverResult, InfiniteQueryObserverSuccessResult, InfiniteQueryPageParamsOptions, InitialDataFunction, InitialPageParam, InvalidateOptions, InvalidateQueryFilters, type ManagedTimerId, MutateFunction, MutateFunctionRest, MutateOptions, Mutation, MutationCache, type MutationCacheConfig, type MutationCacheNotifyEvent, type MutationFilters, MutationFunction, MutationFunctionContext, MutationKey, MutationMeta, MutationObserver, MutationObserverBaseResult, MutationObserverErrorResult, MutationObserverIdleResult, MutationObserverLoadingResult, MutationObserverOptions, MutationObserverResult, MutationObserverSuccessResult, MutationOptions, MutationScope, type MutationState, MutationStatus, NetworkMode, NonUndefinedGuard, NotifyEvent, NotifyEventType, NotifyOnChangeProps, OmitKeyof, type OnlineManager, Override, PlaceholderDataFunction, QueriesObserver, type QueriesObserverOptions, QueriesPlaceholderDataFunction, Query, QueryBooleanOption, QueryCache, type QueryCacheConfig, type QueryCacheNotifyEvent, QueryClient, QueryClientConfig, QueryExecuteOptions, type QueryFilters, QueryFunction, QueryFunctionContext, QueryKey, QueryKeyHashFunction, QueryKeyWithDataTag, QueryMeta, QueryObserver, QueryObserverBaseResult, QueryObserverLoadingErrorResult, QueryObserverLoadingResult, QueryObserverOptions, QueryObserverPendingResult, QueryObserverPlaceholderResult, QueryObserverRefetchErrorResult, QueryObserverResult, QueryObserverSuccessResult, QueryOptions, QueryPersister, type QueryState, QueryStatus, RefetchOptions, RefetchQueryFilters, Register, ResetOptions, ResultOptions, SetDataOptions, type SkipToken, StaleTime, StaleTimeFunction, ThrowOnError, type TimeoutCallback, type TimeoutManager, type TimeoutProvider, UnsetMarker, type Updater, WithRequired, dataTagErrorSymbol, dataTagSymbol, defaultScheduler, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, environmentManager, streamedQuery as experimental_streamedQuery, focusManager, hashKey, hydrate, isCancelledError, isServer, keepPreviousData, matchMutation, matchQuery, noop, notifyManager, onlineManager, partialMatchKey, replaceEqualDeep, shouldThrowError, skipToken, timeoutManager, unsetMarker };
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { timeoutManager } from "./timeoutManager.js";
|
||||
import { hashKey, isServer, keepPreviousData, matchMutation, matchQuery, noop, partialMatchKey, replaceEqualDeep, shouldThrowError, skipToken } from "./utils.js";
|
||||
import { environmentManager } from "./environmentManager.js";
|
||||
import { focusManager } from "./focusManager.js";
|
||||
import { defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, hydrate } from "./hydration.js";
|
||||
import { defaultScheduler, notifyManager } from "./notifyManager.js";
|
||||
import { onlineManager } from "./onlineManager.js";
|
||||
import { CancelledError, isCancelledError } from "./retryer.js";
|
||||
import { Query } from "./query.js";
|
||||
import { QueryObserver } from "./queryObserver.js";
|
||||
import { InfiniteQueryObserver } from "./infiniteQueryObserver.js";
|
||||
import { Mutation } from "./mutation.js";
|
||||
import { MutationCache } from "./mutationCache.js";
|
||||
import { MutationObserver } from "./mutationObserver.js";
|
||||
import { QueriesObserver } from "./queriesObserver.js";
|
||||
import { QueryCache } from "./queryCache.js";
|
||||
import { QueryClient } from "./queryClient.js";
|
||||
import { streamedQuery } from "./streamedQuery.js";
|
||||
import { dataTagErrorSymbol, dataTagSymbol, unsetMarker } from "./types.js";
|
||||
//#region src/index.ts
|
||||
/* istanbul ignore file */
|
||||
//#endregion
|
||||
export { CancelledError, InfiniteQueryObserver, Mutation, MutationCache, MutationObserver, QueriesObserver, Query, QueryCache, QueryClient, QueryObserver, dataTagErrorSymbol, dataTagSymbol, defaultScheduler, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, environmentManager, streamedQuery as experimental_streamedQuery, focusManager, hashKey, hydrate, isCancelledError, isServer, keepPreviousData, matchMutation, matchQuery, noop, notifyManager, onlineManager, partialMatchKey, replaceEqualDeep, shouldThrowError, skipToken, timeoutManager, unsetMarker };
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport { focusManager } from './focusManager'\nexport type { FocusManager } from './focusManager'\nexport { environmentManager } from './environmentManager'\nexport {\n defaultShouldDehydrateMutation,\n defaultShouldDehydrateQuery,\n dehydrate,\n dehydrateQuery,\n hydrate,\n} from './hydration'\nexport { InfiniteQueryObserver } from './infiniteQueryObserver'\nexport { MutationCache } from './mutationCache'\nexport type { MutationCacheNotifyEvent } from './mutationCache'\nexport { MutationObserver } from './mutationObserver'\nexport { defaultScheduler, notifyManager } from './notifyManager'\nexport { onlineManager } from './onlineManager'\nexport type { OnlineManager } from './onlineManager'\nexport { QueriesObserver } from './queriesObserver'\nexport { QueryCache } from './queryCache'\nexport type { QueryCacheNotifyEvent } from './queryCache'\nexport { QueryClient } from './queryClient'\nexport { QueryObserver } from './queryObserver'\nexport { CancelledError, isCancelledError } from './retryer'\nexport {\n timeoutManager,\n type ManagedTimerId,\n type TimeoutCallback,\n type TimeoutManager,\n type TimeoutProvider,\n} from './timeoutManager'\nexport {\n hashKey,\n isServer,\n keepPreviousData,\n matchMutation,\n matchQuery,\n noop,\n partialMatchKey,\n replaceEqualDeep,\n shouldThrowError,\n skipToken,\n} from './utils'\nexport type { MutationFilters, QueryFilters, SkipToken, Updater } from './utils'\n\nexport { streamedQuery as experimental_streamedQuery } from './streamedQuery'\n\n// Types\nexport type {\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from './hydration'\nexport { Mutation } from './mutation'\nexport type { MutationState } from './mutation'\nexport type { MutationCacheConfig } from './mutationCache'\nexport type { QueriesObserverOptions } from './queriesObserver'\nexport { Query } from './query'\nexport type { QueryState } from './query'\nexport type { QueryCacheConfig } from './queryCache'\nexport * from './types'\n"],"mappings":""}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_utils = require("./utils.cjs");
|
||||
//#region src/infiniteQueryBehavior.ts
|
||||
function infiniteQueryBehavior(pages) {
|
||||
return { onFetch: (context, query) => {
|
||||
var _context$fetchOptions, _context$state$data, _context$state$data2;
|
||||
const options = context.options;
|
||||
const direction = (_context$fetchOptions = context.fetchOptions) === null || _context$fetchOptions === void 0 || (_context$fetchOptions = _context$fetchOptions.meta) === null || _context$fetchOptions === void 0 || (_context$fetchOptions = _context$fetchOptions.fetchMore) === null || _context$fetchOptions === void 0 ? void 0 : _context$fetchOptions.direction;
|
||||
const oldPages = ((_context$state$data = context.state.data) === null || _context$state$data === void 0 ? void 0 : _context$state$data.pages) || [];
|
||||
const oldPageParams = ((_context$state$data2 = context.state.data) === null || _context$state$data2 === void 0 ? void 0 : _context$state$data2.pageParams) || [];
|
||||
let result = {
|
||||
pages: [],
|
||||
pageParams: []
|
||||
};
|
||||
let currentPage = 0;
|
||||
const fetchFn = async () => {
|
||||
let cancelled = false;
|
||||
const addSignalProperty = (object) => {
|
||||
require_utils.addConsumeAwareSignal(object, () => context.signal, () => cancelled = true);
|
||||
};
|
||||
const queryFn = require_utils.ensureQueryFn(context.options, context.fetchOptions);
|
||||
const fetchPage = async (data, param, previous) => {
|
||||
if (cancelled) return Promise.reject(context.signal.reason);
|
||||
if (param == null && data.pages.length) return Promise.resolve(data);
|
||||
const createQueryFnContext = () => {
|
||||
const queryFnContext = {
|
||||
client: context.client,
|
||||
queryKey: context.queryKey,
|
||||
pageParam: param,
|
||||
direction: previous ? "backward" : "forward",
|
||||
meta: context.options.meta
|
||||
};
|
||||
addSignalProperty(queryFnContext);
|
||||
return queryFnContext;
|
||||
};
|
||||
const queryFnContext = createQueryFnContext();
|
||||
const page = await queryFn(queryFnContext);
|
||||
const { maxPages } = context.options;
|
||||
const addTo = previous ? require_utils.addToStart : require_utils.addToEnd;
|
||||
return {
|
||||
pages: addTo(data.pages, page, maxPages),
|
||||
pageParams: addTo(data.pageParams, param, maxPages)
|
||||
};
|
||||
};
|
||||
if (direction && oldPages.length) {
|
||||
const previous = direction === "backward";
|
||||
const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
|
||||
const oldData = {
|
||||
pages: oldPages,
|
||||
pageParams: oldPageParams
|
||||
};
|
||||
result = await fetchPage(oldData, pageParamFn(options, oldData), previous);
|
||||
} else {
|
||||
const remainingPages = pages ?? oldPages.length;
|
||||
do {
|
||||
const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);
|
||||
if (currentPage > 0 && param == null) break;
|
||||
result = await fetchPage(result, param);
|
||||
currentPage++;
|
||||
} while (currentPage < remainingPages);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
if (context.options.persister) context.fetchFn = () => {
|
||||
var _context$options$pers, _context$options;
|
||||
return (_context$options$pers = (_context$options = context.options).persister) === null || _context$options$pers === void 0 ? void 0 : _context$options$pers.call(_context$options, fetchFn, {
|
||||
client: context.client,
|
||||
queryKey: context.queryKey,
|
||||
meta: context.options.meta,
|
||||
signal: context.signal
|
||||
}, query);
|
||||
};
|
||||
else context.fetchFn = fetchFn;
|
||||
} };
|
||||
}
|
||||
function getNextPageParam(options, { pages, pageParams }) {
|
||||
const lastIndex = pages.length - 1;
|
||||
return pages.length > 0 ? options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams) : void 0;
|
||||
}
|
||||
function getPreviousPageParam(options, { pages, pageParams }) {
|
||||
var _options$getPreviousP;
|
||||
return pages.length > 0 ? (_options$getPreviousP = options.getPreviousPageParam) === null || _options$getPreviousP === void 0 ? void 0 : _options$getPreviousP.call(options, pages[0], pages, pageParams[0], pageParams) : void 0;
|
||||
}
|
||||
/**
|
||||
* Checks if there is a next page.
|
||||
*/
|
||||
function hasNextPage(options, data) {
|
||||
if (!data) return false;
|
||||
return getNextPageParam(options, data) != null;
|
||||
}
|
||||
/**
|
||||
* Checks if there is a previous page.
|
||||
*/
|
||||
function hasPreviousPage(options, data) {
|
||||
if (!data || !options.getPreviousPageParam) return false;
|
||||
return getPreviousPageParam(options, data) != null;
|
||||
}
|
||||
//#endregion
|
||||
exports.hasNextPage = hasNextPage;
|
||||
exports.hasPreviousPage = hasPreviousPage;
|
||||
exports.infiniteQueryBehavior = infiniteQueryBehavior;
|
||||
|
||||
//# sourceMappingURL=infiniteQueryBehavior.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"infiniteQueryBehavior.cjs","names":["ensureQueryFn","addToStart","addToEnd"],"sources":["../../src/infiniteQueryBehavior.ts"],"sourcesContent":["import {\n addConsumeAwareSignal,\n addToEnd,\n addToStart,\n ensureQueryFn,\n} from './utils'\nimport type { QueryBehavior } from './query'\nimport type {\n InfiniteData,\n InfiniteQueryPageParamsOptions,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\nexport function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(\n pages?: number,\n): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>> {\n return {\n onFetch: (context, query) => {\n const options = context.options as InfiniteQueryPageParamsOptions<TData>\n const direction = context.fetchOptions?.meta?.fetchMore?.direction\n const oldPages = context.state.data?.pages || []\n const oldPageParams = context.state.data?.pageParams || []\n let result: InfiniteData<unknown> = { pages: [], pageParams: [] }\n let currentPage = 0\n\n const fetchFn = async () => {\n let cancelled = false\n const addSignalProperty = (object: unknown) => {\n addConsumeAwareSignal(\n object,\n () => context.signal,\n () => (cancelled = true),\n )\n }\n\n const queryFn = ensureQueryFn(context.options, context.fetchOptions)\n\n // Create function to fetch a page\n const fetchPage = async (\n data: InfiniteData<unknown>,\n param: unknown,\n previous?: boolean,\n ): Promise<InfiniteData<unknown>> => {\n if (cancelled) {\n return Promise.reject(context.signal.reason)\n }\n\n if (param == null && data.pages.length) {\n return Promise.resolve(data)\n }\n\n const createQueryFnContext = () => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<QueryKey, unknown>,\n 'signal'\n > = {\n client: context.client,\n queryKey: context.queryKey,\n pageParam: param,\n direction: previous ? 'backward' : 'forward',\n meta: context.options.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext<QueryKey, unknown>\n }\n\n const queryFnContext = createQueryFnContext()\n\n const page = await queryFn(queryFnContext)\n\n const { maxPages } = context.options\n const addTo = previous ? addToStart : addToEnd\n\n return {\n pages: addTo(data.pages, page, maxPages),\n pageParams: addTo(data.pageParams, param, maxPages),\n }\n }\n\n // fetch next / previous page?\n if (direction && oldPages.length) {\n const previous = direction === 'backward'\n const pageParamFn = previous ? getPreviousPageParam : getNextPageParam\n const oldData = {\n pages: oldPages,\n pageParams: oldPageParams,\n }\n const param = pageParamFn(options, oldData)\n\n result = await fetchPage(oldData, param, previous)\n } else {\n const remainingPages = pages ?? oldPages.length\n\n // Fetch all pages\n do {\n const param =\n currentPage === 0\n ? (oldPageParams[0] ?? options.initialPageParam)\n : getNextPageParam(options, result)\n if (currentPage > 0 && param == null) {\n break\n }\n result = await fetchPage(result, param)\n currentPage++\n } while (currentPage < remainingPages)\n }\n\n return result\n }\n if (context.options.persister) {\n context.fetchFn = () => {\n return context.options.persister?.(\n fetchFn as any,\n {\n client: context.client,\n queryKey: context.queryKey,\n meta: context.options.meta,\n signal: context.signal,\n },\n query,\n )\n }\n } else {\n context.fetchFn = fetchFn\n }\n },\n }\n}\n\nfunction getNextPageParam(\n options: InfiniteQueryPageParamsOptions<any>,\n { pages, pageParams }: InfiniteData<unknown>,\n): unknown | undefined {\n const lastIndex = pages.length - 1\n return pages.length > 0\n ? options.getNextPageParam(\n pages[lastIndex],\n pages,\n pageParams[lastIndex],\n pageParams,\n )\n : undefined\n}\n\nfunction getPreviousPageParam(\n options: InfiniteQueryPageParamsOptions<any>,\n { pages, pageParams }: InfiniteData<unknown>,\n): unknown | undefined {\n return pages.length > 0\n ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)\n : undefined\n}\n\n/**\n * Checks if there is a next page.\n Line truncated
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { A as InfiniteData, V as InfiniteQueryPageParamsOptions, er as QueryBehavior } from "./hydration-DwR10Hi-.cjs";
|
||||
//#region src/infiniteQueryBehavior.d.ts
|
||||
declare function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(pages?: number): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>>;
|
||||
/**
|
||||
* Checks if there is a next page.
|
||||
*/
|
||||
declare function hasNextPage(options: InfiniteQueryPageParamsOptions<any, any>, data?: InfiniteData<unknown>): boolean;
|
||||
/**
|
||||
* Checks if there is a previous page.
|
||||
*/
|
||||
declare function hasPreviousPage(options: InfiniteQueryPageParamsOptions<any, any>, data?: InfiniteData<unknown>): boolean;
|
||||
//#endregion
|
||||
export { hasNextPage, hasPreviousPage, infiniteQueryBehavior };
|
||||
//# sourceMappingURL=infiniteQueryBehavior.d.cts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"infiniteQueryBehavior.d.cts","names":[],"sources":["../../src/infiniteQueryBehavior.ts"],"mappings":";;iBAegB,sBAAsB,cAAc,QAAQ,OAAO,YACjE,iBACC,cAAc,cAAc,QAAQ,aAAa,OAAO;;;;iBA6I3C,YACd,SAAS,0CACT,OAAO;;;;iBASO,gBACd,SAAS,0CACT,OAAO"}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { A as InfiniteData, V as InfiniteQueryPageParamsOptions, er as QueryBehavior } from "./hydration-Cq7QYAzB.js";
|
||||
//#region src/infiniteQueryBehavior.d.ts
|
||||
declare function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(pages?: number): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>>;
|
||||
/**
|
||||
* Checks if there is a next page.
|
||||
*/
|
||||
declare function hasNextPage(options: InfiniteQueryPageParamsOptions<any, any>, data?: InfiniteData<unknown>): boolean;
|
||||
/**
|
||||
* Checks if there is a previous page.
|
||||
*/
|
||||
declare function hasPreviousPage(options: InfiniteQueryPageParamsOptions<any, any>, data?: InfiniteData<unknown>): boolean;
|
||||
//#endregion
|
||||
export { hasNextPage, hasPreviousPage, infiniteQueryBehavior };
|
||||
//# sourceMappingURL=infiniteQueryBehavior.d.ts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"infiniteQueryBehavior.d.ts","names":[],"sources":["../../src/infiniteQueryBehavior.ts"],"mappings":";;iBAegB,sBAAsB,cAAc,QAAQ,OAAO,YACjE,iBACC,cAAc,cAAc,QAAQ,aAAa,OAAO;;;;iBA6I3C,YACd,SAAS,0CACT,OAAO;;;;iBASO,gBACd,SAAS,0CACT,OAAO"}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
import { addConsumeAwareSignal, addToEnd, addToStart, ensureQueryFn } from "./utils.js";
|
||||
//#region src/infiniteQueryBehavior.ts
|
||||
function infiniteQueryBehavior(pages) {
|
||||
return { onFetch: (context, query) => {
|
||||
var _context$fetchOptions, _context$state$data, _context$state$data2;
|
||||
const options = context.options;
|
||||
const direction = (_context$fetchOptions = context.fetchOptions) === null || _context$fetchOptions === void 0 || (_context$fetchOptions = _context$fetchOptions.meta) === null || _context$fetchOptions === void 0 || (_context$fetchOptions = _context$fetchOptions.fetchMore) === null || _context$fetchOptions === void 0 ? void 0 : _context$fetchOptions.direction;
|
||||
const oldPages = ((_context$state$data = context.state.data) === null || _context$state$data === void 0 ? void 0 : _context$state$data.pages) || [];
|
||||
const oldPageParams = ((_context$state$data2 = context.state.data) === null || _context$state$data2 === void 0 ? void 0 : _context$state$data2.pageParams) || [];
|
||||
let result = {
|
||||
pages: [],
|
||||
pageParams: []
|
||||
};
|
||||
let currentPage = 0;
|
||||
const fetchFn = async () => {
|
||||
let cancelled = false;
|
||||
const addSignalProperty = (object) => {
|
||||
addConsumeAwareSignal(object, () => context.signal, () => cancelled = true);
|
||||
};
|
||||
const queryFn = ensureQueryFn(context.options, context.fetchOptions);
|
||||
const fetchPage = async (data, param, previous) => {
|
||||
if (cancelled) return Promise.reject(context.signal.reason);
|
||||
if (param == null && data.pages.length) return Promise.resolve(data);
|
||||
const createQueryFnContext = () => {
|
||||
const queryFnContext = {
|
||||
client: context.client,
|
||||
queryKey: context.queryKey,
|
||||
pageParam: param,
|
||||
direction: previous ? "backward" : "forward",
|
||||
meta: context.options.meta
|
||||
};
|
||||
addSignalProperty(queryFnContext);
|
||||
return queryFnContext;
|
||||
};
|
||||
const queryFnContext = createQueryFnContext();
|
||||
const page = await queryFn(queryFnContext);
|
||||
const { maxPages } = context.options;
|
||||
const addTo = previous ? addToStart : addToEnd;
|
||||
return {
|
||||
pages: addTo(data.pages, page, maxPages),
|
||||
pageParams: addTo(data.pageParams, param, maxPages)
|
||||
};
|
||||
};
|
||||
if (direction && oldPages.length) {
|
||||
const previous = direction === "backward";
|
||||
const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
|
||||
const oldData = {
|
||||
pages: oldPages,
|
||||
pageParams: oldPageParams
|
||||
};
|
||||
result = await fetchPage(oldData, pageParamFn(options, oldData), previous);
|
||||
} else {
|
||||
const remainingPages = pages ?? oldPages.length;
|
||||
do {
|
||||
const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);
|
||||
if (currentPage > 0 && param == null) break;
|
||||
result = await fetchPage(result, param);
|
||||
currentPage++;
|
||||
} while (currentPage < remainingPages);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
if (context.options.persister) context.fetchFn = () => {
|
||||
var _context$options$pers, _context$options;
|
||||
return (_context$options$pers = (_context$options = context.options).persister) === null || _context$options$pers === void 0 ? void 0 : _context$options$pers.call(_context$options, fetchFn, {
|
||||
client: context.client,
|
||||
queryKey: context.queryKey,
|
||||
meta: context.options.meta,
|
||||
signal: context.signal
|
||||
}, query);
|
||||
};
|
||||
else context.fetchFn = fetchFn;
|
||||
} };
|
||||
}
|
||||
function getNextPageParam(options, { pages, pageParams }) {
|
||||
const lastIndex = pages.length - 1;
|
||||
return pages.length > 0 ? options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams) : void 0;
|
||||
}
|
||||
function getPreviousPageParam(options, { pages, pageParams }) {
|
||||
var _options$getPreviousP;
|
||||
return pages.length > 0 ? (_options$getPreviousP = options.getPreviousPageParam) === null || _options$getPreviousP === void 0 ? void 0 : _options$getPreviousP.call(options, pages[0], pages, pageParams[0], pageParams) : void 0;
|
||||
}
|
||||
/**
|
||||
* Checks if there is a next page.
|
||||
*/
|
||||
function hasNextPage(options, data) {
|
||||
if (!data) return false;
|
||||
return getNextPageParam(options, data) != null;
|
||||
}
|
||||
/**
|
||||
* Checks if there is a previous page.
|
||||
*/
|
||||
function hasPreviousPage(options, data) {
|
||||
if (!data || !options.getPreviousPageParam) return false;
|
||||
return getPreviousPageParam(options, data) != null;
|
||||
}
|
||||
//#endregion
|
||||
export { hasNextPage, hasPreviousPage, infiniteQueryBehavior };
|
||||
|
||||
//# sourceMappingURL=infiniteQueryBehavior.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"infiniteQueryBehavior.js","names":[],"sources":["../../src/infiniteQueryBehavior.ts"],"sourcesContent":["import {\n addConsumeAwareSignal,\n addToEnd,\n addToStart,\n ensureQueryFn,\n} from './utils'\nimport type { QueryBehavior } from './query'\nimport type {\n InfiniteData,\n InfiniteQueryPageParamsOptions,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\nexport function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(\n pages?: number,\n): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>> {\n return {\n onFetch: (context, query) => {\n const options = context.options as InfiniteQueryPageParamsOptions<TData>\n const direction = context.fetchOptions?.meta?.fetchMore?.direction\n const oldPages = context.state.data?.pages || []\n const oldPageParams = context.state.data?.pageParams || []\n let result: InfiniteData<unknown> = { pages: [], pageParams: [] }\n let currentPage = 0\n\n const fetchFn = async () => {\n let cancelled = false\n const addSignalProperty = (object: unknown) => {\n addConsumeAwareSignal(\n object,\n () => context.signal,\n () => (cancelled = true),\n )\n }\n\n const queryFn = ensureQueryFn(context.options, context.fetchOptions)\n\n // Create function to fetch a page\n const fetchPage = async (\n data: InfiniteData<unknown>,\n param: unknown,\n previous?: boolean,\n ): Promise<InfiniteData<unknown>> => {\n if (cancelled) {\n return Promise.reject(context.signal.reason)\n }\n\n if (param == null && data.pages.length) {\n return Promise.resolve(data)\n }\n\n const createQueryFnContext = () => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<QueryKey, unknown>,\n 'signal'\n > = {\n client: context.client,\n queryKey: context.queryKey,\n pageParam: param,\n direction: previous ? 'backward' : 'forward',\n meta: context.options.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext<QueryKey, unknown>\n }\n\n const queryFnContext = createQueryFnContext()\n\n const page = await queryFn(queryFnContext)\n\n const { maxPages } = context.options\n const addTo = previous ? addToStart : addToEnd\n\n return {\n pages: addTo(data.pages, page, maxPages),\n pageParams: addTo(data.pageParams, param, maxPages),\n }\n }\n\n // fetch next / previous page?\n if (direction && oldPages.length) {\n const previous = direction === 'backward'\n const pageParamFn = previous ? getPreviousPageParam : getNextPageParam\n const oldData = {\n pages: oldPages,\n pageParams: oldPageParams,\n }\n const param = pageParamFn(options, oldData)\n\n result = await fetchPage(oldData, param, previous)\n } else {\n const remainingPages = pages ?? oldPages.length\n\n // Fetch all pages\n do {\n const param =\n currentPage === 0\n ? (oldPageParams[0] ?? options.initialPageParam)\n : getNextPageParam(options, result)\n if (currentPage > 0 && param == null) {\n break\n }\n result = await fetchPage(result, param)\n currentPage++\n } while (currentPage < remainingPages)\n }\n\n return result\n }\n if (context.options.persister) {\n context.fetchFn = () => {\n return context.options.persister?.(\n fetchFn as any,\n {\n client: context.client,\n queryKey: context.queryKey,\n meta: context.options.meta,\n signal: context.signal,\n },\n query,\n )\n }\n } else {\n context.fetchFn = fetchFn\n }\n },\n }\n}\n\nfunction getNextPageParam(\n options: InfiniteQueryPageParamsOptions<any>,\n { pages, pageParams }: InfiniteData<unknown>,\n): unknown | undefined {\n const lastIndex = pages.length - 1\n return pages.length > 0\n ? options.getNextPageParam(\n pages[lastIndex],\n pages,\n pageParams[lastIndex],\n pageParams,\n )\n : undefined\n}\n\nfunction getPreviousPageParam(\n options: InfiniteQueryPageParamsOptions<any>,\n { pages, pageParams }: InfiniteData<unknown>,\n): unknown | undefined {\n return pages.length > 0\n ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)\n : undefined\n}\n\n/**\n * Checks if there is a next page.\n */\nexport function hasNextPage(\n optiLine truncated
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs");
|
||||
const require_queryObserver = require("./queryObserver.cjs");
|
||||
//#region src/infiniteQueryObserver.ts
|
||||
/**
|
||||
* An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
|
||||
* between infinite queries. It augments the base `QueryObserverResult` with
|
||||
* infinite-query-specific fields and methods, such as `hasNextPage` and
|
||||
* `fetchNextPage`, and is the primitive that framework adapters (e.g.
|
||||
* `useInfiniteQuery`) build their hooks on top of.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const observer = new InfiniteQueryObserver(queryClient, {
|
||||
* queryKey: ['projects'],
|
||||
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
|
||||
* initialPageParam: 0,
|
||||
* getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
* })
|
||||
*
|
||||
* const unsubscribe = observer.subscribe((result) => console.log(result))
|
||||
* ```
|
||||
*/
|
||||
var InfiniteQueryObserver = class extends require_queryObserver.QueryObserver {
|
||||
constructor(client, options) {
|
||||
super(client, options);
|
||||
}
|
||||
bindMethods() {
|
||||
super.bindMethods();
|
||||
this.fetchNextPage = this.fetchNextPage.bind(this);
|
||||
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
|
||||
}
|
||||
/**
|
||||
* Updates the observer's options. Behaves the same as
|
||||
* `QueryObserver.setOptions`, additionally marking the options as
|
||||
* belonging to an infinite query before delegating to the base
|
||||
* implementation.
|
||||
*/
|
||||
setOptions(options) {
|
||||
options._type = "infinite";
|
||||
super.setOptions(options);
|
||||
}
|
||||
/**
|
||||
* The infinite-query counterpart of {@link QueryObserver#getOptimisticResult}, marking the
|
||||
* options as an infinite query before delegating to it. Called by framework adapters (e.g.
|
||||
* `useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`
|
||||
* synchronously.
|
||||
*/
|
||||
getOptimisticResult(options) {
|
||||
options._type = "infinite";
|
||||
return super.getOptimisticResult(options);
|
||||
}
|
||||
/**
|
||||
* Fetches the next page of the infinite query and returns a promise that
|
||||
* resolves with the resulting `InfiniteQueryObserverResult`. The page
|
||||
* param used for the fetch is determined by `getNextPageParam`, which
|
||||
* receives the current pages/page params and whose result also determines
|
||||
* `hasNextPage`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const { hasNextPage } = observer.getCurrentResult()
|
||||
*
|
||||
* if (hasNextPage) {
|
||||
* await observer.fetchNextPage()
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @see {@link InfiniteQueryObserver#fetchPreviousPage}
|
||||
*/
|
||||
fetchNextPage(options) {
|
||||
return this.fetch({
|
||||
...options,
|
||||
meta: { fetchMore: { direction: "forward" } }
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Fetches the previous page of the infinite query and returns a promise
|
||||
* that resolves with the resulting `InfiniteQueryObserverResult`. The page
|
||||
* param used for the fetch is determined by `getPreviousPageParam`, which
|
||||
* receives the current pages/page params and whose result also determines
|
||||
* `hasPreviousPage`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const { hasPreviousPage } = observer.getCurrentResult()
|
||||
*
|
||||
* if (hasPreviousPage) {
|
||||
* await observer.fetchPreviousPage()
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @see {@link InfiniteQueryObserver#fetchNextPage}
|
||||
*/
|
||||
fetchPreviousPage(options) {
|
||||
return this.fetch({
|
||||
...options,
|
||||
meta: { fetchMore: { direction: "backward" } }
|
||||
});
|
||||
}
|
||||
createResult(query, options) {
|
||||
var _state$fetchMeta;
|
||||
const { state } = query;
|
||||
const parentResult = super.createResult(query, options);
|
||||
const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
|
||||
const fetchDirection = (_state$fetchMeta = state.fetchMeta) === null || _state$fetchMeta === void 0 || (_state$fetchMeta = _state$fetchMeta.fetchMore) === null || _state$fetchMeta === void 0 ? void 0 : _state$fetchMeta.direction;
|
||||
const isFetchNextPageError = isError && fetchDirection === "forward";
|
||||
const isFetchingNextPage = isFetching && fetchDirection === "forward";
|
||||
const isFetchPreviousPageError = isError && fetchDirection === "backward";
|
||||
const isFetchingPreviousPage = isFetching && fetchDirection === "backward";
|
||||
return {
|
||||
...parentResult,
|
||||
fetchNextPage: this.fetchNextPage,
|
||||
fetchPreviousPage: this.fetchPreviousPage,
|
||||
hasNextPage: require_infiniteQueryBehavior.hasNextPage(options, state.data),
|
||||
hasPreviousPage: require_infiniteQueryBehavior.hasPreviousPage(options, state.data),
|
||||
isFetchNextPageError,
|
||||
isFetchingNextPage,
|
||||
isFetchPreviousPageError,
|
||||
isFetchingPreviousPage,
|
||||
isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
|
||||
isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
|
||||
};
|
||||
}
|
||||
};
|
||||
//#endregion
|
||||
exports.InfiniteQueryObserver = InfiniteQueryObserver;
|
||||
|
||||
//# sourceMappingURL=infiniteQueryObserver.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"infiniteQueryObserver.cjs","names":["QueryObserver","hasNextPage","hasPreviousPage"],"sources":["../../src/infiniteQueryObserver.ts"],"sourcesContent":["import { QueryObserver } from './queryObserver'\nimport { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior'\nimport type { Subscribable } from './subscribable'\nimport type {\n DefaultError,\n DefaultedInfiniteQueryObserverOptions,\n FetchNextPageOptions,\n FetchPreviousPageOptions,\n InfiniteData,\n InfiniteQueryObserverBaseResult,\n InfiniteQueryObserverOptions,\n InfiniteQueryObserverResult,\n QueryKey,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Query } from './query'\n\ntype InfiniteQueryObserverListener<TData, TError> = (\n result: InfiniteQueryObserverResult<TData, TError>,\n) => void\n\n/**\n * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch\n * between infinite queries. It augments the base `QueryObserverResult` with\n * infinite-query-specific fields and methods, such as `hasNextPage` and\n * `fetchNextPage`, and is the primitive that framework adapters (e.g.\n * `useInfiniteQuery`) build their hooks on top of.\n *\n * @example\n * ```ts\n * const observer = new InfiniteQueryObserver(queryClient, {\n * queryKey: ['projects'],\n * queryFn: ({ pageParam }) => fetchProjects(pageParam),\n * initialPageParam: 0,\n * getNextPageParam: (lastPage) => lastPage.nextCursor,\n * })\n *\n * const unsubscribe = observer.subscribe((result) => console.log(result))\n * ```\n */\nexport class InfiniteQueryObserver<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> extends QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n> {\n // Type override\n subscribe!: Subscribable<\n InfiniteQueryObserverListener<TData, TError>\n >['subscribe']\n\n // Type override\n getCurrentResult!: ReplaceReturnType<\n QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n >['getCurrentResult'],\n InfiniteQueryObserverResult<TData, TError>\n >\n\n // Type override\n protected fetch!: ReplaceReturnType<\n QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n >['fetch'],\n Promise<InfiniteQueryObserverResult<TData, TError>>\n >\n\n constructor(\n client: QueryClient,\n options: InfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ) {\n super(client, options)\n }\n\n protected bindMethods(): void {\n super.bindMethods()\n this.fetchNextPage = this.fetchNextPage.bind(this)\n this.fetchPreviousPage = this.fetchPreviousPage.bind(this)\n }\n\n /**\n * Updates the observer's options. Behaves the same as\n * `QueryObserver.setOptions`, additionally marking the options as\n * belonging to an infinite query before delegating to the base\n * implementation.\n */\n setOptions(\n options: InfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): void {\n options._type = 'infinite'\n super.setOptions(options)\n }\n\n /**\n * The infinite-query counterpart of {@link QueryObserver#getOptimisticResult}, marking the\n * options as an infinite query before delegating to it. Called by framework adapters (e.g.\n * `useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`\n * synchronously.\n */\n getOptimisticResult(\n options: DefaultedInfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): InfiniteQueryObserverResult<TData, TError> {\n options._type = 'infinite'\n return super.getOptimisticResult(options) as InfiniteQueryObserverResult<\n TData,\n TError\n >\n }\n\n /**\n * Fetches the next page of the infinite query and returns a promise that\n * resolves with the resulting `InfiniteQueryObserverResult`. The page\n * param used for the fetch is determined by `getNextPageParam`, which\n * receives the current pages/page params and whose result also determines\n * `hasNextPage`.\n *\n * @example\n * ```ts\n * const { hasNextPage } = observer.getCurrentResult()\n *\n * if (hasNextPage) {\n * await observer.fetchNextPage()\n * }\n * ```\n *\n * @see {@link InfiniteQueryObserver#fetchPreviousPage}\n */\n fetchNextPage(\n options?: FetchNextPageOptions,\n ): Promise<InfiniteQueryObserverResult<TData, TError>> {\n return this.fetch({\n ...options,\n meta: {\n fetchMore: { direction: 'forward' },\n },\n })\n }\n\n /**\n * Fetches the previous page of Line truncated
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
import { t as Subscribable } from "./subscribable-CbifVTKz.cjs";
|
||||
import { $n as Query, A as InfiniteData, C as FetchPreviousPageOptions, Ct as QueryKey, F as InfiniteQueryObserverOptions, S as FetchNextPageOptions, f as DefaultError, m as DefaultedInfiniteQueryObserverOptions, on as QueryClient, rr as QueryObserver, z as InfiniteQueryObserverResult } from "./hydration-DwR10Hi-.cjs";
|
||||
//#region src/infiniteQueryObserver.d.ts
|
||||
type InfiniteQueryObserverListener<TData, TError> = (result: InfiniteQueryObserverResult<TData, TError>) => void;
|
||||
/**
|
||||
* An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
|
||||
* between infinite queries. It augments the base `QueryObserverResult` with
|
||||
* infinite-query-specific fields and methods, such as `hasNextPage` and
|
||||
* `fetchNextPage`, and is the primitive that framework adapters (e.g.
|
||||
* `useInfiniteQuery`) build their hooks on top of.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const observer = new InfiniteQueryObserver(queryClient, {
|
||||
* queryKey: ['projects'],
|
||||
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
|
||||
* initialPageParam: 0,
|
||||
* getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
* })
|
||||
*
|
||||
* const unsubscribe = observer.subscribe((result) => console.log(result))
|
||||
* ```
|
||||
*/
|
||||
declare class InfiniteQueryObserver<TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> extends QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey> {
|
||||
subscribe: Subscribable<InfiniteQueryObserverListener<TData, TError>>['subscribe'];
|
||||
getCurrentResult: ReplaceReturnType<QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>['getCurrentResult'], InfiniteQueryObserverResult<TData, TError>>;
|
||||
protected fetch: ReplaceReturnType<QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>['fetch'], Promise<InfiniteQueryObserverResult<TData, TError>>>;
|
||||
constructor(client: QueryClient, options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>);
|
||||
protected bindMethods(): void;
|
||||
/**
|
||||
* Updates the observer's options. Behaves the same as
|
||||
* `QueryObserver.setOptions`, additionally marking the options as
|
||||
* belonging to an infinite query before delegating to the base
|
||||
* implementation.
|
||||
*/
|
||||
setOptions(options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): void;
|
||||
/**
|
||||
* The infinite-query counterpart of {@link QueryObserver#getOptimisticResult}, marking the
|
||||
* options as an infinite query before delegating to it. Called by framework adapters (e.g.
|
||||
* `useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`
|
||||
* synchronously.
|
||||
*/
|
||||
getOptimisticResult(options: DefaultedInfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserverResult<TData, TError>;
|
||||
/**
|
||||
* Fetches the next page of the infinite query and returns a promise that
|
||||
* resolves with the resulting `InfiniteQueryObserverResult`. The page
|
||||
* param used for the fetch is determined by `getNextPageParam`, which
|
||||
* receives the current pages/page params and whose result also determines
|
||||
* `hasNextPage`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const { hasNextPage } = observer.getCurrentResult()
|
||||
*
|
||||
* if (hasNextPage) {
|
||||
* await observer.fetchNextPage()
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @see {@link InfiniteQueryObserver#fetchPreviousPage}
|
||||
*/
|
||||
fetchNextPage(options?: FetchNextPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
|
||||
/**
|
||||
* Fetches the previous page of the infinite query and returns a promise
|
||||
* that resolves with the resulting `InfiniteQueryObserverResult`. The page
|
||||
* param used for the fetch is determined by `getPreviousPageParam`, which
|
||||
* receives the current pages/page params and whose result also determines
|
||||
* `hasPreviousPage`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const { hasPreviousPage } = observer.getCurrentResult()
|
||||
*
|
||||
* if (hasPreviousPage) {
|
||||
* await observer.fetchPreviousPage()
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @see {@link InfiniteQueryObserver#fetchNextPage}
|
||||
*/
|
||||
fetchPreviousPage(options?: FetchPreviousPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
|
||||
protected createResult(query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>, options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserverResult<TData, TError>;
|
||||
}
|
||||
type ReplaceReturnType<TFunction extends (...args: Array<any>) => unknown, TReturn> = (...args: Parameters<TFunction>) => TReturn;
|
||||
//#endregion
|
||||
export { InfiniteQueryObserver };
|
||||
//# sourceMappingURL=infiniteQueryObserver.d.cts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"infiniteQueryObserver.d.cts","names":[],"sources":["../../src/infiniteQueryObserver.ts"],"mappings":";;;KAiBK,8BAA8B,OAAO,WACxC,QAAQ,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;;cAsBhC,sBACX,wBACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,8BACQ,cACR,cACA,QACA,OACA,aAAa,cAAc,aAC3B;EAGA,WAAY,aACV,8BAA8B,OAAO;EAIvC,kBAAmB,kBACjB,cACE,cACA,QACA,OACA,aAAa,cAAc,aAC3B,gCAEF,4BAA4B,OAAO;YAI3B,OAAQ,kBAChB,cACE,cACA,QACA,OACA,aAAa,cAAc,aAC3B,qBAEF,QAAQ,4BAA4B,OAAO;EAI3C,YAAA,QAAQ,aACR,SAAS,6BACP,cACA,QACA,OACA,WACA;YAMM;;;;;;;EAYV,WACE,SAAS,6BACP,cACA,QACA,OACA,WACA;;;;;;;EAaJ,oBACE,SAAS,sCACP,cACA,QACA,OACA,WACA,cAED,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;EA0BtC,cACE,UAAU,uBACT,QAAQ,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;EA2B9C,kBACE,UAAU,2BACT,QAAQ,4BAA4B,OAAO;YASpC,aACR,OAAO,MACL,cACA,QACA,aAAa,cAAc,aAC3B,YAEF,SAAS,6BACP,cACA,QACA,OACA,WACA,cAED,4BAA4B,OAAO;;KAiCnC,kBACH,sBAAsB,MAAM,wBAC5B,eACM,MAAM,WAAW,eAAe"}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
import { t as Subscribable } from "./subscribable-CbifVTKz.js";
|
||||
import { $n as Query, A as InfiniteData, C as FetchPreviousPageOptions, Ct as QueryKey, F as InfiniteQueryObserverOptions, S as FetchNextPageOptions, f as DefaultError, m as DefaultedInfiniteQueryObserverOptions, on as QueryClient, rr as QueryObserver, z as InfiniteQueryObserverResult } from "./hydration-Cq7QYAzB.js";
|
||||
//#region src/infiniteQueryObserver.d.ts
|
||||
type InfiniteQueryObserverListener<TData, TError> = (result: InfiniteQueryObserverResult<TData, TError>) => void;
|
||||
/**
|
||||
* An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
|
||||
* between infinite queries. It augments the base `QueryObserverResult` with
|
||||
* infinite-query-specific fields and methods, such as `hasNextPage` and
|
||||
* `fetchNextPage`, and is the primitive that framework adapters (e.g.
|
||||
* `useInfiniteQuery`) build their hooks on top of.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const observer = new InfiniteQueryObserver(queryClient, {
|
||||
* queryKey: ['projects'],
|
||||
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
|
||||
* initialPageParam: 0,
|
||||
* getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
* })
|
||||
*
|
||||
* const unsubscribe = observer.subscribe((result) => console.log(result))
|
||||
* ```
|
||||
*/
|
||||
declare class InfiniteQueryObserver<TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> extends QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey> {
|
||||
subscribe: Subscribable<InfiniteQueryObserverListener<TData, TError>>['subscribe'];
|
||||
getCurrentResult: ReplaceReturnType<QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>['getCurrentResult'], InfiniteQueryObserverResult<TData, TError>>;
|
||||
protected fetch: ReplaceReturnType<QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>['fetch'], Promise<InfiniteQueryObserverResult<TData, TError>>>;
|
||||
constructor(client: QueryClient, options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>);
|
||||
protected bindMethods(): void;
|
||||
/**
|
||||
* Updates the observer's options. Behaves the same as
|
||||
* `QueryObserver.setOptions`, additionally marking the options as
|
||||
* belonging to an infinite query before delegating to the base
|
||||
* implementation.
|
||||
*/
|
||||
setOptions(options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): void;
|
||||
/**
|
||||
* The infinite-query counterpart of {@link QueryObserver#getOptimisticResult}, marking the
|
||||
* options as an infinite query before delegating to it. Called by framework adapters (e.g.
|
||||
* `useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`
|
||||
* synchronously.
|
||||
*/
|
||||
getOptimisticResult(options: DefaultedInfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserverResult<TData, TError>;
|
||||
/**
|
||||
* Fetches the next page of the infinite query and returns a promise that
|
||||
* resolves with the resulting `InfiniteQueryObserverResult`. The page
|
||||
* param used for the fetch is determined by `getNextPageParam`, which
|
||||
* receives the current pages/page params and whose result also determines
|
||||
* `hasNextPage`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const { hasNextPage } = observer.getCurrentResult()
|
||||
*
|
||||
* if (hasNextPage) {
|
||||
* await observer.fetchNextPage()
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @see {@link InfiniteQueryObserver#fetchPreviousPage}
|
||||
*/
|
||||
fetchNextPage(options?: FetchNextPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
|
||||
/**
|
||||
* Fetches the previous page of the infinite query and returns a promise
|
||||
* that resolves with the resulting `InfiniteQueryObserverResult`. The page
|
||||
* param used for the fetch is determined by `getPreviousPageParam`, which
|
||||
* receives the current pages/page params and whose result also determines
|
||||
* `hasPreviousPage`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const { hasPreviousPage } = observer.getCurrentResult()
|
||||
*
|
||||
* if (hasPreviousPage) {
|
||||
* await observer.fetchPreviousPage()
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @see {@link InfiniteQueryObserver#fetchNextPage}
|
||||
*/
|
||||
fetchPreviousPage(options?: FetchPreviousPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
|
||||
protected createResult(query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>, options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserverResult<TData, TError>;
|
||||
}
|
||||
type ReplaceReturnType<TFunction extends (...args: Array<any>) => unknown, TReturn> = (...args: Parameters<TFunction>) => TReturn;
|
||||
//#endregion
|
||||
export { InfiniteQueryObserver };
|
||||
//# sourceMappingURL=infiniteQueryObserver.d.ts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"infiniteQueryObserver.d.ts","names":[],"sources":["../../src/infiniteQueryObserver.ts"],"mappings":";;;KAiBK,8BAA8B,OAAO,WACxC,QAAQ,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;;cAsBhC,sBACX,wBACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,8BACQ,cACR,cACA,QACA,OACA,aAAa,cAAc,aAC3B;EAGA,WAAY,aACV,8BAA8B,OAAO;EAIvC,kBAAmB,kBACjB,cACE,cACA,QACA,OACA,aAAa,cAAc,aAC3B,gCAEF,4BAA4B,OAAO;YAI3B,OAAQ,kBAChB,cACE,cACA,QACA,OACA,aAAa,cAAc,aAC3B,qBAEF,QAAQ,4BAA4B,OAAO;EAI3C,YAAA,QAAQ,aACR,SAAS,6BACP,cACA,QACA,OACA,WACA;YAMM;;;;;;;EAYV,WACE,SAAS,6BACP,cACA,QACA,OACA,WACA;;;;;;;EAaJ,oBACE,SAAS,sCACP,cACA,QACA,OACA,WACA,cAED,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;EA0BtC,cACE,UAAU,uBACT,QAAQ,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;EA2B9C,kBACE,UAAU,2BACT,QAAQ,4BAA4B,OAAO;YASpC,aACR,OAAO,MACL,cACA,QACA,aAAa,cAAc,aAC3B,YAEF,SAAS,6BACP,cACA,QACA,OACA,WACA,cAED,4BAA4B,OAAO;;KAiCnC,kBACH,sBAAsB,MAAM,wBAC5B,eACM,MAAM,WAAW,eAAe"}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
import { hasNextPage, hasPreviousPage } from "./infiniteQueryBehavior.js";
|
||||
import { QueryObserver } from "./queryObserver.js";
|
||||
//#region src/infiniteQueryObserver.ts
|
||||
/**
|
||||
* An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
|
||||
* between infinite queries. It augments the base `QueryObserverResult` with
|
||||
* infinite-query-specific fields and methods, such as `hasNextPage` and
|
||||
* `fetchNextPage`, and is the primitive that framework adapters (e.g.
|
||||
* `useInfiniteQuery`) build their hooks on top of.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const observer = new InfiniteQueryObserver(queryClient, {
|
||||
* queryKey: ['projects'],
|
||||
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
|
||||
* initialPageParam: 0,
|
||||
* getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
* })
|
||||
*
|
||||
* const unsubscribe = observer.subscribe((result) => console.log(result))
|
||||
* ```
|
||||
*/
|
||||
var InfiniteQueryObserver = class extends QueryObserver {
|
||||
constructor(client, options) {
|
||||
super(client, options);
|
||||
}
|
||||
bindMethods() {
|
||||
super.bindMethods();
|
||||
this.fetchNextPage = this.fetchNextPage.bind(this);
|
||||
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
|
||||
}
|
||||
/**
|
||||
* Updates the observer's options. Behaves the same as
|
||||
* `QueryObserver.setOptions`, additionally marking the options as
|
||||
* belonging to an infinite query before delegating to the base
|
||||
* implementation.
|
||||
*/
|
||||
setOptions(options) {
|
||||
options._type = "infinite";
|
||||
super.setOptions(options);
|
||||
}
|
||||
/**
|
||||
* The infinite-query counterpart of {@link QueryObserver#getOptimisticResult}, marking the
|
||||
* options as an infinite query before delegating to it. Called by framework adapters (e.g.
|
||||
* `useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`
|
||||
* synchronously.
|
||||
*/
|
||||
getOptimisticResult(options) {
|
||||
options._type = "infinite";
|
||||
return super.getOptimisticResult(options);
|
||||
}
|
||||
/**
|
||||
* Fetches the next page of the infinite query and returns a promise that
|
||||
* resolves with the resulting `InfiniteQueryObserverResult`. The page
|
||||
* param used for the fetch is determined by `getNextPageParam`, which
|
||||
* receives the current pages/page params and whose result also determines
|
||||
* `hasNextPage`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const { hasNextPage } = observer.getCurrentResult()
|
||||
*
|
||||
* if (hasNextPage) {
|
||||
* await observer.fetchNextPage()
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @see {@link InfiniteQueryObserver#fetchPreviousPage}
|
||||
*/
|
||||
fetchNextPage(options) {
|
||||
return this.fetch({
|
||||
...options,
|
||||
meta: { fetchMore: { direction: "forward" } }
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Fetches the previous page of the infinite query and returns a promise
|
||||
* that resolves with the resulting `InfiniteQueryObserverResult`. The page
|
||||
* param used for the fetch is determined by `getPreviousPageParam`, which
|
||||
* receives the current pages/page params and whose result also determines
|
||||
* `hasPreviousPage`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const { hasPreviousPage } = observer.getCurrentResult()
|
||||
*
|
||||
* if (hasPreviousPage) {
|
||||
* await observer.fetchPreviousPage()
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @see {@link InfiniteQueryObserver#fetchNextPage}
|
||||
*/
|
||||
fetchPreviousPage(options) {
|
||||
return this.fetch({
|
||||
...options,
|
||||
meta: { fetchMore: { direction: "backward" } }
|
||||
});
|
||||
}
|
||||
createResult(query, options) {
|
||||
var _state$fetchMeta;
|
||||
const { state } = query;
|
||||
const parentResult = super.createResult(query, options);
|
||||
const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
|
||||
const fetchDirection = (_state$fetchMeta = state.fetchMeta) === null || _state$fetchMeta === void 0 || (_state$fetchMeta = _state$fetchMeta.fetchMore) === null || _state$fetchMeta === void 0 ? void 0 : _state$fetchMeta.direction;
|
||||
const isFetchNextPageError = isError && fetchDirection === "forward";
|
||||
const isFetchingNextPage = isFetching && fetchDirection === "forward";
|
||||
const isFetchPreviousPageError = isError && fetchDirection === "backward";
|
||||
const isFetchingPreviousPage = isFetching && fetchDirection === "backward";
|
||||
return {
|
||||
...parentResult,
|
||||
fetchNextPage: this.fetchNextPage,
|
||||
fetchPreviousPage: this.fetchPreviousPage,
|
||||
hasNextPage: hasNextPage(options, state.data),
|
||||
hasPreviousPage: hasPreviousPage(options, state.data),
|
||||
isFetchNextPageError,
|
||||
isFetchingNextPage,
|
||||
isFetchPreviousPageError,
|
||||
isFetchingPreviousPage,
|
||||
isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
|
||||
isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
|
||||
};
|
||||
}
|
||||
};
|
||||
//#endregion
|
||||
export { InfiniteQueryObserver };
|
||||
|
||||
//# sourceMappingURL=infiniteQueryObserver.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"infiniteQueryObserver.js","names":[],"sources":["../../src/infiniteQueryObserver.ts"],"sourcesContent":["import { QueryObserver } from './queryObserver'\nimport { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior'\nimport type { Subscribable } from './subscribable'\nimport type {\n DefaultError,\n DefaultedInfiniteQueryObserverOptions,\n FetchNextPageOptions,\n FetchPreviousPageOptions,\n InfiniteData,\n InfiniteQueryObserverBaseResult,\n InfiniteQueryObserverOptions,\n InfiniteQueryObserverResult,\n QueryKey,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Query } from './query'\n\ntype InfiniteQueryObserverListener<TData, TError> = (\n result: InfiniteQueryObserverResult<TData, TError>,\n) => void\n\n/**\n * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch\n * between infinite queries. It augments the base `QueryObserverResult` with\n * infinite-query-specific fields and methods, such as `hasNextPage` and\n * `fetchNextPage`, and is the primitive that framework adapters (e.g.\n * `useInfiniteQuery`) build their hooks on top of.\n *\n * @example\n * ```ts\n * const observer = new InfiniteQueryObserver(queryClient, {\n * queryKey: ['projects'],\n * queryFn: ({ pageParam }) => fetchProjects(pageParam),\n * initialPageParam: 0,\n * getNextPageParam: (lastPage) => lastPage.nextCursor,\n * })\n *\n * const unsubscribe = observer.subscribe((result) => console.log(result))\n * ```\n */\nexport class InfiniteQueryObserver<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> extends QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n> {\n // Type override\n subscribe!: Subscribable<\n InfiniteQueryObserverListener<TData, TError>\n >['subscribe']\n\n // Type override\n getCurrentResult!: ReplaceReturnType<\n QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n >['getCurrentResult'],\n InfiniteQueryObserverResult<TData, TError>\n >\n\n // Type override\n protected fetch!: ReplaceReturnType<\n QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n >['fetch'],\n Promise<InfiniteQueryObserverResult<TData, TError>>\n >\n\n constructor(\n client: QueryClient,\n options: InfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ) {\n super(client, options)\n }\n\n protected bindMethods(): void {\n super.bindMethods()\n this.fetchNextPage = this.fetchNextPage.bind(this)\n this.fetchPreviousPage = this.fetchPreviousPage.bind(this)\n }\n\n /**\n * Updates the observer's options. Behaves the same as\n * `QueryObserver.setOptions`, additionally marking the options as\n * belonging to an infinite query before delegating to the base\n * implementation.\n */\n setOptions(\n options: InfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): void {\n options._type = 'infinite'\n super.setOptions(options)\n }\n\n /**\n * The infinite-query counterpart of {@link QueryObserver#getOptimisticResult}, marking the\n * options as an infinite query before delegating to it. Called by framework adapters (e.g.\n * `useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`\n * synchronously.\n */\n getOptimisticResult(\n options: DefaultedInfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): InfiniteQueryObserverResult<TData, TError> {\n options._type = 'infinite'\n return super.getOptimisticResult(options) as InfiniteQueryObserverResult<\n TData,\n TError\n >\n }\n\n /**\n * Fetches the next page of the infinite query and returns a promise that\n * resolves with the resulting `InfiniteQueryObserverResult`. The page\n * param used for the fetch is determined by `getNextPageParam`, which\n * receives the current pages/page params and whose result also determines\n * `hasNextPage`.\n *\n * @example\n * ```ts\n * const { hasNextPage } = observer.getCurrentResult()\n *\n * if (hasNextPage) {\n * await observer.fetchNextPage()\n * }\n * ```\n *\n * @see {@link InfiniteQueryObserver#fetchPreviousPage}\n */\n fetchNextPage(\n options?: FetchNextPageOptions,\n ): Promise<InfiniteQueryObserverResult<TData, TError>> {\n return this.fetch({\n ...options,\n meta: {\n fetchMore: { direction: 'forward' },\n },\n })\n }\n\n /**\n * Fetches the previous page of the infinite query and returns a promise\n * tLine truncated
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
|
||||
const require_notifyManager = require("./notifyManager.cjs");
|
||||
const require_retryer = require("./retryer.cjs");
|
||||
const require_removable = require("./removable.cjs");
|
||||
const require_classPrivateMethodInitSpec = require("./classPrivateMethodInitSpec-DVhcLejn.cjs");
|
||||
//#region src/mutation.ts
|
||||
var _client = /* @__PURE__ */ new WeakMap();
|
||||
var _observers = /* @__PURE__ */ new WeakMap();
|
||||
var _mutationCache = /* @__PURE__ */ new WeakMap();
|
||||
var _retryer = /* @__PURE__ */ new WeakMap();
|
||||
var _Mutation_brand = /* @__PURE__ */ new WeakSet();
|
||||
/**
|
||||
* Represents a single mutation attempt. A `Mutation` holds the mutation's
|
||||
* options, state (data/error/status), and the `MutationObserver`s currently
|
||||
* subscribed to it.
|
||||
*
|
||||
* Instances are created and managed internally by `MutationCache`; application
|
||||
* code typically interacts with mutations indirectly through `QueryClient` or
|
||||
* a framework hook like `useMutation`. Direct access to a `Mutation` instance
|
||||
* is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const mutationCache = queryClient.getMutationCache()
|
||||
*
|
||||
* const mutation = mutationCache.find({ mutationKey: ['addPost'] })
|
||||
* ```
|
||||
*/
|
||||
var Mutation = class extends require_removable.Removable {
|
||||
constructor(config) {
|
||||
super();
|
||||
require_classPrivateMethodInitSpec._classPrivateMethodInitSpec(this, _Mutation_brand);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _client, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _observers, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _mutationCache, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _retryer, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_client, this, config.client);
|
||||
this.mutationId = config.mutationId;
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_mutationCache, this, config.mutationCache);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_observers, this, []);
|
||||
this.state = config.state || getDefaultState();
|
||||
this.setOptions(config.options);
|
||||
this.scheduleGc();
|
||||
}
|
||||
/** @internal */
|
||||
setOptions(options) {
|
||||
this.options = options;
|
||||
this.updateGcTime(this.options.gcTime);
|
||||
}
|
||||
/**
|
||||
* The `meta` object passed in the mutation's options, if any.
|
||||
*/
|
||||
get meta() {
|
||||
return this.options.meta;
|
||||
}
|
||||
/** @internal */
|
||||
addObserver(observer) {
|
||||
if (!require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).includes(observer)) {
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).push(observer);
|
||||
this.clearGcTimeout();
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).notify({
|
||||
type: "observerAdded",
|
||||
mutation: this,
|
||||
observer
|
||||
});
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
removeObserver(observer) {
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_observers, this, require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).filter((x) => x !== observer));
|
||||
this.scheduleGc();
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).notify({
|
||||
type: "observerRemoved",
|
||||
mutation: this,
|
||||
observer
|
||||
});
|
||||
}
|
||||
optionalRemove() {
|
||||
if (!require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).length) {
|
||||
if (this.state.status === "pending") this.scheduleGc();
|
||||
else require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).remove(this);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Resumes a mutation that is currently paused or was restored from a
|
||||
* dehydrated, still-`pending` state.
|
||||
*
|
||||
* - If this mutation has an active retryer (it paused mid-attempt, e.g. due
|
||||
* to the network mode or scope-based queuing), its retryer is resumed.
|
||||
* - Otherwise, if the mutation's status is still `pending` (e.g. it was
|
||||
* dehydrated while an attempt was in flight and never got a retryer in
|
||||
* this instance), `execute` is called again with the last known variables.
|
||||
* - Otherwise the mutation has already settled and this resolves immediately
|
||||
* without running anything again.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()
|
||||
* const mutation = mutationCache.find({ mutationKey: ['addPost'] })
|
||||
* await mutation?.continue()
|
||||
* ```
|
||||
*
|
||||
* @see {@link Mutation#execute}
|
||||
*/
|
||||
continue() {
|
||||
var _classPrivateFieldGet2$1;
|
||||
return ((_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.continue()) ?? (this.state.status === "pending" ? this.execute(this.state.variables) : Promise.resolve());
|
||||
}
|
||||
/**
|
||||
* Runs the mutation function for the given variables through a retryer, and
|
||||
* drives the mutation's state and lifecycle callbacks through to settlement.
|
||||
*
|
||||
* If this mutation's state is already `pending` when `execute` is called
|
||||
* (i.e. it was restored, still in-flight, from a dehydrated state), the
|
||||
* `onMutate` step is skipped and a `continue` action is dispatched to
|
||||
* unpause it; otherwise a `pending` action is dispatched first, then the
|
||||
* mutation cache's `onMutate` and the mutation's own `onMutate` option are
|
||||
* awaited in that order, and the resulting context is stored.
|
||||
*
|
||||
* The mutation function is then run (subject to `retry`/`retryDelay`/
|
||||
* `networkMode`, and to the mutation cache's scope-based serialization).
|
||||
* On success, the cache's `onSuccess`/`onSettled` callbacks run before the
|
||||
* mutation's own `onSuccess`/`onSettled` options, a `success` action is
|
||||
* dispatched, and the resolved data is returned. On failure, the same
|
||||
* cache-then-option ordering is used for `onError`/`onSettled`, but each of
|
||||
* those four callbacks is individually caught so that a throwing callback
|
||||
* cannot mask the original error; an `error` action is then dispatched and
|
||||
* the original error is re-thrown.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // Called internally by `MutationObserver.mutate` and `Mutation.continue` —
|
||||
* // applications normally trigger mutations through those, not this method.
|
||||
* const data = await mutation.execute(variables)
|
||||
* ```
|
||||
*
|
||||
* @see {@link Mutation#continue}
|
||||
*/
|
||||
async execute(variables) {
|
||||
const onContinue = () => {
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, { type: "continue" });
|
||||
};
|
||||
const mutationFnContext = {
|
||||
client: require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this),
|
||||
meta: this.options.meta,
|
||||
mutationKey: this.options.mutationKey
|
||||
};
|
||||
const retryer = require_classPrivateFieldSet2._classPrivateFieldSet2(_retryer, this, require_retryer.createRetryer({
|
||||
fn: () => {
|
||||
if (!this.options.mutationFn) return Promise.reject(/* @__PURE__ */ new Error("No mutationFn found"));
|
||||
return this.options.mutationFn(variables, mutationFnContext);
|
||||
},
|
||||
onFail: (failureCount, error) => {
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
|
||||
type: "failed",
|
||||
failureCount,
|
||||
error
|
||||
});
|
||||
},
|
||||
onPause: () => {
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, { type: "pause" });
|
||||
},
|
||||
onContinue,
|
||||
retry: this.options.retry ?? 0,
|
||||
retryDelay: this.options.retryDelay,
|
||||
networkMode: this.options.networkMode,
|
||||
canRun: () => require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).canRun(this)
|
||||
}));
|
||||
const restored = this.state.status === "pending";
|
||||
const isPaused = !retryer.canStart();
|
||||
try {
|
||||
var _classPrivateFieldGet3, _classPrivateFieldGet4, _this$options$onSucce, _this$options2, _classPrivateFieldGet5, _classPrivateFieldGet6, _this$options$onSettl, _this$options3;
|
||||
if (restored) onContinue();
|
||||
else {
|
||||
var _this$options$onMutat, _this$options;
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
|
||||
type: "pending",
|
||||
variables,
|
||||
isPaused
|
||||
});
|
||||
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config.onMutate) await require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config.onMutate(variables, this, mutationFnContext);
|
||||
const context = await ((_this$options$onMutat = (_this$options = this.options).onMutate) === null || _this$options$onMutat === void 0 ? void 0 : _this$options$onMutat.call(_this$options, variables, mutationFnContext));
|
||||
if (context !== this.state.context) require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
|
||||
type: "pending",
|
||||
context,
|
||||
variables,
|
||||
isPaused
|
||||
});
|
||||
}
|
||||
const data = await retryer.start();
|
||||
await ((_classPrivateFieldGet3 = (_classPrivateFieldGet4 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config).onSuccess) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.call(_classPrivateFieldGet4, data, variables, this.state.context, this, mutationFnContext));
|
||||
await ((_this$options$onSucce = (_this$options2 = this.options).onSuccess) === null || _this$options$onSucce === void 0 ? void 0 : _this$options$onSucce.call(_this$options2, data, variables, this.state.context, mutationFnContext));
|
||||
await ((_classPrivateFieldGet5 = (_classPrivateFieldGet6 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config).onSettled) === null || _classPrivateFieldGet5 === void 0 ? void 0 : _classPrivateFieldGet5.call(_classPrivateFieldGet6, data, null, this.state.variables, this.state.context, this, mutationFnContext));
|
||||
await ((_this$options$onSettl = (_this$options3 = this.options).onSettled) === null || _this$options$onSettl === void 0 ? void 0 : _this$options$onSettl.call(_this$options3, data, null, variables, this.state.context, mutationFnContext));
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
|
||||
type: "success",
|
||||
data
|
||||
});
|
||||
return data;
|
||||
} catch (error) {
|
||||
try {
|
||||
var _classPrivateFieldGet7, _classPrivateFieldGet8;
|
||||
await ((_classPrivateFieldGet7 = (_classPrivateFieldGet8 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config).onError) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.call(_classPrivateFieldGet8, error, variables, this.state.context, this, mutationFnContext));
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
try {
|
||||
var _this$options$onError, _this$options4;
|
||||
await ((_this$options$onError = (_this$options4 = this.options).onError) === null || _this$options$onError === void 0 ? void 0 : _this$options$onError.call(_this$options4, error, variables, this.state.context, mutationFnContext));
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
try {
|
||||
var _classPrivateFieldGet9, _classPrivateFieldGet10;
|
||||
await ((_classPrivateFieldGet9 = (_classPrivateFieldGet10 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config).onSettled) === null || _classPrivateFieldGet9 === void 0 ? void 0 : _classPrivateFieldGet9.call(_classPrivateFieldGet10, void 0, error, this.state.variables, this.state.context, this, mutationFnContext));
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
try {
|
||||
var _this$options$onSettl2, _this$options5;
|
||||
await ((_this$options$onSettl2 = (_this$options5 = this.options).onSettled) === null || _this$options$onSettl2 === void 0 ? void 0 : _this$options$onSettl2.call(_this$options5, void 0, error, variables, this.state.context, mutationFnContext));
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
|
||||
type: "error",
|
||||
error
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this) === retryer) require_classPrivateFieldSet2._classPrivateFieldSet2(_retryer, this, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).runNext(this);
|
||||
}
|
||||
}
|
||||
};
|
||||
function _dispatch(action) {
|
||||
const reducer = (state) => {
|
||||
switch (action.type) {
|
||||
case "failed": return {
|
||||
...state,
|
||||
failureCount: action.failureCount,
|
||||
failureReason: action.error
|
||||
};
|
||||
case "pause": return {
|
||||
...state,
|
||||
isPaused: true
|
||||
};
|
||||
case "continue": return {
|
||||
...state,
|
||||
isPaused: false
|
||||
};
|
||||
case "pending": return {
|
||||
...state,
|
||||
context: action.context,
|
||||
data: void 0,
|
||||
failureCount: 0,
|
||||
failureReason: null,
|
||||
error: null,
|
||||
isPaused: action.isPaused,
|
||||
status: "pending",
|
||||
variables: action.variables,
|
||||
submittedAt: Date.now()
|
||||
};
|
||||
case "success": return {
|
||||
...state,
|
||||
data: action.data,
|
||||
failureCount: 0,
|
||||
failureReason: null,
|
||||
error: null,
|
||||
status: "success",
|
||||
isPaused: false
|
||||
};
|
||||
case "error": return {
|
||||
...state,
|
||||
data: void 0,
|
||||
error: action.error,
|
||||
failureCount: state.failureCount + 1,
|
||||
failureReason: action.error,
|
||||
isPaused: false,
|
||||
status: "error"
|
||||
};
|
||||
}
|
||||
};
|
||||
this.state = reducer(this.state);
|
||||
require_notifyManager.notifyManager.batch(() => {
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).forEach((observer) => {
|
||||
observer.onMutationUpdate(action);
|
||||
});
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).notify({
|
||||
mutation: this,
|
||||
type: "updated",
|
||||
action
|
||||
});
|
||||
});
|
||||
}
|
||||
function getDefaultState() {
|
||||
return {
|
||||
context: void 0,
|
||||
data: void 0,
|
||||
error: null,
|
||||
failureCount: 0,
|
||||
failureReason: null,
|
||||
isPaused: false,
|
||||
status: "idle",
|
||||
variables: void 0,
|
||||
submittedAt: 0
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
exports.Mutation = Mutation;
|
||||
exports.getDefaultState = getDefaultState;
|
||||
|
||||
//# sourceMappingURL=mutation.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"mutation.cjs","names":["Removable","createRetryer"],"sources":["../../src/mutation.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Removable } from './removable'\nimport { createRetryer } from './retryer'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationMeta,\n MutationOptions,\n MutationStatus,\n} from './types'\nimport type { MutationCache } from './mutationCache'\nimport type { MutationObserver } from './mutationObserver'\nimport type { Retryer } from './retryer'\nimport type { QueryClient } from './queryClient'\n\n// TYPES\n\ninterface MutationConfig<TData, TError, TVariables, TOnMutateResult> {\n client: QueryClient\n mutationId: number\n mutationCache: MutationCache\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>\n}\n\n/**\n * The raw state stored on a `Mutation` instance. This is the underlying state\n * that observer results (e.g. `MutationObserverResult`) are derived from.\n */\nexport interface MutationState<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * The value returned by `onMutate`, if defined. Passed to `onSuccess`,\n * `onError` and `onSettled` as the mutation's context.\n */\n context: TOnMutateResult | undefined\n /**\n * The last successfully resolved data for the mutation.\n */\n data: TData | undefined\n /**\n * The error object for the mutation, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The number of times the mutation function has failed for the current attempt.\n */\n failureCount: number\n /**\n * The reason the current attempt failed, as reported by the retryer.\n */\n failureReason: TError | null\n /**\n * Whether the mutation is currently paused (see network mode), or is\n * waiting for another mutation with the same `scope` to finish.\n */\n isPaused: boolean\n /**\n * The status of the mutation.\n */\n status: MutationStatus\n /**\n * The variables the mutation was last called with.\n */\n variables: TVariables | undefined\n /**\n * The timestamp for when the mutation was submitted.\n */\n submittedAt: number\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError | null\n}\n\ninterface PendingAction<TVariables, TOnMutateResult> {\n type: 'pending'\n isPaused: boolean\n variables?: TVariables\n context?: TOnMutateResult\n}\n\ninterface SuccessAction<TData> {\n type: 'success'\n data: TData\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\nexport type Action<TData, TError, TVariables, TOnMutateResult> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | PendingAction<TVariables, TOnMutateResult>\n | PauseAction\n | SuccessAction<TData>\n\n// CLASS\n\n/**\n * Represents a single mutation attempt. A `Mutation` holds the mutation's\n * options, state (data/error/status), and the `MutationObserver`s currently\n * subscribed to it.\n *\n * Instances are created and managed internally by `MutationCache`; application\n * code typically interacts with mutations indirectly through `QueryClient` or\n * a framework hook like `useMutation`. Direct access to a `Mutation` instance\n * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * ```\n */\nexport class Mutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> extends Removable {\n state: MutationState<TData, TError, TVariables, TOnMutateResult>\n options!: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n readonly mutationId: number\n\n #client: QueryClient\n #observers: Array<\n MutationObserver<TData, TError, TVariables, TOnMutateResult>\n >\n #mutationCache: MutationCache\n #retryer?: Retryer<TData>\n\n constructor(\n config: MutationConfig<TData, TError, TVariables, TOnMutateResult>,\n ) {\n super()\n\n this.#client = config.client\n this.mutationId = config.mutationId\n this.#mutationCache = config.mutationCache\n this.#observers = []\n this.state = config.state || getDefaultState()\n\n this.setOptions(config.options)\n this.scheduleGc()\n }\n\n /** @internal */\n setOptions(\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.options = options\n\n this.updateGcTime(this.options.gcTime)\n }\n\n /**\n * The `meta` object passed in the mutation's options, if any.\n */\n get meta(): MutationMeta | undefined {\n return thLine truncated
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { Bn as Action, Hn as MutationState, Un as getDefaultState, Vn as Mutation } from "./hydration-DwR10Hi-.cjs";
|
||||
export { Action, Mutation, MutationState, getDefaultState };
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { Bn as Action, Hn as MutationState, Un as getDefaultState, Vn as Mutation } from "./hydration-Cq7QYAzB.js";
|
||||
export { Action, Mutation, MutationState, getDefaultState };
|
||||
+312
@@ -0,0 +1,312 @@
|
||||
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
|
||||
import { notifyManager } from "./notifyManager.js";
|
||||
import { createRetryer } from "./retryer.js";
|
||||
import { Removable } from "./removable.js";
|
||||
import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-CBwa_Y7C.js";
|
||||
//#region src/mutation.ts
|
||||
var _client = /* @__PURE__ */ new WeakMap();
|
||||
var _observers = /* @__PURE__ */ new WeakMap();
|
||||
var _mutationCache = /* @__PURE__ */ new WeakMap();
|
||||
var _retryer = /* @__PURE__ */ new WeakMap();
|
||||
var _Mutation_brand = /* @__PURE__ */ new WeakSet();
|
||||
/**
|
||||
* Represents a single mutation attempt. A `Mutation` holds the mutation's
|
||||
* options, state (data/error/status), and the `MutationObserver`s currently
|
||||
* subscribed to it.
|
||||
*
|
||||
* Instances are created and managed internally by `MutationCache`; application
|
||||
* code typically interacts with mutations indirectly through `QueryClient` or
|
||||
* a framework hook like `useMutation`. Direct access to a `Mutation` instance
|
||||
* is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const mutationCache = queryClient.getMutationCache()
|
||||
*
|
||||
* const mutation = mutationCache.find({ mutationKey: ['addPost'] })
|
||||
* ```
|
||||
*/
|
||||
var Mutation = class extends Removable {
|
||||
constructor(config) {
|
||||
super();
|
||||
_classPrivateMethodInitSpec(this, _Mutation_brand);
|
||||
_classPrivateFieldInitSpec(this, _client, void 0);
|
||||
_classPrivateFieldInitSpec(this, _observers, void 0);
|
||||
_classPrivateFieldInitSpec(this, _mutationCache, void 0);
|
||||
_classPrivateFieldInitSpec(this, _retryer, void 0);
|
||||
_classPrivateFieldSet2(_client, this, config.client);
|
||||
this.mutationId = config.mutationId;
|
||||
_classPrivateFieldSet2(_mutationCache, this, config.mutationCache);
|
||||
_classPrivateFieldSet2(_observers, this, []);
|
||||
this.state = config.state || getDefaultState();
|
||||
this.setOptions(config.options);
|
||||
this.scheduleGc();
|
||||
}
|
||||
/** @internal */
|
||||
setOptions(options) {
|
||||
this.options = options;
|
||||
this.updateGcTime(this.options.gcTime);
|
||||
}
|
||||
/**
|
||||
* The `meta` object passed in the mutation's options, if any.
|
||||
*/
|
||||
get meta() {
|
||||
return this.options.meta;
|
||||
}
|
||||
/** @internal */
|
||||
addObserver(observer) {
|
||||
if (!_classPrivateFieldGet2(_observers, this).includes(observer)) {
|
||||
_classPrivateFieldGet2(_observers, this).push(observer);
|
||||
this.clearGcTimeout();
|
||||
_classPrivateFieldGet2(_mutationCache, this).notify({
|
||||
type: "observerAdded",
|
||||
mutation: this,
|
||||
observer
|
||||
});
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
removeObserver(observer) {
|
||||
_classPrivateFieldSet2(_observers, this, _classPrivateFieldGet2(_observers, this).filter((x) => x !== observer));
|
||||
this.scheduleGc();
|
||||
_classPrivateFieldGet2(_mutationCache, this).notify({
|
||||
type: "observerRemoved",
|
||||
mutation: this,
|
||||
observer
|
||||
});
|
||||
}
|
||||
optionalRemove() {
|
||||
if (!_classPrivateFieldGet2(_observers, this).length) {
|
||||
if (this.state.status === "pending") this.scheduleGc();
|
||||
else _classPrivateFieldGet2(_mutationCache, this).remove(this);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Resumes a mutation that is currently paused or was restored from a
|
||||
* dehydrated, still-`pending` state.
|
||||
*
|
||||
* - If this mutation has an active retryer (it paused mid-attempt, e.g. due
|
||||
* to the network mode or scope-based queuing), its retryer is resumed.
|
||||
* - Otherwise, if the mutation's status is still `pending` (e.g. it was
|
||||
* dehydrated while an attempt was in flight and never got a retryer in
|
||||
* this instance), `execute` is called again with the last known variables.
|
||||
* - Otherwise the mutation has already settled and this resolves immediately
|
||||
* without running anything again.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()
|
||||
* const mutation = mutationCache.find({ mutationKey: ['addPost'] })
|
||||
* await mutation?.continue()
|
||||
* ```
|
||||
*
|
||||
* @see {@link Mutation#execute}
|
||||
*/
|
||||
continue() {
|
||||
var _classPrivateFieldGet2$1;
|
||||
return ((_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.continue()) ?? (this.state.status === "pending" ? this.execute(this.state.variables) : Promise.resolve());
|
||||
}
|
||||
/**
|
||||
* Runs the mutation function for the given variables through a retryer, and
|
||||
* drives the mutation's state and lifecycle callbacks through to settlement.
|
||||
*
|
||||
* If this mutation's state is already `pending` when `execute` is called
|
||||
* (i.e. it was restored, still in-flight, from a dehydrated state), the
|
||||
* `onMutate` step is skipped and a `continue` action is dispatched to
|
||||
* unpause it; otherwise a `pending` action is dispatched first, then the
|
||||
* mutation cache's `onMutate` and the mutation's own `onMutate` option are
|
||||
* awaited in that order, and the resulting context is stored.
|
||||
*
|
||||
* The mutation function is then run (subject to `retry`/`retryDelay`/
|
||||
* `networkMode`, and to the mutation cache's scope-based serialization).
|
||||
* On success, the cache's `onSuccess`/`onSettled` callbacks run before the
|
||||
* mutation's own `onSuccess`/`onSettled` options, a `success` action is
|
||||
* dispatched, and the resolved data is returned. On failure, the same
|
||||
* cache-then-option ordering is used for `onError`/`onSettled`, but each of
|
||||
* those four callbacks is individually caught so that a throwing callback
|
||||
* cannot mask the original error; an `error` action is then dispatched and
|
||||
* the original error is re-thrown.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // Called internally by `MutationObserver.mutate` and `Mutation.continue` —
|
||||
* // applications normally trigger mutations through those, not this method.
|
||||
* const data = await mutation.execute(variables)
|
||||
* ```
|
||||
*
|
||||
* @see {@link Mutation#continue}
|
||||
*/
|
||||
async execute(variables) {
|
||||
const onContinue = () => {
|
||||
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, { type: "continue" });
|
||||
};
|
||||
const mutationFnContext = {
|
||||
client: _classPrivateFieldGet2(_client, this),
|
||||
meta: this.options.meta,
|
||||
mutationKey: this.options.mutationKey
|
||||
};
|
||||
const retryer = _classPrivateFieldSet2(_retryer, this, createRetryer({
|
||||
fn: () => {
|
||||
if (!this.options.mutationFn) return Promise.reject(/* @__PURE__ */ new Error("No mutationFn found"));
|
||||
return this.options.mutationFn(variables, mutationFnContext);
|
||||
},
|
||||
onFail: (failureCount, error) => {
|
||||
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
|
||||
type: "failed",
|
||||
failureCount,
|
||||
error
|
||||
});
|
||||
},
|
||||
onPause: () => {
|
||||
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, { type: "pause" });
|
||||
},
|
||||
onContinue,
|
||||
retry: this.options.retry ?? 0,
|
||||
retryDelay: this.options.retryDelay,
|
||||
networkMode: this.options.networkMode,
|
||||
canRun: () => _classPrivateFieldGet2(_mutationCache, this).canRun(this)
|
||||
}));
|
||||
const restored = this.state.status === "pending";
|
||||
const isPaused = !retryer.canStart();
|
||||
try {
|
||||
var _classPrivateFieldGet3, _classPrivateFieldGet4, _this$options$onSucce, _this$options2, _classPrivateFieldGet5, _classPrivateFieldGet6, _this$options$onSettl, _this$options3;
|
||||
if (restored) onContinue();
|
||||
else {
|
||||
var _this$options$onMutat, _this$options;
|
||||
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
|
||||
type: "pending",
|
||||
variables,
|
||||
isPaused
|
||||
});
|
||||
if (_classPrivateFieldGet2(_mutationCache, this).config.onMutate) await _classPrivateFieldGet2(_mutationCache, this).config.onMutate(variables, this, mutationFnContext);
|
||||
const context = await ((_this$options$onMutat = (_this$options = this.options).onMutate) === null || _this$options$onMutat === void 0 ? void 0 : _this$options$onMutat.call(_this$options, variables, mutationFnContext));
|
||||
if (context !== this.state.context) _assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
|
||||
type: "pending",
|
||||
context,
|
||||
variables,
|
||||
isPaused
|
||||
});
|
||||
}
|
||||
const data = await retryer.start();
|
||||
await ((_classPrivateFieldGet3 = (_classPrivateFieldGet4 = _classPrivateFieldGet2(_mutationCache, this).config).onSuccess) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.call(_classPrivateFieldGet4, data, variables, this.state.context, this, mutationFnContext));
|
||||
await ((_this$options$onSucce = (_this$options2 = this.options).onSuccess) === null || _this$options$onSucce === void 0 ? void 0 : _this$options$onSucce.call(_this$options2, data, variables, this.state.context, mutationFnContext));
|
||||
await ((_classPrivateFieldGet5 = (_classPrivateFieldGet6 = _classPrivateFieldGet2(_mutationCache, this).config).onSettled) === null || _classPrivateFieldGet5 === void 0 ? void 0 : _classPrivateFieldGet5.call(_classPrivateFieldGet6, data, null, this.state.variables, this.state.context, this, mutationFnContext));
|
||||
await ((_this$options$onSettl = (_this$options3 = this.options).onSettled) === null || _this$options$onSettl === void 0 ? void 0 : _this$options$onSettl.call(_this$options3, data, null, variables, this.state.context, mutationFnContext));
|
||||
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
|
||||
type: "success",
|
||||
data
|
||||
});
|
||||
return data;
|
||||
} catch (error) {
|
||||
try {
|
||||
var _classPrivateFieldGet7, _classPrivateFieldGet8;
|
||||
await ((_classPrivateFieldGet7 = (_classPrivateFieldGet8 = _classPrivateFieldGet2(_mutationCache, this).config).onError) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.call(_classPrivateFieldGet8, error, variables, this.state.context, this, mutationFnContext));
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
try {
|
||||
var _this$options$onError, _this$options4;
|
||||
await ((_this$options$onError = (_this$options4 = this.options).onError) === null || _this$options$onError === void 0 ? void 0 : _this$options$onError.call(_this$options4, error, variables, this.state.context, mutationFnContext));
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
try {
|
||||
var _classPrivateFieldGet9, _classPrivateFieldGet10;
|
||||
await ((_classPrivateFieldGet9 = (_classPrivateFieldGet10 = _classPrivateFieldGet2(_mutationCache, this).config).onSettled) === null || _classPrivateFieldGet9 === void 0 ? void 0 : _classPrivateFieldGet9.call(_classPrivateFieldGet10, void 0, error, this.state.variables, this.state.context, this, mutationFnContext));
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
try {
|
||||
var _this$options$onSettl2, _this$options5;
|
||||
await ((_this$options$onSettl2 = (_this$options5 = this.options).onSettled) === null || _this$options$onSettl2 === void 0 ? void 0 : _this$options$onSettl2.call(_this$options5, void 0, error, variables, this.state.context, mutationFnContext));
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
|
||||
type: "error",
|
||||
error
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
if (_classPrivateFieldGet2(_retryer, this) === retryer) _classPrivateFieldSet2(_retryer, this, void 0);
|
||||
_classPrivateFieldGet2(_mutationCache, this).runNext(this);
|
||||
}
|
||||
}
|
||||
};
|
||||
function _dispatch(action) {
|
||||
const reducer = (state) => {
|
||||
switch (action.type) {
|
||||
case "failed": return {
|
||||
...state,
|
||||
failureCount: action.failureCount,
|
||||
failureReason: action.error
|
||||
};
|
||||
case "pause": return {
|
||||
...state,
|
||||
isPaused: true
|
||||
};
|
||||
case "continue": return {
|
||||
...state,
|
||||
isPaused: false
|
||||
};
|
||||
case "pending": return {
|
||||
...state,
|
||||
context: action.context,
|
||||
data: void 0,
|
||||
failureCount: 0,
|
||||
failureReason: null,
|
||||
error: null,
|
||||
isPaused: action.isPaused,
|
||||
status: "pending",
|
||||
variables: action.variables,
|
||||
submittedAt: Date.now()
|
||||
};
|
||||
case "success": return {
|
||||
...state,
|
||||
data: action.data,
|
||||
failureCount: 0,
|
||||
failureReason: null,
|
||||
error: null,
|
||||
status: "success",
|
||||
isPaused: false
|
||||
};
|
||||
case "error": return {
|
||||
...state,
|
||||
data: void 0,
|
||||
error: action.error,
|
||||
failureCount: state.failureCount + 1,
|
||||
failureReason: action.error,
|
||||
isPaused: false,
|
||||
status: "error"
|
||||
};
|
||||
}
|
||||
};
|
||||
this.state = reducer(this.state);
|
||||
notifyManager.batch(() => {
|
||||
_classPrivateFieldGet2(_observers, this).forEach((observer) => {
|
||||
observer.onMutationUpdate(action);
|
||||
});
|
||||
_classPrivateFieldGet2(_mutationCache, this).notify({
|
||||
mutation: this,
|
||||
type: "updated",
|
||||
action
|
||||
});
|
||||
});
|
||||
}
|
||||
function getDefaultState() {
|
||||
return {
|
||||
context: void 0,
|
||||
data: void 0,
|
||||
error: null,
|
||||
failureCount: 0,
|
||||
failureReason: null,
|
||||
isPaused: false,
|
||||
status: "idle",
|
||||
variables: void 0,
|
||||
submittedAt: 0
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
export { Mutation, getDefaultState };
|
||||
|
||||
//# sourceMappingURL=mutation.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"mutation.js","names":[],"sources":["../../src/mutation.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Removable } from './removable'\nimport { createRetryer } from './retryer'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationMeta,\n MutationOptions,\n MutationStatus,\n} from './types'\nimport type { MutationCache } from './mutationCache'\nimport type { MutationObserver } from './mutationObserver'\nimport type { Retryer } from './retryer'\nimport type { QueryClient } from './queryClient'\n\n// TYPES\n\ninterface MutationConfig<TData, TError, TVariables, TOnMutateResult> {\n client: QueryClient\n mutationId: number\n mutationCache: MutationCache\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>\n}\n\n/**\n * The raw state stored on a `Mutation` instance. This is the underlying state\n * that observer results (e.g. `MutationObserverResult`) are derived from.\n */\nexport interface MutationState<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * The value returned by `onMutate`, if defined. Passed to `onSuccess`,\n * `onError` and `onSettled` as the mutation's context.\n */\n context: TOnMutateResult | undefined\n /**\n * The last successfully resolved data for the mutation.\n */\n data: TData | undefined\n /**\n * The error object for the mutation, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The number of times the mutation function has failed for the current attempt.\n */\n failureCount: number\n /**\n * The reason the current attempt failed, as reported by the retryer.\n */\n failureReason: TError | null\n /**\n * Whether the mutation is currently paused (see network mode), or is\n * waiting for another mutation with the same `scope` to finish.\n */\n isPaused: boolean\n /**\n * The status of the mutation.\n */\n status: MutationStatus\n /**\n * The variables the mutation was last called with.\n */\n variables: TVariables | undefined\n /**\n * The timestamp for when the mutation was submitted.\n */\n submittedAt: number\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError | null\n}\n\ninterface PendingAction<TVariables, TOnMutateResult> {\n type: 'pending'\n isPaused: boolean\n variables?: TVariables\n context?: TOnMutateResult\n}\n\ninterface SuccessAction<TData> {\n type: 'success'\n data: TData\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\nexport type Action<TData, TError, TVariables, TOnMutateResult> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | PendingAction<TVariables, TOnMutateResult>\n | PauseAction\n | SuccessAction<TData>\n\n// CLASS\n\n/**\n * Represents a single mutation attempt. A `Mutation` holds the mutation's\n * options, state (data/error/status), and the `MutationObserver`s currently\n * subscribed to it.\n *\n * Instances are created and managed internally by `MutationCache`; application\n * code typically interacts with mutations indirectly through `QueryClient` or\n * a framework hook like `useMutation`. Direct access to a `Mutation` instance\n * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * ```\n */\nexport class Mutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> extends Removable {\n state: MutationState<TData, TError, TVariables, TOnMutateResult>\n options!: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n readonly mutationId: number\n\n #client: QueryClient\n #observers: Array<\n MutationObserver<TData, TError, TVariables, TOnMutateResult>\n >\n #mutationCache: MutationCache\n #retryer?: Retryer<TData>\n\n constructor(\n config: MutationConfig<TData, TError, TVariables, TOnMutateResult>,\n ) {\n super()\n\n this.#client = config.client\n this.mutationId = config.mutationId\n this.#mutationCache = config.mutationCache\n this.#observers = []\n this.state = config.state || getDefaultState()\n\n this.setOptions(config.options)\n this.scheduleGc()\n }\n\n /** @internal */\n setOptions(\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.options = options\n\n this.updateGcTime(this.options.gcTime)\n }\n\n /**\n * The `meta` object passed in the mutation's options, if any.\n */\n get meta(): MutationMeta | undefined {\n return this.options.meta\n }\n\n /*Line truncated
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
|
||||
const require_utils = require("./utils.cjs");
|
||||
const require_subscribable = require("./subscribable.cjs");
|
||||
const require_notifyManager = require("./notifyManager.cjs");
|
||||
const require_mutation = require("./mutation.cjs");
|
||||
//#region src/mutationCache.ts
|
||||
var _mutations = /* @__PURE__ */ new WeakMap();
|
||||
var _scopes = /* @__PURE__ */ new WeakMap();
|
||||
var _mutationId = /* @__PURE__ */ new WeakMap();
|
||||
/**
|
||||
* The `MutationCache` is the storage for mutations.
|
||||
*
|
||||
* Normally, you will not interact with the `MutationCache` directly and instead use a
|
||||
* `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of
|
||||
* safe/known updates to the cache, such as mutations being added, removed, or updated.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const unsubscribe = mutationCache.subscribe((event) => {
|
||||
* console.log(event.type, event.mutation)
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
var MutationCache = class extends require_subscribable.Subscribable {
|
||||
constructor(config = {}) {
|
||||
super();
|
||||
this.config = config;
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _mutations, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _scopes, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _mutationId, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_mutations, this, /* @__PURE__ */ new Set());
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_scopes, this, /* @__PURE__ */ new Map());
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_mutationId, this, 0);
|
||||
}
|
||||
/** @internal */
|
||||
build(client, options, state) {
|
||||
var _this$mutationId;
|
||||
const mutation = new require_mutation.Mutation({
|
||||
client,
|
||||
mutationCache: this,
|
||||
mutationId: require_classPrivateFieldSet2._classPrivateFieldSet2(_mutationId, this, (_this$mutationId = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationId, this), ++_this$mutationId)),
|
||||
options: client.defaultMutationOptions(options),
|
||||
state
|
||||
});
|
||||
this.add(mutation);
|
||||
return mutation;
|
||||
}
|
||||
/** @internal */
|
||||
add(mutation) {
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutations, this).add(mutation);
|
||||
const scope = scopeFor(mutation);
|
||||
if (typeof scope === "string") {
|
||||
const scopedMutations = require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).get(scope);
|
||||
if (scopedMutations) scopedMutations.push(mutation);
|
||||
else require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).set(scope, [mutation]);
|
||||
}
|
||||
this.notify({
|
||||
type: "added",
|
||||
mutation
|
||||
});
|
||||
}
|
||||
/** @internal */
|
||||
remove(mutation) {
|
||||
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_mutations, this).delete(mutation)) {
|
||||
const scope = scopeFor(mutation);
|
||||
if (typeof scope === "string") {
|
||||
const scopedMutations = require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).get(scope);
|
||||
if (scopedMutations) {
|
||||
if (scopedMutations.length > 1) {
|
||||
const index = scopedMutations.indexOf(mutation);
|
||||
if (index !== -1) scopedMutations.splice(index, 1);
|
||||
} else if (scopedMutations[0] === mutation) require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).delete(scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.notify({
|
||||
type: "removed",
|
||||
mutation
|
||||
});
|
||||
}
|
||||
/** @internal */
|
||||
canRun(mutation) {
|
||||
const scope = scopeFor(mutation);
|
||||
if (typeof scope === "string") {
|
||||
const mutationsWithSameScope = require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).get(scope);
|
||||
const firstPendingMutation = mutationsWithSameScope === null || mutationsWithSameScope === void 0 ? void 0 : mutationsWithSameScope.find((m) => m.state.status === "pending");
|
||||
return !firstPendingMutation || firstPendingMutation === mutation;
|
||||
} else return true;
|
||||
}
|
||||
/** @internal */
|
||||
runNext(mutation) {
|
||||
const scope = scopeFor(mutation);
|
||||
if (typeof scope === "string") {
|
||||
var _classPrivateFieldGet2$1;
|
||||
const foundMutation = (_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).get(scope)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.find((m) => m !== mutation && m.state.isPaused);
|
||||
return (foundMutation === null || foundMutation === void 0 ? void 0 : foundMutation.continue()) ?? Promise.resolve();
|
||||
} else return Promise.resolve();
|
||||
}
|
||||
/**
|
||||
* Removes all mutations from the cache.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const mutationCache = queryClient.getMutationCache()
|
||||
*
|
||||
* mutationCache.clear()
|
||||
* ```
|
||||
*/
|
||||
clear() {
|
||||
require_notifyManager.notifyManager.batch(() => {
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutations, this).forEach((mutation) => {
|
||||
this.notify({
|
||||
type: "removed",
|
||||
mutation
|
||||
});
|
||||
});
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutations, this).clear();
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).clear();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Returns all mutations within the cache.
|
||||
*
|
||||
* This is not typically needed for most applications, but can come in handy when needing more
|
||||
* information about a mutation in rare scenarios.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const mutationCache = queryClient.getMutationCache()
|
||||
*
|
||||
* const mutations = mutationCache.getAll()
|
||||
* ```
|
||||
*/
|
||||
getAll() {
|
||||
return Array.from(require_classPrivateFieldSet2._classPrivateFieldGet2(_mutations, this));
|
||||
}
|
||||
/**
|
||||
* A slightly more advanced method that can be used to get an existing mutation instance from
|
||||
* the cache. If the mutation does not exist, `undefined` is returned.
|
||||
*
|
||||
* This is not typically needed for most applications, but can come in handy when needing more
|
||||
* information about a mutation in rare scenarios.
|
||||
*
|
||||
* @see {@link MutationCache#findAll}
|
||||
* @example
|
||||
* ```ts
|
||||
* const mutationCache = queryClient.getMutationCache()
|
||||
*
|
||||
* const mutation = mutationCache.find({ mutationKey: ['addPost'] })
|
||||
* ```
|
||||
*/
|
||||
find(filters) {
|
||||
const defaultedFilters = {
|
||||
exact: true,
|
||||
...filters
|
||||
};
|
||||
return this.getAll().find((mutation) => require_utils.matchMutation(defaultedFilters, mutation));
|
||||
}
|
||||
/**
|
||||
* An even more advanced method that can be used to get existing mutation instances from the
|
||||
* cache that match the given filters. If no mutations match, an empty array is returned.
|
||||
*
|
||||
* This is not typically needed for most applications, but can come in handy when needing more
|
||||
* information about mutations in rare scenarios.
|
||||
*
|
||||
* @see {@link MutationCache#find}
|
||||
* @example
|
||||
* ```ts
|
||||
* const mutationCache = queryClient.getMutationCache()
|
||||
*
|
||||
* const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })
|
||||
* ```
|
||||
*/
|
||||
findAll(filters = {}) {
|
||||
return this.getAll().filter((mutation) => require_utils.matchMutation(filters, mutation));
|
||||
}
|
||||
/** @internal */
|
||||
notify(event) {
|
||||
require_notifyManager.notifyManager.batch(() => {
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(event);
|
||||
});
|
||||
});
|
||||
}
|
||||
/** @internal */
|
||||
resumePausedMutations() {
|
||||
const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
|
||||
return require_notifyManager.notifyManager.batch(() => Promise.all(pausedMutations.map((mutation) => mutation.continue().catch(require_utils.noop))));
|
||||
}
|
||||
};
|
||||
function scopeFor(mutation) {
|
||||
var _mutation$options$sco;
|
||||
return (_mutation$options$sco = mutation.options.scope) === null || _mutation$options$sco === void 0 ? void 0 : _mutation$options$sco.id;
|
||||
}
|
||||
//#endregion
|
||||
exports.MutationCache = MutationCache;
|
||||
|
||||
//# sourceMappingURL=mutationCache.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"mutationCache.cjs","names":["Subscribable","Mutation","matchMutation","notifyManager","noop"],"sources":["../../src/mutationCache.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Mutation } from './mutation'\nimport { matchMutation, noop } from './utils'\nimport { Subscribable } from './subscribable'\nimport type { MutationObserver } from './mutationObserver'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationOptions,\n NotifyEvent,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Action, MutationState } from './mutation'\nimport type { MutationFilters } from './utils'\n\n// TYPES\n\n/**\n * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which\n * component or observer triggered it. They differ from the `defaultOptions` provided to a\n * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these\n * callbacks are always called, and `onMutate` here does not allow returning a result.\n *\n * If a callback returns a promise, it will be awaited before the mutation continues.\n */\nexport interface MutationCacheConfig {\n /** Called when any mutation in the cache encounters an error. */\n onError?: (\n error: DefaultError,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is successful. */\n onSuccess?: (\n data: unknown,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called before any mutation in the cache executes. */\n onMutate?: (\n variables: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is settled, either successfully or with an error. */\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n}\n\ninterface NotifyEventMutationAdded extends NotifyEvent {\n type: 'added'\n mutation: Mutation<any, any, any, any>\n}\ninterface NotifyEventMutationRemoved extends NotifyEvent {\n type: 'removed'\n mutation: Mutation<any, any, any, any>\n}\n\ninterface NotifyEventMutationObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n mutation?: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any, any>\n}\n\ninterface NotifyEventMutationUpdated extends NotifyEvent {\n type: 'updated'\n mutation: Mutation<any, any, any, any>\n action: Action<any, any, any, any>\n}\n\n/**\n * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed\n * from the cache, its state is updated, or one of its observers is added, removed, or has its\n * options updated.\n */\nexport type MutationCacheNotifyEvent =\n | NotifyEventMutationAdded\n | NotifyEventMutationRemoved\n | NotifyEventMutationObserverAdded\n | NotifyEventMutationObserverRemoved\n | NotifyEventMutationObserverOptionsUpdated\n | NotifyEventMutationUpdated\n\ntype MutationCacheListener = (event: MutationCacheNotifyEvent) => void\n\n// CLASS\n\n/**\n * The `MutationCache` is the storage for mutations.\n *\n * Normally, you will not interact with the `MutationCache` directly and instead use a\n * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of\n * safe/known updates to the cache, such as mutations being added, removed, or updated.\n *\n * @example\n * ```ts\n * const unsubscribe = mutationCache.subscribe((event) => {\n * console.log(event.type, event.mutation)\n * })\n * ```\n */\nexport class MutationCache extends Subscribable<MutationCacheListener> {\n #mutations: Set<Mutation<any, any, any, any>>\n #scopes: Map<string, Array<Mutation<any, any, any, any>>>\n #mutationId: number\n\n constructor(public config: MutationCacheConfig = {}) {\n super()\n this.#mutations = new Set()\n this.#scopes = new Map()\n this.#mutationId = 0\n }\n\n /** @internal */\n build<TData, TError, TVariables, TOnMutateResult>(\n client: QueryClient,\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n state?: MutatiLine truncated
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { Gn as MutationCacheConfig, Kn as MutationCacheNotifyEvent, Wn as MutationCache } from "./hydration-DwR10Hi-.cjs";
|
||||
export { MutationCache, MutationCacheConfig, MutationCacheNotifyEvent };
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { Gn as MutationCacheConfig, Kn as MutationCacheNotifyEvent, Wn as MutationCache } from "./hydration-Cq7QYAzB.js";
|
||||
export { MutationCache, MutationCacheConfig, MutationCacheNotifyEvent };
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
|
||||
import { matchMutation, noop } from "./utils.js";
|
||||
import { Subscribable } from "./subscribable.js";
|
||||
import { notifyManager } from "./notifyManager.js";
|
||||
import { Mutation } from "./mutation.js";
|
||||
//#region src/mutationCache.ts
|
||||
var _mutations = /* @__PURE__ */ new WeakMap();
|
||||
var _scopes = /* @__PURE__ */ new WeakMap();
|
||||
var _mutationId = /* @__PURE__ */ new WeakMap();
|
||||
/**
|
||||
* The `MutationCache` is the storage for mutations.
|
||||
*
|
||||
* Normally, you will not interact with the `MutationCache` directly and instead use a
|
||||
* `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of
|
||||
* safe/known updates to the cache, such as mutations being added, removed, or updated.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const unsubscribe = mutationCache.subscribe((event) => {
|
||||
* console.log(event.type, event.mutation)
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
var MutationCache = class extends Subscribable {
|
||||
constructor(config = {}) {
|
||||
super();
|
||||
this.config = config;
|
||||
_classPrivateFieldInitSpec(this, _mutations, void 0);
|
||||
_classPrivateFieldInitSpec(this, _scopes, void 0);
|
||||
_classPrivateFieldInitSpec(this, _mutationId, void 0);
|
||||
_classPrivateFieldSet2(_mutations, this, /* @__PURE__ */ new Set());
|
||||
_classPrivateFieldSet2(_scopes, this, /* @__PURE__ */ new Map());
|
||||
_classPrivateFieldSet2(_mutationId, this, 0);
|
||||
}
|
||||
/** @internal */
|
||||
build(client, options, state) {
|
||||
var _this$mutationId;
|
||||
const mutation = new Mutation({
|
||||
client,
|
||||
mutationCache: this,
|
||||
mutationId: _classPrivateFieldSet2(_mutationId, this, (_this$mutationId = _classPrivateFieldGet2(_mutationId, this), ++_this$mutationId)),
|
||||
options: client.defaultMutationOptions(options),
|
||||
state
|
||||
});
|
||||
this.add(mutation);
|
||||
return mutation;
|
||||
}
|
||||
/** @internal */
|
||||
add(mutation) {
|
||||
_classPrivateFieldGet2(_mutations, this).add(mutation);
|
||||
const scope = scopeFor(mutation);
|
||||
if (typeof scope === "string") {
|
||||
const scopedMutations = _classPrivateFieldGet2(_scopes, this).get(scope);
|
||||
if (scopedMutations) scopedMutations.push(mutation);
|
||||
else _classPrivateFieldGet2(_scopes, this).set(scope, [mutation]);
|
||||
}
|
||||
this.notify({
|
||||
type: "added",
|
||||
mutation
|
||||
});
|
||||
}
|
||||
/** @internal */
|
||||
remove(mutation) {
|
||||
if (_classPrivateFieldGet2(_mutations, this).delete(mutation)) {
|
||||
const scope = scopeFor(mutation);
|
||||
if (typeof scope === "string") {
|
||||
const scopedMutations = _classPrivateFieldGet2(_scopes, this).get(scope);
|
||||
if (scopedMutations) {
|
||||
if (scopedMutations.length > 1) {
|
||||
const index = scopedMutations.indexOf(mutation);
|
||||
if (index !== -1) scopedMutations.splice(index, 1);
|
||||
} else if (scopedMutations[0] === mutation) _classPrivateFieldGet2(_scopes, this).delete(scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.notify({
|
||||
type: "removed",
|
||||
mutation
|
||||
});
|
||||
}
|
||||
/** @internal */
|
||||
canRun(mutation) {
|
||||
const scope = scopeFor(mutation);
|
||||
if (typeof scope === "string") {
|
||||
const mutationsWithSameScope = _classPrivateFieldGet2(_scopes, this).get(scope);
|
||||
const firstPendingMutation = mutationsWithSameScope === null || mutationsWithSameScope === void 0 ? void 0 : mutationsWithSameScope.find((m) => m.state.status === "pending");
|
||||
return !firstPendingMutation || firstPendingMutation === mutation;
|
||||
} else return true;
|
||||
}
|
||||
/** @internal */
|
||||
runNext(mutation) {
|
||||
const scope = scopeFor(mutation);
|
||||
if (typeof scope === "string") {
|
||||
var _classPrivateFieldGet2$1;
|
||||
const foundMutation = (_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_scopes, this).get(scope)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.find((m) => m !== mutation && m.state.isPaused);
|
||||
return (foundMutation === null || foundMutation === void 0 ? void 0 : foundMutation.continue()) ?? Promise.resolve();
|
||||
} else return Promise.resolve();
|
||||
}
|
||||
/**
|
||||
* Removes all mutations from the cache.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const mutationCache = queryClient.getMutationCache()
|
||||
*
|
||||
* mutationCache.clear()
|
||||
* ```
|
||||
*/
|
||||
clear() {
|
||||
notifyManager.batch(() => {
|
||||
_classPrivateFieldGet2(_mutations, this).forEach((mutation) => {
|
||||
this.notify({
|
||||
type: "removed",
|
||||
mutation
|
||||
});
|
||||
});
|
||||
_classPrivateFieldGet2(_mutations, this).clear();
|
||||
_classPrivateFieldGet2(_scopes, this).clear();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Returns all mutations within the cache.
|
||||
*
|
||||
* This is not typically needed for most applications, but can come in handy when needing more
|
||||
* information about a mutation in rare scenarios.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const mutationCache = queryClient.getMutationCache()
|
||||
*
|
||||
* const mutations = mutationCache.getAll()
|
||||
* ```
|
||||
*/
|
||||
getAll() {
|
||||
return Array.from(_classPrivateFieldGet2(_mutations, this));
|
||||
}
|
||||
/**
|
||||
* A slightly more advanced method that can be used to get an existing mutation instance from
|
||||
* the cache. If the mutation does not exist, `undefined` is returned.
|
||||
*
|
||||
* This is not typically needed for most applications, but can come in handy when needing more
|
||||
* information about a mutation in rare scenarios.
|
||||
*
|
||||
* @see {@link MutationCache#findAll}
|
||||
* @example
|
||||
* ```ts
|
||||
* const mutationCache = queryClient.getMutationCache()
|
||||
*
|
||||
* const mutation = mutationCache.find({ mutationKey: ['addPost'] })
|
||||
* ```
|
||||
*/
|
||||
find(filters) {
|
||||
const defaultedFilters = {
|
||||
exact: true,
|
||||
...filters
|
||||
};
|
||||
return this.getAll().find((mutation) => matchMutation(defaultedFilters, mutation));
|
||||
}
|
||||
/**
|
||||
* An even more advanced method that can be used to get existing mutation instances from the
|
||||
* cache that match the given filters. If no mutations match, an empty array is returned.
|
||||
*
|
||||
* This is not typically needed for most applications, but can come in handy when needing more
|
||||
* information about mutations in rare scenarios.
|
||||
*
|
||||
* @see {@link MutationCache#find}
|
||||
* @example
|
||||
* ```ts
|
||||
* const mutationCache = queryClient.getMutationCache()
|
||||
*
|
||||
* const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })
|
||||
* ```
|
||||
*/
|
||||
findAll(filters = {}) {
|
||||
return this.getAll().filter((mutation) => matchMutation(filters, mutation));
|
||||
}
|
||||
/** @internal */
|
||||
notify(event) {
|
||||
notifyManager.batch(() => {
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(event);
|
||||
});
|
||||
});
|
||||
}
|
||||
/** @internal */
|
||||
resumePausedMutations() {
|
||||
const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
|
||||
return notifyManager.batch(() => Promise.all(pausedMutations.map((mutation) => mutation.continue().catch(noop))));
|
||||
}
|
||||
};
|
||||
function scopeFor(mutation) {
|
||||
var _mutation$options$sco;
|
||||
return (_mutation$options$sco = mutation.options.scope) === null || _mutation$options$sco === void 0 ? void 0 : _mutation$options$sco.id;
|
||||
}
|
||||
//#endregion
|
||||
export { MutationCache };
|
||||
|
||||
//# sourceMappingURL=mutationCache.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"mutationCache.js","names":[],"sources":["../../src/mutationCache.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Mutation } from './mutation'\nimport { matchMutation, noop } from './utils'\nimport { Subscribable } from './subscribable'\nimport type { MutationObserver } from './mutationObserver'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationOptions,\n NotifyEvent,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Action, MutationState } from './mutation'\nimport type { MutationFilters } from './utils'\n\n// TYPES\n\n/**\n * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which\n * component or observer triggered it. They differ from the `defaultOptions` provided to a\n * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these\n * callbacks are always called, and `onMutate` here does not allow returning a result.\n *\n * If a callback returns a promise, it will be awaited before the mutation continues.\n */\nexport interface MutationCacheConfig {\n /** Called when any mutation in the cache encounters an error. */\n onError?: (\n error: DefaultError,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is successful. */\n onSuccess?: (\n data: unknown,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called before any mutation in the cache executes. */\n onMutate?: (\n variables: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is settled, either successfully or with an error. */\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n}\n\ninterface NotifyEventMutationAdded extends NotifyEvent {\n type: 'added'\n mutation: Mutation<any, any, any, any>\n}\ninterface NotifyEventMutationRemoved extends NotifyEvent {\n type: 'removed'\n mutation: Mutation<any, any, any, any>\n}\n\ninterface NotifyEventMutationObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n mutation?: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any, any>\n}\n\ninterface NotifyEventMutationUpdated extends NotifyEvent {\n type: 'updated'\n mutation: Mutation<any, any, any, any>\n action: Action<any, any, any, any>\n}\n\n/**\n * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed\n * from the cache, its state is updated, or one of its observers is added, removed, or has its\n * options updated.\n */\nexport type MutationCacheNotifyEvent =\n | NotifyEventMutationAdded\n | NotifyEventMutationRemoved\n | NotifyEventMutationObserverAdded\n | NotifyEventMutationObserverRemoved\n | NotifyEventMutationObserverOptionsUpdated\n | NotifyEventMutationUpdated\n\ntype MutationCacheListener = (event: MutationCacheNotifyEvent) => void\n\n// CLASS\n\n/**\n * The `MutationCache` is the storage for mutations.\n *\n * Normally, you will not interact with the `MutationCache` directly and instead use a\n * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of\n * safe/known updates to the cache, such as mutations being added, removed, or updated.\n *\n * @example\n * ```ts\n * const unsubscribe = mutationCache.subscribe((event) => {\n * console.log(event.type, event.mutation)\n * })\n * ```\n */\nexport class MutationCache extends Subscribable<MutationCacheListener> {\n #mutations: Set<Mutation<any, any, any, any>>\n #scopes: Map<string, Array<Mutation<any, any, any, any>>>\n #mutationId: number\n\n constructor(public config: MutationCacheConfig = {}) {\n super()\n this.#mutations = new Set()\n this.#scopes = new Map()\n this.#mutationId = 0\n }\n\n /** @internal */\n build<TData, TError, TVariables, TOnMutateResult>(\n client: QueryClient,\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>,\n ): MutatiLine truncated
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
|
||||
const require_utils = require("./utils.cjs");
|
||||
const require_subscribable = require("./subscribable.cjs");
|
||||
const require_notifyManager = require("./notifyManager.cjs");
|
||||
const require_classPrivateMethodInitSpec = require("./classPrivateMethodInitSpec-DVhcLejn.cjs");
|
||||
const require_mutation = require("./mutation.cjs");
|
||||
//#region src/mutationObserver.ts
|
||||
var _client = /* @__PURE__ */ new WeakMap();
|
||||
var _currentResult = /* @__PURE__ */ new WeakMap();
|
||||
var _currentMutation = /* @__PURE__ */ new WeakMap();
|
||||
var _mutateOptions = /* @__PURE__ */ new WeakMap();
|
||||
var _MutationObserver_brand = /* @__PURE__ */ new WeakSet();
|
||||
/**
|
||||
* Observes a single mutation and derives a `MutationObserverResult` from it.
|
||||
* A framework hook like `useMutation` creates one `MutationObserver` per hook
|
||||
* call, keeps it stable across re-renders, calls `setOptions` when the options
|
||||
* passed to the hook change, subscribes to it to re-render on updates, and
|
||||
* reads `getCurrentResult()` for the value to return. Calling `mutate()`
|
||||
* builds a new underlying `Mutation` in the `MutationCache` and executes it.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const observer = new MutationObserver(queryClient, {
|
||||
* mutationFn: (variables: { title: string }) => addPost(variables),
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
var MutationObserver = class extends require_subscribable.Subscribable {
|
||||
constructor(client, options) {
|
||||
super();
|
||||
require_classPrivateMethodInitSpec._classPrivateMethodInitSpec(this, _MutationObserver_brand);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _client, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _currentResult, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _currentMutation, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _mutateOptions, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_client, this, client);
|
||||
this.setOptions(options);
|
||||
this.bindMethods();
|
||||
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
|
||||
}
|
||||
bindMethods() {
|
||||
this.mutate = this.mutate.bind(this);
|
||||
this.reset = this.reset.bind(this);
|
||||
}
|
||||
/**
|
||||
* Updates the observer's options.
|
||||
*
|
||||
* If the new `mutationKey` differs from the previous one (and both were
|
||||
* defined), the observer is reset, detaching it from the mutation it was
|
||||
* observing. Otherwise, if the currently observed mutation is still
|
||||
* `pending`, its options are updated in place as well.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* observer.setOptions({
|
||||
* mutationFn: (variables: { title: string }) => addPost(variables),
|
||||
* onSuccess: (data) => console.log(data),
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
setOptions(options) {
|
||||
var _classPrivateFieldGet2$1;
|
||||
const prevOptions = this.options;
|
||||
this.options = require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this).defaultMutationOptions(options);
|
||||
if (!require_utils.shallowEqualObjects(this.options, prevOptions)) require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this).getMutationCache().notify({
|
||||
type: "observerOptionsUpdated",
|
||||
mutation: require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this),
|
||||
observer: this
|
||||
});
|
||||
if ((prevOptions === null || prevOptions === void 0 ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && require_utils.hashKey(prevOptions.mutationKey) !== require_utils.hashKey(this.options.mutationKey)) this.reset();
|
||||
else if (((_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.state.status) === "pending") require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this).setOptions(this.options);
|
||||
}
|
||||
onSubscribe() {
|
||||
if (this.listeners.size === 1 && require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) {
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this).addObserver(this);
|
||||
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
|
||||
}
|
||||
}
|
||||
onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _classPrivateFieldGet3;
|
||||
(_classPrivateFieldGet3 = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.removeObserver(this);
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
onMutationUpdate(action) {
|
||||
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
|
||||
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _notify).call(this, action);
|
||||
}
|
||||
/**
|
||||
* Returns the observer's current result, derived from the observed
|
||||
* mutation's state (or the default, `idle` state if no mutation has been
|
||||
* built yet, e.g. before the first `mutate()` call or after `reset()`).
|
||||
*/
|
||||
getCurrentResult() {
|
||||
return require_classPrivateFieldSet2._classPrivateFieldGet2(_currentResult, this);
|
||||
}
|
||||
/**
|
||||
* Detaches the observer from the mutation it is currently observing (if
|
||||
* any) and resets the observed result back to its default, `idle` state.
|
||||
*
|
||||
* This does not cancel an in-flight mutation; the mutation itself keeps
|
||||
* running to completion and its own callbacks still fire, but this
|
||||
* observer stops reflecting its state and a subsequent `mutate()` call
|
||||
* will build a brand new mutation.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* observer.reset()
|
||||
* ```
|
||||
*
|
||||
* @see {@link MutationObserver#mutate}
|
||||
*/
|
||||
reset() {
|
||||
var _classPrivateFieldGet4;
|
||||
(_classPrivateFieldGet4 = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet4 === void 0 || _classPrivateFieldGet4.removeObserver(this);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_currentMutation, this, void 0);
|
||||
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
|
||||
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _notify).call(this);
|
||||
}
|
||||
/**
|
||||
* Builds a new `Mutation` in the `MutationCache` using the observer's
|
||||
* current options, detaches this observer from any previously observed
|
||||
* mutation, attaches it to the new one, and executes it with the given
|
||||
* variables.
|
||||
*
|
||||
* The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are
|
||||
* invoked once the mutation settles, in addition to any callbacks defined
|
||||
* on the observer's own options.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await observer.mutate(
|
||||
* { title: 'New post' },
|
||||
* { onSuccess: (data) => console.log(data) },
|
||||
* )
|
||||
* ```
|
||||
*/
|
||||
mutate(variables, options) {
|
||||
var _classPrivateFieldGet5;
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_mutateOptions, this, options);
|
||||
(_classPrivateFieldGet5 = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet5 === void 0 || _classPrivateFieldGet5.removeObserver(this);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_currentMutation, this, require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this).getMutationCache().build(require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this), this.options));
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this).addObserver(this);
|
||||
return require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this).execute(variables);
|
||||
}
|
||||
};
|
||||
function _updateResult() {
|
||||
var _classPrivateFieldGet6;
|
||||
const state = ((_classPrivateFieldGet6 = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet6 === void 0 ? void 0 : _classPrivateFieldGet6.state) ?? require_mutation.getDefaultState();
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_currentResult, this, {
|
||||
...state,
|
||||
isPending: state.status === "pending",
|
||||
isSuccess: state.status === "success",
|
||||
isError: state.status === "error",
|
||||
isIdle: state.status === "idle",
|
||||
mutate: this.mutate,
|
||||
reset: this.reset
|
||||
});
|
||||
}
|
||||
function _notify(action) {
|
||||
require_notifyManager.notifyManager.batch(() => {
|
||||
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_mutateOptions, this) && this.hasListeners()) {
|
||||
const variables = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentResult, this).variables;
|
||||
const onMutateResult = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentResult, this).context;
|
||||
const context = {
|
||||
client: require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this),
|
||||
meta: this.options.meta,
|
||||
mutationKey: this.options.mutationKey
|
||||
};
|
||||
if ((action === null || action === void 0 ? void 0 : action.type) === "success") {
|
||||
try {
|
||||
var _classPrivateFieldGet7, _classPrivateFieldGet8;
|
||||
(_classPrivateFieldGet7 = (_classPrivateFieldGet8 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutateOptions, this)).onSuccess) === null || _classPrivateFieldGet7 === void 0 || _classPrivateFieldGet7.call(_classPrivateFieldGet8, action.data, variables, onMutateResult, context);
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
try {
|
||||
var _classPrivateFieldGet9, _classPrivateFieldGet10;
|
||||
(_classPrivateFieldGet9 = (_classPrivateFieldGet10 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutateOptions, this)).onSettled) === null || _classPrivateFieldGet9 === void 0 || _classPrivateFieldGet9.call(_classPrivateFieldGet10, action.data, null, variables, onMutateResult, context);
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
} else if ((action === null || action === void 0 ? void 0 : action.type) === "error") {
|
||||
try {
|
||||
var _classPrivateFieldGet11, _classPrivateFieldGet12;
|
||||
(_classPrivateFieldGet11 = (_classPrivateFieldGet12 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutateOptions, this)).onError) === null || _classPrivateFieldGet11 === void 0 || _classPrivateFieldGet11.call(_classPrivateFieldGet12, action.error, variables, onMutateResult, context);
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
try {
|
||||
var _classPrivateFieldGet13, _classPrivateFieldGet14;
|
||||
(_classPrivateFieldGet13 = (_classPrivateFieldGet14 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutateOptions, this)).onSettled) === null || _classPrivateFieldGet13 === void 0 || _classPrivateFieldGet13.call(_classPrivateFieldGet14, void 0, action.error, variables, onMutateResult, context);
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(require_classPrivateFieldSet2._classPrivateFieldGet2(_currentResult, this));
|
||||
});
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
exports.MutationObserver = MutationObserver;
|
||||
|
||||
//# sourceMappingURL=mutationObserver.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"mutationObserver.cjs","names":["Subscribable","shallowEqualObjects","hashKey","getDefaultState"],"sources":["../../src/mutationObserver.ts"],"sourcesContent":["import { getDefaultState } from './mutation'\nimport { notifyManager } from './notifyManager'\nimport { Subscribable } from './subscribable'\nimport { hashKey, shallowEqualObjects } from './utils'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultError,\n MutateOptions,\n MutationFunctionContext,\n MutationObserverOptions,\n MutationObserverResult,\n} from './types'\nimport type { Action, Mutation } from './mutation'\n\n// TYPES\n\ntype MutationObserverListener<TData, TError, TVariables, TOnMutateResult> = (\n result: MutationObserverResult<TData, TError, TVariables, TOnMutateResult>,\n) => void\n\n// CLASS\n\n/**\n * Observes a single mutation and derives a `MutationObserverResult` from it.\n * A framework hook like `useMutation` creates one `MutationObserver` per hook\n * call, keeps it stable across re-renders, calls `setOptions` when the options\n * passed to the hook change, subscribes to it to re-render on updates, and\n * reads `getCurrentResult()` for the value to return. Calling `mutate()`\n * builds a new underlying `Mutation` in the `MutationCache` and executes it.\n *\n * @example\n * ```ts\n * const observer = new MutationObserver(queryClient, {\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * })\n * ```\n */\nexport class MutationObserver<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n> extends Subscribable<\n MutationObserverListener<TData, TError, TVariables, TOnMutateResult>\n> {\n options!: MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n\n #client: QueryClient\n #currentResult: MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = undefined!\n #currentMutation?: Mutation<TData, TError, TVariables, TOnMutateResult>\n #mutateOptions?: MutateOptions<TData, TError, TVariables, TOnMutateResult>\n\n constructor(\n client: QueryClient,\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n super()\n\n this.#client = client\n this.setOptions(options)\n this.bindMethods()\n this.#updateResult()\n }\n\n protected bindMethods(): void {\n this.mutate = this.mutate.bind(this)\n this.reset = this.reset.bind(this)\n }\n\n /**\n * Updates the observer's options.\n *\n * If the new `mutationKey` differs from the previous one (and both were\n * defined), the observer is reset, detaching it from the mutation it was\n * observing. Otherwise, if the currently observed mutation is still\n * `pending`, its options are updated in place as well.\n *\n * @example\n * ```ts\n * observer.setOptions({\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * onSuccess: (data) => console.log(data),\n * })\n * ```\n */\n setOptions(\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n const prevOptions = this.options as\n | MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n | undefined\n this.options = this.#client.defaultMutationOptions(options)\n if (!shallowEqualObjects(this.options, prevOptions)) {\n this.#client.getMutationCache().notify({\n type: 'observerOptionsUpdated',\n mutation: this.#currentMutation,\n observer: this,\n })\n }\n\n if (\n prevOptions?.mutationKey &&\n this.options.mutationKey &&\n hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)\n ) {\n this.reset()\n } else if (this.#currentMutation?.state.status === 'pending') {\n this.#currentMutation.setOptions(this.options)\n }\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1 && this.#currentMutation) {\n this.#currentMutation.addObserver(this)\n\n this.#updateResult()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.#currentMutation?.removeObserver(this)\n }\n }\n\n /** @internal */\n onMutationUpdate(\n action: Action<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.#updateResult()\n\n this.#notify(action)\n }\n\n /**\n * Returns the observer's current result, derived from the observed\n * mutation's state (or the default, `idle` state if no mutation has been\n * built yet, e.g. before the first `mutate()` call or after `reset()`).\n */\n getCurrentResult(): MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > {\n return this.#currentResult\n }\n\n /**\n * Detaches the observer from the mutation it is currently observing (if\n * any) and resets the observed result back to its dLine truncated
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { qn as MutationObserver } from "./hydration-DwR10Hi-.cjs";
|
||||
export { MutationObserver };
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { qn as MutationObserver } from "./hydration-Cq7QYAzB.js";
|
||||
export { MutationObserver };
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
|
||||
import { hashKey, shallowEqualObjects } from "./utils.js";
|
||||
import { Subscribable } from "./subscribable.js";
|
||||
import { notifyManager } from "./notifyManager.js";
|
||||
import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-CBwa_Y7C.js";
|
||||
import { getDefaultState } from "./mutation.js";
|
||||
//#region src/mutationObserver.ts
|
||||
var _client = /* @__PURE__ */ new WeakMap();
|
||||
var _currentResult = /* @__PURE__ */ new WeakMap();
|
||||
var _currentMutation = /* @__PURE__ */ new WeakMap();
|
||||
var _mutateOptions = /* @__PURE__ */ new WeakMap();
|
||||
var _MutationObserver_brand = /* @__PURE__ */ new WeakSet();
|
||||
/**
|
||||
* Observes a single mutation and derives a `MutationObserverResult` from it.
|
||||
* A framework hook like `useMutation` creates one `MutationObserver` per hook
|
||||
* call, keeps it stable across re-renders, calls `setOptions` when the options
|
||||
* passed to the hook change, subscribes to it to re-render on updates, and
|
||||
* reads `getCurrentResult()` for the value to return. Calling `mutate()`
|
||||
* builds a new underlying `Mutation` in the `MutationCache` and executes it.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const observer = new MutationObserver(queryClient, {
|
||||
* mutationFn: (variables: { title: string }) => addPost(variables),
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
var MutationObserver = class extends Subscribable {
|
||||
constructor(client, options) {
|
||||
super();
|
||||
_classPrivateMethodInitSpec(this, _MutationObserver_brand);
|
||||
_classPrivateFieldInitSpec(this, _client, void 0);
|
||||
_classPrivateFieldInitSpec(this, _currentResult, void 0);
|
||||
_classPrivateFieldInitSpec(this, _currentMutation, void 0);
|
||||
_classPrivateFieldInitSpec(this, _mutateOptions, void 0);
|
||||
_classPrivateFieldSet2(_client, this, client);
|
||||
this.setOptions(options);
|
||||
this.bindMethods();
|
||||
_assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
|
||||
}
|
||||
bindMethods() {
|
||||
this.mutate = this.mutate.bind(this);
|
||||
this.reset = this.reset.bind(this);
|
||||
}
|
||||
/**
|
||||
* Updates the observer's options.
|
||||
*
|
||||
* If the new `mutationKey` differs from the previous one (and both were
|
||||
* defined), the observer is reset, detaching it from the mutation it was
|
||||
* observing. Otherwise, if the currently observed mutation is still
|
||||
* `pending`, its options are updated in place as well.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* observer.setOptions({
|
||||
* mutationFn: (variables: { title: string }) => addPost(variables),
|
||||
* onSuccess: (data) => console.log(data),
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
setOptions(options) {
|
||||
var _classPrivateFieldGet2$1;
|
||||
const prevOptions = this.options;
|
||||
this.options = _classPrivateFieldGet2(_client, this).defaultMutationOptions(options);
|
||||
if (!shallowEqualObjects(this.options, prevOptions)) _classPrivateFieldGet2(_client, this).getMutationCache().notify({
|
||||
type: "observerOptionsUpdated",
|
||||
mutation: _classPrivateFieldGet2(_currentMutation, this),
|
||||
observer: this
|
||||
});
|
||||
if ((prevOptions === null || prevOptions === void 0 ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) this.reset();
|
||||
else if (((_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.state.status) === "pending") _classPrivateFieldGet2(_currentMutation, this).setOptions(this.options);
|
||||
}
|
||||
onSubscribe() {
|
||||
if (this.listeners.size === 1 && _classPrivateFieldGet2(_currentMutation, this)) {
|
||||
_classPrivateFieldGet2(_currentMutation, this).addObserver(this);
|
||||
_assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
|
||||
}
|
||||
}
|
||||
onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _classPrivateFieldGet3;
|
||||
(_classPrivateFieldGet3 = _classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.removeObserver(this);
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
onMutationUpdate(action) {
|
||||
_assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
|
||||
_assertClassBrand(_MutationObserver_brand, this, _notify).call(this, action);
|
||||
}
|
||||
/**
|
||||
* Returns the observer's current result, derived from the observed
|
||||
* mutation's state (or the default, `idle` state if no mutation has been
|
||||
* built yet, e.g. before the first `mutate()` call or after `reset()`).
|
||||
*/
|
||||
getCurrentResult() {
|
||||
return _classPrivateFieldGet2(_currentResult, this);
|
||||
}
|
||||
/**
|
||||
* Detaches the observer from the mutation it is currently observing (if
|
||||
* any) and resets the observed result back to its default, `idle` state.
|
||||
*
|
||||
* This does not cancel an in-flight mutation; the mutation itself keeps
|
||||
* running to completion and its own callbacks still fire, but this
|
||||
* observer stops reflecting its state and a subsequent `mutate()` call
|
||||
* will build a brand new mutation.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* observer.reset()
|
||||
* ```
|
||||
*
|
||||
* @see {@link MutationObserver#mutate}
|
||||
*/
|
||||
reset() {
|
||||
var _classPrivateFieldGet4;
|
||||
(_classPrivateFieldGet4 = _classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet4 === void 0 || _classPrivateFieldGet4.removeObserver(this);
|
||||
_classPrivateFieldSet2(_currentMutation, this, void 0);
|
||||
_assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
|
||||
_assertClassBrand(_MutationObserver_brand, this, _notify).call(this);
|
||||
}
|
||||
/**
|
||||
* Builds a new `Mutation` in the `MutationCache` using the observer's
|
||||
* current options, detaches this observer from any previously observed
|
||||
* mutation, attaches it to the new one, and executes it with the given
|
||||
* variables.
|
||||
*
|
||||
* The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are
|
||||
* invoked once the mutation settles, in addition to any callbacks defined
|
||||
* on the observer's own options.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await observer.mutate(
|
||||
* { title: 'New post' },
|
||||
* { onSuccess: (data) => console.log(data) },
|
||||
* )
|
||||
* ```
|
||||
*/
|
||||
mutate(variables, options) {
|
||||
var _classPrivateFieldGet5;
|
||||
_classPrivateFieldSet2(_mutateOptions, this, options);
|
||||
(_classPrivateFieldGet5 = _classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet5 === void 0 || _classPrivateFieldGet5.removeObserver(this);
|
||||
_classPrivateFieldSet2(_currentMutation, this, _classPrivateFieldGet2(_client, this).getMutationCache().build(_classPrivateFieldGet2(_client, this), this.options));
|
||||
_classPrivateFieldGet2(_currentMutation, this).addObserver(this);
|
||||
return _classPrivateFieldGet2(_currentMutation, this).execute(variables);
|
||||
}
|
||||
};
|
||||
function _updateResult() {
|
||||
var _classPrivateFieldGet6;
|
||||
const state = ((_classPrivateFieldGet6 = _classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet6 === void 0 ? void 0 : _classPrivateFieldGet6.state) ?? getDefaultState();
|
||||
_classPrivateFieldSet2(_currentResult, this, {
|
||||
...state,
|
||||
isPending: state.status === "pending",
|
||||
isSuccess: state.status === "success",
|
||||
isError: state.status === "error",
|
||||
isIdle: state.status === "idle",
|
||||
mutate: this.mutate,
|
||||
reset: this.reset
|
||||
});
|
||||
}
|
||||
function _notify(action) {
|
||||
notifyManager.batch(() => {
|
||||
if (_classPrivateFieldGet2(_mutateOptions, this) && this.hasListeners()) {
|
||||
const variables = _classPrivateFieldGet2(_currentResult, this).variables;
|
||||
const onMutateResult = _classPrivateFieldGet2(_currentResult, this).context;
|
||||
const context = {
|
||||
client: _classPrivateFieldGet2(_client, this),
|
||||
meta: this.options.meta,
|
||||
mutationKey: this.options.mutationKey
|
||||
};
|
||||
if ((action === null || action === void 0 ? void 0 : action.type) === "success") {
|
||||
try {
|
||||
var _classPrivateFieldGet7, _classPrivateFieldGet8;
|
||||
(_classPrivateFieldGet7 = (_classPrivateFieldGet8 = _classPrivateFieldGet2(_mutateOptions, this)).onSuccess) === null || _classPrivateFieldGet7 === void 0 || _classPrivateFieldGet7.call(_classPrivateFieldGet8, action.data, variables, onMutateResult, context);
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
try {
|
||||
var _classPrivateFieldGet9, _classPrivateFieldGet10;
|
||||
(_classPrivateFieldGet9 = (_classPrivateFieldGet10 = _classPrivateFieldGet2(_mutateOptions, this)).onSettled) === null || _classPrivateFieldGet9 === void 0 || _classPrivateFieldGet9.call(_classPrivateFieldGet10, action.data, null, variables, onMutateResult, context);
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
} else if ((action === null || action === void 0 ? void 0 : action.type) === "error") {
|
||||
try {
|
||||
var _classPrivateFieldGet11, _classPrivateFieldGet12;
|
||||
(_classPrivateFieldGet11 = (_classPrivateFieldGet12 = _classPrivateFieldGet2(_mutateOptions, this)).onError) === null || _classPrivateFieldGet11 === void 0 || _classPrivateFieldGet11.call(_classPrivateFieldGet12, action.error, variables, onMutateResult, context);
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
try {
|
||||
var _classPrivateFieldGet13, _classPrivateFieldGet14;
|
||||
(_classPrivateFieldGet13 = (_classPrivateFieldGet14 = _classPrivateFieldGet2(_mutateOptions, this)).onSettled) === null || _classPrivateFieldGet13 === void 0 || _classPrivateFieldGet13.call(_classPrivateFieldGet14, void 0, action.error, variables, onMutateResult, context);
|
||||
} catch (e) {
|
||||
Promise.reject(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(_classPrivateFieldGet2(_currentResult, this));
|
||||
});
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
export { MutationObserver };
|
||||
|
||||
//# sourceMappingURL=mutationObserver.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"mutationObserver.js","names":[],"sources":["../../src/mutationObserver.ts"],"sourcesContent":["import { getDefaultState } from './mutation'\nimport { notifyManager } from './notifyManager'\nimport { Subscribable } from './subscribable'\nimport { hashKey, shallowEqualObjects } from './utils'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultError,\n MutateOptions,\n MutationFunctionContext,\n MutationObserverOptions,\n MutationObserverResult,\n} from './types'\nimport type { Action, Mutation } from './mutation'\n\n// TYPES\n\ntype MutationObserverListener<TData, TError, TVariables, TOnMutateResult> = (\n result: MutationObserverResult<TData, TError, TVariables, TOnMutateResult>,\n) => void\n\n// CLASS\n\n/**\n * Observes a single mutation and derives a `MutationObserverResult` from it.\n * A framework hook like `useMutation` creates one `MutationObserver` per hook\n * call, keeps it stable across re-renders, calls `setOptions` when the options\n * passed to the hook change, subscribes to it to re-render on updates, and\n * reads `getCurrentResult()` for the value to return. Calling `mutate()`\n * builds a new underlying `Mutation` in the `MutationCache` and executes it.\n *\n * @example\n * ```ts\n * const observer = new MutationObserver(queryClient, {\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * })\n * ```\n */\nexport class MutationObserver<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n> extends Subscribable<\n MutationObserverListener<TData, TError, TVariables, TOnMutateResult>\n> {\n options!: MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n\n #client: QueryClient\n #currentResult: MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = undefined!\n #currentMutation?: Mutation<TData, TError, TVariables, TOnMutateResult>\n #mutateOptions?: MutateOptions<TData, TError, TVariables, TOnMutateResult>\n\n constructor(\n client: QueryClient,\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n super()\n\n this.#client = client\n this.setOptions(options)\n this.bindMethods()\n this.#updateResult()\n }\n\n protected bindMethods(): void {\n this.mutate = this.mutate.bind(this)\n this.reset = this.reset.bind(this)\n }\n\n /**\n * Updates the observer's options.\n *\n * If the new `mutationKey` differs from the previous one (and both were\n * defined), the observer is reset, detaching it from the mutation it was\n * observing. Otherwise, if the currently observed mutation is still\n * `pending`, its options are updated in place as well.\n *\n * @example\n * ```ts\n * observer.setOptions({\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * onSuccess: (data) => console.log(data),\n * })\n * ```\n */\n setOptions(\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n const prevOptions = this.options as\n | MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n | undefined\n this.options = this.#client.defaultMutationOptions(options)\n if (!shallowEqualObjects(this.options, prevOptions)) {\n this.#client.getMutationCache().notify({\n type: 'observerOptionsUpdated',\n mutation: this.#currentMutation,\n observer: this,\n })\n }\n\n if (\n prevOptions?.mutationKey &&\n this.options.mutationKey &&\n hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)\n ) {\n this.reset()\n } else if (this.#currentMutation?.state.status === 'pending') {\n this.#currentMutation.setOptions(this.options)\n }\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1 && this.#currentMutation) {\n this.#currentMutation.addObserver(this)\n\n this.#updateResult()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.#currentMutation?.removeObserver(this)\n }\n }\n\n /** @internal */\n onMutationUpdate(\n action: Action<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.#updateResult()\n\n this.#notify(action)\n }\n\n /**\n * Returns the observer's current result, derived from the observed\n * mutation's state (or the default, `idle` state if no mutation has been\n * built yet, e.g. before the first `mutate()` call or after `reset()`).\n */\n getCurrentResult(): MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > {\n return this.#currentResult\n }\n\n /**\n * Detaches the observer from the mutation it is currently observing (if\n * any) and resets the observed result back to its default, `idle` state.\n *\n * This does not cancel an in-fligLine truncated
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
//#region src/notifyManager.ts
|
||||
/**
|
||||
* Default scheduling function used by the notify manager.
|
||||
* Schedules the callback with the system's `setTimeout(callback, 0)`.
|
||||
*/
|
||||
const defaultScheduler = require("./timeoutManager.cjs").systemSetTimeoutZero;
|
||||
function createNotifyManager() {
|
||||
let queue = [];
|
||||
let transactions = 0;
|
||||
let notifyFn = (callback) => {
|
||||
callback();
|
||||
};
|
||||
let batchNotifyFn = (callback) => {
|
||||
callback();
|
||||
};
|
||||
let scheduleFn = defaultScheduler;
|
||||
const schedule = (callback) => {
|
||||
if (transactions) queue.push(callback);
|
||||
else scheduleFn(() => {
|
||||
notifyFn(callback);
|
||||
});
|
||||
};
|
||||
const flush = () => {
|
||||
const originalQueue = queue;
|
||||
queue = [];
|
||||
if (originalQueue.length) scheduleFn(() => {
|
||||
batchNotifyFn(() => {
|
||||
originalQueue.forEach((callback) => {
|
||||
notifyFn(callback);
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
return {
|
||||
/**
|
||||
* Batches all updates scheduled inside the passed callback.
|
||||
* This is mainly used internally to optimize query client updating.
|
||||
* Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.
|
||||
* The return value of `callback` is passed through.
|
||||
*/
|
||||
batch: (callback) => {
|
||||
let result;
|
||||
transactions++;
|
||||
try {
|
||||
result = callback();
|
||||
} finally {
|
||||
transactions--;
|
||||
if (!transactions) flush();
|
||||
}
|
||||
return result;
|
||||
},
|
||||
/**
|
||||
* All calls to the wrapped function will be batched.
|
||||
*/
|
||||
batchCalls: (callback) => {
|
||||
return (...args) => {
|
||||
schedule(() => {
|
||||
callback(...args);
|
||||
});
|
||||
};
|
||||
},
|
||||
/**
|
||||
* Schedules a function to be run on the next batch.
|
||||
* By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.
|
||||
*/
|
||||
schedule,
|
||||
/**
|
||||
* Use this method to set a custom notify function.
|
||||
* This can be used to for example wrap notifications with `React.act` while running tests.
|
||||
*/
|
||||
setNotifyFunction: (fn) => {
|
||||
notifyFn = fn;
|
||||
},
|
||||
/**
|
||||
* Use this method to set a custom function to batch notifications together into a single tick.
|
||||
* Framework adapters use this to plug in their own batching primitive, so that a single query
|
||||
* update only triggers one re-render instead of one per subscriber.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
* import { batch } from 'solid-js'
|
||||
*
|
||||
* notifyManager.setBatchNotifyFunction(batch)
|
||||
* ```
|
||||
*/
|
||||
setBatchNotifyFunction: (fn) => {
|
||||
batchNotifyFn = fn;
|
||||
},
|
||||
/**
|
||||
* Configures a custom callback that schedules when the next batch runs.
|
||||
* The default behavior is `setTimeout(callback, 0)`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Schedule batches in the next microtask
|
||||
* notifyManager.setScheduler(queueMicrotask)
|
||||
*
|
||||
* // Schedule batches before the next frame is rendered
|
||||
* notifyManager.setScheduler(requestAnimationFrame)
|
||||
*
|
||||
* // Schedule batches some time in the future
|
||||
* notifyManager.setScheduler((cb) => setTimeout(cb, 10))
|
||||
* ```
|
||||
*/
|
||||
setScheduler: (fn) => {
|
||||
scheduleFn = fn;
|
||||
}
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Handles scheduling and batching callbacks in TanStack Query.
|
||||
*/
|
||||
const notifyManager = createNotifyManager();
|
||||
//#endregion
|
||||
exports.createNotifyManager = createNotifyManager;
|
||||
exports.defaultScheduler = defaultScheduler;
|
||||
exports.notifyManager = notifyManager;
|
||||
|
||||
//# sourceMappingURL=notifyManager.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"notifyManager.cjs","names":["systemSetTimeoutZero"],"sources":["../../src/notifyManager.ts"],"sourcesContent":["// TYPES\n\nimport { systemSetTimeoutZero } from './timeoutManager'\n\ntype NotifyCallback = () => void\n\ntype NotifyFunction = (callback: () => void) => void\n\ntype BatchNotifyFunction = (callback: () => void) => void\n\ntype BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void\n\ntype ScheduleFunction = (callback: () => void) => void\n\n/**\n * Default scheduling function used by the notify manager.\n * Schedules the callback with the system's `setTimeout(callback, 0)`.\n */\nexport const defaultScheduler: ScheduleFunction = systemSetTimeoutZero\n\nexport function createNotifyManager() {\n let queue: Array<NotifyCallback> = []\n let transactions = 0\n let notifyFn: NotifyFunction = (callback) => {\n callback()\n }\n let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => {\n callback()\n }\n let scheduleFn = defaultScheduler\n\n const schedule = (callback: NotifyCallback): void => {\n if (transactions) {\n queue.push(callback)\n } else {\n scheduleFn(() => {\n notifyFn(callback)\n })\n }\n }\n const flush = (): void => {\n const originalQueue = queue\n queue = []\n if (originalQueue.length) {\n scheduleFn(() => {\n batchNotifyFn(() => {\n originalQueue.forEach((callback) => {\n notifyFn(callback)\n })\n })\n })\n }\n }\n\n return {\n /**\n * Batches all updates scheduled inside the passed callback.\n * This is mainly used internally to optimize query client updating.\n * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.\n * The return value of `callback` is passed through.\n */\n batch: <T>(callback: () => T): T => {\n let result\n transactions++\n try {\n result = callback()\n } finally {\n transactions--\n if (!transactions) {\n flush()\n }\n }\n return result\n },\n /**\n * All calls to the wrapped function will be batched.\n */\n batchCalls: <T extends Array<unknown>>(\n callback: BatchCallsCallback<T>,\n ): BatchCallsCallback<T> => {\n return (...args) => {\n schedule(() => {\n callback(...args)\n })\n }\n },\n /**\n * Schedules a function to be run on the next batch.\n * By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.\n */\n schedule,\n /**\n * Use this method to set a custom notify function.\n * This can be used to for example wrap notifications with `React.act` while running tests.\n */\n setNotifyFunction: (fn: NotifyFunction) => {\n notifyFn = fn\n },\n /**\n * Use this method to set a custom function to batch notifications together into a single tick.\n * Framework adapters use this to plug in their own batching primitive, so that a single query\n * update only triggers one re-render instead of one per subscriber.\n *\n * @example\n * ```ts\n * import { notifyManager } from '@tanstack/query-core'\n * import { batch } from 'solid-js'\n *\n * notifyManager.setBatchNotifyFunction(batch)\n * ```\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n /**\n * Configures a custom callback that schedules when the next batch runs.\n * The default behavior is `setTimeout(callback, 0)`.\n *\n * @example\n * ```ts\n * import { notifyManager } from '@tanstack/query-core'\n *\n * // Schedule batches in the next microtask\n * notifyManager.setScheduler(queueMicrotask)\n *\n * // Schedule batches before the next frame is rendered\n * notifyManager.setScheduler(requestAnimationFrame)\n *\n * // Schedule batches some time in the future\n * notifyManager.setScheduler((cb) => setTimeout(cb, 10))\n * ```\n */\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\n\n/**\n * Handles scheduling and batching callbacks in TanStack Query.\n */\nexport const notifyManager = createNotifyManager()\n"],"mappings":";;;;;;AAkBA,MAAa,iDAAqCA,CAAAA,CAAAA;AAElD,SAAgB,sBAAsB;CACpC,IAAI,QAA+B,CAAC;CACpC,IAAI,eAAe;CACnB,IAAI,YAA4B,aAAa;EAC3C,SAAS;CACX;CACA,IAAI,iBAAsC,aAAyB;EACjE,SAAS;CACX;CACA,IAAI,aAAa;CAEjB,MAAM,YAAY,aAAmC;EACnD,IAAI,cACF,MAAM,KAAK,QAAQ;OAEnB,iBAAiB;GACf,SAAS,QAAQ;EACnB,CAAC;CAEL;CACA,MAAM,cAAoB;EACxB,MAAM,gBAAgB;EACtB,QAAQ,CAAC;EACT,IAAI,cAAc,QAChB,iBAAiB;GACf,oBAAoB;IAClB,cAAc,SAAS,aAAa;KAClC,SAAS,QAAQ;IACnB,CAAC;GACH,CAAC;EACH,CAAC;CAEL;CAEA,OAAO;;;;;;;EAOL,QAAW,aAAyB;GAClC,IAAI;GACJ;GACA,IAAI;IACF,SAAS,SAAS;GACpB,UAAU;IACR;IACA,IAAI,CAAC,cACH,MAAM;GAEV;GACA,OAAO;EACT;;;;EAIA,aACE,aAC0B;GAC1B,QAAQ,GAAG,SAAS;IAClB,eAAe;KACb,SAAS,GAAG,IAALine truncated
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
//#region src/notifyManager.d.ts
|
||||
type NotifyCallback = () => void;
|
||||
type NotifyFunction = (callback: () => void) => void;
|
||||
type BatchNotifyFunction = (callback: () => void) => void;
|
||||
type BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void;
|
||||
type ScheduleFunction = (callback: () => void) => void;
|
||||
/**
|
||||
* Default scheduling function used by the notify manager.
|
||||
* Schedules the callback with the system's `setTimeout(callback, 0)`.
|
||||
*/
|
||||
declare const defaultScheduler: ScheduleFunction;
|
||||
declare function createNotifyManager(): {
|
||||
/**
|
||||
* Batches all updates scheduled inside the passed callback.
|
||||
* This is mainly used internally to optimize query client updating.
|
||||
* Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.
|
||||
* The return value of `callback` is passed through.
|
||||
*/
|
||||
readonly batch: <T>(callback: () => T) => T;
|
||||
/**
|
||||
* All calls to the wrapped function will be batched.
|
||||
*/
|
||||
readonly batchCalls: <T extends Array<unknown>>(callback: BatchCallsCallback<T>) => BatchCallsCallback<T>;
|
||||
/**
|
||||
* Schedules a function to be run on the next batch.
|
||||
* By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.
|
||||
*/
|
||||
readonly schedule: (callback: NotifyCallback) => void;
|
||||
/**
|
||||
* Use this method to set a custom notify function.
|
||||
* This can be used to for example wrap notifications with `React.act` while running tests.
|
||||
*/
|
||||
readonly setNotifyFunction: (fn: NotifyFunction) => void;
|
||||
/**
|
||||
* Use this method to set a custom function to batch notifications together into a single tick.
|
||||
* Framework adapters use this to plug in their own batching primitive, so that a single query
|
||||
* update only triggers one re-render instead of one per subscriber.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
* import { batch } from 'solid-js'
|
||||
*
|
||||
* notifyManager.setBatchNotifyFunction(batch)
|
||||
* ```
|
||||
*/
|
||||
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
|
||||
/**
|
||||
* Configures a custom callback that schedules when the next batch runs.
|
||||
* The default behavior is `setTimeout(callback, 0)`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Schedule batches in the next microtask
|
||||
* notifyManager.setScheduler(queueMicrotask)
|
||||
*
|
||||
* // Schedule batches before the next frame is rendered
|
||||
* notifyManager.setScheduler(requestAnimationFrame)
|
||||
*
|
||||
* // Schedule batches some time in the future
|
||||
* notifyManager.setScheduler((cb) => setTimeout(cb, 10))
|
||||
* ```
|
||||
*/
|
||||
readonly setScheduler: (fn: ScheduleFunction) => void;
|
||||
};
|
||||
/**
|
||||
* Handles scheduling and batching callbacks in TanStack Query.
|
||||
*/
|
||||
declare const notifyManager: {
|
||||
/**
|
||||
* Batches all updates scheduled inside the passed callback.
|
||||
* This is mainly used internally to optimize query client updating.
|
||||
* Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.
|
||||
* The return value of `callback` is passed through.
|
||||
*/
|
||||
readonly batch: <T>(callback: () => T) => T;
|
||||
/**
|
||||
* All calls to the wrapped function will be batched.
|
||||
*/
|
||||
readonly batchCalls: <T extends Array<unknown>>(callback: BatchCallsCallback<T>) => BatchCallsCallback<T>;
|
||||
/**
|
||||
* Schedules a function to be run on the next batch.
|
||||
* By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.
|
||||
*/
|
||||
readonly schedule: (callback: NotifyCallback) => void;
|
||||
/**
|
||||
* Use this method to set a custom notify function.
|
||||
* This can be used to for example wrap notifications with `React.act` while running tests.
|
||||
*/
|
||||
readonly setNotifyFunction: (fn: NotifyFunction) => void;
|
||||
/**
|
||||
* Use this method to set a custom function to batch notifications together into a single tick.
|
||||
* Framework adapters use this to plug in their own batching primitive, so that a single query
|
||||
* update only triggers one re-render instead of one per subscriber.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
* import { batch } from 'solid-js'
|
||||
*
|
||||
* notifyManager.setBatchNotifyFunction(batch)
|
||||
* ```
|
||||
*/
|
||||
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
|
||||
/**
|
||||
* Configures a custom callback that schedules when the next batch runs.
|
||||
* The default behavior is `setTimeout(callback, 0)`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Schedule batches in the next microtask
|
||||
* notifyManager.setScheduler(queueMicrotask)
|
||||
*
|
||||
* // Schedule batches before the next frame is rendered
|
||||
* notifyManager.setScheduler(requestAnimationFrame)
|
||||
*
|
||||
* // Schedule batches some time in the future
|
||||
* notifyManager.setScheduler((cb) => setTimeout(cb, 10))
|
||||
* ```
|
||||
*/
|
||||
readonly setScheduler: (fn: ScheduleFunction) => void;
|
||||
};
|
||||
//#endregion
|
||||
export { createNotifyManager, defaultScheduler, notifyManager };
|
||||
//# sourceMappingURL=notifyManager.d.cts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"notifyManager.d.cts","names":[],"sources":["../../src/notifyManager.ts"],"mappings":";KAIK;KAEA,kBAAkB;KAElB,uBAAuB;KAEvB,mBAAmB,UAAU,sBAAsB,MAAM;KAEzD,oBAAoB;;;;;cAMZ,kBAAkB;iBAEf;;;;;;;WAyCJ,QAAA,GAAC,gBAAkB,MAAI;;;;WAgBlB,aAAA,UAAU,gBAAc,UACzB,mBAAmB,OAC5B,mBAAmB;;;;;WAhDI,WAAA,UAAA;;;;;WAgEF,oBAAA,IAAA;;;;;;;;;;;;;;WAgBK,yBAAA,IAAA;;;;;;;;;;;;;;;;;;;WAqBV,eAAA,IAAA;;;;;cAWV;;;;;;;WAlFD,QAAA,GAAC,gBAAkB,MAAI;;;;WAgBlB,aAAA,UAAU,gBAAc,UACzB,mBAAmB,OAC5B,mBAAmB;;;;;WAhDI,WAAA,UAAA;;;;;WAgEF,oBAAA,IAAA;;;;;;;;;;;;;;WAgBK,yBAAA,IAAA;;;;;;;;;;;;;;;;;;;WAqBV,eAAA,IAAA"}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
//#region src/notifyManager.d.ts
|
||||
type NotifyCallback = () => void;
|
||||
type NotifyFunction = (callback: () => void) => void;
|
||||
type BatchNotifyFunction = (callback: () => void) => void;
|
||||
type BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void;
|
||||
type ScheduleFunction = (callback: () => void) => void;
|
||||
/**
|
||||
* Default scheduling function used by the notify manager.
|
||||
* Schedules the callback with the system's `setTimeout(callback, 0)`.
|
||||
*/
|
||||
declare const defaultScheduler: ScheduleFunction;
|
||||
declare function createNotifyManager(): {
|
||||
/**
|
||||
* Batches all updates scheduled inside the passed callback.
|
||||
* This is mainly used internally to optimize query client updating.
|
||||
* Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.
|
||||
* The return value of `callback` is passed through.
|
||||
*/
|
||||
readonly batch: <T>(callback: () => T) => T;
|
||||
/**
|
||||
* All calls to the wrapped function will be batched.
|
||||
*/
|
||||
readonly batchCalls: <T extends Array<unknown>>(callback: BatchCallsCallback<T>) => BatchCallsCallback<T>;
|
||||
/**
|
||||
* Schedules a function to be run on the next batch.
|
||||
* By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.
|
||||
*/
|
||||
readonly schedule: (callback: NotifyCallback) => void;
|
||||
/**
|
||||
* Use this method to set a custom notify function.
|
||||
* This can be used to for example wrap notifications with `React.act` while running tests.
|
||||
*/
|
||||
readonly setNotifyFunction: (fn: NotifyFunction) => void;
|
||||
/**
|
||||
* Use this method to set a custom function to batch notifications together into a single tick.
|
||||
* Framework adapters use this to plug in their own batching primitive, so that a single query
|
||||
* update only triggers one re-render instead of one per subscriber.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
* import { batch } from 'solid-js'
|
||||
*
|
||||
* notifyManager.setBatchNotifyFunction(batch)
|
||||
* ```
|
||||
*/
|
||||
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
|
||||
/**
|
||||
* Configures a custom callback that schedules when the next batch runs.
|
||||
* The default behavior is `setTimeout(callback, 0)`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Schedule batches in the next microtask
|
||||
* notifyManager.setScheduler(queueMicrotask)
|
||||
*
|
||||
* // Schedule batches before the next frame is rendered
|
||||
* notifyManager.setScheduler(requestAnimationFrame)
|
||||
*
|
||||
* // Schedule batches some time in the future
|
||||
* notifyManager.setScheduler((cb) => setTimeout(cb, 10))
|
||||
* ```
|
||||
*/
|
||||
readonly setScheduler: (fn: ScheduleFunction) => void;
|
||||
};
|
||||
/**
|
||||
* Handles scheduling and batching callbacks in TanStack Query.
|
||||
*/
|
||||
declare const notifyManager: {
|
||||
/**
|
||||
* Batches all updates scheduled inside the passed callback.
|
||||
* This is mainly used internally to optimize query client updating.
|
||||
* Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.
|
||||
* The return value of `callback` is passed through.
|
||||
*/
|
||||
readonly batch: <T>(callback: () => T) => T;
|
||||
/**
|
||||
* All calls to the wrapped function will be batched.
|
||||
*/
|
||||
readonly batchCalls: <T extends Array<unknown>>(callback: BatchCallsCallback<T>) => BatchCallsCallback<T>;
|
||||
/**
|
||||
* Schedules a function to be run on the next batch.
|
||||
* By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.
|
||||
*/
|
||||
readonly schedule: (callback: NotifyCallback) => void;
|
||||
/**
|
||||
* Use this method to set a custom notify function.
|
||||
* This can be used to for example wrap notifications with `React.act` while running tests.
|
||||
*/
|
||||
readonly setNotifyFunction: (fn: NotifyFunction) => void;
|
||||
/**
|
||||
* Use this method to set a custom function to batch notifications together into a single tick.
|
||||
* Framework adapters use this to plug in their own batching primitive, so that a single query
|
||||
* update only triggers one re-render instead of one per subscriber.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
* import { batch } from 'solid-js'
|
||||
*
|
||||
* notifyManager.setBatchNotifyFunction(batch)
|
||||
* ```
|
||||
*/
|
||||
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
|
||||
/**
|
||||
* Configures a custom callback that schedules when the next batch runs.
|
||||
* The default behavior is `setTimeout(callback, 0)`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Schedule batches in the next microtask
|
||||
* notifyManager.setScheduler(queueMicrotask)
|
||||
*
|
||||
* // Schedule batches before the next frame is rendered
|
||||
* notifyManager.setScheduler(requestAnimationFrame)
|
||||
*
|
||||
* // Schedule batches some time in the future
|
||||
* notifyManager.setScheduler((cb) => setTimeout(cb, 10))
|
||||
* ```
|
||||
*/
|
||||
readonly setScheduler: (fn: ScheduleFunction) => void;
|
||||
};
|
||||
//#endregion
|
||||
export { createNotifyManager, defaultScheduler, notifyManager };
|
||||
//# sourceMappingURL=notifyManager.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"notifyManager.d.ts","names":[],"sources":["../../src/notifyManager.ts"],"mappings":";KAIK;KAEA,kBAAkB;KAElB,uBAAuB;KAEvB,mBAAmB,UAAU,sBAAsB,MAAM;KAEzD,oBAAoB;;;;;cAMZ,kBAAkB;iBAEf;;;;;;;WAyCJ,QAAA,GAAC,gBAAkB,MAAI;;;;WAgBlB,aAAA,UAAU,gBAAc,UACzB,mBAAmB,OAC5B,mBAAmB;;;;;WAhDI,WAAA,UAAA;;;;;WAgEF,oBAAA,IAAA;;;;;;;;;;;;;;WAgBK,yBAAA,IAAA;;;;;;;;;;;;;;;;;;;WAqBV,eAAA,IAAA;;;;;cAWV;;;;;;;WAlFD,QAAA,GAAC,gBAAkB,MAAI;;;;WAgBlB,aAAA,UAAU,gBAAc,UACzB,mBAAmB,OAC5B,mBAAmB;;;;;WAhDI,WAAA,UAAA;;;;;WAgEF,oBAAA,IAAA;;;;;;;;;;;;;;WAgBK,yBAAA,IAAA;;;;;;;;;;;;;;;;;;;WAqBV,eAAA,IAAA"}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
import { systemSetTimeoutZero } from "./timeoutManager.js";
|
||||
//#region src/notifyManager.ts
|
||||
/**
|
||||
* Default scheduling function used by the notify manager.
|
||||
* Schedules the callback with the system's `setTimeout(callback, 0)`.
|
||||
*/
|
||||
const defaultScheduler = systemSetTimeoutZero;
|
||||
function createNotifyManager() {
|
||||
let queue = [];
|
||||
let transactions = 0;
|
||||
let notifyFn = (callback) => {
|
||||
callback();
|
||||
};
|
||||
let batchNotifyFn = (callback) => {
|
||||
callback();
|
||||
};
|
||||
let scheduleFn = defaultScheduler;
|
||||
const schedule = (callback) => {
|
||||
if (transactions) queue.push(callback);
|
||||
else scheduleFn(() => {
|
||||
notifyFn(callback);
|
||||
});
|
||||
};
|
||||
const flush = () => {
|
||||
const originalQueue = queue;
|
||||
queue = [];
|
||||
if (originalQueue.length) scheduleFn(() => {
|
||||
batchNotifyFn(() => {
|
||||
originalQueue.forEach((callback) => {
|
||||
notifyFn(callback);
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
return {
|
||||
/**
|
||||
* Batches all updates scheduled inside the passed callback.
|
||||
* This is mainly used internally to optimize query client updating.
|
||||
* Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.
|
||||
* The return value of `callback` is passed through.
|
||||
*/
|
||||
batch: (callback) => {
|
||||
let result;
|
||||
transactions++;
|
||||
try {
|
||||
result = callback();
|
||||
} finally {
|
||||
transactions--;
|
||||
if (!transactions) flush();
|
||||
}
|
||||
return result;
|
||||
},
|
||||
/**
|
||||
* All calls to the wrapped function will be batched.
|
||||
*/
|
||||
batchCalls: (callback) => {
|
||||
return (...args) => {
|
||||
schedule(() => {
|
||||
callback(...args);
|
||||
});
|
||||
};
|
||||
},
|
||||
/**
|
||||
* Schedules a function to be run on the next batch.
|
||||
* By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.
|
||||
*/
|
||||
schedule,
|
||||
/**
|
||||
* Use this method to set a custom notify function.
|
||||
* This can be used to for example wrap notifications with `React.act` while running tests.
|
||||
*/
|
||||
setNotifyFunction: (fn) => {
|
||||
notifyFn = fn;
|
||||
},
|
||||
/**
|
||||
* Use this method to set a custom function to batch notifications together into a single tick.
|
||||
* Framework adapters use this to plug in their own batching primitive, so that a single query
|
||||
* update only triggers one re-render instead of one per subscriber.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
* import { batch } from 'solid-js'
|
||||
*
|
||||
* notifyManager.setBatchNotifyFunction(batch)
|
||||
* ```
|
||||
*/
|
||||
setBatchNotifyFunction: (fn) => {
|
||||
batchNotifyFn = fn;
|
||||
},
|
||||
/**
|
||||
* Configures a custom callback that schedules when the next batch runs.
|
||||
* The default behavior is `setTimeout(callback, 0)`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { notifyManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Schedule batches in the next microtask
|
||||
* notifyManager.setScheduler(queueMicrotask)
|
||||
*
|
||||
* // Schedule batches before the next frame is rendered
|
||||
* notifyManager.setScheduler(requestAnimationFrame)
|
||||
*
|
||||
* // Schedule batches some time in the future
|
||||
* notifyManager.setScheduler((cb) => setTimeout(cb, 10))
|
||||
* ```
|
||||
*/
|
||||
setScheduler: (fn) => {
|
||||
scheduleFn = fn;
|
||||
}
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Handles scheduling and batching callbacks in TanStack Query.
|
||||
*/
|
||||
const notifyManager = createNotifyManager();
|
||||
//#endregion
|
||||
export { createNotifyManager, defaultScheduler, notifyManager };
|
||||
|
||||
//# sourceMappingURL=notifyManager.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"notifyManager.js","names":[],"sources":["../../src/notifyManager.ts"],"sourcesContent":["// TYPES\n\nimport { systemSetTimeoutZero } from './timeoutManager'\n\ntype NotifyCallback = () => void\n\ntype NotifyFunction = (callback: () => void) => void\n\ntype BatchNotifyFunction = (callback: () => void) => void\n\ntype BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void\n\ntype ScheduleFunction = (callback: () => void) => void\n\n/**\n * Default scheduling function used by the notify manager.\n * Schedules the callback with the system's `setTimeout(callback, 0)`.\n */\nexport const defaultScheduler: ScheduleFunction = systemSetTimeoutZero\n\nexport function createNotifyManager() {\n let queue: Array<NotifyCallback> = []\n let transactions = 0\n let notifyFn: NotifyFunction = (callback) => {\n callback()\n }\n let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => {\n callback()\n }\n let scheduleFn = defaultScheduler\n\n const schedule = (callback: NotifyCallback): void => {\n if (transactions) {\n queue.push(callback)\n } else {\n scheduleFn(() => {\n notifyFn(callback)\n })\n }\n }\n const flush = (): void => {\n const originalQueue = queue\n queue = []\n if (originalQueue.length) {\n scheduleFn(() => {\n batchNotifyFn(() => {\n originalQueue.forEach((callback) => {\n notifyFn(callback)\n })\n })\n })\n }\n }\n\n return {\n /**\n * Batches all updates scheduled inside the passed callback.\n * This is mainly used internally to optimize query client updating.\n * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.\n * The return value of `callback` is passed through.\n */\n batch: <T>(callback: () => T): T => {\n let result\n transactions++\n try {\n result = callback()\n } finally {\n transactions--\n if (!transactions) {\n flush()\n }\n }\n return result\n },\n /**\n * All calls to the wrapped function will be batched.\n */\n batchCalls: <T extends Array<unknown>>(\n callback: BatchCallsCallback<T>,\n ): BatchCallsCallback<T> => {\n return (...args) => {\n schedule(() => {\n callback(...args)\n })\n }\n },\n /**\n * Schedules a function to be run on the next batch.\n * By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.\n */\n schedule,\n /**\n * Use this method to set a custom notify function.\n * This can be used to for example wrap notifications with `React.act` while running tests.\n */\n setNotifyFunction: (fn: NotifyFunction) => {\n notifyFn = fn\n },\n /**\n * Use this method to set a custom function to batch notifications together into a single tick.\n * Framework adapters use this to plug in their own batching primitive, so that a single query\n * update only triggers one re-render instead of one per subscriber.\n *\n * @example\n * ```ts\n * import { notifyManager } from '@tanstack/query-core'\n * import { batch } from 'solid-js'\n *\n * notifyManager.setBatchNotifyFunction(batch)\n * ```\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n /**\n * Configures a custom callback that schedules when the next batch runs.\n * The default behavior is `setTimeout(callback, 0)`.\n *\n * @example\n * ```ts\n * import { notifyManager } from '@tanstack/query-core'\n *\n * // Schedule batches in the next microtask\n * notifyManager.setScheduler(queueMicrotask)\n *\n * // Schedule batches before the next frame is rendered\n * notifyManager.setScheduler(requestAnimationFrame)\n *\n * // Schedule batches some time in the future\n * notifyManager.setScheduler((cb) => setTimeout(cb, 10))\n * ```\n */\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\n\n/**\n * Handles scheduling and batching callbacks in TanStack Query.\n */\nexport const notifyManager = createNotifyManager()\n"],"mappings":";;;;;;AAkBA,MAAa,mBAAqC;AAElD,SAAgB,sBAAsB;CACpC,IAAI,QAA+B,CAAC;CACpC,IAAI,eAAe;CACnB,IAAI,YAA4B,aAAa;EAC3C,SAAS;CACX;CACA,IAAI,iBAAsC,aAAyB;EACjE,SAAS;CACX;CACA,IAAI,aAAa;CAEjB,MAAM,YAAY,aAAmC;EACnD,IAAI,cACF,MAAM,KAAK,QAAQ;OAEnB,iBAAiB;GACf,SAAS,QAAQ;EACnB,CAAC;CAEL;CACA,MAAM,cAAoB;EACxB,MAAM,gBAAgB;EACtB,QAAQ,CAAC;EACT,IAAI,cAAc,QAChB,iBAAiB;GACf,oBAAoB;IAClB,cAAc,SAAS,aAAa;KAClC,SAAS,QAAQ;IACnB,CAAC;GACH,CAAC;EACH,CAAC;CAEL;CAEA,OAAO;;;;;;;EAOL,QAAW,aAAyB;GAClC,IAAI;GACJ;GACA,IAAI;IACF,SAAS,SAAS;GACpB,UAAU;IACR;IACA,IAAI,CAAC,cACH,MAAM;GAEV;GACA,OAAO;EACT;;;;EAIA,aACE,aAC0B;GAC1B,QAAQ,GAAG,SAAS;IAClB,eAAe;KACb,SAAS,GAAG,IAAI;IAClB,CAAC;GACH;EACF;;;;;EAKA;;;;;Line truncated
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
|
||||
const require_subscribable = require("./subscribable.cjs");
|
||||
//#region src/onlineManager.ts
|
||||
var _online = /* @__PURE__ */ new WeakMap();
|
||||
var _cleanup = /* @__PURE__ */ new WeakMap();
|
||||
var _setup = /* @__PURE__ */ new WeakMap();
|
||||
/**
|
||||
* The `OnlineManager` manages the online state within TanStack Query. It can
|
||||
* be used to change the default event listeners or to manually change the
|
||||
* online state.
|
||||
*
|
||||
* By default, the `onlineManager` assumes an active network connection, and
|
||||
* listens to the `online` and `offline` events on the `window` object to
|
||||
* detect changes.
|
||||
*/
|
||||
var OnlineManager = class extends require_subscribable.Subscribable {
|
||||
constructor() {
|
||||
super();
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _online, true);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _cleanup, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _setup, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_setup, this, (onOnline) => {
|
||||
if (typeof window !== "undefined" && window.addEventListener) {
|
||||
const onlineListener = () => onOnline(true);
|
||||
const offlineListener = () => onOnline(false);
|
||||
window.addEventListener("online", onlineListener, false);
|
||||
window.addEventListener("offline", offlineListener, false);
|
||||
return () => {
|
||||
window.removeEventListener("online", onlineListener);
|
||||
window.removeEventListener("offline", offlineListener);
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
onSubscribe() {
|
||||
if (!require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) this.setEventListener(require_classPrivateFieldSet2._classPrivateFieldGet2(_setup, this));
|
||||
}
|
||||
onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _classPrivateFieldGet2$1;
|
||||
(_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet2$1 === void 0 || _classPrivateFieldGet2$1.call(this);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_cleanup, this, void 0);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* `setEventListener` can be used to set a custom event listener that will
|
||||
* be used to determine the online state. The provided `setup` function
|
||||
* receives a `setOnline` callback that should be called with a `boolean`
|
||||
* whenever the online state changes.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import NetInfo from '@react-native-community/netinfo'
|
||||
* import { onlineManager } from '@tanstack/query-core'
|
||||
*
|
||||
* onlineManager.setEventListener((setOnline) => {
|
||||
* return NetInfo.addEventListener((state) => {
|
||||
* setOnline(!!state.isConnected)
|
||||
* })
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
setEventListener(setup) {
|
||||
var _classPrivateFieldGet3;
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_setup, this, setup);
|
||||
(_classPrivateFieldGet3 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.call(this);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_cleanup, this, setup(this.setOnline.bind(this)));
|
||||
}
|
||||
/**
|
||||
* `setOnline` can be used to manually set the online state.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { onlineManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Set to online
|
||||
* onlineManager.setOnline(true)
|
||||
*
|
||||
* // Set to offline
|
||||
* onlineManager.setOnline(false)
|
||||
* ```
|
||||
*/
|
||||
setOnline(online) {
|
||||
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_online, this) !== online) {
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_online, this, online);
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(online);
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* `isOnline` can be used to get the current online state.
|
||||
*/
|
||||
isOnline() {
|
||||
return require_classPrivateFieldSet2._classPrivateFieldGet2(_online, this);
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.
|
||||
*/
|
||||
const onlineManager = new OnlineManager();
|
||||
//#endregion
|
||||
exports.OnlineManager = OnlineManager;
|
||||
exports.onlineManager = onlineManager;
|
||||
|
||||
//# sourceMappingURL=onlineManager.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"onlineManager.cjs","names":["Subscribable"],"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\n\n/**\n * The `OnlineManager` manages the online state within TanStack Query. It can\n * be used to change the default event listeners or to manually change the\n * online state.\n *\n * By default, the `onlineManager` assumes an active network connection, and\n * listens to the `online` and `offline` events on the `window` object to\n * detect changes.\n */\nexport class OnlineManager extends Subscribable<Listener> {\n #online = true\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onOnline) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const onlineListener = () => onOnline(true)\n const offlineListener = () => onOnline(false)\n // Listen to online\n window.addEventListener('online', onlineListener, false)\n window.addEventListener('offline', offlineListener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('online', onlineListener)\n window.removeEventListener('offline', offlineListener)\n }\n }\n\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n /**\n * `setEventListener` can be used to set a custom event listener that will\n * be used to determine the online state. The provided `setup` function\n * receives a `setOnline` callback that should be called with a `boolean`\n * whenever the online state changes.\n *\n * @example\n * ```ts\n * import NetInfo from '@react-native-community/netinfo'\n * import { onlineManager } from '@tanstack/query-core'\n *\n * onlineManager.setEventListener((setOnline) => {\n * return NetInfo.addEventListener((state) => {\n * setOnline(!!state.isConnected)\n * })\n * })\n * ```\n */\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\n }\n\n /**\n * `setOnline` can be used to manually set the online state.\n *\n * @example\n * ```ts\n * import { onlineManager } from '@tanstack/query-core'\n *\n * // Set to online\n * onlineManager.setOnline(true)\n *\n * // Set to offline\n * onlineManager.setOnline(false)\n * ```\n */\n setOnline(online: boolean): void {\n const changed = this.#online !== online\n\n if (changed) {\n this.#online = online\n this.listeners.forEach((listener) => {\n listener(online)\n })\n }\n }\n\n /**\n * `isOnline` can be used to get the current online state.\n */\n isOnline(): boolean {\n return this.#online\n }\n}\n\n/**\n * Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.\n */\nexport const onlineManager = new OnlineManager()\n"],"mappings":";;;;;;;;;;;;;;;;AAcA,IAAa,gBAAb,cAAmCA,qBAAAA,aAAuB;CAMxD,cAAc;EACZ,MAAM;EANE,8BAAA,2BAAA,MAAA,SAAA,IAAA;;;EAOR,8BAAA,uBAAA,QAAA,OAAe,aAAa;GAG1B,IAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;IAC5D,MAAM,uBAAuB,SAAS,IAAI;IAC1C,MAAM,wBAAwB,SAAS,KAAK;IAE5C,OAAO,iBAAiB,UAAU,gBAAgB,KAAK;IACvD,OAAO,iBAAiB,WAAW,iBAAiB,KAAK;IAEzD,aAAa;KAEX,OAAO,oBAAoB,UAAU,cAAc;KACnD,OAAO,oBAAoB,WAAW,eAAe;IACvD;GACF;EAGF,CAAA;CACF;CAEA,cAA8B;EAC5B,IAAI,CAAA,8BAAA,uBAAA,UAAC,IAAA,GACH,KAAK,iBAAA,8BAAA,uBAAA,QAAiB,IAAA,CAAW;CAErC;CAEA,gBAA0B;EACxB,IAAI,CAAC,KAAK,aAAa,GAAG;;GACxB,CAAA,2BAAA,8BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,6BAAA,KAAA,KAAA,yBAAA,KAAA,IAAgB;GAChB,8BAAA,uBAAA,UAAA,MAAgB,KAAA,CAAA;EAClB;CACF;;;;;;;;;;;;;;;;;;;CAoBA,iBAAiB,OAAsB;;EACrC,8BAAA,uBAAA,QAAA,MAAc,KAAA;EACd,CAAA,yBAAA,8BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,2BAAA,KAAA,KAAA,uBAAA,KAAA,IAAgB;EAChB,8BAAA,uBAAA,UAAA,MAAgB,MAAM,KAAK,UAAU,KAAK,IAAI,CAAC,CAAA;CACjD;;;;;;;;;;;;;;;CAgBA,UAAU,QAAuB;EAG/B,IAAA,8BAAA,uBAAA,SAFgB,IAAA,MAAiB,QAEpB;GACX,8BAAA,uBAAA,SAAA,MAAe,MAAA;GACf,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,MAAM;GACjB,CAAC;EACH;CACF;;;;CAKA,WAAoB;EAClB,OAAA,8BAAA,uBAAA,SAAO,IAAA;CACT;AACF;;;;AAKA,MAAa,gBAAgB,IAAI,cAAc"}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import { t as Subscribable } from "./subscribable-CbifVTKz.cjs";
|
||||
//#region src/onlineManager.d.ts
|
||||
type Listener = (online: boolean) => void;
|
||||
type SetupFn = (setOnline: Listener) => (() => void) | undefined;
|
||||
/**
|
||||
* The `OnlineManager` manages the online state within TanStack Query. It can
|
||||
* be used to change the default event listeners or to manually change the
|
||||
* online state.
|
||||
*
|
||||
* By default, the `onlineManager` assumes an active network connection, and
|
||||
* listens to the `online` and `offline` events on the `window` object to
|
||||
* detect changes.
|
||||
*/
|
||||
declare class OnlineManager extends Subscribable<Listener> {
|
||||
#private;
|
||||
constructor();
|
||||
protected onSubscribe(): void;
|
||||
protected onUnsubscribe(): void;
|
||||
/**
|
||||
* `setEventListener` can be used to set a custom event listener that will
|
||||
* be used to determine the online state. The provided `setup` function
|
||||
* receives a `setOnline` callback that should be called with a `boolean`
|
||||
* whenever the online state changes.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import NetInfo from '@react-native-community/netinfo'
|
||||
* import { onlineManager } from '@tanstack/query-core'
|
||||
*
|
||||
* onlineManager.setEventListener((setOnline) => {
|
||||
* return NetInfo.addEventListener((state) => {
|
||||
* setOnline(!!state.isConnected)
|
||||
* })
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
setEventListener(setup: SetupFn): void;
|
||||
/**
|
||||
* `setOnline` can be used to manually set the online state.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { onlineManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Set to online
|
||||
* onlineManager.setOnline(true)
|
||||
*
|
||||
* // Set to offline
|
||||
* onlineManager.setOnline(false)
|
||||
* ```
|
||||
*/
|
||||
setOnline(online: boolean): void;
|
||||
/**
|
||||
* `isOnline` can be used to get the current online state.
|
||||
*/
|
||||
isOnline(): boolean;
|
||||
}
|
||||
/**
|
||||
* Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.
|
||||
*/
|
||||
declare const onlineManager: OnlineManager;
|
||||
//#endregion
|
||||
export { OnlineManager, onlineManager };
|
||||
//# sourceMappingURL=onlineManager.d.cts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"onlineManager.d.cts","names":[],"sources":["../../src/onlineManager.ts"],"mappings":";;KAEK,YAAY;KACZ,WAAW,WAAW;;;;;;;;;;cAWd,sBAAsB,aAAa;;;YA6BpC;YAMA;;;;;;;;;;;;;;;;;;;EAyBV,iBAAiB,OAAO;;;;;;;;;;;;;;;EAoBxB,UAAU;;;;EAcV;;;;;cAQW,eAAa"}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import { t as Subscribable } from "./subscribable-CbifVTKz.js";
|
||||
//#region src/onlineManager.d.ts
|
||||
type Listener = (online: boolean) => void;
|
||||
type SetupFn = (setOnline: Listener) => (() => void) | undefined;
|
||||
/**
|
||||
* The `OnlineManager` manages the online state within TanStack Query. It can
|
||||
* be used to change the default event listeners or to manually change the
|
||||
* online state.
|
||||
*
|
||||
* By default, the `onlineManager` assumes an active network connection, and
|
||||
* listens to the `online` and `offline` events on the `window` object to
|
||||
* detect changes.
|
||||
*/
|
||||
declare class OnlineManager extends Subscribable<Listener> {
|
||||
#private;
|
||||
constructor();
|
||||
protected onSubscribe(): void;
|
||||
protected onUnsubscribe(): void;
|
||||
/**
|
||||
* `setEventListener` can be used to set a custom event listener that will
|
||||
* be used to determine the online state. The provided `setup` function
|
||||
* receives a `setOnline` callback that should be called with a `boolean`
|
||||
* whenever the online state changes.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import NetInfo from '@react-native-community/netinfo'
|
||||
* import { onlineManager } from '@tanstack/query-core'
|
||||
*
|
||||
* onlineManager.setEventListener((setOnline) => {
|
||||
* return NetInfo.addEventListener((state) => {
|
||||
* setOnline(!!state.isConnected)
|
||||
* })
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
setEventListener(setup: SetupFn): void;
|
||||
/**
|
||||
* `setOnline` can be used to manually set the online state.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { onlineManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Set to online
|
||||
* onlineManager.setOnline(true)
|
||||
*
|
||||
* // Set to offline
|
||||
* onlineManager.setOnline(false)
|
||||
* ```
|
||||
*/
|
||||
setOnline(online: boolean): void;
|
||||
/**
|
||||
* `isOnline` can be used to get the current online state.
|
||||
*/
|
||||
isOnline(): boolean;
|
||||
}
|
||||
/**
|
||||
* Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.
|
||||
*/
|
||||
declare const onlineManager: OnlineManager;
|
||||
//#endregion
|
||||
export { OnlineManager, onlineManager };
|
||||
//# sourceMappingURL=onlineManager.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"onlineManager.d.ts","names":[],"sources":["../../src/onlineManager.ts"],"mappings":";;KAEK,YAAY;KACZ,WAAW,WAAW;;;;;;;;;;cAWd,sBAAsB,aAAa;;;YA6BpC;YAMA;;;;;;;;;;;;;;;;;;;EAyBV,iBAAiB,OAAO;;;;;;;;;;;;;;;EAoBxB,UAAU;;;;EAcV;;;;;cAQW,eAAa"}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
|
||||
import { Subscribable } from "./subscribable.js";
|
||||
//#region src/onlineManager.ts
|
||||
var _online = /* @__PURE__ */ new WeakMap();
|
||||
var _cleanup = /* @__PURE__ */ new WeakMap();
|
||||
var _setup = /* @__PURE__ */ new WeakMap();
|
||||
/**
|
||||
* The `OnlineManager` manages the online state within TanStack Query. It can
|
||||
* be used to change the default event listeners or to manually change the
|
||||
* online state.
|
||||
*
|
||||
* By default, the `onlineManager` assumes an active network connection, and
|
||||
* listens to the `online` and `offline` events on the `window` object to
|
||||
* detect changes.
|
||||
*/
|
||||
var OnlineManager = class extends Subscribable {
|
||||
constructor() {
|
||||
super();
|
||||
_classPrivateFieldInitSpec(this, _online, true);
|
||||
_classPrivateFieldInitSpec(this, _cleanup, void 0);
|
||||
_classPrivateFieldInitSpec(this, _setup, void 0);
|
||||
_classPrivateFieldSet2(_setup, this, (onOnline) => {
|
||||
if (typeof window !== "undefined" && window.addEventListener) {
|
||||
const onlineListener = () => onOnline(true);
|
||||
const offlineListener = () => onOnline(false);
|
||||
window.addEventListener("online", onlineListener, false);
|
||||
window.addEventListener("offline", offlineListener, false);
|
||||
return () => {
|
||||
window.removeEventListener("online", onlineListener);
|
||||
window.removeEventListener("offline", offlineListener);
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
onSubscribe() {
|
||||
if (!_classPrivateFieldGet2(_cleanup, this)) this.setEventListener(_classPrivateFieldGet2(_setup, this));
|
||||
}
|
||||
onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _classPrivateFieldGet2$1;
|
||||
(_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet2$1 === void 0 || _classPrivateFieldGet2$1.call(this);
|
||||
_classPrivateFieldSet2(_cleanup, this, void 0);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* `setEventListener` can be used to set a custom event listener that will
|
||||
* be used to determine the online state. The provided `setup` function
|
||||
* receives a `setOnline` callback that should be called with a `boolean`
|
||||
* whenever the online state changes.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import NetInfo from '@react-native-community/netinfo'
|
||||
* import { onlineManager } from '@tanstack/query-core'
|
||||
*
|
||||
* onlineManager.setEventListener((setOnline) => {
|
||||
* return NetInfo.addEventListener((state) => {
|
||||
* setOnline(!!state.isConnected)
|
||||
* })
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
setEventListener(setup) {
|
||||
var _classPrivateFieldGet3;
|
||||
_classPrivateFieldSet2(_setup, this, setup);
|
||||
(_classPrivateFieldGet3 = _classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.call(this);
|
||||
_classPrivateFieldSet2(_cleanup, this, setup(this.setOnline.bind(this)));
|
||||
}
|
||||
/**
|
||||
* `setOnline` can be used to manually set the online state.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { onlineManager } from '@tanstack/query-core'
|
||||
*
|
||||
* // Set to online
|
||||
* onlineManager.setOnline(true)
|
||||
*
|
||||
* // Set to offline
|
||||
* onlineManager.setOnline(false)
|
||||
* ```
|
||||
*/
|
||||
setOnline(online) {
|
||||
if (_classPrivateFieldGet2(_online, this) !== online) {
|
||||
_classPrivateFieldSet2(_online, this, online);
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(online);
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* `isOnline` can be used to get the current online state.
|
||||
*/
|
||||
isOnline() {
|
||||
return _classPrivateFieldGet2(_online, this);
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.
|
||||
*/
|
||||
const onlineManager = new OnlineManager();
|
||||
//#endregion
|
||||
export { OnlineManager, onlineManager };
|
||||
|
||||
//# sourceMappingURL=onlineManager.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"onlineManager.js","names":[],"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\n\n/**\n * The `OnlineManager` manages the online state within TanStack Query. It can\n * be used to change the default event listeners or to manually change the\n * online state.\n *\n * By default, the `onlineManager` assumes an active network connection, and\n * listens to the `online` and `offline` events on the `window` object to\n * detect changes.\n */\nexport class OnlineManager extends Subscribable<Listener> {\n #online = true\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onOnline) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const onlineListener = () => onOnline(true)\n const offlineListener = () => onOnline(false)\n // Listen to online\n window.addEventListener('online', onlineListener, false)\n window.addEventListener('offline', offlineListener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('online', onlineListener)\n window.removeEventListener('offline', offlineListener)\n }\n }\n\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n /**\n * `setEventListener` can be used to set a custom event listener that will\n * be used to determine the online state. The provided `setup` function\n * receives a `setOnline` callback that should be called with a `boolean`\n * whenever the online state changes.\n *\n * @example\n * ```ts\n * import NetInfo from '@react-native-community/netinfo'\n * import { onlineManager } from '@tanstack/query-core'\n *\n * onlineManager.setEventListener((setOnline) => {\n * return NetInfo.addEventListener((state) => {\n * setOnline(!!state.isConnected)\n * })\n * })\n * ```\n */\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\n }\n\n /**\n * `setOnline` can be used to manually set the online state.\n *\n * @example\n * ```ts\n * import { onlineManager } from '@tanstack/query-core'\n *\n * // Set to online\n * onlineManager.setOnline(true)\n *\n * // Set to offline\n * onlineManager.setOnline(false)\n * ```\n */\n setOnline(online: boolean): void {\n const changed = this.#online !== online\n\n if (changed) {\n this.#online = online\n this.listeners.forEach((listener) => {\n listener(online)\n })\n }\n }\n\n /**\n * `isOnline` can be used to get the current online state.\n */\n isOnline(): boolean {\n return this.#online\n }\n}\n\n/**\n * Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.\n */\nexport const onlineManager = new OnlineManager()\n"],"mappings":";;;;;;;;;;;;;;;AAcA,IAAa,gBAAb,cAAmC,aAAuB;CAMxD,cAAc;EACZ,MAAM;EANE,2BAAA,MAAA,SAAA,IAAA;;;EAOR,uBAAA,QAAA,OAAe,aAAa;GAG1B,IAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;IAC5D,MAAM,uBAAuB,SAAS,IAAI;IAC1C,MAAM,wBAAwB,SAAS,KAAK;IAE5C,OAAO,iBAAiB,UAAU,gBAAgB,KAAK;IACvD,OAAO,iBAAiB,WAAW,iBAAiB,KAAK;IAEzD,aAAa;KAEX,OAAO,oBAAoB,UAAU,cAAc;KACnD,OAAO,oBAAoB,WAAW,eAAe;IACvD;GACF;EAGF,CAAA;CACF;CAEA,cAA8B;EAC5B,IAAI,CAAA,uBAAA,UAAC,IAAA,GACH,KAAK,iBAAA,uBAAA,QAAiB,IAAA,CAAW;CAErC;CAEA,gBAA0B;EACxB,IAAI,CAAC,KAAK,aAAa,GAAG;;GACxB,CAAA,2BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,6BAAA,KAAA,KAAA,yBAAA,KAAA,IAAgB;GAChB,uBAAA,UAAA,MAAgB,KAAA,CAAA;EAClB;CACF;;;;;;;;;;;;;;;;;;;CAoBA,iBAAiB,OAAsB;;EACrC,uBAAA,QAAA,MAAc,KAAA;EACd,CAAA,yBAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,2BAAA,KAAA,KAAA,uBAAA,KAAA,IAAgB;EAChB,uBAAA,UAAA,MAAgB,MAAM,KAAK,UAAU,KAAK,IAAI,CAAC,CAAA;CACjD;;;;;;;;;;;;;;;CAgBA,UAAU,QAAuB;EAG/B,IAAA,uBAAA,SAFgB,IAAA,MAAiB,QAEpB;GACX,uBAAA,SAAA,MAAe,MAAA;GACf,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,MAAM;GACjB,CAAC;EACH;CACF;;;;CAKA,WAAoB;EAClB,OAAA,uBAAA,SAAO,IAAA;CACT;AACF;;;;AAKA,MAAa,gBAAgB,IAAI,cAAc"}
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
|
||||
const require_utils = require("./utils.cjs");
|
||||
const require_subscribable = require("./subscribable.cjs");
|
||||
const require_notifyManager = require("./notifyManager.cjs");
|
||||
const require_classPrivateMethodInitSpec = require("./classPrivateMethodInitSpec-DVhcLejn.cjs");
|
||||
const require_queryObserver = require("./queryObserver.cjs");
|
||||
//#region src/queriesObserver.ts
|
||||
function difference(array1, array2) {
|
||||
const excludeSet = new Set(array2);
|
||||
return array1.filter((x) => !excludeSet.has(x));
|
||||
}
|
||||
var _client = /* @__PURE__ */ new WeakMap();
|
||||
var _result = /* @__PURE__ */ new WeakMap();
|
||||
var _queries = /* @__PURE__ */ new WeakMap();
|
||||
var _options = /* @__PURE__ */ new WeakMap();
|
||||
var _observers = /* @__PURE__ */ new WeakMap();
|
||||
var _combinedResult = /* @__PURE__ */ new WeakMap();
|
||||
var _lastCombine = /* @__PURE__ */ new WeakMap();
|
||||
var _lastResult = /* @__PURE__ */ new WeakMap();
|
||||
var _lastQueryHashes = /* @__PURE__ */ new WeakMap();
|
||||
var _observerMatches = /* @__PURE__ */ new WeakMap();
|
||||
var _QueriesObserver_brand = /* @__PURE__ */ new WeakSet();
|
||||
/**
|
||||
* A `QueriesObserver` watches an array of queries at once, exposing them as
|
||||
* a single array of `QueryObserverResult`s (or, when a `combine` option is
|
||||
* given, as a combined value derived from that array). It manages one
|
||||
* internal `QueryObserver` per query, and is the primitive that framework
|
||||
* adapters (e.g. `useQueries`) build their hooks on top of.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const observer = new QueriesObserver(queryClient, [
|
||||
* { queryKey: ['post', 1], queryFn: fetchPost },
|
||||
* { queryKey: ['post', 2], queryFn: fetchPost },
|
||||
* ])
|
||||
*
|
||||
* const unsubscribe = observer.subscribe((result) => {
|
||||
* console.log(result)
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
var QueriesObserver = class extends require_subscribable.Subscribable {
|
||||
constructor(client, queries, options) {
|
||||
super();
|
||||
require_classPrivateMethodInitSpec._classPrivateMethodInitSpec(this, _QueriesObserver_brand);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _client, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _result, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _queries, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _options, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _observers, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _combinedResult, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _lastCombine, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _lastResult, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _lastQueryHashes, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _observerMatches, []);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_client, this, client);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_options, this, options);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_queries, this, []);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_observers, this, []);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_result, this, []);
|
||||
this.setQueries(queries);
|
||||
}
|
||||
onSubscribe() {
|
||||
if (this.listeners.size === 1) require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).forEach((observer) => {
|
||||
observer.subscribe((result) => {
|
||||
require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _onUpdate).call(this, observer, result);
|
||||
});
|
||||
});
|
||||
}
|
||||
onUnsubscribe() {
|
||||
if (!this.listeners.size) this.destroy();
|
||||
}
|
||||
/**
|
||||
* Stops observing all queries: clears all listeners and destroys every
|
||||
* underlying `QueryObserver` this observer manages.
|
||||
*/
|
||||
destroy() {
|
||||
this.listeners = /* @__PURE__ */ new Set();
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).forEach((observer) => {
|
||||
observer.destroy();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Replaces the set of queries being observed. Existing `QueryObserver`s
|
||||
* are reused for queries that match an already-observed query hash;
|
||||
* observers for queries that are no longer present are destroyed, and new
|
||||
* observers are created and subscribed to for newly added queries.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* observer.setQueries([
|
||||
* { queryKey: ['post', 1], queryFn: fetchPost },
|
||||
* { queryKey: ['post', 3], queryFn: fetchPost },
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
setQueries(queries, options) {
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_queries, this, queries);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_options, this, options);
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
const queryHashes = queries.map((query) => require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this).defaultQueryOptions(query).queryHash);
|
||||
if (new Set(queryHashes).size !== queryHashes.length) console.warn("[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.");
|
||||
}
|
||||
require_notifyManager.notifyManager.batch(() => {
|
||||
const prevObservers = require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this);
|
||||
const newObserverMatches = require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _findMatchingObservers).call(this, require_classPrivateFieldSet2._classPrivateFieldGet2(_queries, this));
|
||||
newObserverMatches.forEach((match) => match.observer.setOptions(match.defaultedQueryOptions));
|
||||
const newObservers = newObserverMatches.map((match) => match.observer);
|
||||
const newResult = newObservers.map((observer) => observer.getCurrentResult());
|
||||
const hasLengthChange = prevObservers.length !== newObservers.length;
|
||||
const hasIndexChange = newObservers.some((observer, index) => observer !== prevObservers[index]);
|
||||
const hasStructuralChange = hasLengthChange || hasIndexChange;
|
||||
const hasResultChange = hasStructuralChange ? true : newResult.some((result, index) => {
|
||||
const prev = require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this)[index];
|
||||
return !prev || !require_utils.shallowEqualObjects(result, prev);
|
||||
});
|
||||
if (!hasStructuralChange && !hasResultChange) return;
|
||||
if (hasStructuralChange) {
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_observerMatches, this, newObserverMatches);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_observers, this, newObservers);
|
||||
}
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_result, this, newResult);
|
||||
if (!this.hasListeners()) return;
|
||||
if (hasStructuralChange) {
|
||||
difference(prevObservers, newObservers).forEach((observer) => {
|
||||
observer.destroy();
|
||||
});
|
||||
difference(newObservers, prevObservers).forEach((observer) => {
|
||||
observer.subscribe((result) => {
|
||||
require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _onUpdate).call(this, observer, result);
|
||||
});
|
||||
});
|
||||
}
|
||||
require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _notify).call(this);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Returns the most recently computed array of `QueryObserverResult`s, one
|
||||
* per observed query, in the same order as the queries passed to the
|
||||
* constructor or `setQueries`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const results = observer.getCurrentResult()
|
||||
* const data = results.map((result) => result.data)
|
||||
* ```
|
||||
*/
|
||||
getCurrentResult() {
|
||||
return require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this);
|
||||
}
|
||||
/**
|
||||
* Returns the underlying `Query` instances currently being observed, in
|
||||
* the same order as the queries passed to the constructor or `setQueries`.
|
||||
*/
|
||||
getQueries() {
|
||||
return require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).map((observer) => observer.getCurrentQuery());
|
||||
}
|
||||
/**
|
||||
* Returns the underlying `QueryObserver` instances this observer manages,
|
||||
* in the same order as the queries passed to the constructor or
|
||||
* `setQueries`.
|
||||
*/
|
||||
getObservers() {
|
||||
return require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this);
|
||||
}
|
||||
/**
|
||||
* The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} — computes
|
||||
* the result for the given (already-defaulted) queries right now, synchronously. Called by
|
||||
* framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw
|
||||
* per-query results, a function to compute the combined result from them, and a function to
|
||||
* wrap the results for property-access tracking.
|
||||
*/
|
||||
getOptimisticResult(queries, combine) {
|
||||
const matches = require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _findMatchingObservers).call(this, queries);
|
||||
const result = matches.map((match) => match.observer.getOptimisticResult(match.defaultedQueryOptions));
|
||||
const queryHashes = matches.map((match) => match.defaultedQueryOptions.queryHash);
|
||||
return [
|
||||
result,
|
||||
(r) => {
|
||||
return require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _combineResult).call(this, r ?? result, combine, queryHashes);
|
||||
},
|
||||
() => {
|
||||
return require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _trackResult).call(this, result, matches);
|
||||
}
|
||||
];
|
||||
}
|
||||
};
|
||||
function _trackResult(result, matches) {
|
||||
const trackedProps = /* @__PURE__ */ new Set();
|
||||
return matches.map((match, index) => {
|
||||
const observerResult = result[index];
|
||||
return !match.defaultedQueryOptions.notifyOnChangeProps ? match.observer.trackResult(observerResult, (accessedProp) => {
|
||||
if (!trackedProps.has(accessedProp)) {
|
||||
trackedProps.add(accessedProp);
|
||||
matches.forEach((m) => {
|
||||
m.observer.trackProp(accessedProp);
|
||||
});
|
||||
}
|
||||
}) : observerResult;
|
||||
});
|
||||
}
|
||||
function _combineResult(input, combine, queryHashes) {
|
||||
if (combine) {
|
||||
const lastHashes = require_classPrivateFieldSet2._classPrivateFieldGet2(_lastQueryHashes, this);
|
||||
const queryHashesChanged = queryHashes !== void 0 && lastHashes !== void 0 && (lastHashes.length !== queryHashes.length || queryHashes.some((hash, i) => hash !== lastHashes[i]));
|
||||
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this) !== require_classPrivateFieldSet2._classPrivateFieldGet2(_lastResult, this) || queryHashesChanged || combine !== require_classPrivateFieldSet2._classPrivateFieldGet2(_lastCombine, this)) {
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_lastCombine, this, combine);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_lastResult, this, require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this));
|
||||
if (queryHashes !== void 0) require_classPrivateFieldSet2._classPrivateFieldSet2(_lastQueryHashes, this, queryHashes);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_combinedResult, this, require_utils.replaceEqualDeep(require_classPrivateFieldSet2._classPrivateFieldGet2(_combinedResult, this), combine(input)));
|
||||
}
|
||||
return require_classPrivateFieldSet2._classPrivateFieldGet2(_combinedResult, this);
|
||||
}
|
||||
return input;
|
||||
}
|
||||
function _shouldSkipCombine() {
|
||||
var _classPrivateFieldGet2$1;
|
||||
return !((_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_options, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.combine) || require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).some((observer, index) => {
|
||||
var _classPrivateFieldGet3;
|
||||
return observer.options.suspense && ((_classPrivateFieldGet3 = require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this)[index]) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.data) === void 0;
|
||||
});
|
||||
}
|
||||
function _findMatchingObservers(queries) {
|
||||
const prevObserversMap = /* @__PURE__ */ new Map();
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).forEach((observer) => {
|
||||
const key = observer.options.queryHash;
|
||||
if (!key) return;
|
||||
const previousObservers = prevObserversMap.get(key);
|
||||
if (previousObservers) previousObservers.push(observer);
|
||||
else prevObserversMap.set(key, [observer]);
|
||||
});
|
||||
const observers = [];
|
||||
queries.forEach((options) => {
|
||||
var _prevObserversMap$get;
|
||||
const defaultedOptions = require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this).defaultQueryOptions(options);
|
||||
const observer = ((_prevObserversMap$get = prevObserversMap.get(defaultedOptions.queryHash)) === null || _prevObserversMap$get === void 0 ? void 0 : _prevObserversMap$get.shift()) ?? new require_queryObserver.QueryObserver(require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this), defaultedOptions);
|
||||
observers.push({
|
||||
defaultedQueryOptions: defaultedOptions,
|
||||
observer
|
||||
});
|
||||
});
|
||||
return observers;
|
||||
}
|
||||
function _onUpdate(observer, result) {
|
||||
const index = require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).indexOf(observer);
|
||||
if (index !== -1) {
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_result, this, require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this).slice());
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this)[index] = result;
|
||||
require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _notify).call(this);
|
||||
}
|
||||
}
|
||||
function _notify() {
|
||||
if (this.hasListeners()) {
|
||||
var _classPrivateFieldGet4;
|
||||
const shouldSkipCombine = require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _shouldSkipCombine).call(this);
|
||||
const previousResult = require_classPrivateFieldSet2._classPrivateFieldGet2(_combinedResult, this);
|
||||
const newResult = shouldSkipCombine ? previousResult : require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _combineResult).call(this, require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _trackResult).call(this, require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this), require_classPrivateFieldSet2._classPrivateFieldGet2(_observerMatches, this)), (_classPrivateFieldGet4 = require_classPrivateFieldSet2._classPrivateFieldGet2(_options, this)) === null || _classPrivateFieldGet4 === void 0 ? void 0 : _classPrivateFieldGet4.combine);
|
||||
if (shouldSkipCombine || previousResult !== newResult) require_notifyManager.notifyManager.batch(() => {
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
//#endregion
|
||||
exports.QueriesObserver = QueriesObserver;
|
||||
|
||||
//# sourceMappingURL=queriesObserver.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"queriesObserver.cjs","names":["Subscribable","shallowEqualObjects","replaceEqualDeep","QueryObserver"],"sources":["../../src/queriesObserver.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { QueryObserver } from './queryObserver'\nimport { Subscribable } from './subscribable'\nimport { replaceEqualDeep, shallowEqualObjects } from './utils'\nimport type {\n DefaultedQueryObserverOptions,\n QueryObserverOptions,\n QueryObserverResult,\n} from './types'\nimport type { QueryClient } from './queryClient'\n\nfunction difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {\n const excludeSet = new Set(array2)\n return array1.filter((x) => !excludeSet.has(x))\n}\n\ntype QueriesObserverListener = (result: Array<QueryObserverResult>) => void\n\ntype CombineFn<TCombinedResult> = (\n result: Array<QueryObserverResult>,\n) => TCombinedResult\n\nexport interface QueriesObserverOptions<\n TCombinedResult = Array<QueryObserverResult>,\n> {\n /**\n * A function that combines the array of `QueryObserverResult`s (one per\n * observed query) into a single value. The combined value is memoized and\n * only recomputed when one of the underlying results, the query hashes, or\n * the `combine` function itself changes.\n *\n * Defaults to returning the array of `QueryObserverResult`s unchanged.\n */\n combine?: CombineFn<TCombinedResult>\n}\n\n/**\n * A `QueriesObserver` watches an array of queries at once, exposing them as\n * a single array of `QueryObserverResult`s (or, when a `combine` option is\n * given, as a combined value derived from that array). It manages one\n * internal `QueryObserver` per query, and is the primitive that framework\n * adapters (e.g. `useQueries`) build their hooks on top of.\n *\n * @example\n * ```ts\n * const observer = new QueriesObserver(queryClient, [\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 2], queryFn: fetchPost },\n * ])\n *\n * const unsubscribe = observer.subscribe((result) => {\n * console.log(result)\n * })\n * ```\n */\nexport class QueriesObserver<\n TCombinedResult = Array<QueryObserverResult>,\n> extends Subscribable<QueriesObserverListener> {\n #client: QueryClient\n #result!: Array<QueryObserverResult>\n #queries: Array<QueryObserverOptions>\n #options?: QueriesObserverOptions<TCombinedResult>\n #observers: Array<QueryObserver>\n #combinedResult!: TCombinedResult\n #lastCombine?: CombineFn<TCombinedResult>\n #lastResult?: Array<QueryObserverResult>\n #lastQueryHashes?: Array<string>\n #observerMatches: Array<QueryObserverMatch> = []\n\n constructor(\n client: QueryClient,\n queries: Array<QueryObserverOptions<any, any, any, any, any>>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ) {\n super()\n\n this.#client = client\n this.#options = options\n this.#queries = []\n this.#observers = []\n this.#result = []\n\n this.setQueries(queries)\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#observers.forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.listeners.size) {\n this.destroy()\n }\n }\n\n /**\n * Stops observing all queries: clears all listeners and destroys every\n * underlying `QueryObserver` this observer manages.\n */\n destroy(): void {\n this.listeners = new Set()\n this.#observers.forEach((observer) => {\n observer.destroy()\n })\n }\n\n /**\n * Replaces the set of queries being observed. Existing `QueryObserver`s\n * are reused for queries that match an already-observed query hash;\n * observers for queries that are no longer present are destroyed, and new\n * observers are created and subscribed to for newly added queries.\n *\n * @example\n * ```ts\n * observer.setQueries([\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 3], queryFn: fetchPost },\n * ])\n * ```\n */\n setQueries(\n queries: Array<QueryObserverOptions>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ): void {\n this.#queries = queries\n this.#options = options\n\n if (process.env.NODE_ENV !== 'production') {\n const queryHashes = queries.map(\n (query) => this.#client.defaultQueryOptions(query).queryHash,\n )\n if (new Set(queryHashes).size !== queryHashes.length) {\n console.warn(\n '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',\n )\n }\n }\n\n notifyManager.batch(() => {\n const prevObservers = this.#observers\n\n const newObserverMatches = this.#findMatchingObservers(this.#queries)\n\n // set options for the new observers to notify of changes\n newObserverMatches.forEach((match) =>\n match.observer.setOptioLine truncated
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import { t as Subscribable } from "./subscribable-CbifVTKz.cjs";
|
||||
import { $n as Query, At as QueryObserverOptions, Pt as QueryObserverResult, on as QueryClient, rr as QueryObserver } from "./hydration-DwR10Hi-.cjs";
|
||||
//#region src/queriesObserver.d.ts
|
||||
type QueriesObserverListener = (result: Array<QueryObserverResult>) => void;
|
||||
type CombineFn<TCombinedResult> = (result: Array<QueryObserverResult>) => TCombinedResult;
|
||||
interface QueriesObserverOptions<TCombinedResult = Array<QueryObserverResult>> {
|
||||
/**
|
||||
* A function that combines the array of `QueryObserverResult`s (one per
|
||||
* observed query) into a single value. The combined value is memoized and
|
||||
* only recomputed when one of the underlying results, the query hashes, or
|
||||
* the `combine` function itself changes.
|
||||
*
|
||||
* Defaults to returning the array of `QueryObserverResult`s unchanged.
|
||||
*/
|
||||
combine?: CombineFn<TCombinedResult>;
|
||||
}
|
||||
/**
|
||||
* A `QueriesObserver` watches an array of queries at once, exposing them as
|
||||
* a single array of `QueryObserverResult`s (or, when a `combine` option is
|
||||
* given, as a combined value derived from that array). It manages one
|
||||
* internal `QueryObserver` per query, and is the primitive that framework
|
||||
* adapters (e.g. `useQueries`) build their hooks on top of.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const observer = new QueriesObserver(queryClient, [
|
||||
* { queryKey: ['post', 1], queryFn: fetchPost },
|
||||
* { queryKey: ['post', 2], queryFn: fetchPost },
|
||||
* ])
|
||||
*
|
||||
* const unsubscribe = observer.subscribe((result) => {
|
||||
* console.log(result)
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
declare class QueriesObserver<TCombinedResult = Array<QueryObserverResult>> extends Subscribable<QueriesObserverListener> {
|
||||
#private;
|
||||
constructor(client: QueryClient, queries: Array<QueryObserverOptions<any, any, any, any, any>>, options?: QueriesObserverOptions<TCombinedResult>);
|
||||
protected onSubscribe(): void;
|
||||
protected onUnsubscribe(): void;
|
||||
/**
|
||||
* Stops observing all queries: clears all listeners and destroys every
|
||||
* underlying `QueryObserver` this observer manages.
|
||||
*/
|
||||
destroy(): void;
|
||||
/**
|
||||
* Replaces the set of queries being observed. Existing `QueryObserver`s
|
||||
* are reused for queries that match an already-observed query hash;
|
||||
* observers for queries that are no longer present are destroyed, and new
|
||||
* observers are created and subscribed to for newly added queries.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* observer.setQueries([
|
||||
* { queryKey: ['post', 1], queryFn: fetchPost },
|
||||
* { queryKey: ['post', 3], queryFn: fetchPost },
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
setQueries(queries: Array<QueryObserverOptions>, options?: QueriesObserverOptions<TCombinedResult>): void;
|
||||
/**
|
||||
* Returns the most recently computed array of `QueryObserverResult`s, one
|
||||
* per observed query, in the same order as the queries passed to the
|
||||
* constructor or `setQueries`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const results = observer.getCurrentResult()
|
||||
* const data = results.map((result) => result.data)
|
||||
* ```
|
||||
*/
|
||||
getCurrentResult(): Array<QueryObserverResult>;
|
||||
/**
|
||||
* Returns the underlying `Query` instances currently being observed, in
|
||||
* the same order as the queries passed to the constructor or `setQueries`.
|
||||
*/
|
||||
getQueries(): Query<unknown, Error, unknown, readonly unknown[]>[];
|
||||
/**
|
||||
* Returns the underlying `QueryObserver` instances this observer manages,
|
||||
* in the same order as the queries passed to the constructor or
|
||||
* `setQueries`.
|
||||
*/
|
||||
getObservers(): QueryObserver<unknown, Error, unknown, unknown, readonly unknown[]>[];
|
||||
/**
|
||||
* The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} — computes
|
||||
* the result for the given (already-defaulted) queries right now, synchronously. Called by
|
||||
* framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw
|
||||
* per-query results, a function to compute the combined result from them, and a function to
|
||||
* wrap the results for property-access tracking.
|
||||
*/
|
||||
getOptimisticResult(queries: Array<QueryObserverOptions>, combine: CombineFn<TCombinedResult> | undefined): [rawResult: Array<QueryObserverResult>, combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult, trackResult: () => Array<QueryObserverResult>];
|
||||
}
|
||||
//#endregion
|
||||
export { QueriesObserver, QueriesObserverOptions };
|
||||
//# sourceMappingURL=queriesObserver.d.cts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"queriesObserver.d.cts","names":[],"sources":["../../src/queriesObserver.ts"],"mappings":";;;KAgBK,2BAA2B,QAAQ,MAAM;KAEzC,UAAU,oBACb,QAAQ,MAAM,yBACX;UAEY,uBACf,kBAAkB,MAAM;;;;;;;;;EAUxB,UAAU,UAAU;;;;;;;;;;;;;;;;;;;;;cAsBT,gBACX,kBAAkB,MAAM,8BAChB,aAAa;;EAanB,YAAA,QAAQ,aACR,SAAS,MAAM,gDACf,UAAU,uBAAuB;YAazB;YAUA;;;;;EAUV;;;;;;;;;;;;;;;EAqBA,WACE,SAAS,MAAM,uBACf,UAAU,uBAAuB;;;;;;;;;;;;EAiFnC,oBAAoB,MAAM;;;;;EAQ1B,cAAU,eAAA;;;;;;EASV,gBAAY,uBAAA;;;;;;;;EAWZ,oBACE,SAAS,MAAM,uBACf,SAAS,UAAU,gCAEnB,WAAW,MAAM,sBACjB,gBAAgB,IAAI,MAAM,yBAAyB,iBACnD,mBAAmB,MAAM"}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import { t as Subscribable } from "./subscribable-CbifVTKz.js";
|
||||
import { $n as Query, At as QueryObserverOptions, Pt as QueryObserverResult, on as QueryClient, rr as QueryObserver } from "./hydration-Cq7QYAzB.js";
|
||||
//#region src/queriesObserver.d.ts
|
||||
type QueriesObserverListener = (result: Array<QueryObserverResult>) => void;
|
||||
type CombineFn<TCombinedResult> = (result: Array<QueryObserverResult>) => TCombinedResult;
|
||||
interface QueriesObserverOptions<TCombinedResult = Array<QueryObserverResult>> {
|
||||
/**
|
||||
* A function that combines the array of `QueryObserverResult`s (one per
|
||||
* observed query) into a single value. The combined value is memoized and
|
||||
* only recomputed when one of the underlying results, the query hashes, or
|
||||
* the `combine` function itself changes.
|
||||
*
|
||||
* Defaults to returning the array of `QueryObserverResult`s unchanged.
|
||||
*/
|
||||
combine?: CombineFn<TCombinedResult>;
|
||||
}
|
||||
/**
|
||||
* A `QueriesObserver` watches an array of queries at once, exposing them as
|
||||
* a single array of `QueryObserverResult`s (or, when a `combine` option is
|
||||
* given, as a combined value derived from that array). It manages one
|
||||
* internal `QueryObserver` per query, and is the primitive that framework
|
||||
* adapters (e.g. `useQueries`) build their hooks on top of.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const observer = new QueriesObserver(queryClient, [
|
||||
* { queryKey: ['post', 1], queryFn: fetchPost },
|
||||
* { queryKey: ['post', 2], queryFn: fetchPost },
|
||||
* ])
|
||||
*
|
||||
* const unsubscribe = observer.subscribe((result) => {
|
||||
* console.log(result)
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
declare class QueriesObserver<TCombinedResult = Array<QueryObserverResult>> extends Subscribable<QueriesObserverListener> {
|
||||
#private;
|
||||
constructor(client: QueryClient, queries: Array<QueryObserverOptions<any, any, any, any, any>>, options?: QueriesObserverOptions<TCombinedResult>);
|
||||
protected onSubscribe(): void;
|
||||
protected onUnsubscribe(): void;
|
||||
/**
|
||||
* Stops observing all queries: clears all listeners and destroys every
|
||||
* underlying `QueryObserver` this observer manages.
|
||||
*/
|
||||
destroy(): void;
|
||||
/**
|
||||
* Replaces the set of queries being observed. Existing `QueryObserver`s
|
||||
* are reused for queries that match an already-observed query hash;
|
||||
* observers for queries that are no longer present are destroyed, and new
|
||||
* observers are created and subscribed to for newly added queries.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* observer.setQueries([
|
||||
* { queryKey: ['post', 1], queryFn: fetchPost },
|
||||
* { queryKey: ['post', 3], queryFn: fetchPost },
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
setQueries(queries: Array<QueryObserverOptions>, options?: QueriesObserverOptions<TCombinedResult>): void;
|
||||
/**
|
||||
* Returns the most recently computed array of `QueryObserverResult`s, one
|
||||
* per observed query, in the same order as the queries passed to the
|
||||
* constructor or `setQueries`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const results = observer.getCurrentResult()
|
||||
* const data = results.map((result) => result.data)
|
||||
* ```
|
||||
*/
|
||||
getCurrentResult(): Array<QueryObserverResult>;
|
||||
/**
|
||||
* Returns the underlying `Query` instances currently being observed, in
|
||||
* the same order as the queries passed to the constructor or `setQueries`.
|
||||
*/
|
||||
getQueries(): Query<unknown, Error, unknown, readonly unknown[]>[];
|
||||
/**
|
||||
* Returns the underlying `QueryObserver` instances this observer manages,
|
||||
* in the same order as the queries passed to the constructor or
|
||||
* `setQueries`.
|
||||
*/
|
||||
getObservers(): QueryObserver<unknown, Error, unknown, unknown, readonly unknown[]>[];
|
||||
/**
|
||||
* The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} — computes
|
||||
* the result for the given (already-defaulted) queries right now, synchronously. Called by
|
||||
* framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw
|
||||
* per-query results, a function to compute the combined result from them, and a function to
|
||||
* wrap the results for property-access tracking.
|
||||
*/
|
||||
getOptimisticResult(queries: Array<QueryObserverOptions>, combine: CombineFn<TCombinedResult> | undefined): [rawResult: Array<QueryObserverResult>, combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult, trackResult: () => Array<QueryObserverResult>];
|
||||
}
|
||||
//#endregion
|
||||
export { QueriesObserver, QueriesObserverOptions };
|
||||
//# sourceMappingURL=queriesObserver.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"queriesObserver.d.ts","names":[],"sources":["../../src/queriesObserver.ts"],"mappings":";;;KAgBK,2BAA2B,QAAQ,MAAM;KAEzC,UAAU,oBACb,QAAQ,MAAM,yBACX;UAEY,uBACf,kBAAkB,MAAM;;;;;;;;;EAUxB,UAAU,UAAU;;;;;;;;;;;;;;;;;;;;;cAsBT,gBACX,kBAAkB,MAAM,8BAChB,aAAa;;EAanB,YAAA,QAAQ,aACR,SAAS,MAAM,gDACf,UAAU,uBAAuB;YAazB;YAUA;;;;;EAUV;;;;;;;;;;;;;;;EAqBA,WACE,SAAS,MAAM,uBACf,UAAU,uBAAuB;;;;;;;;;;;;EAiFnC,oBAAoB,MAAM;;;;;EAQ1B,cAAU,eAAA;;;;;;EASV,gBAAY,uBAAA;;;;;;;;EAWZ,oBACE,SAAS,MAAM,uBACf,SAAS,UAAU,gCAEnB,WAAW,MAAM,sBACjB,gBAAgB,IAAI,MAAM,yBAAyB,iBACnD,mBAAmB,MAAM"}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
|
||||
import { replaceEqualDeep, shallowEqualObjects } from "./utils.js";
|
||||
import { Subscribable } from "./subscribable.js";
|
||||
import { notifyManager } from "./notifyManager.js";
|
||||
import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-CBwa_Y7C.js";
|
||||
import { QueryObserver } from "./queryObserver.js";
|
||||
//#region src/queriesObserver.ts
|
||||
function difference(array1, array2) {
|
||||
const excludeSet = new Set(array2);
|
||||
return array1.filter((x) => !excludeSet.has(x));
|
||||
}
|
||||
var _client = /* @__PURE__ */ new WeakMap();
|
||||
var _result = /* @__PURE__ */ new WeakMap();
|
||||
var _queries = /* @__PURE__ */ new WeakMap();
|
||||
var _options = /* @__PURE__ */ new WeakMap();
|
||||
var _observers = /* @__PURE__ */ new WeakMap();
|
||||
var _combinedResult = /* @__PURE__ */ new WeakMap();
|
||||
var _lastCombine = /* @__PURE__ */ new WeakMap();
|
||||
var _lastResult = /* @__PURE__ */ new WeakMap();
|
||||
var _lastQueryHashes = /* @__PURE__ */ new WeakMap();
|
||||
var _observerMatches = /* @__PURE__ */ new WeakMap();
|
||||
var _QueriesObserver_brand = /* @__PURE__ */ new WeakSet();
|
||||
/**
|
||||
* A `QueriesObserver` watches an array of queries at once, exposing them as
|
||||
* a single array of `QueryObserverResult`s (or, when a `combine` option is
|
||||
* given, as a combined value derived from that array). It manages one
|
||||
* internal `QueryObserver` per query, and is the primitive that framework
|
||||
* adapters (e.g. `useQueries`) build their hooks on top of.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const observer = new QueriesObserver(queryClient, [
|
||||
* { queryKey: ['post', 1], queryFn: fetchPost },
|
||||
* { queryKey: ['post', 2], queryFn: fetchPost },
|
||||
* ])
|
||||
*
|
||||
* const unsubscribe = observer.subscribe((result) => {
|
||||
* console.log(result)
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
var QueriesObserver = class extends Subscribable {
|
||||
constructor(client, queries, options) {
|
||||
super();
|
||||
_classPrivateMethodInitSpec(this, _QueriesObserver_brand);
|
||||
_classPrivateFieldInitSpec(this, _client, void 0);
|
||||
_classPrivateFieldInitSpec(this, _result, void 0);
|
||||
_classPrivateFieldInitSpec(this, _queries, void 0);
|
||||
_classPrivateFieldInitSpec(this, _options, void 0);
|
||||
_classPrivateFieldInitSpec(this, _observers, void 0);
|
||||
_classPrivateFieldInitSpec(this, _combinedResult, void 0);
|
||||
_classPrivateFieldInitSpec(this, _lastCombine, void 0);
|
||||
_classPrivateFieldInitSpec(this, _lastResult, void 0);
|
||||
_classPrivateFieldInitSpec(this, _lastQueryHashes, void 0);
|
||||
_classPrivateFieldInitSpec(this, _observerMatches, []);
|
||||
_classPrivateFieldSet2(_client, this, client);
|
||||
_classPrivateFieldSet2(_options, this, options);
|
||||
_classPrivateFieldSet2(_queries, this, []);
|
||||
_classPrivateFieldSet2(_observers, this, []);
|
||||
_classPrivateFieldSet2(_result, this, []);
|
||||
this.setQueries(queries);
|
||||
}
|
||||
onSubscribe() {
|
||||
if (this.listeners.size === 1) _classPrivateFieldGet2(_observers, this).forEach((observer) => {
|
||||
observer.subscribe((result) => {
|
||||
_assertClassBrand(_QueriesObserver_brand, this, _onUpdate).call(this, observer, result);
|
||||
});
|
||||
});
|
||||
}
|
||||
onUnsubscribe() {
|
||||
if (!this.listeners.size) this.destroy();
|
||||
}
|
||||
/**
|
||||
* Stops observing all queries: clears all listeners and destroys every
|
||||
* underlying `QueryObserver` this observer manages.
|
||||
*/
|
||||
destroy() {
|
||||
this.listeners = /* @__PURE__ */ new Set();
|
||||
_classPrivateFieldGet2(_observers, this).forEach((observer) => {
|
||||
observer.destroy();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Replaces the set of queries being observed. Existing `QueryObserver`s
|
||||
* are reused for queries that match an already-observed query hash;
|
||||
* observers for queries that are no longer present are destroyed, and new
|
||||
* observers are created and subscribed to for newly added queries.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* observer.setQueries([
|
||||
* { queryKey: ['post', 1], queryFn: fetchPost },
|
||||
* { queryKey: ['post', 3], queryFn: fetchPost },
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
setQueries(queries, options) {
|
||||
_classPrivateFieldSet2(_queries, this, queries);
|
||||
_classPrivateFieldSet2(_options, this, options);
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
const queryHashes = queries.map((query) => _classPrivateFieldGet2(_client, this).defaultQueryOptions(query).queryHash);
|
||||
if (new Set(queryHashes).size !== queryHashes.length) console.warn("[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.");
|
||||
}
|
||||
notifyManager.batch(() => {
|
||||
const prevObservers = _classPrivateFieldGet2(_observers, this);
|
||||
const newObserverMatches = _assertClassBrand(_QueriesObserver_brand, this, _findMatchingObservers).call(this, _classPrivateFieldGet2(_queries, this));
|
||||
newObserverMatches.forEach((match) => match.observer.setOptions(match.defaultedQueryOptions));
|
||||
const newObservers = newObserverMatches.map((match) => match.observer);
|
||||
const newResult = newObservers.map((observer) => observer.getCurrentResult());
|
||||
const hasLengthChange = prevObservers.length !== newObservers.length;
|
||||
const hasIndexChange = newObservers.some((observer, index) => observer !== prevObservers[index]);
|
||||
const hasStructuralChange = hasLengthChange || hasIndexChange;
|
||||
const hasResultChange = hasStructuralChange ? true : newResult.some((result, index) => {
|
||||
const prev = _classPrivateFieldGet2(_result, this)[index];
|
||||
return !prev || !shallowEqualObjects(result, prev);
|
||||
});
|
||||
if (!hasStructuralChange && !hasResultChange) return;
|
||||
if (hasStructuralChange) {
|
||||
_classPrivateFieldSet2(_observerMatches, this, newObserverMatches);
|
||||
_classPrivateFieldSet2(_observers, this, newObservers);
|
||||
}
|
||||
_classPrivateFieldSet2(_result, this, newResult);
|
||||
if (!this.hasListeners()) return;
|
||||
if (hasStructuralChange) {
|
||||
difference(prevObservers, newObservers).forEach((observer) => {
|
||||
observer.destroy();
|
||||
});
|
||||
difference(newObservers, prevObservers).forEach((observer) => {
|
||||
observer.subscribe((result) => {
|
||||
_assertClassBrand(_QueriesObserver_brand, this, _onUpdate).call(this, observer, result);
|
||||
});
|
||||
});
|
||||
}
|
||||
_assertClassBrand(_QueriesObserver_brand, this, _notify).call(this);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Returns the most recently computed array of `QueryObserverResult`s, one
|
||||
* per observed query, in the same order as the queries passed to the
|
||||
* constructor or `setQueries`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const results = observer.getCurrentResult()
|
||||
* const data = results.map((result) => result.data)
|
||||
* ```
|
||||
*/
|
||||
getCurrentResult() {
|
||||
return _classPrivateFieldGet2(_result, this);
|
||||
}
|
||||
/**
|
||||
* Returns the underlying `Query` instances currently being observed, in
|
||||
* the same order as the queries passed to the constructor or `setQueries`.
|
||||
*/
|
||||
getQueries() {
|
||||
return _classPrivateFieldGet2(_observers, this).map((observer) => observer.getCurrentQuery());
|
||||
}
|
||||
/**
|
||||
* Returns the underlying `QueryObserver` instances this observer manages,
|
||||
* in the same order as the queries passed to the constructor or
|
||||
* `setQueries`.
|
||||
*/
|
||||
getObservers() {
|
||||
return _classPrivateFieldGet2(_observers, this);
|
||||
}
|
||||
/**
|
||||
* The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} — computes
|
||||
* the result for the given (already-defaulted) queries right now, synchronously. Called by
|
||||
* framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw
|
||||
* per-query results, a function to compute the combined result from them, and a function to
|
||||
* wrap the results for property-access tracking.
|
||||
*/
|
||||
getOptimisticResult(queries, combine) {
|
||||
const matches = _assertClassBrand(_QueriesObserver_brand, this, _findMatchingObservers).call(this, queries);
|
||||
const result = matches.map((match) => match.observer.getOptimisticResult(match.defaultedQueryOptions));
|
||||
const queryHashes = matches.map((match) => match.defaultedQueryOptions.queryHash);
|
||||
return [
|
||||
result,
|
||||
(r) => {
|
||||
return _assertClassBrand(_QueriesObserver_brand, this, _combineResult).call(this, r ?? result, combine, queryHashes);
|
||||
},
|
||||
() => {
|
||||
return _assertClassBrand(_QueriesObserver_brand, this, _trackResult).call(this, result, matches);
|
||||
}
|
||||
];
|
||||
}
|
||||
};
|
||||
function _trackResult(result, matches) {
|
||||
const trackedProps = /* @__PURE__ */ new Set();
|
||||
return matches.map((match, index) => {
|
||||
const observerResult = result[index];
|
||||
return !match.defaultedQueryOptions.notifyOnChangeProps ? match.observer.trackResult(observerResult, (accessedProp) => {
|
||||
if (!trackedProps.has(accessedProp)) {
|
||||
trackedProps.add(accessedProp);
|
||||
matches.forEach((m) => {
|
||||
m.observer.trackProp(accessedProp);
|
||||
});
|
||||
}
|
||||
}) : observerResult;
|
||||
});
|
||||
}
|
||||
function _combineResult(input, combine, queryHashes) {
|
||||
if (combine) {
|
||||
const lastHashes = _classPrivateFieldGet2(_lastQueryHashes, this);
|
||||
const queryHashesChanged = queryHashes !== void 0 && lastHashes !== void 0 && (lastHashes.length !== queryHashes.length || queryHashes.some((hash, i) => hash !== lastHashes[i]));
|
||||
if (_classPrivateFieldGet2(_result, this) !== _classPrivateFieldGet2(_lastResult, this) || queryHashesChanged || combine !== _classPrivateFieldGet2(_lastCombine, this)) {
|
||||
_classPrivateFieldSet2(_lastCombine, this, combine);
|
||||
_classPrivateFieldSet2(_lastResult, this, _classPrivateFieldGet2(_result, this));
|
||||
if (queryHashes !== void 0) _classPrivateFieldSet2(_lastQueryHashes, this, queryHashes);
|
||||
_classPrivateFieldSet2(_combinedResult, this, replaceEqualDeep(_classPrivateFieldGet2(_combinedResult, this), combine(input)));
|
||||
}
|
||||
return _classPrivateFieldGet2(_combinedResult, this);
|
||||
}
|
||||
return input;
|
||||
}
|
||||
function _shouldSkipCombine() {
|
||||
var _classPrivateFieldGet2$1;
|
||||
return !((_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_options, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.combine) || _classPrivateFieldGet2(_observers, this).some((observer, index) => {
|
||||
var _classPrivateFieldGet3;
|
||||
return observer.options.suspense && ((_classPrivateFieldGet3 = _classPrivateFieldGet2(_result, this)[index]) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.data) === void 0;
|
||||
});
|
||||
}
|
||||
function _findMatchingObservers(queries) {
|
||||
const prevObserversMap = /* @__PURE__ */ new Map();
|
||||
_classPrivateFieldGet2(_observers, this).forEach((observer) => {
|
||||
const key = observer.options.queryHash;
|
||||
if (!key) return;
|
||||
const previousObservers = prevObserversMap.get(key);
|
||||
if (previousObservers) previousObservers.push(observer);
|
||||
else prevObserversMap.set(key, [observer]);
|
||||
});
|
||||
const observers = [];
|
||||
queries.forEach((options) => {
|
||||
var _prevObserversMap$get;
|
||||
const defaultedOptions = _classPrivateFieldGet2(_client, this).defaultQueryOptions(options);
|
||||
const observer = ((_prevObserversMap$get = prevObserversMap.get(defaultedOptions.queryHash)) === null || _prevObserversMap$get === void 0 ? void 0 : _prevObserversMap$get.shift()) ?? new QueryObserver(_classPrivateFieldGet2(_client, this), defaultedOptions);
|
||||
observers.push({
|
||||
defaultedQueryOptions: defaultedOptions,
|
||||
observer
|
||||
});
|
||||
});
|
||||
return observers;
|
||||
}
|
||||
function _onUpdate(observer, result) {
|
||||
const index = _classPrivateFieldGet2(_observers, this).indexOf(observer);
|
||||
if (index !== -1) {
|
||||
_classPrivateFieldSet2(_result, this, _classPrivateFieldGet2(_result, this).slice());
|
||||
_classPrivateFieldGet2(_result, this)[index] = result;
|
||||
_assertClassBrand(_QueriesObserver_brand, this, _notify).call(this);
|
||||
}
|
||||
}
|
||||
function _notify() {
|
||||
if (this.hasListeners()) {
|
||||
var _classPrivateFieldGet4;
|
||||
const shouldSkipCombine = _assertClassBrand(_QueriesObserver_brand, this, _shouldSkipCombine).call(this);
|
||||
const previousResult = _classPrivateFieldGet2(_combinedResult, this);
|
||||
const newResult = shouldSkipCombine ? previousResult : _assertClassBrand(_QueriesObserver_brand, this, _combineResult).call(this, _assertClassBrand(_QueriesObserver_brand, this, _trackResult).call(this, _classPrivateFieldGet2(_result, this), _classPrivateFieldGet2(_observerMatches, this)), (_classPrivateFieldGet4 = _classPrivateFieldGet2(_options, this)) === null || _classPrivateFieldGet4 === void 0 ? void 0 : _classPrivateFieldGet4.combine);
|
||||
if (shouldSkipCombine || previousResult !== newResult) notifyManager.batch(() => {
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(_classPrivateFieldGet2(_result, this));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
//#endregion
|
||||
export { QueriesObserver };
|
||||
|
||||
//# sourceMappingURL=queriesObserver.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"queriesObserver.js","names":[],"sources":["../../src/queriesObserver.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { QueryObserver } from './queryObserver'\nimport { Subscribable } from './subscribable'\nimport { replaceEqualDeep, shallowEqualObjects } from './utils'\nimport type {\n DefaultedQueryObserverOptions,\n QueryObserverOptions,\n QueryObserverResult,\n} from './types'\nimport type { QueryClient } from './queryClient'\n\nfunction difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {\n const excludeSet = new Set(array2)\n return array1.filter((x) => !excludeSet.has(x))\n}\n\ntype QueriesObserverListener = (result: Array<QueryObserverResult>) => void\n\ntype CombineFn<TCombinedResult> = (\n result: Array<QueryObserverResult>,\n) => TCombinedResult\n\nexport interface QueriesObserverOptions<\n TCombinedResult = Array<QueryObserverResult>,\n> {\n /**\n * A function that combines the array of `QueryObserverResult`s (one per\n * observed query) into a single value. The combined value is memoized and\n * only recomputed when one of the underlying results, the query hashes, or\n * the `combine` function itself changes.\n *\n * Defaults to returning the array of `QueryObserverResult`s unchanged.\n */\n combine?: CombineFn<TCombinedResult>\n}\n\n/**\n * A `QueriesObserver` watches an array of queries at once, exposing them as\n * a single array of `QueryObserverResult`s (or, when a `combine` option is\n * given, as a combined value derived from that array). It manages one\n * internal `QueryObserver` per query, and is the primitive that framework\n * adapters (e.g. `useQueries`) build their hooks on top of.\n *\n * @example\n * ```ts\n * const observer = new QueriesObserver(queryClient, [\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 2], queryFn: fetchPost },\n * ])\n *\n * const unsubscribe = observer.subscribe((result) => {\n * console.log(result)\n * })\n * ```\n */\nexport class QueriesObserver<\n TCombinedResult = Array<QueryObserverResult>,\n> extends Subscribable<QueriesObserverListener> {\n #client: QueryClient\n #result!: Array<QueryObserverResult>\n #queries: Array<QueryObserverOptions>\n #options?: QueriesObserverOptions<TCombinedResult>\n #observers: Array<QueryObserver>\n #combinedResult!: TCombinedResult\n #lastCombine?: CombineFn<TCombinedResult>\n #lastResult?: Array<QueryObserverResult>\n #lastQueryHashes?: Array<string>\n #observerMatches: Array<QueryObserverMatch> = []\n\n constructor(\n client: QueryClient,\n queries: Array<QueryObserverOptions<any, any, any, any, any>>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ) {\n super()\n\n this.#client = client\n this.#options = options\n this.#queries = []\n this.#observers = []\n this.#result = []\n\n this.setQueries(queries)\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#observers.forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.listeners.size) {\n this.destroy()\n }\n }\n\n /**\n * Stops observing all queries: clears all listeners and destroys every\n * underlying `QueryObserver` this observer manages.\n */\n destroy(): void {\n this.listeners = new Set()\n this.#observers.forEach((observer) => {\n observer.destroy()\n })\n }\n\n /**\n * Replaces the set of queries being observed. Existing `QueryObserver`s\n * are reused for queries that match an already-observed query hash;\n * observers for queries that are no longer present are destroyed, and new\n * observers are created and subscribed to for newly added queries.\n *\n * @example\n * ```ts\n * observer.setQueries([\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 3], queryFn: fetchPost },\n * ])\n * ```\n */\n setQueries(\n queries: Array<QueryObserverOptions>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ): void {\n this.#queries = queries\n this.#options = options\n\n if (process.env.NODE_ENV !== 'production') {\n const queryHashes = queries.map(\n (query) => this.#client.defaultQueryOptions(query).queryHash,\n )\n if (new Set(queryHashes).size !== queryHashes.length) {\n console.warn(\n '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',\n )\n }\n }\n\n notifyManager.batch(() => {\n const prevObservers = this.#observers\n\n const newObserverMatches = this.#findMatchingObservers(this.#queries)\n\n // set options for the new observers to notify of changes\n newObserverMatches.forEach((match) =>\n match.observer.setOptions(match.defaultedQueryOptions),\n )\n\n const newObservers = Line truncated
|
||||
+555
@@ -0,0 +1,555 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
|
||||
const require_utils = require("./utils.cjs");
|
||||
const require_notifyManager = require("./notifyManager.cjs");
|
||||
const require_retryer = require("./retryer.cjs");
|
||||
const require_removable = require("./removable.cjs");
|
||||
const require_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs");
|
||||
const require_classPrivateMethodInitSpec = require("./classPrivateMethodInitSpec-DVhcLejn.cjs");
|
||||
//#region src/query.ts
|
||||
var _queryType = /* @__PURE__ */ new WeakMap();
|
||||
var _initialState = /* @__PURE__ */ new WeakMap();
|
||||
var _revertState = /* @__PURE__ */ new WeakMap();
|
||||
var _cache = /* @__PURE__ */ new WeakMap();
|
||||
var _client = /* @__PURE__ */ new WeakMap();
|
||||
var _retryer = /* @__PURE__ */ new WeakMap();
|
||||
var _defaultOptions = /* @__PURE__ */ new WeakMap();
|
||||
var _abortSignalConsumed = /* @__PURE__ */ new WeakMap();
|
||||
var _Query_brand = /* @__PURE__ */ new WeakSet();
|
||||
/**
|
||||
* Represents a single cached query. A `Query` holds the query's key, options,
|
||||
* state (data/error/status), and the observers currently subscribed to it.
|
||||
*
|
||||
* Instances are created and managed internally by `QueryCache`; application
|
||||
* code typically interacts with queries indirectly through `QueryClient` or
|
||||
* a framework hook like `useQuery`. Direct access to a `Query` instance is
|
||||
* possible via `queryCache.find()`/`findAll()` for inspecting cache state.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const queryCache = queryClient.getQueryCache()
|
||||
* const query = queryCache.find({ queryKey: ['posts'] })
|
||||
*
|
||||
* if (query) {
|
||||
* console.log(query.state.dataUpdatedAt)
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
var Query = class extends require_removable.Removable {
|
||||
constructor(config) {
|
||||
super();
|
||||
require_classPrivateMethodInitSpec._classPrivateMethodInitSpec(this, _Query_brand);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _queryType, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _initialState, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _revertState, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _cache, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _client, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _retryer, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _defaultOptions, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _abortSignalConsumed, void 0);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_abortSignalConsumed, this, false);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_defaultOptions, this, config.defaultOptions);
|
||||
this.setOptions(config.options);
|
||||
this.observers = [];
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_client, this, config.client);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_cache, this, require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this).getQueryCache());
|
||||
this.queryKey = config.queryKey;
|
||||
this.queryHash = config.queryHash;
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_initialState, this, getDefaultState(this.options));
|
||||
this.state = config.state ?? require_classPrivateFieldSet2._classPrivateFieldGet2(_initialState, this);
|
||||
this.scheduleGc();
|
||||
}
|
||||
/**
|
||||
* The `meta` object passed in the query's options, if any.
|
||||
*/
|
||||
get meta() {
|
||||
return this.options.meta;
|
||||
}
|
||||
/** @internal */
|
||||
get queryType() {
|
||||
return require_classPrivateFieldSet2._classPrivateFieldGet2(_queryType, this);
|
||||
}
|
||||
/**
|
||||
* The promise for the currently in-flight fetch, if the query is fetching.
|
||||
* `undefined` when the query is not fetching.
|
||||
*/
|
||||
get promise() {
|
||||
var _classPrivateFieldGet2$1;
|
||||
return (_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.promise;
|
||||
}
|
||||
/** @internal */
|
||||
setOptions(options) {
|
||||
this.options = {
|
||||
...require_classPrivateFieldSet2._classPrivateFieldGet2(_defaultOptions, this),
|
||||
...options
|
||||
};
|
||||
if (options === null || options === void 0 ? void 0 : options._type) require_classPrivateFieldSet2._classPrivateFieldSet2(_queryType, this, options._type);
|
||||
this.updateGcTime(this.options.gcTime);
|
||||
if (this.state && this.state.data === void 0) {
|
||||
const defaultState = getDefaultState(this.options);
|
||||
if (defaultState.data !== void 0) {
|
||||
this.setState(successState(defaultState.data, defaultState.dataUpdatedAt));
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_initialState, this, defaultState);
|
||||
}
|
||||
}
|
||||
}
|
||||
optionalRemove() {
|
||||
if (!this.observers.length && this.state.fetchStatus === "idle") require_classPrivateFieldSet2._classPrivateFieldGet2(_cache, this).remove(this);
|
||||
}
|
||||
/** @internal */
|
||||
setData(newData, options) {
|
||||
const data = require_utils.replaceData(this.state.data, newData, this.options);
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
||||
data,
|
||||
type: "success",
|
||||
dataUpdatedAt: options === null || options === void 0 ? void 0 : options.updatedAt,
|
||||
manual: options === null || options === void 0 ? void 0 : options.manual
|
||||
});
|
||||
return data;
|
||||
}
|
||||
/**
|
||||
* Merges the given partial state directly into this query's state, notifying observers. Used
|
||||
* by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a
|
||||
* user manually trigger a loading/error state or edit the cached data.
|
||||
*/
|
||||
setState(state) {
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
||||
type: "setState",
|
||||
state
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Cancels the query's currently in-flight fetch, if any.
|
||||
* - Returns a promise that resolves once the cancellation has settled.
|
||||
* - If no fetch is in progress, resolves immediately.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await query.cancel()
|
||||
* ```
|
||||
*/
|
||||
cancel(options) {
|
||||
var _classPrivateFieldGet3, _classPrivateFieldGet4;
|
||||
const promise = (_classPrivateFieldGet3 = require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.promise;
|
||||
(_classPrivateFieldGet4 = require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet4 === void 0 || _classPrivateFieldGet4.cancel(options);
|
||||
return promise ? promise.then(require_utils.noop).catch(require_utils.noop) : Promise.resolve();
|
||||
}
|
||||
/**
|
||||
* Clears the query's garbage collection timeout and silently cancels any
|
||||
* in-flight fetch. Called by `QueryCache` when the query is removed from
|
||||
* the cache.
|
||||
*
|
||||
* @see {@link Query#cancel}
|
||||
*/
|
||||
destroy() {
|
||||
super.destroy();
|
||||
this.cancel({ silent: true });
|
||||
}
|
||||
/** @internal */
|
||||
get resetState() {
|
||||
return require_classPrivateFieldSet2._classPrivateFieldGet2(_initialState, this);
|
||||
}
|
||||
/**
|
||||
* Resets the query back to its initial state (the state it had when it was
|
||||
* first created, e.g. any `initialData`), destroying it first to cancel any
|
||||
* in-flight fetch.
|
||||
*/
|
||||
reset() {
|
||||
this.destroy();
|
||||
this.setState(this.resetState);
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query has at least one observer for which `enabled`
|
||||
* does not resolve to `false`.
|
||||
*/
|
||||
isActive() {
|
||||
return this.observers.some((observer) => require_utils.resolveQueryValue(observer.options.enabled, this) !== false);
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query is disabled, meaning it will not fetch
|
||||
* automatically.
|
||||
* - If the query has observers, it is disabled when none of them are active
|
||||
* (see `isActive`).
|
||||
* - If the query has no observers, it is disabled when its `queryFn` is
|
||||
* `skipToken` or it has never been fetched.
|
||||
*/
|
||||
isDisabled() {
|
||||
if (this.getObserversCount() > 0) return !this.isActive();
|
||||
return this.options.queryFn === require_utils.skipToken || !this.isFetched();
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query has been fetched, i.e. it has resolved with
|
||||
* either data or an error at least once.
|
||||
*/
|
||||
isFetched() {
|
||||
return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query has at least one observer configured with
|
||||
* `staleTime: 'static'`, meaning it is treated as never stale.
|
||||
*/
|
||||
isStatic() {
|
||||
if (this.getObserversCount() > 0) return this.observers.some((observer) => require_utils.resolveQueryValue(observer.options.staleTime, this) === "static");
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query is stale.
|
||||
* - If the query has observers, defers to whether any observer's current
|
||||
* result reports `isStale` (which accounts for each observer's own
|
||||
* `staleTime` and `enabled` state).
|
||||
* - If the query has no observers, it is considered stale when it has no
|
||||
* data or has been invalidated.
|
||||
*
|
||||
* @see {@link Query#isStaleByTime}
|
||||
* @example
|
||||
* ```ts
|
||||
* if (query.isStale()) {
|
||||
* // refetch or otherwise treat the cached data as outdated
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
isStale() {
|
||||
if (this.getObserversCount() > 0) return this.observers.some((observer) => observer.getCurrentResult().isStale);
|
||||
return this.state.data === void 0 || this.state.isInvalidated;
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query's data is stale relative to the given
|
||||
* `staleTime` (defaults to `0`).
|
||||
* - A query with no data is always stale.
|
||||
* - `staleTime: 'static'` is never stale.
|
||||
* - An invalidated query is always stale.
|
||||
* - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.
|
||||
*
|
||||
* @see {@link Query#isStale}
|
||||
* @example
|
||||
* ```ts
|
||||
* const isStale = query.isStaleByTime(1000 * 60)
|
||||
* ```
|
||||
*/
|
||||
isStaleByTime(staleTime = 0) {
|
||||
if (this.state.data === void 0) return true;
|
||||
if (staleTime === "static") return false;
|
||||
if (this.state.isInvalidated) return true;
|
||||
return !require_utils.timeUntilStale(this.state.dataUpdatedAt, staleTime);
|
||||
}
|
||||
/** @internal */
|
||||
onFocus() {
|
||||
var _classPrivateFieldGet5;
|
||||
const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());
|
||||
observer === null || observer === void 0 || observer.refetch({ cancelRefetch: false });
|
||||
(_classPrivateFieldGet5 = require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet5 === void 0 || _classPrivateFieldGet5.continue();
|
||||
}
|
||||
/** @internal */
|
||||
onOnline() {
|
||||
var _classPrivateFieldGet6;
|
||||
const observer = this.observers.find((x) => x.shouldFetchOnReconnect());
|
||||
observer === null || observer === void 0 || observer.refetch({ cancelRefetch: false });
|
||||
(_classPrivateFieldGet6 = require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet6 === void 0 || _classPrivateFieldGet6.continue();
|
||||
}
|
||||
/** @internal */
|
||||
addObserver(observer) {
|
||||
if (!this.observers.includes(observer)) {
|
||||
this.observers.push(observer);
|
||||
this.clearGcTimeout();
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_cache, this).notify({
|
||||
type: "observerAdded",
|
||||
query: this,
|
||||
observer
|
||||
});
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
removeObserver(observer) {
|
||||
const index = this.observers.indexOf(observer);
|
||||
if (index !== -1) {
|
||||
this.observers.splice(index, 1);
|
||||
if (!this.observers.length) {
|
||||
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this)) {
|
||||
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_abortSignalConsumed, this) || this.state.fetchStatus === "paused" && this.state.status === "pending") require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this).cancel({ revert: true });
|
||||
else require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this).cancelRetry();
|
||||
}
|
||||
this.scheduleGc();
|
||||
}
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_cache, this).notify({
|
||||
type: "observerRemoved",
|
||||
query: this,
|
||||
observer
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns the number of observers currently subscribed to this query.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* if (query.getObserversCount() === 0) {
|
||||
* // no component is currently watching this query
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
getObserversCount() {
|
||||
return this.observers.length;
|
||||
}
|
||||
/**
|
||||
* Marks the query as invalidated, unless it is already invalidated. This
|
||||
* updates `state.isInvalidated` and notifies observers, but does not by
|
||||
* itself trigger a refetch.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* query.invalidate()
|
||||
* ```
|
||||
*/
|
||||
invalidate() {
|
||||
if (!this.state.isInvalidated) require_classPrivateFieldSet2._assertClassBrand(_Query_brand, this, _dispatch).call(this, { type: "invalidate" });
|
||||
}
|
||||
/**
|
||||
* Fetches the query, i.e. runs its `queryFn` (through any configured
|
||||
* retryer/behavior) and updates the query's state with the result.
|
||||
* - If a fetch is already in flight, returns its promise instead of
|
||||
* starting a new one, unless `fetchOptions.cancelRefetch` is set and the
|
||||
* query already has data, in which case the current fetch is silently
|
||||
* cancelled first.
|
||||
* - If `options` is passed, it replaces the query's current options
|
||||
* before fetching.
|
||||
*/
|
||||
async fetch(options, fetchOptions) {
|
||||
var _classPrivateFieldGet7, _context$fetchOptions;
|
||||
if (this.state.fetchStatus !== "idle" && ((_classPrivateFieldGet7 = require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.status()) !== "rejected") {
|
||||
if (this.state.data !== void 0 && (fetchOptions === null || fetchOptions === void 0 ? void 0 : fetchOptions.cancelRefetch)) this.cancel({ silent: true });
|
||||
else if (require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this)) {
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this).continueRetry();
|
||||
return require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this).promise;
|
||||
}
|
||||
}
|
||||
if (options) this.setOptions(options);
|
||||
if (!this.options.queryFn) {
|
||||
const observer = this.observers.find((x) => x.options.queryFn);
|
||||
if (observer) this.setOptions(observer.options);
|
||||
}
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
if (!Array.isArray(this.options.queryKey)) console.error(`As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`);
|
||||
}
|
||||
const abortController = new AbortController();
|
||||
const addSignalProperty = (object) => {
|
||||
Object.defineProperty(object, "signal", {
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_abortSignalConsumed, this, true);
|
||||
return abortController.signal;
|
||||
}
|
||||
});
|
||||
};
|
||||
const fetchFn = () => {
|
||||
const queryFn = require_utils.ensureQueryFn(this.options, fetchOptions);
|
||||
const createQueryFnContext = () => {
|
||||
const queryFnContext = {
|
||||
client: require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this),
|
||||
queryKey: this.queryKey,
|
||||
meta: this.meta
|
||||
};
|
||||
addSignalProperty(queryFnContext);
|
||||
return queryFnContext;
|
||||
};
|
||||
const queryFnContext = createQueryFnContext();
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_abortSignalConsumed, this, false);
|
||||
if (this.options.persister) return this.options.persister(queryFn, queryFnContext, this);
|
||||
return queryFn(queryFnContext);
|
||||
};
|
||||
const createFetchContext = () => {
|
||||
const context = {
|
||||
fetchOptions,
|
||||
options: this.options,
|
||||
queryKey: this.queryKey,
|
||||
client: require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this),
|
||||
state: this.state,
|
||||
fetchFn
|
||||
};
|
||||
addSignalProperty(context);
|
||||
return context;
|
||||
};
|
||||
const context = createFetchContext();
|
||||
const behavior = require_classPrivateFieldSet2._classPrivateFieldGet2(_queryType, this) === "infinite" ? require_infiniteQueryBehavior.infiniteQueryBehavior(this.options.pages) : this.options.behavior;
|
||||
behavior === null || behavior === void 0 || behavior.onFetch(context, this);
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_revertState, this, this.state);
|
||||
if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) === null || _context$fetchOptions === void 0 ? void 0 : _context$fetchOptions.meta)) {
|
||||
var _context$fetchOptions2;
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
||||
type: "fetch",
|
||||
meta: (_context$fetchOptions2 = context.fetchOptions) === null || _context$fetchOptions2 === void 0 ? void 0 : _context$fetchOptions2.meta
|
||||
});
|
||||
}
|
||||
const retryer = require_classPrivateFieldSet2._classPrivateFieldSet2(_retryer, this, require_retryer.createRetryer({
|
||||
initialPromise: fetchOptions === null || fetchOptions === void 0 ? void 0 : fetchOptions.initialPromise,
|
||||
fn: context.fetchFn,
|
||||
onCancel: (error) => {
|
||||
if (error instanceof require_retryer.CancelledError && error.revert) this.setState({
|
||||
...require_classPrivateFieldSet2._classPrivateFieldGet2(_revertState, this),
|
||||
fetchStatus: "idle"
|
||||
});
|
||||
abortController.abort();
|
||||
},
|
||||
onFail: (failureCount, error) => {
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
||||
type: "failed",
|
||||
failureCount,
|
||||
error
|
||||
});
|
||||
},
|
||||
onPause: () => {
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Query_brand, this, _dispatch).call(this, { type: "pause" });
|
||||
},
|
||||
onContinue: () => {
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Query_brand, this, _dispatch).call(this, { type: "continue" });
|
||||
},
|
||||
retry: context.options.retry,
|
||||
retryDelay: context.options.retryDelay,
|
||||
networkMode: context.options.networkMode,
|
||||
canRun: () => true
|
||||
}));
|
||||
try {
|
||||
var _classPrivateFieldGet8, _classPrivateFieldGet9, _classPrivateFieldGet10, _classPrivateFieldGet11;
|
||||
const data = await retryer.start();
|
||||
if (data === void 0) {
|
||||
if (process.env.NODE_ENV !== "production") console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`);
|
||||
throw new Error(`${this.queryHash} data is undefined`);
|
||||
}
|
||||
this.setData(data);
|
||||
(_classPrivateFieldGet8 = (_classPrivateFieldGet9 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cache, this).config).onSuccess) === null || _classPrivateFieldGet8 === void 0 || _classPrivateFieldGet8.call(_classPrivateFieldGet9, data, this);
|
||||
(_classPrivateFieldGet10 = (_classPrivateFieldGet11 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cache, this).config).onSettled) === null || _classPrivateFieldGet10 === void 0 || _classPrivateFieldGet10.call(_classPrivateFieldGet11, data, this.state.error, this);
|
||||
return data;
|
||||
} catch (error) {
|
||||
var _classPrivateFieldGet12, _classPrivateFieldGet13, _classPrivateFieldGet14, _classPrivateFieldGet15;
|
||||
if (error instanceof require_retryer.CancelledError) {
|
||||
if (error.silent) return require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this).promise;
|
||||
else if (error.revert) {
|
||||
if (this.state.data === void 0) throw error;
|
||||
return this.state.data;
|
||||
}
|
||||
}
|
||||
require_classPrivateFieldSet2._assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
||||
type: "error",
|
||||
error
|
||||
});
|
||||
(_classPrivateFieldGet12 = (_classPrivateFieldGet13 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cache, this).config).onError) === null || _classPrivateFieldGet12 === void 0 || _classPrivateFieldGet12.call(_classPrivateFieldGet13, error, this);
|
||||
(_classPrivateFieldGet14 = (_classPrivateFieldGet15 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cache, this).config).onSettled) === null || _classPrivateFieldGet14 === void 0 || _classPrivateFieldGet14.call(_classPrivateFieldGet15, this.state.data, error, this);
|
||||
throw error;
|
||||
} finally {
|
||||
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this) === retryer) require_classPrivateFieldSet2._classPrivateFieldSet2(_retryer, this, void 0);
|
||||
this.scheduleGc();
|
||||
}
|
||||
}
|
||||
};
|
||||
function _dispatch(action) {
|
||||
const reducer = (state) => {
|
||||
switch (action.type) {
|
||||
case "failed": return {
|
||||
...state,
|
||||
fetchFailureCount: action.failureCount,
|
||||
fetchFailureReason: action.error
|
||||
};
|
||||
case "pause": return {
|
||||
...state,
|
||||
fetchStatus: "paused"
|
||||
};
|
||||
case "continue": return {
|
||||
...state,
|
||||
fetchStatus: "fetching"
|
||||
};
|
||||
case "fetch": return {
|
||||
...state,
|
||||
...fetchState(state.data, this.options),
|
||||
fetchMeta: action.meta ?? null
|
||||
};
|
||||
case "success":
|
||||
const newState = {
|
||||
...state,
|
||||
...successState(action.data, action.dataUpdatedAt),
|
||||
dataUpdateCount: state.dataUpdateCount + 1,
|
||||
...!action.manual && {
|
||||
fetchStatus: "idle",
|
||||
fetchFailureCount: 0,
|
||||
fetchFailureReason: null
|
||||
}
|
||||
};
|
||||
require_classPrivateFieldSet2._classPrivateFieldSet2(_revertState, this, action.manual ? newState : void 0);
|
||||
return newState;
|
||||
case "error":
|
||||
const error = action.error;
|
||||
return {
|
||||
...state,
|
||||
error,
|
||||
errorUpdateCount: state.errorUpdateCount + 1,
|
||||
errorUpdatedAt: Date.now(),
|
||||
fetchFailureCount: state.fetchFailureCount + 1,
|
||||
fetchFailureReason: error,
|
||||
fetchStatus: "idle",
|
||||
status: "error",
|
||||
isInvalidated: true
|
||||
};
|
||||
case "invalidate": return {
|
||||
...state,
|
||||
isInvalidated: true
|
||||
};
|
||||
case "setState": return {
|
||||
...state,
|
||||
...action.state
|
||||
};
|
||||
}
|
||||
};
|
||||
this.state = reducer(this.state);
|
||||
require_notifyManager.notifyManager.batch(() => {
|
||||
this.observers.slice().forEach((observer) => {
|
||||
observer.onQueryUpdate();
|
||||
});
|
||||
require_classPrivateFieldSet2._classPrivateFieldGet2(_cache, this).notify({
|
||||
query: this,
|
||||
type: "updated",
|
||||
action
|
||||
});
|
||||
});
|
||||
}
|
||||
function fetchState(data, options) {
|
||||
return {
|
||||
fetchFailureCount: 0,
|
||||
fetchFailureReason: null,
|
||||
fetchStatus: require_retryer.canFetch(options.networkMode) ? "fetching" : "paused",
|
||||
...data === void 0 && {
|
||||
error: null,
|
||||
status: "pending"
|
||||
}
|
||||
};
|
||||
}
|
||||
function successState(data, dataUpdatedAt) {
|
||||
return {
|
||||
data,
|
||||
dataUpdatedAt: dataUpdatedAt ?? Date.now(),
|
||||
error: null,
|
||||
isInvalidated: false,
|
||||
status: "success"
|
||||
};
|
||||
}
|
||||
function getDefaultState(options) {
|
||||
const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
|
||||
const hasData = data !== void 0;
|
||||
const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
|
||||
return {
|
||||
data,
|
||||
dataUpdateCount: 0,
|
||||
dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
|
||||
error: null,
|
||||
errorUpdateCount: 0,
|
||||
errorUpdatedAt: 0,
|
||||
fetchFailureCount: 0,
|
||||
fetchFailureReason: null,
|
||||
fetchMeta: null,
|
||||
isInvalidated: false,
|
||||
status: hasData ? "success" : "pending",
|
||||
fetchStatus: "idle"
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
exports.Query = Query;
|
||||
exports.fetchState = fetchState;
|
||||
|
||||
//# sourceMappingURL=query.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"query.cjs","names":["Removable","replaceData","noop","resolveQueryValue","skipToken","timeUntilStale","ensureQueryFn","infiniteQueryBehavior","createRetryer","CancelledError","canFetch"],"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveQueryValue,\n skipToken,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { CancelledError, canFetch, createRetryer } from './retryer'\nimport { Removable } from './removable'\nimport { infiniteQueryBehavior } from './infiniteQueryBehavior'\nimport type { QueryCache } from './queryCache'\nimport type { QueryClient } from './queryClient'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n StaleTime,\n} from './types'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n client: QueryClient\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\n/**\n * The raw state stored on a `Query` instance. This is the underlying state\n * that observer results (e.g. `QueryObserverResult`) are derived from.\n */\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n /**\n * The last successfully resolved data for the query.\n */\n data: TData | undefined\n /**\n * The number of times the query has successfully resolved.\n */\n dataUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"success\"`.\n */\n dataUpdatedAt: number\n /**\n * The error object for the query, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The sum of all errors, incremented every time the query resolves with an error.\n */\n errorUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"error\"`.\n */\n errorUpdatedAt: number\n /**\n * The failure count for the current fetch.\n * - Incremented every time the fetch fails.\n * - Reset to `0` when the fetch succeeds.\n */\n fetchFailureCount: number\n /**\n * The reason the current fetch failed, as reported by the retryer.\n * - Reset to `null` when the fetch succeeds.\n */\n fetchFailureReason: TError | null\n /**\n * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the\n * `fetchMore` direction for infinite queries.\n */\n fetchMeta: FetchMeta | null\n /**\n * Whether the query has been marked as invalidated via `invalidate()`.\n * - Reset to `false` whenever the query resolves successfully.\n */\n isInvalidated: boolean\n /**\n * The status of the query.\n * - `pending` if there's no cached data and no attempt was finished yet.\n * - `error` if the last attempt resulted in an error.\n * - `success` if the query has data.\n */\n status: QueryStatus\n /**\n * The fetch status of the query.\n * - `fetching`: the `queryFn` is currently executing.\n * - `paused`: a fetch wanted to run but has been paused (see network mode).\n * - `idle`: the query is not fetching.\n */\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise<unknown>\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions<TQueryFnData, TError, TData, any>\n client: QueryClient\n queryKey: TQueryKey\n state: QueryState<TData, TError>\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions<TData = unknown> {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterfacLine truncated
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { $n as Query, Jn as Action, Qn as FetchOptions, Xn as FetchDirection, Yn as FetchContext, Zn as FetchMeta, er as QueryBehavior, nr as fetchState, tr as QueryState } from "./hydration-DwR10Hi-.cjs";
|
||||
export { Action, FetchContext, FetchDirection, FetchMeta, FetchOptions, Query, QueryBehavior, QueryState, fetchState };
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { $n as Query, Jn as Action, Qn as FetchOptions, Xn as FetchDirection, Yn as FetchContext, Zn as FetchMeta, er as QueryBehavior, nr as fetchState, tr as QueryState } from "./hydration-Cq7QYAzB.js";
|
||||
export { Action, FetchContext, FetchDirection, FetchMeta, FetchOptions, Query, QueryBehavior, QueryState, fetchState };
|
||||
+553
@@ -0,0 +1,553 @@
|
||||
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
|
||||
import { ensureQueryFn, noop, replaceData, resolveQueryValue, skipToken, timeUntilStale } from "./utils.js";
|
||||
import { notifyManager } from "./notifyManager.js";
|
||||
import { CancelledError, canFetch, createRetryer } from "./retryer.js";
|
||||
import { Removable } from "./removable.js";
|
||||
import { infiniteQueryBehavior } from "./infiniteQueryBehavior.js";
|
||||
import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-CBwa_Y7C.js";
|
||||
//#region src/query.ts
|
||||
var _queryType = /* @__PURE__ */ new WeakMap();
|
||||
var _initialState = /* @__PURE__ */ new WeakMap();
|
||||
var _revertState = /* @__PURE__ */ new WeakMap();
|
||||
var _cache = /* @__PURE__ */ new WeakMap();
|
||||
var _client = /* @__PURE__ */ new WeakMap();
|
||||
var _retryer = /* @__PURE__ */ new WeakMap();
|
||||
var _defaultOptions = /* @__PURE__ */ new WeakMap();
|
||||
var _abortSignalConsumed = /* @__PURE__ */ new WeakMap();
|
||||
var _Query_brand = /* @__PURE__ */ new WeakSet();
|
||||
/**
|
||||
* Represents a single cached query. A `Query` holds the query's key, options,
|
||||
* state (data/error/status), and the observers currently subscribed to it.
|
||||
*
|
||||
* Instances are created and managed internally by `QueryCache`; application
|
||||
* code typically interacts with queries indirectly through `QueryClient` or
|
||||
* a framework hook like `useQuery`. Direct access to a `Query` instance is
|
||||
* possible via `queryCache.find()`/`findAll()` for inspecting cache state.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const queryCache = queryClient.getQueryCache()
|
||||
* const query = queryCache.find({ queryKey: ['posts'] })
|
||||
*
|
||||
* if (query) {
|
||||
* console.log(query.state.dataUpdatedAt)
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
var Query = class extends Removable {
|
||||
constructor(config) {
|
||||
super();
|
||||
_classPrivateMethodInitSpec(this, _Query_brand);
|
||||
_classPrivateFieldInitSpec(this, _queryType, void 0);
|
||||
_classPrivateFieldInitSpec(this, _initialState, void 0);
|
||||
_classPrivateFieldInitSpec(this, _revertState, void 0);
|
||||
_classPrivateFieldInitSpec(this, _cache, void 0);
|
||||
_classPrivateFieldInitSpec(this, _client, void 0);
|
||||
_classPrivateFieldInitSpec(this, _retryer, void 0);
|
||||
_classPrivateFieldInitSpec(this, _defaultOptions, void 0);
|
||||
_classPrivateFieldInitSpec(this, _abortSignalConsumed, void 0);
|
||||
_classPrivateFieldSet2(_abortSignalConsumed, this, false);
|
||||
_classPrivateFieldSet2(_defaultOptions, this, config.defaultOptions);
|
||||
this.setOptions(config.options);
|
||||
this.observers = [];
|
||||
_classPrivateFieldSet2(_client, this, config.client);
|
||||
_classPrivateFieldSet2(_cache, this, _classPrivateFieldGet2(_client, this).getQueryCache());
|
||||
this.queryKey = config.queryKey;
|
||||
this.queryHash = config.queryHash;
|
||||
_classPrivateFieldSet2(_initialState, this, getDefaultState(this.options));
|
||||
this.state = config.state ?? _classPrivateFieldGet2(_initialState, this);
|
||||
this.scheduleGc();
|
||||
}
|
||||
/**
|
||||
* The `meta` object passed in the query's options, if any.
|
||||
*/
|
||||
get meta() {
|
||||
return this.options.meta;
|
||||
}
|
||||
/** @internal */
|
||||
get queryType() {
|
||||
return _classPrivateFieldGet2(_queryType, this);
|
||||
}
|
||||
/**
|
||||
* The promise for the currently in-flight fetch, if the query is fetching.
|
||||
* `undefined` when the query is not fetching.
|
||||
*/
|
||||
get promise() {
|
||||
var _classPrivateFieldGet2$1;
|
||||
return (_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.promise;
|
||||
}
|
||||
/** @internal */
|
||||
setOptions(options) {
|
||||
this.options = {
|
||||
..._classPrivateFieldGet2(_defaultOptions, this),
|
||||
...options
|
||||
};
|
||||
if (options === null || options === void 0 ? void 0 : options._type) _classPrivateFieldSet2(_queryType, this, options._type);
|
||||
this.updateGcTime(this.options.gcTime);
|
||||
if (this.state && this.state.data === void 0) {
|
||||
const defaultState = getDefaultState(this.options);
|
||||
if (defaultState.data !== void 0) {
|
||||
this.setState(successState(defaultState.data, defaultState.dataUpdatedAt));
|
||||
_classPrivateFieldSet2(_initialState, this, defaultState);
|
||||
}
|
||||
}
|
||||
}
|
||||
optionalRemove() {
|
||||
if (!this.observers.length && this.state.fetchStatus === "idle") _classPrivateFieldGet2(_cache, this).remove(this);
|
||||
}
|
||||
/** @internal */
|
||||
setData(newData, options) {
|
||||
const data = replaceData(this.state.data, newData, this.options);
|
||||
_assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
||||
data,
|
||||
type: "success",
|
||||
dataUpdatedAt: options === null || options === void 0 ? void 0 : options.updatedAt,
|
||||
manual: options === null || options === void 0 ? void 0 : options.manual
|
||||
});
|
||||
return data;
|
||||
}
|
||||
/**
|
||||
* Merges the given partial state directly into this query's state, notifying observers. Used
|
||||
* by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a
|
||||
* user manually trigger a loading/error state or edit the cached data.
|
||||
*/
|
||||
setState(state) {
|
||||
_assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
||||
type: "setState",
|
||||
state
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Cancels the query's currently in-flight fetch, if any.
|
||||
* - Returns a promise that resolves once the cancellation has settled.
|
||||
* - If no fetch is in progress, resolves immediately.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await query.cancel()
|
||||
* ```
|
||||
*/
|
||||
cancel(options) {
|
||||
var _classPrivateFieldGet3, _classPrivateFieldGet4;
|
||||
const promise = (_classPrivateFieldGet3 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.promise;
|
||||
(_classPrivateFieldGet4 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet4 === void 0 || _classPrivateFieldGet4.cancel(options);
|
||||
return promise ? promise.then(noop).catch(noop) : Promise.resolve();
|
||||
}
|
||||
/**
|
||||
* Clears the query's garbage collection timeout and silently cancels any
|
||||
* in-flight fetch. Called by `QueryCache` when the query is removed from
|
||||
* the cache.
|
||||
*
|
||||
* @see {@link Query#cancel}
|
||||
*/
|
||||
destroy() {
|
||||
super.destroy();
|
||||
this.cancel({ silent: true });
|
||||
}
|
||||
/** @internal */
|
||||
get resetState() {
|
||||
return _classPrivateFieldGet2(_initialState, this);
|
||||
}
|
||||
/**
|
||||
* Resets the query back to its initial state (the state it had when it was
|
||||
* first created, e.g. any `initialData`), destroying it first to cancel any
|
||||
* in-flight fetch.
|
||||
*/
|
||||
reset() {
|
||||
this.destroy();
|
||||
this.setState(this.resetState);
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query has at least one observer for which `enabled`
|
||||
* does not resolve to `false`.
|
||||
*/
|
||||
isActive() {
|
||||
return this.observers.some((observer) => resolveQueryValue(observer.options.enabled, this) !== false);
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query is disabled, meaning it will not fetch
|
||||
* automatically.
|
||||
* - If the query has observers, it is disabled when none of them are active
|
||||
* (see `isActive`).
|
||||
* - If the query has no observers, it is disabled when its `queryFn` is
|
||||
* `skipToken` or it has never been fetched.
|
||||
*/
|
||||
isDisabled() {
|
||||
if (this.getObserversCount() > 0) return !this.isActive();
|
||||
return this.options.queryFn === skipToken || !this.isFetched();
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query has been fetched, i.e. it has resolved with
|
||||
* either data or an error at least once.
|
||||
*/
|
||||
isFetched() {
|
||||
return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query has at least one observer configured with
|
||||
* `staleTime: 'static'`, meaning it is treated as never stale.
|
||||
*/
|
||||
isStatic() {
|
||||
if (this.getObserversCount() > 0) return this.observers.some((observer) => resolveQueryValue(observer.options.staleTime, this) === "static");
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query is stale.
|
||||
* - If the query has observers, defers to whether any observer's current
|
||||
* result reports `isStale` (which accounts for each observer's own
|
||||
* `staleTime` and `enabled` state).
|
||||
* - If the query has no observers, it is considered stale when it has no
|
||||
* data or has been invalidated.
|
||||
*
|
||||
* @see {@link Query#isStaleByTime}
|
||||
* @example
|
||||
* ```ts
|
||||
* if (query.isStale()) {
|
||||
* // refetch or otherwise treat the cached data as outdated
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
isStale() {
|
||||
if (this.getObserversCount() > 0) return this.observers.some((observer) => observer.getCurrentResult().isStale);
|
||||
return this.state.data === void 0 || this.state.isInvalidated;
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the query's data is stale relative to the given
|
||||
* `staleTime` (defaults to `0`).
|
||||
* - A query with no data is always stale.
|
||||
* - `staleTime: 'static'` is never stale.
|
||||
* - An invalidated query is always stale.
|
||||
* - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.
|
||||
*
|
||||
* @see {@link Query#isStale}
|
||||
* @example
|
||||
* ```ts
|
||||
* const isStale = query.isStaleByTime(1000 * 60)
|
||||
* ```
|
||||
*/
|
||||
isStaleByTime(staleTime = 0) {
|
||||
if (this.state.data === void 0) return true;
|
||||
if (staleTime === "static") return false;
|
||||
if (this.state.isInvalidated) return true;
|
||||
return !timeUntilStale(this.state.dataUpdatedAt, staleTime);
|
||||
}
|
||||
/** @internal */
|
||||
onFocus() {
|
||||
var _classPrivateFieldGet5;
|
||||
const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());
|
||||
observer === null || observer === void 0 || observer.refetch({ cancelRefetch: false });
|
||||
(_classPrivateFieldGet5 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet5 === void 0 || _classPrivateFieldGet5.continue();
|
||||
}
|
||||
/** @internal */
|
||||
onOnline() {
|
||||
var _classPrivateFieldGet6;
|
||||
const observer = this.observers.find((x) => x.shouldFetchOnReconnect());
|
||||
observer === null || observer === void 0 || observer.refetch({ cancelRefetch: false });
|
||||
(_classPrivateFieldGet6 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet6 === void 0 || _classPrivateFieldGet6.continue();
|
||||
}
|
||||
/** @internal */
|
||||
addObserver(observer) {
|
||||
if (!this.observers.includes(observer)) {
|
||||
this.observers.push(observer);
|
||||
this.clearGcTimeout();
|
||||
_classPrivateFieldGet2(_cache, this).notify({
|
||||
type: "observerAdded",
|
||||
query: this,
|
||||
observer
|
||||
});
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
removeObserver(observer) {
|
||||
const index = this.observers.indexOf(observer);
|
||||
if (index !== -1) {
|
||||
this.observers.splice(index, 1);
|
||||
if (!this.observers.length) {
|
||||
if (_classPrivateFieldGet2(_retryer, this)) {
|
||||
if (_classPrivateFieldGet2(_abortSignalConsumed, this) || this.state.fetchStatus === "paused" && this.state.status === "pending") _classPrivateFieldGet2(_retryer, this).cancel({ revert: true });
|
||||
else _classPrivateFieldGet2(_retryer, this).cancelRetry();
|
||||
}
|
||||
this.scheduleGc();
|
||||
}
|
||||
_classPrivateFieldGet2(_cache, this).notify({
|
||||
type: "observerRemoved",
|
||||
query: this,
|
||||
observer
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns the number of observers currently subscribed to this query.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* if (query.getObserversCount() === 0) {
|
||||
* // no component is currently watching this query
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
getObserversCount() {
|
||||
return this.observers.length;
|
||||
}
|
||||
/**
|
||||
* Marks the query as invalidated, unless it is already invalidated. This
|
||||
* updates `state.isInvalidated` and notifies observers, but does not by
|
||||
* itself trigger a refetch.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* query.invalidate()
|
||||
* ```
|
||||
*/
|
||||
invalidate() {
|
||||
if (!this.state.isInvalidated) _assertClassBrand(_Query_brand, this, _dispatch).call(this, { type: "invalidate" });
|
||||
}
|
||||
/**
|
||||
* Fetches the query, i.e. runs its `queryFn` (through any configured
|
||||
* retryer/behavior) and updates the query's state with the result.
|
||||
* - If a fetch is already in flight, returns its promise instead of
|
||||
* starting a new one, unless `fetchOptions.cancelRefetch` is set and the
|
||||
* query already has data, in which case the current fetch is silently
|
||||
* cancelled first.
|
||||
* - If `options` is passed, it replaces the query's current options
|
||||
* before fetching.
|
||||
*/
|
||||
async fetch(options, fetchOptions) {
|
||||
var _classPrivateFieldGet7, _context$fetchOptions;
|
||||
if (this.state.fetchStatus !== "idle" && ((_classPrivateFieldGet7 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.status()) !== "rejected") {
|
||||
if (this.state.data !== void 0 && (fetchOptions === null || fetchOptions === void 0 ? void 0 : fetchOptions.cancelRefetch)) this.cancel({ silent: true });
|
||||
else if (_classPrivateFieldGet2(_retryer, this)) {
|
||||
_classPrivateFieldGet2(_retryer, this).continueRetry();
|
||||
return _classPrivateFieldGet2(_retryer, this).promise;
|
||||
}
|
||||
}
|
||||
if (options) this.setOptions(options);
|
||||
if (!this.options.queryFn) {
|
||||
const observer = this.observers.find((x) => x.options.queryFn);
|
||||
if (observer) this.setOptions(observer.options);
|
||||
}
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
if (!Array.isArray(this.options.queryKey)) console.error(`As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`);
|
||||
}
|
||||
const abortController = new AbortController();
|
||||
const addSignalProperty = (object) => {
|
||||
Object.defineProperty(object, "signal", {
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
_classPrivateFieldSet2(_abortSignalConsumed, this, true);
|
||||
return abortController.signal;
|
||||
}
|
||||
});
|
||||
};
|
||||
const fetchFn = () => {
|
||||
const queryFn = ensureQueryFn(this.options, fetchOptions);
|
||||
const createQueryFnContext = () => {
|
||||
const queryFnContext = {
|
||||
client: _classPrivateFieldGet2(_client, this),
|
||||
queryKey: this.queryKey,
|
||||
meta: this.meta
|
||||
};
|
||||
addSignalProperty(queryFnContext);
|
||||
return queryFnContext;
|
||||
};
|
||||
const queryFnContext = createQueryFnContext();
|
||||
_classPrivateFieldSet2(_abortSignalConsumed, this, false);
|
||||
if (this.options.persister) return this.options.persister(queryFn, queryFnContext, this);
|
||||
return queryFn(queryFnContext);
|
||||
};
|
||||
const createFetchContext = () => {
|
||||
const context = {
|
||||
fetchOptions,
|
||||
options: this.options,
|
||||
queryKey: this.queryKey,
|
||||
client: _classPrivateFieldGet2(_client, this),
|
||||
state: this.state,
|
||||
fetchFn
|
||||
};
|
||||
addSignalProperty(context);
|
||||
return context;
|
||||
};
|
||||
const context = createFetchContext();
|
||||
const behavior = _classPrivateFieldGet2(_queryType, this) === "infinite" ? infiniteQueryBehavior(this.options.pages) : this.options.behavior;
|
||||
behavior === null || behavior === void 0 || behavior.onFetch(context, this);
|
||||
_classPrivateFieldSet2(_revertState, this, this.state);
|
||||
if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) === null || _context$fetchOptions === void 0 ? void 0 : _context$fetchOptions.meta)) {
|
||||
var _context$fetchOptions2;
|
||||
_assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
||||
type: "fetch",
|
||||
meta: (_context$fetchOptions2 = context.fetchOptions) === null || _context$fetchOptions2 === void 0 ? void 0 : _context$fetchOptions2.meta
|
||||
});
|
||||
}
|
||||
const retryer = _classPrivateFieldSet2(_retryer, this, createRetryer({
|
||||
initialPromise: fetchOptions === null || fetchOptions === void 0 ? void 0 : fetchOptions.initialPromise,
|
||||
fn: context.fetchFn,
|
||||
onCancel: (error) => {
|
||||
if (error instanceof CancelledError && error.revert) this.setState({
|
||||
..._classPrivateFieldGet2(_revertState, this),
|
||||
fetchStatus: "idle"
|
||||
});
|
||||
abortController.abort();
|
||||
},
|
||||
onFail: (failureCount, error) => {
|
||||
_assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
||||
type: "failed",
|
||||
failureCount,
|
||||
error
|
||||
});
|
||||
},
|
||||
onPause: () => {
|
||||
_assertClassBrand(_Query_brand, this, _dispatch).call(this, { type: "pause" });
|
||||
},
|
||||
onContinue: () => {
|
||||
_assertClassBrand(_Query_brand, this, _dispatch).call(this, { type: "continue" });
|
||||
},
|
||||
retry: context.options.retry,
|
||||
retryDelay: context.options.retryDelay,
|
||||
networkMode: context.options.networkMode,
|
||||
canRun: () => true
|
||||
}));
|
||||
try {
|
||||
var _classPrivateFieldGet8, _classPrivateFieldGet9, _classPrivateFieldGet10, _classPrivateFieldGet11;
|
||||
const data = await retryer.start();
|
||||
if (data === void 0) {
|
||||
if (process.env.NODE_ENV !== "production") console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`);
|
||||
throw new Error(`${this.queryHash} data is undefined`);
|
||||
}
|
||||
this.setData(data);
|
||||
(_classPrivateFieldGet8 = (_classPrivateFieldGet9 = _classPrivateFieldGet2(_cache, this).config).onSuccess) === null || _classPrivateFieldGet8 === void 0 || _classPrivateFieldGet8.call(_classPrivateFieldGet9, data, this);
|
||||
(_classPrivateFieldGet10 = (_classPrivateFieldGet11 = _classPrivateFieldGet2(_cache, this).config).onSettled) === null || _classPrivateFieldGet10 === void 0 || _classPrivateFieldGet10.call(_classPrivateFieldGet11, data, this.state.error, this);
|
||||
return data;
|
||||
} catch (error) {
|
||||
var _classPrivateFieldGet12, _classPrivateFieldGet13, _classPrivateFieldGet14, _classPrivateFieldGet15;
|
||||
if (error instanceof CancelledError) {
|
||||
if (error.silent) return _classPrivateFieldGet2(_retryer, this).promise;
|
||||
else if (error.revert) {
|
||||
if (this.state.data === void 0) throw error;
|
||||
return this.state.data;
|
||||
}
|
||||
}
|
||||
_assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
||||
type: "error",
|
||||
error
|
||||
});
|
||||
(_classPrivateFieldGet12 = (_classPrivateFieldGet13 = _classPrivateFieldGet2(_cache, this).config).onError) === null || _classPrivateFieldGet12 === void 0 || _classPrivateFieldGet12.call(_classPrivateFieldGet13, error, this);
|
||||
(_classPrivateFieldGet14 = (_classPrivateFieldGet15 = _classPrivateFieldGet2(_cache, this).config).onSettled) === null || _classPrivateFieldGet14 === void 0 || _classPrivateFieldGet14.call(_classPrivateFieldGet15, this.state.data, error, this);
|
||||
throw error;
|
||||
} finally {
|
||||
if (_classPrivateFieldGet2(_retryer, this) === retryer) _classPrivateFieldSet2(_retryer, this, void 0);
|
||||
this.scheduleGc();
|
||||
}
|
||||
}
|
||||
};
|
||||
function _dispatch(action) {
|
||||
const reducer = (state) => {
|
||||
switch (action.type) {
|
||||
case "failed": return {
|
||||
...state,
|
||||
fetchFailureCount: action.failureCount,
|
||||
fetchFailureReason: action.error
|
||||
};
|
||||
case "pause": return {
|
||||
...state,
|
||||
fetchStatus: "paused"
|
||||
};
|
||||
case "continue": return {
|
||||
...state,
|
||||
fetchStatus: "fetching"
|
||||
};
|
||||
case "fetch": return {
|
||||
...state,
|
||||
...fetchState(state.data, this.options),
|
||||
fetchMeta: action.meta ?? null
|
||||
};
|
||||
case "success":
|
||||
const newState = {
|
||||
...state,
|
||||
...successState(action.data, action.dataUpdatedAt),
|
||||
dataUpdateCount: state.dataUpdateCount + 1,
|
||||
...!action.manual && {
|
||||
fetchStatus: "idle",
|
||||
fetchFailureCount: 0,
|
||||
fetchFailureReason: null
|
||||
}
|
||||
};
|
||||
_classPrivateFieldSet2(_revertState, this, action.manual ? newState : void 0);
|
||||
return newState;
|
||||
case "error":
|
||||
const error = action.error;
|
||||
return {
|
||||
...state,
|
||||
error,
|
||||
errorUpdateCount: state.errorUpdateCount + 1,
|
||||
errorUpdatedAt: Date.now(),
|
||||
fetchFailureCount: state.fetchFailureCount + 1,
|
||||
fetchFailureReason: error,
|
||||
fetchStatus: "idle",
|
||||
status: "error",
|
||||
isInvalidated: true
|
||||
};
|
||||
case "invalidate": return {
|
||||
...state,
|
||||
isInvalidated: true
|
||||
};
|
||||
case "setState": return {
|
||||
...state,
|
||||
...action.state
|
||||
};
|
||||
}
|
||||
};
|
||||
this.state = reducer(this.state);
|
||||
notifyManager.batch(() => {
|
||||
this.observers.slice().forEach((observer) => {
|
||||
observer.onQueryUpdate();
|
||||
});
|
||||
_classPrivateFieldGet2(_cache, this).notify({
|
||||
query: this,
|
||||
type: "updated",
|
||||
action
|
||||
});
|
||||
});
|
||||
}
|
||||
function fetchState(data, options) {
|
||||
return {
|
||||
fetchFailureCount: 0,
|
||||
fetchFailureReason: null,
|
||||
fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused",
|
||||
...data === void 0 && {
|
||||
error: null,
|
||||
status: "pending"
|
||||
}
|
||||
};
|
||||
}
|
||||
function successState(data, dataUpdatedAt) {
|
||||
return {
|
||||
data,
|
||||
dataUpdatedAt: dataUpdatedAt ?? Date.now(),
|
||||
error: null,
|
||||
isInvalidated: false,
|
||||
status: "success"
|
||||
};
|
||||
}
|
||||
function getDefaultState(options) {
|
||||
const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
|
||||
const hasData = data !== void 0;
|
||||
const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
|
||||
return {
|
||||
data,
|
||||
dataUpdateCount: 0,
|
||||
dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
|
||||
error: null,
|
||||
errorUpdateCount: 0,
|
||||
errorUpdatedAt: 0,
|
||||
fetchFailureCount: 0,
|
||||
fetchFailureReason: null,
|
||||
fetchMeta: null,
|
||||
isInvalidated: false,
|
||||
status: hasData ? "success" : "pending",
|
||||
fetchStatus: "idle"
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
export { Query, fetchState };
|
||||
|
||||
//# sourceMappingURL=query.js.map
|
||||
Loaded 100 of 4271 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user