UEA-Prodem

This commit is contained in:
2026-06-10 12:38:42 -03:00
parent 3f33154e16
commit c41625e542
9352 changed files with 1128292 additions and 14752 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+48
View File
@@ -0,0 +1,48 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/environmentManager.ts
var environmentManager_exports = {};
__export(environmentManager_exports, {
environmentManager: () => environmentManager
});
module.exports = __toCommonJS(environmentManager_exports);
var import_utils = require("./utils.cjs");
var environmentManager = /* @__PURE__ */ (() => {
let isServerFn = () => import_utils.isServer;
return {
/**
* Returns whether the current runtime should be treated as a server environment.
*/
isServer() {
return isServerFn();
},
/**
* Overrides the server check globally.
*/
setIsServer(isServerValue) {
isServerFn = isServerValue;
}
};
})();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
environmentManager
});
//# sourceMappingURL=environmentManager.cjs.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/environmentManager.ts"],"sourcesContent":["import { isServer } from './utils'\n\nexport type IsServerValue = () => boolean\n\n/**\n * Manages environment detection used by TanStack Query internals.\n */\nexport const environmentManager = (() => {\n let isServerFn: IsServerValue = () => isServer\n\n return {\n /**\n * Returns whether the current runtime should be treated as a server environment.\n */\n isServer(): boolean {\n return isServerFn()\n },\n /**\n * Overrides the server check globally.\n */\n setIsServer(isServerValue: IsServerValue): void {\n isServerFn = isServerValue\n },\n }\n})()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAyB;AAOlB,IAAM,qBAAsB,uBAAM;AACvC,MAAI,aAA4B,MAAM;AAEtC,SAAO;AAAA;AAAA;AAAA;AAAA,IAIL,WAAoB;AAClB,aAAO,WAAW;AAAA,IACpB;AAAA;AAAA;AAAA;AAAA,IAIA,YAAY,eAAoC;AAC9C,mBAAa;AAAA,IACf;AAAA,EACF;AACF,GAAG;","names":[]}
@@ -0,0 +1,2 @@
export { IsServerValue } from './_tsup-dts-rollup.cjs';
export { environmentManager } from './_tsup-dts-rollup.cjs';
@@ -0,0 +1,2 @@
export { IsServerValue } from './_tsup-dts-rollup.js';
export { environmentManager } from './_tsup-dts-rollup.js';
+23
View File
@@ -0,0 +1,23 @@
// src/environmentManager.ts
import { isServer } from "./utils.js";
var environmentManager = /* @__PURE__ */ (() => {
let isServerFn = () => isServer;
return {
/**
* Returns whether the current runtime should be treated as a server environment.
*/
isServer() {
return isServerFn();
},
/**
* Overrides the server check globally.
*/
setIsServer(isServerValue) {
isServerFn = isServerValue;
}
};
})();
export {
environmentManager
};
//# sourceMappingURL=environmentManager.js.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/environmentManager.ts"],"sourcesContent":["import { isServer } from './utils'\n\nexport type IsServerValue = () => boolean\n\n/**\n * Manages environment detection used by TanStack Query internals.\n */\nexport const environmentManager = (() => {\n let isServerFn: IsServerValue = () => isServer\n\n return {\n /**\n * Returns whether the current runtime should be treated as a server environment.\n */\n isServer(): boolean {\n return isServerFn()\n },\n /**\n * Overrides the server check globally.\n */\n setIsServer(isServerValue: IsServerValue): void {\n isServerFn = isServerValue\n },\n }\n})()\n"],"mappings":";AAAA,SAAS,gBAAgB;AAOlB,IAAM,qBAAsB,uBAAM;AACvC,MAAI,aAA4B,MAAM;AAEtC,SAAO;AAAA;AAAA;AAAA;AAAA,IAIL,WAAoB;AAClB,aAAO,WAAW;AAAA,IACpB;AAAA;AAAA;AAAA;AAAA,IAIA,YAAY,eAAoC;AAC9C,mBAAa;AAAA,IACf;AAAA,EACF;AACF,GAAG;","names":[]}
+93
View File
@@ -0,0 +1,93 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/focusManager.ts
var focusManager_exports = {};
__export(focusManager_exports, {
FocusManager: () => FocusManager,
focusManager: () => focusManager
});
module.exports = __toCommonJS(focusManager_exports);
var import_subscribable = require("./subscribable.cjs");
var FocusManager = class extends import_subscribable.Subscribable {
#focused;
#cleanup;
#setup;
constructor() {
super();
this.#setup = (onFocus) => {
if (typeof window !== "undefined" && window.addEventListener) {
const listener = () => onFocus();
window.addEventListener("visibilitychange", listener, false);
return () => {
window.removeEventListener("visibilitychange", listener);
};
}
return;
};
}
onSubscribe() {
if (!this.#cleanup) {
this.setEventListener(this.#setup);
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
this.#cleanup?.();
this.#cleanup = void 0;
}
}
setEventListener(setup) {
this.#setup = setup;
this.#cleanup?.();
this.#cleanup = setup((focused) => {
if (typeof focused === "boolean") {
this.setFocused(focused);
} else {
this.onFocus();
}
});
}
setFocused(focused) {
const changed = this.#focused !== focused;
if (changed) {
this.#focused = focused;
this.onFocus();
}
}
onFocus() {
const isFocused = this.isFocused();
this.listeners.forEach((listener) => {
listener(isFocused);
});
}
isFocused() {
if (typeof this.#focused === "boolean") {
return this.#focused;
}
return globalThis.document?.visibilityState !== "hidden";
}
};
var focusManager = new FocusManager();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
FocusManager,
focusManager
});
//# sourceMappingURL=focusManager.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"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\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 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 setFocused(focused?: boolean): void {\n const changed = this.#focused !== focused\n if (changed) {\n this.#focused = focused\n this.onFocus()\n }\n }\n\n onFocus(): void {\n const isFocused = this.isFocused()\n this.listeners.forEach((listener) => {\n listener(isFocused)\n })\n }\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\nexport const focusManager = new FocusManager()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAA6B;AAQtB,IAAM,eAAN,cAA2B,iCAAuB;AAAA,EACvD;AAAA,EACA;AAAA,EAEA;AAAA,EAEA,cAAc;AACZ,UAAM;AACN,SAAK,SAAS,CAAC,YAAY;AAGzB,UAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;AAC5D,cAAM,WAAW,MAAM,QAAQ;AAE/B,eAAO,iBAAiB,oBAAoB,UAAU,KAAK;AAE3D,eAAO,MAAM;AAEX,iBAAO,oBAAoB,oBAAoB,QAAQ;AAAA,QACzD;AAAA,MACF;AACA;AAAA,IACF;AAAA,EACF;AAAA,EAEU,cAAoB;AAC5B,QAAI,CAAC,KAAK,UAAU;AAClB,WAAK,iBAAiB,KAAK,MAAM;AAAA,IACnC;AAAA,EACF;AAAA,EAEU,gBAAgB;AACxB,QAAI,CAAC,KAAK,aAAa,GAAG;AACxB,WAAK,WAAW;AAChB,WAAK,WAAW;AAAA,IAClB;AAAA,EACF;AAAA,EAEA,iBAAiB,OAAsB;AACrC,SAAK,SAAS;AACd,SAAK,WAAW;AAChB,SAAK,WAAW,MAAM,CAAC,YAAY;AACjC,UAAI,OAAO,YAAY,WAAW;AAChC,aAAK,WAAW,OAAO;AAAA,MACzB,OAAO;AACL,aAAK,QAAQ;AAAA,MACf;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,WAAW,SAAyB;AAClC,UAAM,UAAU,KAAK,aAAa;AAClC,QAAI,SAAS;AACX,WAAK,WAAW;AAChB,WAAK,QAAQ;AAAA,IACf;AAAA,EACF;AAAA,EAEA,UAAgB;AACd,UAAM,YAAY,KAAK,UAAU;AACjC,SAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,eAAS,SAAS;AAAA,IACpB,CAAC;AAAA,EACH;AAAA,EAEA,YAAqB;AACnB,QAAI,OAAO,KAAK,aAAa,WAAW;AACtC,aAAO,KAAK;AAAA,IACd;AAIA,WAAO,WAAW,UAAU,oBAAoB;AAAA,EAClD;AACF;AAEO,IAAM,eAAe,IAAI,aAAa;","names":[]}
+2
View File
@@ -0,0 +1,2 @@
export { FocusManager } from './_tsup-dts-rollup.cjs';
export { focusManager } from './_tsup-dts-rollup.cjs';
+2
View File
@@ -0,0 +1,2 @@
export { FocusManager } from './_tsup-dts-rollup.js';
export { focusManager } from './_tsup-dts-rollup.js';
+67
View File
@@ -0,0 +1,67 @@
// src/focusManager.ts
import { Subscribable } from "./subscribable.js";
var FocusManager = class extends Subscribable {
#focused;
#cleanup;
#setup;
constructor() {
super();
this.#setup = (onFocus) => {
if (typeof window !== "undefined" && window.addEventListener) {
const listener = () => onFocus();
window.addEventListener("visibilitychange", listener, false);
return () => {
window.removeEventListener("visibilitychange", listener);
};
}
return;
};
}
onSubscribe() {
if (!this.#cleanup) {
this.setEventListener(this.#setup);
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
this.#cleanup?.();
this.#cleanup = void 0;
}
}
setEventListener(setup) {
this.#setup = setup;
this.#cleanup?.();
this.#cleanup = setup((focused) => {
if (typeof focused === "boolean") {
this.setFocused(focused);
} else {
this.onFocus();
}
});
}
setFocused(focused) {
const changed = this.#focused !== focused;
if (changed) {
this.#focused = focused;
this.onFocus();
}
}
onFocus() {
const isFocused = this.isFocused();
this.listeners.forEach((listener) => {
listener(isFocused);
});
}
isFocused() {
if (typeof this.#focused === "boolean") {
return this.#focused;
}
return globalThis.document?.visibilityState !== "hidden";
}
};
var focusManager = new FocusManager();
export {
FocusManager,
focusManager
};
//# sourceMappingURL=focusManager.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"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\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 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 setFocused(focused?: boolean): void {\n const changed = this.#focused !== focused\n if (changed) {\n this.#focused = focused\n this.onFocus()\n }\n }\n\n onFocus(): void {\n const isFocused = this.isFocused()\n this.listeners.forEach((listener) => {\n listener(isFocused)\n })\n }\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\nexport const focusManager = new FocusManager()\n"],"mappings":";AAAA,SAAS,oBAAoB;AAQtB,IAAM,eAAN,cAA2B,aAAuB;AAAA,EACvD;AAAA,EACA;AAAA,EAEA;AAAA,EAEA,cAAc;AACZ,UAAM;AACN,SAAK,SAAS,CAAC,YAAY;AAGzB,UAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;AAC5D,cAAM,WAAW,MAAM,QAAQ;AAE/B,eAAO,iBAAiB,oBAAoB,UAAU,KAAK;AAE3D,eAAO,MAAM;AAEX,iBAAO,oBAAoB,oBAAoB,QAAQ;AAAA,QACzD;AAAA,MACF;AACA;AAAA,IACF;AAAA,EACF;AAAA,EAEU,cAAoB;AAC5B,QAAI,CAAC,KAAK,UAAU;AAClB,WAAK,iBAAiB,KAAK,MAAM;AAAA,IACnC;AAAA,EACF;AAAA,EAEU,gBAAgB;AACxB,QAAI,CAAC,KAAK,aAAa,GAAG;AACxB,WAAK,WAAW;AAChB,WAAK,WAAW;AAAA,IAClB;AAAA,EACF;AAAA,EAEA,iBAAiB,OAAsB;AACrC,SAAK,SAAS;AACd,SAAK,WAAW;AAChB,SAAK,WAAW,MAAM,CAAC,YAAY;AACjC,UAAI,OAAO,YAAY,WAAW;AAChC,aAAK,WAAW,OAAO;AAAA,MACzB,OAAO;AACL,aAAK,QAAQ;AAAA,MACf;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,WAAW,SAAyB;AAClC,UAAM,UAAU,KAAK,aAAa;AAClC,QAAI,SAAS;AACX,WAAK,WAAW;AAChB,WAAK,QAAQ;AAAA,IACf;AAAA,EACF;AAAA,EAEA,UAAgB;AACd,UAAM,YAAY,KAAK,UAAU;AACjC,SAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,eAAS,SAAS;AAAA,IACpB,CAAC;AAAA,EACH;AAAA,EAEA,YAAqB;AACnB,QAAI,OAAO,KAAK,aAAa,WAAW;AACtC,aAAO,KAAK;AAAA,IACd;AAIA,WAAO,WAAW,UAAU,oBAAoB;AAAA,EAClD;AACF;AAEO,IAAM,eAAe,IAAI,aAAa;","names":[]}
+199
View File
@@ -0,0 +1,199 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/hydration.ts
var hydration_exports = {};
__export(hydration_exports, {
defaultShouldDehydrateMutation: () => defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery: () => defaultShouldDehydrateQuery,
dehydrate: () => dehydrate,
hydrate: () => hydrate
});
module.exports = __toCommonJS(hydration_exports);
var import_thenable = require("./thenable.cjs");
var import_utils = require("./utils.cjs");
function defaultTransformerFn(data) {
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 dehydrateQuery(query, serializeData, shouldRedactErrors) {
const dehydratePromise = () => {
const promise = query.promise?.then(serializeData).catch((error) => {
if (!shouldRedactErrors(error)) {
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(new Error("redacted"));
});
promise?.catch(import_utils.noop);
return promise;
};
return {
dehydratedAt: Date.now(),
state: {
...query.state,
...query.state.data !== void 0 && {
data: serializeData(query.state.data)
}
},
queryKey: query.queryKey,
queryHash: query.queryHash,
...query.state.status === "pending" && {
promise: dehydratePromise()
},
...query.meta && { meta: query.meta },
...query.queryType && { queryType: query.queryType }
};
}
function defaultShouldDehydrateMutation(mutation) {
return mutation.state.isPaused;
}
function defaultShouldDehydrateQuery(query) {
return query.state.status === "success";
}
function defaultShouldRedactErrors(_) {
return true;
}
function dehydrate(client, options = {}) {
const filterMutation = options.shouldDehydrateMutation ?? client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ?? defaultShouldDehydrateMutation;
const mutations = client.getMutationCache().getAll().flatMap(
(mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []
);
const filterQuery = options.shouldDehydrateQuery ?? client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ?? defaultShouldDehydrateQuery;
const shouldRedactErrors = options.shouldRedactErrors ?? client.getDefaultOptions().dehydrate?.shouldRedactErrors ?? defaultShouldRedactErrors;
const serializeData = options.serializeData ?? client.getDefaultOptions().dehydrate?.serializeData ?? defaultTransformerFn;
const queries = client.getQueryCache().getAll().flatMap(
(query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : []
);
return { mutations, queries };
}
function hydrate(client, dehydratedState, options) {
if (typeof dehydratedState !== "object" || dehydratedState === null) {
return;
}
const mutationCache = client.getMutationCache();
const queryCache = client.getQueryCache();
const deserializeData = options?.defaultOptions?.deserializeData ?? client.getDefaultOptions().hydrate?.deserializeData ?? defaultTransformerFn;
const mutations = dehydratedState.mutations || [];
const queries = dehydratedState.queries || [];
mutations.forEach(({ state, ...mutationOptions }) => {
mutationCache.build(
client,
{
...client.getDefaultOptions().hydrate?.mutations,
...options?.defaultOptions?.mutations,
...mutationOptions
},
state
);
});
queries.forEach(
({
queryKey,
state,
queryHash,
meta,
promise,
dehydratedAt,
queryType
}) => {
const syncData = promise ? (0, import_thenable.tryResolveSync)(promise) : void 0;
const rawData = state.data === void 0 ? syncData?.data : state.data;
const data = rawData === void 0 ? rawData : deserializeData(rawData);
let query = queryCache.get(queryHash);
const existingQueryIsPending = query?.state.status === "pending";
const existingQueryIsFetching = query?.state.fetchStatus === "fetching";
if (query) {
const hasNewerSyncData = syncData && // We only need this undefined check to handle older dehydration
// payloads that might not have dehydratedAt
dehydratedAt !== void 0 && dehydratedAt > query.state.dataUpdatedAt;
if (state.dataUpdatedAt > query.state.dataUpdatedAt || hasNewerSyncData) {
const { fetchStatus: _ignored, ...serializedState } = state;
query.setState({
...serializedState,
data,
// If the query was pending at the moment of dehydration, but resolved to have data
// before hydration, we can assume the query should be hydrated as successful.
//
// Since you can opt into dehydrating failed queries, and those can have data from
// previous successful fetches, we make sure we only do this for pending queries.
...state.status === "pending" && data !== void 0 && {
status: "success",
// Preserve existing fetchStatus if the existing query is actively fetching.
...!existingQueryIsFetching && {
fetchStatus: "idle"
}
}
});
}
} else {
query = queryCache.build(
client,
{
...client.getDefaultOptions().hydrate?.queries,
...options?.defaultOptions?.queries,
queryKey,
queryHash,
meta,
_type: queryType
},
// Reset fetch status to idle to avoid
// query being stuck in fetching state upon hydration
{
...state,
data,
fetchStatus: "idle",
// Like above, if the query was pending at the moment of dehydration but has data,
// we can assume it should be hydrated as successful.
status: state.status === "pending" && data !== void 0 ? "success" : state.status
}
);
}
if (promise && // If the data was synchronously available, there is no need to set up
// a retryer and thus no reason to call fetch
!syncData && !existingQueryIsPending && !existingQueryIsFetching && // Only hydrate if dehydration is newer than any existing data,
// this is always true for new queries
(dehydratedAt === void 0 || dehydratedAt > query.state.dataUpdatedAt)) {
query.fetch(void 0, {
// RSC transformed promises are not thenable
initialPromise: Promise.resolve(promise).then(deserializeData)
}).catch(import_utils.noop);
}
}
);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
hydrate
});
//# sourceMappingURL=hydration.cjs.map
File diff suppressed because one or more lines are too long
+7
View File
@@ -0,0 +1,7 @@
export { defaultShouldDehydrateMutation } from './_tsup-dts-rollup.cjs';
export { defaultShouldDehydrateQuery } from './_tsup-dts-rollup.cjs';
export { dehydrate } from './_tsup-dts-rollup.cjs';
export { hydrate } from './_tsup-dts-rollup.cjs';
export { DehydrateOptions } from './_tsup-dts-rollup.cjs';
export { HydrateOptions } from './_tsup-dts-rollup.cjs';
export { DehydratedState } from './_tsup-dts-rollup.cjs';
+7
View File
@@ -0,0 +1,7 @@
export { defaultShouldDehydrateMutation } from './_tsup-dts-rollup.js';
export { defaultShouldDehydrateQuery } from './_tsup-dts-rollup.js';
export { dehydrate } from './_tsup-dts-rollup.js';
export { hydrate } from './_tsup-dts-rollup.js';
export { DehydrateOptions } from './_tsup-dts-rollup.js';
export { HydrateOptions } from './_tsup-dts-rollup.js';
export { DehydratedState } from './_tsup-dts-rollup.js';
+171
View File
@@ -0,0 +1,171 @@
// src/hydration.ts
import { tryResolveSync } from "./thenable.js";
import { noop } from "./utils.js";
function defaultTransformerFn(data) {
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 dehydrateQuery(query, serializeData, shouldRedactErrors) {
const dehydratePromise = () => {
const promise = query.promise?.then(serializeData).catch((error) => {
if (!shouldRedactErrors(error)) {
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(new Error("redacted"));
});
promise?.catch(noop);
return promise;
};
return {
dehydratedAt: Date.now(),
state: {
...query.state,
...query.state.data !== void 0 && {
data: serializeData(query.state.data)
}
},
queryKey: query.queryKey,
queryHash: query.queryHash,
...query.state.status === "pending" && {
promise: dehydratePromise()
},
...query.meta && { meta: query.meta },
...query.queryType && { queryType: query.queryType }
};
}
function defaultShouldDehydrateMutation(mutation) {
return mutation.state.isPaused;
}
function defaultShouldDehydrateQuery(query) {
return query.state.status === "success";
}
function defaultShouldRedactErrors(_) {
return true;
}
function dehydrate(client, options = {}) {
const filterMutation = options.shouldDehydrateMutation ?? client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ?? defaultShouldDehydrateMutation;
const mutations = client.getMutationCache().getAll().flatMap(
(mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []
);
const filterQuery = options.shouldDehydrateQuery ?? client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ?? defaultShouldDehydrateQuery;
const shouldRedactErrors = options.shouldRedactErrors ?? client.getDefaultOptions().dehydrate?.shouldRedactErrors ?? defaultShouldRedactErrors;
const serializeData = options.serializeData ?? client.getDefaultOptions().dehydrate?.serializeData ?? defaultTransformerFn;
const queries = client.getQueryCache().getAll().flatMap(
(query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : []
);
return { mutations, queries };
}
function hydrate(client, dehydratedState, options) {
if (typeof dehydratedState !== "object" || dehydratedState === null) {
return;
}
const mutationCache = client.getMutationCache();
const queryCache = client.getQueryCache();
const deserializeData = options?.defaultOptions?.deserializeData ?? client.getDefaultOptions().hydrate?.deserializeData ?? defaultTransformerFn;
const mutations = dehydratedState.mutations || [];
const queries = dehydratedState.queries || [];
mutations.forEach(({ state, ...mutationOptions }) => {
mutationCache.build(
client,
{
...client.getDefaultOptions().hydrate?.mutations,
...options?.defaultOptions?.mutations,
...mutationOptions
},
state
);
});
queries.forEach(
({
queryKey,
state,
queryHash,
meta,
promise,
dehydratedAt,
queryType
}) => {
const syncData = promise ? tryResolveSync(promise) : void 0;
const rawData = state.data === void 0 ? syncData?.data : state.data;
const data = rawData === void 0 ? rawData : deserializeData(rawData);
let query = queryCache.get(queryHash);
const existingQueryIsPending = query?.state.status === "pending";
const existingQueryIsFetching = query?.state.fetchStatus === "fetching";
if (query) {
const hasNewerSyncData = syncData && // We only need this undefined check to handle older dehydration
// payloads that might not have dehydratedAt
dehydratedAt !== void 0 && dehydratedAt > query.state.dataUpdatedAt;
if (state.dataUpdatedAt > query.state.dataUpdatedAt || hasNewerSyncData) {
const { fetchStatus: _ignored, ...serializedState } = state;
query.setState({
...serializedState,
data,
// If the query was pending at the moment of dehydration, but resolved to have data
// before hydration, we can assume the query should be hydrated as successful.
//
// Since you can opt into dehydrating failed queries, and those can have data from
// previous successful fetches, we make sure we only do this for pending queries.
...state.status === "pending" && data !== void 0 && {
status: "success",
// Preserve existing fetchStatus if the existing query is actively fetching.
...!existingQueryIsFetching && {
fetchStatus: "idle"
}
}
});
}
} else {
query = queryCache.build(
client,
{
...client.getDefaultOptions().hydrate?.queries,
...options?.defaultOptions?.queries,
queryKey,
queryHash,
meta,
_type: queryType
},
// Reset fetch status to idle to avoid
// query being stuck in fetching state upon hydration
{
...state,
data,
fetchStatus: "idle",
// Like above, if the query was pending at the moment of dehydration but has data,
// we can assume it should be hydrated as successful.
status: state.status === "pending" && data !== void 0 ? "success" : state.status
}
);
}
if (promise && // If the data was synchronously available, there is no need to set up
// a retryer and thus no reason to call fetch
!syncData && !existingQueryIsPending && !existingQueryIsFetching && // Only hydrate if dehydration is newer than any existing data,
// this is always true for new queries
(dehydratedAt === void 0 || dehydratedAt > query.state.dataUpdatedAt)) {
query.fetch(void 0, {
// RSC transformed promises are not thenable
initialPromise: Promise.resolve(promise).then(deserializeData)
}).catch(noop);
}
}
);
}
export {
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
hydrate
};
//# sourceMappingURL=hydration.js.map
File diff suppressed because one or more lines are too long
+113
View File
@@ -0,0 +1,113 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
CancelledError: () => import_retryer.CancelledError,
InfiniteQueryObserver: () => import_infiniteQueryObserver.InfiniteQueryObserver,
Mutation: () => import_mutation.Mutation,
MutationCache: () => import_mutationCache.MutationCache,
MutationObserver: () => import_mutationObserver.MutationObserver,
QueriesObserver: () => import_queriesObserver.QueriesObserver,
Query: () => import_query.Query,
QueryCache: () => import_queryCache.QueryCache,
QueryClient: () => import_queryClient.QueryClient,
QueryObserver: () => import_queryObserver.QueryObserver,
defaultScheduler: () => import_notifyManager.defaultScheduler,
defaultShouldDehydrateMutation: () => import_hydration.defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery: () => import_hydration.defaultShouldDehydrateQuery,
dehydrate: () => import_hydration.dehydrate,
environmentManager: () => import_environmentManager.environmentManager,
experimental_streamedQuery: () => import_streamedQuery.streamedQuery,
focusManager: () => import_focusManager.focusManager,
hashKey: () => import_utils.hashKey,
hydrate: () => import_hydration.hydrate,
isCancelledError: () => import_retryer.isCancelledError,
isServer: () => import_utils.isServer,
keepPreviousData: () => import_utils.keepPreviousData,
matchMutation: () => import_utils.matchMutation,
matchQuery: () => import_utils.matchQuery,
noop: () => import_utils.noop,
notifyManager: () => import_notifyManager.notifyManager,
onlineManager: () => import_onlineManager.onlineManager,
partialMatchKey: () => import_utils.partialMatchKey,
replaceEqualDeep: () => import_utils.replaceEqualDeep,
shouldThrowError: () => import_utils.shouldThrowError,
skipToken: () => import_utils.skipToken,
timeoutManager: () => import_timeoutManager.timeoutManager
});
module.exports = __toCommonJS(index_exports);
var import_focusManager = require("./focusManager.cjs");
var import_environmentManager = require("./environmentManager.cjs");
var import_hydration = require("./hydration.cjs");
var import_infiniteQueryObserver = require("./infiniteQueryObserver.cjs");
var import_mutationCache = require("./mutationCache.cjs");
var import_mutationObserver = require("./mutationObserver.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_onlineManager = require("./onlineManager.cjs");
var import_queriesObserver = require("./queriesObserver.cjs");
var import_queryCache = require("./queryCache.cjs");
var import_queryClient = require("./queryClient.cjs");
var import_queryObserver = require("./queryObserver.cjs");
var import_retryer = require("./retryer.cjs");
var import_timeoutManager = require("./timeoutManager.cjs");
var import_utils = require("./utils.cjs");
var import_streamedQuery = require("./streamedQuery.cjs");
var import_mutation = require("./mutation.cjs");
var import_query = require("./query.cjs");
__reExport(index_exports, require("./types.cjs"), module.exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
CancelledError,
InfiniteQueryObserver,
Mutation,
MutationCache,
MutationObserver,
QueriesObserver,
Query,
QueryCache,
QueryClient,
QueryObserver,
defaultScheduler,
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
environmentManager,
experimental_streamedQuery,
focusManager,
hashKey,
hydrate,
isCancelledError,
isServer,
keepPreviousData,
matchMutation,
matchQuery,
noop,
notifyManager,
onlineManager,
partialMatchKey,
replaceEqualDeep,
shouldThrowError,
skipToken,
timeoutManager,
...require("./types.cjs")
});
//# sourceMappingURL=index.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport { focusManager } from './focusManager'\nexport { environmentManager } from './environmentManager'\nexport {\n defaultShouldDehydrateMutation,\n defaultShouldDehydrateQuery,\n dehydrate,\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 { 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 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 { QueriesObserverOptions } from './queriesObserver'\nexport { Query } from './query'\nexport type { QueryState } from './query'\nexport * from './types'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,0BAA6B;AAC7B,gCAAmC;AACnC,uBAKO;AACP,mCAAsC;AACtC,2BAA8B;AAE9B,8BAAiC;AACjC,2BAAgD;AAChD,2BAA8B;AAC9B,6BAAgC;AAChC,wBAA2B;AAE3B,yBAA4B;AAC5B,2BAA8B;AAC9B,qBAAiD;AACjD,4BAKO;AACP,mBAWO;AAGP,2BAA4D;AAQ5D,sBAAyB;AAGzB,mBAAsB;AAEtB,0BAAc,wBAvDd;","names":[]}
+141
View File
@@ -0,0 +1,141 @@
export { focusManager_alias_1 as focusManager } from './_tsup-dts-rollup.cjs';
export { environmentManager_alias_1 as environmentManager } from './_tsup-dts-rollup.cjs';
export { defaultShouldDehydrateMutation_alias_1 as defaultShouldDehydrateMutation } from './_tsup-dts-rollup.cjs';
export { defaultShouldDehydrateQuery_alias_1 as defaultShouldDehydrateQuery } from './_tsup-dts-rollup.cjs';
export { dehydrate_alias_1 as dehydrate } from './_tsup-dts-rollup.cjs';
export { hydrate_alias_1 as hydrate } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserver } from './_tsup-dts-rollup.cjs';
export { MutationCache } from './_tsup-dts-rollup.cjs';
export { MutationCacheNotifyEvent } from './_tsup-dts-rollup.cjs';
export { MutationObserver } from './_tsup-dts-rollup.cjs';
export { defaultScheduler } from './_tsup-dts-rollup.cjs';
export { notifyManager } from './_tsup-dts-rollup.cjs';
export { onlineManager } from './_tsup-dts-rollup.cjs';
export { QueriesObserver } from './_tsup-dts-rollup.cjs';
export { QueryCache } from './_tsup-dts-rollup.cjs';
export { QueryCacheNotifyEvent } from './_tsup-dts-rollup.cjs';
export { QueryClient } from './_tsup-dts-rollup.cjs';
export { QueryObserver } from './_tsup-dts-rollup.cjs';
export { CancelledError } from './_tsup-dts-rollup.cjs';
export { isCancelledError } from './_tsup-dts-rollup.cjs';
export { timeoutManager } from './_tsup-dts-rollup.cjs';
export { ManagedTimerId } from './_tsup-dts-rollup.cjs';
export { TimeoutCallback } from './_tsup-dts-rollup.cjs';
export { TimeoutProvider } from './_tsup-dts-rollup.cjs';
export { hashKey } from './_tsup-dts-rollup.cjs';
export { isServer } from './_tsup-dts-rollup.cjs';
export { keepPreviousData } from './_tsup-dts-rollup.cjs';
export { matchMutation } from './_tsup-dts-rollup.cjs';
export { matchQuery } from './_tsup-dts-rollup.cjs';
export { noop } from './_tsup-dts-rollup.cjs';
export { partialMatchKey } from './_tsup-dts-rollup.cjs';
export { replaceEqualDeep } from './_tsup-dts-rollup.cjs';
export { shouldThrowError } from './_tsup-dts-rollup.cjs';
export { skipToken } from './_tsup-dts-rollup.cjs';
export { MutationFilters } from './_tsup-dts-rollup.cjs';
export { QueryFilters } from './_tsup-dts-rollup.cjs';
export { SkipToken } from './_tsup-dts-rollup.cjs';
export { Updater } from './_tsup-dts-rollup.cjs';
export { experimental_streamedQuery } from './_tsup-dts-rollup.cjs';
export { DehydratedState_alias_1 as DehydratedState } from './_tsup-dts-rollup.cjs';
export { DehydrateOptions_alias_1 as DehydrateOptions } from './_tsup-dts-rollup.cjs';
export { HydrateOptions_alias_1 as HydrateOptions } from './_tsup-dts-rollup.cjs';
export { Mutation } from './_tsup-dts-rollup.cjs';
export { MutationState } from './_tsup-dts-rollup.cjs';
export { QueriesObserverOptions } from './_tsup-dts-rollup.cjs';
export { Query } from './_tsup-dts-rollup.cjs';
export { QueryState } from './_tsup-dts-rollup.cjs';
export { NonUndefinedGuard } from './_tsup-dts-rollup.cjs';
export { DistributiveOmit } from './_tsup-dts-rollup.cjs';
export { OmitKeyof } from './_tsup-dts-rollup.cjs';
export { Override } from './_tsup-dts-rollup.cjs';
export { Register } from './_tsup-dts-rollup.cjs';
export { DefaultError } from './_tsup-dts-rollup.cjs';
export { QueryKey } from './_tsup-dts-rollup.cjs';
export { dataTagSymbol } from './_tsup-dts-rollup.cjs';
export { dataTagErrorSymbol } from './_tsup-dts-rollup.cjs';
export { unsetMarker } from './_tsup-dts-rollup.cjs';
export { UnsetMarker } from './_tsup-dts-rollup.cjs';
export { AnyDataTag } from './_tsup-dts-rollup.cjs';
export { DataTag } from './_tsup-dts-rollup.cjs';
export { InferDataFromTag } from './_tsup-dts-rollup.cjs';
export { InferErrorFromTag } from './_tsup-dts-rollup.cjs';
export { QueryFunction } from './_tsup-dts-rollup.cjs';
export { StaleTime } from './_tsup-dts-rollup.cjs';
export { StaleTimeFunction } from './_tsup-dts-rollup.cjs';
export { QueryBooleanOption } from './_tsup-dts-rollup.cjs';
export { QueryPersister } from './_tsup-dts-rollup.cjs';
export { QueryFunctionContext } from './_tsup-dts-rollup.cjs';
export { InitialDataFunction } from './_tsup-dts-rollup.cjs';
export { PlaceholderDataFunction } from './_tsup-dts-rollup.cjs';
export { QueriesPlaceholderDataFunction } from './_tsup-dts-rollup.cjs';
export { QueryKeyHashFunction } from './_tsup-dts-rollup.cjs';
export { GetPreviousPageParamFunction } from './_tsup-dts-rollup.cjs';
export { GetNextPageParamFunction } from './_tsup-dts-rollup.cjs';
export { InfiniteData } from './_tsup-dts-rollup.cjs';
export { QueryMeta } from './_tsup-dts-rollup.cjs';
export { NetworkMode } from './_tsup-dts-rollup.cjs';
export { NotifyOnChangeProps } from './_tsup-dts-rollup.cjs';
export { QueryOptions } from './_tsup-dts-rollup.cjs';
export { InitialPageParam } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryPageParamsOptions } from './_tsup-dts-rollup.cjs';
export { ThrowOnError } from './_tsup-dts-rollup.cjs';
export { QueryObserverOptions } from './_tsup-dts-rollup.cjs';
export { WithRequired } from './_tsup-dts-rollup.cjs';
export { DefaultedQueryObserverOptions } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverOptions } from './_tsup-dts-rollup.cjs';
export { DefaultedInfiniteQueryObserverOptions } from './_tsup-dts-rollup.cjs';
export { FetchQueryOptions } from './_tsup-dts-rollup.cjs';
export { EnsureQueryDataOptions } from './_tsup-dts-rollup.cjs';
export { EnsureInfiniteQueryDataOptions } from './_tsup-dts-rollup.cjs';
export { FetchInfiniteQueryOptions } from './_tsup-dts-rollup.cjs';
export { ResultOptions } from './_tsup-dts-rollup.cjs';
export { RefetchOptions } from './_tsup-dts-rollup.cjs';
export { InvalidateQueryFilters } from './_tsup-dts-rollup.cjs';
export { RefetchQueryFilters } from './_tsup-dts-rollup.cjs';
export { InvalidateOptions } from './_tsup-dts-rollup.cjs';
export { ResetOptions } from './_tsup-dts-rollup.cjs';
export { FetchNextPageOptions } from './_tsup-dts-rollup.cjs';
export { FetchPreviousPageOptions } from './_tsup-dts-rollup.cjs';
export { QueryStatus } from './_tsup-dts-rollup.cjs';
export { FetchStatus } from './_tsup-dts-rollup.cjs';
export { QueryObserverBaseResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverPendingResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverLoadingResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverLoadingErrorResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverRefetchErrorResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverSuccessResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverPlaceholderResult } from './_tsup-dts-rollup.cjs';
export { DefinedQueryObserverResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverBaseResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverPendingResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverLoadingResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverLoadingErrorResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverRefetchErrorResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverSuccessResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverPlaceholderResult } from './_tsup-dts-rollup.cjs';
export { DefinedInfiniteQueryObserverResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverResult } from './_tsup-dts-rollup.cjs';
export { MutationKey } from './_tsup-dts-rollup.cjs';
export { MutationStatus } from './_tsup-dts-rollup.cjs';
export { MutationScope } from './_tsup-dts-rollup.cjs';
export { MutationMeta } from './_tsup-dts-rollup.cjs';
export { MutationFunctionContext } from './_tsup-dts-rollup.cjs';
export { MutationFunction } from './_tsup-dts-rollup.cjs';
export { MutationOptions } from './_tsup-dts-rollup.cjs';
export { MutationObserverOptions } from './_tsup-dts-rollup.cjs';
export { MutateOptions } from './_tsup-dts-rollup.cjs';
export { MutateFunction } from './_tsup-dts-rollup.cjs';
export { MutationObserverBaseResult } from './_tsup-dts-rollup.cjs';
export { MutationObserverIdleResult } from './_tsup-dts-rollup.cjs';
export { MutationObserverLoadingResult } from './_tsup-dts-rollup.cjs';
export { MutationObserverErrorResult } from './_tsup-dts-rollup.cjs';
export { MutationObserverSuccessResult } from './_tsup-dts-rollup.cjs';
export { MutationObserverResult } from './_tsup-dts-rollup.cjs';
export { QueryClientConfig } from './_tsup-dts-rollup.cjs';
export { DefaultOptions } from './_tsup-dts-rollup.cjs';
export { CancelOptions } from './_tsup-dts-rollup.cjs';
export { SetDataOptions } from './_tsup-dts-rollup.cjs';
export { NotifyEventType } from './_tsup-dts-rollup.cjs';
export { NotifyEvent } from './_tsup-dts-rollup.cjs';
+141
View File
@@ -0,0 +1,141 @@
export { focusManager_alias_1 as focusManager } from './_tsup-dts-rollup.js';
export { environmentManager_alias_1 as environmentManager } from './_tsup-dts-rollup.js';
export { defaultShouldDehydrateMutation_alias_1 as defaultShouldDehydrateMutation } from './_tsup-dts-rollup.js';
export { defaultShouldDehydrateQuery_alias_1 as defaultShouldDehydrateQuery } from './_tsup-dts-rollup.js';
export { dehydrate_alias_1 as dehydrate } from './_tsup-dts-rollup.js';
export { hydrate_alias_1 as hydrate } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserver } from './_tsup-dts-rollup.js';
export { MutationCache } from './_tsup-dts-rollup.js';
export { MutationCacheNotifyEvent } from './_tsup-dts-rollup.js';
export { MutationObserver } from './_tsup-dts-rollup.js';
export { defaultScheduler } from './_tsup-dts-rollup.js';
export { notifyManager } from './_tsup-dts-rollup.js';
export { onlineManager } from './_tsup-dts-rollup.js';
export { QueriesObserver } from './_tsup-dts-rollup.js';
export { QueryCache } from './_tsup-dts-rollup.js';
export { QueryCacheNotifyEvent } from './_tsup-dts-rollup.js';
export { QueryClient } from './_tsup-dts-rollup.js';
export { QueryObserver } from './_tsup-dts-rollup.js';
export { CancelledError } from './_tsup-dts-rollup.js';
export { isCancelledError } from './_tsup-dts-rollup.js';
export { timeoutManager } from './_tsup-dts-rollup.js';
export { ManagedTimerId } from './_tsup-dts-rollup.js';
export { TimeoutCallback } from './_tsup-dts-rollup.js';
export { TimeoutProvider } from './_tsup-dts-rollup.js';
export { hashKey } from './_tsup-dts-rollup.js';
export { isServer } from './_tsup-dts-rollup.js';
export { keepPreviousData } from './_tsup-dts-rollup.js';
export { matchMutation } from './_tsup-dts-rollup.js';
export { matchQuery } from './_tsup-dts-rollup.js';
export { noop } from './_tsup-dts-rollup.js';
export { partialMatchKey } from './_tsup-dts-rollup.js';
export { replaceEqualDeep } from './_tsup-dts-rollup.js';
export { shouldThrowError } from './_tsup-dts-rollup.js';
export { skipToken } from './_tsup-dts-rollup.js';
export { MutationFilters } from './_tsup-dts-rollup.js';
export { QueryFilters } from './_tsup-dts-rollup.js';
export { SkipToken } from './_tsup-dts-rollup.js';
export { Updater } from './_tsup-dts-rollup.js';
export { experimental_streamedQuery } from './_tsup-dts-rollup.js';
export { DehydratedState_alias_1 as DehydratedState } from './_tsup-dts-rollup.js';
export { DehydrateOptions_alias_1 as DehydrateOptions } from './_tsup-dts-rollup.js';
export { HydrateOptions_alias_1 as HydrateOptions } from './_tsup-dts-rollup.js';
export { Mutation } from './_tsup-dts-rollup.js';
export { MutationState } from './_tsup-dts-rollup.js';
export { QueriesObserverOptions } from './_tsup-dts-rollup.js';
export { Query } from './_tsup-dts-rollup.js';
export { QueryState } from './_tsup-dts-rollup.js';
export { NonUndefinedGuard } from './_tsup-dts-rollup.js';
export { DistributiveOmit } from './_tsup-dts-rollup.js';
export { OmitKeyof } from './_tsup-dts-rollup.js';
export { Override } from './_tsup-dts-rollup.js';
export { Register } from './_tsup-dts-rollup.js';
export { DefaultError } from './_tsup-dts-rollup.js';
export { QueryKey } from './_tsup-dts-rollup.js';
export { dataTagSymbol } from './_tsup-dts-rollup.js';
export { dataTagErrorSymbol } from './_tsup-dts-rollup.js';
export { unsetMarker } from './_tsup-dts-rollup.js';
export { UnsetMarker } from './_tsup-dts-rollup.js';
export { AnyDataTag } from './_tsup-dts-rollup.js';
export { DataTag } from './_tsup-dts-rollup.js';
export { InferDataFromTag } from './_tsup-dts-rollup.js';
export { InferErrorFromTag } from './_tsup-dts-rollup.js';
export { QueryFunction } from './_tsup-dts-rollup.js';
export { StaleTime } from './_tsup-dts-rollup.js';
export { StaleTimeFunction } from './_tsup-dts-rollup.js';
export { QueryBooleanOption } from './_tsup-dts-rollup.js';
export { QueryPersister } from './_tsup-dts-rollup.js';
export { QueryFunctionContext } from './_tsup-dts-rollup.js';
export { InitialDataFunction } from './_tsup-dts-rollup.js';
export { PlaceholderDataFunction } from './_tsup-dts-rollup.js';
export { QueriesPlaceholderDataFunction } from './_tsup-dts-rollup.js';
export { QueryKeyHashFunction } from './_tsup-dts-rollup.js';
export { GetPreviousPageParamFunction } from './_tsup-dts-rollup.js';
export { GetNextPageParamFunction } from './_tsup-dts-rollup.js';
export { InfiniteData } from './_tsup-dts-rollup.js';
export { QueryMeta } from './_tsup-dts-rollup.js';
export { NetworkMode } from './_tsup-dts-rollup.js';
export { NotifyOnChangeProps } from './_tsup-dts-rollup.js';
export { QueryOptions } from './_tsup-dts-rollup.js';
export { InitialPageParam } from './_tsup-dts-rollup.js';
export { InfiniteQueryPageParamsOptions } from './_tsup-dts-rollup.js';
export { ThrowOnError } from './_tsup-dts-rollup.js';
export { QueryObserverOptions } from './_tsup-dts-rollup.js';
export { WithRequired } from './_tsup-dts-rollup.js';
export { DefaultedQueryObserverOptions } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverOptions } from './_tsup-dts-rollup.js';
export { DefaultedInfiniteQueryObserverOptions } from './_tsup-dts-rollup.js';
export { FetchQueryOptions } from './_tsup-dts-rollup.js';
export { EnsureQueryDataOptions } from './_tsup-dts-rollup.js';
export { EnsureInfiniteQueryDataOptions } from './_tsup-dts-rollup.js';
export { FetchInfiniteQueryOptions } from './_tsup-dts-rollup.js';
export { ResultOptions } from './_tsup-dts-rollup.js';
export { RefetchOptions } from './_tsup-dts-rollup.js';
export { InvalidateQueryFilters } from './_tsup-dts-rollup.js';
export { RefetchQueryFilters } from './_tsup-dts-rollup.js';
export { InvalidateOptions } from './_tsup-dts-rollup.js';
export { ResetOptions } from './_tsup-dts-rollup.js';
export { FetchNextPageOptions } from './_tsup-dts-rollup.js';
export { FetchPreviousPageOptions } from './_tsup-dts-rollup.js';
export { QueryStatus } from './_tsup-dts-rollup.js';
export { FetchStatus } from './_tsup-dts-rollup.js';
export { QueryObserverBaseResult } from './_tsup-dts-rollup.js';
export { QueryObserverPendingResult } from './_tsup-dts-rollup.js';
export { QueryObserverLoadingResult } from './_tsup-dts-rollup.js';
export { QueryObserverLoadingErrorResult } from './_tsup-dts-rollup.js';
export { QueryObserverRefetchErrorResult } from './_tsup-dts-rollup.js';
export { QueryObserverSuccessResult } from './_tsup-dts-rollup.js';
export { QueryObserverPlaceholderResult } from './_tsup-dts-rollup.js';
export { DefinedQueryObserverResult } from './_tsup-dts-rollup.js';
export { QueryObserverResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverBaseResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverPendingResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverLoadingResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverLoadingErrorResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverRefetchErrorResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverSuccessResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverPlaceholderResult } from './_tsup-dts-rollup.js';
export { DefinedInfiniteQueryObserverResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverResult } from './_tsup-dts-rollup.js';
export { MutationKey } from './_tsup-dts-rollup.js';
export { MutationStatus } from './_tsup-dts-rollup.js';
export { MutationScope } from './_tsup-dts-rollup.js';
export { MutationMeta } from './_tsup-dts-rollup.js';
export { MutationFunctionContext } from './_tsup-dts-rollup.js';
export { MutationFunction } from './_tsup-dts-rollup.js';
export { MutationOptions } from './_tsup-dts-rollup.js';
export { MutationObserverOptions } from './_tsup-dts-rollup.js';
export { MutateOptions } from './_tsup-dts-rollup.js';
export { MutateFunction } from './_tsup-dts-rollup.js';
export { MutationObserverBaseResult } from './_tsup-dts-rollup.js';
export { MutationObserverIdleResult } from './_tsup-dts-rollup.js';
export { MutationObserverLoadingResult } from './_tsup-dts-rollup.js';
export { MutationObserverErrorResult } from './_tsup-dts-rollup.js';
export { MutationObserverSuccessResult } from './_tsup-dts-rollup.js';
export { MutationObserverResult } from './_tsup-dts-rollup.js';
export { QueryClientConfig } from './_tsup-dts-rollup.js';
export { DefaultOptions } from './_tsup-dts-rollup.js';
export { CancelOptions } from './_tsup-dts-rollup.js';
export { SetDataOptions } from './_tsup-dts-rollup.js';
export { NotifyEventType } from './_tsup-dts-rollup.js';
export { NotifyEvent } from './_tsup-dts-rollup.js';
+73
View File
@@ -0,0 +1,73 @@
// src/index.ts
import { focusManager } from "./focusManager.js";
import { environmentManager } from "./environmentManager.js";
import {
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
hydrate
} from "./hydration.js";
import { InfiniteQueryObserver } from "./infiniteQueryObserver.js";
import { MutationCache } from "./mutationCache.js";
import { MutationObserver } from "./mutationObserver.js";
import { defaultScheduler, notifyManager } from "./notifyManager.js";
import { onlineManager } from "./onlineManager.js";
import { QueriesObserver } from "./queriesObserver.js";
import { QueryCache } from "./queryCache.js";
import { QueryClient } from "./queryClient.js";
import { QueryObserver } from "./queryObserver.js";
import { CancelledError, isCancelledError } from "./retryer.js";
import {
timeoutManager
} from "./timeoutManager.js";
import {
hashKey,
isServer,
keepPreviousData,
matchMutation,
matchQuery,
noop,
partialMatchKey,
replaceEqualDeep,
shouldThrowError,
skipToken
} from "./utils.js";
import { streamedQuery } from "./streamedQuery.js";
import { Mutation } from "./mutation.js";
import { Query } from "./query.js";
export * from "./types.js";
export {
CancelledError,
InfiniteQueryObserver,
Mutation,
MutationCache,
MutationObserver,
QueriesObserver,
Query,
QueryCache,
QueryClient,
QueryObserver,
defaultScheduler,
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
environmentManager,
streamedQuery as experimental_streamedQuery,
focusManager,
hashKey,
hydrate,
isCancelledError,
isServer,
keepPreviousData,
matchMutation,
matchQuery,
noop,
notifyManager,
onlineManager,
partialMatchKey,
replaceEqualDeep,
shouldThrowError,
skipToken,
timeoutManager
};
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport { focusManager } from './focusManager'\nexport { environmentManager } from './environmentManager'\nexport {\n defaultShouldDehydrateMutation,\n defaultShouldDehydrateQuery,\n dehydrate,\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 { 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 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 { QueriesObserverOptions } from './queriesObserver'\nexport { Query } from './query'\nexport type { QueryState } from './query'\nexport * from './types'\n"],"mappings":";AAEA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AACtC,SAAS,qBAAqB;AAE9B,SAAS,wBAAwB;AACjC,SAAS,kBAAkB,qBAAqB;AAChD,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,kBAAkB;AAE3B,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB,wBAAwB;AACjD;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAA0B,qBAAkC;AAQ5D,SAAS,gBAAgB;AAGzB,SAAS,aAAa;AAEtB,cAAc;","names":[]}
@@ -0,0 +1,142 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/infiniteQueryBehavior.ts
var infiniteQueryBehavior_exports = {};
__export(infiniteQueryBehavior_exports, {
hasNextPage: () => hasNextPage,
hasPreviousPage: () => hasPreviousPage,
infiniteQueryBehavior: () => infiniteQueryBehavior
});
module.exports = __toCommonJS(infiniteQueryBehavior_exports);
var import_utils = require("./utils.cjs");
function infiniteQueryBehavior(pages) {
return {
onFetch: (context, query) => {
const options = context.options;
const direction = context.fetchOptions?.meta?.fetchMore?.direction;
const oldPages = context.state.data?.pages || [];
const oldPageParams = context.state.data?.pageParams || [];
let result = { pages: [], pageParams: [] };
let currentPage = 0;
const fetchFn = async () => {
let cancelled = false;
const addSignalProperty = (object) => {
(0, import_utils.addConsumeAwareSignal)(
object,
() => context.signal,
() => cancelled = true
);
};
const queryFn = (0, import_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 queryFnContext2 = {
client: context.client,
queryKey: context.queryKey,
pageParam: param,
direction: previous ? "backward" : "forward",
meta: context.options.meta
};
addSignalProperty(queryFnContext2);
return queryFnContext2;
};
const queryFnContext = createQueryFnContext();
const page = await queryFn(queryFnContext);
const { maxPages } = context.options;
const addTo = previous ? import_utils.addToStart : import_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
};
const param = pageParamFn(options, oldData);
result = await fetchPage(oldData, param, 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 = () => {
return context.options.persister?.(
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 }) {
return pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0;
}
function hasNextPage(options, data) {
if (!data) return false;
return getNextPageParam(options, data) != null;
}
function hasPreviousPage(options, data) {
if (!data || !options.getPreviousPageParam) return false;
return getPreviousPageParam(options, data) != null;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
hasNextPage,
hasPreviousPage,
infiniteQueryBehavior
});
//# sourceMappingURL=infiniteQueryBehavior.cjs.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
export { infiniteQueryBehavior } from './_tsup-dts-rollup.cjs';
export { hasNextPage } from './_tsup-dts-rollup.cjs';
export { hasPreviousPage } from './_tsup-dts-rollup.cjs';
@@ -0,0 +1,3 @@
export { infiniteQueryBehavior } from './_tsup-dts-rollup.js';
export { hasNextPage } from './_tsup-dts-rollup.js';
export { hasPreviousPage } from './_tsup-dts-rollup.js';
+120
View File
@@ -0,0 +1,120 @@
// src/infiniteQueryBehavior.ts
import {
addConsumeAwareSignal,
addToEnd,
addToStart,
ensureQueryFn
} from "./utils.js";
function infiniteQueryBehavior(pages) {
return {
onFetch: (context, query) => {
const options = context.options;
const direction = context.fetchOptions?.meta?.fetchMore?.direction;
const oldPages = context.state.data?.pages || [];
const oldPageParams = context.state.data?.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 queryFnContext2 = {
client: context.client,
queryKey: context.queryKey,
pageParam: param,
direction: previous ? "backward" : "forward",
meta: context.options.meta
};
addSignalProperty(queryFnContext2);
return queryFnContext2;
};
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
};
const param = pageParamFn(options, oldData);
result = await fetchPage(oldData, param, 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 = () => {
return context.options.persister?.(
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 }) {
return pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0;
}
function hasNextPage(options, data) {
if (!data) return false;
return getNextPageParam(options, data) != null;
}
function hasPreviousPage(options, data) {
if (!data || !options.getPreviousPageParam) return false;
return getPreviousPageParam(options, data) != null;
}
export {
hasNextPage,
hasPreviousPage,
infiniteQueryBehavior
};
//# sourceMappingURL=infiniteQueryBehavior.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,90 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/infiniteQueryObserver.ts
var infiniteQueryObserver_exports = {};
__export(infiniteQueryObserver_exports, {
InfiniteQueryObserver: () => InfiniteQueryObserver
});
module.exports = __toCommonJS(infiniteQueryObserver_exports);
var import_queryObserver = require("./queryObserver.cjs");
var import_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs");
var InfiniteQueryObserver = class extends import_queryObserver.QueryObserver {
constructor(client, options) {
super(client, options);
}
bindMethods() {
super.bindMethods();
this.fetchNextPage = this.fetchNextPage.bind(this);
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
}
setOptions(options) {
options._type = "infinite";
super.setOptions(options);
}
getOptimisticResult(options) {
options._type = "infinite";
return super.getOptimisticResult(options);
}
fetchNextPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "forward" }
}
});
}
fetchPreviousPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "backward" }
}
});
}
createResult(query, options) {
const { state } = query;
const parentResult = super.createResult(query, options);
const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
const fetchDirection = state.fetchMeta?.fetchMore?.direction;
const isFetchNextPageError = isError && fetchDirection === "forward";
const isFetchingNextPage = isFetching && fetchDirection === "forward";
const isFetchPreviousPageError = isError && fetchDirection === "backward";
const isFetchingPreviousPage = isFetching && fetchDirection === "backward";
const result = {
...parentResult,
fetchNextPage: this.fetchNextPage,
fetchPreviousPage: this.fetchPreviousPage,
hasNextPage: (0, import_infiniteQueryBehavior.hasNextPage)(options, state.data),
hasPreviousPage: (0, import_infiniteQueryBehavior.hasPreviousPage)(options, state.data),
isFetchNextPageError,
isFetchingNextPage,
isFetchPreviousPageError,
isFetchingPreviousPage,
isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
};
return result;
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
InfiniteQueryObserver
});
//# sourceMappingURL=infiniteQueryObserver.cjs.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
export { InfiniteQueryObserver_alias_1 as InfiniteQueryObserver } from './_tsup-dts-rollup.cjs';
@@ -0,0 +1 @@
export { InfiniteQueryObserver_alias_1 as InfiniteQueryObserver } from './_tsup-dts-rollup.js';
@@ -0,0 +1,65 @@
// src/infiniteQueryObserver.ts
import { QueryObserver } from "./queryObserver.js";
import { hasNextPage, hasPreviousPage } from "./infiniteQueryBehavior.js";
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);
}
setOptions(options) {
options._type = "infinite";
super.setOptions(options);
}
getOptimisticResult(options) {
options._type = "infinite";
return super.getOptimisticResult(options);
}
fetchNextPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "forward" }
}
});
}
fetchPreviousPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "backward" }
}
});
}
createResult(query, options) {
const { state } = query;
const parentResult = super.createResult(query, options);
const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
const fetchDirection = state.fetchMeta?.fetchMore?.direction;
const isFetchNextPageError = isError && fetchDirection === "forward";
const isFetchingNextPage = isFetching && fetchDirection === "forward";
const isFetchPreviousPageError = isError && fetchDirection === "backward";
const isFetchingPreviousPage = isFetching && fetchDirection === "backward";
const result = {
...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
};
return result;
}
};
export {
InfiniteQueryObserver
};
//# sourceMappingURL=infiniteQueryObserver.js.map
File diff suppressed because one or more lines are too long
+307
View File
@@ -0,0 +1,307 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/mutation.ts
var mutation_exports = {};
__export(mutation_exports, {
Mutation: () => Mutation,
getDefaultState: () => getDefaultState
});
module.exports = __toCommonJS(mutation_exports);
var import_notifyManager = require("./notifyManager.cjs");
var import_removable = require("./removable.cjs");
var import_retryer = require("./retryer.cjs");
var Mutation = class extends import_removable.Removable {
#client;
#observers;
#mutationCache;
#retryer;
constructor(config) {
super();
this.#client = config.client;
this.mutationId = config.mutationId;
this.#mutationCache = config.mutationCache;
this.#observers = [];
this.state = config.state || getDefaultState();
this.setOptions(config.options);
this.scheduleGc();
}
setOptions(options) {
this.options = options;
this.updateGcTime(this.options.gcTime);
}
get meta() {
return this.options.meta;
}
addObserver(observer) {
if (!this.#observers.includes(observer)) {
this.#observers.push(observer);
this.clearGcTimeout();
this.#mutationCache.notify({
type: "observerAdded",
mutation: this,
observer
});
}
}
removeObserver(observer) {
this.#observers = this.#observers.filter((x) => x !== observer);
this.scheduleGc();
this.#mutationCache.notify({
type: "observerRemoved",
mutation: this,
observer
});
}
optionalRemove() {
if (!this.#observers.length) {
if (this.state.status === "pending") {
this.scheduleGc();
} else {
this.#mutationCache.remove(this);
}
}
}
continue() {
return this.#retryer?.continue() ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
this.execute(this.state.variables);
}
async execute(variables) {
const onContinue = () => {
this.#dispatch({ type: "continue" });
};
const mutationFnContext = {
client: this.#client,
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
this.#retryer = (0, import_retryer.createRetryer)({
fn: () => {
if (!this.options.mutationFn) {
return Promise.reject(new Error("No mutationFn found"));
}
return this.options.mutationFn(variables, mutationFnContext);
},
onFail: (failureCount, error) => {
this.#dispatch({ type: "failed", failureCount, error });
},
onPause: () => {
this.#dispatch({ type: "pause" });
},
onContinue,
retry: this.options.retry ?? 0,
retryDelay: this.options.retryDelay,
networkMode: this.options.networkMode,
canRun: () => this.#mutationCache.canRun(this)
});
const restored = this.state.status === "pending";
const isPaused = !this.#retryer.canStart();
try {
if (restored) {
onContinue();
} else {
this.#dispatch({ type: "pending", variables, isPaused });
if (this.#mutationCache.config.onMutate) {
await this.#mutationCache.config.onMutate(
variables,
this,
mutationFnContext
);
}
const context = await this.options.onMutate?.(
variables,
mutationFnContext
);
if (context !== this.state.context) {
this.#dispatch({
type: "pending",
context,
variables,
isPaused
});
}
}
const data = await this.#retryer.start();
await this.#mutationCache.config.onSuccess?.(
data,
variables,
this.state.context,
this,
mutationFnContext
);
await this.options.onSuccess?.(
data,
variables,
this.state.context,
mutationFnContext
);
await this.#mutationCache.config.onSettled?.(
data,
null,
this.state.variables,
this.state.context,
this,
mutationFnContext
);
await this.options.onSettled?.(
data,
null,
variables,
this.state.context,
mutationFnContext
);
this.#dispatch({ type: "success", data });
return data;
} catch (error) {
try {
await this.#mutationCache.config.onError?.(
error,
variables,
this.state.context,
this,
mutationFnContext
);
} catch (e) {
void Promise.reject(e);
}
try {
await this.options.onError?.(
error,
variables,
this.state.context,
mutationFnContext
);
} catch (e) {
void Promise.reject(e);
}
try {
await this.#mutationCache.config.onSettled?.(
void 0,
error,
this.state.variables,
this.state.context,
this,
mutationFnContext
);
} catch (e) {
void Promise.reject(e);
}
try {
await this.options.onSettled?.(
void 0,
error,
variables,
this.state.context,
mutationFnContext
);
} catch (e) {
void Promise.reject(e);
}
this.#dispatch({ type: "error", error });
throw error;
} finally {
this.#mutationCache.runNext(this);
}
}
#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);
import_notifyManager.notifyManager.batch(() => {
this.#observers.forEach((observer) => {
observer.onMutationUpdate(action);
});
this.#mutationCache.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
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Mutation,
getDefaultState
});
//# sourceMappingURL=mutation.cjs.map
File diff suppressed because one or more lines are too long
+4
View File
@@ -0,0 +1,4 @@
export { getDefaultState } from './_tsup-dts-rollup.cjs';
export { MutationState_alias_1 as MutationState } from './_tsup-dts-rollup.cjs';
export { Action } from './_tsup-dts-rollup.cjs';
export { Mutation_alias_1 as Mutation } from './_tsup-dts-rollup.cjs';
+4
View File
@@ -0,0 +1,4 @@
export { getDefaultState } from './_tsup-dts-rollup.js';
export { MutationState_alias_1 as MutationState } from './_tsup-dts-rollup.js';
export { Action } from './_tsup-dts-rollup.js';
export { Mutation_alias_1 as Mutation } from './_tsup-dts-rollup.js';
+281
View File
@@ -0,0 +1,281 @@
// src/mutation.ts
import { notifyManager } from "./notifyManager.js";
import { Removable } from "./removable.js";
import { createRetryer } from "./retryer.js";
var Mutation = class extends Removable {
#client;
#observers;
#mutationCache;
#retryer;
constructor(config) {
super();
this.#client = config.client;
this.mutationId = config.mutationId;
this.#mutationCache = config.mutationCache;
this.#observers = [];
this.state = config.state || getDefaultState();
this.setOptions(config.options);
this.scheduleGc();
}
setOptions(options) {
this.options = options;
this.updateGcTime(this.options.gcTime);
}
get meta() {
return this.options.meta;
}
addObserver(observer) {
if (!this.#observers.includes(observer)) {
this.#observers.push(observer);
this.clearGcTimeout();
this.#mutationCache.notify({
type: "observerAdded",
mutation: this,
observer
});
}
}
removeObserver(observer) {
this.#observers = this.#observers.filter((x) => x !== observer);
this.scheduleGc();
this.#mutationCache.notify({
type: "observerRemoved",
mutation: this,
observer
});
}
optionalRemove() {
if (!this.#observers.length) {
if (this.state.status === "pending") {
this.scheduleGc();
} else {
this.#mutationCache.remove(this);
}
}
}
continue() {
return this.#retryer?.continue() ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
this.execute(this.state.variables);
}
async execute(variables) {
const onContinue = () => {
this.#dispatch({ type: "continue" });
};
const mutationFnContext = {
client: this.#client,
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
this.#retryer = createRetryer({
fn: () => {
if (!this.options.mutationFn) {
return Promise.reject(new Error("No mutationFn found"));
}
return this.options.mutationFn(variables, mutationFnContext);
},
onFail: (failureCount, error) => {
this.#dispatch({ type: "failed", failureCount, error });
},
onPause: () => {
this.#dispatch({ type: "pause" });
},
onContinue,
retry: this.options.retry ?? 0,
retryDelay: this.options.retryDelay,
networkMode: this.options.networkMode,
canRun: () => this.#mutationCache.canRun(this)
});
const restored = this.state.status === "pending";
const isPaused = !this.#retryer.canStart();
try {
if (restored) {
onContinue();
} else {
this.#dispatch({ type: "pending", variables, isPaused });
if (this.#mutationCache.config.onMutate) {
await this.#mutationCache.config.onMutate(
variables,
this,
mutationFnContext
);
}
const context = await this.options.onMutate?.(
variables,
mutationFnContext
);
if (context !== this.state.context) {
this.#dispatch({
type: "pending",
context,
variables,
isPaused
});
}
}
const data = await this.#retryer.start();
await this.#mutationCache.config.onSuccess?.(
data,
variables,
this.state.context,
this,
mutationFnContext
);
await this.options.onSuccess?.(
data,
variables,
this.state.context,
mutationFnContext
);
await this.#mutationCache.config.onSettled?.(
data,
null,
this.state.variables,
this.state.context,
this,
mutationFnContext
);
await this.options.onSettled?.(
data,
null,
variables,
this.state.context,
mutationFnContext
);
this.#dispatch({ type: "success", data });
return data;
} catch (error) {
try {
await this.#mutationCache.config.onError?.(
error,
variables,
this.state.context,
this,
mutationFnContext
);
} catch (e) {
void Promise.reject(e);
}
try {
await this.options.onError?.(
error,
variables,
this.state.context,
mutationFnContext
);
} catch (e) {
void Promise.reject(e);
}
try {
await this.#mutationCache.config.onSettled?.(
void 0,
error,
this.state.variables,
this.state.context,
this,
mutationFnContext
);
} catch (e) {
void Promise.reject(e);
}
try {
await this.options.onSettled?.(
void 0,
error,
variables,
this.state.context,
mutationFnContext
);
} catch (e) {
void Promise.reject(e);
}
this.#dispatch({ type: "error", error });
throw error;
} finally {
this.#mutationCache.runNext(this);
}
}
#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(() => {
this.#observers.forEach((observer) => {
observer.onMutationUpdate(action);
});
this.#mutationCache.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
};
}
export {
Mutation,
getDefaultState
};
//# sourceMappingURL=mutation.js.map
File diff suppressed because one or more lines are too long
+149
View File
@@ -0,0 +1,149 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/mutationCache.ts
var mutationCache_exports = {};
__export(mutationCache_exports, {
MutationCache: () => MutationCache
});
module.exports = __toCommonJS(mutationCache_exports);
var import_notifyManager = require("./notifyManager.cjs");
var import_mutation = require("./mutation.cjs");
var import_utils = require("./utils.cjs");
var import_subscribable = require("./subscribable.cjs");
var MutationCache = class extends import_subscribable.Subscribable {
constructor(config = {}) {
super();
this.config = config;
this.#mutations = /* @__PURE__ */ new Set();
this.#scopes = /* @__PURE__ */ new Map();
this.#mutationId = 0;
}
#mutations;
#scopes;
#mutationId;
build(client, options, state) {
const mutation = new import_mutation.Mutation({
client,
mutationCache: this,
mutationId: ++this.#mutationId,
options: client.defaultMutationOptions(options),
state
});
this.add(mutation);
return mutation;
}
add(mutation) {
this.#mutations.add(mutation);
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = this.#scopes.get(scope);
if (scopedMutations) {
scopedMutations.push(mutation);
} else {
this.#scopes.set(scope, [mutation]);
}
}
this.notify({ type: "added", mutation });
}
remove(mutation) {
if (this.#mutations.delete(mutation)) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = this.#scopes.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) {
this.#scopes.delete(scope);
}
}
}
}
this.notify({ type: "removed", mutation });
}
canRun(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const mutationsWithSameScope = this.#scopes.get(scope);
const firstPendingMutation = mutationsWithSameScope?.find(
(m) => m.state.status === "pending"
);
return !firstPendingMutation || firstPendingMutation === mutation;
} else {
return true;
}
}
runNext(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const foundMutation = this.#scopes.get(scope)?.find((m) => m !== mutation && m.state.isPaused);
return foundMutation?.continue() ?? Promise.resolve();
} else {
return Promise.resolve();
}
}
clear() {
import_notifyManager.notifyManager.batch(() => {
this.#mutations.forEach((mutation) => {
this.notify({ type: "removed", mutation });
});
this.#mutations.clear();
this.#scopes.clear();
});
}
getAll() {
return Array.from(this.#mutations);
}
find(filters) {
const defaultedFilters = { exact: true, ...filters };
return this.getAll().find(
(mutation) => (0, import_utils.matchMutation)(defaultedFilters, mutation)
);
}
findAll(filters = {}) {
return this.getAll().filter((mutation) => (0, import_utils.matchMutation)(filters, mutation));
}
notify(event) {
import_notifyManager.notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(event);
});
});
}
resumePausedMutations() {
const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
return import_notifyManager.notifyManager.batch(
() => Promise.all(
pausedMutations.map((mutation) => mutation.continue().catch(import_utils.noop))
)
);
}
};
function scopeFor(mutation) {
return mutation.options.scope?.id;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MutationCache
});
//# sourceMappingURL=mutationCache.cjs.map
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
export { MutationCacheNotifyEvent_alias_1 as MutationCacheNotifyEvent } from './_tsup-dts-rollup.cjs';
export { MutationCache_alias_1 as MutationCache } from './_tsup-dts-rollup.cjs';
+2
View File
@@ -0,0 +1,2 @@
export { MutationCacheNotifyEvent_alias_1 as MutationCacheNotifyEvent } from './_tsup-dts-rollup.js';
export { MutationCache_alias_1 as MutationCache } from './_tsup-dts-rollup.js';
+124
View File
@@ -0,0 +1,124 @@
// src/mutationCache.ts
import { notifyManager } from "./notifyManager.js";
import { Mutation } from "./mutation.js";
import { matchMutation, noop } from "./utils.js";
import { Subscribable } from "./subscribable.js";
var MutationCache = class extends Subscribable {
constructor(config = {}) {
super();
this.config = config;
this.#mutations = /* @__PURE__ */ new Set();
this.#scopes = /* @__PURE__ */ new Map();
this.#mutationId = 0;
}
#mutations;
#scopes;
#mutationId;
build(client, options, state) {
const mutation = new Mutation({
client,
mutationCache: this,
mutationId: ++this.#mutationId,
options: client.defaultMutationOptions(options),
state
});
this.add(mutation);
return mutation;
}
add(mutation) {
this.#mutations.add(mutation);
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = this.#scopes.get(scope);
if (scopedMutations) {
scopedMutations.push(mutation);
} else {
this.#scopes.set(scope, [mutation]);
}
}
this.notify({ type: "added", mutation });
}
remove(mutation) {
if (this.#mutations.delete(mutation)) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = this.#scopes.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) {
this.#scopes.delete(scope);
}
}
}
}
this.notify({ type: "removed", mutation });
}
canRun(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const mutationsWithSameScope = this.#scopes.get(scope);
const firstPendingMutation = mutationsWithSameScope?.find(
(m) => m.state.status === "pending"
);
return !firstPendingMutation || firstPendingMutation === mutation;
} else {
return true;
}
}
runNext(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const foundMutation = this.#scopes.get(scope)?.find((m) => m !== mutation && m.state.isPaused);
return foundMutation?.continue() ?? Promise.resolve();
} else {
return Promise.resolve();
}
}
clear() {
notifyManager.batch(() => {
this.#mutations.forEach((mutation) => {
this.notify({ type: "removed", mutation });
});
this.#mutations.clear();
this.#scopes.clear();
});
}
getAll() {
return Array.from(this.#mutations);
}
find(filters) {
const defaultedFilters = { exact: true, ...filters };
return this.getAll().find(
(mutation) => matchMutation(defaultedFilters, mutation)
);
}
findAll(filters = {}) {
return this.getAll().filter((mutation) => matchMutation(filters, mutation));
}
notify(event) {
notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(event);
});
});
}
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) {
return mutation.options.scope?.id;
}
export {
MutationCache
};
//# sourceMappingURL=mutationCache.js.map
File diff suppressed because one or more lines are too long
+165
View File
@@ -0,0 +1,165 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/mutationObserver.ts
var mutationObserver_exports = {};
__export(mutationObserver_exports, {
MutationObserver: () => MutationObserver
});
module.exports = __toCommonJS(mutationObserver_exports);
var import_mutation = require("./mutation.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_subscribable = require("./subscribable.cjs");
var import_utils = require("./utils.cjs");
var MutationObserver = class extends import_subscribable.Subscribable {
#client;
#currentResult = void 0;
#currentMutation;
#mutateOptions;
constructor(client, options) {
super();
this.#client = client;
this.setOptions(options);
this.bindMethods();
this.#updateResult();
}
bindMethods() {
this.mutate = this.mutate.bind(this);
this.reset = this.reset.bind(this);
}
setOptions(options) {
const prevOptions = this.options;
this.options = this.#client.defaultMutationOptions(options);
if (!(0, import_utils.shallowEqualObjects)(this.options, prevOptions)) {
this.#client.getMutationCache().notify({
type: "observerOptionsUpdated",
mutation: this.#currentMutation,
observer: this
});
}
if (prevOptions?.mutationKey && this.options.mutationKey && (0, import_utils.hashKey)(prevOptions.mutationKey) !== (0, import_utils.hashKey)(this.options.mutationKey)) {
this.reset();
} else if (this.#currentMutation?.state.status === "pending") {
this.#currentMutation.setOptions(this.options);
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
this.#currentMutation?.removeObserver(this);
}
}
onMutationUpdate(action) {
this.#updateResult();
this.#notify(action);
}
getCurrentResult() {
return this.#currentResult;
}
reset() {
this.#currentMutation?.removeObserver(this);
this.#currentMutation = void 0;
this.#updateResult();
this.#notify();
}
mutate(variables, options) {
this.#mutateOptions = options;
this.#currentMutation?.removeObserver(this);
this.#currentMutation = this.#client.getMutationCache().build(this.#client, this.options);
this.#currentMutation.addObserver(this);
return this.#currentMutation.execute(variables);
}
#updateResult() {
const state = this.#currentMutation?.state ?? (0, import_mutation.getDefaultState)();
this.#currentResult = {
...state,
isPending: state.status === "pending",
isSuccess: state.status === "success",
isError: state.status === "error",
isIdle: state.status === "idle",
mutate: this.mutate,
reset: this.reset
};
}
#notify(action) {
import_notifyManager.notifyManager.batch(() => {
if (this.#mutateOptions && this.hasListeners()) {
const variables = this.#currentResult.variables;
const onMutateResult = this.#currentResult.context;
const context = {
client: this.#client,
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
if (action?.type === "success") {
try {
this.#mutateOptions.onSuccess?.(
action.data,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
try {
this.#mutateOptions.onSettled?.(
action.data,
null,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
} else if (action?.type === "error") {
try {
this.#mutateOptions.onError?.(
action.error,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
try {
this.#mutateOptions.onSettled?.(
void 0,
action.error,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
}
}
this.listeners.forEach((listener) => {
listener(this.#currentResult);
});
});
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MutationObserver
});
//# sourceMappingURL=mutationObserver.cjs.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
export { MutationObserver_alias_1 as MutationObserver } from './_tsup-dts-rollup.cjs';
+1
View File
@@ -0,0 +1 @@
export { MutationObserver_alias_1 as MutationObserver } from './_tsup-dts-rollup.js';
+140
View File
@@ -0,0 +1,140 @@
// src/mutationObserver.ts
import { getDefaultState } from "./mutation.js";
import { notifyManager } from "./notifyManager.js";
import { Subscribable } from "./subscribable.js";
import { hashKey, shallowEqualObjects } from "./utils.js";
var MutationObserver = class extends Subscribable {
#client;
#currentResult = void 0;
#currentMutation;
#mutateOptions;
constructor(client, options) {
super();
this.#client = client;
this.setOptions(options);
this.bindMethods();
this.#updateResult();
}
bindMethods() {
this.mutate = this.mutate.bind(this);
this.reset = this.reset.bind(this);
}
setOptions(options) {
const prevOptions = this.options;
this.options = this.#client.defaultMutationOptions(options);
if (!shallowEqualObjects(this.options, prevOptions)) {
this.#client.getMutationCache().notify({
type: "observerOptionsUpdated",
mutation: this.#currentMutation,
observer: this
});
}
if (prevOptions?.mutationKey && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
this.reset();
} else if (this.#currentMutation?.state.status === "pending") {
this.#currentMutation.setOptions(this.options);
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
this.#currentMutation?.removeObserver(this);
}
}
onMutationUpdate(action) {
this.#updateResult();
this.#notify(action);
}
getCurrentResult() {
return this.#currentResult;
}
reset() {
this.#currentMutation?.removeObserver(this);
this.#currentMutation = void 0;
this.#updateResult();
this.#notify();
}
mutate(variables, options) {
this.#mutateOptions = options;
this.#currentMutation?.removeObserver(this);
this.#currentMutation = this.#client.getMutationCache().build(this.#client, this.options);
this.#currentMutation.addObserver(this);
return this.#currentMutation.execute(variables);
}
#updateResult() {
const state = this.#currentMutation?.state ?? getDefaultState();
this.#currentResult = {
...state,
isPending: state.status === "pending",
isSuccess: state.status === "success",
isError: state.status === "error",
isIdle: state.status === "idle",
mutate: this.mutate,
reset: this.reset
};
}
#notify(action) {
notifyManager.batch(() => {
if (this.#mutateOptions && this.hasListeners()) {
const variables = this.#currentResult.variables;
const onMutateResult = this.#currentResult.context;
const context = {
client: this.#client,
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
if (action?.type === "success") {
try {
this.#mutateOptions.onSuccess?.(
action.data,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
try {
this.#mutateOptions.onSettled?.(
action.data,
null,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
} else if (action?.type === "error") {
try {
this.#mutateOptions.onError?.(
action.error,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
try {
this.#mutateOptions.onSettled?.(
void 0,
action.error,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
}
}
this.listeners.forEach((listener) => {
listener(this.#currentResult);
});
});
}
};
export {
MutationObserver
};
//# sourceMappingURL=mutationObserver.js.map
File diff suppressed because one or more lines are too long
+113
View File
@@ -0,0 +1,113 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/notifyManager.ts
var notifyManager_exports = {};
__export(notifyManager_exports, {
createNotifyManager: () => createNotifyManager,
defaultScheduler: () => defaultScheduler,
notifyManager: () => notifyManager
});
module.exports = __toCommonJS(notifyManager_exports);
var import_timeoutManager = require("./timeoutManager.cjs");
var defaultScheduler = import_timeoutManager.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 {
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);
});
};
},
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.
* By default React Query will use the batch function provided by ReactDOM or React Native.
*/
setBatchNotifyFunction: (fn) => {
batchNotifyFn = fn;
},
setScheduler: (fn) => {
scheduleFn = fn;
}
};
}
var notifyManager = createNotifyManager();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createNotifyManager,
defaultScheduler,
notifyManager
});
//# sourceMappingURL=notifyManager.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"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\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 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 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 * By default React Query will use the batch function provided by ReactDOM or React Native.\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\nexport const notifyManager = createNotifyManager()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,4BAAqC;AAY9B,IAAM,mBAAqC;AAE3C,SAAS,sBAAsB;AACpC,MAAI,QAA+B,CAAC;AACpC,MAAI,eAAe;AACnB,MAAI,WAA2B,CAAC,aAAa;AAC3C,aAAS;AAAA,EACX;AACA,MAAI,gBAAqC,CAAC,aAAyB;AACjE,aAAS;AAAA,EACX;AACA,MAAI,aAAa;AAEjB,QAAM,WAAW,CAAC,aAAmC;AACnD,QAAI,cAAc;AAChB,YAAM,KAAK,QAAQ;AAAA,IACrB,OAAO;AACL,iBAAW,MAAM;AACf,iBAAS,QAAQ;AAAA,MACnB,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,QAAQ,MAAY;AACxB,UAAM,gBAAgB;AACtB,YAAQ,CAAC;AACT,QAAI,cAAc,QAAQ;AACxB,iBAAW,MAAM;AACf,sBAAc,MAAM;AAClB,wBAAc,QAAQ,CAAC,aAAa;AAClC,qBAAS,QAAQ;AAAA,UACnB,CAAC;AAAA,QACH,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,CAAI,aAAyB;AAClC,UAAI;AACJ;AACA,UAAI;AACF,iBAAS,SAAS;AAAA,MACpB,UAAE;AACA;AACA,YAAI,CAAC,cAAc;AACjB,gBAAM;AAAA,QACR;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA,IAIA,YAAY,CACV,aAC0B;AAC1B,aAAO,IAAI,SAAS;AAClB,iBAAS,MAAM;AACb,mBAAS,GAAG,IAAI;AAAA,QAClB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,mBAAmB,CAAC,OAAuB;AACzC,iBAAW;AAAA,IACb;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,wBAAwB,CAAC,OAA4B;AACnD,sBAAgB;AAAA,IAClB;AAAA,IACA,cAAc,CAAC,OAAyB;AACtC,mBAAa;AAAA,IACf;AAAA,EACF;AACF;AAGO,IAAM,gBAAgB,oBAAoB;","names":[]}
+3
View File
@@ -0,0 +1,3 @@
export { createNotifyManager } from './_tsup-dts-rollup.cjs';
export { defaultScheduler_alias_1 as defaultScheduler } from './_tsup-dts-rollup.cjs';
export { notifyManager_alias_1 as notifyManager } from './_tsup-dts-rollup.cjs';
+3
View File
@@ -0,0 +1,3 @@
export { createNotifyManager } from './_tsup-dts-rollup.js';
export { defaultScheduler_alias_1 as defaultScheduler } from './_tsup-dts-rollup.js';
export { notifyManager_alias_1 as notifyManager } from './_tsup-dts-rollup.js';
+86
View File
@@ -0,0 +1,86 @@
// src/notifyManager.ts
import { systemSetTimeoutZero } from "./timeoutManager.js";
var 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 {
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);
});
};
},
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.
* By default React Query will use the batch function provided by ReactDOM or React Native.
*/
setBatchNotifyFunction: (fn) => {
batchNotifyFn = fn;
},
setScheduler: (fn) => {
scheduleFn = fn;
}
};
}
var notifyManager = createNotifyManager();
export {
createNotifyManager,
defaultScheduler,
notifyManager
};
//# sourceMappingURL=notifyManager.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"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\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 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 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 * By default React Query will use the batch function provided by ReactDOM or React Native.\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\nexport const notifyManager = createNotifyManager()\n"],"mappings":";AAEA,SAAS,4BAA4B;AAY9B,IAAM,mBAAqC;AAE3C,SAAS,sBAAsB;AACpC,MAAI,QAA+B,CAAC;AACpC,MAAI,eAAe;AACnB,MAAI,WAA2B,CAAC,aAAa;AAC3C,aAAS;AAAA,EACX;AACA,MAAI,gBAAqC,CAAC,aAAyB;AACjE,aAAS;AAAA,EACX;AACA,MAAI,aAAa;AAEjB,QAAM,WAAW,CAAC,aAAmC;AACnD,QAAI,cAAc;AAChB,YAAM,KAAK,QAAQ;AAAA,IACrB,OAAO;AACL,iBAAW,MAAM;AACf,iBAAS,QAAQ;AAAA,MACnB,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,QAAQ,MAAY;AACxB,UAAM,gBAAgB;AACtB,YAAQ,CAAC;AACT,QAAI,cAAc,QAAQ;AACxB,iBAAW,MAAM;AACf,sBAAc,MAAM;AAClB,wBAAc,QAAQ,CAAC,aAAa;AAClC,qBAAS,QAAQ;AAAA,UACnB,CAAC;AAAA,QACH,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,CAAI,aAAyB;AAClC,UAAI;AACJ;AACA,UAAI;AACF,iBAAS,SAAS;AAAA,MACpB,UAAE;AACA;AACA,YAAI,CAAC,cAAc;AACjB,gBAAM;AAAA,QACR;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA,IAIA,YAAY,CACV,aAC0B;AAC1B,aAAO,IAAI,SAAS;AAClB,iBAAS,MAAM;AACb,mBAAS,GAAG,IAAI;AAAA,QAClB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,mBAAmB,CAAC,OAAuB;AACzC,iBAAW;AAAA,IACb;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,wBAAwB,CAAC,OAA4B;AACnD,sBAAgB;AAAA,IAClB;AAAA,IACA,cAAc,CAAC,OAAyB;AACtC,mBAAa;AAAA,IACf;AAAA,EACF;AACF;AAGO,IAAM,gBAAgB,oBAAoB;","names":[]}
+83
View File
@@ -0,0 +1,83 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/onlineManager.ts
var onlineManager_exports = {};
__export(onlineManager_exports, {
OnlineManager: () => OnlineManager,
onlineManager: () => onlineManager
});
module.exports = __toCommonJS(onlineManager_exports);
var import_subscribable = require("./subscribable.cjs");
var OnlineManager = class extends import_subscribable.Subscribable {
#online = true;
#cleanup;
#setup;
constructor() {
super();
this.#setup = (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);
};
}
return;
};
}
onSubscribe() {
if (!this.#cleanup) {
this.setEventListener(this.#setup);
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
this.#cleanup?.();
this.#cleanup = void 0;
}
}
setEventListener(setup) {
this.#setup = setup;
this.#cleanup?.();
this.#cleanup = setup(this.setOnline.bind(this));
}
setOnline(online) {
const changed = this.#online !== online;
if (changed) {
this.#online = online;
this.listeners.forEach((listener) => {
listener(online);
});
}
}
isOnline() {
return this.#online;
}
};
var onlineManager = new OnlineManager();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
OnlineManager,
onlineManager
});
//# sourceMappingURL=onlineManager.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\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 setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\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 isOnline(): boolean {\n return this.#online\n }\n}\n\nexport const onlineManager = new OnlineManager()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAA6B;AAKtB,IAAM,gBAAN,cAA4B,iCAAuB;AAAA,EACxD,UAAU;AAAA,EACV;AAAA,EAEA;AAAA,EAEA,cAAc;AACZ,UAAM;AACN,SAAK,SAAS,CAAC,aAAa;AAG1B,UAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;AAC5D,cAAM,iBAAiB,MAAM,SAAS,IAAI;AAC1C,cAAM,kBAAkB,MAAM,SAAS,KAAK;AAE5C,eAAO,iBAAiB,UAAU,gBAAgB,KAAK;AACvD,eAAO,iBAAiB,WAAW,iBAAiB,KAAK;AAEzD,eAAO,MAAM;AAEX,iBAAO,oBAAoB,UAAU,cAAc;AACnD,iBAAO,oBAAoB,WAAW,eAAe;AAAA,QACvD;AAAA,MACF;AAEA;AAAA,IACF;AAAA,EACF;AAAA,EAEU,cAAoB;AAC5B,QAAI,CAAC,KAAK,UAAU;AAClB,WAAK,iBAAiB,KAAK,MAAM;AAAA,IACnC;AAAA,EACF;AAAA,EAEU,gBAAgB;AACxB,QAAI,CAAC,KAAK,aAAa,GAAG;AACxB,WAAK,WAAW;AAChB,WAAK,WAAW;AAAA,IAClB;AAAA,EACF;AAAA,EAEA,iBAAiB,OAAsB;AACrC,SAAK,SAAS;AACd,SAAK,WAAW;AAChB,SAAK,WAAW,MAAM,KAAK,UAAU,KAAK,IAAI,CAAC;AAAA,EACjD;AAAA,EAEA,UAAU,QAAuB;AAC/B,UAAM,UAAU,KAAK,YAAY;AAEjC,QAAI,SAAS;AACX,WAAK,UAAU;AACf,WAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,iBAAS,MAAM;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,WAAoB;AAClB,WAAO,KAAK;AAAA,EACd;AACF;AAEO,IAAM,gBAAgB,IAAI,cAAc;","names":[]}
+2
View File
@@ -0,0 +1,2 @@
export { OnlineManager } from './_tsup-dts-rollup.cjs';
export { onlineManager_alias_1 as onlineManager } from './_tsup-dts-rollup.cjs';
+2
View File
@@ -0,0 +1,2 @@
export { OnlineManager } from './_tsup-dts-rollup.js';
export { onlineManager_alias_1 as onlineManager } from './_tsup-dts-rollup.js';
+57
View File
@@ -0,0 +1,57 @@
// src/onlineManager.ts
import { Subscribable } from "./subscribable.js";
var OnlineManager = class extends Subscribable {
#online = true;
#cleanup;
#setup;
constructor() {
super();
this.#setup = (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);
};
}
return;
};
}
onSubscribe() {
if (!this.#cleanup) {
this.setEventListener(this.#setup);
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
this.#cleanup?.();
this.#cleanup = void 0;
}
}
setEventListener(setup) {
this.#setup = setup;
this.#cleanup?.();
this.#cleanup = setup(this.setOnline.bind(this));
}
setOnline(online) {
const changed = this.#online !== online;
if (changed) {
this.#online = online;
this.listeners.forEach((listener) => {
listener(online);
});
}
}
isOnline() {
return this.#online;
}
};
var onlineManager = new OnlineManager();
export {
OnlineManager,
onlineManager
};
//# sourceMappingURL=onlineManager.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\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 setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\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 isOnline(): boolean {\n return this.#online\n }\n}\n\nexport const onlineManager = new OnlineManager()\n"],"mappings":";AAAA,SAAS,oBAAoB;AAKtB,IAAM,gBAAN,cAA4B,aAAuB;AAAA,EACxD,UAAU;AAAA,EACV;AAAA,EAEA;AAAA,EAEA,cAAc;AACZ,UAAM;AACN,SAAK,SAAS,CAAC,aAAa;AAG1B,UAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;AAC5D,cAAM,iBAAiB,MAAM,SAAS,IAAI;AAC1C,cAAM,kBAAkB,MAAM,SAAS,KAAK;AAE5C,eAAO,iBAAiB,UAAU,gBAAgB,KAAK;AACvD,eAAO,iBAAiB,WAAW,iBAAiB,KAAK;AAEzD,eAAO,MAAM;AAEX,iBAAO,oBAAoB,UAAU,cAAc;AACnD,iBAAO,oBAAoB,WAAW,eAAe;AAAA,QACvD;AAAA,MACF;AAEA;AAAA,IACF;AAAA,EACF;AAAA,EAEU,cAAoB;AAC5B,QAAI,CAAC,KAAK,UAAU;AAClB,WAAK,iBAAiB,KAAK,MAAM;AAAA,IACnC;AAAA,EACF;AAAA,EAEU,gBAAgB;AACxB,QAAI,CAAC,KAAK,aAAa,GAAG;AACxB,WAAK,WAAW;AAChB,WAAK,WAAW;AAAA,IAClB;AAAA,EACF;AAAA,EAEA,iBAAiB,OAAsB;AACrC,SAAK,SAAS;AACd,SAAK,WAAW;AAChB,SAAK,WAAW,MAAM,KAAK,UAAU,KAAK,IAAI,CAAC;AAAA,EACjD;AAAA,EAEA,UAAU,QAAuB;AAC/B,UAAM,UAAU,KAAK,YAAY;AAEjC,QAAI,SAAS;AACX,WAAK,UAAU;AACf,WAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,iBAAS,MAAM;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,WAAoB;AAClB,WAAO,KAAK;AAAA,EACd;AACF;AAEO,IAAM,gBAAgB,IAAI,cAAc;","names":[]}
+243
View File
@@ -0,0 +1,243 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/queriesObserver.ts
var queriesObserver_exports = {};
__export(queriesObserver_exports, {
QueriesObserver: () => QueriesObserver
});
module.exports = __toCommonJS(queriesObserver_exports);
var import_notifyManager = require("./notifyManager.cjs");
var import_queryObserver = require("./queryObserver.cjs");
var import_subscribable = require("./subscribable.cjs");
var import_utils = require("./utils.cjs");
function difference(array1, array2) {
const excludeSet = new Set(array2);
return array1.filter((x) => !excludeSet.has(x));
}
function replaceAt(array, index, value) {
const copy = array.slice(0);
copy[index] = value;
return copy;
}
var QueriesObserver = class extends import_subscribable.Subscribable {
#client;
#result;
#queries;
#options;
#observers;
#combinedResult;
#lastCombine;
#lastResult;
#lastQueryHashes;
#observerMatches = [];
constructor(client, queries, options) {
super();
this.#client = client;
this.#options = options;
this.#queries = [];
this.#observers = [];
this.#result = [];
this.setQueries(queries);
}
onSubscribe() {
if (this.listeners.size === 1) {
this.#observers.forEach((observer) => {
observer.subscribe((result) => {
this.#onUpdate(observer, result);
});
});
}
}
onUnsubscribe() {
if (!this.listeners.size) {
this.destroy();
}
}
destroy() {
this.listeners = /* @__PURE__ */ new Set();
this.#observers.forEach((observer) => {
observer.destroy();
});
}
setQueries(queries, options) {
this.#queries = queries;
this.#options = options;
if (process.env.NODE_ENV !== "production") {
const queryHashes = queries.map(
(query) => this.#client.defaultQueryOptions(query).queryHash
);
if (new Set(queryHashes).size !== queryHashes.length) {
console.warn(
"[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior."
);
}
}
import_notifyManager.notifyManager.batch(() => {
const prevObservers = this.#observers;
const newObserverMatches = this.#findMatchingObservers(this.#queries);
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 = this.#result[index];
return !prev || !(0, import_utils.shallowEqualObjects)(result, prev);
});
if (!hasStructuralChange && !hasResultChange) return;
if (hasStructuralChange) {
this.#observerMatches = newObserverMatches;
this.#observers = newObservers;
}
this.#result = newResult;
if (!this.hasListeners()) return;
if (hasStructuralChange) {
difference(prevObservers, newObservers).forEach((observer) => {
observer.destroy();
});
difference(newObservers, prevObservers).forEach((observer) => {
observer.subscribe((result) => {
this.#onUpdate(observer, result);
});
});
}
this.#notify();
});
}
getCurrentResult() {
return this.#result;
}
getQueries() {
return this.#observers.map((observer) => observer.getCurrentQuery());
}
getObservers() {
return this.#observers;
}
getOptimisticResult(queries, combine) {
const matches = this.#findMatchingObservers(queries);
const result = matches.map(
(match) => match.observer.getOptimisticResult(match.defaultedQueryOptions)
);
const queryHashes = matches.map(
(match) => match.defaultedQueryOptions.queryHash
);
return [
result,
(r) => {
return this.#combineResult(r ?? result, combine, queryHashes);
},
() => {
return this.#trackResult(result, matches);
}
];
}
#trackResult(result, matches) {
return matches.map((match, index) => {
const observerResult = result[index];
return !match.defaultedQueryOptions.notifyOnChangeProps ? match.observer.trackResult(observerResult, (accessedProp) => {
matches.forEach((m) => {
m.observer.trackProp(accessedProp);
});
}) : observerResult;
});
}
#combineResult(input, combine, queryHashes) {
if (combine) {
const lastHashes = this.#lastQueryHashes;
const queryHashesChanged = queryHashes !== void 0 && lastHashes !== void 0 && (lastHashes.length !== queryHashes.length || queryHashes.some((hash, i) => hash !== lastHashes[i]));
if (!this.#combinedResult || this.#result !== this.#lastResult || queryHashesChanged || combine !== this.#lastCombine) {
this.#lastCombine = combine;
this.#lastResult = this.#result;
if (queryHashes !== void 0) {
this.#lastQueryHashes = queryHashes;
}
this.#combinedResult = (0, import_utils.replaceEqualDeep)(
this.#combinedResult,
combine(input)
);
}
return this.#combinedResult;
}
return input;
}
#shouldSkipCombine() {
return this.#options?.combine !== void 0 && this.#observers.some((observer, index) => {
return observer.options.suspense && this.#result[index]?.data === void 0;
});
}
#findMatchingObservers(queries) {
const prevObserversMap = /* @__PURE__ */ new Map();
this.#observers.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) => {
const defaultedOptions = this.#client.defaultQueryOptions(options);
const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift();
const observer = match ?? new import_queryObserver.QueryObserver(this.#client, defaultedOptions);
observers.push({
defaultedQueryOptions: defaultedOptions,
observer
});
});
return observers;
}
#onUpdate(observer, result) {
const index = this.#observers.indexOf(observer);
if (index !== -1) {
this.#result = replaceAt(this.#result, index, result);
this.#notify();
}
}
#notify() {
if (this.hasListeners()) {
const newTracked = this.#trackResult(this.#result, this.#observerMatches);
const shouldSkipCombine = this.#shouldSkipCombine();
const previousResult = this.#combinedResult;
const newResult = shouldSkipCombine ? previousResult : this.#combineResult(newTracked, this.#options?.combine);
if (shouldSkipCombine || previousResult !== newResult) {
import_notifyManager.notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(this.#result);
});
});
}
}
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QueriesObserver
});
//# sourceMappingURL=queriesObserver.cjs.map
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
export { QueriesObserverOptions_alias_1 as QueriesObserverOptions } from './_tsup-dts-rollup.cjs';
export { QueriesObserver_alias_1 as QueriesObserver } from './_tsup-dts-rollup.cjs';
+2
View File
@@ -0,0 +1,2 @@
export { QueriesObserverOptions_alias_1 as QueriesObserverOptions } from './_tsup-dts-rollup.js';
export { QueriesObserver_alias_1 as QueriesObserver } from './_tsup-dts-rollup.js';
+218
View File
@@ -0,0 +1,218 @@
// src/queriesObserver.ts
import { notifyManager } from "./notifyManager.js";
import { QueryObserver } from "./queryObserver.js";
import { Subscribable } from "./subscribable.js";
import { replaceEqualDeep, shallowEqualObjects } from "./utils.js";
function difference(array1, array2) {
const excludeSet = new Set(array2);
return array1.filter((x) => !excludeSet.has(x));
}
function replaceAt(array, index, value) {
const copy = array.slice(0);
copy[index] = value;
return copy;
}
var QueriesObserver = class extends Subscribable {
#client;
#result;
#queries;
#options;
#observers;
#combinedResult;
#lastCombine;
#lastResult;
#lastQueryHashes;
#observerMatches = [];
constructor(client, queries, options) {
super();
this.#client = client;
this.#options = options;
this.#queries = [];
this.#observers = [];
this.#result = [];
this.setQueries(queries);
}
onSubscribe() {
if (this.listeners.size === 1) {
this.#observers.forEach((observer) => {
observer.subscribe((result) => {
this.#onUpdate(observer, result);
});
});
}
}
onUnsubscribe() {
if (!this.listeners.size) {
this.destroy();
}
}
destroy() {
this.listeners = /* @__PURE__ */ new Set();
this.#observers.forEach((observer) => {
observer.destroy();
});
}
setQueries(queries, options) {
this.#queries = queries;
this.#options = options;
if (process.env.NODE_ENV !== "production") {
const queryHashes = queries.map(
(query) => this.#client.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 = this.#observers;
const newObserverMatches = this.#findMatchingObservers(this.#queries);
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 = this.#result[index];
return !prev || !shallowEqualObjects(result, prev);
});
if (!hasStructuralChange && !hasResultChange) return;
if (hasStructuralChange) {
this.#observerMatches = newObserverMatches;
this.#observers = newObservers;
}
this.#result = newResult;
if (!this.hasListeners()) return;
if (hasStructuralChange) {
difference(prevObservers, newObservers).forEach((observer) => {
observer.destroy();
});
difference(newObservers, prevObservers).forEach((observer) => {
observer.subscribe((result) => {
this.#onUpdate(observer, result);
});
});
}
this.#notify();
});
}
getCurrentResult() {
return this.#result;
}
getQueries() {
return this.#observers.map((observer) => observer.getCurrentQuery());
}
getObservers() {
return this.#observers;
}
getOptimisticResult(queries, combine) {
const matches = this.#findMatchingObservers(queries);
const result = matches.map(
(match) => match.observer.getOptimisticResult(match.defaultedQueryOptions)
);
const queryHashes = matches.map(
(match) => match.defaultedQueryOptions.queryHash
);
return [
result,
(r) => {
return this.#combineResult(r ?? result, combine, queryHashes);
},
() => {
return this.#trackResult(result, matches);
}
];
}
#trackResult(result, matches) {
return matches.map((match, index) => {
const observerResult = result[index];
return !match.defaultedQueryOptions.notifyOnChangeProps ? match.observer.trackResult(observerResult, (accessedProp) => {
matches.forEach((m) => {
m.observer.trackProp(accessedProp);
});
}) : observerResult;
});
}
#combineResult(input, combine, queryHashes) {
if (combine) {
const lastHashes = this.#lastQueryHashes;
const queryHashesChanged = queryHashes !== void 0 && lastHashes !== void 0 && (lastHashes.length !== queryHashes.length || queryHashes.some((hash, i) => hash !== lastHashes[i]));
if (!this.#combinedResult || this.#result !== this.#lastResult || queryHashesChanged || combine !== this.#lastCombine) {
this.#lastCombine = combine;
this.#lastResult = this.#result;
if (queryHashes !== void 0) {
this.#lastQueryHashes = queryHashes;
}
this.#combinedResult = replaceEqualDeep(
this.#combinedResult,
combine(input)
);
}
return this.#combinedResult;
}
return input;
}
#shouldSkipCombine() {
return this.#options?.combine !== void 0 && this.#observers.some((observer, index) => {
return observer.options.suspense && this.#result[index]?.data === void 0;
});
}
#findMatchingObservers(queries) {
const prevObserversMap = /* @__PURE__ */ new Map();
this.#observers.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) => {
const defaultedOptions = this.#client.defaultQueryOptions(options);
const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift();
const observer = match ?? new QueryObserver(this.#client, defaultedOptions);
observers.push({
defaultedQueryOptions: defaultedOptions,
observer
});
});
return observers;
}
#onUpdate(observer, result) {
const index = this.#observers.indexOf(observer);
if (index !== -1) {
this.#result = replaceAt(this.#result, index, result);
this.#notify();
}
}
#notify() {
if (this.hasListeners()) {
const newTracked = this.#trackResult(this.#result, this.#observerMatches);
const shouldSkipCombine = this.#shouldSkipCombine();
const previousResult = this.#combinedResult;
const newResult = shouldSkipCombine ? previousResult : this.#combineResult(newTracked, this.#options?.combine);
if (shouldSkipCombine || previousResult !== newResult) {
notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(this.#result);
});
});
}
}
}
};
export {
QueriesObserver
};
//# sourceMappingURL=queriesObserver.js.map
File diff suppressed because one or more lines are too long
+472
View File
@@ -0,0 +1,472 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/query.ts
var query_exports = {};
__export(query_exports, {
Query: () => Query,
fetchState: () => fetchState
});
module.exports = __toCommonJS(query_exports);
var import_utils = require("./utils.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_retryer = require("./retryer.cjs");
var import_removable = require("./removable.cjs");
var import_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs");
var Query = class extends import_removable.Removable {
#queryType;
#initialState;
#revertState;
#cache;
#client;
#retryer;
#defaultOptions;
#abortSignalConsumed;
constructor(config) {
super();
this.#abortSignalConsumed = false;
this.#defaultOptions = config.defaultOptions;
this.setOptions(config.options);
this.observers = [];
this.#client = config.client;
this.#cache = this.#client.getQueryCache();
this.queryKey = config.queryKey;
this.queryHash = config.queryHash;
this.#initialState = getDefaultState(this.options);
this.state = config.state ?? this.#initialState;
this.scheduleGc();
}
get meta() {
return this.options.meta;
}
get queryType() {
return this.#queryType;
}
get promise() {
return this.#retryer?.promise;
}
setOptions(options) {
this.options = { ...this.#defaultOptions, ...options };
if (options?._type) {
this.#queryType = 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)
);
this.#initialState = defaultState;
}
}
}
optionalRemove() {
if (!this.observers.length && this.state.fetchStatus === "idle") {
this.#cache.remove(this);
}
}
setData(newData, options) {
const data = (0, import_utils.replaceData)(this.state.data, newData, this.options);
this.#dispatch({
data,
type: "success",
dataUpdatedAt: options?.updatedAt,
manual: options?.manual
});
return data;
}
setState(state) {
this.#dispatch({ type: "setState", state });
}
cancel(options) {
const promise = this.#retryer?.promise;
this.#retryer?.cancel(options);
return promise ? promise.then(import_utils.noop).catch(import_utils.noop) : Promise.resolve();
}
destroy() {
super.destroy();
this.cancel({ silent: true });
}
get resetState() {
return this.#initialState;
}
reset() {
this.destroy();
this.setState(this.resetState);
}
isActive() {
return this.observers.some(
(observer) => (0, import_utils.resolveQueryBoolean)(observer.options.enabled, this) !== false
);
}
isDisabled() {
if (this.getObserversCount() > 0) {
return !this.isActive();
}
return this.options.queryFn === import_utils.skipToken || !this.isFetched();
}
isFetched() {
return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;
}
isStatic() {
if (this.getObserversCount() > 0) {
return this.observers.some(
(observer) => (0, import_utils.resolveStaleTime)(observer.options.staleTime, this) === "static"
);
}
return false;
}
isStale() {
if (this.getObserversCount() > 0) {
return this.observers.some(
(observer) => observer.getCurrentResult().isStale
);
}
return this.state.data === void 0 || this.state.isInvalidated;
}
isStaleByTime(staleTime = 0) {
if (this.state.data === void 0) {
return true;
}
if (staleTime === "static") {
return false;
}
if (this.state.isInvalidated) {
return true;
}
return !(0, import_utils.timeUntilStale)(this.state.dataUpdatedAt, staleTime);
}
onFocus() {
const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());
observer?.refetch({ cancelRefetch: false });
this.#retryer?.continue();
}
onOnline() {
const observer = this.observers.find((x) => x.shouldFetchOnReconnect());
observer?.refetch({ cancelRefetch: false });
this.#retryer?.continue();
}
addObserver(observer) {
if (!this.observers.includes(observer)) {
this.observers.push(observer);
this.clearGcTimeout();
this.#cache.notify({ type: "observerAdded", query: this, observer });
}
}
removeObserver(observer) {
if (this.observers.includes(observer)) {
this.observers = this.observers.filter((x) => x !== observer);
if (!this.observers.length) {
if (this.#retryer) {
if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) {
this.#retryer.cancel({ revert: true });
} else {
this.#retryer.cancelRetry();
}
}
this.scheduleGc();
}
this.#cache.notify({ type: "observerRemoved", query: this, observer });
}
}
getObserversCount() {
return this.observers.length;
}
#isInitialPausedFetch() {
return this.state.fetchStatus === "paused" && this.state.status === "pending";
}
invalidate() {
if (!this.state.isInvalidated) {
this.#dispatch({ type: "invalidate" });
}
}
async fetch(options, fetchOptions) {
if (this.state.fetchStatus !== "idle" && // If the promise in the retryer is already rejected, we have to definitely
// re-start the fetch; there is a chance that the query is still in a
// pending state when that happens
this.#retryer?.status() !== "rejected") {
if (this.state.data !== void 0 && fetchOptions?.cancelRefetch) {
this.cancel({ silent: true });
} else if (this.#retryer) {
this.#retryer.continueRetry();
return this.#retryer.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: () => {
this.#abortSignalConsumed = true;
return abortController.signal;
}
});
};
const fetchFn = () => {
const queryFn = (0, import_utils.ensureQueryFn)(this.options, fetchOptions);
const createQueryFnContext = () => {
const queryFnContext2 = {
client: this.#client,
queryKey: this.queryKey,
meta: this.meta
};
addSignalProperty(queryFnContext2);
return queryFnContext2;
};
const queryFnContext = createQueryFnContext();
this.#abortSignalConsumed = false;
if (this.options.persister) {
return this.options.persister(
queryFn,
queryFnContext,
this
);
}
return queryFn(queryFnContext);
};
const createFetchContext = () => {
const context2 = {
fetchOptions,
options: this.options,
queryKey: this.queryKey,
client: this.#client,
state: this.state,
fetchFn
};
addSignalProperty(context2);
return context2;
};
const context = createFetchContext();
const behavior = this.#queryType === "infinite" ? (0, import_infiniteQueryBehavior.infiniteQueryBehavior)(
this.options.pages
) : this.options.behavior;
behavior?.onFetch(context, this);
this.#revertState = this.state;
if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== context.fetchOptions?.meta) {
this.#dispatch({ type: "fetch", meta: context.fetchOptions?.meta });
}
this.#retryer = (0, import_retryer.createRetryer)({
initialPromise: fetchOptions?.initialPromise,
fn: context.fetchFn,
onCancel: (error) => {
if (error instanceof import_retryer.CancelledError && error.revert) {
this.setState({
...this.#revertState,
fetchStatus: "idle"
});
}
abortController.abort();
},
onFail: (failureCount, error) => {
this.#dispatch({ type: "failed", failureCount, error });
},
onPause: () => {
this.#dispatch({ type: "pause" });
},
onContinue: () => {
this.#dispatch({ type: "continue" });
},
retry: context.options.retry,
retryDelay: context.options.retryDelay,
networkMode: context.options.networkMode,
canRun: () => true
});
try {
const data = await this.#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);
this.#cache.config.onSuccess?.(data, this);
this.#cache.config.onSettled?.(
data,
this.state.error,
this
);
return data;
} catch (error) {
if (error instanceof import_retryer.CancelledError) {
if (error.silent) {
return this.#retryer.promise;
} else if (error.revert) {
if (this.state.data === void 0) {
throw error;
}
return this.state.data;
}
}
this.#dispatch({
type: "error",
error
});
this.#cache.config.onError?.(
error,
this
);
this.#cache.config.onSettled?.(
this.state.data,
error,
this
);
throw error;
} finally {
this.scheduleGc();
}
}
#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
}
};
this.#revertState = 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",
// flag existing data as invalidated if we get a background error
// note that "no data" always means stale so we can set unconditionally here
isInvalidated: true
};
case "invalidate":
return {
...state,
isInvalidated: true
};
case "setState":
return {
...state,
...action.state
};
}
};
this.state = reducer(this.state);
import_notifyManager.notifyManager.batch(() => {
this.observers.forEach((observer) => {
observer.onQueryUpdate();
});
this.#cache.notify({ query: this, type: "updated", action });
});
}
};
function fetchState(data, options) {
return {
fetchFailureCount: 0,
fetchFailureReason: null,
fetchStatus: (0, import_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"
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Query,
fetchState
});
//# sourceMappingURL=query.cjs.map
File diff suppressed because one or more lines are too long
+9
View File
@@ -0,0 +1,9 @@
export { fetchState } from './_tsup-dts-rollup.cjs';
export { QueryState_alias_1 as QueryState } from './_tsup-dts-rollup.cjs';
export { FetchContext } from './_tsup-dts-rollup.cjs';
export { QueryBehavior } from './_tsup-dts-rollup.cjs';
export { FetchDirection } from './_tsup-dts-rollup.cjs';
export { FetchMeta } from './_tsup-dts-rollup.cjs';
export { FetchOptions } from './_tsup-dts-rollup.cjs';
export { Action_alias_1 as Action } from './_tsup-dts-rollup.cjs';
export { Query_alias_1 as Query } from './_tsup-dts-rollup.cjs';
+9
View File
@@ -0,0 +1,9 @@
export { fetchState } from './_tsup-dts-rollup.js';
export { QueryState_alias_1 as QueryState } from './_tsup-dts-rollup.js';
export { FetchContext } from './_tsup-dts-rollup.js';
export { QueryBehavior } from './_tsup-dts-rollup.js';
export { FetchDirection } from './_tsup-dts-rollup.js';
export { FetchMeta } from './_tsup-dts-rollup.js';
export { FetchOptions } from './_tsup-dts-rollup.js';
export { Action_alias_1 as Action } from './_tsup-dts-rollup.js';
export { Query_alias_1 as Query } from './_tsup-dts-rollup.js';
+454
View File
@@ -0,0 +1,454 @@
// src/query.ts
import {
ensureQueryFn,
noop,
replaceData,
resolveQueryBoolean,
resolveStaleTime,
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";
var Query = class extends Removable {
#queryType;
#initialState;
#revertState;
#cache;
#client;
#retryer;
#defaultOptions;
#abortSignalConsumed;
constructor(config) {
super();
this.#abortSignalConsumed = false;
this.#defaultOptions = config.defaultOptions;
this.setOptions(config.options);
this.observers = [];
this.#client = config.client;
this.#cache = this.#client.getQueryCache();
this.queryKey = config.queryKey;
this.queryHash = config.queryHash;
this.#initialState = getDefaultState(this.options);
this.state = config.state ?? this.#initialState;
this.scheduleGc();
}
get meta() {
return this.options.meta;
}
get queryType() {
return this.#queryType;
}
get promise() {
return this.#retryer?.promise;
}
setOptions(options) {
this.options = { ...this.#defaultOptions, ...options };
if (options?._type) {
this.#queryType = 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)
);
this.#initialState = defaultState;
}
}
}
optionalRemove() {
if (!this.observers.length && this.state.fetchStatus === "idle") {
this.#cache.remove(this);
}
}
setData(newData, options) {
const data = replaceData(this.state.data, newData, this.options);
this.#dispatch({
data,
type: "success",
dataUpdatedAt: options?.updatedAt,
manual: options?.manual
});
return data;
}
setState(state) {
this.#dispatch({ type: "setState", state });
}
cancel(options) {
const promise = this.#retryer?.promise;
this.#retryer?.cancel(options);
return promise ? promise.then(noop).catch(noop) : Promise.resolve();
}
destroy() {
super.destroy();
this.cancel({ silent: true });
}
get resetState() {
return this.#initialState;
}
reset() {
this.destroy();
this.setState(this.resetState);
}
isActive() {
return this.observers.some(
(observer) => resolveQueryBoolean(observer.options.enabled, this) !== false
);
}
isDisabled() {
if (this.getObserversCount() > 0) {
return !this.isActive();
}
return this.options.queryFn === skipToken || !this.isFetched();
}
isFetched() {
return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;
}
isStatic() {
if (this.getObserversCount() > 0) {
return this.observers.some(
(observer) => resolveStaleTime(observer.options.staleTime, this) === "static"
);
}
return false;
}
isStale() {
if (this.getObserversCount() > 0) {
return this.observers.some(
(observer) => observer.getCurrentResult().isStale
);
}
return this.state.data === void 0 || this.state.isInvalidated;
}
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);
}
onFocus() {
const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());
observer?.refetch({ cancelRefetch: false });
this.#retryer?.continue();
}
onOnline() {
const observer = this.observers.find((x) => x.shouldFetchOnReconnect());
observer?.refetch({ cancelRefetch: false });
this.#retryer?.continue();
}
addObserver(observer) {
if (!this.observers.includes(observer)) {
this.observers.push(observer);
this.clearGcTimeout();
this.#cache.notify({ type: "observerAdded", query: this, observer });
}
}
removeObserver(observer) {
if (this.observers.includes(observer)) {
this.observers = this.observers.filter((x) => x !== observer);
if (!this.observers.length) {
if (this.#retryer) {
if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) {
this.#retryer.cancel({ revert: true });
} else {
this.#retryer.cancelRetry();
}
}
this.scheduleGc();
}
this.#cache.notify({ type: "observerRemoved", query: this, observer });
}
}
getObserversCount() {
return this.observers.length;
}
#isInitialPausedFetch() {
return this.state.fetchStatus === "paused" && this.state.status === "pending";
}
invalidate() {
if (!this.state.isInvalidated) {
this.#dispatch({ type: "invalidate" });
}
}
async fetch(options, fetchOptions) {
if (this.state.fetchStatus !== "idle" && // If the promise in the retryer is already rejected, we have to definitely
// re-start the fetch; there is a chance that the query is still in a
// pending state when that happens
this.#retryer?.status() !== "rejected") {
if (this.state.data !== void 0 && fetchOptions?.cancelRefetch) {
this.cancel({ silent: true });
} else if (this.#retryer) {
this.#retryer.continueRetry();
return this.#retryer.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: () => {
this.#abortSignalConsumed = true;
return abortController.signal;
}
});
};
const fetchFn = () => {
const queryFn = ensureQueryFn(this.options, fetchOptions);
const createQueryFnContext = () => {
const queryFnContext2 = {
client: this.#client,
queryKey: this.queryKey,
meta: this.meta
};
addSignalProperty(queryFnContext2);
return queryFnContext2;
};
const queryFnContext = createQueryFnContext();
this.#abortSignalConsumed = false;
if (this.options.persister) {
return this.options.persister(
queryFn,
queryFnContext,
this
);
}
return queryFn(queryFnContext);
};
const createFetchContext = () => {
const context2 = {
fetchOptions,
options: this.options,
queryKey: this.queryKey,
client: this.#client,
state: this.state,
fetchFn
};
addSignalProperty(context2);
return context2;
};
const context = createFetchContext();
const behavior = this.#queryType === "infinite" ? infiniteQueryBehavior(
this.options.pages
) : this.options.behavior;
behavior?.onFetch(context, this);
this.#revertState = this.state;
if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== context.fetchOptions?.meta) {
this.#dispatch({ type: "fetch", meta: context.fetchOptions?.meta });
}
this.#retryer = createRetryer({
initialPromise: fetchOptions?.initialPromise,
fn: context.fetchFn,
onCancel: (error) => {
if (error instanceof CancelledError && error.revert) {
this.setState({
...this.#revertState,
fetchStatus: "idle"
});
}
abortController.abort();
},
onFail: (failureCount, error) => {
this.#dispatch({ type: "failed", failureCount, error });
},
onPause: () => {
this.#dispatch({ type: "pause" });
},
onContinue: () => {
this.#dispatch({ type: "continue" });
},
retry: context.options.retry,
retryDelay: context.options.retryDelay,
networkMode: context.options.networkMode,
canRun: () => true
});
try {
const data = await this.#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);
this.#cache.config.onSuccess?.(data, this);
this.#cache.config.onSettled?.(
data,
this.state.error,
this
);
return data;
} catch (error) {
if (error instanceof CancelledError) {
if (error.silent) {
return this.#retryer.promise;
} else if (error.revert) {
if (this.state.data === void 0) {
throw error;
}
return this.state.data;
}
}
this.#dispatch({
type: "error",
error
});
this.#cache.config.onError?.(
error,
this
);
this.#cache.config.onSettled?.(
this.state.data,
error,
this
);
throw error;
} finally {
this.scheduleGc();
}
}
#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
}
};
this.#revertState = 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",
// flag existing data as invalidated if we get a background error
// note that "no data" always means stale so we can set unconditionally here
isInvalidated: true
};
case "invalidate":
return {
...state,
isInvalidated: true
};
case "setState":
return {
...state,
...action.state
};
}
};
this.state = reducer(this.state);
notifyManager.batch(() => {
this.observers.forEach((observer) => {
observer.onQueryUpdate();
});
this.#cache.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"
};
}
export {
Query,
fetchState
};
//# sourceMappingURL=query.js.map
File diff suppressed because one or more lines are too long
+122
View File
@@ -0,0 +1,122 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/queryCache.ts
var queryCache_exports = {};
__export(queryCache_exports, {
QueryCache: () => QueryCache
});
module.exports = __toCommonJS(queryCache_exports);
var import_utils = require("./utils.cjs");
var import_query = require("./query.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_subscribable = require("./subscribable.cjs");
var QueryCache = class extends import_subscribable.Subscribable {
constructor(config = {}) {
super();
this.config = config;
this.#queries = /* @__PURE__ */ new Map();
}
#queries;
build(client, options, state) {
const queryKey = options.queryKey;
const queryHash = options.queryHash ?? (0, import_utils.hashQueryKeyByOptions)(queryKey, options);
let query = this.get(queryHash);
if (!query) {
query = new import_query.Query({
client,
queryKey,
queryHash,
options: client.defaultQueryOptions(options),
state,
defaultOptions: client.getQueryDefaults(queryKey)
});
this.add(query);
}
return query;
}
add(query) {
if (!this.#queries.has(query.queryHash)) {
this.#queries.set(query.queryHash, query);
this.notify({
type: "added",
query
});
}
}
remove(query) {
const queryInMap = this.#queries.get(query.queryHash);
if (queryInMap) {
query.destroy();
if (queryInMap === query) {
this.#queries.delete(query.queryHash);
}
this.notify({ type: "removed", query });
}
}
clear() {
import_notifyManager.notifyManager.batch(() => {
this.getAll().forEach((query) => {
this.remove(query);
});
});
}
get(queryHash) {
return this.#queries.get(queryHash);
}
getAll() {
return [...this.#queries.values()];
}
find(filters) {
const defaultedFilters = { exact: true, ...filters };
return this.getAll().find(
(query) => (0, import_utils.matchQuery)(defaultedFilters, query)
);
}
findAll(filters = {}) {
const queries = this.getAll();
return Object.keys(filters).length > 0 ? queries.filter((query) => (0, import_utils.matchQuery)(filters, query)) : queries;
}
notify(event) {
import_notifyManager.notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(event);
});
});
}
onFocus() {
import_notifyManager.notifyManager.batch(() => {
this.getAll().forEach((query) => {
query.onFocus();
});
});
}
onOnline() {
import_notifyManager.notifyManager.batch(() => {
this.getAll().forEach((query) => {
query.onOnline();
});
});
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QueryCache
});
//# sourceMappingURL=queryCache.cjs.map
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
export { QueryCacheNotifyEvent_alias_1 as QueryCacheNotifyEvent } from './_tsup-dts-rollup.cjs';
export { QueryStore } from './_tsup-dts-rollup.cjs';
export { QueryCache_alias_1 as QueryCache } from './_tsup-dts-rollup.cjs';
+3
View File
@@ -0,0 +1,3 @@
export { QueryCacheNotifyEvent_alias_1 as QueryCacheNotifyEvent } from './_tsup-dts-rollup.js';
export { QueryStore } from './_tsup-dts-rollup.js';
export { QueryCache_alias_1 as QueryCache } from './_tsup-dts-rollup.js';
+97
View File
@@ -0,0 +1,97 @@
// src/queryCache.ts
import { hashQueryKeyByOptions, matchQuery } from "./utils.js";
import { Query } from "./query.js";
import { notifyManager } from "./notifyManager.js";
import { Subscribable } from "./subscribable.js";
var QueryCache = class extends Subscribable {
constructor(config = {}) {
super();
this.config = config;
this.#queries = /* @__PURE__ */ new Map();
}
#queries;
build(client, options, state) {
const queryKey = options.queryKey;
const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
let query = this.get(queryHash);
if (!query) {
query = new Query({
client,
queryKey,
queryHash,
options: client.defaultQueryOptions(options),
state,
defaultOptions: client.getQueryDefaults(queryKey)
});
this.add(query);
}
return query;
}
add(query) {
if (!this.#queries.has(query.queryHash)) {
this.#queries.set(query.queryHash, query);
this.notify({
type: "added",
query
});
}
}
remove(query) {
const queryInMap = this.#queries.get(query.queryHash);
if (queryInMap) {
query.destroy();
if (queryInMap === query) {
this.#queries.delete(query.queryHash);
}
this.notify({ type: "removed", query });
}
}
clear() {
notifyManager.batch(() => {
this.getAll().forEach((query) => {
this.remove(query);
});
});
}
get(queryHash) {
return this.#queries.get(queryHash);
}
getAll() {
return [...this.#queries.values()];
}
find(filters) {
const defaultedFilters = { exact: true, ...filters };
return this.getAll().find(
(query) => matchQuery(defaultedFilters, query)
);
}
findAll(filters = {}) {
const queries = this.getAll();
return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
}
notify(event) {
notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(event);
});
});
}
onFocus() {
notifyManager.batch(() => {
this.getAll().forEach((query) => {
query.onFocus();
});
});
}
onOnline() {
notifyManager.batch(() => {
this.getAll().forEach((query) => {
query.onOnline();
});
});
}
};
export {
QueryCache
};
//# sourceMappingURL=queryCache.js.map
File diff suppressed because one or more lines are too long
+321
View File
@@ -0,0 +1,321 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/queryClient.ts
var queryClient_exports = {};
__export(queryClient_exports, {
QueryClient: () => QueryClient
});
module.exports = __toCommonJS(queryClient_exports);
var import_utils = require("./utils.cjs");
var import_queryCache = require("./queryCache.cjs");
var import_mutationCache = require("./mutationCache.cjs");
var import_focusManager = require("./focusManager.cjs");
var import_onlineManager = require("./onlineManager.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var QueryClient = class {
#queryCache;
#mutationCache;
#defaultOptions;
#queryDefaults;
#mutationDefaults;
#mountCount;
#unsubscribeFocus;
#unsubscribeOnline;
constructor(config = {}) {
this.#queryCache = config.queryCache || new import_queryCache.QueryCache();
this.#mutationCache = config.mutationCache || new import_mutationCache.MutationCache();
this.#defaultOptions = config.defaultOptions || {};
this.#queryDefaults = /* @__PURE__ */ new Map();
this.#mutationDefaults = /* @__PURE__ */ new Map();
this.#mountCount = 0;
}
mount() {
this.#mountCount++;
if (this.#mountCount !== 1) return;
this.#unsubscribeFocus = import_focusManager.focusManager.subscribe(async (focused) => {
if (focused) {
await this.resumePausedMutations();
this.#queryCache.onFocus();
}
});
this.#unsubscribeOnline = import_onlineManager.onlineManager.subscribe(async (online) => {
if (online) {
await this.resumePausedMutations();
this.#queryCache.onOnline();
}
});
}
unmount() {
this.#mountCount--;
if (this.#mountCount !== 0) return;
this.#unsubscribeFocus?.();
this.#unsubscribeFocus = void 0;
this.#unsubscribeOnline?.();
this.#unsubscribeOnline = void 0;
}
isFetching(filters) {
return this.#queryCache.findAll({ ...filters, fetchStatus: "fetching" }).length;
}
isMutating(filters) {
return this.#mutationCache.findAll({ ...filters, status: "pending" }).length;
}
/**
* Imperative (non-reactive) way to retrieve data for a QueryKey.
* Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.
*
* Hint: Do not use this function inside a component, because it won't receive updates.
* Use `useQuery` to create a `QueryObserver` that subscribes to changes.
*/
getQueryData(queryKey) {
const options = this.defaultQueryOptions({ queryKey });
return this.#queryCache.get(options.queryHash)?.state.data;
}
ensureQueryData(options) {
const defaultedOptions = this.defaultQueryOptions(options);
const query = this.#queryCache.build(this, defaultedOptions);
const cachedData = query.state.data;
if (cachedData === void 0) {
return this.fetchQuery(options);
}
if (options.revalidateIfStale && query.isStaleByTime((0, import_utils.resolveStaleTime)(defaultedOptions.staleTime, query))) {
void this.prefetchQuery(defaultedOptions);
}
return Promise.resolve(cachedData);
}
getQueriesData(filters) {
return this.#queryCache.findAll(filters).map(({ queryKey, state }) => {
const data = state.data;
return [queryKey, data];
});
}
setQueryData(queryKey, updater, options) {
const defaultedOptions = this.defaultQueryOptions({ queryKey });
const query = this.#queryCache.get(
defaultedOptions.queryHash
);
const prevData = query?.state.data;
const data = (0, import_utils.functionalUpdate)(updater, prevData);
if (data === void 0) {
return void 0;
}
return this.#queryCache.build(this, defaultedOptions).setData(data, { ...options, manual: true });
}
setQueriesData(filters, updater, options) {
return import_notifyManager.notifyManager.batch(
() => this.#queryCache.findAll(filters).map(({ queryKey }) => [
queryKey,
this.setQueryData(queryKey, updater, options)
])
);
}
getQueryState(queryKey) {
const options = this.defaultQueryOptions({ queryKey });
return this.#queryCache.get(
options.queryHash
)?.state;
}
removeQueries(filters) {
const queryCache = this.#queryCache;
import_notifyManager.notifyManager.batch(() => {
queryCache.findAll(filters).forEach((query) => {
queryCache.remove(query);
});
});
}
resetQueries(filters, options) {
const queryCache = this.#queryCache;
return import_notifyManager.notifyManager.batch(() => {
queryCache.findAll(filters).forEach((query) => {
query.reset();
});
return this.refetchQueries(
{
type: "active",
...filters
},
options
);
});
}
cancelQueries(filters, cancelOptions = {}) {
const defaultedCancelOptions = { revert: true, ...cancelOptions };
const promises = import_notifyManager.notifyManager.batch(
() => this.#queryCache.findAll(filters).map((query) => query.cancel(defaultedCancelOptions))
);
return Promise.all(promises).then(import_utils.noop).catch(import_utils.noop);
}
invalidateQueries(filters, options = {}) {
return import_notifyManager.notifyManager.batch(() => {
this.#queryCache.findAll(filters).forEach((query) => {
query.invalidate();
});
if (filters?.refetchType === "none") {
return Promise.resolve();
}
return this.refetchQueries(
{
...filters,
type: filters?.refetchType ?? filters?.type ?? "active"
},
options
);
});
}
refetchQueries(filters, options = {}) {
const fetchOptions = {
...options,
cancelRefetch: options.cancelRefetch ?? true
};
const promises = import_notifyManager.notifyManager.batch(
() => this.#queryCache.findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {
let promise = query.fetch(void 0, fetchOptions);
if (!fetchOptions.throwOnError) {
promise = promise.catch(import_utils.noop);
}
return query.state.fetchStatus === "paused" ? Promise.resolve() : promise;
})
);
return Promise.all(promises).then(import_utils.noop);
}
fetchQuery(options) {
const defaultedOptions = this.defaultQueryOptions(options);
if (defaultedOptions.retry === void 0) {
defaultedOptions.retry = false;
}
const query = this.#queryCache.build(this, defaultedOptions);
return query.isStaleByTime(
(0, import_utils.resolveStaleTime)(defaultedOptions.staleTime, query)
) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
}
prefetchQuery(options) {
return this.fetchQuery(options).then(import_utils.noop).catch(import_utils.noop);
}
fetchInfiniteQuery(options) {
options._type = "infinite";
return this.fetchQuery(options);
}
prefetchInfiniteQuery(options) {
return this.fetchInfiniteQuery(options).then(import_utils.noop).catch(import_utils.noop);
}
ensureInfiniteQueryData(options) {
options._type = "infinite";
return this.ensureQueryData(options);
}
resumePausedMutations() {
if (import_onlineManager.onlineManager.isOnline()) {
return this.#mutationCache.resumePausedMutations();
}
return Promise.resolve();
}
getQueryCache() {
return this.#queryCache;
}
getMutationCache() {
return this.#mutationCache;
}
getDefaultOptions() {
return this.#defaultOptions;
}
setDefaultOptions(options) {
this.#defaultOptions = options;
}
setQueryDefaults(queryKey, options) {
this.#queryDefaults.set((0, import_utils.hashKey)(queryKey), {
queryKey,
defaultOptions: options
});
}
getQueryDefaults(queryKey) {
const defaults = [...this.#queryDefaults.values()];
const result = {};
defaults.forEach((queryDefault) => {
if ((0, import_utils.partialMatchKey)(queryKey, queryDefault.queryKey)) {
Object.assign(result, queryDefault.defaultOptions);
}
});
return result;
}
setMutationDefaults(mutationKey, options) {
this.#mutationDefaults.set((0, import_utils.hashKey)(mutationKey), {
mutationKey,
defaultOptions: options
});
}
getMutationDefaults(mutationKey) {
const defaults = [...this.#mutationDefaults.values()];
const result = {};
defaults.forEach((queryDefault) => {
if ((0, import_utils.partialMatchKey)(mutationKey, queryDefault.mutationKey)) {
Object.assign(result, queryDefault.defaultOptions);
}
});
return result;
}
defaultQueryOptions(options) {
if (options._defaulted) {
return options;
}
const defaultedOptions = {
...this.#defaultOptions.queries,
...this.getQueryDefaults(options.queryKey),
...options,
_defaulted: true
};
if (!defaultedOptions.queryHash) {
defaultedOptions.queryHash = (0, import_utils.hashQueryKeyByOptions)(
defaultedOptions.queryKey,
defaultedOptions
);
}
if (defaultedOptions.refetchOnReconnect === void 0) {
defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
}
if (defaultedOptions.throwOnError === void 0) {
defaultedOptions.throwOnError = !!defaultedOptions.suspense;
}
if (!defaultedOptions.networkMode && defaultedOptions.persister) {
defaultedOptions.networkMode = "offlineFirst";
}
if (defaultedOptions.queryFn === import_utils.skipToken) {
defaultedOptions.enabled = false;
}
return defaultedOptions;
}
defaultMutationOptions(options) {
if (options?._defaulted) {
return options;
}
return {
...this.#defaultOptions.mutations,
...options?.mutationKey && this.getMutationDefaults(options.mutationKey),
...options,
_defaulted: true
};
}
clear() {
this.#queryCache.clear();
this.#mutationCache.clear();
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QueryClient
});
//# sourceMappingURL=queryClient.cjs.map
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
export { QueryClient_alias_1 as QueryClient } from './_tsup-dts-rollup.cjs';
+1
View File
@@ -0,0 +1 @@
export { QueryClient_alias_1 as QueryClient } from './_tsup-dts-rollup.js';
+304
View File
@@ -0,0 +1,304 @@
// src/queryClient.ts
import {
functionalUpdate,
hashKey,
hashQueryKeyByOptions,
noop,
partialMatchKey,
resolveStaleTime,
skipToken
} from "./utils.js";
import { QueryCache } from "./queryCache.js";
import { MutationCache } from "./mutationCache.js";
import { focusManager } from "./focusManager.js";
import { onlineManager } from "./onlineManager.js";
import { notifyManager } from "./notifyManager.js";
var QueryClient = class {
#queryCache;
#mutationCache;
#defaultOptions;
#queryDefaults;
#mutationDefaults;
#mountCount;
#unsubscribeFocus;
#unsubscribeOnline;
constructor(config = {}) {
this.#queryCache = config.queryCache || new QueryCache();
this.#mutationCache = config.mutationCache || new MutationCache();
this.#defaultOptions = config.defaultOptions || {};
this.#queryDefaults = /* @__PURE__ */ new Map();
this.#mutationDefaults = /* @__PURE__ */ new Map();
this.#mountCount = 0;
}
mount() {
this.#mountCount++;
if (this.#mountCount !== 1) return;
this.#unsubscribeFocus = focusManager.subscribe(async (focused) => {
if (focused) {
await this.resumePausedMutations();
this.#queryCache.onFocus();
}
});
this.#unsubscribeOnline = onlineManager.subscribe(async (online) => {
if (online) {
await this.resumePausedMutations();
this.#queryCache.onOnline();
}
});
}
unmount() {
this.#mountCount--;
if (this.#mountCount !== 0) return;
this.#unsubscribeFocus?.();
this.#unsubscribeFocus = void 0;
this.#unsubscribeOnline?.();
this.#unsubscribeOnline = void 0;
}
isFetching(filters) {
return this.#queryCache.findAll({ ...filters, fetchStatus: "fetching" }).length;
}
isMutating(filters) {
return this.#mutationCache.findAll({ ...filters, status: "pending" }).length;
}
/**
* Imperative (non-reactive) way to retrieve data for a QueryKey.
* Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.
*
* Hint: Do not use this function inside a component, because it won't receive updates.
* Use `useQuery` to create a `QueryObserver` that subscribes to changes.
*/
getQueryData(queryKey) {
const options = this.defaultQueryOptions({ queryKey });
return this.#queryCache.get(options.queryHash)?.state.data;
}
ensureQueryData(options) {
const defaultedOptions = this.defaultQueryOptions(options);
const query = this.#queryCache.build(this, defaultedOptions);
const cachedData = query.state.data;
if (cachedData === void 0) {
return this.fetchQuery(options);
}
if (options.revalidateIfStale && query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query))) {
void this.prefetchQuery(defaultedOptions);
}
return Promise.resolve(cachedData);
}
getQueriesData(filters) {
return this.#queryCache.findAll(filters).map(({ queryKey, state }) => {
const data = state.data;
return [queryKey, data];
});
}
setQueryData(queryKey, updater, options) {
const defaultedOptions = this.defaultQueryOptions({ queryKey });
const query = this.#queryCache.get(
defaultedOptions.queryHash
);
const prevData = query?.state.data;
const data = functionalUpdate(updater, prevData);
if (data === void 0) {
return void 0;
}
return this.#queryCache.build(this, defaultedOptions).setData(data, { ...options, manual: true });
}
setQueriesData(filters, updater, options) {
return notifyManager.batch(
() => this.#queryCache.findAll(filters).map(({ queryKey }) => [
queryKey,
this.setQueryData(queryKey, updater, options)
])
);
}
getQueryState(queryKey) {
const options = this.defaultQueryOptions({ queryKey });
return this.#queryCache.get(
options.queryHash
)?.state;
}
removeQueries(filters) {
const queryCache = this.#queryCache;
notifyManager.batch(() => {
queryCache.findAll(filters).forEach((query) => {
queryCache.remove(query);
});
});
}
resetQueries(filters, options) {
const queryCache = this.#queryCache;
return notifyManager.batch(() => {
queryCache.findAll(filters).forEach((query) => {
query.reset();
});
return this.refetchQueries(
{
type: "active",
...filters
},
options
);
});
}
cancelQueries(filters, cancelOptions = {}) {
const defaultedCancelOptions = { revert: true, ...cancelOptions };
const promises = notifyManager.batch(
() => this.#queryCache.findAll(filters).map((query) => query.cancel(defaultedCancelOptions))
);
return Promise.all(promises).then(noop).catch(noop);
}
invalidateQueries(filters, options = {}) {
return notifyManager.batch(() => {
this.#queryCache.findAll(filters).forEach((query) => {
query.invalidate();
});
if (filters?.refetchType === "none") {
return Promise.resolve();
}
return this.refetchQueries(
{
...filters,
type: filters?.refetchType ?? filters?.type ?? "active"
},
options
);
});
}
refetchQueries(filters, options = {}) {
const fetchOptions = {
...options,
cancelRefetch: options.cancelRefetch ?? true
};
const promises = notifyManager.batch(
() => this.#queryCache.findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {
let promise = query.fetch(void 0, fetchOptions);
if (!fetchOptions.throwOnError) {
promise = promise.catch(noop);
}
return query.state.fetchStatus === "paused" ? Promise.resolve() : promise;
})
);
return Promise.all(promises).then(noop);
}
fetchQuery(options) {
const defaultedOptions = this.defaultQueryOptions(options);
if (defaultedOptions.retry === void 0) {
defaultedOptions.retry = false;
}
const query = this.#queryCache.build(this, defaultedOptions);
return query.isStaleByTime(
resolveStaleTime(defaultedOptions.staleTime, query)
) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
}
prefetchQuery(options) {
return this.fetchQuery(options).then(noop).catch(noop);
}
fetchInfiniteQuery(options) {
options._type = "infinite";
return this.fetchQuery(options);
}
prefetchInfiniteQuery(options) {
return this.fetchInfiniteQuery(options).then(noop).catch(noop);
}
ensureInfiniteQueryData(options) {
options._type = "infinite";
return this.ensureQueryData(options);
}
resumePausedMutations() {
if (onlineManager.isOnline()) {
return this.#mutationCache.resumePausedMutations();
}
return Promise.resolve();
}
getQueryCache() {
return this.#queryCache;
}
getMutationCache() {
return this.#mutationCache;
}
getDefaultOptions() {
return this.#defaultOptions;
}
setDefaultOptions(options) {
this.#defaultOptions = options;
}
setQueryDefaults(queryKey, options) {
this.#queryDefaults.set(hashKey(queryKey), {
queryKey,
defaultOptions: options
});
}
getQueryDefaults(queryKey) {
const defaults = [...this.#queryDefaults.values()];
const result = {};
defaults.forEach((queryDefault) => {
if (partialMatchKey(queryKey, queryDefault.queryKey)) {
Object.assign(result, queryDefault.defaultOptions);
}
});
return result;
}
setMutationDefaults(mutationKey, options) {
this.#mutationDefaults.set(hashKey(mutationKey), {
mutationKey,
defaultOptions: options
});
}
getMutationDefaults(mutationKey) {
const defaults = [...this.#mutationDefaults.values()];
const result = {};
defaults.forEach((queryDefault) => {
if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {
Object.assign(result, queryDefault.defaultOptions);
}
});
return result;
}
defaultQueryOptions(options) {
if (options._defaulted) {
return options;
}
const defaultedOptions = {
...this.#defaultOptions.queries,
...this.getQueryDefaults(options.queryKey),
...options,
_defaulted: true
};
if (!defaultedOptions.queryHash) {
defaultedOptions.queryHash = hashQueryKeyByOptions(
defaultedOptions.queryKey,
defaultedOptions
);
}
if (defaultedOptions.refetchOnReconnect === void 0) {
defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
}
if (defaultedOptions.throwOnError === void 0) {
defaultedOptions.throwOnError = !!defaultedOptions.suspense;
}
if (!defaultedOptions.networkMode && defaultedOptions.persister) {
defaultedOptions.networkMode = "offlineFirst";
}
if (defaultedOptions.queryFn === skipToken) {
defaultedOptions.enabled = false;
}
return defaultedOptions;
}
defaultMutationOptions(options) {
if (options?._defaulted) {
return options;
}
return {
...this.#defaultOptions.mutations,
...options?.mutationKey && this.getMutationDefaults(options.mutationKey),
...options,
_defaulted: true
};
}
clear() {
this.#queryCache.clear();
this.#mutationCache.clear();
}
};
export {
QueryClient
};
//# sourceMappingURL=queryClient.js.map
File diff suppressed because one or more lines are too long
+489
View File
@@ -0,0 +1,489 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/queryObserver.ts
var queryObserver_exports = {};
__export(queryObserver_exports, {
QueryObserver: () => QueryObserver
});
module.exports = __toCommonJS(queryObserver_exports);
var import_focusManager = require("./focusManager.cjs");
var import_environmentManager = require("./environmentManager.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_query = require("./query.cjs");
var import_subscribable = require("./subscribable.cjs");
var import_thenable = require("./thenable.cjs");
var import_utils = require("./utils.cjs");
var import_timeoutManager = require("./timeoutManager.cjs");
var QueryObserver = class extends import_subscribable.Subscribable {
constructor(client, options) {
super();
this.options = options;
this.#client = client;
this.#selectError = null;
this.#currentThenable = (0, import_thenable.pendingThenable)();
this.bindMethods();
this.setOptions(options);
}
#client;
#currentQuery = void 0;
#currentQueryInitialState = void 0;
#currentResult = void 0;
#currentResultState;
#currentResultOptions;
#currentThenable;
#selectError;
#selectFn;
#selectResult;
// This property keeps track of the last query with defined data.
// It will be used to pass the previous data and query to the placeholder function between renders.
#lastQueryWithDefinedData;
#staleTimeoutId;
#refetchIntervalId;
#currentRefetchInterval;
#trackedProps = /* @__PURE__ */ new Set();
bindMethods() {
this.refetch = this.refetch.bind(this);
}
onSubscribe() {
if (this.listeners.size === 1) {
this.#currentQuery.addObserver(this);
if (shouldFetchOnMount(this.#currentQuery, this.options)) {
this.#executeFetch();
} else {
this.updateResult();
}
this.#updateTimers();
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
this.destroy();
}
}
shouldFetchOnReconnect() {
return shouldFetchOn(
this.#currentQuery,
this.options,
this.options.refetchOnReconnect
);
}
shouldFetchOnWindowFocus() {
return shouldFetchOn(
this.#currentQuery,
this.options,
this.options.refetchOnWindowFocus
);
}
destroy() {
this.listeners = /* @__PURE__ */ new Set();
this.#clearStaleTimeout();
this.#clearRefetchInterval();
this.#currentQuery.removeObserver(this);
}
setOptions(options) {
const prevOptions = this.options;
const prevQuery = this.#currentQuery;
this.options = this.#client.defaultQueryOptions(options);
if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof (0, import_utils.resolveQueryBoolean)(this.options.enabled, this.#currentQuery) !== "boolean") {
throw new Error(
"Expected enabled to be a boolean or a callback that returns a boolean"
);
}
this.#updateQuery();
this.#currentQuery.setOptions(this.options);
if (prevOptions._defaulted && !(0, import_utils.shallowEqualObjects)(this.options, prevOptions)) {
this.#client.getQueryCache().notify({
type: "observerOptionsUpdated",
query: this.#currentQuery,
observer: this
});
}
const mounted = this.hasListeners();
if (mounted && shouldFetchOptionally(
this.#currentQuery,
prevQuery,
this.options,
prevOptions
)) {
this.#executeFetch();
}
this.updateResult();
if (mounted && (this.#currentQuery !== prevQuery || (0, import_utils.resolveQueryBoolean)(this.options.enabled, this.#currentQuery) !== (0, import_utils.resolveQueryBoolean)(prevOptions.enabled, this.#currentQuery) || (0, import_utils.resolveStaleTime)(this.options.staleTime, this.#currentQuery) !== (0, import_utils.resolveStaleTime)(prevOptions.staleTime, this.#currentQuery))) {
this.#updateStaleTimeout();
}
const nextRefetchInterval = this.#computeRefetchInterval();
if (mounted && (this.#currentQuery !== prevQuery || (0, import_utils.resolveQueryBoolean)(this.options.enabled, this.#currentQuery) !== (0, import_utils.resolveQueryBoolean)(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) {
this.#updateRefetchInterval(nextRefetchInterval);
}
}
getOptimisticResult(options) {
const query = this.#client.getQueryCache().build(this.#client, options);
const result = this.createResult(query, options);
if (shouldAssignObserverCurrentProperties(this, result)) {
this.#currentResult = result;
this.#currentResultOptions = this.options;
this.#currentResultState = this.#currentQuery.state;
}
return result;
}
getCurrentResult() {
return this.#currentResult;
}
trackResult(result, onPropTracked) {
return new Proxy(result, {
get: (target, key) => {
this.trackProp(key);
onPropTracked?.(key);
if (key === "promise") {
this.trackProp("data");
if (!this.options.experimental_prefetchInRender && this.#currentThenable.status === "pending") {
this.#currentThenable.reject(
new Error(
"experimental_prefetchInRender feature flag is not enabled"
)
);
}
}
return Reflect.get(target, key);
}
});
}
trackProp(key) {
this.#trackedProps.add(key);
}
getCurrentQuery() {
return this.#currentQuery;
}
refetch({ ...options } = {}) {
return this.fetch({
...options
});
}
fetchOptimistic(options) {
const defaultedOptions = this.#client.defaultQueryOptions(options);
const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);
return query.fetch().then(() => this.createResult(query, defaultedOptions));
}
fetch(fetchOptions) {
return this.#executeFetch({
...fetchOptions,
cancelRefetch: fetchOptions.cancelRefetch ?? true
}).then(() => {
this.updateResult();
return this.#currentResult;
});
}
#executeFetch(fetchOptions) {
this.#updateQuery();
let promise = this.#currentQuery.fetch(
this.options,
fetchOptions
);
if (!fetchOptions?.throwOnError) {
promise = promise.catch(import_utils.noop);
}
return promise;
}
#updateStaleTimeout() {
this.#clearStaleTimeout();
const staleTime = (0, import_utils.resolveStaleTime)(
this.options.staleTime,
this.#currentQuery
);
if (import_environmentManager.environmentManager.isServer() || this.#currentResult.isStale || !(0, import_utils.isValidTimeout)(staleTime)) {
return;
}
const time = (0, import_utils.timeUntilStale)(this.#currentResult.dataUpdatedAt, staleTime);
const timeout = time + 1;
this.#staleTimeoutId = import_timeoutManager.timeoutManager.setTimeout(() => {
if (!this.#currentResult.isStale) {
this.updateResult();
}
}, timeout);
}
#computeRefetchInterval() {
return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(this.#currentQuery) : this.options.refetchInterval) ?? false;
}
#updateRefetchInterval(nextInterval) {
this.#clearRefetchInterval();
this.#currentRefetchInterval = nextInterval;
if (import_environmentManager.environmentManager.isServer() || (0, import_utils.resolveQueryBoolean)(this.options.enabled, this.#currentQuery) === false || !(0, import_utils.isValidTimeout)(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {
return;
}
this.#refetchIntervalId = import_timeoutManager.timeoutManager.setInterval(() => {
if (this.options.refetchIntervalInBackground || import_focusManager.focusManager.isFocused()) {
this.#executeFetch();
}
}, this.#currentRefetchInterval);
}
#updateTimers() {
this.#updateStaleTimeout();
this.#updateRefetchInterval(this.#computeRefetchInterval());
}
#clearStaleTimeout() {
if (this.#staleTimeoutId !== void 0) {
import_timeoutManager.timeoutManager.clearTimeout(this.#staleTimeoutId);
this.#staleTimeoutId = void 0;
}
}
#clearRefetchInterval() {
if (this.#refetchIntervalId !== void 0) {
import_timeoutManager.timeoutManager.clearInterval(this.#refetchIntervalId);
this.#refetchIntervalId = void 0;
}
}
createResult(query, options) {
const prevQuery = this.#currentQuery;
const prevOptions = this.options;
const prevResult = this.#currentResult;
const prevResultState = this.#currentResultState;
const prevResultOptions = this.#currentResultOptions;
const queryChange = query !== prevQuery;
const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;
const { state } = query;
let newState = { ...state };
let isPlaceholderData = false;
let data;
if (options._optimisticResults) {
const mounted = this.hasListeners();
const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
if (fetchOnMount || fetchOptionally) {
newState = {
...newState,
...(0, import_query.fetchState)(state.data, query.options)
};
}
if (options._optimisticResults === "isRestoring") {
newState.fetchStatus = "idle";
}
}
let { error, errorUpdatedAt, status } = newState;
data = newState.data;
let skipSelect = false;
if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
let placeholderData;
if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {
placeholderData = prevResult.data;
skipSelect = true;
} else {
placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
this.#lastQueryWithDefinedData?.state.data,
this.#lastQueryWithDefinedData
) : options.placeholderData;
}
if (placeholderData !== void 0) {
status = "success";
data = (0, import_utils.replaceData)(
prevResult?.data,
placeholderData,
options
);
isPlaceholderData = true;
}
}
if (options.select && data !== void 0 && !skipSelect) {
if (prevResult && data === prevResultState?.data && options.select === this.#selectFn) {
data = this.#selectResult;
} else {
try {
this.#selectFn = options.select;
data = options.select(data);
data = (0, import_utils.replaceData)(prevResult?.data, data, options);
this.#selectResult = data;
this.#selectError = null;
} catch (selectError) {
this.#selectError = selectError;
}
}
}
if (this.#selectError) {
error = this.#selectError;
data = this.#selectResult;
errorUpdatedAt = Date.now();
status = "error";
}
const isFetching = newState.fetchStatus === "fetching";
const isPending = status === "pending";
const isError = status === "error";
const isLoading = isPending && isFetching;
const hasData = data !== void 0;
const result = {
status,
fetchStatus: newState.fetchStatus,
isPending,
isSuccess: status === "success",
isError,
isInitialLoading: isLoading,
isLoading,
data,
dataUpdatedAt: newState.dataUpdatedAt,
error,
errorUpdatedAt,
failureCount: newState.fetchFailureCount,
failureReason: newState.fetchFailureReason,
errorUpdateCount: newState.errorUpdateCount,
isFetched: query.isFetched(),
isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,
isFetching,
isRefetching: isFetching && !isPending,
isLoadingError: isError && !hasData,
isPaused: newState.fetchStatus === "paused",
isPlaceholderData,
isRefetchError: isError && hasData,
isStale: isStale(query, options),
refetch: this.refetch,
promise: this.#currentThenable,
isEnabled: (0, import_utils.resolveQueryBoolean)(options.enabled, query) !== false
};
const nextResult = result;
if (this.options.experimental_prefetchInRender) {
const hasResultData = nextResult.data !== void 0;
const isErrorWithoutData = nextResult.status === "error" && !hasResultData;
const finalizeThenableIfPossible = (thenable) => {
if (isErrorWithoutData) {
thenable.reject(nextResult.error);
} else if (hasResultData) {
thenable.resolve(nextResult.data);
}
};
const recreateThenable = () => {
const pending = this.#currentThenable = nextResult.promise = (0, import_thenable.pendingThenable)();
finalizeThenableIfPossible(pending);
};
const prevThenable = this.#currentThenable;
switch (prevThenable.status) {
case "pending":
if (query.queryHash === prevQuery.queryHash) {
finalizeThenableIfPossible(prevThenable);
}
break;
case "fulfilled":
if (isErrorWithoutData || nextResult.data !== prevThenable.value) {
recreateThenable();
}
break;
case "rejected":
if (!isErrorWithoutData || nextResult.error !== prevThenable.reason) {
recreateThenable();
}
break;
}
}
return nextResult;
}
updateResult() {
const prevResult = this.#currentResult;
const nextResult = this.createResult(this.#currentQuery, this.options);
this.#currentResultState = this.#currentQuery.state;
this.#currentResultOptions = this.options;
if (this.#currentResultState.data !== void 0) {
this.#lastQueryWithDefinedData = this.#currentQuery;
}
if ((0, import_utils.shallowEqualObjects)(nextResult, prevResult)) {
return;
}
this.#currentResult = nextResult;
const shouldNotifyListeners = () => {
if (!prevResult) {
return true;
}
const { notifyOnChangeProps } = this.options;
const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !this.#trackedProps.size) {
return true;
}
const includedProps = new Set(
notifyOnChangePropsValue ?? this.#trackedProps
);
if (this.options.throwOnError) {
includedProps.add("error");
}
return Object.keys(this.#currentResult).some((key) => {
const typedKey = key;
const changed = this.#currentResult[typedKey] !== prevResult[typedKey];
return changed && includedProps.has(typedKey);
});
};
this.#notify({ listeners: shouldNotifyListeners() });
}
#updateQuery() {
const query = this.#client.getQueryCache().build(this.#client, this.options);
if (query === this.#currentQuery) {
return;
}
const prevQuery = this.#currentQuery;
this.#currentQuery = query;
this.#currentQueryInitialState = query.state;
if (this.hasListeners()) {
prevQuery?.removeObserver(this);
query.addObserver(this);
}
}
onQueryUpdate() {
this.updateResult();
if (this.hasListeners()) {
this.#updateTimers();
}
}
#notify(notifyOptions) {
import_notifyManager.notifyManager.batch(() => {
if (notifyOptions.listeners) {
this.listeners.forEach((listener) => {
listener(this.#currentResult);
});
}
this.#client.getQueryCache().notify({
query: this.#currentQuery,
type: "observerResultsUpdated"
});
});
}
};
function shouldLoadOnMount(query, options) {
return (0, import_utils.resolveQueryBoolean)(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && (0, import_utils.resolveQueryBoolean)(options.retryOnMount, query) === false);
}
function shouldFetchOnMount(query, options) {
return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);
}
function shouldFetchOn(query, options, field) {
if ((0, import_utils.resolveQueryBoolean)(options.enabled, query) !== false && (0, import_utils.resolveStaleTime)(options.staleTime, query) !== "static") {
const value = typeof field === "function" ? field(query) : field;
return value === "always" || value !== false && isStale(query, options);
}
return false;
}
function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
return (query !== prevQuery || (0, import_utils.resolveQueryBoolean)(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
}
function isStale(query, options) {
return (0, import_utils.resolveQueryBoolean)(options.enabled, query) !== false && query.isStaleByTime((0, import_utils.resolveStaleTime)(options.staleTime, query));
}
function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
if (!(0, import_utils.shallowEqualObjects)(observer.getCurrentResult(), optimisticResult)) {
return true;
}
return false;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QueryObserver
});
//# sourceMappingURL=queryObserver.cjs.map
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
export { QueryObserver_alias_1 as QueryObserver } from './_tsup-dts-rollup.cjs';
+1
View File
@@ -0,0 +1 @@
export { QueryObserver_alias_1 as QueryObserver } from './_tsup-dts-rollup.js';
+472
View File
@@ -0,0 +1,472 @@
// src/queryObserver.ts
import { focusManager } from "./focusManager.js";
import { environmentManager } from "./environmentManager.js";
import { notifyManager } from "./notifyManager.js";
import { fetchState } from "./query.js";
import { Subscribable } from "./subscribable.js";
import { pendingThenable } from "./thenable.js";
import {
isValidTimeout,
noop,
replaceData,
resolveQueryBoolean,
resolveStaleTime,
shallowEqualObjects,
timeUntilStale
} from "./utils.js";
import { timeoutManager } from "./timeoutManager.js";
var QueryObserver = class extends Subscribable {
constructor(client, options) {
super();
this.options = options;
this.#client = client;
this.#selectError = null;
this.#currentThenable = pendingThenable();
this.bindMethods();
this.setOptions(options);
}
#client;
#currentQuery = void 0;
#currentQueryInitialState = void 0;
#currentResult = void 0;
#currentResultState;
#currentResultOptions;
#currentThenable;
#selectError;
#selectFn;
#selectResult;
// This property keeps track of the last query with defined data.
// It will be used to pass the previous data and query to the placeholder function between renders.
#lastQueryWithDefinedData;
#staleTimeoutId;
#refetchIntervalId;
#currentRefetchInterval;
#trackedProps = /* @__PURE__ */ new Set();
bindMethods() {
this.refetch = this.refetch.bind(this);
}
onSubscribe() {
if (this.listeners.size === 1) {
this.#currentQuery.addObserver(this);
if (shouldFetchOnMount(this.#currentQuery, this.options)) {
this.#executeFetch();
} else {
this.updateResult();
}
this.#updateTimers();
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
this.destroy();
}
}
shouldFetchOnReconnect() {
return shouldFetchOn(
this.#currentQuery,
this.options,
this.options.refetchOnReconnect
);
}
shouldFetchOnWindowFocus() {
return shouldFetchOn(
this.#currentQuery,
this.options,
this.options.refetchOnWindowFocus
);
}
destroy() {
this.listeners = /* @__PURE__ */ new Set();
this.#clearStaleTimeout();
this.#clearRefetchInterval();
this.#currentQuery.removeObserver(this);
}
setOptions(options) {
const prevOptions = this.options;
const prevQuery = this.#currentQuery;
this.options = this.#client.defaultQueryOptions(options);
if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== "boolean") {
throw new Error(
"Expected enabled to be a boolean or a callback that returns a boolean"
);
}
this.#updateQuery();
this.#currentQuery.setOptions(this.options);
if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) {
this.#client.getQueryCache().notify({
type: "observerOptionsUpdated",
query: this.#currentQuery,
observer: this
});
}
const mounted = this.hasListeners();
if (mounted && shouldFetchOptionally(
this.#currentQuery,
prevQuery,
this.options,
prevOptions
)) {
this.#executeFetch();
}
this.updateResult();
if (mounted && (this.#currentQuery !== prevQuery || resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== resolveQueryBoolean(prevOptions.enabled, this.#currentQuery) || resolveStaleTime(this.options.staleTime, this.#currentQuery) !== resolveStaleTime(prevOptions.staleTime, this.#currentQuery))) {
this.#updateStaleTimeout();
}
const nextRefetchInterval = this.#computeRefetchInterval();
if (mounted && (this.#currentQuery !== prevQuery || resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== resolveQueryBoolean(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) {
this.#updateRefetchInterval(nextRefetchInterval);
}
}
getOptimisticResult(options) {
const query = this.#client.getQueryCache().build(this.#client, options);
const result = this.createResult(query, options);
if (shouldAssignObserverCurrentProperties(this, result)) {
this.#currentResult = result;
this.#currentResultOptions = this.options;
this.#currentResultState = this.#currentQuery.state;
}
return result;
}
getCurrentResult() {
return this.#currentResult;
}
trackResult(result, onPropTracked) {
return new Proxy(result, {
get: (target, key) => {
this.trackProp(key);
onPropTracked?.(key);
if (key === "promise") {
this.trackProp("data");
if (!this.options.experimental_prefetchInRender && this.#currentThenable.status === "pending") {
this.#currentThenable.reject(
new Error(
"experimental_prefetchInRender feature flag is not enabled"
)
);
}
}
return Reflect.get(target, key);
}
});
}
trackProp(key) {
this.#trackedProps.add(key);
}
getCurrentQuery() {
return this.#currentQuery;
}
refetch({ ...options } = {}) {
return this.fetch({
...options
});
}
fetchOptimistic(options) {
const defaultedOptions = this.#client.defaultQueryOptions(options);
const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);
return query.fetch().then(() => this.createResult(query, defaultedOptions));
}
fetch(fetchOptions) {
return this.#executeFetch({
...fetchOptions,
cancelRefetch: fetchOptions.cancelRefetch ?? true
}).then(() => {
this.updateResult();
return this.#currentResult;
});
}
#executeFetch(fetchOptions) {
this.#updateQuery();
let promise = this.#currentQuery.fetch(
this.options,
fetchOptions
);
if (!fetchOptions?.throwOnError) {
promise = promise.catch(noop);
}
return promise;
}
#updateStaleTimeout() {
this.#clearStaleTimeout();
const staleTime = resolveStaleTime(
this.options.staleTime,
this.#currentQuery
);
if (environmentManager.isServer() || this.#currentResult.isStale || !isValidTimeout(staleTime)) {
return;
}
const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime);
const timeout = time + 1;
this.#staleTimeoutId = timeoutManager.setTimeout(() => {
if (!this.#currentResult.isStale) {
this.updateResult();
}
}, timeout);
}
#computeRefetchInterval() {
return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(this.#currentQuery) : this.options.refetchInterval) ?? false;
}
#updateRefetchInterval(nextInterval) {
this.#clearRefetchInterval();
this.#currentRefetchInterval = nextInterval;
if (environmentManager.isServer() || resolveQueryBoolean(this.options.enabled, this.#currentQuery) === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {
return;
}
this.#refetchIntervalId = timeoutManager.setInterval(() => {
if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
this.#executeFetch();
}
}, this.#currentRefetchInterval);
}
#updateTimers() {
this.#updateStaleTimeout();
this.#updateRefetchInterval(this.#computeRefetchInterval());
}
#clearStaleTimeout() {
if (this.#staleTimeoutId !== void 0) {
timeoutManager.clearTimeout(this.#staleTimeoutId);
this.#staleTimeoutId = void 0;
}
}
#clearRefetchInterval() {
if (this.#refetchIntervalId !== void 0) {
timeoutManager.clearInterval(this.#refetchIntervalId);
this.#refetchIntervalId = void 0;
}
}
createResult(query, options) {
const prevQuery = this.#currentQuery;
const prevOptions = this.options;
const prevResult = this.#currentResult;
const prevResultState = this.#currentResultState;
const prevResultOptions = this.#currentResultOptions;
const queryChange = query !== prevQuery;
const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;
const { state } = query;
let newState = { ...state };
let isPlaceholderData = false;
let data;
if (options._optimisticResults) {
const mounted = this.hasListeners();
const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
if (fetchOnMount || fetchOptionally) {
newState = {
...newState,
...fetchState(state.data, query.options)
};
}
if (options._optimisticResults === "isRestoring") {
newState.fetchStatus = "idle";
}
}
let { error, errorUpdatedAt, status } = newState;
data = newState.data;
let skipSelect = false;
if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
let placeholderData;
if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {
placeholderData = prevResult.data;
skipSelect = true;
} else {
placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
this.#lastQueryWithDefinedData?.state.data,
this.#lastQueryWithDefinedData
) : options.placeholderData;
}
if (placeholderData !== void 0) {
status = "success";
data = replaceData(
prevResult?.data,
placeholderData,
options
);
isPlaceholderData = true;
}
}
if (options.select && data !== void 0 && !skipSelect) {
if (prevResult && data === prevResultState?.data && options.select === this.#selectFn) {
data = this.#selectResult;
} else {
try {
this.#selectFn = options.select;
data = options.select(data);
data = replaceData(prevResult?.data, data, options);
this.#selectResult = data;
this.#selectError = null;
} catch (selectError) {
this.#selectError = selectError;
}
}
}
if (this.#selectError) {
error = this.#selectError;
data = this.#selectResult;
errorUpdatedAt = Date.now();
status = "error";
}
const isFetching = newState.fetchStatus === "fetching";
const isPending = status === "pending";
const isError = status === "error";
const isLoading = isPending && isFetching;
const hasData = data !== void 0;
const result = {
status,
fetchStatus: newState.fetchStatus,
isPending,
isSuccess: status === "success",
isError,
isInitialLoading: isLoading,
isLoading,
data,
dataUpdatedAt: newState.dataUpdatedAt,
error,
errorUpdatedAt,
failureCount: newState.fetchFailureCount,
failureReason: newState.fetchFailureReason,
errorUpdateCount: newState.errorUpdateCount,
isFetched: query.isFetched(),
isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,
isFetching,
isRefetching: isFetching && !isPending,
isLoadingError: isError && !hasData,
isPaused: newState.fetchStatus === "paused",
isPlaceholderData,
isRefetchError: isError && hasData,
isStale: isStale(query, options),
refetch: this.refetch,
promise: this.#currentThenable,
isEnabled: resolveQueryBoolean(options.enabled, query) !== false
};
const nextResult = result;
if (this.options.experimental_prefetchInRender) {
const hasResultData = nextResult.data !== void 0;
const isErrorWithoutData = nextResult.status === "error" && !hasResultData;
const finalizeThenableIfPossible = (thenable) => {
if (isErrorWithoutData) {
thenable.reject(nextResult.error);
} else if (hasResultData) {
thenable.resolve(nextResult.data);
}
};
const recreateThenable = () => {
const pending = this.#currentThenable = nextResult.promise = pendingThenable();
finalizeThenableIfPossible(pending);
};
const prevThenable = this.#currentThenable;
switch (prevThenable.status) {
case "pending":
if (query.queryHash === prevQuery.queryHash) {
finalizeThenableIfPossible(prevThenable);
}
break;
case "fulfilled":
if (isErrorWithoutData || nextResult.data !== prevThenable.value) {
recreateThenable();
}
break;
case "rejected":
if (!isErrorWithoutData || nextResult.error !== prevThenable.reason) {
recreateThenable();
}
break;
}
}
return nextResult;
}
updateResult() {
const prevResult = this.#currentResult;
const nextResult = this.createResult(this.#currentQuery, this.options);
this.#currentResultState = this.#currentQuery.state;
this.#currentResultOptions = this.options;
if (this.#currentResultState.data !== void 0) {
this.#lastQueryWithDefinedData = this.#currentQuery;
}
if (shallowEqualObjects(nextResult, prevResult)) {
return;
}
this.#currentResult = nextResult;
const shouldNotifyListeners = () => {
if (!prevResult) {
return true;
}
const { notifyOnChangeProps } = this.options;
const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !this.#trackedProps.size) {
return true;
}
const includedProps = new Set(
notifyOnChangePropsValue ?? this.#trackedProps
);
if (this.options.throwOnError) {
includedProps.add("error");
}
return Object.keys(this.#currentResult).some((key) => {
const typedKey = key;
const changed = this.#currentResult[typedKey] !== prevResult[typedKey];
return changed && includedProps.has(typedKey);
});
};
this.#notify({ listeners: shouldNotifyListeners() });
}
#updateQuery() {
const query = this.#client.getQueryCache().build(this.#client, this.options);
if (query === this.#currentQuery) {
return;
}
const prevQuery = this.#currentQuery;
this.#currentQuery = query;
this.#currentQueryInitialState = query.state;
if (this.hasListeners()) {
prevQuery?.removeObserver(this);
query.addObserver(this);
}
}
onQueryUpdate() {
this.updateResult();
if (this.hasListeners()) {
this.#updateTimers();
}
}
#notify(notifyOptions) {
notifyManager.batch(() => {
if (notifyOptions.listeners) {
this.listeners.forEach((listener) => {
listener(this.#currentResult);
});
}
this.#client.getQueryCache().notify({
query: this.#currentQuery,
type: "observerResultsUpdated"
});
});
}
};
function shouldLoadOnMount(query, options) {
return resolveQueryBoolean(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && resolveQueryBoolean(options.retryOnMount, query) === false);
}
function shouldFetchOnMount(query, options) {
return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);
}
function shouldFetchOn(query, options, field) {
if (resolveQueryBoolean(options.enabled, query) !== false && resolveStaleTime(options.staleTime, query) !== "static") {
const value = typeof field === "function" ? field(query) : field;
return value === "always" || value !== false && isStale(query, options);
}
return false;
}
function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
return (query !== prevQuery || resolveQueryBoolean(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
}
function isStale(query, options) {
return resolveQueryBoolean(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query));
}
function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {
return true;
}
return false;
}
export {
QueryObserver
};
//# sourceMappingURL=queryObserver.js.map
File diff suppressed because one or more lines are too long
+59
View File
@@ -0,0 +1,59 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/removable.ts
var removable_exports = {};
__export(removable_exports, {
Removable: () => Removable
});
module.exports = __toCommonJS(removable_exports);
var import_timeoutManager = require("./timeoutManager.cjs");
var import_environmentManager = require("./environmentManager.cjs");
var import_utils = require("./utils.cjs");
var Removable = class {
#gcTimeout;
destroy() {
this.clearGcTimeout();
}
scheduleGc() {
this.clearGcTimeout();
if ((0, import_utils.isValidTimeout)(this.gcTime)) {
this.#gcTimeout = import_timeoutManager.timeoutManager.setTimeout(() => {
this.optionalRemove();
}, this.gcTime);
}
}
updateGcTime(newGcTime) {
this.gcTime = Math.max(
this.gcTime || 0,
newGcTime ?? (import_environmentManager.environmentManager.isServer() ? Infinity : 5 * 60 * 1e3)
);
}
clearGcTimeout() {
if (this.#gcTimeout !== void 0) {
import_timeoutManager.timeoutManager.clearTimeout(this.#gcTimeout);
this.#gcTimeout = void 0;
}
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Removable
});
//# sourceMappingURL=removable.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/removable.ts"],"sourcesContent":["import { timeoutManager } from './timeoutManager'\nimport { environmentManager } from './environmentManager'\nimport { isValidTimeout } from './utils'\nimport type { ManagedTimerId } from './timeoutManager'\n\nexport abstract class Removable {\n gcTime!: number\n #gcTimeout?: ManagedTimerId\n\n destroy(): void {\n this.clearGcTimeout()\n }\n\n protected scheduleGc(): void {\n this.clearGcTimeout()\n\n if (isValidTimeout(this.gcTime)) {\n this.#gcTimeout = timeoutManager.setTimeout(() => {\n this.optionalRemove()\n }, this.gcTime)\n }\n }\n\n protected updateGcTime(newGcTime: number | undefined): void {\n // Default to 5 minutes (Infinity for server-side) if no gcTime is set\n this.gcTime = Math.max(\n this.gcTime || 0,\n newGcTime ?? (environmentManager.isServer() ? Infinity : 5 * 60 * 1000),\n )\n }\n\n protected clearGcTimeout() {\n if (this.#gcTimeout !== undefined) {\n timeoutManager.clearTimeout(this.#gcTimeout)\n this.#gcTimeout = undefined\n }\n }\n\n protected abstract optionalRemove(): void\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAA+B;AAC/B,gCAAmC;AACnC,mBAA+B;AAGxB,IAAe,YAAf,MAAyB;AAAA,EAE9B;AAAA,EAEA,UAAgB;AACd,SAAK,eAAe;AAAA,EACtB;AAAA,EAEU,aAAmB;AAC3B,SAAK,eAAe;AAEpB,YAAI,6BAAe,KAAK,MAAM,GAAG;AAC/B,WAAK,aAAa,qCAAe,WAAW,MAAM;AAChD,aAAK,eAAe;AAAA,MACtB,GAAG,KAAK,MAAM;AAAA,IAChB;AAAA,EACF;AAAA,EAEU,aAAa,WAAqC;AAE1D,SAAK,SAAS,KAAK;AAAA,MACjB,KAAK,UAAU;AAAA,MACf,cAAc,6CAAmB,SAAS,IAAI,WAAW,IAAI,KAAK;AAAA,IACpE;AAAA,EACF;AAAA,EAEU,iBAAiB;AACzB,QAAI,KAAK,eAAe,QAAW;AACjC,2CAAe,aAAa,KAAK,UAAU;AAC3C,WAAK,aAAa;AAAA,IACpB;AAAA,EACF;AAGF;","names":[]}

Some files were not shown because too many files have changed in this diff Show More