@tanstack/query-core
Advanced tools
Comparing version 5.0.0-alpha.5 to 5.0.0-alpha.6
@@ -0,11 +1,24 @@ | ||
import { classPrivateFieldLooseBase as _classPrivateFieldLooseBase, classPrivateFieldLooseKey as _classPrivateFieldLooseKey } from './_virtual/_rollupPluginBabelHelpers.esm.js'; | ||
import { Subscribable } from './subscribable.esm.js'; | ||
import { isServer } from './utils.esm.js'; | ||
var _focused = /*#__PURE__*/_classPrivateFieldLooseKey("focused"); | ||
var _cleanup = /*#__PURE__*/_classPrivateFieldLooseKey("cleanup"); | ||
var _setup = /*#__PURE__*/_classPrivateFieldLooseKey("setup"); | ||
class FocusManager extends Subscribable { | ||
#focused; | ||
#cleanup; | ||
#setup; | ||
constructor() { | ||
super(); | ||
this.#setup = onFocus => { | ||
Object.defineProperty(this, _focused, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _cleanup, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _setup, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_classPrivateFieldLooseBase(this, _setup)[_setup] = onFocus => { | ||
// addEventListener does not exist in React Native, but window does | ||
@@ -26,4 +39,4 @@ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition | ||
onSubscribe() { | ||
if (!this.#cleanup) { | ||
this.setEventListener(this.#setup); | ||
if (!_classPrivateFieldLooseBase(this, _cleanup)[_cleanup]) { | ||
this.setEventListener(_classPrivateFieldLooseBase(this, _setup)[_setup]); | ||
} | ||
@@ -33,10 +46,12 @@ } | ||
if (!this.hasListeners()) { | ||
this.#cleanup?.(); | ||
this.#cleanup = undefined; | ||
var _classPrivateFieldLoo, _classPrivateFieldLoo2; | ||
(_classPrivateFieldLoo = (_classPrivateFieldLoo2 = _classPrivateFieldLooseBase(this, _cleanup))[_cleanup]) == null ? void 0 : _classPrivateFieldLoo.call(_classPrivateFieldLoo2); | ||
_classPrivateFieldLooseBase(this, _cleanup)[_cleanup] = undefined; | ||
} | ||
} | ||
setEventListener(setup) { | ||
this.#setup = setup; | ||
this.#cleanup?.(); | ||
this.#cleanup = setup(focused => { | ||
var _classPrivateFieldLoo3, _classPrivateFieldLoo4; | ||
_classPrivateFieldLooseBase(this, _setup)[_setup] = setup; | ||
(_classPrivateFieldLoo3 = (_classPrivateFieldLoo4 = _classPrivateFieldLooseBase(this, _cleanup))[_cleanup]) == null ? void 0 : _classPrivateFieldLoo3.call(_classPrivateFieldLoo4); | ||
_classPrivateFieldLooseBase(this, _cleanup)[_cleanup] = setup(focused => { | ||
if (typeof focused === 'boolean') { | ||
@@ -50,3 +65,3 @@ this.setFocused(focused); | ||
setFocused(focused) { | ||
this.#focused = focused; | ||
_classPrivateFieldLooseBase(this, _focused)[_focused] = focused; | ||
if (focused) { | ||
@@ -62,4 +77,5 @@ this.onFocus(); | ||
isFocused() { | ||
if (typeof this.#focused === 'boolean') { | ||
return this.#focused; | ||
var _globalThis$document; | ||
if (typeof _classPrivateFieldLooseBase(this, _focused)[_focused] === 'boolean') { | ||
return _classPrivateFieldLooseBase(this, _focused)[_focused]; | ||
} | ||
@@ -69,3 +85,3 @@ | ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition | ||
return globalThis.document?.visibilityState !== 'hidden'; | ||
return ((_globalThis$document = globalThis.document) == null ? void 0 : _globalThis$document.visibilityState) !== 'hidden'; | ||
} | ||
@@ -72,0 +88,0 @@ } |
'use strict'; | ||
var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js'); | ||
var subscribable = require('./subscribable.js'); | ||
var utils = require('./utils.js'); | ||
var _focused = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("focused"); | ||
var _cleanup = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("cleanup"); | ||
var _setup = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("setup"); | ||
class FocusManager extends subscribable.Subscribable { | ||
#focused; | ||
#cleanup; | ||
#setup; | ||
constructor() { | ||
super(); | ||
this.#setup = onFocus => { | ||
Object.defineProperty(this, _focused, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _cleanup, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _setup, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _setup)[_setup] = onFocus => { | ||
// addEventListener does not exist in React Native, but window does | ||
@@ -28,4 +41,4 @@ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition | ||
onSubscribe() { | ||
if (!this.#cleanup) { | ||
this.setEventListener(this.#setup); | ||
if (!_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cleanup)[_cleanup]) { | ||
this.setEventListener(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _setup)[_setup]); | ||
} | ||
@@ -35,10 +48,12 @@ } | ||
if (!this.hasListeners()) { | ||
this.#cleanup?.(); | ||
this.#cleanup = undefined; | ||
var _classPrivateFieldLoo, _classPrivateFieldLoo2; | ||
(_classPrivateFieldLoo = (_classPrivateFieldLoo2 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cleanup))[_cleanup]) == null ? void 0 : _classPrivateFieldLoo.call(_classPrivateFieldLoo2); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cleanup)[_cleanup] = undefined; | ||
} | ||
} | ||
setEventListener(setup) { | ||
this.#setup = setup; | ||
this.#cleanup?.(); | ||
this.#cleanup = setup(focused => { | ||
var _classPrivateFieldLoo3, _classPrivateFieldLoo4; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _setup)[_setup] = setup; | ||
(_classPrivateFieldLoo3 = (_classPrivateFieldLoo4 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cleanup))[_cleanup]) == null ? void 0 : _classPrivateFieldLoo3.call(_classPrivateFieldLoo4); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cleanup)[_cleanup] = setup(focused => { | ||
if (typeof focused === 'boolean') { | ||
@@ -52,3 +67,3 @@ this.setFocused(focused); | ||
setFocused(focused) { | ||
this.#focused = focused; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _focused)[_focused] = focused; | ||
if (focused) { | ||
@@ -64,4 +79,5 @@ this.onFocus(); | ||
isFocused() { | ||
if (typeof this.#focused === 'boolean') { | ||
return this.#focused; | ||
var _globalThis$document; | ||
if (typeof _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _focused)[_focused] === 'boolean') { | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _focused)[_focused]; | ||
} | ||
@@ -71,3 +87,3 @@ | ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition | ||
return globalThis.document?.visibilityState !== 'hidden'; | ||
return ((_globalThis$document = globalThis.document) == null ? void 0 : _globalThis$document.visibilityState) !== 'hidden'; | ||
} | ||
@@ -74,0 +90,0 @@ } |
@@ -65,4 +65,5 @@ // TYPES | ||
mutations.forEach(dehydratedMutation => { | ||
var _options$defaultOptio; | ||
mutationCache.build(client, { | ||
...options?.defaultOptions?.mutations, | ||
...(options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations), | ||
mutationKey: dehydratedMutation.mutationKey | ||
@@ -72,2 +73,3 @@ }, dehydratedMutation.state); | ||
queries.forEach(dehydratedQuery => { | ||
var _options$defaultOptio2; | ||
const query = queryCache.get(dehydratedQuery.queryHash); | ||
@@ -92,3 +94,3 @@ | ||
queryCache.build(client, { | ||
...options?.defaultOptions?.queries, | ||
...(options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries), | ||
queryKey: dehydratedQuery.queryKey, | ||
@@ -95,0 +97,0 @@ queryHash: dehydratedQuery.queryHash |
@@ -67,4 +67,5 @@ 'use strict'; | ||
mutations.forEach(dehydratedMutation => { | ||
var _options$defaultOptio; | ||
mutationCache.build(client, { | ||
...options?.defaultOptions?.mutations, | ||
...(options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations), | ||
mutationKey: dehydratedMutation.mutationKey | ||
@@ -74,2 +75,3 @@ }, dehydratedMutation.state); | ||
queries.forEach(dehydratedQuery => { | ||
var _options$defaultOptio2; | ||
const query = queryCache.get(dehydratedQuery.queryHash); | ||
@@ -94,3 +96,3 @@ | ||
queryCache.build(client, { | ||
...options?.defaultOptions?.queries, | ||
...(options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries), | ||
queryKey: dehydratedQuery.queryKey, | ||
@@ -97,0 +99,0 @@ queryHash: dehydratedQuery.queryHash |
@@ -7,6 +7,7 @@ import { addToStart, addToEnd } from './utils.esm.js'; | ||
context.fetchFn = async () => { | ||
var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$state$data, _context$state$data2; | ||
const options = context.options; | ||
const direction = context.fetchOptions?.meta?.fetchMore?.direction; | ||
const oldPages = context.state.data?.pages || []; | ||
const oldPageParams = context.state.data?.pageParams || []; | ||
const direction = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : (_context$fetchOptions3 = _context$fetchOptions2.fetchMore) == null ? void 0 : _context$fetchOptions3.direction; | ||
const oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || []; | ||
const oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || []; | ||
const empty = { | ||
@@ -47,2 +48,3 @@ pages: [], | ||
pageParam: param, | ||
direction: previous ? 'backward' : 'forward', | ||
meta: context.options.meta | ||
@@ -107,3 +109,3 @@ }; | ||
}) { | ||
return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams); | ||
return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages, pageParams[0], pageParams); | ||
} | ||
@@ -110,0 +112,0 @@ |
@@ -9,6 +9,7 @@ 'use strict'; | ||
context.fetchFn = async () => { | ||
var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$state$data, _context$state$data2; | ||
const options = context.options; | ||
const direction = context.fetchOptions?.meta?.fetchMore?.direction; | ||
const oldPages = context.state.data?.pages || []; | ||
const oldPageParams = context.state.data?.pageParams || []; | ||
const direction = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : (_context$fetchOptions3 = _context$fetchOptions2.fetchMore) == null ? void 0 : _context$fetchOptions3.direction; | ||
const oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || []; | ||
const oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || []; | ||
const empty = { | ||
@@ -49,2 +50,3 @@ pages: [], | ||
pageParam: param, | ||
direction: previous ? 'backward' : 'forward', | ||
meta: context.options.meta | ||
@@ -109,3 +111,3 @@ }; | ||
}) { | ||
return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams); | ||
return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages, pageParams[0], pageParams); | ||
} | ||
@@ -112,0 +114,0 @@ |
@@ -51,2 +51,3 @@ import { QueryObserver } from './queryObserver.esm.js'; | ||
createResult(query, options) { | ||
var _state$fetchMeta, _state$fetchMeta$fetc, _state$fetchMeta2, _state$fetchMeta2$fet; | ||
const { | ||
@@ -60,4 +61,4 @@ state | ||
} = result; | ||
const isFetchingNextPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'forward'; | ||
const isFetchingPreviousPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'backward'; | ||
const isFetchingNextPage = isFetching && ((_state$fetchMeta = state.fetchMeta) == null ? void 0 : (_state$fetchMeta$fetc = _state$fetchMeta.fetchMore) == null ? void 0 : _state$fetchMeta$fetc.direction) === 'forward'; | ||
const isFetchingPreviousPage = isFetching && ((_state$fetchMeta2 = state.fetchMeta) == null ? void 0 : (_state$fetchMeta2$fet = _state$fetchMeta2.fetchMore) == null ? void 0 : _state$fetchMeta2$fet.direction) === 'backward'; | ||
return { | ||
@@ -64,0 +65,0 @@ ...result, |
@@ -53,2 +53,3 @@ 'use strict'; | ||
createResult(query, options) { | ||
var _state$fetchMeta, _state$fetchMeta$fetc, _state$fetchMeta2, _state$fetchMeta2$fet; | ||
const { | ||
@@ -62,4 +63,4 @@ state | ||
} = result; | ||
const isFetchingNextPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'forward'; | ||
const isFetchingPreviousPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'backward'; | ||
const isFetchingNextPage = isFetching && ((_state$fetchMeta = state.fetchMeta) == null ? void 0 : (_state$fetchMeta$fetc = _state$fetchMeta.fetchMore) == null ? void 0 : _state$fetchMeta$fetc.direction) === 'forward'; | ||
const isFetchingPreviousPage = isFetching && ((_state$fetchMeta2 = state.fetchMeta) == null ? void 0 : (_state$fetchMeta2$fet = _state$fetchMeta2.fetchMore) == null ? void 0 : _state$fetchMeta2$fet.direction) === 'backward'; | ||
return { | ||
@@ -66,0 +67,0 @@ ...result, |
@@ -0,1 +1,2 @@ | ||
import { classPrivateFieldLooseBase as _classPrivateFieldLooseBase, classPrivateFieldLooseKey as _classPrivateFieldLooseKey } from './_virtual/_rollupPluginBabelHelpers.esm.js'; | ||
import { notifyManager } from './notifyManager.esm.js'; | ||
@@ -6,16 +7,35 @@ import { Removable } from './removable.esm.js'; | ||
// TYPES | ||
var _observers = /*#__PURE__*/_classPrivateFieldLooseKey("observers"); | ||
var _defaultOptions = /*#__PURE__*/_classPrivateFieldLooseKey("defaultOptions"); | ||
var _mutationCache = /*#__PURE__*/_classPrivateFieldLooseKey("mutationCache"); | ||
var _retryer = /*#__PURE__*/_classPrivateFieldLooseKey("retryer"); | ||
var _dispatch = /*#__PURE__*/_classPrivateFieldLooseKey("dispatch"); | ||
// CLASS | ||
class Mutation extends Removable { | ||
#observers; | ||
#defaultOptions; | ||
#mutationCache; | ||
#retryer; | ||
constructor(config) { | ||
super(); | ||
Object.defineProperty(this, _dispatch, { | ||
value: _dispatch2 | ||
}); | ||
Object.defineProperty(this, _observers, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _defaultOptions, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mutationCache, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _retryer, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
this.mutationId = config.mutationId; | ||
this.#defaultOptions = config.defaultOptions; | ||
this.#mutationCache = config.mutationCache; | ||
this.#observers = []; | ||
_classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions] = config.defaultOptions; | ||
_classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache] = config.mutationCache; | ||
_classPrivateFieldLooseBase(this, _observers)[_observers] = []; | ||
this.state = config.state || getDefaultState(); | ||
@@ -27,3 +47,3 @@ this.setOptions(config.options); | ||
this.options = { | ||
...this.#defaultOptions, | ||
..._classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions], | ||
...options | ||
@@ -37,8 +57,8 @@ }; | ||
addObserver(observer) { | ||
if (this.#observers.indexOf(observer) === -1) { | ||
this.#observers.push(observer); | ||
if (_classPrivateFieldLooseBase(this, _observers)[_observers].indexOf(observer) === -1) { | ||
_classPrivateFieldLooseBase(this, _observers)[_observers].push(observer); | ||
// Stop the mutation from being garbage collected | ||
this.clearGcTimeout(); | ||
this.#mutationCache.notify({ | ||
_classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].notify({ | ||
type: 'observerAdded', | ||
@@ -51,5 +71,5 @@ mutation: this, | ||
removeObserver(observer) { | ||
this.#observers = this.#observers.filter(x => x !== observer); | ||
_classPrivateFieldLooseBase(this, _observers)[_observers] = _classPrivateFieldLooseBase(this, _observers)[_observers].filter(x => x !== observer); | ||
this.scheduleGc(); | ||
this.#mutationCache.notify({ | ||
_classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].notify({ | ||
type: 'observerRemoved', | ||
@@ -61,7 +81,7 @@ mutation: this, | ||
optionalRemove() { | ||
if (!this.#observers.length) { | ||
if (!_classPrivateFieldLooseBase(this, _observers)[_observers].length) { | ||
if (this.state.status === 'pending') { | ||
this.scheduleGc(); | ||
} else { | ||
this.#mutationCache.remove(this); | ||
_classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].remove(this); | ||
} | ||
@@ -71,3 +91,4 @@ } | ||
continue() { | ||
return this.#retryer?.continue() ?? | ||
var _classPrivateFieldLoo, _classPrivateFieldLoo2; | ||
return (_classPrivateFieldLoo = (_classPrivateFieldLoo2 = _classPrivateFieldLooseBase(this, _retryer)[_retryer]) == null ? void 0 : _classPrivateFieldLoo2.continue()) != null ? _classPrivateFieldLoo : | ||
// continuing a mutation assumes that variables are set, mutation must have been dehydrated before | ||
@@ -78,3 +99,4 @@ this.execute(this.state.variables); | ||
const executeMutation = () => { | ||
this.#retryer = createRetryer({ | ||
var _this$options$retry; | ||
_classPrivateFieldLooseBase(this, _retryer)[_retryer] = createRetryer({ | ||
fn: () => { | ||
@@ -87,3 +109,3 @@ if (!this.options.mutationFn) { | ||
onFail: (failureCount, error) => { | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'failed', | ||
@@ -95,3 +117,3 @@ failureCount, | ||
onPause: () => { | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'pause' | ||
@@ -101,16 +123,18 @@ }); | ||
onContinue: () => { | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'continue' | ||
}); | ||
}, | ||
retry: this.options.retry ?? 0, | ||
retry: (_this$options$retry = this.options.retry) != null ? _this$options$retry : 0, | ||
retryDelay: this.options.retryDelay, | ||
networkMode: this.options.networkMode | ||
}); | ||
return this.#retryer.promise; | ||
return _classPrivateFieldLooseBase(this, _retryer)[_retryer].promise; | ||
}; | ||
const restored = this.state.status === 'pending'; | ||
try { | ||
var _classPrivateFieldLoo5, _classPrivateFieldLoo6, _this$options$onSucce, _this$options2, _classPrivateFieldLoo7, _classPrivateFieldLoo8, _this$options$onSettl, _this$options3; | ||
if (!restored) { | ||
this.#dispatch({ | ||
var _classPrivateFieldLoo3, _classPrivateFieldLoo4, _this$options$onMutat, _this$options; | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'pending', | ||
@@ -120,6 +144,6 @@ variables | ||
// Notify cache callback | ||
await this.#mutationCache.config.onMutate?.(variables, this); | ||
const context = await this.options.onMutate?.(variables); | ||
await ((_classPrivateFieldLoo3 = (_classPrivateFieldLoo4 = _classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].config).onMutate) == null ? void 0 : _classPrivateFieldLoo3.call(_classPrivateFieldLoo4, variables, this)); | ||
const context = await ((_this$options$onMutat = (_this$options = this.options).onMutate) == null ? void 0 : _this$options$onMutat.call(_this$options, variables)); | ||
if (context !== this.state.context) { | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'pending', | ||
@@ -134,9 +158,9 @@ context, | ||
// Notify cache callback | ||
await this.#mutationCache.config.onSuccess?.(data, variables, this.state.context, this); | ||
await this.options.onSuccess?.(data, variables, this.state.context); | ||
await ((_classPrivateFieldLoo5 = (_classPrivateFieldLoo6 = _classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].config).onSuccess) == null ? void 0 : _classPrivateFieldLoo5.call(_classPrivateFieldLoo6, data, variables, this.state.context, this)); | ||
await ((_this$options$onSucce = (_this$options2 = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options2, data, variables, this.state.context)); | ||
// Notify cache callback | ||
await this.#mutationCache.config.onSettled?.(data, null, this.state.variables, this.state.context, this); | ||
await this.options.onSettled?.(data, null, variables, this.state.context); | ||
this.#dispatch({ | ||
await ((_classPrivateFieldLoo7 = (_classPrivateFieldLoo8 = _classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].config).onSettled) == null ? void 0 : _classPrivateFieldLoo7.call(_classPrivateFieldLoo8, data, null, this.state.variables, this.state.context, this)); | ||
await ((_this$options$onSettl = (_this$options3 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options3, data, null, variables, this.state.context)); | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'success', | ||
@@ -148,12 +172,13 @@ data | ||
try { | ||
var _classPrivateFieldLoo9, _classPrivateFieldLoo10, _this$options$onError, _this$options4, _classPrivateFieldLoo11, _classPrivateFieldLoo12, _this$options$onSettl2, _this$options5; | ||
// Notify cache callback | ||
await this.#mutationCache.config.onError?.(error, variables, this.state.context, this); | ||
await this.options.onError?.(error, variables, this.state.context); | ||
await ((_classPrivateFieldLoo9 = (_classPrivateFieldLoo10 = _classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].config).onError) == null ? void 0 : _classPrivateFieldLoo9.call(_classPrivateFieldLoo10, error, variables, this.state.context, this)); | ||
await ((_this$options$onError = (_this$options4 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options4, error, variables, this.state.context)); | ||
// Notify cache callback | ||
await this.#mutationCache.config.onSettled?.(undefined, error, this.state.variables, this.state.context, this); | ||
await this.options.onSettled?.(undefined, error, variables, this.state.context); | ||
await ((_classPrivateFieldLoo11 = (_classPrivateFieldLoo12 = _classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].config).onSettled) == null ? void 0 : _classPrivateFieldLoo11.call(_classPrivateFieldLoo12, undefined, error, this.state.variables, this.state.context, this)); | ||
await ((_this$options$onSettl2 = (_this$options5 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options5, undefined, error, variables, this.state.context)); | ||
throw error; | ||
} finally { | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'error', | ||
@@ -165,68 +190,68 @@ error: error | ||
} | ||
#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: undefined, | ||
failureCount: 0, | ||
failureReason: null, | ||
error: null, | ||
isPaused: !canFetch(this.options.networkMode), | ||
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: undefined, | ||
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 _dispatch2(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: undefined, | ||
failureCount: 0, | ||
failureReason: null, | ||
error: null, | ||
isPaused: !canFetch(this.options.networkMode), | ||
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: undefined, | ||
error: action.error, | ||
failureCount: state.failureCount + 1, | ||
failureReason: action.error, | ||
isPaused: false, | ||
status: 'error' | ||
}; | ||
} | ||
}; | ||
this.state = reducer(this.state); | ||
notifyManager.batch(() => { | ||
_classPrivateFieldLooseBase(this, _observers)[_observers].forEach(observer => { | ||
observer.onMutationUpdate(action); | ||
}); | ||
} | ||
_classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].notify({ | ||
mutation: this, | ||
type: 'updated', | ||
action | ||
}); | ||
}); | ||
} | ||
@@ -233,0 +258,0 @@ function getDefaultState() { |
'use strict'; | ||
var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js'); | ||
var notifyManager = require('./notifyManager.js'); | ||
@@ -8,16 +9,35 @@ var removable = require('./removable.js'); | ||
// TYPES | ||
var _observers = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("observers"); | ||
var _defaultOptions = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("defaultOptions"); | ||
var _mutationCache = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("mutationCache"); | ||
var _retryer = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("retryer"); | ||
var _dispatch = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("dispatch"); | ||
// CLASS | ||
class Mutation extends removable.Removable { | ||
#observers; | ||
#defaultOptions; | ||
#mutationCache; | ||
#retryer; | ||
constructor(config) { | ||
super(); | ||
Object.defineProperty(this, _dispatch, { | ||
value: _dispatch2 | ||
}); | ||
Object.defineProperty(this, _observers, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _defaultOptions, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mutationCache, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _retryer, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
this.mutationId = config.mutationId; | ||
this.#defaultOptions = config.defaultOptions; | ||
this.#mutationCache = config.mutationCache; | ||
this.#observers = []; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions] = config.defaultOptions; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache] = config.mutationCache; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers] = []; | ||
this.state = config.state || getDefaultState(); | ||
@@ -29,3 +49,3 @@ this.setOptions(config.options); | ||
this.options = { | ||
...this.#defaultOptions, | ||
..._rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions], | ||
...options | ||
@@ -39,8 +59,8 @@ }; | ||
addObserver(observer) { | ||
if (this.#observers.indexOf(observer) === -1) { | ||
this.#observers.push(observer); | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].indexOf(observer) === -1) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].push(observer); | ||
// Stop the mutation from being garbage collected | ||
this.clearGcTimeout(); | ||
this.#mutationCache.notify({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].notify({ | ||
type: 'observerAdded', | ||
@@ -53,5 +73,5 @@ mutation: this, | ||
removeObserver(observer) { | ||
this.#observers = this.#observers.filter(x => x !== observer); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers] = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].filter(x => x !== observer); | ||
this.scheduleGc(); | ||
this.#mutationCache.notify({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].notify({ | ||
type: 'observerRemoved', | ||
@@ -63,7 +83,7 @@ mutation: this, | ||
optionalRemove() { | ||
if (!this.#observers.length) { | ||
if (!_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].length) { | ||
if (this.state.status === 'pending') { | ||
this.scheduleGc(); | ||
} else { | ||
this.#mutationCache.remove(this); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].remove(this); | ||
} | ||
@@ -73,3 +93,4 @@ } | ||
continue() { | ||
return this.#retryer?.continue() ?? | ||
var _classPrivateFieldLoo, _classPrivateFieldLoo2; | ||
return (_classPrivateFieldLoo = (_classPrivateFieldLoo2 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer]) == null ? void 0 : _classPrivateFieldLoo2.continue()) != null ? _classPrivateFieldLoo : | ||
// continuing a mutation assumes that variables are set, mutation must have been dehydrated before | ||
@@ -80,3 +101,4 @@ this.execute(this.state.variables); | ||
const executeMutation = () => { | ||
this.#retryer = retryer.createRetryer({ | ||
var _this$options$retry; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer] = retryer.createRetryer({ | ||
fn: () => { | ||
@@ -89,3 +111,3 @@ if (!this.options.mutationFn) { | ||
onFail: (failureCount, error) => { | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'failed', | ||
@@ -97,3 +119,3 @@ failureCount, | ||
onPause: () => { | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'pause' | ||
@@ -103,16 +125,18 @@ }); | ||
onContinue: () => { | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'continue' | ||
}); | ||
}, | ||
retry: this.options.retry ?? 0, | ||
retry: (_this$options$retry = this.options.retry) != null ? _this$options$retry : 0, | ||
retryDelay: this.options.retryDelay, | ||
networkMode: this.options.networkMode | ||
}); | ||
return this.#retryer.promise; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer].promise; | ||
}; | ||
const restored = this.state.status === 'pending'; | ||
try { | ||
var _classPrivateFieldLoo5, _classPrivateFieldLoo6, _this$options$onSucce, _this$options2, _classPrivateFieldLoo7, _classPrivateFieldLoo8, _this$options$onSettl, _this$options3; | ||
if (!restored) { | ||
this.#dispatch({ | ||
var _classPrivateFieldLoo3, _classPrivateFieldLoo4, _this$options$onMutat, _this$options; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'pending', | ||
@@ -122,6 +146,6 @@ variables | ||
// Notify cache callback | ||
await this.#mutationCache.config.onMutate?.(variables, this); | ||
const context = await this.options.onMutate?.(variables); | ||
await ((_classPrivateFieldLoo3 = (_classPrivateFieldLoo4 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].config).onMutate) == null ? void 0 : _classPrivateFieldLoo3.call(_classPrivateFieldLoo4, variables, this)); | ||
const context = await ((_this$options$onMutat = (_this$options = this.options).onMutate) == null ? void 0 : _this$options$onMutat.call(_this$options, variables)); | ||
if (context !== this.state.context) { | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'pending', | ||
@@ -136,9 +160,9 @@ context, | ||
// Notify cache callback | ||
await this.#mutationCache.config.onSuccess?.(data, variables, this.state.context, this); | ||
await this.options.onSuccess?.(data, variables, this.state.context); | ||
await ((_classPrivateFieldLoo5 = (_classPrivateFieldLoo6 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].config).onSuccess) == null ? void 0 : _classPrivateFieldLoo5.call(_classPrivateFieldLoo6, data, variables, this.state.context, this)); | ||
await ((_this$options$onSucce = (_this$options2 = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options2, data, variables, this.state.context)); | ||
// Notify cache callback | ||
await this.#mutationCache.config.onSettled?.(data, null, this.state.variables, this.state.context, this); | ||
await this.options.onSettled?.(data, null, variables, this.state.context); | ||
this.#dispatch({ | ||
await ((_classPrivateFieldLoo7 = (_classPrivateFieldLoo8 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].config).onSettled) == null ? void 0 : _classPrivateFieldLoo7.call(_classPrivateFieldLoo8, data, null, this.state.variables, this.state.context, this)); | ||
await ((_this$options$onSettl = (_this$options3 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options3, data, null, variables, this.state.context)); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'success', | ||
@@ -150,12 +174,13 @@ data | ||
try { | ||
var _classPrivateFieldLoo9, _classPrivateFieldLoo10, _this$options$onError, _this$options4, _classPrivateFieldLoo11, _classPrivateFieldLoo12, _this$options$onSettl2, _this$options5; | ||
// Notify cache callback | ||
await this.#mutationCache.config.onError?.(error, variables, this.state.context, this); | ||
await this.options.onError?.(error, variables, this.state.context); | ||
await ((_classPrivateFieldLoo9 = (_classPrivateFieldLoo10 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].config).onError) == null ? void 0 : _classPrivateFieldLoo9.call(_classPrivateFieldLoo10, error, variables, this.state.context, this)); | ||
await ((_this$options$onError = (_this$options4 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options4, error, variables, this.state.context)); | ||
// Notify cache callback | ||
await this.#mutationCache.config.onSettled?.(undefined, error, this.state.variables, this.state.context, this); | ||
await this.options.onSettled?.(undefined, error, variables, this.state.context); | ||
await ((_classPrivateFieldLoo11 = (_classPrivateFieldLoo12 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].config).onSettled) == null ? void 0 : _classPrivateFieldLoo11.call(_classPrivateFieldLoo12, undefined, error, this.state.variables, this.state.context, this)); | ||
await ((_this$options$onSettl2 = (_this$options5 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options5, undefined, error, variables, this.state.context)); | ||
throw error; | ||
} finally { | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'error', | ||
@@ -167,68 +192,68 @@ error: error | ||
} | ||
#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: undefined, | ||
failureCount: 0, | ||
failureReason: null, | ||
error: null, | ||
isPaused: !retryer.canFetch(this.options.networkMode), | ||
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: undefined, | ||
error: action.error, | ||
failureCount: state.failureCount + 1, | ||
failureReason: action.error, | ||
isPaused: false, | ||
status: 'error' | ||
}; | ||
} | ||
}; | ||
this.state = reducer(this.state); | ||
notifyManager.notifyManager.batch(() => { | ||
this.#observers.forEach(observer => { | ||
observer.onMutationUpdate(action); | ||
}); | ||
this.#mutationCache.notify({ | ||
mutation: this, | ||
type: 'updated', | ||
action | ||
}); | ||
} | ||
function _dispatch2(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: undefined, | ||
failureCount: 0, | ||
failureReason: null, | ||
error: null, | ||
isPaused: !retryer.canFetch(this.options.networkMode), | ||
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: undefined, | ||
error: action.error, | ||
failureCount: state.failureCount + 1, | ||
failureReason: action.error, | ||
isPaused: false, | ||
status: 'error' | ||
}; | ||
} | ||
}; | ||
this.state = reducer(this.state); | ||
notifyManager.notifyManager.batch(() => { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].forEach(observer => { | ||
observer.onMutationUpdate(action); | ||
}); | ||
} | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].notify({ | ||
mutation: this, | ||
type: 'updated', | ||
action | ||
}); | ||
}); | ||
} | ||
@@ -235,0 +260,0 @@ function getDefaultState() { |
@@ -0,1 +1,2 @@ | ||
import { classPrivateFieldLooseBase as _classPrivateFieldLooseBase, classPrivateFieldLooseKey as _classPrivateFieldLooseKey } from './_virtual/_rollupPluginBabelHelpers.esm.js'; | ||
import { notifyManager } from './notifyManager.esm.js'; | ||
@@ -7,14 +8,25 @@ import { Mutation } from './mutation.esm.js'; | ||
// TYPES | ||
var _mutations = /*#__PURE__*/_classPrivateFieldLooseKey("mutations"); | ||
var _mutationId = /*#__PURE__*/_classPrivateFieldLooseKey("mutationId"); | ||
var _resuming = /*#__PURE__*/_classPrivateFieldLooseKey("resuming"); | ||
// CLASS | ||
class MutationCache extends Subscribable { | ||
#mutations; | ||
#mutationId; | ||
#resuming; | ||
constructor(config = {}) { | ||
super(); | ||
Object.defineProperty(this, _mutations, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mutationId, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _resuming, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
this.config = config; | ||
this.#mutations = []; | ||
this.#mutationId = 0; | ||
_classPrivateFieldLooseBase(this, _mutations)[_mutations] = []; | ||
_classPrivateFieldLooseBase(this, _mutationId)[_mutationId] = 0; | ||
} | ||
@@ -24,3 +36,3 @@ build(client, options, state) { | ||
mutationCache: this, | ||
mutationId: ++this.#mutationId, | ||
mutationId: ++_classPrivateFieldLooseBase(this, _mutationId)[_mutationId], | ||
options: client.defaultMutationOptions(options), | ||
@@ -33,3 +45,3 @@ state | ||
add(mutation) { | ||
this.#mutations.push(mutation); | ||
_classPrivateFieldLooseBase(this, _mutations)[_mutations].push(mutation); | ||
this.notify({ | ||
@@ -41,3 +53,3 @@ type: 'added', | ||
remove(mutation) { | ||
this.#mutations = this.#mutations.filter(x => x !== mutation); | ||
_classPrivateFieldLooseBase(this, _mutations)[_mutations] = _classPrivateFieldLooseBase(this, _mutations)[_mutations].filter(x => x !== mutation); | ||
this.notify({ | ||
@@ -50,3 +62,3 @@ type: 'removed', | ||
notifyManager.batch(() => { | ||
this.#mutations.forEach(mutation => { | ||
_classPrivateFieldLooseBase(this, _mutations)[_mutations].forEach(mutation => { | ||
this.remove(mutation); | ||
@@ -57,3 +69,3 @@ }); | ||
getAll() { | ||
return this.#mutations; | ||
return _classPrivateFieldLooseBase(this, _mutations)[_mutations]; | ||
} | ||
@@ -64,6 +76,6 @@ find(filters) { | ||
} | ||
return this.#mutations.find(mutation => matchMutation(filters, mutation)); | ||
return _classPrivateFieldLooseBase(this, _mutations)[_mutations].find(mutation => matchMutation(filters, mutation)); | ||
} | ||
findAll(filters = {}) { | ||
return this.#mutations.filter(mutation => matchMutation(filters, mutation)); | ||
return _classPrivateFieldLooseBase(this, _mutations)[_mutations].filter(mutation => matchMutation(filters, mutation)); | ||
} | ||
@@ -78,9 +90,10 @@ notify(event) { | ||
resumePausedMutations() { | ||
this.#resuming = (this.#resuming ?? Promise.resolve()).then(() => { | ||
const pausedMutations = this.#mutations.filter(x => x.state.isPaused); | ||
var _classPrivateFieldLoo; | ||
_classPrivateFieldLooseBase(this, _resuming)[_resuming] = ((_classPrivateFieldLoo = _classPrivateFieldLooseBase(this, _resuming)[_resuming]) != null ? _classPrivateFieldLoo : Promise.resolve()).then(() => { | ||
const pausedMutations = _classPrivateFieldLooseBase(this, _mutations)[_mutations].filter(x => x.state.isPaused); | ||
return notifyManager.batch(() => pausedMutations.reduce((promise, mutation) => promise.then(() => mutation.continue().catch(noop)), Promise.resolve())); | ||
}).then(() => { | ||
this.#resuming = undefined; | ||
_classPrivateFieldLooseBase(this, _resuming)[_resuming] = undefined; | ||
}); | ||
return this.#resuming; | ||
return _classPrivateFieldLooseBase(this, _resuming)[_resuming]; | ||
} | ||
@@ -87,0 +100,0 @@ } |
'use strict'; | ||
var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js'); | ||
var notifyManager = require('./notifyManager.js'); | ||
@@ -9,14 +10,25 @@ var mutation = require('./mutation.js'); | ||
// TYPES | ||
var _mutations = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("mutations"); | ||
var _mutationId = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("mutationId"); | ||
var _resuming = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("resuming"); | ||
// CLASS | ||
class MutationCache extends subscribable.Subscribable { | ||
#mutations; | ||
#mutationId; | ||
#resuming; | ||
constructor(config = {}) { | ||
super(); | ||
Object.defineProperty(this, _mutations, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mutationId, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _resuming, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
this.config = config; | ||
this.#mutations = []; | ||
this.#mutationId = 0; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutations)[_mutations] = []; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationId)[_mutationId] = 0; | ||
} | ||
@@ -26,3 +38,3 @@ build(client, options, state) { | ||
mutationCache: this, | ||
mutationId: ++this.#mutationId, | ||
mutationId: ++_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationId)[_mutationId], | ||
options: client.defaultMutationOptions(options), | ||
@@ -35,3 +47,3 @@ state | ||
add(mutation) { | ||
this.#mutations.push(mutation); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutations)[_mutations].push(mutation); | ||
this.notify({ | ||
@@ -43,3 +55,3 @@ type: 'added', | ||
remove(mutation) { | ||
this.#mutations = this.#mutations.filter(x => x !== mutation); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutations)[_mutations] = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutations)[_mutations].filter(x => x !== mutation); | ||
this.notify({ | ||
@@ -52,3 +64,3 @@ type: 'removed', | ||
notifyManager.notifyManager.batch(() => { | ||
this.#mutations.forEach(mutation => { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutations)[_mutations].forEach(mutation => { | ||
this.remove(mutation); | ||
@@ -59,3 +71,3 @@ }); | ||
getAll() { | ||
return this.#mutations; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutations)[_mutations]; | ||
} | ||
@@ -66,6 +78,6 @@ find(filters) { | ||
} | ||
return this.#mutations.find(mutation => utils.matchMutation(filters, mutation)); | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutations)[_mutations].find(mutation => utils.matchMutation(filters, mutation)); | ||
} | ||
findAll(filters = {}) { | ||
return this.#mutations.filter(mutation => utils.matchMutation(filters, mutation)); | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutations)[_mutations].filter(mutation => utils.matchMutation(filters, mutation)); | ||
} | ||
@@ -80,9 +92,10 @@ notify(event) { | ||
resumePausedMutations() { | ||
this.#resuming = (this.#resuming ?? Promise.resolve()).then(() => { | ||
const pausedMutations = this.#mutations.filter(x => x.state.isPaused); | ||
var _classPrivateFieldLoo; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _resuming)[_resuming] = ((_classPrivateFieldLoo = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _resuming)[_resuming]) != null ? _classPrivateFieldLoo : Promise.resolve()).then(() => { | ||
const pausedMutations = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutations)[_mutations].filter(x => x.state.isPaused); | ||
return notifyManager.notifyManager.batch(() => pausedMutations.reduce((promise, mutation) => promise.then(() => mutation.continue().catch(utils.noop)), Promise.resolve())); | ||
}).then(() => { | ||
this.#resuming = undefined; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _resuming)[_resuming] = undefined; | ||
}); | ||
return this.#resuming; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _resuming)[_resuming]; | ||
} | ||
@@ -89,0 +102,0 @@ } |
@@ -0,1 +1,2 @@ | ||
import { classPrivateFieldLooseBase as _classPrivateFieldLooseBase, classPrivateFieldLooseKey as _classPrivateFieldLooseKey } from './_virtual/_rollupPluginBabelHelpers.esm.js'; | ||
import { getDefaultState } from './mutation.esm.js'; | ||
@@ -7,16 +8,39 @@ import { notifyManager } from './notifyManager.esm.js'; | ||
// TYPES | ||
var _client = /*#__PURE__*/_classPrivateFieldLooseKey("client"); | ||
var _currentResult = /*#__PURE__*/_classPrivateFieldLooseKey("currentResult"); | ||
var _currentMutation = /*#__PURE__*/_classPrivateFieldLooseKey("currentMutation"); | ||
var _mutateOptions = /*#__PURE__*/_classPrivateFieldLooseKey("mutateOptions"); | ||
var _updateResult = /*#__PURE__*/_classPrivateFieldLooseKey("updateResult"); | ||
var _notify = /*#__PURE__*/_classPrivateFieldLooseKey("notify"); | ||
// CLASS | ||
class MutationObserver extends Subscribable { | ||
#client; | ||
#currentResult = undefined; | ||
#currentMutation; | ||
#mutateOptions; | ||
constructor(client, options) { | ||
super(); | ||
this.#client = client; | ||
Object.defineProperty(this, _notify, { | ||
value: _notify2 | ||
}); | ||
Object.defineProperty(this, _updateResult, { | ||
value: _updateResult2 | ||
}); | ||
Object.defineProperty(this, _client, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _currentResult, { | ||
writable: true, | ||
value: undefined | ||
}); | ||
Object.defineProperty(this, _currentMutation, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mutateOptions, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_classPrivateFieldLooseBase(this, _client)[_client] = client; | ||
this.setOptions(options); | ||
this.bindMethods(); | ||
this.#updateResult(); | ||
_classPrivateFieldLooseBase(this, _updateResult)[_updateResult](); | ||
} | ||
@@ -28,68 +52,74 @@ bindMethods() { | ||
setOptions(options) { | ||
var _classPrivateFieldLoo; | ||
const prevOptions = this.options; | ||
this.options = this.#client.defaultMutationOptions(options); | ||
this.options = _classPrivateFieldLooseBase(this, _client)[_client].defaultMutationOptions(options); | ||
if (!shallowEqualObjects(prevOptions, this.options)) { | ||
this.#client.getMutationCache().notify({ | ||
_classPrivateFieldLooseBase(this, _client)[_client].getMutationCache().notify({ | ||
type: 'observerOptionsUpdated', | ||
mutation: this.#currentMutation, | ||
mutation: _classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation], | ||
observer: this | ||
}); | ||
} | ||
this.#currentMutation?.setOptions(this.options); | ||
(_classPrivateFieldLoo = _classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation]) == null ? void 0 : _classPrivateFieldLoo.setOptions(this.options); | ||
} | ||
onUnsubscribe() { | ||
if (!this.listeners.length) { | ||
this.#currentMutation?.removeObserver(this); | ||
var _classPrivateFieldLoo2; | ||
(_classPrivateFieldLoo2 = _classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation]) == null ? void 0 : _classPrivateFieldLoo2.removeObserver(this); | ||
} | ||
} | ||
onMutationUpdate(action) { | ||
this.#updateResult(); | ||
this.#notify(action); | ||
_classPrivateFieldLooseBase(this, _updateResult)[_updateResult](); | ||
_classPrivateFieldLooseBase(this, _notify)[_notify](action); | ||
} | ||
getCurrentResult() { | ||
return this.#currentResult; | ||
return _classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
} | ||
reset() { | ||
this.#currentMutation = undefined; | ||
this.#updateResult(); | ||
this.#notify(); | ||
_classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation] = undefined; | ||
_classPrivateFieldLooseBase(this, _updateResult)[_updateResult](); | ||
_classPrivateFieldLooseBase(this, _notify)[_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); | ||
var _classPrivateFieldLoo3; | ||
_classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions] = options; | ||
(_classPrivateFieldLoo3 = _classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation]) == null ? void 0 : _classPrivateFieldLoo3.removeObserver(this); | ||
_classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation] = _classPrivateFieldLooseBase(this, _client)[_client].getMutationCache().build(_classPrivateFieldLooseBase(this, _client)[_client], this.options); | ||
_classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation].addObserver(this); | ||
return _classPrivateFieldLooseBase(this, _currentMutation)[_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(() => { | ||
// First trigger the mutate callbacks | ||
if (this.#mutateOptions && this.hasListeners()) { | ||
if (action?.type === 'success') { | ||
this.#mutateOptions.onSuccess?.(action.data, this.#currentResult.variables, this.#currentResult.context); | ||
this.#mutateOptions.onSettled?.(action.data, null, this.#currentResult.variables, this.#currentResult.context); | ||
} else if (action?.type === 'error') { | ||
this.#mutateOptions.onError?.(action.error, this.#currentResult.variables, this.#currentResult.context); | ||
this.#mutateOptions.onSettled?.(undefined, action.error, this.#currentResult.variables, this.#currentResult.context); | ||
} | ||
} | ||
function _updateResult2() { | ||
var _classPrivateFieldLoo4, _classPrivateFieldLoo5; | ||
const state = (_classPrivateFieldLoo4 = (_classPrivateFieldLoo5 = _classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation]) == null ? void 0 : _classPrivateFieldLoo5.state) != null ? _classPrivateFieldLoo4 : getDefaultState(); | ||
_classPrivateFieldLooseBase(this, _currentResult)[_currentResult] = { | ||
...state, | ||
isPending: state.status === 'pending', | ||
isSuccess: state.status === 'success', | ||
isError: state.status === 'error', | ||
isIdle: state.status === 'idle', | ||
mutate: this.mutate, | ||
reset: this.reset | ||
}; | ||
} | ||
function _notify2(action) { | ||
notifyManager.batch(() => { | ||
// First trigger the mutate callbacks | ||
if (_classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions] && this.hasListeners()) { | ||
if ((action == null ? void 0 : action.type) === 'success') { | ||
var _classPrivateFieldLoo6, _classPrivateFieldLoo7, _classPrivateFieldLoo8, _classPrivateFieldLoo9; | ||
(_classPrivateFieldLoo6 = (_classPrivateFieldLoo7 = _classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions]).onSuccess) == null ? void 0 : _classPrivateFieldLoo6.call(_classPrivateFieldLoo7, action.data, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].variables, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].context); | ||
(_classPrivateFieldLoo8 = (_classPrivateFieldLoo9 = _classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions]).onSettled) == null ? void 0 : _classPrivateFieldLoo8.call(_classPrivateFieldLoo9, action.data, null, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].variables, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].context); | ||
} else if ((action == null ? void 0 : action.type) === 'error') { | ||
var _classPrivateFieldLoo10, _classPrivateFieldLoo11, _classPrivateFieldLoo12, _classPrivateFieldLoo13; | ||
(_classPrivateFieldLoo10 = (_classPrivateFieldLoo11 = _classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions]).onError) == null ? void 0 : _classPrivateFieldLoo10.call(_classPrivateFieldLoo11, action.error, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].variables, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].context); | ||
(_classPrivateFieldLoo12 = (_classPrivateFieldLoo13 = _classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions]).onSettled) == null ? void 0 : _classPrivateFieldLoo12.call(_classPrivateFieldLoo13, undefined, action.error, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].variables, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].context); | ||
} | ||
} | ||
// Then trigger the listeners | ||
this.listeners.forEach(listener => { | ||
listener(this.#currentResult); | ||
}); | ||
// Then trigger the listeners | ||
this.listeners.forEach(listener => { | ||
listener(_classPrivateFieldLooseBase(this, _currentResult)[_currentResult]); | ||
}); | ||
} | ||
}); | ||
} | ||
@@ -96,0 +126,0 @@ |
'use strict'; | ||
var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js'); | ||
var mutation = require('./mutation.js'); | ||
@@ -9,16 +10,39 @@ var notifyManager = require('./notifyManager.js'); | ||
// TYPES | ||
var _client = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("client"); | ||
var _currentResult = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("currentResult"); | ||
var _currentMutation = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("currentMutation"); | ||
var _mutateOptions = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("mutateOptions"); | ||
var _updateResult = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("updateResult"); | ||
var _notify = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("notify"); | ||
// CLASS | ||
class MutationObserver extends subscribable.Subscribable { | ||
#client; | ||
#currentResult = undefined; | ||
#currentMutation; | ||
#mutateOptions; | ||
constructor(client, options) { | ||
super(); | ||
this.#client = client; | ||
Object.defineProperty(this, _notify, { | ||
value: _notify2 | ||
}); | ||
Object.defineProperty(this, _updateResult, { | ||
value: _updateResult2 | ||
}); | ||
Object.defineProperty(this, _client, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _currentResult, { | ||
writable: true, | ||
value: undefined | ||
}); | ||
Object.defineProperty(this, _currentMutation, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mutateOptions, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client] = client; | ||
this.setOptions(options); | ||
this.bindMethods(); | ||
this.#updateResult(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateResult)[_updateResult](); | ||
} | ||
@@ -30,68 +54,74 @@ bindMethods() { | ||
setOptions(options) { | ||
var _classPrivateFieldLoo; | ||
const prevOptions = this.options; | ||
this.options = this.#client.defaultMutationOptions(options); | ||
this.options = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].defaultMutationOptions(options); | ||
if (!utils.shallowEqualObjects(prevOptions, this.options)) { | ||
this.#client.getMutationCache().notify({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].getMutationCache().notify({ | ||
type: 'observerOptionsUpdated', | ||
mutation: this.#currentMutation, | ||
mutation: _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation], | ||
observer: this | ||
}); | ||
} | ||
this.#currentMutation?.setOptions(this.options); | ||
(_classPrivateFieldLoo = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation]) == null ? void 0 : _classPrivateFieldLoo.setOptions(this.options); | ||
} | ||
onUnsubscribe() { | ||
if (!this.listeners.length) { | ||
this.#currentMutation?.removeObserver(this); | ||
var _classPrivateFieldLoo2; | ||
(_classPrivateFieldLoo2 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation]) == null ? void 0 : _classPrivateFieldLoo2.removeObserver(this); | ||
} | ||
} | ||
onMutationUpdate(action) { | ||
this.#updateResult(); | ||
this.#notify(action); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateResult)[_updateResult](); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _notify)[_notify](action); | ||
} | ||
getCurrentResult() { | ||
return this.#currentResult; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
} | ||
reset() { | ||
this.#currentMutation = undefined; | ||
this.#updateResult(); | ||
this.#notify(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation] = undefined; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateResult)[_updateResult](); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _notify)[_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); | ||
var _classPrivateFieldLoo3; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions] = options; | ||
(_classPrivateFieldLoo3 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation]) == null ? void 0 : _classPrivateFieldLoo3.removeObserver(this); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation] = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].getMutationCache().build(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client], this.options); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation].addObserver(this); | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation].execute(variables); | ||
} | ||
#updateResult() { | ||
const state = this.#currentMutation?.state ?? 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) { | ||
notifyManager.notifyManager.batch(() => { | ||
// First trigger the mutate callbacks | ||
if (this.#mutateOptions && this.hasListeners()) { | ||
if (action?.type === 'success') { | ||
this.#mutateOptions.onSuccess?.(action.data, this.#currentResult.variables, this.#currentResult.context); | ||
this.#mutateOptions.onSettled?.(action.data, null, this.#currentResult.variables, this.#currentResult.context); | ||
} else if (action?.type === 'error') { | ||
this.#mutateOptions.onError?.(action.error, this.#currentResult.variables, this.#currentResult.context); | ||
this.#mutateOptions.onSettled?.(undefined, action.error, this.#currentResult.variables, this.#currentResult.context); | ||
} | ||
} | ||
function _updateResult2() { | ||
var _classPrivateFieldLoo4, _classPrivateFieldLoo5; | ||
const state = (_classPrivateFieldLoo4 = (_classPrivateFieldLoo5 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentMutation)[_currentMutation]) == null ? void 0 : _classPrivateFieldLoo5.state) != null ? _classPrivateFieldLoo4 : mutation.getDefaultState(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult] = { | ||
...state, | ||
isPending: state.status === 'pending', | ||
isSuccess: state.status === 'success', | ||
isError: state.status === 'error', | ||
isIdle: state.status === 'idle', | ||
mutate: this.mutate, | ||
reset: this.reset | ||
}; | ||
} | ||
function _notify2(action) { | ||
notifyManager.notifyManager.batch(() => { | ||
// First trigger the mutate callbacks | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions] && this.hasListeners()) { | ||
if ((action == null ? void 0 : action.type) === 'success') { | ||
var _classPrivateFieldLoo6, _classPrivateFieldLoo7, _classPrivateFieldLoo8, _classPrivateFieldLoo9; | ||
(_classPrivateFieldLoo6 = (_classPrivateFieldLoo7 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions]).onSuccess) == null ? void 0 : _classPrivateFieldLoo6.call(_classPrivateFieldLoo7, action.data, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].variables, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].context); | ||
(_classPrivateFieldLoo8 = (_classPrivateFieldLoo9 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions]).onSettled) == null ? void 0 : _classPrivateFieldLoo8.call(_classPrivateFieldLoo9, action.data, null, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].variables, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].context); | ||
} else if ((action == null ? void 0 : action.type) === 'error') { | ||
var _classPrivateFieldLoo10, _classPrivateFieldLoo11, _classPrivateFieldLoo12, _classPrivateFieldLoo13; | ||
(_classPrivateFieldLoo10 = (_classPrivateFieldLoo11 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions]).onError) == null ? void 0 : _classPrivateFieldLoo10.call(_classPrivateFieldLoo11, action.error, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].variables, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].context); | ||
(_classPrivateFieldLoo12 = (_classPrivateFieldLoo13 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutateOptions)[_mutateOptions]).onSettled) == null ? void 0 : _classPrivateFieldLoo12.call(_classPrivateFieldLoo13, undefined, action.error, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].variables, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].context); | ||
} | ||
} | ||
// Then trigger the listeners | ||
this.listeners.forEach(listener => { | ||
listener(this.#currentResult); | ||
}); | ||
// Then trigger the listeners | ||
this.listeners.forEach(listener => { | ||
listener(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult]); | ||
}); | ||
} | ||
}); | ||
} | ||
@@ -98,0 +128,0 @@ |
@@ -0,11 +1,24 @@ | ||
import { classPrivateFieldLooseBase as _classPrivateFieldLooseBase, classPrivateFieldLooseKey as _classPrivateFieldLooseKey } from './_virtual/_rollupPluginBabelHelpers.esm.js'; | ||
import { Subscribable } from './subscribable.esm.js'; | ||
import { isServer } from './utils.esm.js'; | ||
var _online = /*#__PURE__*/_classPrivateFieldLooseKey("online"); | ||
var _cleanup = /*#__PURE__*/_classPrivateFieldLooseKey("cleanup"); | ||
var _setup = /*#__PURE__*/_classPrivateFieldLooseKey("setup"); | ||
class OnlineManager extends Subscribable { | ||
#online; | ||
#cleanup; | ||
#setup; | ||
constructor() { | ||
super(); | ||
this.#setup = onOnline => { | ||
Object.defineProperty(this, _online, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _cleanup, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _setup, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_classPrivateFieldLooseBase(this, _setup)[_setup] = onOnline => { | ||
// addEventListener does not exist in React Native, but window does | ||
@@ -28,4 +41,4 @@ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition | ||
onSubscribe() { | ||
if (!this.#cleanup) { | ||
this.setEventListener(this.#setup); | ||
if (!_classPrivateFieldLooseBase(this, _cleanup)[_cleanup]) { | ||
this.setEventListener(_classPrivateFieldLooseBase(this, _setup)[_setup]); | ||
} | ||
@@ -35,10 +48,12 @@ } | ||
if (!this.hasListeners()) { | ||
this.#cleanup?.(); | ||
this.#cleanup = undefined; | ||
var _classPrivateFieldLoo, _classPrivateFieldLoo2; | ||
(_classPrivateFieldLoo = (_classPrivateFieldLoo2 = _classPrivateFieldLooseBase(this, _cleanup))[_cleanup]) == null ? void 0 : _classPrivateFieldLoo.call(_classPrivateFieldLoo2); | ||
_classPrivateFieldLooseBase(this, _cleanup)[_cleanup] = undefined; | ||
} | ||
} | ||
setEventListener(setup) { | ||
this.#setup = setup; | ||
this.#cleanup?.(); | ||
this.#cleanup = setup(online => { | ||
var _classPrivateFieldLoo3, _classPrivateFieldLoo4; | ||
_classPrivateFieldLooseBase(this, _setup)[_setup] = setup; | ||
(_classPrivateFieldLoo3 = (_classPrivateFieldLoo4 = _classPrivateFieldLooseBase(this, _cleanup))[_cleanup]) == null ? void 0 : _classPrivateFieldLoo3.call(_classPrivateFieldLoo4); | ||
_classPrivateFieldLooseBase(this, _cleanup)[_cleanup] = setup(online => { | ||
if (typeof online === 'boolean') { | ||
@@ -52,3 +67,3 @@ this.setOnline(online); | ||
setOnline(online) { | ||
this.#online = online; | ||
_classPrivateFieldLooseBase(this, _online)[_online] = online; | ||
if (online) { | ||
@@ -64,4 +79,4 @@ this.onOnline(); | ||
isOnline() { | ||
if (typeof this.#online === 'boolean') { | ||
return this.#online; | ||
if (typeof _classPrivateFieldLooseBase(this, _online)[_online] === 'boolean') { | ||
return _classPrivateFieldLooseBase(this, _online)[_online]; | ||
} | ||
@@ -68,0 +83,0 @@ if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') { |
'use strict'; | ||
var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js'); | ||
var subscribable = require('./subscribable.js'); | ||
var utils = require('./utils.js'); | ||
var _online = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("online"); | ||
var _cleanup = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("cleanup"); | ||
var _setup = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("setup"); | ||
class OnlineManager extends subscribable.Subscribable { | ||
#online; | ||
#cleanup; | ||
#setup; | ||
constructor() { | ||
super(); | ||
this.#setup = onOnline => { | ||
Object.defineProperty(this, _online, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _cleanup, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _setup, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _setup)[_setup] = onOnline => { | ||
// addEventListener does not exist in React Native, but window does | ||
@@ -30,4 +43,4 @@ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition | ||
onSubscribe() { | ||
if (!this.#cleanup) { | ||
this.setEventListener(this.#setup); | ||
if (!_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cleanup)[_cleanup]) { | ||
this.setEventListener(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _setup)[_setup]); | ||
} | ||
@@ -37,10 +50,12 @@ } | ||
if (!this.hasListeners()) { | ||
this.#cleanup?.(); | ||
this.#cleanup = undefined; | ||
var _classPrivateFieldLoo, _classPrivateFieldLoo2; | ||
(_classPrivateFieldLoo = (_classPrivateFieldLoo2 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cleanup))[_cleanup]) == null ? void 0 : _classPrivateFieldLoo.call(_classPrivateFieldLoo2); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cleanup)[_cleanup] = undefined; | ||
} | ||
} | ||
setEventListener(setup) { | ||
this.#setup = setup; | ||
this.#cleanup?.(); | ||
this.#cleanup = setup(online => { | ||
var _classPrivateFieldLoo3, _classPrivateFieldLoo4; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _setup)[_setup] = setup; | ||
(_classPrivateFieldLoo3 = (_classPrivateFieldLoo4 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cleanup))[_cleanup]) == null ? void 0 : _classPrivateFieldLoo3.call(_classPrivateFieldLoo4); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cleanup)[_cleanup] = setup(online => { | ||
if (typeof online === 'boolean') { | ||
@@ -54,3 +69,3 @@ this.setOnline(online); | ||
setOnline(online) { | ||
this.#online = online; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _online)[_online] = online; | ||
if (online) { | ||
@@ -66,4 +81,4 @@ this.onOnline(); | ||
isOnline() { | ||
if (typeof this.#online === 'boolean') { | ||
return this.#online; | ||
if (typeof _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _online)[_online] === 'boolean') { | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _online)[_online]; | ||
} | ||
@@ -70,0 +85,0 @@ if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') { |
@@ -0,1 +1,2 @@ | ||
import { classPrivateFieldLooseBase as _classPrivateFieldLooseBase, classPrivateFieldLooseKey as _classPrivateFieldLooseKey } from './_virtual/_rollupPluginBabelHelpers.esm.js'; | ||
import { notifyManager } from './notifyManager.esm.js'; | ||
@@ -13,15 +14,43 @@ import { QueryObserver } from './queryObserver.esm.js'; | ||
} | ||
var _client = /*#__PURE__*/_classPrivateFieldLooseKey("client"); | ||
var _result = /*#__PURE__*/_classPrivateFieldLooseKey("result"); | ||
var _queries = /*#__PURE__*/_classPrivateFieldLooseKey("queries"); | ||
var _observers = /*#__PURE__*/_classPrivateFieldLooseKey("observers"); | ||
var _findMatchingObservers = /*#__PURE__*/_classPrivateFieldLooseKey("findMatchingObservers"); | ||
var _onUpdate = /*#__PURE__*/_classPrivateFieldLooseKey("onUpdate"); | ||
var _notify = /*#__PURE__*/_classPrivateFieldLooseKey("notify"); | ||
class QueriesObserver extends Subscribable { | ||
#client; | ||
#result; | ||
#queries; | ||
#observers; | ||
constructor(client, queries) { | ||
constructor(client, _queries2) { | ||
super(); | ||
this.#client = client; | ||
this.#queries = []; | ||
this.#result = []; | ||
this.#observers = []; | ||
if (queries) { | ||
this.setQueries(queries); | ||
Object.defineProperty(this, _notify, { | ||
value: _notify2 | ||
}); | ||
Object.defineProperty(this, _onUpdate, { | ||
value: _onUpdate2 | ||
}); | ||
Object.defineProperty(this, _findMatchingObservers, { | ||
value: _findMatchingObservers2 | ||
}); | ||
Object.defineProperty(this, _client, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _result, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _queries, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _observers, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_classPrivateFieldLooseBase(this, _client)[_client] = client; | ||
_classPrivateFieldLooseBase(this, _queries)[_queries] = []; | ||
_classPrivateFieldLooseBase(this, _result)[_result] = []; | ||
_classPrivateFieldLooseBase(this, _observers)[_observers] = []; | ||
if (_queries2) { | ||
this.setQueries(_queries2); | ||
} | ||
@@ -31,5 +60,5 @@ } | ||
if (this.listeners.length === 1) { | ||
this.#observers.forEach(observer => { | ||
_classPrivateFieldLooseBase(this, _observers)[_observers].forEach(observer => { | ||
observer.subscribe(result => { | ||
this.#onUpdate(observer, result); | ||
_classPrivateFieldLooseBase(this, _onUpdate)[_onUpdate](observer, result); | ||
}); | ||
@@ -46,3 +75,3 @@ }); | ||
this.listeners = []; | ||
this.#observers.forEach(observer => { | ||
_classPrivateFieldLooseBase(this, _observers)[_observers].forEach(observer => { | ||
observer.destroy(); | ||
@@ -52,6 +81,6 @@ }); | ||
setQueries(queries, notifyOptions) { | ||
this.#queries = queries; | ||
_classPrivateFieldLooseBase(this, _queries)[_queries] = queries; | ||
notifyManager.batch(() => { | ||
const prevObservers = this.#observers; | ||
const newObserverMatches = this.#findMatchingObservers(this.#queries); | ||
const prevObservers = _classPrivateFieldLooseBase(this, _observers)[_observers]; | ||
const newObserverMatches = _classPrivateFieldLooseBase(this, _findMatchingObservers)[_findMatchingObservers](_classPrivateFieldLooseBase(this, _queries)[_queries]); | ||
@@ -66,4 +95,4 @@ // set options for the new observers to notify of changes | ||
} | ||
this.#observers = newObservers; | ||
this.#result = newResult; | ||
_classPrivateFieldLooseBase(this, _observers)[_observers] = newObservers; | ||
_classPrivateFieldLooseBase(this, _result)[_result] = newResult; | ||
if (!this.hasListeners()) { | ||
@@ -77,63 +106,63 @@ return; | ||
observer.subscribe(result => { | ||
this.#onUpdate(observer, result); | ||
_classPrivateFieldLooseBase(this, _onUpdate)[_onUpdate](observer, result); | ||
}); | ||
}); | ||
this.#notify(); | ||
_classPrivateFieldLooseBase(this, _notify)[_notify](); | ||
}); | ||
} | ||
getCurrentResult() { | ||
return this.#result; | ||
return _classPrivateFieldLooseBase(this, _result)[_result]; | ||
} | ||
getQueries() { | ||
return this.#observers.map(observer => observer.getCurrentQuery()); | ||
return _classPrivateFieldLooseBase(this, _observers)[_observers].map(observer => observer.getCurrentQuery()); | ||
} | ||
getObservers() { | ||
return this.#observers; | ||
return _classPrivateFieldLooseBase(this, _observers)[_observers]; | ||
} | ||
getOptimisticResult(queries) { | ||
return this.#findMatchingObservers(queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions)); | ||
return _classPrivateFieldLooseBase(this, _findMatchingObservers)[_findMatchingObservers](queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions)); | ||
} | ||
#findMatchingObservers(queries) { | ||
const prevObservers = this.#observers; | ||
const defaultedQueryOptions = queries.map(options => this.#client.defaultQueryOptions(options)); | ||
const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => { | ||
const match = prevObservers.find(observer => observer.options.queryHash === defaultedOptions.queryHash); | ||
if (match != null) { | ||
return [{ | ||
defaultedQueryOptions: defaultedOptions, | ||
observer: match | ||
}]; | ||
} | ||
return []; | ||
}); | ||
const matchedQueryHashes = matchingObservers.map(match => match.defaultedQueryOptions.queryHash); | ||
const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.includes(defaultedOptions.queryHash)); | ||
const getObserver = options => { | ||
const defaultedOptions = this.#client.defaultQueryOptions(options); | ||
const currentObserver = this.#observers.find(o => o.options.queryHash === defaultedOptions.queryHash); | ||
return currentObserver ?? new QueryObserver(this.#client, defaultedOptions); | ||
} | ||
function _findMatchingObservers2(queries) { | ||
const prevObservers = _classPrivateFieldLooseBase(this, _observers)[_observers]; | ||
const defaultedQueryOptions = queries.map(options => _classPrivateFieldLooseBase(this, _client)[_client].defaultQueryOptions(options)); | ||
const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => { | ||
const match = prevObservers.find(observer => observer.options.queryHash === defaultedOptions.queryHash); | ||
if (match != null) { | ||
return [{ | ||
defaultedQueryOptions: defaultedOptions, | ||
observer: match | ||
}]; | ||
} | ||
return []; | ||
}); | ||
const matchedQueryHashes = matchingObservers.map(match => match.defaultedQueryOptions.queryHash); | ||
const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.includes(defaultedOptions.queryHash)); | ||
const getObserver = options => { | ||
const defaultedOptions = _classPrivateFieldLooseBase(this, _client)[_client].defaultQueryOptions(options); | ||
const currentObserver = _classPrivateFieldLooseBase(this, _observers)[_observers].find(o => o.options.queryHash === defaultedOptions.queryHash); | ||
return currentObserver != null ? currentObserver : new QueryObserver(_classPrivateFieldLooseBase(this, _client)[_client], defaultedOptions); | ||
}; | ||
const newOrReusedObservers = unmatchedQueries.map(options => { | ||
return { | ||
defaultedQueryOptions: options, | ||
observer: getObserver(options) | ||
}; | ||
const newOrReusedObservers = unmatchedQueries.map(options => { | ||
return { | ||
defaultedQueryOptions: options, | ||
observer: getObserver(options) | ||
}; | ||
}); | ||
const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions); | ||
return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries); | ||
}); | ||
const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions); | ||
return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries); | ||
} | ||
function _onUpdate2(observer, result) { | ||
const index = _classPrivateFieldLooseBase(this, _observers)[_observers].indexOf(observer); | ||
if (index !== -1) { | ||
_classPrivateFieldLooseBase(this, _result)[_result] = replaceAt(_classPrivateFieldLooseBase(this, _result)[_result], index, result); | ||
_classPrivateFieldLooseBase(this, _notify)[_notify](); | ||
} | ||
#onUpdate(observer, result) { | ||
const index = this.#observers.indexOf(observer); | ||
if (index !== -1) { | ||
this.#result = replaceAt(this.#result, index, result); | ||
this.#notify(); | ||
} | ||
} | ||
#notify() { | ||
notifyManager.batch(() => { | ||
this.listeners.forEach(listener => { | ||
listener(this.#result); | ||
}); | ||
} | ||
function _notify2() { | ||
notifyManager.batch(() => { | ||
this.listeners.forEach(listener => { | ||
listener(_classPrivateFieldLooseBase(this, _result)[_result]); | ||
}); | ||
} | ||
}); | ||
} | ||
@@ -140,0 +169,0 @@ |
'use strict'; | ||
var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js'); | ||
var notifyManager = require('./notifyManager.js'); | ||
@@ -15,15 +16,43 @@ var queryObserver = require('./queryObserver.js'); | ||
} | ||
var _client = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("client"); | ||
var _result = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("result"); | ||
var _queries = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("queries"); | ||
var _observers = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("observers"); | ||
var _findMatchingObservers = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("findMatchingObservers"); | ||
var _onUpdate = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("onUpdate"); | ||
var _notify = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("notify"); | ||
class QueriesObserver extends subscribable.Subscribable { | ||
#client; | ||
#result; | ||
#queries; | ||
#observers; | ||
constructor(client, queries) { | ||
constructor(client, _queries2) { | ||
super(); | ||
this.#client = client; | ||
this.#queries = []; | ||
this.#result = []; | ||
this.#observers = []; | ||
if (queries) { | ||
this.setQueries(queries); | ||
Object.defineProperty(this, _notify, { | ||
value: _notify2 | ||
}); | ||
Object.defineProperty(this, _onUpdate, { | ||
value: _onUpdate2 | ||
}); | ||
Object.defineProperty(this, _findMatchingObservers, { | ||
value: _findMatchingObservers2 | ||
}); | ||
Object.defineProperty(this, _client, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _result, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _queries, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _observers, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client] = client; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queries)[_queries] = []; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _result)[_result] = []; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers] = []; | ||
if (_queries2) { | ||
this.setQueries(_queries2); | ||
} | ||
@@ -33,5 +62,5 @@ } | ||
if (this.listeners.length === 1) { | ||
this.#observers.forEach(observer => { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].forEach(observer => { | ||
observer.subscribe(result => { | ||
this.#onUpdate(observer, result); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _onUpdate)[_onUpdate](observer, result); | ||
}); | ||
@@ -48,3 +77,3 @@ }); | ||
this.listeners = []; | ||
this.#observers.forEach(observer => { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].forEach(observer => { | ||
observer.destroy(); | ||
@@ -54,6 +83,6 @@ }); | ||
setQueries(queries, notifyOptions) { | ||
this.#queries = queries; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queries)[_queries] = queries; | ||
notifyManager.notifyManager.batch(() => { | ||
const prevObservers = this.#observers; | ||
const newObserverMatches = this.#findMatchingObservers(this.#queries); | ||
const prevObservers = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers]; | ||
const newObserverMatches = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _findMatchingObservers)[_findMatchingObservers](_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queries)[_queries]); | ||
@@ -68,4 +97,4 @@ // set options for the new observers to notify of changes | ||
} | ||
this.#observers = newObservers; | ||
this.#result = newResult; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers] = newObservers; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _result)[_result] = newResult; | ||
if (!this.hasListeners()) { | ||
@@ -79,63 +108,63 @@ return; | ||
observer.subscribe(result => { | ||
this.#onUpdate(observer, result); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _onUpdate)[_onUpdate](observer, result); | ||
}); | ||
}); | ||
this.#notify(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _notify)[_notify](); | ||
}); | ||
} | ||
getCurrentResult() { | ||
return this.#result; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _result)[_result]; | ||
} | ||
getQueries() { | ||
return this.#observers.map(observer => observer.getCurrentQuery()); | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].map(observer => observer.getCurrentQuery()); | ||
} | ||
getObservers() { | ||
return this.#observers; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers]; | ||
} | ||
getOptimisticResult(queries) { | ||
return this.#findMatchingObservers(queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions)); | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _findMatchingObservers)[_findMatchingObservers](queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions)); | ||
} | ||
#findMatchingObservers(queries) { | ||
const prevObservers = this.#observers; | ||
const defaultedQueryOptions = queries.map(options => this.#client.defaultQueryOptions(options)); | ||
const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => { | ||
const match = prevObservers.find(observer => observer.options.queryHash === defaultedOptions.queryHash); | ||
if (match != null) { | ||
return [{ | ||
defaultedQueryOptions: defaultedOptions, | ||
observer: match | ||
}]; | ||
} | ||
return []; | ||
}); | ||
const matchedQueryHashes = matchingObservers.map(match => match.defaultedQueryOptions.queryHash); | ||
const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.includes(defaultedOptions.queryHash)); | ||
const getObserver = options => { | ||
const defaultedOptions = this.#client.defaultQueryOptions(options); | ||
const currentObserver = this.#observers.find(o => o.options.queryHash === defaultedOptions.queryHash); | ||
return currentObserver ?? new queryObserver.QueryObserver(this.#client, defaultedOptions); | ||
} | ||
function _findMatchingObservers2(queries) { | ||
const prevObservers = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers]; | ||
const defaultedQueryOptions = queries.map(options => _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].defaultQueryOptions(options)); | ||
const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => { | ||
const match = prevObservers.find(observer => observer.options.queryHash === defaultedOptions.queryHash); | ||
if (match != null) { | ||
return [{ | ||
defaultedQueryOptions: defaultedOptions, | ||
observer: match | ||
}]; | ||
} | ||
return []; | ||
}); | ||
const matchedQueryHashes = matchingObservers.map(match => match.defaultedQueryOptions.queryHash); | ||
const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.includes(defaultedOptions.queryHash)); | ||
const getObserver = options => { | ||
const defaultedOptions = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].defaultQueryOptions(options); | ||
const currentObserver = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].find(o => o.options.queryHash === defaultedOptions.queryHash); | ||
return currentObserver != null ? currentObserver : new queryObserver.QueryObserver(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client], defaultedOptions); | ||
}; | ||
const newOrReusedObservers = unmatchedQueries.map(options => { | ||
return { | ||
defaultedQueryOptions: options, | ||
observer: getObserver(options) | ||
}; | ||
const newOrReusedObservers = unmatchedQueries.map(options => { | ||
return { | ||
defaultedQueryOptions: options, | ||
observer: getObserver(options) | ||
}; | ||
}); | ||
const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions); | ||
return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries); | ||
}); | ||
const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions); | ||
return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries); | ||
} | ||
function _onUpdate2(observer, result) { | ||
const index = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].indexOf(observer); | ||
if (index !== -1) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _result)[_result] = replaceAt(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _result)[_result], index, result); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _notify)[_notify](); | ||
} | ||
#onUpdate(observer, result) { | ||
const index = this.#observers.indexOf(observer); | ||
if (index !== -1) { | ||
this.#result = replaceAt(this.#result, index, result); | ||
this.#notify(); | ||
} | ||
} | ||
#notify() { | ||
notifyManager.notifyManager.batch(() => { | ||
this.listeners.forEach(listener => { | ||
listener(this.#result); | ||
}); | ||
} | ||
function _notify2() { | ||
notifyManager.notifyManager.batch(() => { | ||
this.listeners.forEach(listener => { | ||
listener(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _result)[_result]); | ||
}); | ||
} | ||
}); | ||
} | ||
@@ -142,0 +171,0 @@ |
@@ -38,5 +38,6 @@ import type { QueryKey, QueryOptions, QueryStatus, QueryMeta, CancelOptions, SetDataOptions, FetchStatus, DefaultError } from './types'; | ||
} | ||
export declare type FetchDirection = 'forward' | 'backward'; | ||
export interface FetchMeta { | ||
fetchMore?: { | ||
direction: 'forward' | 'backward'; | ||
direction: FetchDirection; | ||
}; | ||
@@ -78,3 +79,3 @@ } | ||
type: 'setState'; | ||
state: QueryState<TData, TError>; | ||
state: Partial<QueryState<TData, TError>>; | ||
setStateOptions?: SetStateOptions; | ||
@@ -99,3 +100,3 @@ } | ||
}): TData; | ||
setState(state: QueryState<TData, TError>, setStateOptions?: SetStateOptions): void; | ||
setState(state: Partial<QueryState<TData, TError>>, setStateOptions?: SetStateOptions): void; | ||
cancel(options?: CancelOptions): Promise<void>; | ||
@@ -102,0 +103,0 @@ destroy(): void; |
@@ -0,1 +1,2 @@ | ||
import { classPrivateFieldLooseBase as _classPrivateFieldLooseBase, classPrivateFieldLooseKey as _classPrivateFieldLooseKey } from './_virtual/_rollupPluginBabelHelpers.esm.js'; | ||
import { replaceData, noop, timeUntilStale } from './utils.esm.js'; | ||
@@ -7,25 +8,64 @@ import { notifyManager } from './notifyManager.esm.js'; | ||
// TYPES | ||
var _initialState = /*#__PURE__*/_classPrivateFieldLooseKey("initialState"); | ||
var _revertState = /*#__PURE__*/_classPrivateFieldLooseKey("revertState"); | ||
var _cache = /*#__PURE__*/_classPrivateFieldLooseKey("cache"); | ||
var _promise = /*#__PURE__*/_classPrivateFieldLooseKey("promise"); | ||
var _retryer = /*#__PURE__*/_classPrivateFieldLooseKey("retryer"); | ||
var _observers = /*#__PURE__*/_classPrivateFieldLooseKey("observers"); | ||
var _defaultOptions = /*#__PURE__*/_classPrivateFieldLooseKey("defaultOptions"); | ||
var _abortSignalConsumed = /*#__PURE__*/_classPrivateFieldLooseKey("abortSignalConsumed"); | ||
var _setOptions = /*#__PURE__*/_classPrivateFieldLooseKey("setOptions"); | ||
var _dispatch = /*#__PURE__*/_classPrivateFieldLooseKey("dispatch"); | ||
// CLASS | ||
class Query extends Removable { | ||
#initialState; | ||
#revertState; | ||
#cache; | ||
#promise; | ||
#retryer; | ||
#observers; | ||
#defaultOptions; | ||
#abortSignalConsumed; | ||
constructor(config) { | ||
super(); | ||
this.#abortSignalConsumed = false; | ||
this.#defaultOptions = config.defaultOptions; | ||
this.#setOptions(config.options); | ||
this.#observers = []; | ||
this.#cache = config.cache; | ||
Object.defineProperty(this, _dispatch, { | ||
value: _dispatch2 | ||
}); | ||
Object.defineProperty(this, _setOptions, { | ||
value: _setOptions2 | ||
}); | ||
Object.defineProperty(this, _initialState, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _revertState, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _cache, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _promise, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _retryer, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _observers, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _defaultOptions, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _abortSignalConsumed, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_classPrivateFieldLooseBase(this, _abortSignalConsumed)[_abortSignalConsumed] = false; | ||
_classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions] = config.defaultOptions; | ||
_classPrivateFieldLooseBase(this, _setOptions)[_setOptions](config.options); | ||
_classPrivateFieldLooseBase(this, _observers)[_observers] = []; | ||
_classPrivateFieldLooseBase(this, _cache)[_cache] = config.cache; | ||
this.queryKey = config.queryKey; | ||
this.queryHash = config.queryHash; | ||
this.#initialState = config.state || getDefaultState(this.options); | ||
this.state = this.#initialState; | ||
_classPrivateFieldLooseBase(this, _initialState)[_initialState] = config.state || getDefaultState(this.options); | ||
this.state = _classPrivateFieldLooseBase(this, _initialState)[_initialState]; | ||
this.scheduleGc(); | ||
@@ -36,12 +76,5 @@ } | ||
} | ||
#setOptions(options) { | ||
this.options = { | ||
...this.#defaultOptions, | ||
...options | ||
}; | ||
this.updateGcTime(this.options.gcTime); | ||
} | ||
optionalRemove() { | ||
if (!this.#observers.length && this.state.fetchStatus === 'idle') { | ||
this.#cache.remove(this); | ||
if (!_classPrivateFieldLooseBase(this, _observers)[_observers].length && this.state.fetchStatus === 'idle') { | ||
_classPrivateFieldLooseBase(this, _cache)[_cache].remove(this); | ||
} | ||
@@ -53,7 +86,7 @@ } | ||
// Set data and mark it as cached | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
data, | ||
type: 'success', | ||
dataUpdatedAt: options?.updatedAt, | ||
manual: options?.manual | ||
dataUpdatedAt: options == null ? void 0 : options.updatedAt, | ||
manual: options == null ? void 0 : options.manual | ||
}); | ||
@@ -63,3 +96,3 @@ return data; | ||
setState(state, setStateOptions) { | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'setState', | ||
@@ -71,4 +104,5 @@ state, | ||
cancel(options) { | ||
const promise = this.#promise; | ||
this.#retryer?.cancel(options); | ||
var _classPrivateFieldLoo; | ||
const promise = _classPrivateFieldLooseBase(this, _promise)[_promise]; | ||
(_classPrivateFieldLoo = _classPrivateFieldLooseBase(this, _retryer)[_retryer]) == null ? void 0 : _classPrivateFieldLoo.cancel(options); | ||
return promise ? promise.then(noop).catch(noop) : Promise.resolve(); | ||
@@ -84,6 +118,6 @@ } | ||
this.destroy(); | ||
this.setState(this.#initialState); | ||
this.setState(_classPrivateFieldLooseBase(this, _initialState)[_initialState]); | ||
} | ||
isActive() { | ||
return this.#observers.some(observer => observer.options.enabled !== false); | ||
return _classPrivateFieldLooseBase(this, _observers)[_observers].some(observer => observer.options.enabled !== false); | ||
} | ||
@@ -94,3 +128,3 @@ isDisabled() { | ||
isStale() { | ||
return this.state.isInvalidated || !this.state.dataUpdatedAt || this.#observers.some(observer => observer.getCurrentResult().isStale); | ||
return this.state.isInvalidated || !this.state.dataUpdatedAt || _classPrivateFieldLooseBase(this, _observers)[_observers].some(observer => observer.getCurrentResult().isStale); | ||
} | ||
@@ -101,4 +135,5 @@ isStaleByTime(staleTime = 0) { | ||
onFocus() { | ||
const observer = this.#observers.find(x => x.shouldFetchOnWindowFocus()); | ||
observer?.refetch({ | ||
var _classPrivateFieldLoo2; | ||
const observer = _classPrivateFieldLooseBase(this, _observers)[_observers].find(x => x.shouldFetchOnWindowFocus()); | ||
observer == null ? void 0 : observer.refetch({ | ||
cancelRefetch: false | ||
@@ -108,7 +143,8 @@ }); | ||
// Continue fetch if currently paused | ||
this.#retryer?.continue(); | ||
(_classPrivateFieldLoo2 = _classPrivateFieldLooseBase(this, _retryer)[_retryer]) == null ? void 0 : _classPrivateFieldLoo2.continue(); | ||
} | ||
onOnline() { | ||
const observer = this.#observers.find(x => x.shouldFetchOnReconnect()); | ||
observer?.refetch({ | ||
var _classPrivateFieldLoo3; | ||
const observer = _classPrivateFieldLooseBase(this, _observers)[_observers].find(x => x.shouldFetchOnReconnect()); | ||
observer == null ? void 0 : observer.refetch({ | ||
cancelRefetch: false | ||
@@ -118,11 +154,11 @@ }); | ||
// Continue fetch if currently paused | ||
this.#retryer?.continue(); | ||
(_classPrivateFieldLoo3 = _classPrivateFieldLooseBase(this, _retryer)[_retryer]) == null ? void 0 : _classPrivateFieldLoo3.continue(); | ||
} | ||
addObserver(observer) { | ||
if (this.#observers.indexOf(observer) === -1) { | ||
this.#observers.push(observer); | ||
if (_classPrivateFieldLooseBase(this, _observers)[_observers].indexOf(observer) === -1) { | ||
_classPrivateFieldLooseBase(this, _observers)[_observers].push(observer); | ||
// Stop the query from being garbage collected | ||
this.clearGcTimeout(); | ||
this.#cache.notify({ | ||
_classPrivateFieldLooseBase(this, _cache)[_cache].notify({ | ||
type: 'observerAdded', | ||
@@ -135,14 +171,14 @@ query: this, | ||
removeObserver(observer) { | ||
if (this.#observers.indexOf(observer) !== -1) { | ||
this.#observers = this.#observers.filter(x => x !== observer); | ||
if (!this.#observers.length) { | ||
if (_classPrivateFieldLooseBase(this, _observers)[_observers].indexOf(observer) !== -1) { | ||
_classPrivateFieldLooseBase(this, _observers)[_observers] = _classPrivateFieldLooseBase(this, _observers)[_observers].filter(x => x !== observer); | ||
if (!_classPrivateFieldLooseBase(this, _observers)[_observers].length) { | ||
// If the transport layer does not support cancellation | ||
// we'll let the query continue so the result can be cached | ||
if (this.#retryer) { | ||
if (this.#abortSignalConsumed) { | ||
this.#retryer.cancel({ | ||
if (_classPrivateFieldLooseBase(this, _retryer)[_retryer]) { | ||
if (_classPrivateFieldLooseBase(this, _abortSignalConsumed)[_abortSignalConsumed]) { | ||
_classPrivateFieldLooseBase(this, _retryer)[_retryer].cancel({ | ||
revert: true | ||
}); | ||
} else { | ||
this.#retryer.cancelRetry(); | ||
_classPrivateFieldLooseBase(this, _retryer)[_retryer].cancelRetry(); | ||
} | ||
@@ -152,3 +188,3 @@ } | ||
} | ||
this.#cache.notify({ | ||
_classPrivateFieldLooseBase(this, _cache)[_cache].notify({ | ||
type: 'observerRemoved', | ||
@@ -161,7 +197,7 @@ query: this, | ||
getObserversCount() { | ||
return this.#observers.length; | ||
return _classPrivateFieldLooseBase(this, _observers)[_observers].length; | ||
} | ||
invalidate() { | ||
if (!this.state.isInvalidated) { | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'invalidate' | ||
@@ -172,4 +208,5 @@ }); | ||
fetch(options, fetchOptions) { | ||
var _this$options$behavio, _context$fetchOptions; | ||
if (this.state.fetchStatus !== 'idle') { | ||
if (this.state.dataUpdatedAt && fetchOptions?.cancelRefetch) { | ||
if (this.state.dataUpdatedAt && fetchOptions != null && fetchOptions.cancelRefetch) { | ||
// Silently cancel current fetch if the user wants to cancel refetches | ||
@@ -179,7 +216,8 @@ this.cancel({ | ||
}); | ||
} else if (this.#promise) { | ||
} else if (_classPrivateFieldLooseBase(this, _promise)[_promise]) { | ||
var _classPrivateFieldLoo4; | ||
// make sure that retries that were potentially cancelled due to unmounts can continue | ||
this.#retryer?.continueRetry(); | ||
(_classPrivateFieldLoo4 = _classPrivateFieldLooseBase(this, _retryer)[_retryer]) == null ? void 0 : _classPrivateFieldLoo4.continueRetry(); | ||
// Return current promise if we are already fetching | ||
return this.#promise; | ||
return _classPrivateFieldLooseBase(this, _promise)[_promise]; | ||
} | ||
@@ -190,3 +228,3 @@ } | ||
if (options) { | ||
this.#setOptions(options); | ||
_classPrivateFieldLooseBase(this, _setOptions)[_setOptions](options); | ||
} | ||
@@ -197,5 +235,5 @@ | ||
if (!this.options.queryFn) { | ||
const observer = this.#observers.find(x => x.options.queryFn); | ||
const observer = _classPrivateFieldLooseBase(this, _observers)[_observers].find(x => x.options.queryFn); | ||
if (observer) { | ||
this.#setOptions(observer.options); | ||
_classPrivateFieldLooseBase(this, _setOptions)[_setOptions](observer.options); | ||
} | ||
@@ -223,3 +261,3 @@ } | ||
get: () => { | ||
this.#abortSignalConsumed = true; | ||
_classPrivateFieldLooseBase(this, _abortSignalConsumed)[_abortSignalConsumed] = true; | ||
return abortController.signal; | ||
@@ -236,3 +274,3 @@ } | ||
} | ||
this.#abortSignalConsumed = false; | ||
_classPrivateFieldLooseBase(this, _abortSignalConsumed)[_abortSignalConsumed] = false; | ||
return this.options.queryFn(queryFnContext); | ||
@@ -250,12 +288,13 @@ }; | ||
addSignalProperty(context); | ||
this.options.behavior?.onFetch(context); | ||
(_this$options$behavio = this.options.behavior) == null ? void 0 : _this$options$behavio.onFetch(context); | ||
// Store state in case the current fetch needs to be reverted | ||
this.#revertState = this.state; | ||
_classPrivateFieldLooseBase(this, _revertState)[_revertState] = this.state; | ||
// Set to fetching state if not already in it | ||
if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== context.fetchOptions?.meta) { | ||
this.#dispatch({ | ||
if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) == null ? void 0 : _context$fetchOptions.meta)) { | ||
var _context$fetchOptions2; | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'fetch', | ||
meta: context.fetchOptions?.meta | ||
meta: (_context$fetchOptions2 = context.fetchOptions) == null ? void 0 : _context$fetchOptions2.meta | ||
}); | ||
@@ -266,3 +305,3 @@ } | ||
if (!(isCancelledError(error) && error.silent)) { | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'error', | ||
@@ -273,5 +312,6 @@ error: error | ||
if (!isCancelledError(error)) { | ||
var _classPrivateFieldLoo5, _classPrivateFieldLoo6, _classPrivateFieldLoo7, _classPrivateFieldLoo8; | ||
// Notify cache callback | ||
this.#cache.config.onError?.(error, this); | ||
this.#cache.config.onSettled?.(this.state.data, error, this); | ||
(_classPrivateFieldLoo5 = (_classPrivateFieldLoo6 = _classPrivateFieldLooseBase(this, _cache)[_cache].config).onError) == null ? void 0 : _classPrivateFieldLoo5.call(_classPrivateFieldLoo6, error, this); | ||
(_classPrivateFieldLoo7 = (_classPrivateFieldLoo8 = _classPrivateFieldLooseBase(this, _cache)[_cache].config).onSettled) == null ? void 0 : _classPrivateFieldLoo7.call(_classPrivateFieldLoo8, this.state.data, error, this); | ||
} | ||
@@ -286,6 +326,7 @@ if (!this.isFetchingOptimistic) { | ||
// Try to fetch the data | ||
this.#retryer = createRetryer({ | ||
_classPrivateFieldLooseBase(this, _retryer)[_retryer] = createRetryer({ | ||
fn: context.fetchFn, | ||
abort: abortController.abort.bind(abortController), | ||
onSuccess: data => { | ||
var _classPrivateFieldLoo9, _classPrivateFieldLoo10, _classPrivateFieldLoo11, _classPrivateFieldLoo12; | ||
if (typeof data === 'undefined') { | ||
@@ -301,4 +342,4 @@ if (process.env.NODE_ENV !== 'production') { | ||
// Notify cache callback | ||
this.#cache.config.onSuccess?.(data, this); | ||
this.#cache.config.onSettled?.(data, this.state.error, this); | ||
(_classPrivateFieldLoo9 = (_classPrivateFieldLoo10 = _classPrivateFieldLooseBase(this, _cache)[_cache].config).onSuccess) == null ? void 0 : _classPrivateFieldLoo9.call(_classPrivateFieldLoo10, data, this); | ||
(_classPrivateFieldLoo11 = (_classPrivateFieldLoo12 = _classPrivateFieldLooseBase(this, _cache)[_cache].config).onSettled) == null ? void 0 : _classPrivateFieldLoo11.call(_classPrivateFieldLoo12, data, this.state.error, this); | ||
if (!this.isFetchingOptimistic) { | ||
@@ -312,3 +353,3 @@ // Schedule query gc after fetching | ||
onFail: (failureCount, error) => { | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'failed', | ||
@@ -320,3 +361,3 @@ failureCount, | ||
onPause: () => { | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'pause' | ||
@@ -326,3 +367,3 @@ }); | ||
onContinue: () => { | ||
this.#dispatch({ | ||
_classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'continue' | ||
@@ -335,92 +376,100 @@ }); | ||
}); | ||
this.#promise = this.#retryer.promise; | ||
return this.#promise; | ||
_classPrivateFieldLooseBase(this, _promise)[_promise] = _classPrivateFieldLooseBase(this, _retryer)[_retryer].promise; | ||
return _classPrivateFieldLooseBase(this, _promise)[_promise]; | ||
} | ||
#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, | ||
fetchFailureCount: 0, | ||
fetchFailureReason: null, | ||
fetchMeta: action.meta ?? null, | ||
fetchStatus: canFetch(this.options.networkMode) ? 'fetching' : 'paused', | ||
...(!state.dataUpdatedAt && { | ||
error: null, | ||
status: 'pending' | ||
}) | ||
}; | ||
case 'success': | ||
return { | ||
...state, | ||
data: action.data, | ||
dataUpdateCount: state.dataUpdateCount + 1, | ||
dataUpdatedAt: action.dataUpdatedAt ?? Date.now(), | ||
} | ||
function _setOptions2(options) { | ||
this.options = { | ||
..._classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions], | ||
...options | ||
}; | ||
this.updateGcTime(this.options.gcTime); | ||
} | ||
function _dispatch2(action) { | ||
const reducer = state => { | ||
var _action$meta, _action$dataUpdatedAt; | ||
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, | ||
fetchFailureCount: 0, | ||
fetchFailureReason: null, | ||
fetchMeta: (_action$meta = action.meta) != null ? _action$meta : null, | ||
fetchStatus: canFetch(this.options.networkMode) ? 'fetching' : 'paused', | ||
...(!state.dataUpdatedAt && { | ||
error: null, | ||
isInvalidated: false, | ||
status: 'success', | ||
...(!action.manual && { | ||
fetchStatus: 'idle', | ||
fetchFailureCount: 0, | ||
fetchFailureReason: null | ||
}) | ||
}; | ||
case 'error': | ||
const error = action.error; | ||
if (isCancelledError(error) && error.revert && this.#revertState) { | ||
return { | ||
...this.#revertState | ||
}; | ||
} | ||
return { | ||
...state, | ||
error: error, | ||
errorUpdateCount: state.errorUpdateCount + 1, | ||
errorUpdatedAt: Date.now(), | ||
fetchFailureCount: state.fetchFailureCount + 1, | ||
fetchFailureReason: error, | ||
status: 'pending' | ||
}) | ||
}; | ||
case 'success': | ||
return { | ||
...state, | ||
data: action.data, | ||
dataUpdateCount: state.dataUpdateCount + 1, | ||
dataUpdatedAt: (_action$dataUpdatedAt = action.dataUpdatedAt) != null ? _action$dataUpdatedAt : Date.now(), | ||
error: null, | ||
isInvalidated: false, | ||
status: 'success', | ||
...(!action.manual && { | ||
fetchStatus: 'idle', | ||
status: 'error' | ||
}; | ||
case 'invalidate': | ||
fetchFailureCount: 0, | ||
fetchFailureReason: null | ||
}) | ||
}; | ||
case 'error': | ||
const error = action.error; | ||
if (isCancelledError(error) && error.revert && _classPrivateFieldLooseBase(this, _revertState)[_revertState]) { | ||
return { | ||
...state, | ||
isInvalidated: true | ||
..._classPrivateFieldLooseBase(this, _revertState)[_revertState] | ||
}; | ||
case 'setState': | ||
return { | ||
...state, | ||
...action.state | ||
}; | ||
} | ||
}; | ||
this.state = reducer(this.state); | ||
notifyManager.batch(() => { | ||
this.#observers.forEach(observer => { | ||
observer.onQueryUpdate(action); | ||
}); | ||
this.#cache.notify({ | ||
query: this, | ||
type: 'updated', | ||
action | ||
}); | ||
} | ||
return { | ||
...state, | ||
error: error, | ||
errorUpdateCount: state.errorUpdateCount + 1, | ||
errorUpdatedAt: Date.now(), | ||
fetchFailureCount: state.fetchFailureCount + 1, | ||
fetchFailureReason: error, | ||
fetchStatus: 'idle', | ||
status: 'error' | ||
}; | ||
case 'invalidate': | ||
return { | ||
...state, | ||
isInvalidated: true | ||
}; | ||
case 'setState': | ||
return { | ||
...state, | ||
...action.state | ||
}; | ||
} | ||
}; | ||
this.state = reducer(this.state); | ||
notifyManager.batch(() => { | ||
_classPrivateFieldLooseBase(this, _observers)[_observers].forEach(observer => { | ||
observer.onQueryUpdate(action); | ||
}); | ||
} | ||
_classPrivateFieldLooseBase(this, _cache)[_cache].notify({ | ||
query: this, | ||
type: 'updated', | ||
action | ||
}); | ||
}); | ||
} | ||
@@ -434,3 +483,3 @@ function getDefaultState(options) { | ||
dataUpdateCount: 0, | ||
dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0, | ||
dataUpdatedAt: hasData ? initialDataUpdatedAt != null ? initialDataUpdatedAt : Date.now() : 0, | ||
error: null, | ||
@@ -437,0 +486,0 @@ errorUpdateCount: 0, |
'use strict'; | ||
var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js'); | ||
var utils = require('./utils.js'); | ||
@@ -9,25 +10,64 @@ var notifyManager = require('./notifyManager.js'); | ||
// TYPES | ||
var _initialState = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("initialState"); | ||
var _revertState = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("revertState"); | ||
var _cache = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("cache"); | ||
var _promise = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("promise"); | ||
var _retryer = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("retryer"); | ||
var _observers = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("observers"); | ||
var _defaultOptions = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("defaultOptions"); | ||
var _abortSignalConsumed = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("abortSignalConsumed"); | ||
var _setOptions = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("setOptions"); | ||
var _dispatch = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("dispatch"); | ||
// CLASS | ||
class Query extends removable.Removable { | ||
#initialState; | ||
#revertState; | ||
#cache; | ||
#promise; | ||
#retryer; | ||
#observers; | ||
#defaultOptions; | ||
#abortSignalConsumed; | ||
constructor(config) { | ||
super(); | ||
this.#abortSignalConsumed = false; | ||
this.#defaultOptions = config.defaultOptions; | ||
this.#setOptions(config.options); | ||
this.#observers = []; | ||
this.#cache = config.cache; | ||
Object.defineProperty(this, _dispatch, { | ||
value: _dispatch2 | ||
}); | ||
Object.defineProperty(this, _setOptions, { | ||
value: _setOptions2 | ||
}); | ||
Object.defineProperty(this, _initialState, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _revertState, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _cache, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _promise, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _retryer, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _observers, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _defaultOptions, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _abortSignalConsumed, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _abortSignalConsumed)[_abortSignalConsumed] = false; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions] = config.defaultOptions; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _setOptions)[_setOptions](config.options); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers] = []; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cache)[_cache] = config.cache; | ||
this.queryKey = config.queryKey; | ||
this.queryHash = config.queryHash; | ||
this.#initialState = config.state || getDefaultState(this.options); | ||
this.state = this.#initialState; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _initialState)[_initialState] = config.state || getDefaultState(this.options); | ||
this.state = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _initialState)[_initialState]; | ||
this.scheduleGc(); | ||
@@ -38,12 +78,5 @@ } | ||
} | ||
#setOptions(options) { | ||
this.options = { | ||
...this.#defaultOptions, | ||
...options | ||
}; | ||
this.updateGcTime(this.options.gcTime); | ||
} | ||
optionalRemove() { | ||
if (!this.#observers.length && this.state.fetchStatus === 'idle') { | ||
this.#cache.remove(this); | ||
if (!_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].length && this.state.fetchStatus === 'idle') { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cache)[_cache].remove(this); | ||
} | ||
@@ -55,7 +88,7 @@ } | ||
// Set data and mark it as cached | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
data, | ||
type: 'success', | ||
dataUpdatedAt: options?.updatedAt, | ||
manual: options?.manual | ||
dataUpdatedAt: options == null ? void 0 : options.updatedAt, | ||
manual: options == null ? void 0 : options.manual | ||
}); | ||
@@ -65,3 +98,3 @@ return data; | ||
setState(state, setStateOptions) { | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'setState', | ||
@@ -73,4 +106,5 @@ state, | ||
cancel(options) { | ||
const promise = this.#promise; | ||
this.#retryer?.cancel(options); | ||
var _classPrivateFieldLoo; | ||
const promise = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _promise)[_promise]; | ||
(_classPrivateFieldLoo = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer]) == null ? void 0 : _classPrivateFieldLoo.cancel(options); | ||
return promise ? promise.then(utils.noop).catch(utils.noop) : Promise.resolve(); | ||
@@ -86,6 +120,6 @@ } | ||
this.destroy(); | ||
this.setState(this.#initialState); | ||
this.setState(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _initialState)[_initialState]); | ||
} | ||
isActive() { | ||
return this.#observers.some(observer => observer.options.enabled !== false); | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].some(observer => observer.options.enabled !== false); | ||
} | ||
@@ -96,3 +130,3 @@ isDisabled() { | ||
isStale() { | ||
return this.state.isInvalidated || !this.state.dataUpdatedAt || this.#observers.some(observer => observer.getCurrentResult().isStale); | ||
return this.state.isInvalidated || !this.state.dataUpdatedAt || _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].some(observer => observer.getCurrentResult().isStale); | ||
} | ||
@@ -103,4 +137,5 @@ isStaleByTime(staleTime = 0) { | ||
onFocus() { | ||
const observer = this.#observers.find(x => x.shouldFetchOnWindowFocus()); | ||
observer?.refetch({ | ||
var _classPrivateFieldLoo2; | ||
const observer = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].find(x => x.shouldFetchOnWindowFocus()); | ||
observer == null ? void 0 : observer.refetch({ | ||
cancelRefetch: false | ||
@@ -110,7 +145,8 @@ }); | ||
// Continue fetch if currently paused | ||
this.#retryer?.continue(); | ||
(_classPrivateFieldLoo2 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer]) == null ? void 0 : _classPrivateFieldLoo2.continue(); | ||
} | ||
onOnline() { | ||
const observer = this.#observers.find(x => x.shouldFetchOnReconnect()); | ||
observer?.refetch({ | ||
var _classPrivateFieldLoo3; | ||
const observer = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].find(x => x.shouldFetchOnReconnect()); | ||
observer == null ? void 0 : observer.refetch({ | ||
cancelRefetch: false | ||
@@ -120,11 +156,11 @@ }); | ||
// Continue fetch if currently paused | ||
this.#retryer?.continue(); | ||
(_classPrivateFieldLoo3 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer]) == null ? void 0 : _classPrivateFieldLoo3.continue(); | ||
} | ||
addObserver(observer) { | ||
if (this.#observers.indexOf(observer) === -1) { | ||
this.#observers.push(observer); | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].indexOf(observer) === -1) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].push(observer); | ||
// Stop the query from being garbage collected | ||
this.clearGcTimeout(); | ||
this.#cache.notify({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cache)[_cache].notify({ | ||
type: 'observerAdded', | ||
@@ -137,14 +173,14 @@ query: this, | ||
removeObserver(observer) { | ||
if (this.#observers.indexOf(observer) !== -1) { | ||
this.#observers = this.#observers.filter(x => x !== observer); | ||
if (!this.#observers.length) { | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].indexOf(observer) !== -1) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers] = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].filter(x => x !== observer); | ||
if (!_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].length) { | ||
// If the transport layer does not support cancellation | ||
// we'll let the query continue so the result can be cached | ||
if (this.#retryer) { | ||
if (this.#abortSignalConsumed) { | ||
this.#retryer.cancel({ | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer]) { | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _abortSignalConsumed)[_abortSignalConsumed]) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer].cancel({ | ||
revert: true | ||
}); | ||
} else { | ||
this.#retryer.cancelRetry(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer].cancelRetry(); | ||
} | ||
@@ -154,3 +190,3 @@ } | ||
} | ||
this.#cache.notify({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cache)[_cache].notify({ | ||
type: 'observerRemoved', | ||
@@ -163,7 +199,7 @@ query: this, | ||
getObserversCount() { | ||
return this.#observers.length; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].length; | ||
} | ||
invalidate() { | ||
if (!this.state.isInvalidated) { | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'invalidate' | ||
@@ -174,4 +210,5 @@ }); | ||
fetch(options, fetchOptions) { | ||
var _this$options$behavio, _context$fetchOptions; | ||
if (this.state.fetchStatus !== 'idle') { | ||
if (this.state.dataUpdatedAt && fetchOptions?.cancelRefetch) { | ||
if (this.state.dataUpdatedAt && fetchOptions != null && fetchOptions.cancelRefetch) { | ||
// Silently cancel current fetch if the user wants to cancel refetches | ||
@@ -181,7 +218,8 @@ this.cancel({ | ||
}); | ||
} else if (this.#promise) { | ||
} else if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _promise)[_promise]) { | ||
var _classPrivateFieldLoo4; | ||
// make sure that retries that were potentially cancelled due to unmounts can continue | ||
this.#retryer?.continueRetry(); | ||
(_classPrivateFieldLoo4 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer]) == null ? void 0 : _classPrivateFieldLoo4.continueRetry(); | ||
// Return current promise if we are already fetching | ||
return this.#promise; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _promise)[_promise]; | ||
} | ||
@@ -192,3 +230,3 @@ } | ||
if (options) { | ||
this.#setOptions(options); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _setOptions)[_setOptions](options); | ||
} | ||
@@ -199,5 +237,5 @@ | ||
if (!this.options.queryFn) { | ||
const observer = this.#observers.find(x => x.options.queryFn); | ||
const observer = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].find(x => x.options.queryFn); | ||
if (observer) { | ||
this.#setOptions(observer.options); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _setOptions)[_setOptions](observer.options); | ||
} | ||
@@ -225,3 +263,3 @@ } | ||
get: () => { | ||
this.#abortSignalConsumed = true; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _abortSignalConsumed)[_abortSignalConsumed] = true; | ||
return abortController.signal; | ||
@@ -238,3 +276,3 @@ } | ||
} | ||
this.#abortSignalConsumed = false; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _abortSignalConsumed)[_abortSignalConsumed] = false; | ||
return this.options.queryFn(queryFnContext); | ||
@@ -252,12 +290,13 @@ }; | ||
addSignalProperty(context); | ||
this.options.behavior?.onFetch(context); | ||
(_this$options$behavio = this.options.behavior) == null ? void 0 : _this$options$behavio.onFetch(context); | ||
// Store state in case the current fetch needs to be reverted | ||
this.#revertState = this.state; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _revertState)[_revertState] = this.state; | ||
// Set to fetching state if not already in it | ||
if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== context.fetchOptions?.meta) { | ||
this.#dispatch({ | ||
if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) == null ? void 0 : _context$fetchOptions.meta)) { | ||
var _context$fetchOptions2; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'fetch', | ||
meta: context.fetchOptions?.meta | ||
meta: (_context$fetchOptions2 = context.fetchOptions) == null ? void 0 : _context$fetchOptions2.meta | ||
}); | ||
@@ -268,3 +307,3 @@ } | ||
if (!(retryer.isCancelledError(error) && error.silent)) { | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'error', | ||
@@ -275,5 +314,6 @@ error: error | ||
if (!retryer.isCancelledError(error)) { | ||
var _classPrivateFieldLoo5, _classPrivateFieldLoo6, _classPrivateFieldLoo7, _classPrivateFieldLoo8; | ||
// Notify cache callback | ||
this.#cache.config.onError?.(error, this); | ||
this.#cache.config.onSettled?.(this.state.data, error, this); | ||
(_classPrivateFieldLoo5 = (_classPrivateFieldLoo6 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cache)[_cache].config).onError) == null ? void 0 : _classPrivateFieldLoo5.call(_classPrivateFieldLoo6, error, this); | ||
(_classPrivateFieldLoo7 = (_classPrivateFieldLoo8 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cache)[_cache].config).onSettled) == null ? void 0 : _classPrivateFieldLoo7.call(_classPrivateFieldLoo8, this.state.data, error, this); | ||
} | ||
@@ -288,6 +328,7 @@ if (!this.isFetchingOptimistic) { | ||
// Try to fetch the data | ||
this.#retryer = retryer.createRetryer({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer] = retryer.createRetryer({ | ||
fn: context.fetchFn, | ||
abort: abortController.abort.bind(abortController), | ||
onSuccess: data => { | ||
var _classPrivateFieldLoo9, _classPrivateFieldLoo10, _classPrivateFieldLoo11, _classPrivateFieldLoo12; | ||
if (typeof data === 'undefined') { | ||
@@ -303,4 +344,4 @@ if (process.env.NODE_ENV !== 'production') { | ||
// Notify cache callback | ||
this.#cache.config.onSuccess?.(data, this); | ||
this.#cache.config.onSettled?.(data, this.state.error, this); | ||
(_classPrivateFieldLoo9 = (_classPrivateFieldLoo10 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cache)[_cache].config).onSuccess) == null ? void 0 : _classPrivateFieldLoo9.call(_classPrivateFieldLoo10, data, this); | ||
(_classPrivateFieldLoo11 = (_classPrivateFieldLoo12 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cache)[_cache].config).onSettled) == null ? void 0 : _classPrivateFieldLoo11.call(_classPrivateFieldLoo12, data, this.state.error, this); | ||
if (!this.isFetchingOptimistic) { | ||
@@ -314,3 +355,3 @@ // Schedule query gc after fetching | ||
onFail: (failureCount, error) => { | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'failed', | ||
@@ -322,3 +363,3 @@ failureCount, | ||
onPause: () => { | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'pause' | ||
@@ -328,3 +369,3 @@ }); | ||
onContinue: () => { | ||
this.#dispatch({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _dispatch)[_dispatch]({ | ||
type: 'continue' | ||
@@ -337,92 +378,100 @@ }); | ||
}); | ||
this.#promise = this.#retryer.promise; | ||
return this.#promise; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _promise)[_promise] = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _retryer)[_retryer].promise; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _promise)[_promise]; | ||
} | ||
#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, | ||
fetchFailureCount: 0, | ||
fetchFailureReason: null, | ||
fetchMeta: action.meta ?? null, | ||
fetchStatus: retryer.canFetch(this.options.networkMode) ? 'fetching' : 'paused', | ||
...(!state.dataUpdatedAt && { | ||
error: null, | ||
status: 'pending' | ||
}) | ||
}; | ||
case 'success': | ||
return { | ||
...state, | ||
data: action.data, | ||
dataUpdateCount: state.dataUpdateCount + 1, | ||
dataUpdatedAt: action.dataUpdatedAt ?? Date.now(), | ||
} | ||
function _setOptions2(options) { | ||
this.options = { | ||
..._rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions], | ||
...options | ||
}; | ||
this.updateGcTime(this.options.gcTime); | ||
} | ||
function _dispatch2(action) { | ||
const reducer = state => { | ||
var _action$meta, _action$dataUpdatedAt; | ||
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, | ||
fetchFailureCount: 0, | ||
fetchFailureReason: null, | ||
fetchMeta: (_action$meta = action.meta) != null ? _action$meta : null, | ||
fetchStatus: retryer.canFetch(this.options.networkMode) ? 'fetching' : 'paused', | ||
...(!state.dataUpdatedAt && { | ||
error: null, | ||
isInvalidated: false, | ||
status: 'success', | ||
...(!action.manual && { | ||
fetchStatus: 'idle', | ||
fetchFailureCount: 0, | ||
fetchFailureReason: null | ||
}) | ||
}; | ||
case 'error': | ||
const error = action.error; | ||
if (retryer.isCancelledError(error) && error.revert && this.#revertState) { | ||
return { | ||
...this.#revertState | ||
}; | ||
} | ||
return { | ||
...state, | ||
error: error, | ||
errorUpdateCount: state.errorUpdateCount + 1, | ||
errorUpdatedAt: Date.now(), | ||
fetchFailureCount: state.fetchFailureCount + 1, | ||
fetchFailureReason: error, | ||
status: 'pending' | ||
}) | ||
}; | ||
case 'success': | ||
return { | ||
...state, | ||
data: action.data, | ||
dataUpdateCount: state.dataUpdateCount + 1, | ||
dataUpdatedAt: (_action$dataUpdatedAt = action.dataUpdatedAt) != null ? _action$dataUpdatedAt : Date.now(), | ||
error: null, | ||
isInvalidated: false, | ||
status: 'success', | ||
...(!action.manual && { | ||
fetchStatus: 'idle', | ||
status: 'error' | ||
}; | ||
case 'invalidate': | ||
fetchFailureCount: 0, | ||
fetchFailureReason: null | ||
}) | ||
}; | ||
case 'error': | ||
const error = action.error; | ||
if (retryer.isCancelledError(error) && error.revert && _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _revertState)[_revertState]) { | ||
return { | ||
...state, | ||
isInvalidated: true | ||
..._rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _revertState)[_revertState] | ||
}; | ||
case 'setState': | ||
return { | ||
...state, | ||
...action.state | ||
}; | ||
} | ||
}; | ||
this.state = reducer(this.state); | ||
notifyManager.notifyManager.batch(() => { | ||
this.#observers.forEach(observer => { | ||
observer.onQueryUpdate(action); | ||
}); | ||
this.#cache.notify({ | ||
query: this, | ||
type: 'updated', | ||
action | ||
}); | ||
} | ||
return { | ||
...state, | ||
error: error, | ||
errorUpdateCount: state.errorUpdateCount + 1, | ||
errorUpdatedAt: Date.now(), | ||
fetchFailureCount: state.fetchFailureCount + 1, | ||
fetchFailureReason: error, | ||
fetchStatus: 'idle', | ||
status: 'error' | ||
}; | ||
case 'invalidate': | ||
return { | ||
...state, | ||
isInvalidated: true | ||
}; | ||
case 'setState': | ||
return { | ||
...state, | ||
...action.state | ||
}; | ||
} | ||
}; | ||
this.state = reducer(this.state); | ||
notifyManager.notifyManager.batch(() => { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _observers)[_observers].forEach(observer => { | ||
observer.onQueryUpdate(action); | ||
}); | ||
} | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _cache)[_cache].notify({ | ||
query: this, | ||
type: 'updated', | ||
action | ||
}); | ||
}); | ||
} | ||
@@ -436,3 +485,3 @@ function getDefaultState(options) { | ||
dataUpdateCount: 0, | ||
dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0, | ||
dataUpdatedAt: hasData ? initialDataUpdatedAt != null ? initialDataUpdatedAt : Date.now() : 0, | ||
error: null, | ||
@@ -439,0 +488,0 @@ errorUpdateCount: 0, |
@@ -0,1 +1,2 @@ | ||
import { classPrivateFieldLooseBase as _classPrivateFieldLooseBase, classPrivateFieldLooseKey as _classPrivateFieldLooseKey } from './_virtual/_rollupPluginBabelHelpers.esm.js'; | ||
import { hashQueryKeyByOptions, matchQuery } from './utils.esm.js'; | ||
@@ -6,14 +7,20 @@ import { Query } from './query.esm.js'; | ||
var _queries = /*#__PURE__*/_classPrivateFieldLooseKey("queries"); | ||
// CLASS | ||
class QueryCache extends Subscribable { | ||
#queries; | ||
constructor(config = {}) { | ||
var _config$createStore; | ||
super(); | ||
Object.defineProperty(this, _queries, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
this.config = config; | ||
this.#queries = config.createStore?.() ?? new Map(); | ||
_classPrivateFieldLooseBase(this, _queries)[_queries] = (_config$createStore = config.createStore == null ? void 0 : config.createStore()) != null ? _config$createStore : new Map(); | ||
} | ||
build(client, options, state) { | ||
var _options$queryHash; | ||
const queryKey = options.queryKey; | ||
const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options); | ||
const queryHash = (_options$queryHash = options.queryHash) != null ? _options$queryHash : hashQueryKeyByOptions(queryKey, options); | ||
let query = this.get(queryHash); | ||
@@ -34,4 +41,4 @@ if (!query) { | ||
add(query) { | ||
if (!this.#queries.has(query.queryHash)) { | ||
this.#queries.set(query.queryHash, query); | ||
if (!_classPrivateFieldLooseBase(this, _queries)[_queries].has(query.queryHash)) { | ||
_classPrivateFieldLooseBase(this, _queries)[_queries].set(query.queryHash, query); | ||
this.notify({ | ||
@@ -44,7 +51,7 @@ type: 'added', | ||
remove(query) { | ||
const queryInMap = this.#queries.get(query.queryHash); | ||
const queryInMap = _classPrivateFieldLooseBase(this, _queries)[_queries].get(query.queryHash); | ||
if (queryInMap) { | ||
query.destroy(); | ||
if (queryInMap === query) { | ||
this.#queries.delete(query.queryHash); | ||
_classPrivateFieldLooseBase(this, _queries)[_queries].delete(query.queryHash); | ||
} | ||
@@ -65,6 +72,6 @@ this.notify({ | ||
get(queryHash) { | ||
return this.#queries.get(queryHash); | ||
return _classPrivateFieldLooseBase(this, _queries)[_queries].get(queryHash); | ||
} | ||
getAll() { | ||
return [...this.#queries.values()]; | ||
return [..._classPrivateFieldLooseBase(this, _queries)[_queries].values()]; | ||
} | ||
@@ -71,0 +78,0 @@ find(filters) { |
'use strict'; | ||
var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js'); | ||
var utils = require('./utils.js'); | ||
@@ -8,14 +9,20 @@ var query = require('./query.js'); | ||
var _queries = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("queries"); | ||
// CLASS | ||
class QueryCache extends subscribable.Subscribable { | ||
#queries; | ||
constructor(config = {}) { | ||
var _config$createStore; | ||
super(); | ||
Object.defineProperty(this, _queries, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
this.config = config; | ||
this.#queries = config.createStore?.() ?? new Map(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queries)[_queries] = (_config$createStore = config.createStore == null ? void 0 : config.createStore()) != null ? _config$createStore : new Map(); | ||
} | ||
build(client, options, state) { | ||
var _options$queryHash; | ||
const queryKey = options.queryKey; | ||
const queryHash = options.queryHash ?? utils.hashQueryKeyByOptions(queryKey, options); | ||
const queryHash = (_options$queryHash = options.queryHash) != null ? _options$queryHash : utils.hashQueryKeyByOptions(queryKey, options); | ||
let query$1 = this.get(queryHash); | ||
@@ -36,4 +43,4 @@ if (!query$1) { | ||
add(query) { | ||
if (!this.#queries.has(query.queryHash)) { | ||
this.#queries.set(query.queryHash, query); | ||
if (!_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queries)[_queries].has(query.queryHash)) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queries)[_queries].set(query.queryHash, query); | ||
this.notify({ | ||
@@ -46,7 +53,7 @@ type: 'added', | ||
remove(query) { | ||
const queryInMap = this.#queries.get(query.queryHash); | ||
const queryInMap = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queries)[_queries].get(query.queryHash); | ||
if (queryInMap) { | ||
query.destroy(); | ||
if (queryInMap === query) { | ||
this.#queries.delete(query.queryHash); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queries)[_queries].delete(query.queryHash); | ||
} | ||
@@ -67,6 +74,6 @@ this.notify({ | ||
get(queryHash) { | ||
return this.#queries.get(queryHash); | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queries)[_queries].get(queryHash); | ||
} | ||
getAll() { | ||
return [...this.#queries.values()]; | ||
return [..._rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queries)[_queries].values()]; | ||
} | ||
@@ -73,0 +80,0 @@ find(filters) { |
@@ -0,1 +1,2 @@ | ||
import { classPrivateFieldLooseBase as _classPrivateFieldLooseBase, classPrivateFieldLooseKey as _classPrivateFieldLooseKey } from './_virtual/_rollupPluginBabelHelpers.esm.js'; | ||
import { functionalUpdate, noop, hashKey, partialMatchKey, hashQueryKeyByOptions } from './utils.esm.js'; | ||
@@ -9,34 +10,66 @@ import { QueryCache } from './queryCache.esm.js'; | ||
var _queryCache = /*#__PURE__*/_classPrivateFieldLooseKey("queryCache"); | ||
var _mutationCache = /*#__PURE__*/_classPrivateFieldLooseKey("mutationCache"); | ||
var _defaultOptions = /*#__PURE__*/_classPrivateFieldLooseKey("defaultOptions"); | ||
var _queryDefaults = /*#__PURE__*/_classPrivateFieldLooseKey("queryDefaults"); | ||
var _mutationDefaults = /*#__PURE__*/_classPrivateFieldLooseKey("mutationDefaults"); | ||
var _mountCount = /*#__PURE__*/_classPrivateFieldLooseKey("mountCount"); | ||
var _unsubscribeFocus = /*#__PURE__*/_classPrivateFieldLooseKey("unsubscribeFocus"); | ||
var _unsubscribeOnline = /*#__PURE__*/_classPrivateFieldLooseKey("unsubscribeOnline"); | ||
// CLASS | ||
class QueryClient { | ||
#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 = new Map(); | ||
this.#mutationDefaults = new Map(); | ||
this.#mountCount = 0; | ||
Object.defineProperty(this, _queryCache, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mutationCache, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _defaultOptions, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _queryDefaults, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mutationDefaults, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mountCount, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _unsubscribeFocus, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _unsubscribeOnline, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_classPrivateFieldLooseBase(this, _queryCache)[_queryCache] = config.queryCache || new QueryCache(); | ||
_classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache] = config.mutationCache || new MutationCache(); | ||
_classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions] = config.defaultOptions || {}; | ||
_classPrivateFieldLooseBase(this, _queryDefaults)[_queryDefaults] = new Map(); | ||
_classPrivateFieldLooseBase(this, _mutationDefaults)[_mutationDefaults] = new Map(); | ||
_classPrivateFieldLooseBase(this, _mountCount)[_mountCount] = 0; | ||
} | ||
mount() { | ||
this.#mountCount++; | ||
if (this.#mountCount !== 1) return; | ||
this.#unsubscribeFocus = focusManager.subscribe(() => { | ||
_classPrivateFieldLooseBase(this, _mountCount)[_mountCount]++; | ||
if (_classPrivateFieldLooseBase(this, _mountCount)[_mountCount] !== 1) return; | ||
_classPrivateFieldLooseBase(this, _unsubscribeFocus)[_unsubscribeFocus] = focusManager.subscribe(() => { | ||
if (focusManager.isFocused()) { | ||
this.resumePausedMutations(); | ||
this.#queryCache.onFocus(); | ||
_classPrivateFieldLooseBase(this, _queryCache)[_queryCache].onFocus(); | ||
} | ||
}); | ||
this.#unsubscribeOnline = onlineManager.subscribe(() => { | ||
_classPrivateFieldLooseBase(this, _unsubscribeOnline)[_unsubscribeOnline] = onlineManager.subscribe(() => { | ||
if (onlineManager.isOnline()) { | ||
this.resumePausedMutations(); | ||
this.#queryCache.onOnline(); | ||
_classPrivateFieldLooseBase(this, _queryCache)[_queryCache].onOnline(); | ||
} | ||
@@ -46,11 +79,12 @@ }); | ||
unmount() { | ||
this.#mountCount--; | ||
if (this.#mountCount !== 0) return; | ||
this.#unsubscribeFocus?.(); | ||
this.#unsubscribeFocus = undefined; | ||
this.#unsubscribeOnline?.(); | ||
this.#unsubscribeOnline = undefined; | ||
var _classPrivateFieldLoo, _classPrivateFieldLoo2, _classPrivateFieldLoo3, _classPrivateFieldLoo4; | ||
_classPrivateFieldLooseBase(this, _mountCount)[_mountCount]--; | ||
if (_classPrivateFieldLooseBase(this, _mountCount)[_mountCount] !== 0) return; | ||
(_classPrivateFieldLoo = (_classPrivateFieldLoo2 = _classPrivateFieldLooseBase(this, _unsubscribeFocus))[_unsubscribeFocus]) == null ? void 0 : _classPrivateFieldLoo.call(_classPrivateFieldLoo2); | ||
_classPrivateFieldLooseBase(this, _unsubscribeFocus)[_unsubscribeFocus] = undefined; | ||
(_classPrivateFieldLoo3 = (_classPrivateFieldLoo4 = _classPrivateFieldLooseBase(this, _unsubscribeOnline))[_unsubscribeOnline]) == null ? void 0 : _classPrivateFieldLoo3.call(_classPrivateFieldLoo4); | ||
_classPrivateFieldLooseBase(this, _unsubscribeOnline)[_unsubscribeOnline] = undefined; | ||
} | ||
isFetching(filters) { | ||
return this.#queryCache.findAll({ | ||
return _classPrivateFieldLooseBase(this, _queryCache)[_queryCache].findAll({ | ||
...filters, | ||
@@ -61,3 +95,3 @@ fetchStatus: 'fetching' | ||
isMutating(filters) { | ||
return this.#mutationCache.findAll({ | ||
return _classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].findAll({ | ||
...filters, | ||
@@ -68,5 +102,6 @@ status: 'pending' | ||
getQueryData(queryKey) { | ||
return this.#queryCache.find({ | ||
var _classPrivateFieldLoo5; | ||
return (_classPrivateFieldLoo5 = _classPrivateFieldLooseBase(this, _queryCache)[_queryCache].find({ | ||
queryKey | ||
})?.state.data; | ||
})) == null ? void 0 : _classPrivateFieldLoo5.state.data; | ||
} | ||
@@ -87,6 +122,6 @@ ensureQueryData(options) { | ||
setQueryData(queryKey, updater, options) { | ||
const query = this.#queryCache.find({ | ||
const query = _classPrivateFieldLooseBase(this, _queryCache)[_queryCache].find({ | ||
queryKey | ||
}); | ||
const prevData = query?.state.data; | ||
const prevData = query == null ? void 0 : query.state.data; | ||
const data = functionalUpdate(updater, prevData); | ||
@@ -99,3 +134,3 @@ if (typeof data === 'undefined') { | ||
}); | ||
return this.#queryCache.build(this, defaultedOptions).setData(data, { | ||
return _classPrivateFieldLooseBase(this, _queryCache)[_queryCache].build(this, defaultedOptions).setData(data, { | ||
...options, | ||
@@ -111,8 +146,9 @@ manual: true | ||
getQueryState(queryKey) { | ||
return this.#queryCache.find({ | ||
var _classPrivateFieldLoo6; | ||
return (_classPrivateFieldLoo6 = _classPrivateFieldLooseBase(this, _queryCache)[_queryCache].find({ | ||
queryKey | ||
})?.state; | ||
})) == null ? void 0 : _classPrivateFieldLoo6.state; | ||
} | ||
removeQueries(filters) { | ||
const queryCache = this.#queryCache; | ||
const queryCache = _classPrivateFieldLooseBase(this, _queryCache)[_queryCache]; | ||
notifyManager.batch(() => { | ||
@@ -125,3 +161,3 @@ queryCache.findAll(filters).forEach(query => { | ||
resetQueries(filters, options) { | ||
const queryCache = this.#queryCache; | ||
const queryCache = _classPrivateFieldLooseBase(this, _queryCache)[_queryCache]; | ||
const refetchFilters = { | ||
@@ -142,3 +178,3 @@ type: 'active', | ||
} | ||
const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).map(query => query.cancel(cancelOptions))); | ||
const promises = notifyManager.batch(() => _classPrivateFieldLooseBase(this, _queryCache)[_queryCache].findAll(filters).map(query => query.cancel(cancelOptions))); | ||
return Promise.all(promises).then(noop).catch(noop); | ||
@@ -148,3 +184,4 @@ } | ||
return notifyManager.batch(() => { | ||
this.#queryCache.findAll(filters).forEach(query => { | ||
var _ref, _filters$refetchType; | ||
_classPrivateFieldLooseBase(this, _queryCache)[_queryCache].findAll(filters).forEach(query => { | ||
query.invalidate(); | ||
@@ -157,3 +194,3 @@ }); | ||
...filters, | ||
type: filters.refetchType ?? filters.type ?? 'active' | ||
type: (_ref = (_filters$refetchType = filters.refetchType) != null ? _filters$refetchType : filters.type) != null ? _ref : 'active' | ||
}; | ||
@@ -164,8 +201,11 @@ return this.refetchQueries(refetchFilters, options); | ||
refetchQueries(filters = {}, options) { | ||
const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => query.fetch(undefined, { | ||
...options, | ||
cancelRefetch: options?.cancelRefetch ?? true | ||
}))); | ||
const promises = notifyManager.batch(() => _classPrivateFieldLooseBase(this, _queryCache)[_queryCache].findAll(filters).filter(query => !query.isDisabled()).map(query => { | ||
var _options$cancelRefetc; | ||
return query.fetch(undefined, { | ||
...options, | ||
cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true | ||
}); | ||
})); | ||
let promise = Promise.all(promises).then(noop); | ||
if (!options?.throwOnError) { | ||
if (!(options != null && options.throwOnError)) { | ||
promise = promise.catch(noop); | ||
@@ -182,3 +222,3 @@ } | ||
} | ||
const query = this.#queryCache.build(this, defaultedOptions); | ||
const query = _classPrivateFieldLooseBase(this, _queryCache)[_queryCache].build(this, defaultedOptions); | ||
return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data); | ||
@@ -197,18 +237,18 @@ } | ||
resumePausedMutations() { | ||
return this.#mutationCache.resumePausedMutations(); | ||
return _classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].resumePausedMutations(); | ||
} | ||
getQueryCache() { | ||
return this.#queryCache; | ||
return _classPrivateFieldLooseBase(this, _queryCache)[_queryCache]; | ||
} | ||
getMutationCache() { | ||
return this.#mutationCache; | ||
return _classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache]; | ||
} | ||
getDefaultOptions() { | ||
return this.#defaultOptions; | ||
return _classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions]; | ||
} | ||
setDefaultOptions(options) { | ||
this.#defaultOptions = options; | ||
_classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions] = options; | ||
} | ||
setQueryDefaults(queryKey, options) { | ||
this.#queryDefaults.set(hashKey(queryKey), { | ||
_classPrivateFieldLooseBase(this, _queryDefaults)[_queryDefaults].set(hashKey(queryKey), { | ||
queryKey, | ||
@@ -219,3 +259,3 @@ defaultOptions: options | ||
getQueryDefaults(queryKey) { | ||
const defaults = [...this.#queryDefaults.values()]; | ||
const defaults = [..._classPrivateFieldLooseBase(this, _queryDefaults)[_queryDefaults].values()]; | ||
let result = {}; | ||
@@ -233,3 +273,3 @@ defaults.forEach(queryDefault => { | ||
setMutationDefaults(mutationKey, options) { | ||
this.#mutationDefaults.set(hashKey(mutationKey), { | ||
_classPrivateFieldLooseBase(this, _mutationDefaults)[_mutationDefaults].set(hashKey(mutationKey), { | ||
mutationKey, | ||
@@ -240,3 +280,3 @@ defaultOptions: options | ||
getMutationDefaults(mutationKey) { | ||
const defaults = [...this.#mutationDefaults.values()]; | ||
const defaults = [..._classPrivateFieldLooseBase(this, _mutationDefaults)[_mutationDefaults].values()]; | ||
let result = {}; | ||
@@ -254,8 +294,8 @@ defaults.forEach(queryDefault => { | ||
defaultQueryOptions(options) { | ||
if (options?._defaulted) { | ||
if (options != null && options._defaulted) { | ||
return options; | ||
} | ||
const defaultedOptions = { | ||
...this.#defaultOptions.queries, | ||
...(options?.queryKey && this.getQueryDefaults(options.queryKey)), | ||
..._classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions].queries, | ||
...((options == null ? void 0 : options.queryKey) && this.getQueryDefaults(options.queryKey)), | ||
...options, | ||
@@ -278,8 +318,8 @@ _defaulted: true | ||
defaultMutationOptions(options) { | ||
if (options?._defaulted) { | ||
if (options != null && options._defaulted) { | ||
return options; | ||
} | ||
return { | ||
...this.#defaultOptions.mutations, | ||
...(options?.mutationKey && this.getMutationDefaults(options.mutationKey)), | ||
..._classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions].mutations, | ||
...((options == null ? void 0 : options.mutationKey) && this.getMutationDefaults(options.mutationKey)), | ||
...options, | ||
@@ -290,4 +330,4 @@ _defaulted: true | ||
clear() { | ||
this.#queryCache.clear(); | ||
this.#mutationCache.clear(); | ||
_classPrivateFieldLooseBase(this, _queryCache)[_queryCache].clear(); | ||
_classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].clear(); | ||
} | ||
@@ -294,0 +334,0 @@ } |
'use strict'; | ||
var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js'); | ||
var utils = require('./utils.js'); | ||
@@ -11,34 +12,66 @@ var queryCache = require('./queryCache.js'); | ||
var _queryCache = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("queryCache"); | ||
var _mutationCache = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("mutationCache"); | ||
var _defaultOptions = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("defaultOptions"); | ||
var _queryDefaults = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("queryDefaults"); | ||
var _mutationDefaults = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("mutationDefaults"); | ||
var _mountCount = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("mountCount"); | ||
var _unsubscribeFocus = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("unsubscribeFocus"); | ||
var _unsubscribeOnline = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("unsubscribeOnline"); | ||
// CLASS | ||
class QueryClient { | ||
#queryCache; | ||
#mutationCache; | ||
#defaultOptions; | ||
#queryDefaults; | ||
#mutationDefaults; | ||
#mountCount; | ||
#unsubscribeFocus; | ||
#unsubscribeOnline; | ||
constructor(config = {}) { | ||
this.#queryCache = config.queryCache || new queryCache.QueryCache(); | ||
this.#mutationCache = config.mutationCache || new mutationCache.MutationCache(); | ||
this.#defaultOptions = config.defaultOptions || {}; | ||
this.#queryDefaults = new Map(); | ||
this.#mutationDefaults = new Map(); | ||
this.#mountCount = 0; | ||
Object.defineProperty(this, _queryCache, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mutationCache, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _defaultOptions, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _queryDefaults, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mutationDefaults, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _mountCount, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _unsubscribeFocus, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _unsubscribeOnline, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache] = config.queryCache || new queryCache.QueryCache(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache] = config.mutationCache || new mutationCache.MutationCache(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions] = config.defaultOptions || {}; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryDefaults)[_queryDefaults] = new Map(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationDefaults)[_mutationDefaults] = new Map(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mountCount)[_mountCount] = 0; | ||
} | ||
mount() { | ||
this.#mountCount++; | ||
if (this.#mountCount !== 1) return; | ||
this.#unsubscribeFocus = focusManager.focusManager.subscribe(() => { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mountCount)[_mountCount]++; | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mountCount)[_mountCount] !== 1) return; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _unsubscribeFocus)[_unsubscribeFocus] = focusManager.focusManager.subscribe(() => { | ||
if (focusManager.focusManager.isFocused()) { | ||
this.resumePausedMutations(); | ||
this.#queryCache.onFocus(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].onFocus(); | ||
} | ||
}); | ||
this.#unsubscribeOnline = onlineManager.onlineManager.subscribe(() => { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _unsubscribeOnline)[_unsubscribeOnline] = onlineManager.onlineManager.subscribe(() => { | ||
if (onlineManager.onlineManager.isOnline()) { | ||
this.resumePausedMutations(); | ||
this.#queryCache.onOnline(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].onOnline(); | ||
} | ||
@@ -48,11 +81,12 @@ }); | ||
unmount() { | ||
this.#mountCount--; | ||
if (this.#mountCount !== 0) return; | ||
this.#unsubscribeFocus?.(); | ||
this.#unsubscribeFocus = undefined; | ||
this.#unsubscribeOnline?.(); | ||
this.#unsubscribeOnline = undefined; | ||
var _classPrivateFieldLoo, _classPrivateFieldLoo2, _classPrivateFieldLoo3, _classPrivateFieldLoo4; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mountCount)[_mountCount]--; | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mountCount)[_mountCount] !== 0) return; | ||
(_classPrivateFieldLoo = (_classPrivateFieldLoo2 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _unsubscribeFocus))[_unsubscribeFocus]) == null ? void 0 : _classPrivateFieldLoo.call(_classPrivateFieldLoo2); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _unsubscribeFocus)[_unsubscribeFocus] = undefined; | ||
(_classPrivateFieldLoo3 = (_classPrivateFieldLoo4 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _unsubscribeOnline))[_unsubscribeOnline]) == null ? void 0 : _classPrivateFieldLoo3.call(_classPrivateFieldLoo4); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _unsubscribeOnline)[_unsubscribeOnline] = undefined; | ||
} | ||
isFetching(filters) { | ||
return this.#queryCache.findAll({ | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].findAll({ | ||
...filters, | ||
@@ -63,3 +97,3 @@ fetchStatus: 'fetching' | ||
isMutating(filters) { | ||
return this.#mutationCache.findAll({ | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].findAll({ | ||
...filters, | ||
@@ -70,5 +104,6 @@ status: 'pending' | ||
getQueryData(queryKey) { | ||
return this.#queryCache.find({ | ||
var _classPrivateFieldLoo5; | ||
return (_classPrivateFieldLoo5 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].find({ | ||
queryKey | ||
})?.state.data; | ||
})) == null ? void 0 : _classPrivateFieldLoo5.state.data; | ||
} | ||
@@ -89,6 +124,6 @@ ensureQueryData(options) { | ||
setQueryData(queryKey, updater, options) { | ||
const query = this.#queryCache.find({ | ||
const query = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].find({ | ||
queryKey | ||
}); | ||
const prevData = query?.state.data; | ||
const prevData = query == null ? void 0 : query.state.data; | ||
const data = utils.functionalUpdate(updater, prevData); | ||
@@ -101,3 +136,3 @@ if (typeof data === 'undefined') { | ||
}); | ||
return this.#queryCache.build(this, defaultedOptions).setData(data, { | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].build(this, defaultedOptions).setData(data, { | ||
...options, | ||
@@ -113,8 +148,9 @@ manual: true | ||
getQueryState(queryKey) { | ||
return this.#queryCache.find({ | ||
var _classPrivateFieldLoo6; | ||
return (_classPrivateFieldLoo6 = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].find({ | ||
queryKey | ||
})?.state; | ||
})) == null ? void 0 : _classPrivateFieldLoo6.state; | ||
} | ||
removeQueries(filters) { | ||
const queryCache = this.#queryCache; | ||
const queryCache = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache]; | ||
notifyManager.notifyManager.batch(() => { | ||
@@ -127,3 +163,3 @@ queryCache.findAll(filters).forEach(query => { | ||
resetQueries(filters, options) { | ||
const queryCache = this.#queryCache; | ||
const queryCache = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache]; | ||
const refetchFilters = { | ||
@@ -144,3 +180,3 @@ type: 'active', | ||
} | ||
const promises = notifyManager.notifyManager.batch(() => this.#queryCache.findAll(filters).map(query => query.cancel(cancelOptions))); | ||
const promises = notifyManager.notifyManager.batch(() => _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].findAll(filters).map(query => query.cancel(cancelOptions))); | ||
return Promise.all(promises).then(utils.noop).catch(utils.noop); | ||
@@ -150,3 +186,4 @@ } | ||
return notifyManager.notifyManager.batch(() => { | ||
this.#queryCache.findAll(filters).forEach(query => { | ||
var _ref, _filters$refetchType; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].findAll(filters).forEach(query => { | ||
query.invalidate(); | ||
@@ -159,3 +196,3 @@ }); | ||
...filters, | ||
type: filters.refetchType ?? filters.type ?? 'active' | ||
type: (_ref = (_filters$refetchType = filters.refetchType) != null ? _filters$refetchType : filters.type) != null ? _ref : 'active' | ||
}; | ||
@@ -166,8 +203,11 @@ return this.refetchQueries(refetchFilters, options); | ||
refetchQueries(filters = {}, options) { | ||
const promises = notifyManager.notifyManager.batch(() => this.#queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => query.fetch(undefined, { | ||
...options, | ||
cancelRefetch: options?.cancelRefetch ?? true | ||
}))); | ||
const promises = notifyManager.notifyManager.batch(() => _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].findAll(filters).filter(query => !query.isDisabled()).map(query => { | ||
var _options$cancelRefetc; | ||
return query.fetch(undefined, { | ||
...options, | ||
cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true | ||
}); | ||
})); | ||
let promise = Promise.all(promises).then(utils.noop); | ||
if (!options?.throwOnError) { | ||
if (!(options != null && options.throwOnError)) { | ||
promise = promise.catch(utils.noop); | ||
@@ -184,3 +224,3 @@ } | ||
} | ||
const query = this.#queryCache.build(this, defaultedOptions); | ||
const query = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].build(this, defaultedOptions); | ||
return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data); | ||
@@ -199,18 +239,18 @@ } | ||
resumePausedMutations() { | ||
return this.#mutationCache.resumePausedMutations(); | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].resumePausedMutations(); | ||
} | ||
getQueryCache() { | ||
return this.#queryCache; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache]; | ||
} | ||
getMutationCache() { | ||
return this.#mutationCache; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache]; | ||
} | ||
getDefaultOptions() { | ||
return this.#defaultOptions; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions]; | ||
} | ||
setDefaultOptions(options) { | ||
this.#defaultOptions = options; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions] = options; | ||
} | ||
setQueryDefaults(queryKey, options) { | ||
this.#queryDefaults.set(utils.hashKey(queryKey), { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryDefaults)[_queryDefaults].set(utils.hashKey(queryKey), { | ||
queryKey, | ||
@@ -221,3 +261,3 @@ defaultOptions: options | ||
getQueryDefaults(queryKey) { | ||
const defaults = [...this.#queryDefaults.values()]; | ||
const defaults = [..._rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryDefaults)[_queryDefaults].values()]; | ||
let result = {}; | ||
@@ -235,3 +275,3 @@ defaults.forEach(queryDefault => { | ||
setMutationDefaults(mutationKey, options) { | ||
this.#mutationDefaults.set(utils.hashKey(mutationKey), { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationDefaults)[_mutationDefaults].set(utils.hashKey(mutationKey), { | ||
mutationKey, | ||
@@ -242,3 +282,3 @@ defaultOptions: options | ||
getMutationDefaults(mutationKey) { | ||
const defaults = [...this.#mutationDefaults.values()]; | ||
const defaults = [..._rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationDefaults)[_mutationDefaults].values()]; | ||
let result = {}; | ||
@@ -256,8 +296,8 @@ defaults.forEach(queryDefault => { | ||
defaultQueryOptions(options) { | ||
if (options?._defaulted) { | ||
if (options != null && options._defaulted) { | ||
return options; | ||
} | ||
const defaultedOptions = { | ||
...this.#defaultOptions.queries, | ||
...(options?.queryKey && this.getQueryDefaults(options.queryKey)), | ||
..._rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions].queries, | ||
...((options == null ? void 0 : options.queryKey) && this.getQueryDefaults(options.queryKey)), | ||
...options, | ||
@@ -280,8 +320,8 @@ _defaulted: true | ||
defaultMutationOptions(options) { | ||
if (options?._defaulted) { | ||
if (options != null && options._defaulted) { | ||
return options; | ||
} | ||
return { | ||
...this.#defaultOptions.mutations, | ||
...(options?.mutationKey && this.getMutationDefaults(options.mutationKey)), | ||
..._rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _defaultOptions)[_defaultOptions].mutations, | ||
...((options == null ? void 0 : options.mutationKey) && this.getMutationDefaults(options.mutationKey)), | ||
...options, | ||
@@ -292,4 +332,4 @@ _defaulted: true | ||
clear() { | ||
this.#queryCache.clear(); | ||
this.#mutationCache.clear(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _queryCache)[_queryCache].clear(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _mutationCache)[_mutationCache].clear(); | ||
} | ||
@@ -296,0 +336,0 @@ } |
@@ -1,2 +0,3 @@ | ||
import { shallowEqualObjects, noop, isServer, isValidTimeout, timeUntilStale, replaceData } from './utils.esm.js'; | ||
import { classPrivateFieldLooseBase as _classPrivateFieldLooseBase, classPrivateFieldLooseKey as _classPrivateFieldLooseKey } from './_virtual/_rollupPluginBabelHelpers.esm.js'; | ||
import { shallowEqualObjects, replaceData, noop, isServer, isValidTimeout, timeUntilStale } from './utils.esm.js'; | ||
import { notifyManager } from './notifyManager.esm.js'; | ||
@@ -7,22 +8,118 @@ import { focusManager } from './focusManager.esm.js'; | ||
var _client = /*#__PURE__*/_classPrivateFieldLooseKey("client"); | ||
var _currentQuery = /*#__PURE__*/_classPrivateFieldLooseKey("currentQuery"); | ||
var _currentQueryInitialState = /*#__PURE__*/_classPrivateFieldLooseKey("currentQueryInitialState"); | ||
var _currentResult = /*#__PURE__*/_classPrivateFieldLooseKey("currentResult"); | ||
var _currentResultState = /*#__PURE__*/_classPrivateFieldLooseKey("currentResultState"); | ||
var _currentResultOptions = /*#__PURE__*/_classPrivateFieldLooseKey("currentResultOptions"); | ||
var _previousQueryResult = /*#__PURE__*/_classPrivateFieldLooseKey("previousQueryResult"); | ||
var _selectError = /*#__PURE__*/_classPrivateFieldLooseKey("selectError"); | ||
var _selectFn = /*#__PURE__*/_classPrivateFieldLooseKey("selectFn"); | ||
var _selectResult = /*#__PURE__*/_classPrivateFieldLooseKey("selectResult"); | ||
var _staleTimeoutId = /*#__PURE__*/_classPrivateFieldLooseKey("staleTimeoutId"); | ||
var _refetchIntervalId = /*#__PURE__*/_classPrivateFieldLooseKey("refetchIntervalId"); | ||
var _currentRefetchInterval = /*#__PURE__*/_classPrivateFieldLooseKey("currentRefetchInterval"); | ||
var _trackedProps = /*#__PURE__*/_classPrivateFieldLooseKey("trackedProps"); | ||
var _executeFetch = /*#__PURE__*/_classPrivateFieldLooseKey("executeFetch"); | ||
var _updateStaleTimeout = /*#__PURE__*/_classPrivateFieldLooseKey("updateStaleTimeout"); | ||
var _computeRefetchInterval = /*#__PURE__*/_classPrivateFieldLooseKey("computeRefetchInterval"); | ||
var _updateRefetchInterval = /*#__PURE__*/_classPrivateFieldLooseKey("updateRefetchInterval"); | ||
var _updateTimers = /*#__PURE__*/_classPrivateFieldLooseKey("updateTimers"); | ||
var _clearStaleTimeout = /*#__PURE__*/_classPrivateFieldLooseKey("clearStaleTimeout"); | ||
var _clearRefetchInterval = /*#__PURE__*/_classPrivateFieldLooseKey("clearRefetchInterval"); | ||
var _updateResult = /*#__PURE__*/_classPrivateFieldLooseKey("updateResult"); | ||
var _updateQuery = /*#__PURE__*/_classPrivateFieldLooseKey("updateQuery"); | ||
var _notify = /*#__PURE__*/_classPrivateFieldLooseKey("notify"); | ||
class QueryObserver extends Subscribable { | ||
#client; | ||
#currentQuery = undefined; | ||
#currentQueryInitialState = undefined; | ||
#currentResult = undefined; | ||
#currentResultState; | ||
#currentResultOptions; | ||
#previousQueryResult; | ||
#selectError; | ||
#selectFn; | ||
#selectResult; | ||
#staleTimeoutId; | ||
#refetchIntervalId; | ||
#currentRefetchInterval; | ||
#trackedProps = new Set(); | ||
constructor(client, options) { | ||
super(); | ||
this.#client = client; | ||
Object.defineProperty(this, _notify, { | ||
value: _notify2 | ||
}); | ||
Object.defineProperty(this, _updateQuery, { | ||
value: _updateQuery2 | ||
}); | ||
Object.defineProperty(this, _updateResult, { | ||
value: _updateResult2 | ||
}); | ||
Object.defineProperty(this, _clearRefetchInterval, { | ||
value: _clearRefetchInterval2 | ||
}); | ||
Object.defineProperty(this, _clearStaleTimeout, { | ||
value: _clearStaleTimeout2 | ||
}); | ||
Object.defineProperty(this, _updateTimers, { | ||
value: _updateTimers2 | ||
}); | ||
Object.defineProperty(this, _updateRefetchInterval, { | ||
value: _updateRefetchInterval2 | ||
}); | ||
Object.defineProperty(this, _computeRefetchInterval, { | ||
value: _computeRefetchInterval2 | ||
}); | ||
Object.defineProperty(this, _updateStaleTimeout, { | ||
value: _updateStaleTimeout2 | ||
}); | ||
Object.defineProperty(this, _executeFetch, { | ||
value: _executeFetch2 | ||
}); | ||
Object.defineProperty(this, _client, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _currentQuery, { | ||
writable: true, | ||
value: undefined | ||
}); | ||
Object.defineProperty(this, _currentQueryInitialState, { | ||
writable: true, | ||
value: undefined | ||
}); | ||
Object.defineProperty(this, _currentResult, { | ||
writable: true, | ||
value: undefined | ||
}); | ||
Object.defineProperty(this, _currentResultState, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _currentResultOptions, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _previousQueryResult, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _selectError, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _selectFn, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _selectResult, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _staleTimeoutId, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _refetchIntervalId, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _currentRefetchInterval, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _trackedProps, { | ||
writable: true, | ||
value: new Set() | ||
}); | ||
_classPrivateFieldLooseBase(this, _client)[_client] = client; | ||
this.options = options; | ||
this.#selectError = null; | ||
_classPrivateFieldLooseBase(this, _selectError)[_selectError] = null; | ||
this.bindMethods(); | ||
@@ -36,7 +133,7 @@ this.setOptions(options); | ||
if (this.listeners.length === 1) { | ||
this.#currentQuery.addObserver(this); | ||
if (shouldFetchOnMount(this.#currentQuery, this.options)) { | ||
this.#executeFetch(); | ||
_classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery].addObserver(this); | ||
if (shouldFetchOnMount(_classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], this.options)) { | ||
_classPrivateFieldLooseBase(this, _executeFetch)[_executeFetch](); | ||
} | ||
this.#updateTimers(); | ||
_classPrivateFieldLooseBase(this, _updateTimers)[_updateTimers](); | ||
} | ||
@@ -50,21 +147,21 @@ } | ||
shouldFetchOnReconnect() { | ||
return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnReconnect); | ||
return shouldFetchOn(_classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], this.options, this.options.refetchOnReconnect); | ||
} | ||
shouldFetchOnWindowFocus() { | ||
return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnWindowFocus); | ||
return shouldFetchOn(_classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], this.options, this.options.refetchOnWindowFocus); | ||
} | ||
destroy() { | ||
this.listeners = []; | ||
this.#clearStaleTimeout(); | ||
this.#clearRefetchInterval(); | ||
this.#currentQuery.removeObserver(this); | ||
_classPrivateFieldLooseBase(this, _clearStaleTimeout)[_clearStaleTimeout](); | ||
_classPrivateFieldLooseBase(this, _clearRefetchInterval)[_clearRefetchInterval](); | ||
_classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery].removeObserver(this); | ||
} | ||
setOptions(options, notifyOptions) { | ||
const prevOptions = this.options; | ||
const prevQuery = this.#currentQuery; | ||
this.options = this.#client.defaultQueryOptions(options); | ||
const prevQuery = _classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]; | ||
this.options = _classPrivateFieldLooseBase(this, _client)[_client].defaultQueryOptions(options); | ||
if (!shallowEqualObjects(prevOptions, this.options)) { | ||
this.#client.getQueryCache().notify({ | ||
_classPrivateFieldLooseBase(this, _client)[_client].getQueryCache().notify({ | ||
type: 'observerOptionsUpdated', | ||
query: this.#currentQuery, | ||
query: _classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], | ||
observer: this | ||
@@ -81,30 +178,30 @@ }); | ||
} | ||
this.#updateQuery(); | ||
_classPrivateFieldLooseBase(this, _updateQuery)[_updateQuery](); | ||
const mounted = this.hasListeners(); | ||
// Fetch if there are subscribers | ||
if (mounted && shouldFetchOptionally(this.#currentQuery, prevQuery, this.options, prevOptions)) { | ||
this.#executeFetch(); | ||
if (mounted && shouldFetchOptionally(_classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], prevQuery, this.options, prevOptions)) { | ||
_classPrivateFieldLooseBase(this, _executeFetch)[_executeFetch](); | ||
} | ||
// Update result | ||
this.#updateResult(notifyOptions); | ||
_classPrivateFieldLooseBase(this, _updateResult)[_updateResult](notifyOptions); | ||
// Update stale interval if needed | ||
if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) { | ||
this.#updateStaleTimeout(); | ||
if (mounted && (_classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery] !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) { | ||
_classPrivateFieldLooseBase(this, _updateStaleTimeout)[_updateStaleTimeout](); | ||
} | ||
const nextRefetchInterval = this.#computeRefetchInterval(); | ||
const nextRefetchInterval = _classPrivateFieldLooseBase(this, _computeRefetchInterval)[_computeRefetchInterval](); | ||
// Update refetch interval if needed | ||
if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.#currentRefetchInterval)) { | ||
this.#updateRefetchInterval(nextRefetchInterval); | ||
if (mounted && (_classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery] !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== _classPrivateFieldLooseBase(this, _currentRefetchInterval)[_currentRefetchInterval])) { | ||
_classPrivateFieldLooseBase(this, _updateRefetchInterval)[_updateRefetchInterval](nextRefetchInterval); | ||
} | ||
} | ||
getOptimisticResult(options) { | ||
const query = this.#client.getQueryCache().build(this.#client, options); | ||
const query = _classPrivateFieldLooseBase(this, _client)[_client].getQueryCache().build(_classPrivateFieldLooseBase(this, _client)[_client], options); | ||
return this.createResult(query, options); | ||
} | ||
getCurrentResult() { | ||
return this.#currentResult; | ||
return _classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
} | ||
@@ -118,3 +215,3 @@ trackResult(result) { | ||
get: () => { | ||
this.#trackedProps.add(key); | ||
_classPrivateFieldLooseBase(this, _trackedProps)[_trackedProps].add(key); | ||
return result[key]; | ||
@@ -127,3 +224,3 @@ } | ||
getCurrentQuery() { | ||
return this.#currentQuery; | ||
return _classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]; | ||
} | ||
@@ -138,4 +235,4 @@ refetch({ | ||
fetchOptimistic(options) { | ||
const defaultedOptions = this.#client.defaultQueryOptions(options); | ||
const query = this.#client.getQueryCache().build(this.#client, defaultedOptions); | ||
const defaultedOptions = _classPrivateFieldLooseBase(this, _client)[_client].defaultQueryOptions(options); | ||
const query = _classPrivateFieldLooseBase(this, _client)[_client].getQueryCache().build(_classPrivateFieldLooseBase(this, _client)[_client], defaultedOptions); | ||
query.isFetchingOptimistic = true; | ||
@@ -145,77 +242,20 @@ return query.fetch().then(() => this.createResult(query, defaultedOptions)); | ||
fetch(fetchOptions) { | ||
return this.#executeFetch({ | ||
var _fetchOptions$cancelR; | ||
return _classPrivateFieldLooseBase(this, _executeFetch)[_executeFetch]({ | ||
...fetchOptions, | ||
cancelRefetch: fetchOptions.cancelRefetch ?? true | ||
cancelRefetch: (_fetchOptions$cancelR = fetchOptions.cancelRefetch) != null ? _fetchOptions$cancelR : true | ||
}).then(() => { | ||
this.#updateResult(); | ||
return this.#currentResult; | ||
_classPrivateFieldLooseBase(this, _updateResult)[_updateResult](); | ||
return _classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
}); | ||
} | ||
#executeFetch(fetchOptions) { | ||
// Make sure we reference the latest query as the current one might have been removed | ||
this.#updateQuery(); | ||
// Fetch | ||
let promise = this.#currentQuery.fetch(this.options, fetchOptions); | ||
if (!fetchOptions?.throwOnError) { | ||
promise = promise.catch(noop); | ||
} | ||
return promise; | ||
} | ||
#updateStaleTimeout() { | ||
this.#clearStaleTimeout(); | ||
if (isServer || this.#currentResult.isStale || !isValidTimeout(this.options.staleTime)) { | ||
return; | ||
} | ||
const time = timeUntilStale(this.#currentResult.dataUpdatedAt, this.options.staleTime); | ||
// The timeout is sometimes triggered 1 ms before the stale time expiration. | ||
// To mitigate this issue we always add 1 ms to the timeout. | ||
const timeout = time + 1; | ||
this.#staleTimeoutId = setTimeout(() => { | ||
if (!this.#currentResult.isStale) { | ||
this.#updateResult(); | ||
} | ||
}, timeout); | ||
} | ||
#computeRefetchInterval() { | ||
return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.#currentResult.data, this.#currentQuery) : this.options.refetchInterval ?? false; | ||
} | ||
#updateRefetchInterval(nextInterval) { | ||
this.#clearRefetchInterval(); | ||
this.#currentRefetchInterval = nextInterval; | ||
if (isServer || this.options.enabled === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) { | ||
return; | ||
} | ||
this.#refetchIntervalId = setInterval(() => { | ||
if (this.options.refetchIntervalInBackground || focusManager.isFocused()) { | ||
this.#executeFetch(); | ||
} | ||
}, this.#currentRefetchInterval); | ||
} | ||
#updateTimers() { | ||
this.#updateStaleTimeout(); | ||
this.#updateRefetchInterval(this.#computeRefetchInterval()); | ||
} | ||
#clearStaleTimeout() { | ||
if (this.#staleTimeoutId) { | ||
clearTimeout(this.#staleTimeoutId); | ||
this.#staleTimeoutId = undefined; | ||
} | ||
} | ||
#clearRefetchInterval() { | ||
if (this.#refetchIntervalId) { | ||
clearInterval(this.#refetchIntervalId); | ||
this.#refetchIntervalId = undefined; | ||
} | ||
} | ||
createResult(query, options) { | ||
const prevQuery = this.#currentQuery; | ||
const prevQuery = _classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]; | ||
const prevOptions = this.options; | ||
const prevResult = this.#currentResult; | ||
const prevResultState = this.#currentResultState; | ||
const prevResultOptions = this.#currentResultOptions; | ||
const prevResult = _classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
const prevResultState = _classPrivateFieldLooseBase(this, _currentResultState)[_currentResultState]; | ||
const prevResultOptions = _classPrivateFieldLooseBase(this, _currentResultOptions)[_currentResultOptions]; | ||
const queryChange = query !== prevQuery; | ||
const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState; | ||
const prevQueryResult = queryChange ? this.#currentResult : this.#previousQueryResult; | ||
const queryInitialState = queryChange ? query.state : _classPrivateFieldLooseBase(this, _currentQueryInitialState)[_currentQueryInitialState]; | ||
const prevQueryResult = queryChange ? _classPrivateFieldLooseBase(this, _currentResult)[_currentResult] : _classPrivateFieldLooseBase(this, _previousQueryResult)[_previousQueryResult]; | ||
const { | ||
@@ -252,13 +292,13 @@ state | ||
// Memoize select result | ||
if (prevResult && state.data === prevResultState?.data && options.select === this.#selectFn) { | ||
data = this.#selectResult; | ||
if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === _classPrivateFieldLooseBase(this, _selectFn)[_selectFn]) { | ||
data = _classPrivateFieldLooseBase(this, _selectResult)[_selectResult]; | ||
} else { | ||
try { | ||
this.#selectFn = options.select; | ||
_classPrivateFieldLooseBase(this, _selectFn)[_selectFn] = options.select; | ||
data = options.select(state.data); | ||
data = replaceData(prevResult?.data, data, options); | ||
this.#selectResult = data; | ||
this.#selectError = null; | ||
data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options); | ||
_classPrivateFieldLooseBase(this, _selectResult)[_selectResult] = data; | ||
_classPrivateFieldLooseBase(this, _selectError)[_selectError] = null; | ||
} catch (selectError) { | ||
this.#selectError = selectError; | ||
_classPrivateFieldLooseBase(this, _selectError)[_selectError] = selectError; | ||
} | ||
@@ -277,12 +317,12 @@ } | ||
// Memoize placeholder data | ||
if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) { | ||
if (prevResult != null && prevResult.isPlaceholderData && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) { | ||
placeholderData = prevResult.data; | ||
} else { | ||
placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData(prevQueryResult?.data) : options.placeholderData; | ||
placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData(prevQueryResult == null ? void 0 : prevQueryResult.data) : options.placeholderData; | ||
if (options.select && typeof placeholderData !== 'undefined') { | ||
try { | ||
placeholderData = options.select(placeholderData); | ||
this.#selectError = null; | ||
_classPrivateFieldLooseBase(this, _selectError)[_selectError] = null; | ||
} catch (selectError) { | ||
this.#selectError = selectError; | ||
_classPrivateFieldLooseBase(this, _selectError)[_selectError] = selectError; | ||
} | ||
@@ -293,9 +333,9 @@ } | ||
status = 'success'; | ||
data = replaceData(prevResult?.data, placeholderData, options); | ||
data = replaceData(prevResult == null ? void 0 : prevResult.data, placeholderData, options); | ||
isPlaceholderData = true; | ||
} | ||
} | ||
if (this.#selectError) { | ||
error = this.#selectError; | ||
data = this.#selectResult; | ||
if (_classPrivateFieldLooseBase(this, _selectError)[_selectError]) { | ||
error = _classPrivateFieldLooseBase(this, _selectError)[_selectError]; | ||
data = _classPrivateFieldLooseBase(this, _selectResult)[_selectResult]; | ||
errorUpdatedAt = Date.now(); | ||
@@ -336,58 +376,2 @@ status = 'error'; | ||
} | ||
#updateResult(notifyOptions) { | ||
const prevResult = this.#currentResult; | ||
const nextResult = this.createResult(this.#currentQuery, this.options); | ||
this.#currentResultState = this.#currentQuery.state; | ||
this.#currentResultOptions = this.options; | ||
// Only notify and update result if something has changed | ||
if (shallowEqualObjects(nextResult, prevResult)) { | ||
return; | ||
} | ||
this.#currentResult = nextResult; | ||
// Determine which callbacks to trigger | ||
const defaultNotifyOptions = {}; | ||
const shouldNotifyListeners = () => { | ||
if (!prevResult) { | ||
return true; | ||
} | ||
const { | ||
notifyOnChangeProps | ||
} = this.options; | ||
if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !this.#trackedProps.size) { | ||
return true; | ||
} | ||
const includedProps = new Set(notifyOnChangeProps ?? this.#trackedProps); | ||
if (this.options.throwErrors) { | ||
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); | ||
}); | ||
}; | ||
if (notifyOptions?.listeners !== false && shouldNotifyListeners()) { | ||
defaultNotifyOptions.listeners = true; | ||
} | ||
this.#notify({ | ||
...defaultNotifyOptions, | ||
...notifyOptions | ||
}); | ||
} | ||
#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; | ||
this.#previousQueryResult = this.#currentResult; | ||
if (this.hasListeners()) { | ||
prevQuery?.removeObserver(this); | ||
query.addObserver(this); | ||
} | ||
} | ||
onQueryUpdate(action) { | ||
@@ -400,33 +384,150 @@ const notifyOptions = {}; | ||
} | ||
this.#updateResult(notifyOptions); | ||
_classPrivateFieldLooseBase(this, _updateResult)[_updateResult](notifyOptions); | ||
if (this.hasListeners()) { | ||
this.#updateTimers(); | ||
_classPrivateFieldLooseBase(this, _updateTimers)[_updateTimers](); | ||
} | ||
} | ||
#notify(notifyOptions) { | ||
notifyManager.batch(() => { | ||
// First trigger the configuration callbacks | ||
if (notifyOptions.onSuccess) { | ||
this.options.onSuccess?.(this.#currentResult.data); | ||
this.options.onSettled?.(this.#currentResult.data, null); | ||
} else if (notifyOptions.onError) { | ||
this.options.onError?.(this.#currentResult.error); | ||
this.options.onSettled?.(undefined, this.#currentResult.error); | ||
} | ||
} | ||
function _executeFetch2(fetchOptions) { | ||
// Make sure we reference the latest query as the current one might have been removed | ||
_classPrivateFieldLooseBase(this, _updateQuery)[_updateQuery](); | ||
// Then trigger the listeners | ||
if (notifyOptions.listeners) { | ||
this.listeners.forEach(listener => { | ||
listener(this.#currentResult); | ||
}); | ||
} | ||
// Fetch | ||
let promise = _classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery].fetch(this.options, fetchOptions); | ||
if (!(fetchOptions != null && fetchOptions.throwOnError)) { | ||
promise = promise.catch(noop); | ||
} | ||
return promise; | ||
} | ||
function _updateStaleTimeout2() { | ||
_classPrivateFieldLooseBase(this, _clearStaleTimeout)[_clearStaleTimeout](); | ||
if (isServer || _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].isStale || !isValidTimeout(this.options.staleTime)) { | ||
return; | ||
} | ||
const time = timeUntilStale(_classPrivateFieldLooseBase(this, _currentResult)[_currentResult].dataUpdatedAt, this.options.staleTime); | ||
// Then the cache listeners | ||
this.#client.getQueryCache().notify({ | ||
query: this.#currentQuery, | ||
type: 'observerResultsUpdated' | ||
}); | ||
// The timeout is sometimes triggered 1 ms before the stale time expiration. | ||
// To mitigate this issue we always add 1 ms to the timeout. | ||
const timeout = time + 1; | ||
_classPrivateFieldLooseBase(this, _staleTimeoutId)[_staleTimeoutId] = setTimeout(() => { | ||
if (!_classPrivateFieldLooseBase(this, _currentResult)[_currentResult].isStale) { | ||
_classPrivateFieldLooseBase(this, _updateResult)[_updateResult](); | ||
} | ||
}, timeout); | ||
} | ||
function _computeRefetchInterval2() { | ||
var _this$options$refetch; | ||
return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(_classPrivateFieldLooseBase(this, _currentResult)[_currentResult].data, _classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]) : (_this$options$refetch = this.options.refetchInterval) != null ? _this$options$refetch : false; | ||
} | ||
function _updateRefetchInterval2(nextInterval) { | ||
_classPrivateFieldLooseBase(this, _clearRefetchInterval)[_clearRefetchInterval](); | ||
_classPrivateFieldLooseBase(this, _currentRefetchInterval)[_currentRefetchInterval] = nextInterval; | ||
if (isServer || this.options.enabled === false || !isValidTimeout(_classPrivateFieldLooseBase(this, _currentRefetchInterval)[_currentRefetchInterval]) || _classPrivateFieldLooseBase(this, _currentRefetchInterval)[_currentRefetchInterval] === 0) { | ||
return; | ||
} | ||
_classPrivateFieldLooseBase(this, _refetchIntervalId)[_refetchIntervalId] = setInterval(() => { | ||
if (this.options.refetchIntervalInBackground || focusManager.isFocused()) { | ||
_classPrivateFieldLooseBase(this, _executeFetch)[_executeFetch](); | ||
} | ||
}, _classPrivateFieldLooseBase(this, _currentRefetchInterval)[_currentRefetchInterval]); | ||
} | ||
function _updateTimers2() { | ||
_classPrivateFieldLooseBase(this, _updateStaleTimeout)[_updateStaleTimeout](); | ||
_classPrivateFieldLooseBase(this, _updateRefetchInterval)[_updateRefetchInterval](_classPrivateFieldLooseBase(this, _computeRefetchInterval)[_computeRefetchInterval]()); | ||
} | ||
function _clearStaleTimeout2() { | ||
if (_classPrivateFieldLooseBase(this, _staleTimeoutId)[_staleTimeoutId]) { | ||
clearTimeout(_classPrivateFieldLooseBase(this, _staleTimeoutId)[_staleTimeoutId]); | ||
_classPrivateFieldLooseBase(this, _staleTimeoutId)[_staleTimeoutId] = undefined; | ||
} | ||
} | ||
function _clearRefetchInterval2() { | ||
if (_classPrivateFieldLooseBase(this, _refetchIntervalId)[_refetchIntervalId]) { | ||
clearInterval(_classPrivateFieldLooseBase(this, _refetchIntervalId)[_refetchIntervalId]); | ||
_classPrivateFieldLooseBase(this, _refetchIntervalId)[_refetchIntervalId] = undefined; | ||
} | ||
} | ||
function _updateResult2(notifyOptions) { | ||
const prevResult = _classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
const nextResult = this.createResult(_classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], this.options); | ||
_classPrivateFieldLooseBase(this, _currentResultState)[_currentResultState] = _classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery].state; | ||
_classPrivateFieldLooseBase(this, _currentResultOptions)[_currentResultOptions] = this.options; | ||
// Only notify and update result if something has changed | ||
if (shallowEqualObjects(nextResult, prevResult)) { | ||
return; | ||
} | ||
_classPrivateFieldLooseBase(this, _currentResult)[_currentResult] = nextResult; | ||
// Determine which callbacks to trigger | ||
const defaultNotifyOptions = {}; | ||
const shouldNotifyListeners = () => { | ||
if (!prevResult) { | ||
return true; | ||
} | ||
const { | ||
notifyOnChangeProps | ||
} = this.options; | ||
if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !_classPrivateFieldLooseBase(this, _trackedProps)[_trackedProps].size) { | ||
return true; | ||
} | ||
const includedProps = new Set(notifyOnChangeProps != null ? notifyOnChangeProps : _classPrivateFieldLooseBase(this, _trackedProps)[_trackedProps]); | ||
if (this.options.throwErrors) { | ||
includedProps.add('error'); | ||
} | ||
return Object.keys(_classPrivateFieldLooseBase(this, _currentResult)[_currentResult]).some(key => { | ||
const typedKey = key; | ||
const changed = _classPrivateFieldLooseBase(this, _currentResult)[_currentResult][typedKey] !== prevResult[typedKey]; | ||
return changed && includedProps.has(typedKey); | ||
}); | ||
}; | ||
if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && shouldNotifyListeners()) { | ||
defaultNotifyOptions.listeners = true; | ||
} | ||
_classPrivateFieldLooseBase(this, _notify)[_notify]({ | ||
...defaultNotifyOptions, | ||
...notifyOptions | ||
}); | ||
} | ||
function _updateQuery2() { | ||
const query = _classPrivateFieldLooseBase(this, _client)[_client].getQueryCache().build(_classPrivateFieldLooseBase(this, _client)[_client], this.options); | ||
if (query === _classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]) { | ||
return; | ||
} | ||
const prevQuery = _classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]; | ||
_classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery] = query; | ||
_classPrivateFieldLooseBase(this, _currentQueryInitialState)[_currentQueryInitialState] = query.state; | ||
_classPrivateFieldLooseBase(this, _previousQueryResult)[_previousQueryResult] = _classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
if (this.hasListeners()) { | ||
prevQuery == null ? void 0 : prevQuery.removeObserver(this); | ||
query.addObserver(this); | ||
} | ||
} | ||
function _notify2(notifyOptions) { | ||
notifyManager.batch(() => { | ||
// First trigger the configuration callbacks | ||
if (notifyOptions.onSuccess) { | ||
var _this$options$onSucce, _this$options, _this$options$onSettl, _this$options2; | ||
(_this$options$onSucce = (_this$options = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].data); | ||
(_this$options$onSettl = (_this$options2 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options2, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].data, null); | ||
} else if (notifyOptions.onError) { | ||
var _this$options$onError, _this$options3, _this$options$onSettl2, _this$options4; | ||
(_this$options$onError = (_this$options3 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options3, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].error); | ||
(_this$options$onSettl2 = (_this$options4 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options4, undefined, _classPrivateFieldLooseBase(this, _currentResult)[_currentResult].error); | ||
} | ||
// Then trigger the listeners | ||
if (notifyOptions.listeners) { | ||
this.listeners.forEach(listener => { | ||
listener(_classPrivateFieldLooseBase(this, _currentResult)[_currentResult]); | ||
}); | ||
} | ||
// Then the cache listeners | ||
_classPrivateFieldLooseBase(this, _client)[_client].getQueryCache().notify({ | ||
query: _classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], | ||
type: 'observerResultsUpdated' | ||
}); | ||
}); | ||
} | ||
function shouldLoadOnMount(query, options) { | ||
@@ -433,0 +534,0 @@ return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false); |
'use strict'; | ||
var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js'); | ||
var utils = require('./utils.js'); | ||
@@ -9,22 +10,118 @@ var notifyManager = require('./notifyManager.js'); | ||
var _client = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("client"); | ||
var _currentQuery = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("currentQuery"); | ||
var _currentQueryInitialState = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("currentQueryInitialState"); | ||
var _currentResult = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("currentResult"); | ||
var _currentResultState = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("currentResultState"); | ||
var _currentResultOptions = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("currentResultOptions"); | ||
var _previousQueryResult = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("previousQueryResult"); | ||
var _selectError = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("selectError"); | ||
var _selectFn = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("selectFn"); | ||
var _selectResult = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("selectResult"); | ||
var _staleTimeoutId = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("staleTimeoutId"); | ||
var _refetchIntervalId = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("refetchIntervalId"); | ||
var _currentRefetchInterval = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("currentRefetchInterval"); | ||
var _trackedProps = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("trackedProps"); | ||
var _executeFetch = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("executeFetch"); | ||
var _updateStaleTimeout = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("updateStaleTimeout"); | ||
var _computeRefetchInterval = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("computeRefetchInterval"); | ||
var _updateRefetchInterval = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("updateRefetchInterval"); | ||
var _updateTimers = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("updateTimers"); | ||
var _clearStaleTimeout = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("clearStaleTimeout"); | ||
var _clearRefetchInterval = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("clearRefetchInterval"); | ||
var _updateResult = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("updateResult"); | ||
var _updateQuery = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("updateQuery"); | ||
var _notify = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("notify"); | ||
class QueryObserver extends subscribable.Subscribable { | ||
#client; | ||
#currentQuery = undefined; | ||
#currentQueryInitialState = undefined; | ||
#currentResult = undefined; | ||
#currentResultState; | ||
#currentResultOptions; | ||
#previousQueryResult; | ||
#selectError; | ||
#selectFn; | ||
#selectResult; | ||
#staleTimeoutId; | ||
#refetchIntervalId; | ||
#currentRefetchInterval; | ||
#trackedProps = new Set(); | ||
constructor(client, options) { | ||
super(); | ||
this.#client = client; | ||
Object.defineProperty(this, _notify, { | ||
value: _notify2 | ||
}); | ||
Object.defineProperty(this, _updateQuery, { | ||
value: _updateQuery2 | ||
}); | ||
Object.defineProperty(this, _updateResult, { | ||
value: _updateResult2 | ||
}); | ||
Object.defineProperty(this, _clearRefetchInterval, { | ||
value: _clearRefetchInterval2 | ||
}); | ||
Object.defineProperty(this, _clearStaleTimeout, { | ||
value: _clearStaleTimeout2 | ||
}); | ||
Object.defineProperty(this, _updateTimers, { | ||
value: _updateTimers2 | ||
}); | ||
Object.defineProperty(this, _updateRefetchInterval, { | ||
value: _updateRefetchInterval2 | ||
}); | ||
Object.defineProperty(this, _computeRefetchInterval, { | ||
value: _computeRefetchInterval2 | ||
}); | ||
Object.defineProperty(this, _updateStaleTimeout, { | ||
value: _updateStaleTimeout2 | ||
}); | ||
Object.defineProperty(this, _executeFetch, { | ||
value: _executeFetch2 | ||
}); | ||
Object.defineProperty(this, _client, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _currentQuery, { | ||
writable: true, | ||
value: undefined | ||
}); | ||
Object.defineProperty(this, _currentQueryInitialState, { | ||
writable: true, | ||
value: undefined | ||
}); | ||
Object.defineProperty(this, _currentResult, { | ||
writable: true, | ||
value: undefined | ||
}); | ||
Object.defineProperty(this, _currentResultState, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _currentResultOptions, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _previousQueryResult, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _selectError, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _selectFn, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _selectResult, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _staleTimeoutId, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _refetchIntervalId, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _currentRefetchInterval, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, _trackedProps, { | ||
writable: true, | ||
value: new Set() | ||
}); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client] = client; | ||
this.options = options; | ||
this.#selectError = null; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectError)[_selectError] = null; | ||
this.bindMethods(); | ||
@@ -38,7 +135,7 @@ this.setOptions(options); | ||
if (this.listeners.length === 1) { | ||
this.#currentQuery.addObserver(this); | ||
if (shouldFetchOnMount(this.#currentQuery, this.options)) { | ||
this.#executeFetch(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery].addObserver(this); | ||
if (shouldFetchOnMount(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], this.options)) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _executeFetch)[_executeFetch](); | ||
} | ||
this.#updateTimers(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateTimers)[_updateTimers](); | ||
} | ||
@@ -52,21 +149,21 @@ } | ||
shouldFetchOnReconnect() { | ||
return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnReconnect); | ||
return shouldFetchOn(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], this.options, this.options.refetchOnReconnect); | ||
} | ||
shouldFetchOnWindowFocus() { | ||
return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnWindowFocus); | ||
return shouldFetchOn(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], this.options, this.options.refetchOnWindowFocus); | ||
} | ||
destroy() { | ||
this.listeners = []; | ||
this.#clearStaleTimeout(); | ||
this.#clearRefetchInterval(); | ||
this.#currentQuery.removeObserver(this); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _clearStaleTimeout)[_clearStaleTimeout](); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _clearRefetchInterval)[_clearRefetchInterval](); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery].removeObserver(this); | ||
} | ||
setOptions(options, notifyOptions) { | ||
const prevOptions = this.options; | ||
const prevQuery = this.#currentQuery; | ||
this.options = this.#client.defaultQueryOptions(options); | ||
const prevQuery = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]; | ||
this.options = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].defaultQueryOptions(options); | ||
if (!utils.shallowEqualObjects(prevOptions, this.options)) { | ||
this.#client.getQueryCache().notify({ | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].getQueryCache().notify({ | ||
type: 'observerOptionsUpdated', | ||
query: this.#currentQuery, | ||
query: _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], | ||
observer: this | ||
@@ -83,30 +180,30 @@ }); | ||
} | ||
this.#updateQuery(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateQuery)[_updateQuery](); | ||
const mounted = this.hasListeners(); | ||
// Fetch if there are subscribers | ||
if (mounted && shouldFetchOptionally(this.#currentQuery, prevQuery, this.options, prevOptions)) { | ||
this.#executeFetch(); | ||
if (mounted && shouldFetchOptionally(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], prevQuery, this.options, prevOptions)) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _executeFetch)[_executeFetch](); | ||
} | ||
// Update result | ||
this.#updateResult(notifyOptions); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateResult)[_updateResult](notifyOptions); | ||
// Update stale interval if needed | ||
if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) { | ||
this.#updateStaleTimeout(); | ||
if (mounted && (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery] !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateStaleTimeout)[_updateStaleTimeout](); | ||
} | ||
const nextRefetchInterval = this.#computeRefetchInterval(); | ||
const nextRefetchInterval = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _computeRefetchInterval)[_computeRefetchInterval](); | ||
// Update refetch interval if needed | ||
if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.#currentRefetchInterval)) { | ||
this.#updateRefetchInterval(nextRefetchInterval); | ||
if (mounted && (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery] !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentRefetchInterval)[_currentRefetchInterval])) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateRefetchInterval)[_updateRefetchInterval](nextRefetchInterval); | ||
} | ||
} | ||
getOptimisticResult(options) { | ||
const query = this.#client.getQueryCache().build(this.#client, options); | ||
const query = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].getQueryCache().build(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client], options); | ||
return this.createResult(query, options); | ||
} | ||
getCurrentResult() { | ||
return this.#currentResult; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
} | ||
@@ -120,3 +217,3 @@ trackResult(result) { | ||
get: () => { | ||
this.#trackedProps.add(key); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _trackedProps)[_trackedProps].add(key); | ||
return result[key]; | ||
@@ -129,3 +226,3 @@ } | ||
getCurrentQuery() { | ||
return this.#currentQuery; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]; | ||
} | ||
@@ -140,4 +237,4 @@ refetch({ | ||
fetchOptimistic(options) { | ||
const defaultedOptions = this.#client.defaultQueryOptions(options); | ||
const query = this.#client.getQueryCache().build(this.#client, defaultedOptions); | ||
const defaultedOptions = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].defaultQueryOptions(options); | ||
const query = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].getQueryCache().build(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client], defaultedOptions); | ||
query.isFetchingOptimistic = true; | ||
@@ -147,77 +244,20 @@ return query.fetch().then(() => this.createResult(query, defaultedOptions)); | ||
fetch(fetchOptions) { | ||
return this.#executeFetch({ | ||
var _fetchOptions$cancelR; | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _executeFetch)[_executeFetch]({ | ||
...fetchOptions, | ||
cancelRefetch: fetchOptions.cancelRefetch ?? true | ||
cancelRefetch: (_fetchOptions$cancelR = fetchOptions.cancelRefetch) != null ? _fetchOptions$cancelR : true | ||
}).then(() => { | ||
this.#updateResult(); | ||
return this.#currentResult; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateResult)[_updateResult](); | ||
return _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
}); | ||
} | ||
#executeFetch(fetchOptions) { | ||
// Make sure we reference the latest query as the current one might have been removed | ||
this.#updateQuery(); | ||
// Fetch | ||
let promise = this.#currentQuery.fetch(this.options, fetchOptions); | ||
if (!fetchOptions?.throwOnError) { | ||
promise = promise.catch(utils.noop); | ||
} | ||
return promise; | ||
} | ||
#updateStaleTimeout() { | ||
this.#clearStaleTimeout(); | ||
if (utils.isServer || this.#currentResult.isStale || !utils.isValidTimeout(this.options.staleTime)) { | ||
return; | ||
} | ||
const time = utils.timeUntilStale(this.#currentResult.dataUpdatedAt, this.options.staleTime); | ||
// The timeout is sometimes triggered 1 ms before the stale time expiration. | ||
// To mitigate this issue we always add 1 ms to the timeout. | ||
const timeout = time + 1; | ||
this.#staleTimeoutId = setTimeout(() => { | ||
if (!this.#currentResult.isStale) { | ||
this.#updateResult(); | ||
} | ||
}, timeout); | ||
} | ||
#computeRefetchInterval() { | ||
return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.#currentResult.data, this.#currentQuery) : this.options.refetchInterval ?? false; | ||
} | ||
#updateRefetchInterval(nextInterval) { | ||
this.#clearRefetchInterval(); | ||
this.#currentRefetchInterval = nextInterval; | ||
if (utils.isServer || this.options.enabled === false || !utils.isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) { | ||
return; | ||
} | ||
this.#refetchIntervalId = setInterval(() => { | ||
if (this.options.refetchIntervalInBackground || focusManager.focusManager.isFocused()) { | ||
this.#executeFetch(); | ||
} | ||
}, this.#currentRefetchInterval); | ||
} | ||
#updateTimers() { | ||
this.#updateStaleTimeout(); | ||
this.#updateRefetchInterval(this.#computeRefetchInterval()); | ||
} | ||
#clearStaleTimeout() { | ||
if (this.#staleTimeoutId) { | ||
clearTimeout(this.#staleTimeoutId); | ||
this.#staleTimeoutId = undefined; | ||
} | ||
} | ||
#clearRefetchInterval() { | ||
if (this.#refetchIntervalId) { | ||
clearInterval(this.#refetchIntervalId); | ||
this.#refetchIntervalId = undefined; | ||
} | ||
} | ||
createResult(query, options) { | ||
const prevQuery = this.#currentQuery; | ||
const prevQuery = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]; | ||
const prevOptions = this.options; | ||
const prevResult = this.#currentResult; | ||
const prevResultState = this.#currentResultState; | ||
const prevResultOptions = this.#currentResultOptions; | ||
const prevResult = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
const prevResultState = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResultState)[_currentResultState]; | ||
const prevResultOptions = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResultOptions)[_currentResultOptions]; | ||
const queryChange = query !== prevQuery; | ||
const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState; | ||
const prevQueryResult = queryChange ? this.#currentResult : this.#previousQueryResult; | ||
const queryInitialState = queryChange ? query.state : _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQueryInitialState)[_currentQueryInitialState]; | ||
const prevQueryResult = queryChange ? _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult] : _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _previousQueryResult)[_previousQueryResult]; | ||
const { | ||
@@ -254,13 +294,13 @@ state | ||
// Memoize select result | ||
if (prevResult && state.data === prevResultState?.data && options.select === this.#selectFn) { | ||
data = this.#selectResult; | ||
if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectFn)[_selectFn]) { | ||
data = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectResult)[_selectResult]; | ||
} else { | ||
try { | ||
this.#selectFn = options.select; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectFn)[_selectFn] = options.select; | ||
data = options.select(state.data); | ||
data = utils.replaceData(prevResult?.data, data, options); | ||
this.#selectResult = data; | ||
this.#selectError = null; | ||
data = utils.replaceData(prevResult == null ? void 0 : prevResult.data, data, options); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectResult)[_selectResult] = data; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectError)[_selectError] = null; | ||
} catch (selectError) { | ||
this.#selectError = selectError; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectError)[_selectError] = selectError; | ||
} | ||
@@ -279,12 +319,12 @@ } | ||
// Memoize placeholder data | ||
if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) { | ||
if (prevResult != null && prevResult.isPlaceholderData && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) { | ||
placeholderData = prevResult.data; | ||
} else { | ||
placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData(prevQueryResult?.data) : options.placeholderData; | ||
placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData(prevQueryResult == null ? void 0 : prevQueryResult.data) : options.placeholderData; | ||
if (options.select && typeof placeholderData !== 'undefined') { | ||
try { | ||
placeholderData = options.select(placeholderData); | ||
this.#selectError = null; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectError)[_selectError] = null; | ||
} catch (selectError) { | ||
this.#selectError = selectError; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectError)[_selectError] = selectError; | ||
} | ||
@@ -295,9 +335,9 @@ } | ||
status = 'success'; | ||
data = utils.replaceData(prevResult?.data, placeholderData, options); | ||
data = utils.replaceData(prevResult == null ? void 0 : prevResult.data, placeholderData, options); | ||
isPlaceholderData = true; | ||
} | ||
} | ||
if (this.#selectError) { | ||
error = this.#selectError; | ||
data = this.#selectResult; | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectError)[_selectError]) { | ||
error = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectError)[_selectError]; | ||
data = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _selectResult)[_selectResult]; | ||
errorUpdatedAt = Date.now(); | ||
@@ -338,58 +378,2 @@ status = 'error'; | ||
} | ||
#updateResult(notifyOptions) { | ||
const prevResult = this.#currentResult; | ||
const nextResult = this.createResult(this.#currentQuery, this.options); | ||
this.#currentResultState = this.#currentQuery.state; | ||
this.#currentResultOptions = this.options; | ||
// Only notify and update result if something has changed | ||
if (utils.shallowEqualObjects(nextResult, prevResult)) { | ||
return; | ||
} | ||
this.#currentResult = nextResult; | ||
// Determine which callbacks to trigger | ||
const defaultNotifyOptions = {}; | ||
const shouldNotifyListeners = () => { | ||
if (!prevResult) { | ||
return true; | ||
} | ||
const { | ||
notifyOnChangeProps | ||
} = this.options; | ||
if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !this.#trackedProps.size) { | ||
return true; | ||
} | ||
const includedProps = new Set(notifyOnChangeProps ?? this.#trackedProps); | ||
if (this.options.throwErrors) { | ||
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); | ||
}); | ||
}; | ||
if (notifyOptions?.listeners !== false && shouldNotifyListeners()) { | ||
defaultNotifyOptions.listeners = true; | ||
} | ||
this.#notify({ | ||
...defaultNotifyOptions, | ||
...notifyOptions | ||
}); | ||
} | ||
#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; | ||
this.#previousQueryResult = this.#currentResult; | ||
if (this.hasListeners()) { | ||
prevQuery?.removeObserver(this); | ||
query.addObserver(this); | ||
} | ||
} | ||
onQueryUpdate(action) { | ||
@@ -402,33 +386,150 @@ const notifyOptions = {}; | ||
} | ||
this.#updateResult(notifyOptions); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateResult)[_updateResult](notifyOptions); | ||
if (this.hasListeners()) { | ||
this.#updateTimers(); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateTimers)[_updateTimers](); | ||
} | ||
} | ||
#notify(notifyOptions) { | ||
notifyManager.notifyManager.batch(() => { | ||
// First trigger the configuration callbacks | ||
if (notifyOptions.onSuccess) { | ||
this.options.onSuccess?.(this.#currentResult.data); | ||
this.options.onSettled?.(this.#currentResult.data, null); | ||
} else if (notifyOptions.onError) { | ||
this.options.onError?.(this.#currentResult.error); | ||
this.options.onSettled?.(undefined, this.#currentResult.error); | ||
} | ||
} | ||
function _executeFetch2(fetchOptions) { | ||
// Make sure we reference the latest query as the current one might have been removed | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateQuery)[_updateQuery](); | ||
// Then trigger the listeners | ||
if (notifyOptions.listeners) { | ||
this.listeners.forEach(listener => { | ||
listener(this.#currentResult); | ||
}); | ||
} | ||
// Fetch | ||
let promise = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery].fetch(this.options, fetchOptions); | ||
if (!(fetchOptions != null && fetchOptions.throwOnError)) { | ||
promise = promise.catch(utils.noop); | ||
} | ||
return promise; | ||
} | ||
function _updateStaleTimeout2() { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _clearStaleTimeout)[_clearStaleTimeout](); | ||
if (utils.isServer || _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].isStale || !utils.isValidTimeout(this.options.staleTime)) { | ||
return; | ||
} | ||
const time = utils.timeUntilStale(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].dataUpdatedAt, this.options.staleTime); | ||
// Then the cache listeners | ||
this.#client.getQueryCache().notify({ | ||
query: this.#currentQuery, | ||
type: 'observerResultsUpdated' | ||
}); | ||
// The timeout is sometimes triggered 1 ms before the stale time expiration. | ||
// To mitigate this issue we always add 1 ms to the timeout. | ||
const timeout = time + 1; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _staleTimeoutId)[_staleTimeoutId] = setTimeout(() => { | ||
if (!_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].isStale) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateResult)[_updateResult](); | ||
} | ||
}, timeout); | ||
} | ||
function _computeRefetchInterval2() { | ||
var _this$options$refetch; | ||
return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].data, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]) : (_this$options$refetch = this.options.refetchInterval) != null ? _this$options$refetch : false; | ||
} | ||
function _updateRefetchInterval2(nextInterval) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _clearRefetchInterval)[_clearRefetchInterval](); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentRefetchInterval)[_currentRefetchInterval] = nextInterval; | ||
if (utils.isServer || this.options.enabled === false || !utils.isValidTimeout(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentRefetchInterval)[_currentRefetchInterval]) || _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentRefetchInterval)[_currentRefetchInterval] === 0) { | ||
return; | ||
} | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _refetchIntervalId)[_refetchIntervalId] = setInterval(() => { | ||
if (this.options.refetchIntervalInBackground || focusManager.focusManager.isFocused()) { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _executeFetch)[_executeFetch](); | ||
} | ||
}, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentRefetchInterval)[_currentRefetchInterval]); | ||
} | ||
function _updateTimers2() { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateStaleTimeout)[_updateStaleTimeout](); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _updateRefetchInterval)[_updateRefetchInterval](_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _computeRefetchInterval)[_computeRefetchInterval]()); | ||
} | ||
function _clearStaleTimeout2() { | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _staleTimeoutId)[_staleTimeoutId]) { | ||
clearTimeout(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _staleTimeoutId)[_staleTimeoutId]); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _staleTimeoutId)[_staleTimeoutId] = undefined; | ||
} | ||
} | ||
function _clearRefetchInterval2() { | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _refetchIntervalId)[_refetchIntervalId]) { | ||
clearInterval(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _refetchIntervalId)[_refetchIntervalId]); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _refetchIntervalId)[_refetchIntervalId] = undefined; | ||
} | ||
} | ||
function _updateResult2(notifyOptions) { | ||
const prevResult = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
const nextResult = this.createResult(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], this.options); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResultState)[_currentResultState] = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery].state; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResultOptions)[_currentResultOptions] = this.options; | ||
// Only notify and update result if something has changed | ||
if (utils.shallowEqualObjects(nextResult, prevResult)) { | ||
return; | ||
} | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult] = nextResult; | ||
// Determine which callbacks to trigger | ||
const defaultNotifyOptions = {}; | ||
const shouldNotifyListeners = () => { | ||
if (!prevResult) { | ||
return true; | ||
} | ||
const { | ||
notifyOnChangeProps | ||
} = this.options; | ||
if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _trackedProps)[_trackedProps].size) { | ||
return true; | ||
} | ||
const includedProps = new Set(notifyOnChangeProps != null ? notifyOnChangeProps : _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _trackedProps)[_trackedProps]); | ||
if (this.options.throwErrors) { | ||
includedProps.add('error'); | ||
} | ||
return Object.keys(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult]).some(key => { | ||
const typedKey = key; | ||
const changed = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult][typedKey] !== prevResult[typedKey]; | ||
return changed && includedProps.has(typedKey); | ||
}); | ||
}; | ||
if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && shouldNotifyListeners()) { | ||
defaultNotifyOptions.listeners = true; | ||
} | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _notify)[_notify]({ | ||
...defaultNotifyOptions, | ||
...notifyOptions | ||
}); | ||
} | ||
function _updateQuery2() { | ||
const query = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].getQueryCache().build(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client], this.options); | ||
if (query === _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]) { | ||
return; | ||
} | ||
const prevQuery = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery]; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery] = query; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQueryInitialState)[_currentQueryInitialState] = query.state; | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _previousQueryResult)[_previousQueryResult] = _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult]; | ||
if (this.hasListeners()) { | ||
prevQuery == null ? void 0 : prevQuery.removeObserver(this); | ||
query.addObserver(this); | ||
} | ||
} | ||
function _notify2(notifyOptions) { | ||
notifyManager.notifyManager.batch(() => { | ||
// First trigger the configuration callbacks | ||
if (notifyOptions.onSuccess) { | ||
var _this$options$onSucce, _this$options, _this$options$onSettl, _this$options2; | ||
(_this$options$onSucce = (_this$options = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].data); | ||
(_this$options$onSettl = (_this$options2 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options2, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].data, null); | ||
} else if (notifyOptions.onError) { | ||
var _this$options$onError, _this$options3, _this$options$onSettl2, _this$options4; | ||
(_this$options$onError = (_this$options3 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options3, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].error); | ||
(_this$options$onSettl2 = (_this$options4 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options4, undefined, _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult].error); | ||
} | ||
// Then trigger the listeners | ||
if (notifyOptions.listeners) { | ||
this.listeners.forEach(listener => { | ||
listener(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentResult)[_currentResult]); | ||
}); | ||
} | ||
// Then the cache listeners | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _client)[_client].getQueryCache().notify({ | ||
query: _rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _currentQuery)[_currentQuery], | ||
type: 'observerResultsUpdated' | ||
}); | ||
}); | ||
} | ||
function shouldLoadOnMount(query, options) { | ||
@@ -435,0 +536,0 @@ return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false); |
@@ -0,5 +1,12 @@ | ||
import { classPrivateFieldLooseBase as _classPrivateFieldLooseBase, classPrivateFieldLooseKey as _classPrivateFieldLooseKey } from './_virtual/_rollupPluginBabelHelpers.esm.js'; | ||
import { isValidTimeout, isServer } from './utils.esm.js'; | ||
var _gcTimeout = /*#__PURE__*/_classPrivateFieldLooseKey("gcTimeout"); | ||
class Removable { | ||
#gcTimeout; | ||
constructor() { | ||
Object.defineProperty(this, _gcTimeout, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
} | ||
destroy() { | ||
@@ -11,3 +18,3 @@ this.clearGcTimeout(); | ||
if (isValidTimeout(this.gcTime)) { | ||
this.#gcTimeout = setTimeout(() => { | ||
_classPrivateFieldLooseBase(this, _gcTimeout)[_gcTimeout] = setTimeout(() => { | ||
this.optionalRemove(); | ||
@@ -19,8 +26,8 @@ }, this.gcTime); | ||
// Default to 5 minutes (Infinity for server-side) if no gcTime is set | ||
this.gcTime = Math.max(this.gcTime || 0, newGcTime ?? (isServer ? Infinity : 5 * 60 * 1000)); | ||
this.gcTime = Math.max(this.gcTime || 0, newGcTime != null ? newGcTime : isServer ? Infinity : 5 * 60 * 1000); | ||
} | ||
clearGcTimeout() { | ||
if (this.#gcTimeout) { | ||
clearTimeout(this.#gcTimeout); | ||
this.#gcTimeout = undefined; | ||
if (_classPrivateFieldLooseBase(this, _gcTimeout)[_gcTimeout]) { | ||
clearTimeout(_classPrivateFieldLooseBase(this, _gcTimeout)[_gcTimeout]); | ||
_classPrivateFieldLooseBase(this, _gcTimeout)[_gcTimeout] = undefined; | ||
} | ||
@@ -27,0 +34,0 @@ } |
'use strict'; | ||
var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js'); | ||
var utils = require('./utils.js'); | ||
var _gcTimeout = /*#__PURE__*/_rollupPluginBabelHelpers.classPrivateFieldLooseKey("gcTimeout"); | ||
class Removable { | ||
#gcTimeout; | ||
constructor() { | ||
Object.defineProperty(this, _gcTimeout, { | ||
writable: true, | ||
value: void 0 | ||
}); | ||
} | ||
destroy() { | ||
@@ -13,3 +20,3 @@ this.clearGcTimeout(); | ||
if (utils.isValidTimeout(this.gcTime)) { | ||
this.#gcTimeout = setTimeout(() => { | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _gcTimeout)[_gcTimeout] = setTimeout(() => { | ||
this.optionalRemove(); | ||
@@ -21,8 +28,8 @@ }, this.gcTime); | ||
// Default to 5 minutes (Infinity for server-side) if no gcTime is set | ||
this.gcTime = Math.max(this.gcTime || 0, newGcTime ?? (utils.isServer ? Infinity : 5 * 60 * 1000)); | ||
this.gcTime = Math.max(this.gcTime || 0, newGcTime != null ? newGcTime : utils.isServer ? Infinity : 5 * 60 * 1000); | ||
} | ||
clearGcTimeout() { | ||
if (this.#gcTimeout) { | ||
clearTimeout(this.#gcTimeout); | ||
this.#gcTimeout = undefined; | ||
if (_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _gcTimeout)[_gcTimeout]) { | ||
clearTimeout(_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _gcTimeout)[_gcTimeout]); | ||
_rollupPluginBabelHelpers.classPrivateFieldLooseBase(this, _gcTimeout)[_gcTimeout] = undefined; | ||
} | ||
@@ -29,0 +36,0 @@ } |
@@ -9,8 +9,8 @@ import { focusManager } from './focusManager.esm.js'; | ||
function canFetch(networkMode) { | ||
return (networkMode ?? 'online') === 'online' ? onlineManager.isOnline() : true; | ||
return (networkMode != null ? networkMode : 'online') === 'online' ? onlineManager.isOnline() : true; | ||
} | ||
class CancelledError { | ||
constructor(options) { | ||
this.revert = options?.revert; | ||
this.silent = options?.silent; | ||
this.revert = options == null ? void 0 : options.revert; | ||
this.silent = options == null ? void 0 : options.silent; | ||
} | ||
@@ -35,3 +35,3 @@ } | ||
reject(new CancelledError(cancelOptions)); | ||
config.abort?.(); | ||
config.abort == null ? void 0 : config.abort(); | ||
} | ||
@@ -49,4 +49,4 @@ }; | ||
isResolved = true; | ||
config.onSuccess?.(value); | ||
continueFn?.(); | ||
config.onSuccess == null ? void 0 : config.onSuccess(value); | ||
continueFn == null ? void 0 : continueFn(); | ||
promiseResolve(value); | ||
@@ -58,4 +58,4 @@ } | ||
isResolved = true; | ||
config.onError?.(value); | ||
continueFn?.(); | ||
config.onError == null ? void 0 : config.onError(value); | ||
continueFn == null ? void 0 : continueFn(); | ||
promiseReject(value); | ||
@@ -73,7 +73,7 @@ } | ||
}; | ||
config.onPause?.(); | ||
config.onPause == null ? void 0 : config.onPause(); | ||
}).then(() => { | ||
continueFn = undefined; | ||
if (!isResolved) { | ||
config.onContinue?.(); | ||
config.onContinue == null ? void 0 : config.onContinue(); | ||
} | ||
@@ -98,2 +98,3 @@ }); | ||
Promise.resolve(promiseOrValue).then(resolve).catch(error => { | ||
var _config$retry, _config$retryDelay; | ||
// Stop if the fetch is already resolved | ||
@@ -105,4 +106,4 @@ if (isResolved) { | ||
// Do we need to retry the request? | ||
const retry = config.retry ?? 3; | ||
const retryDelay = config.retryDelay ?? defaultRetryDelay; | ||
const retry = (_config$retry = config.retry) != null ? _config$retry : 3; | ||
const retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay; | ||
const delay = typeof retryDelay === 'function' ? retryDelay(failureCount, error) : retryDelay; | ||
@@ -118,3 +119,3 @@ const shouldRetry = retry === true || typeof retry === 'number' && failureCount < retry || typeof retry === 'function' && retry(failureCount, error); | ||
// Notify on fail | ||
config.onFail?.(failureCount, error); | ||
config.onFail == null ? void 0 : config.onFail(failureCount, error); | ||
@@ -149,3 +150,3 @@ // Delay | ||
continue: () => { | ||
const didContinue = continueFn?.(); | ||
const didContinue = continueFn == null ? void 0 : continueFn(); | ||
return didContinue ? promise : Promise.resolve(); | ||
@@ -152,0 +153,0 @@ }, |
@@ -11,8 +11,8 @@ 'use strict'; | ||
function canFetch(networkMode) { | ||
return (networkMode ?? 'online') === 'online' ? onlineManager.onlineManager.isOnline() : true; | ||
return (networkMode != null ? networkMode : 'online') === 'online' ? onlineManager.onlineManager.isOnline() : true; | ||
} | ||
class CancelledError { | ||
constructor(options) { | ||
this.revert = options?.revert; | ||
this.silent = options?.silent; | ||
this.revert = options == null ? void 0 : options.revert; | ||
this.silent = options == null ? void 0 : options.silent; | ||
} | ||
@@ -37,3 +37,3 @@ } | ||
reject(new CancelledError(cancelOptions)); | ||
config.abort?.(); | ||
config.abort == null ? void 0 : config.abort(); | ||
} | ||
@@ -51,4 +51,4 @@ }; | ||
isResolved = true; | ||
config.onSuccess?.(value); | ||
continueFn?.(); | ||
config.onSuccess == null ? void 0 : config.onSuccess(value); | ||
continueFn == null ? void 0 : continueFn(); | ||
promiseResolve(value); | ||
@@ -60,4 +60,4 @@ } | ||
isResolved = true; | ||
config.onError?.(value); | ||
continueFn?.(); | ||
config.onError == null ? void 0 : config.onError(value); | ||
continueFn == null ? void 0 : continueFn(); | ||
promiseReject(value); | ||
@@ -75,7 +75,7 @@ } | ||
}; | ||
config.onPause?.(); | ||
config.onPause == null ? void 0 : config.onPause(); | ||
}).then(() => { | ||
continueFn = undefined; | ||
if (!isResolved) { | ||
config.onContinue?.(); | ||
config.onContinue == null ? void 0 : config.onContinue(); | ||
} | ||
@@ -100,2 +100,3 @@ }); | ||
Promise.resolve(promiseOrValue).then(resolve).catch(error => { | ||
var _config$retry, _config$retryDelay; | ||
// Stop if the fetch is already resolved | ||
@@ -107,4 +108,4 @@ if (isResolved) { | ||
// Do we need to retry the request? | ||
const retry = config.retry ?? 3; | ||
const retryDelay = config.retryDelay ?? defaultRetryDelay; | ||
const retry = (_config$retry = config.retry) != null ? _config$retry : 3; | ||
const retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay; | ||
const delay = typeof retryDelay === 'function' ? retryDelay(failureCount, error) : retryDelay; | ||
@@ -120,3 +121,3 @@ const shouldRetry = retry === true || typeof retry === 'number' && failureCount < retry || typeof retry === 'function' && retry(failureCount, error); | ||
// Notify on fail | ||
config.onFail?.(failureCount, error); | ||
config.onFail == null ? void 0 : config.onFail(failureCount, error); | ||
@@ -151,3 +152,3 @@ // Delay | ||
continue: () => { | ||
const didContinue = continueFn?.(); | ||
const didContinue = continueFn == null ? void 0 : continueFn(); | ||
return didContinue ? promise : Promise.resolve(); | ||
@@ -154,0 +155,0 @@ }, |
@@ -7,2 +7,3 @@ import type { MutationState } from './mutation'; | ||
import type { MutationCache } from './mutationCache'; | ||
import type { FetchDirection } from './query'; | ||
export interface Register { | ||
@@ -23,2 +24,3 @@ } | ||
pageParam: TPageParam; | ||
direction: FetchDirection; | ||
meta: QueryMeta | undefined; | ||
@@ -25,0 +27,0 @@ }; |
@@ -84,3 +84,3 @@ // TYPES | ||
function hashQueryKeyByOptions(queryKey, options) { | ||
const hashFn = options?.queryKeyHashFn || hashKey; | ||
const hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashKey; | ||
return hashFn(queryKey); | ||
@@ -87,0 +87,0 @@ } |
@@ -86,3 +86,3 @@ 'use strict'; | ||
function hashQueryKeyByOptions(queryKey, options) { | ||
const hashFn = options?.queryKeyHashFn || hashKey; | ||
const hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashKey; | ||
return hashFn(queryKey); | ||
@@ -89,0 +89,0 @@ } |
@@ -1,2 +0,2 @@ | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).QueryCore={})}(this,(function(t){"use strict";class e{constructor(){this.listeners=[],this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.push(t),this.onSubscribe(),()=>{this.listeners=this.listeners.filter((e=>e!==t)),this.onUnsubscribe()}}hasListeners(){return this.listeners.length>0}onSubscribe(){}onUnsubscribe(){}}const s="undefined"==typeof window||"Deno"in window;function i(){}function r(t){return"number"==typeof t&&t>=0&&t!==1/0}function n(t,e){return Math.max(t+(e||0)-Date.now(),0)}function a(t,e){const{type:s="all",exact:i,fetchStatus:r,predicate:n,queryKey:a,stale:o}=t;if(a)if(i){if(e.queryHash!==u(a,e.options))return!1}else if(!c(e.queryKey,a))return!1;if("all"!==s){const t=e.isActive();if("active"===s&&!t)return!1;if("inactive"===s&&t)return!1}return("boolean"!=typeof o||e.isStale()===o)&&((void 0===r||r===e.state.fetchStatus)&&!(n&&!n(e)))}function o(t,e){const{exact:s,status:i,predicate:r,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(s){if(h(e.options.mutationKey)!==h(n))return!1}else if(!c(e.options.mutationKey,n))return!1}return(!i||e.state.status===i)&&!(r&&!r(e))}function u(t,e){return(e?.queryKeyHashFn||h)(t)}function h(t){return JSON.stringify(t,((t,e)=>p(e)?Object.keys(e).sort().reduce(((t,s)=>(t[s]=e[s],t)),{}):e))}function c(t,e){return t===e||typeof t==typeof e&&(!(!t||!e||"object"!=typeof t||"object"!=typeof e)&&!Object.keys(e).some((s=>!c(t[s],e[s]))))}function l(t,e){if(t===e)return t;const s=f(t)&&f(e);if(s||p(t)&&p(e)){const i=s?t.length:Object.keys(t).length,r=s?e:Object.keys(e),n=r.length,a=s?[]:{};let o=0;for(let i=0;i<n;i++){const n=s?i:r[i];a[n]=l(t[n],e[n]),a[n]===t[n]&&o++}return i===n&&o===i?t:a}return e}function d(t,e){if(t&&!e||e&&!t)return!1;for(const s in t)if(t[s]!==e[s])return!1;return!0}function f(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function p(t){if(!y(t))return!1;const e=t.constructor;if(void 0===e)return!0;const s=e.prototype;return!!y(s)&&!!s.hasOwnProperty("isPrototypeOf")}function y(t){return"[object Object]"===Object.prototype.toString.call(t)}function m(t){return new Promise((e=>{setTimeout(e,t)}))}function v(t){m(0).then(t)}function b(t,e,s){return"function"==typeof s.structuralSharing?s.structuralSharing(t,e):!1!==s.structuralSharing?l(t,e):e}function g(t,e,s=0){const i=[...t,e];return s&&i.length>s?i.slice(1):i}function O(t,e,s=0){const i=[e,...t];return s&&i.length>s?i.slice(0,-1):i}const R=new class extends e{#t;#e;#s;constructor(){super(),this.#s=t=>{if(!s&&window.addEventListener){const e=()=>t();return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#e||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(t){this.#s=t,this.#e?.(),this.#e=t((t=>{"boolean"==typeof t?this.setFocused(t):this.onFocus()}))}setFocused(t){this.#t=t,t&&this.onFocus()}onFocus(){this.listeners.forEach((t=>{t()}))}isFocused(){return"boolean"==typeof this.#t?this.#t:"hidden"!==globalThis.document?.visibilityState}};const C=new class extends e{#i;#e;#s;constructor(){super(),this.#s=t=>{if(!s&&window.addEventListener){const e=()=>t();return window.addEventListener("online",e,!1),window.addEventListener("offline",e,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",e)}}}}onSubscribe(){this.#e||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(t){this.#s=t,this.#e?.(),this.#e=t((t=>{"boolean"==typeof t?this.setOnline(t):this.onOnline()}))}setOnline(t){this.#i=t,t&&this.onOnline()}onOnline(){this.listeners.forEach((t=>{t()}))}isOnline(){return"boolean"==typeof this.#i?this.#i:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine}};function q(t){return Math.min(1e3*2**t,3e4)}function Q(t){return"online"!==(t??"online")||C.isOnline()}class w{constructor(t){this.revert=t?.revert,this.silent=t?.silent}}function S(t){return t instanceof w}function P(t){let e,s,i,r=!1,n=0,a=!1;const o=new Promise(((t,e)=>{s=t,i=e})),u=()=>!R.isFocused()||"always"!==t.networkMode&&!C.isOnline(),h=i=>{a||(a=!0,t.onSuccess?.(i),e?.(),s(i))},c=s=>{a||(a=!0,t.onError?.(s),e?.(),i(s))},l=()=>new Promise((s=>{e=t=>{const e=a||!u();return e&&s(t),e},t.onPause?.()})).then((()=>{e=void 0,a||t.onContinue?.()})),d=()=>{if(a)return;let e;try{e=t.fn()}catch(t){e=Promise.reject(t)}Promise.resolve(e).then(h).catch((e=>{if(a)return;const s=t.retry??3,i=t.retryDelay??q,o="function"==typeof i?i(n,e):i,h=!0===s||"number"==typeof s&&n<s||"function"==typeof s&&s(n,e);!r&&h?(n++,t.onFail?.(n,e),m(o).then((()=>{if(u())return l()})).then((()=>{r?c(e):d()}))):c(e)}))};return Q(t.networkMode)?d():l().then(d),{promise:o,cancel:e=>{a||(c(new w(e)),t.abort?.())},continue:()=>{const t=e?.();return t?o:Promise.resolve()},cancelRetry:()=>{r=!0},continueRetry:()=>{r=!1}}}const M=function(){let t=[],e=0,s=t=>{t()},i=t=>{t()};const r=i=>{e?t.push(i):v((()=>{s(i)}))},n=()=>{const e=t;t=[],e.length&&v((()=>{i((()=>{e.forEach((t=>{s(t)}))}))}))};return{batch:t=>{let s;e++;try{s=t()}finally{e--,e||n()}return s},batchCalls:t=>(...e)=>{r((()=>{t(...e)}))},schedule:r,setNotifyFunction:t=>{s=t},setBatchNotifyFunction:t=>{i=t}}}();class F{#r;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),r(this.gcTime)&&(this.#r=setTimeout((()=>{this.optionalRemove()}),this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(s?1/0:3e5))}clearGcTimeout(){this.#r&&(clearTimeout(this.#r),this.#r=void 0)}}class E extends F{#n;#a;#o;#u;#h;#c;#l;#d;constructor(t){super(),this.#d=!1,this.#l=t.defaultOptions,this.#f(t.options),this.#c=[],this.#o=t.cache,this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#n=t.state||function(t){const e="function"==typeof t.initialData?t.initialData():t.initialData,s=void 0!==e,i=s?"function"==typeof t.initialDataUpdatedAt?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:s?i??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}(this.options),this.state=this.#n,this.scheduleGc()}get meta(){return this.options.meta}#f(t){this.options={...this.#l,...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){this.#c.length||"idle"!==this.state.fetchStatus||this.#o.remove(this)}setData(t,e){const s=b(this.state.data,t,this.options);return this.#p({data:s,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),s}setState(t,e){this.#p({type:"setState",state:t,setStateOptions:e})}cancel(t){const e=this.#u;return this.#h?.cancel(t),e?e.then(i).catch(i):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#n)}isActive(){return this.#c.some((t=>!1!==t.options.enabled))}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||this.#c.some((t=>t.getCurrentResult().isStale))}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!n(this.state.dataUpdatedAt,t)}onFocus(){this.#c.find((t=>t.shouldFetchOnWindowFocus()))?.refetch({cancelRefetch:!1}),this.#h?.continue()}onOnline(){this.#c.find((t=>t.shouldFetchOnReconnect()))?.refetch({cancelRefetch:!1}),this.#h?.continue()}addObserver(t){-1===this.#c.indexOf(t)&&(this.#c.push(t),this.clearGcTimeout(),this.#o.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){-1!==this.#c.indexOf(t)&&(this.#c=this.#c.filter((e=>e!==t)),this.#c.length||(this.#h&&(this.#d?this.#h.cancel({revert:!0}):this.#h.cancelRetry()),this.scheduleGc()),this.#o.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.#c.length}invalidate(){this.state.isInvalidated||this.#p({type:"invalidate"})}fetch(t,e){if("idle"!==this.state.fetchStatus)if(this.state.dataUpdatedAt&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#u)return this.#h?.continueRetry(),this.#u;if(t&&this.#f(t),!this.options.queryFn){const t=this.#c.find((t=>t.options.queryFn));t&&this.#f(t.options)}const s=new AbortController,i={queryKey:this.queryKey,meta:this.meta},r=t=>{Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(this.#d=!0,s.signal)})};r(i);const n={fetchOptions:e,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:()=>this.options.queryFn?(this.#d=!1,this.options.queryFn(i)):Promise.reject(new Error("Missing queryFn"))};r(n),this.options.behavior?.onFetch(n),this.#a=this.state,"idle"!==this.state.fetchStatus&&this.state.fetchMeta===n.fetchOptions?.meta||this.#p({type:"fetch",meta:n.fetchOptions?.meta});const a=t=>{S(t)&&t.silent||this.#p({type:"error",error:t}),S(t)||(this.#o.config.onError?.(t,this),this.#o.config.onSettled?.(this.state.data,t,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return this.#h=P({fn:n.fetchFn,abort:s.abort.bind(s),onSuccess:t=>{void 0!==t?(this.setData(t),this.#o.config.onSuccess?.(t,this),this.#o.config.onSettled?.(t,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1):a(new Error("undefined"))},onError:a,onFail:(t,e)=>{this.#p({type:"failed",failureCount:t,error:e})},onPause:()=>{this.#p({type:"pause"})},onContinue:()=>{this.#p({type:"continue"})},retry:n.options.retry,retryDelay:n.options.retryDelay,networkMode:n.options.networkMode}),this.#u=this.#h.promise,this.#u}#p(t){this.state=(e=>{switch(t.type){case"failed":return{...e,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...e,fetchStatus:"paused"};case"continue":return{...e,fetchStatus:"fetching"};case"fetch":return{...e,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Q(this.options.networkMode)?"fetching":"paused",...!e.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...e,data:t.data,dataUpdateCount:e.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const s=t.error;return S(s)&&s.revert&&this.#a?{...this.#a}:{...e,error:s,errorUpdateCount:e.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:e.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error"};case"invalidate":return{...e,isInvalidated:!0};case"setState":return{...e,...t.state}}})(this.state),M.batch((()=>{this.#c.forEach((e=>{e.onQueryUpdate(t)})),this.#o.notify({query:this,type:"updated",action:t})}))}}class x extends e{#y;constructor(t={}){super(),this.config=t,this.#y=t.createStore?.()??new Map}build(t,e,s){const i=e.queryKey,r=e.queryHash??u(i,e);let n=this.get(r);return n||(n=new E({cache:this,queryKey:i,queryHash:r,options:t.defaultQueryOptions(e),state:s,defaultOptions:t.getQueryDefaults(i)}),this.add(n)),n}add(t){this.#y.has(t.queryHash)||(this.#y.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const e=this.#y.get(t.queryHash);e&&(t.destroy(),e===t&&this.#y.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){M.batch((()=>{this.getAll().forEach((t=>{this.remove(t)}))}))}get(t){return this.#y.get(t)}getAll(){return[...this.#y.values()]}find(t){return void 0===t.exact&&(t.exact=!0),this.getAll().find((e=>a(t,e)))}findAll(t={}){const e=this.getAll();return Object.keys(t).length>0?e.filter((e=>a(t,e))):e}notify(t){M.batch((()=>{this.listeners.forEach((e=>{e(t)}))}))}onFocus(){M.batch((()=>{this.getAll().forEach((t=>{t.onFocus()}))}))}onOnline(){M.batch((()=>{this.getAll().forEach((t=>{t.onOnline()}))}))}}class D extends F{#c;#l;#m;#h;constructor(t){super(),this.mutationId=t.mutationId,this.#l=t.defaultOptions,this.#m=t.mutationCache,this.#c=[],this.state=t.state||A(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...this.#l,...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){-1===this.#c.indexOf(t)&&(this.#c.push(t),this.clearGcTimeout(),this.#m.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#c=this.#c.filter((e=>e!==t)),this.scheduleGc(),this.#m.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#c.length||("pending"===this.state.status?this.scheduleGc():this.#m.remove(this))}continue(){return this.#h?.continue()??this.execute(this.state.variables)}async execute(t){const e=()=>(this.#h=P({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(t,e)=>{this.#p({type:"failed",failureCount:t,error:e})},onPause:()=>{this.#p({type:"pause"})},onContinue:()=>{this.#p({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode}),this.#h.promise),s="pending"===this.state.status;try{if(!s){this.#p({type:"pending",variables:t}),await(this.#m.config.onMutate?.(t,this));const e=await(this.options.onMutate?.(t));e!==this.state.context&&this.#p({type:"pending",context:e,variables:t})}const i=await e();return await(this.#m.config.onSuccess?.(i,t,this.state.context,this)),await(this.options.onSuccess?.(i,t,this.state.context)),await(this.#m.config.onSettled?.(i,null,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(i,null,t,this.state.context)),this.#p({type:"success",data:i}),i}catch(e){try{throw await(this.#m.config.onError?.(e,t,this.state.context,this)),await(this.options.onError?.(e,t,this.state.context)),await(this.#m.config.onSettled?.(void 0,e,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(void 0,e,t,this.state.context)),e}finally{this.#p({type:"error",error:e})}}}#p(t){this.state=(e=>{switch(t.type){case"failed":return{...e,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...e,isPaused:!0};case"continue":return{...e,isPaused:!1};case"pending":return{...e,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Q(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...e,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...e,data:void 0,error:t.error,failureCount:e.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}})(this.state),M.batch((()=>{this.#c.forEach((e=>{e.onMutationUpdate(t)})),this.#m.notify({mutation:this,type:"updated",action:t})}))}}function A(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}class I extends e{#v;#b;#g;constructor(t={}){super(),this.config=t,this.#v=[],this.#b=0}build(t,e,s){const i=new D({mutationCache:this,mutationId:++this.#b,options:t.defaultMutationOptions(e),state:s});return this.add(i),i}add(t){this.#v.push(t),this.notify({type:"added",mutation:t})}remove(t){this.#v=this.#v.filter((e=>e!==t)),this.notify({type:"removed",mutation:t})}clear(){M.batch((()=>{this.#v.forEach((t=>{this.remove(t)}))}))}getAll(){return this.#v}find(t){return void 0===t.exact&&(t.exact=!0),this.#v.find((e=>o(t,e)))}findAll(t={}){return this.#v.filter((e=>o(t,e)))}notify(t){M.batch((()=>{this.listeners.forEach((e=>{e(t)}))}))}resumePausedMutations(){return this.#g=(this.#g??Promise.resolve()).then((()=>{const t=this.#v.filter((t=>t.state.isPaused));return M.batch((()=>t.reduce(((t,e)=>t.then((()=>e.continue().catch(i)))),Promise.resolve())))})).then((()=>{this.#g=void 0})),this.#g}}function U(){return{onFetch:t=>{t.fetchFn=async()=>{const e=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],r=t.state.data?.pageParams||[],n={pages:[],pageParams:[]};let a=!1;const o=t.options.queryFn||(()=>Promise.reject(new Error("Missing queryFn"))),u=async(e,s,i)=>{if(a)return Promise.reject();if(void 0===s&&e.pages.length)return Promise.resolve(e);const r={queryKey:t.queryKey,pageParam:s,meta:t.options.meta};var n;n=r,Object.defineProperty(n,"signal",{enumerable:!0,get:()=>(t.signal.aborted?a=!0:t.signal.addEventListener("abort",(()=>{a=!0})),t.signal)});const u=await o(r),{maxPages:h}=t.options,c=i?O:g;return{pages:c(e.pages,u,h),pageParams:c(e.pageParams,s,h)}};let h;if(i.length)if(s){const t="backward"===s,n={pages:i,pageParams:r},a=(t?K:T)(e,n);h=await u(n,a,t)}else{h=await u(n,r[0]);for(let t=1;t<i.length;t++){const t=T(e,h);h=await u(h,t)}}else h=await u(n,e.defaultPageParam);return h}}}}function T(t,{pages:e,pageParams:s}){const i=e.length-1;return t.getNextPageParam(e[i],e,s[i],s)}function K(t,{pages:e,pageParams:s}){return t.getPreviousPageParam?.(e[0],e,s[0],s)}function k(t,e){return!!e&&void 0!==T(t,e)}function L(t,e){return!(!e||!t.getPreviousPageParam)&&void 0!==K(t,e)}class j extends e{#O;#R=void 0;#C=void 0;#q=void 0;#Q;#w;#S;#P;#M;#F;#E;#x;#D;#A=new Set;constructor(t,e){super(),this.#O=t,this.options=e,this.#P=null,this.bindMethods(),this.setOptions(e)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){1===this.listeners.length&&(this.#R.addObserver(this),H(this.#R,this.options)&&this.#I(),this.#U())}onUnsubscribe(){this.listeners.length||this.destroy()}shouldFetchOnReconnect(){return G(this.#R,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return G(this.#R,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=[],this.#T(),this.#K(),this.#R.removeObserver(this)}setOptions(t,e){const s=this.options,i=this.#R;if(this.options=this.#O.defaultQueryOptions(t),d(s,this.options)||this.#O.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#R,observer:this}),void 0!==this.options.enabled&&"boolean"!=typeof this.options.enabled)throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=s.queryKey),this.#k();const r=this.hasListeners();r&&N(this.#R,i,this.options,s)&&this.#I(),this.#L(e),!r||this.#R===i&&this.options.enabled===s.enabled&&this.options.staleTime===s.staleTime||this.#j();const n=this.#H();!r||this.#R===i&&this.options.enabled===s.enabled&&n===this.#D||this.#G(n)}getOptimisticResult(t){const e=this.#O.getQueryCache().build(this.#O,t);return this.createResult(e,t)}getCurrentResult(){return this.#q}trackResult(t){const e={};return Object.keys(t).forEach((s=>{Object.defineProperty(e,s,{configurable:!1,enumerable:!0,get:()=>(this.#A.add(s),t[s])})})),e}getCurrentQuery(){return this.#R}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const e=this.#O.defaultQueryOptions(t),s=this.#O.getQueryCache().build(this.#O,e);return s.isFetchingOptimistic=!0,s.fetch().then((()=>this.createResult(s,e)))}fetch(t){return this.#I({...t,cancelRefetch:t.cancelRefetch??!0}).then((()=>(this.#L(),this.#q)))}#I(t){this.#k();let e=this.#R.fetch(this.options,t);return t?.throwOnError||(e=e.catch(i)),e}#j(){if(this.#T(),s||this.#q.isStale||!r(this.options.staleTime))return;const t=n(this.#q.dataUpdatedAt,this.options.staleTime)+1;this.#E=setTimeout((()=>{this.#q.isStale||this.#L()}),t)}#H(){return"function"==typeof this.options.refetchInterval?this.options.refetchInterval(this.#q.data,this.#R):this.options.refetchInterval??!1}#G(t){this.#K(),this.#D=t,!s&&!1!==this.options.enabled&&r(this.#D)&&0!==this.#D&&(this.#x=setInterval((()=>{(this.options.refetchIntervalInBackground||R.isFocused())&&this.#I()}),this.#D))}#U(){this.#j(),this.#G(this.#H())}#T(){this.#E&&(clearTimeout(this.#E),this.#E=void 0)}#K(){this.#x&&(clearInterval(this.#x),this.#x=void 0)}createResult(t,e){const s=this.#R,i=this.options,r=this.#q,n=this.#Q,a=this.#w,o=t!==s,u=o?t.state:this.#C,h=o?this.#q:this.#S,{state:c}=t;let l,{error:d,errorUpdatedAt:f,fetchStatus:p,status:y}=c,m=!1;if(e._optimisticResults){const r=this.hasListeners(),n=!r&&H(t,e),a=r&&N(t,s,e,i);(n||a)&&(p=Q(t.options.networkMode)?"fetching":"paused",c.dataUpdatedAt||(y="pending")),"isRestoring"===e._optimisticResults&&(p="idle")}if(e.select&&void 0!==c.data)if(r&&c.data===n?.data&&e.select===this.#M)l=this.#F;else try{this.#M=e.select,l=e.select(c.data),l=b(r?.data,l,e),this.#F=l,this.#P=null}catch(t){this.#P=t}else l=c.data;if(void 0!==e.placeholderData&&void 0===l&&"pending"===y){let t;if(r?.isPlaceholderData&&e.placeholderData===a?.placeholderData)t=r.data;else if(t="function"==typeof e.placeholderData?e.placeholderData(h?.data):e.placeholderData,e.select&&void 0!==t)try{t=e.select(t),this.#P=null}catch(t){this.#P=t}void 0!==t&&(y="success",l=b(r?.data,t,e),m=!0)}this.#P&&(d=this.#P,l=this.#F,f=Date.now(),y="error");const v="fetching"===p,g="pending"===y,O="error"===y,R=g&&v;return{status:y,fetchStatus:p,isPending:g,isSuccess:"success"===y,isError:O,isInitialLoading:R,isLoading:R,data:l,dataUpdatedAt:c.dataUpdatedAt,error:d,errorUpdatedAt:f,failureCount:c.fetchFailureCount,failureReason:c.fetchFailureReason,errorUpdateCount:c.errorUpdateCount,isFetched:c.dataUpdateCount>0||c.errorUpdateCount>0,isFetchedAfterMount:c.dataUpdateCount>u.dataUpdateCount||c.errorUpdateCount>u.errorUpdateCount,isFetching:v,isRefetching:v&&!g,isLoadingError:O&&0===c.dataUpdatedAt,isPaused:"paused"===p,isPlaceholderData:m,isRefetchError:O&&0!==c.dataUpdatedAt,isStale:_(t,e),refetch:this.refetch}}#L(t){const e=this.#q,s=this.createResult(this.#R,this.options);if(this.#Q=this.#R.state,this.#w=this.options,d(s,e))return;this.#q=s;const i={};!1!==t?.listeners&&(()=>{if(!e)return!0;const{notifyOnChangeProps:t}=this.options;if("all"===t||!t&&!this.#A.size)return!0;const s=new Set(t??this.#A);return this.options.throwErrors&&s.add("error"),Object.keys(this.#q).some((t=>{const i=t;return this.#q[i]!==e[i]&&s.has(i)}))})()&&(i.listeners=!0),this.#N({...i,...t})}#k(){const t=this.#O.getQueryCache().build(this.#O,this.options);if(t===this.#R)return;const e=this.#R;this.#R=t,this.#C=t.state,this.#S=this.#q,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(t){const e={};"success"===t.type?e.onSuccess=!t.manual:"error"!==t.type||S(t.error)||(e.onError=!0),this.#L(e),this.hasListeners()&&this.#U()}#N(t){M.batch((()=>{t.onSuccess?(this.options.onSuccess?.(this.#q.data),this.options.onSettled?.(this.#q.data,null)):t.onError&&(this.options.onError?.(this.#q.error),this.options.onSettled?.(void 0,this.#q.error)),t.listeners&&this.listeners.forEach((t=>{t(this.#q)})),this.#O.getQueryCache().notify({query:this.#R,type:"observerResultsUpdated"})}))}}function H(t,e){return function(t,e){return!(!1===e.enabled||t.state.dataUpdatedAt||"error"===t.state.status&&!1===e.retryOnMount)}(t,e)||t.state.dataUpdatedAt>0&&G(t,e,e.refetchOnMount)}function G(t,e,s){if(!1!==e.enabled){const i="function"==typeof s?s(t):s;return"always"===i||!1!==i&&_(t,e)}return!1}function N(t,e,s,i){return!1!==s.enabled&&(t!==e||!1===i.enabled)&&(!s.suspense||"error"!==t.state.status)&&_(t,s)}function _(t,e){return t.isStaleByTime(e.staleTime)}function B(t,e){return t.filter((t=>-1===e.indexOf(t)))}function W(t){return t.state.isPaused}function z(t){return"success"===t.state.status}t.CancelledError=w,t.InfiniteQueryObserver=class extends j{constructor(t,e){super(t,e)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(t,e){super.setOptions({...t,behavior:U()},e)}getOptimisticResult(t){return t.behavior=U(),super.getOptimisticResult(t)}fetchNextPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"backward"}}})}createResult(t,e){const{state:s}=t,i=super.createResult(t,e),{isFetching:r,isRefetching:n}=i,a=r&&"forward"===s.fetchMeta?.fetchMore?.direction,o=r&&"backward"===s.fetchMeta?.fetchMore?.direction;return{...i,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:k(e,s.data),hasPreviousPage:L(e,s.data),isFetchingNextPage:a,isFetchingPreviousPage:o,isRefetching:n&&!a&&!o}}},t.MutationCache=I,t.MutationObserver=class extends e{#O;#q=void 0;#_;#B;constructor(t,e){super(),this.#O=t,this.setOptions(e),this.bindMethods(),this.#L()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const e=this.options;this.options=this.#O.defaultMutationOptions(t),d(e,this.options)||this.#O.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#_,observer:this}),this.#_?.setOptions(this.options)}onUnsubscribe(){this.listeners.length||this.#_?.removeObserver(this)}onMutationUpdate(t){this.#L(),this.#N(t)}getCurrentResult(){return this.#q}reset(){this.#_=void 0,this.#L(),this.#N()}mutate(t,e){return this.#B=e,this.#_?.removeObserver(this),this.#_=this.#O.getMutationCache().build(this.#O,this.options),this.#_.addObserver(this),this.#_.execute(t)}#L(){const t=this.#_?.state??{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0};this.#q={...t,isPending:"pending"===t.status,isSuccess:"success"===t.status,isError:"error"===t.status,isIdle:"idle"===t.status,mutate:this.mutate,reset:this.reset}}#N(t){M.batch((()=>{this.#B&&this.hasListeners()&&("success"===t?.type?(this.#B.onSuccess?.(t.data,this.#q.variables,this.#q.context),this.#B.onSettled?.(t.data,null,this.#q.variables,this.#q.context)):"error"===t?.type&&(this.#B.onError?.(t.error,this.#q.variables,this.#q.context),this.#B.onSettled?.(void 0,t.error,this.#q.variables,this.#q.context))),this.listeners.forEach((t=>{t(this.#q)}))}))}},t.QueriesObserver=class extends e{#O;#W;#y;#c;constructor(t,e){super(),this.#O=t,this.#y=[],this.#W=[],this.#c=[],e&&this.setQueries(e)}onSubscribe(){1===this.listeners.length&&this.#c.forEach((t=>{t.subscribe((e=>{this.#z(t,e)}))}))}onUnsubscribe(){this.listeners.length||this.destroy()}destroy(){this.listeners=[],this.#c.forEach((t=>{t.destroy()}))}setQueries(t,e){this.#y=t,M.batch((()=>{const t=this.#c,s=this.#J(this.#y);s.forEach((t=>t.observer.setOptions(t.defaultedQueryOptions,e)));const i=s.map((t=>t.observer)),r=i.map((t=>t.getCurrentResult())),n=i.some(((e,s)=>e!==t[s]));(t.length!==i.length||n)&&(this.#c=i,this.#W=r,this.hasListeners()&&(B(t,i).forEach((t=>{t.destroy()})),B(i,t).forEach((t=>{t.subscribe((e=>{this.#z(t,e)}))})),this.#N()))}))}getCurrentResult(){return this.#W}getQueries(){return this.#c.map((t=>t.getCurrentQuery()))}getObservers(){return this.#c}getOptimisticResult(t){return this.#J(t).map((t=>t.observer.getOptimisticResult(t.defaultedQueryOptions)))}#J(t){const e=this.#c,s=t.map((t=>this.#O.defaultQueryOptions(t))),i=s.flatMap((t=>{const s=e.find((e=>e.options.queryHash===t.queryHash));return null!=s?[{defaultedQueryOptions:t,observer:s}]:[]})),r=i.map((t=>t.defaultedQueryOptions.queryHash)),n=s.filter((t=>!r.includes(t.queryHash))),a=t=>{const e=this.#O.defaultQueryOptions(t);return this.#c.find((t=>t.options.queryHash===e.queryHash))??new j(this.#O,e)},o=n.map((t=>({defaultedQueryOptions:t,observer:a(t)})));return i.concat(o).sort(((t,e)=>s.indexOf(t.defaultedQueryOptions)-s.indexOf(e.defaultedQueryOptions)))}#z(t,e){const s=this.#c.indexOf(t);-1!==s&&(this.#W=function(t,e,s){const i=t.slice(0);return i[e]=s,i}(this.#W,s,e),this.#N())}#N(){M.batch((()=>{this.listeners.forEach((t=>{t(this.#W)}))}))}},t.QueryCache=x,t.QueryClient=class{#V;#m;#l;#X;#Y;#Z;#$;#tt;constructor(t={}){this.#V=t.queryCache||new x,this.#m=t.mutationCache||new I,this.#l=t.defaultOptions||{},this.#X=new Map,this.#Y=new Map,this.#Z=0}mount(){this.#Z++,1===this.#Z&&(this.#$=R.subscribe((()=>{R.isFocused()&&(this.resumePausedMutations(),this.#V.onFocus())})),this.#tt=C.subscribe((()=>{C.isOnline()&&(this.resumePausedMutations(),this.#V.onOnline())})))}unmount(){this.#Z--,0===this.#Z&&(this.#$?.(),this.#$=void 0,this.#tt?.(),this.#tt=void 0)}isFetching(t){return this.#V.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#m.findAll({...t,status:"pending"}).length}getQueryData(t){return this.#V.find({queryKey:t})?.state.data}ensureQueryData(t){const e=this.getQueryData(t.queryKey);return e?Promise.resolve(e):this.fetchQuery(t)}getQueriesData(t){return this.getQueryCache().findAll(t).map((({queryKey:t,state:e})=>[t,e.data]))}setQueryData(t,e,s){const i=this.#V.find({queryKey:t})?.state.data,r=function(t,e){return"function"==typeof t?t(e):t}(e,i);if(void 0===r)return;const n=this.defaultQueryOptions({queryKey:t});return this.#V.build(this,n).setData(r,{...s,manual:!0})}setQueriesData(t,e,s){return M.batch((()=>this.getQueryCache().findAll(t).map((({queryKey:t})=>[t,this.setQueryData(t,e,s)]))))}getQueryState(t){return this.#V.find({queryKey:t})?.state}removeQueries(t){const e=this.#V;M.batch((()=>{e.findAll(t).forEach((t=>{e.remove(t)}))}))}resetQueries(t,e){const s=this.#V,i={type:"active",...t};return M.batch((()=>(s.findAll(t).forEach((t=>{t.reset()})),this.refetchQueries(i,e))))}cancelQueries(t={},e={}){void 0===e.revert&&(e.revert=!0);const s=M.batch((()=>this.#V.findAll(t).map((t=>t.cancel(e)))));return Promise.all(s).then(i).catch(i)}invalidateQueries(t={},e={}){return M.batch((()=>{if(this.#V.findAll(t).forEach((t=>{t.invalidate()})),"none"===t.refetchType)return Promise.resolve();const s={...t,type:t.refetchType??t.type??"active"};return this.refetchQueries(s,e)}))}refetchQueries(t={},e){const s=M.batch((()=>this.#V.findAll(t).filter((t=>!t.isDisabled())).map((t=>t.fetch(void 0,{...e,cancelRefetch:e?.cancelRefetch??!0})))));let r=Promise.all(s).then(i);return e?.throwOnError||(r=r.catch(i)),r}fetchQuery(t){const e=this.defaultQueryOptions(t);void 0===e.retry&&(e.retry=!1);const s=this.#V.build(this,e);return s.isStaleByTime(e.staleTime)?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(i).catch(i)}fetchInfiniteQuery(t){return t.behavior=U(),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(i).catch(i)}resumePausedMutations(){return this.#m.resumePausedMutations()}getQueryCache(){return this.#V}getMutationCache(){return this.#m}getDefaultOptions(){return this.#l}setDefaultOptions(t){this.#l=t}setQueryDefaults(t,e){this.#X.set(h(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...this.#X.values()];let s={};return e.forEach((e=>{c(t,e.queryKey)&&(s={...s,...e.defaultOptions})})),s}setMutationDefaults(t,e){this.#Y.set(h(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...this.#Y.values()];let s={};return e.forEach((e=>{c(t,e.mutationKey)&&(s={...s,...e.defaultOptions})})),s}defaultQueryOptions(t){if(t?._defaulted)return t;const e={...this.#l.queries,...t?.queryKey&&this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=u(e.queryKey,e)),void 0===e.refetchOnReconnect&&(e.refetchOnReconnect="always"!==e.networkMode),void 0===e.throwErrors&&(e.throwErrors=!!e.suspense),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#l.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#V.clear(),this.#m.clear()}},t.QueryObserver=j,t.defaultShouldDehydrateMutation=W,t.defaultShouldDehydrateQuery=z,t.dehydrate=function(t,e={}){const s=[],i=[];if(!1!==e.dehydrateMutations){const i=e.shouldDehydrateMutation||W;t.getMutationCache().getAll().forEach((t=>{i(t)&&s.push(function(t){return{mutationKey:t.options.mutationKey,state:t.state}}(t))}))}if(!1!==e.dehydrateQueries){const s=e.shouldDehydrateQuery||z;t.getQueryCache().getAll().forEach((t=>{s(t)&&i.push(function(t){return{state:t.state,queryKey:t.queryKey,queryHash:t.queryHash}}(t))}))}return{mutations:s,queries:i}},t.focusManager=R,t.hashKey=h,t.hydrate=function(t,e,s){if("object"!=typeof e||null===e)return;const i=t.getMutationCache(),r=t.getQueryCache(),n=e.mutations||[],a=e.queries||[];n.forEach((e=>{i.build(t,{...s?.defaultOptions?.mutations,mutationKey:e.mutationKey},e.state)})),a.forEach((e=>{const i=r.get(e.queryHash),n={...e.state,fetchStatus:"idle"};i?i.state.dataUpdatedAt<n.dataUpdatedAt&&i.setState(n):r.build(t,{...s?.defaultOptions?.queries,queryKey:e.queryKey,queryHash:e.queryHash},n)}))},t.isCancelledError=S,t.isServer=s,t.keepPreviousData=function(t){return t},t.matchQuery=a,t.notifyManager=M,t.onlineManager=C,t.replaceEqualDeep=l})); | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).QueryCore={})}(this,(function(t){"use strict";class e{constructor(){this.listeners=[],this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.push(t),this.onSubscribe(),()=>{this.listeners=this.listeners.filter((e=>e!==t)),this.onUnsubscribe()}}hasListeners(){return this.listeners.length>0}onSubscribe(){}onUnsubscribe(){}}const s="undefined"==typeof window||"Deno"in window;function i(){}function r(t){return"number"==typeof t&&t>=0&&t!==1/0}function n(t,e){return Math.max(t+(e||0)-Date.now(),0)}function a(t,e){const{type:s="all",exact:i,fetchStatus:r,predicate:n,queryKey:a,stale:o}=t;if(a)if(i){if(e.queryHash!==u(a,e.options))return!1}else if(!c(e.queryKey,a))return!1;if("all"!==s){const t=e.isActive();if("active"===s&&!t)return!1;if("inactive"===s&&t)return!1}return("boolean"!=typeof o||e.isStale()===o)&&((void 0===r||r===e.state.fetchStatus)&&!(n&&!n(e)))}function o(t,e){const{exact:s,status:i,predicate:r,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(s){if(h(e.options.mutationKey)!==h(n))return!1}else if(!c(e.options.mutationKey,n))return!1}return(!i||e.state.status===i)&&!(r&&!r(e))}function u(t,e){return(e?.queryKeyHashFn||h)(t)}function h(t){return JSON.stringify(t,((t,e)=>p(e)?Object.keys(e).sort().reduce(((t,s)=>(t[s]=e[s],t)),{}):e))}function c(t,e){return t===e||typeof t==typeof e&&(!(!t||!e||"object"!=typeof t||"object"!=typeof e)&&!Object.keys(e).some((s=>!c(t[s],e[s]))))}function l(t,e){if(t===e)return t;const s=f(t)&&f(e);if(s||p(t)&&p(e)){const i=s?t.length:Object.keys(t).length,r=s?e:Object.keys(e),n=r.length,a=s?[]:{};let o=0;for(let i=0;i<n;i++){const n=s?i:r[i];a[n]=l(t[n],e[n]),a[n]===t[n]&&o++}return i===n&&o===i?t:a}return e}function d(t,e){if(t&&!e||e&&!t)return!1;for(const s in t)if(t[s]!==e[s])return!1;return!0}function f(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function p(t){if(!y(t))return!1;const e=t.constructor;if(void 0===e)return!0;const s=e.prototype;return!!y(s)&&!!s.hasOwnProperty("isPrototypeOf")}function y(t){return"[object Object]"===Object.prototype.toString.call(t)}function m(t){return new Promise((e=>{setTimeout(e,t)}))}function v(t){m(0).then(t)}function b(t,e,s){return"function"==typeof s.structuralSharing?s.structuralSharing(t,e):!1!==s.structuralSharing?l(t,e):e}function g(t,e,s=0){const i=[...t,e];return s&&i.length>s?i.slice(1):i}function O(t,e,s=0){const i=[e,...t];return s&&i.length>s?i.slice(0,-1):i}const R=new class extends e{#t;#e;#s;constructor(){super(),this.#s=t=>{if(!s&&window.addEventListener){const e=()=>t();return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#e||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(t){this.#s=t,this.#e?.(),this.#e=t((t=>{"boolean"==typeof t?this.setFocused(t):this.onFocus()}))}setFocused(t){this.#t=t,t&&this.onFocus()}onFocus(){this.listeners.forEach((t=>{t()}))}isFocused(){return"boolean"==typeof this.#t?this.#t:"hidden"!==globalThis.document?.visibilityState}};const C=new class extends e{#i;#e;#s;constructor(){super(),this.#s=t=>{if(!s&&window.addEventListener){const e=()=>t();return window.addEventListener("online",e,!1),window.addEventListener("offline",e,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",e)}}}}onSubscribe(){this.#e||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(t){this.#s=t,this.#e?.(),this.#e=t((t=>{"boolean"==typeof t?this.setOnline(t):this.onOnline()}))}setOnline(t){this.#i=t,t&&this.onOnline()}onOnline(){this.listeners.forEach((t=>{t()}))}isOnline(){return"boolean"==typeof this.#i?this.#i:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine}};function q(t){return Math.min(1e3*2**t,3e4)}function Q(t){return"online"!==(t??"online")||C.isOnline()}class w{constructor(t){this.revert=t?.revert,this.silent=t?.silent}}function S(t){return t instanceof w}function P(t){let e,s,i,r=!1,n=0,a=!1;const o=new Promise(((t,e)=>{s=t,i=e})),u=()=>!R.isFocused()||"always"!==t.networkMode&&!C.isOnline(),h=i=>{a||(a=!0,t.onSuccess?.(i),e?.(),s(i))},c=s=>{a||(a=!0,t.onError?.(s),e?.(),i(s))},l=()=>new Promise((s=>{e=t=>{const e=a||!u();return e&&s(t),e},t.onPause?.()})).then((()=>{e=void 0,a||t.onContinue?.()})),d=()=>{if(a)return;let e;try{e=t.fn()}catch(t){e=Promise.reject(t)}Promise.resolve(e).then(h).catch((e=>{if(a)return;const s=t.retry??3,i=t.retryDelay??q,o="function"==typeof i?i(n,e):i,h=!0===s||"number"==typeof s&&n<s||"function"==typeof s&&s(n,e);!r&&h?(n++,t.onFail?.(n,e),m(o).then((()=>{if(u())return l()})).then((()=>{r?c(e):d()}))):c(e)}))};return Q(t.networkMode)?d():l().then(d),{promise:o,cancel:e=>{a||(c(new w(e)),t.abort?.())},continue:()=>{const t=e?.();return t?o:Promise.resolve()},cancelRetry:()=>{r=!0},continueRetry:()=>{r=!1}}}const M=function(){let t=[],e=0,s=t=>{t()},i=t=>{t()};const r=i=>{e?t.push(i):v((()=>{s(i)}))},n=()=>{const e=t;t=[],e.length&&v((()=>{i((()=>{e.forEach((t=>{s(t)}))}))}))};return{batch:t=>{let s;e++;try{s=t()}finally{e--,e||n()}return s},batchCalls:t=>(...e)=>{r((()=>{t(...e)}))},schedule:r,setNotifyFunction:t=>{s=t},setBatchNotifyFunction:t=>{i=t}}}();class F{#r;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),r(this.gcTime)&&(this.#r=setTimeout((()=>{this.optionalRemove()}),this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(s?1/0:3e5))}clearGcTimeout(){this.#r&&(clearTimeout(this.#r),this.#r=void 0)}}class E extends F{#n;#a;#o;#u;#h;#c;#l;#d;constructor(t){super(),this.#d=!1,this.#l=t.defaultOptions,this.#f(t.options),this.#c=[],this.#o=t.cache,this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#n=t.state||function(t){const e="function"==typeof t.initialData?t.initialData():t.initialData,s=void 0!==e,i=s?"function"==typeof t.initialDataUpdatedAt?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:s?i??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}(this.options),this.state=this.#n,this.scheduleGc()}get meta(){return this.options.meta}#f(t){this.options={...this.#l,...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){this.#c.length||"idle"!==this.state.fetchStatus||this.#o.remove(this)}setData(t,e){const s=b(this.state.data,t,this.options);return this.#p({data:s,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),s}setState(t,e){this.#p({type:"setState",state:t,setStateOptions:e})}cancel(t){const e=this.#u;return this.#h?.cancel(t),e?e.then(i).catch(i):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#n)}isActive(){return this.#c.some((t=>!1!==t.options.enabled))}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||this.#c.some((t=>t.getCurrentResult().isStale))}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!n(this.state.dataUpdatedAt,t)}onFocus(){this.#c.find((t=>t.shouldFetchOnWindowFocus()))?.refetch({cancelRefetch:!1}),this.#h?.continue()}onOnline(){this.#c.find((t=>t.shouldFetchOnReconnect()))?.refetch({cancelRefetch:!1}),this.#h?.continue()}addObserver(t){-1===this.#c.indexOf(t)&&(this.#c.push(t),this.clearGcTimeout(),this.#o.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){-1!==this.#c.indexOf(t)&&(this.#c=this.#c.filter((e=>e!==t)),this.#c.length||(this.#h&&(this.#d?this.#h.cancel({revert:!0}):this.#h.cancelRetry()),this.scheduleGc()),this.#o.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.#c.length}invalidate(){this.state.isInvalidated||this.#p({type:"invalidate"})}fetch(t,e){if("idle"!==this.state.fetchStatus)if(this.state.dataUpdatedAt&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#u)return this.#h?.continueRetry(),this.#u;if(t&&this.#f(t),!this.options.queryFn){const t=this.#c.find((t=>t.options.queryFn));t&&this.#f(t.options)}const s=new AbortController,i={queryKey:this.queryKey,meta:this.meta},r=t=>{Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(this.#d=!0,s.signal)})};r(i);const n={fetchOptions:e,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:()=>this.options.queryFn?(this.#d=!1,this.options.queryFn(i)):Promise.reject(new Error("Missing queryFn"))};r(n),this.options.behavior?.onFetch(n),this.#a=this.state,"idle"!==this.state.fetchStatus&&this.state.fetchMeta===n.fetchOptions?.meta||this.#p({type:"fetch",meta:n.fetchOptions?.meta});const a=t=>{S(t)&&t.silent||this.#p({type:"error",error:t}),S(t)||(this.#o.config.onError?.(t,this),this.#o.config.onSettled?.(this.state.data,t,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return this.#h=P({fn:n.fetchFn,abort:s.abort.bind(s),onSuccess:t=>{void 0!==t?(this.setData(t),this.#o.config.onSuccess?.(t,this),this.#o.config.onSettled?.(t,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1):a(new Error("undefined"))},onError:a,onFail:(t,e)=>{this.#p({type:"failed",failureCount:t,error:e})},onPause:()=>{this.#p({type:"pause"})},onContinue:()=>{this.#p({type:"continue"})},retry:n.options.retry,retryDelay:n.options.retryDelay,networkMode:n.options.networkMode}),this.#u=this.#h.promise,this.#u}#p(t){this.state=(e=>{switch(t.type){case"failed":return{...e,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...e,fetchStatus:"paused"};case"continue":return{...e,fetchStatus:"fetching"};case"fetch":return{...e,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Q(this.options.networkMode)?"fetching":"paused",...!e.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...e,data:t.data,dataUpdateCount:e.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const s=t.error;return S(s)&&s.revert&&this.#a?{...this.#a}:{...e,error:s,errorUpdateCount:e.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:e.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error"};case"invalidate":return{...e,isInvalidated:!0};case"setState":return{...e,...t.state}}})(this.state),M.batch((()=>{this.#c.forEach((e=>{e.onQueryUpdate(t)})),this.#o.notify({query:this,type:"updated",action:t})}))}}class x extends e{#y;constructor(t={}){super(),this.config=t,this.#y=t.createStore?.()??new Map}build(t,e,s){const i=e.queryKey,r=e.queryHash??u(i,e);let n=this.get(r);return n||(n=new E({cache:this,queryKey:i,queryHash:r,options:t.defaultQueryOptions(e),state:s,defaultOptions:t.getQueryDefaults(i)}),this.add(n)),n}add(t){this.#y.has(t.queryHash)||(this.#y.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const e=this.#y.get(t.queryHash);e&&(t.destroy(),e===t&&this.#y.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){M.batch((()=>{this.getAll().forEach((t=>{this.remove(t)}))}))}get(t){return this.#y.get(t)}getAll(){return[...this.#y.values()]}find(t){return void 0===t.exact&&(t.exact=!0),this.getAll().find((e=>a(t,e)))}findAll(t={}){const e=this.getAll();return Object.keys(t).length>0?e.filter((e=>a(t,e))):e}notify(t){M.batch((()=>{this.listeners.forEach((e=>{e(t)}))}))}onFocus(){M.batch((()=>{this.getAll().forEach((t=>{t.onFocus()}))}))}onOnline(){M.batch((()=>{this.getAll().forEach((t=>{t.onOnline()}))}))}}class D extends F{#c;#l;#m;#h;constructor(t){super(),this.mutationId=t.mutationId,this.#l=t.defaultOptions,this.#m=t.mutationCache,this.#c=[],this.state=t.state||A(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...this.#l,...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){-1===this.#c.indexOf(t)&&(this.#c.push(t),this.clearGcTimeout(),this.#m.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#c=this.#c.filter((e=>e!==t)),this.scheduleGc(),this.#m.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#c.length||("pending"===this.state.status?this.scheduleGc():this.#m.remove(this))}continue(){return this.#h?.continue()??this.execute(this.state.variables)}async execute(t){const e=()=>(this.#h=P({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(t,e)=>{this.#p({type:"failed",failureCount:t,error:e})},onPause:()=>{this.#p({type:"pause"})},onContinue:()=>{this.#p({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode}),this.#h.promise),s="pending"===this.state.status;try{if(!s){this.#p({type:"pending",variables:t}),await(this.#m.config.onMutate?.(t,this));const e=await(this.options.onMutate?.(t));e!==this.state.context&&this.#p({type:"pending",context:e,variables:t})}const i=await e();return await(this.#m.config.onSuccess?.(i,t,this.state.context,this)),await(this.options.onSuccess?.(i,t,this.state.context)),await(this.#m.config.onSettled?.(i,null,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(i,null,t,this.state.context)),this.#p({type:"success",data:i}),i}catch(e){try{throw await(this.#m.config.onError?.(e,t,this.state.context,this)),await(this.options.onError?.(e,t,this.state.context)),await(this.#m.config.onSettled?.(void 0,e,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(void 0,e,t,this.state.context)),e}finally{this.#p({type:"error",error:e})}}}#p(t){this.state=(e=>{switch(t.type){case"failed":return{...e,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...e,isPaused:!0};case"continue":return{...e,isPaused:!1};case"pending":return{...e,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Q(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...e,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...e,data:void 0,error:t.error,failureCount:e.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}})(this.state),M.batch((()=>{this.#c.forEach((e=>{e.onMutationUpdate(t)})),this.#m.notify({mutation:this,type:"updated",action:t})}))}}function A(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}class I extends e{#v;#b;#g;constructor(t={}){super(),this.config=t,this.#v=[],this.#b=0}build(t,e,s){const i=new D({mutationCache:this,mutationId:++this.#b,options:t.defaultMutationOptions(e),state:s});return this.add(i),i}add(t){this.#v.push(t),this.notify({type:"added",mutation:t})}remove(t){this.#v=this.#v.filter((e=>e!==t)),this.notify({type:"removed",mutation:t})}clear(){M.batch((()=>{this.#v.forEach((t=>{this.remove(t)}))}))}getAll(){return this.#v}find(t){return void 0===t.exact&&(t.exact=!0),this.#v.find((e=>o(t,e)))}findAll(t={}){return this.#v.filter((e=>o(t,e)))}notify(t){M.batch((()=>{this.listeners.forEach((e=>{e(t)}))}))}resumePausedMutations(){return this.#g=(this.#g??Promise.resolve()).then((()=>{const t=this.#v.filter((t=>t.state.isPaused));return M.batch((()=>t.reduce(((t,e)=>t.then((()=>e.continue().catch(i)))),Promise.resolve())))})).then((()=>{this.#g=void 0})),this.#g}}function U(){return{onFetch:t=>{t.fetchFn=async()=>{const e=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],r=t.state.data?.pageParams||[],n={pages:[],pageParams:[]};let a=!1;const o=t.options.queryFn||(()=>Promise.reject(new Error("Missing queryFn"))),u=async(e,s,i)=>{if(a)return Promise.reject();if(void 0===s&&e.pages.length)return Promise.resolve(e);const r={queryKey:t.queryKey,pageParam:s,direction:i?"backward":"forward",meta:t.options.meta};var n;n=r,Object.defineProperty(n,"signal",{enumerable:!0,get:()=>(t.signal.aborted?a=!0:t.signal.addEventListener("abort",(()=>{a=!0})),t.signal)});const u=await o(r),{maxPages:h}=t.options,c=i?O:g;return{pages:c(e.pages,u,h),pageParams:c(e.pageParams,s,h)}};let h;if(i.length)if(s){const t="backward"===s,n={pages:i,pageParams:r},a=(t?K:T)(e,n);h=await u(n,a,t)}else{h=await u(n,r[0]);for(let t=1;t<i.length;t++){const t=T(e,h);h=await u(h,t)}}else h=await u(n,e.defaultPageParam);return h}}}}function T(t,{pages:e,pageParams:s}){const i=e.length-1;return t.getNextPageParam(e[i],e,s[i],s)}function K(t,{pages:e,pageParams:s}){return t.getPreviousPageParam?.(e[0],e,s[0],s)}function k(t,e){return!!e&&void 0!==T(t,e)}function L(t,e){return!(!e||!t.getPreviousPageParam)&&void 0!==K(t,e)}class j extends e{#O;#R=void 0;#C=void 0;#q=void 0;#Q;#w;#S;#P;#M;#F;#E;#x;#D;#A=new Set;constructor(t,e){super(),this.#O=t,this.options=e,this.#P=null,this.bindMethods(),this.setOptions(e)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){1===this.listeners.length&&(this.#R.addObserver(this),H(this.#R,this.options)&&this.#I(),this.#U())}onUnsubscribe(){this.listeners.length||this.destroy()}shouldFetchOnReconnect(){return G(this.#R,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return G(this.#R,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=[],this.#T(),this.#K(),this.#R.removeObserver(this)}setOptions(t,e){const s=this.options,i=this.#R;if(this.options=this.#O.defaultQueryOptions(t),d(s,this.options)||this.#O.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#R,observer:this}),void 0!==this.options.enabled&&"boolean"!=typeof this.options.enabled)throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=s.queryKey),this.#k();const r=this.hasListeners();r&&N(this.#R,i,this.options,s)&&this.#I(),this.#L(e),!r||this.#R===i&&this.options.enabled===s.enabled&&this.options.staleTime===s.staleTime||this.#j();const n=this.#H();!r||this.#R===i&&this.options.enabled===s.enabled&&n===this.#D||this.#G(n)}getOptimisticResult(t){const e=this.#O.getQueryCache().build(this.#O,t);return this.createResult(e,t)}getCurrentResult(){return this.#q}trackResult(t){const e={};return Object.keys(t).forEach((s=>{Object.defineProperty(e,s,{configurable:!1,enumerable:!0,get:()=>(this.#A.add(s),t[s])})})),e}getCurrentQuery(){return this.#R}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const e=this.#O.defaultQueryOptions(t),s=this.#O.getQueryCache().build(this.#O,e);return s.isFetchingOptimistic=!0,s.fetch().then((()=>this.createResult(s,e)))}fetch(t){return this.#I({...t,cancelRefetch:t.cancelRefetch??!0}).then((()=>(this.#L(),this.#q)))}#I(t){this.#k();let e=this.#R.fetch(this.options,t);return t?.throwOnError||(e=e.catch(i)),e}#j(){if(this.#T(),s||this.#q.isStale||!r(this.options.staleTime))return;const t=n(this.#q.dataUpdatedAt,this.options.staleTime)+1;this.#E=setTimeout((()=>{this.#q.isStale||this.#L()}),t)}#H(){return"function"==typeof this.options.refetchInterval?this.options.refetchInterval(this.#q.data,this.#R):this.options.refetchInterval??!1}#G(t){this.#K(),this.#D=t,!s&&!1!==this.options.enabled&&r(this.#D)&&0!==this.#D&&(this.#x=setInterval((()=>{(this.options.refetchIntervalInBackground||R.isFocused())&&this.#I()}),this.#D))}#U(){this.#j(),this.#G(this.#H())}#T(){this.#E&&(clearTimeout(this.#E),this.#E=void 0)}#K(){this.#x&&(clearInterval(this.#x),this.#x=void 0)}createResult(t,e){const s=this.#R,i=this.options,r=this.#q,n=this.#Q,a=this.#w,o=t!==s,u=o?t.state:this.#C,h=o?this.#q:this.#S,{state:c}=t;let l,{error:d,errorUpdatedAt:f,fetchStatus:p,status:y}=c,m=!1;if(e._optimisticResults){const r=this.hasListeners(),n=!r&&H(t,e),a=r&&N(t,s,e,i);(n||a)&&(p=Q(t.options.networkMode)?"fetching":"paused",c.dataUpdatedAt||(y="pending")),"isRestoring"===e._optimisticResults&&(p="idle")}if(e.select&&void 0!==c.data)if(r&&c.data===n?.data&&e.select===this.#M)l=this.#F;else try{this.#M=e.select,l=e.select(c.data),l=b(r?.data,l,e),this.#F=l,this.#P=null}catch(t){this.#P=t}else l=c.data;if(void 0!==e.placeholderData&&void 0===l&&"pending"===y){let t;if(r?.isPlaceholderData&&e.placeholderData===a?.placeholderData)t=r.data;else if(t="function"==typeof e.placeholderData?e.placeholderData(h?.data):e.placeholderData,e.select&&void 0!==t)try{t=e.select(t),this.#P=null}catch(t){this.#P=t}void 0!==t&&(y="success",l=b(r?.data,t,e),m=!0)}this.#P&&(d=this.#P,l=this.#F,f=Date.now(),y="error");const v="fetching"===p,g="pending"===y,O="error"===y,R=g&&v;return{status:y,fetchStatus:p,isPending:g,isSuccess:"success"===y,isError:O,isInitialLoading:R,isLoading:R,data:l,dataUpdatedAt:c.dataUpdatedAt,error:d,errorUpdatedAt:f,failureCount:c.fetchFailureCount,failureReason:c.fetchFailureReason,errorUpdateCount:c.errorUpdateCount,isFetched:c.dataUpdateCount>0||c.errorUpdateCount>0,isFetchedAfterMount:c.dataUpdateCount>u.dataUpdateCount||c.errorUpdateCount>u.errorUpdateCount,isFetching:v,isRefetching:v&&!g,isLoadingError:O&&0===c.dataUpdatedAt,isPaused:"paused"===p,isPlaceholderData:m,isRefetchError:O&&0!==c.dataUpdatedAt,isStale:_(t,e),refetch:this.refetch}}#L(t){const e=this.#q,s=this.createResult(this.#R,this.options);if(this.#Q=this.#R.state,this.#w=this.options,d(s,e))return;this.#q=s;const i={};!1!==t?.listeners&&(()=>{if(!e)return!0;const{notifyOnChangeProps:t}=this.options;if("all"===t||!t&&!this.#A.size)return!0;const s=new Set(t??this.#A);return this.options.throwErrors&&s.add("error"),Object.keys(this.#q).some((t=>{const i=t;return this.#q[i]!==e[i]&&s.has(i)}))})()&&(i.listeners=!0),this.#N({...i,...t})}#k(){const t=this.#O.getQueryCache().build(this.#O,this.options);if(t===this.#R)return;const e=this.#R;this.#R=t,this.#C=t.state,this.#S=this.#q,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(t){const e={};"success"===t.type?e.onSuccess=!t.manual:"error"!==t.type||S(t.error)||(e.onError=!0),this.#L(e),this.hasListeners()&&this.#U()}#N(t){M.batch((()=>{t.onSuccess?(this.options.onSuccess?.(this.#q.data),this.options.onSettled?.(this.#q.data,null)):t.onError&&(this.options.onError?.(this.#q.error),this.options.onSettled?.(void 0,this.#q.error)),t.listeners&&this.listeners.forEach((t=>{t(this.#q)})),this.#O.getQueryCache().notify({query:this.#R,type:"observerResultsUpdated"})}))}}function H(t,e){return function(t,e){return!(!1===e.enabled||t.state.dataUpdatedAt||"error"===t.state.status&&!1===e.retryOnMount)}(t,e)||t.state.dataUpdatedAt>0&&G(t,e,e.refetchOnMount)}function G(t,e,s){if(!1!==e.enabled){const i="function"==typeof s?s(t):s;return"always"===i||!1!==i&&_(t,e)}return!1}function N(t,e,s,i){return!1!==s.enabled&&(t!==e||!1===i.enabled)&&(!s.suspense||"error"!==t.state.status)&&_(t,s)}function _(t,e){return t.isStaleByTime(e.staleTime)}function B(t,e){return t.filter((t=>-1===e.indexOf(t)))}function W(t){return t.state.isPaused}function z(t){return"success"===t.state.status}t.CancelledError=w,t.InfiniteQueryObserver=class extends j{constructor(t,e){super(t,e)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(t,e){super.setOptions({...t,behavior:U()},e)}getOptimisticResult(t){return t.behavior=U(),super.getOptimisticResult(t)}fetchNextPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"backward"}}})}createResult(t,e){const{state:s}=t,i=super.createResult(t,e),{isFetching:r,isRefetching:n}=i,a=r&&"forward"===s.fetchMeta?.fetchMore?.direction,o=r&&"backward"===s.fetchMeta?.fetchMore?.direction;return{...i,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:k(e,s.data),hasPreviousPage:L(e,s.data),isFetchingNextPage:a,isFetchingPreviousPage:o,isRefetching:n&&!a&&!o}}},t.MutationCache=I,t.MutationObserver=class extends e{#O;#q=void 0;#_;#B;constructor(t,e){super(),this.#O=t,this.setOptions(e),this.bindMethods(),this.#L()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const e=this.options;this.options=this.#O.defaultMutationOptions(t),d(e,this.options)||this.#O.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#_,observer:this}),this.#_?.setOptions(this.options)}onUnsubscribe(){this.listeners.length||this.#_?.removeObserver(this)}onMutationUpdate(t){this.#L(),this.#N(t)}getCurrentResult(){return this.#q}reset(){this.#_=void 0,this.#L(),this.#N()}mutate(t,e){return this.#B=e,this.#_?.removeObserver(this),this.#_=this.#O.getMutationCache().build(this.#O,this.options),this.#_.addObserver(this),this.#_.execute(t)}#L(){const t=this.#_?.state??{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0};this.#q={...t,isPending:"pending"===t.status,isSuccess:"success"===t.status,isError:"error"===t.status,isIdle:"idle"===t.status,mutate:this.mutate,reset:this.reset}}#N(t){M.batch((()=>{this.#B&&this.hasListeners()&&("success"===t?.type?(this.#B.onSuccess?.(t.data,this.#q.variables,this.#q.context),this.#B.onSettled?.(t.data,null,this.#q.variables,this.#q.context)):"error"===t?.type&&(this.#B.onError?.(t.error,this.#q.variables,this.#q.context),this.#B.onSettled?.(void 0,t.error,this.#q.variables,this.#q.context))),this.listeners.forEach((t=>{t(this.#q)}))}))}},t.QueriesObserver=class extends e{#O;#W;#y;#c;constructor(t,e){super(),this.#O=t,this.#y=[],this.#W=[],this.#c=[],e&&this.setQueries(e)}onSubscribe(){1===this.listeners.length&&this.#c.forEach((t=>{t.subscribe((e=>{this.#z(t,e)}))}))}onUnsubscribe(){this.listeners.length||this.destroy()}destroy(){this.listeners=[],this.#c.forEach((t=>{t.destroy()}))}setQueries(t,e){this.#y=t,M.batch((()=>{const t=this.#c,s=this.#J(this.#y);s.forEach((t=>t.observer.setOptions(t.defaultedQueryOptions,e)));const i=s.map((t=>t.observer)),r=i.map((t=>t.getCurrentResult())),n=i.some(((e,s)=>e!==t[s]));(t.length!==i.length||n)&&(this.#c=i,this.#W=r,this.hasListeners()&&(B(t,i).forEach((t=>{t.destroy()})),B(i,t).forEach((t=>{t.subscribe((e=>{this.#z(t,e)}))})),this.#N()))}))}getCurrentResult(){return this.#W}getQueries(){return this.#c.map((t=>t.getCurrentQuery()))}getObservers(){return this.#c}getOptimisticResult(t){return this.#J(t).map((t=>t.observer.getOptimisticResult(t.defaultedQueryOptions)))}#J(t){const e=this.#c,s=t.map((t=>this.#O.defaultQueryOptions(t))),i=s.flatMap((t=>{const s=e.find((e=>e.options.queryHash===t.queryHash));return null!=s?[{defaultedQueryOptions:t,observer:s}]:[]})),r=i.map((t=>t.defaultedQueryOptions.queryHash)),n=s.filter((t=>!r.includes(t.queryHash))),a=t=>{const e=this.#O.defaultQueryOptions(t);return this.#c.find((t=>t.options.queryHash===e.queryHash))??new j(this.#O,e)},o=n.map((t=>({defaultedQueryOptions:t,observer:a(t)})));return i.concat(o).sort(((t,e)=>s.indexOf(t.defaultedQueryOptions)-s.indexOf(e.defaultedQueryOptions)))}#z(t,e){const s=this.#c.indexOf(t);-1!==s&&(this.#W=function(t,e,s){const i=t.slice(0);return i[e]=s,i}(this.#W,s,e),this.#N())}#N(){M.batch((()=>{this.listeners.forEach((t=>{t(this.#W)}))}))}},t.QueryCache=x,t.QueryClient=class{#V;#m;#l;#X;#Y;#Z;#$;#tt;constructor(t={}){this.#V=t.queryCache||new x,this.#m=t.mutationCache||new I,this.#l=t.defaultOptions||{},this.#X=new Map,this.#Y=new Map,this.#Z=0}mount(){this.#Z++,1===this.#Z&&(this.#$=R.subscribe((()=>{R.isFocused()&&(this.resumePausedMutations(),this.#V.onFocus())})),this.#tt=C.subscribe((()=>{C.isOnline()&&(this.resumePausedMutations(),this.#V.onOnline())})))}unmount(){this.#Z--,0===this.#Z&&(this.#$?.(),this.#$=void 0,this.#tt?.(),this.#tt=void 0)}isFetching(t){return this.#V.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#m.findAll({...t,status:"pending"}).length}getQueryData(t){return this.#V.find({queryKey:t})?.state.data}ensureQueryData(t){const e=this.getQueryData(t.queryKey);return e?Promise.resolve(e):this.fetchQuery(t)}getQueriesData(t){return this.getQueryCache().findAll(t).map((({queryKey:t,state:e})=>[t,e.data]))}setQueryData(t,e,s){const i=this.#V.find({queryKey:t})?.state.data,r=function(t,e){return"function"==typeof t?t(e):t}(e,i);if(void 0===r)return;const n=this.defaultQueryOptions({queryKey:t});return this.#V.build(this,n).setData(r,{...s,manual:!0})}setQueriesData(t,e,s){return M.batch((()=>this.getQueryCache().findAll(t).map((({queryKey:t})=>[t,this.setQueryData(t,e,s)]))))}getQueryState(t){return this.#V.find({queryKey:t})?.state}removeQueries(t){const e=this.#V;M.batch((()=>{e.findAll(t).forEach((t=>{e.remove(t)}))}))}resetQueries(t,e){const s=this.#V,i={type:"active",...t};return M.batch((()=>(s.findAll(t).forEach((t=>{t.reset()})),this.refetchQueries(i,e))))}cancelQueries(t={},e={}){void 0===e.revert&&(e.revert=!0);const s=M.batch((()=>this.#V.findAll(t).map((t=>t.cancel(e)))));return Promise.all(s).then(i).catch(i)}invalidateQueries(t={},e={}){return M.batch((()=>{if(this.#V.findAll(t).forEach((t=>{t.invalidate()})),"none"===t.refetchType)return Promise.resolve();const s={...t,type:t.refetchType??t.type??"active"};return this.refetchQueries(s,e)}))}refetchQueries(t={},e){const s=M.batch((()=>this.#V.findAll(t).filter((t=>!t.isDisabled())).map((t=>t.fetch(void 0,{...e,cancelRefetch:e?.cancelRefetch??!0})))));let r=Promise.all(s).then(i);return e?.throwOnError||(r=r.catch(i)),r}fetchQuery(t){const e=this.defaultQueryOptions(t);void 0===e.retry&&(e.retry=!1);const s=this.#V.build(this,e);return s.isStaleByTime(e.staleTime)?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(i).catch(i)}fetchInfiniteQuery(t){return t.behavior=U(),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(i).catch(i)}resumePausedMutations(){return this.#m.resumePausedMutations()}getQueryCache(){return this.#V}getMutationCache(){return this.#m}getDefaultOptions(){return this.#l}setDefaultOptions(t){this.#l=t}setQueryDefaults(t,e){this.#X.set(h(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...this.#X.values()];let s={};return e.forEach((e=>{c(t,e.queryKey)&&(s={...s,...e.defaultOptions})})),s}setMutationDefaults(t,e){this.#Y.set(h(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...this.#Y.values()];let s={};return e.forEach((e=>{c(t,e.mutationKey)&&(s={...s,...e.defaultOptions})})),s}defaultQueryOptions(t){if(t?._defaulted)return t;const e={...this.#l.queries,...t?.queryKey&&this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=u(e.queryKey,e)),void 0===e.refetchOnReconnect&&(e.refetchOnReconnect="always"!==e.networkMode),void 0===e.throwErrors&&(e.throwErrors=!!e.suspense),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#l.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#V.clear(),this.#m.clear()}},t.QueryObserver=j,t.defaultShouldDehydrateMutation=W,t.defaultShouldDehydrateQuery=z,t.dehydrate=function(t,e={}){const s=[],i=[];if(!1!==e.dehydrateMutations){const i=e.shouldDehydrateMutation||W;t.getMutationCache().getAll().forEach((t=>{i(t)&&s.push(function(t){return{mutationKey:t.options.mutationKey,state:t.state}}(t))}))}if(!1!==e.dehydrateQueries){const s=e.shouldDehydrateQuery||z;t.getQueryCache().getAll().forEach((t=>{s(t)&&i.push(function(t){return{state:t.state,queryKey:t.queryKey,queryHash:t.queryHash}}(t))}))}return{mutations:s,queries:i}},t.focusManager=R,t.hashKey=h,t.hydrate=function(t,e,s){if("object"!=typeof e||null===e)return;const i=t.getMutationCache(),r=t.getQueryCache(),n=e.mutations||[],a=e.queries||[];n.forEach((e=>{i.build(t,{...s?.defaultOptions?.mutations,mutationKey:e.mutationKey},e.state)})),a.forEach((e=>{const i=r.get(e.queryHash),n={...e.state,fetchStatus:"idle"};i?i.state.dataUpdatedAt<n.dataUpdatedAt&&i.setState(n):r.build(t,{...s?.defaultOptions?.queries,queryKey:e.queryKey,queryHash:e.queryHash},n)}))},t.isCancelledError=S,t.isServer=s,t.keepPreviousData=function(t){return t},t.matchQuery=a,t.notifyManager=M,t.onlineManager=C,t.replaceEqualDeep=l})); | ||
//# sourceMappingURL=index.production.js.map |
{ | ||
"name": "@tanstack/query-core", | ||
"version": "5.0.0-alpha.5", | ||
"version": "5.0.0-alpha.6", | ||
"description": "The framework agnostic core that powers TanStack Query", | ||
@@ -5,0 +5,0 @@ "author": "tannerlinsley", |
@@ -66,2 +66,3 @@ import type { QueryBehavior } from './query' | ||
pageParam: param, | ||
direction: previous ? 'backward' : 'forward', | ||
meta: context.options.meta, | ||
@@ -68,0 +69,0 @@ } |
@@ -77,4 +77,6 @@ import { noop, replaceData, timeUntilStale } from './utils' | ||
export type FetchDirection = 'forward' | 'backward' | ||
export interface FetchMeta { | ||
fetchMore?: { direction: 'forward' | 'backward' } | ||
fetchMore?: { direction: FetchDirection } | ||
} | ||
@@ -124,3 +126,3 @@ | ||
type: 'setState' | ||
state: QueryState<TData, TError> | ||
state: Partial<QueryState<TData, TError>> | ||
setStateOptions?: SetStateOptions | ||
@@ -216,3 +218,3 @@ } | ||
setState( | ||
state: QueryState<TData, TError>, | ||
state: Partial<QueryState<TData, TError>>, | ||
setStateOptions?: SetStateOptions, | ||
@@ -219,0 +221,0 @@ ): void { |
@@ -9,2 +9,3 @@ /* istanbul ignore file */ | ||
import type { MutationCache } from './mutationCache' | ||
import type { FetchDirection } from './query' | ||
@@ -44,2 +45,3 @@ export interface Register { | ||
pageParam: TPageParam | ||
direction: FetchDirection | ||
meta: QueryMeta | undefined | ||
@@ -46,0 +48,0 @@ } |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
1923677
196
22626