@studiolambda/query 1.4.0 → 1.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/query-CGIqlfYX.js +185 -0
- package/dist/query-CGIqlfYX.js.map +1 -0
- package/dist/query-Do4OvbxG.cjs +2 -0
- package/dist/query-Do4OvbxG.cjs.map +1 -0
- package/dist/query.cjs +1 -2
- package/dist/query.js +2 -193
- package/dist/query_react.cjs +3 -19
- package/dist/query_react.cjs.map +1 -1
- package/dist/query_react.js +255 -418
- package/dist/query_react.js.map +1 -1
- package/dist/src/query/options.d.ts +78 -4
- package/dist/src/react/components/QueryPrefetch.d.ts +30 -1
- package/dist/src/react/components/QueryPrefetchTags.d.ts +34 -1
- package/dist/src/react/components/QueryProvider.d.ts +30 -0
- package/dist/src/react/components/QueryTransition.d.ts +35 -0
- package/dist/src/react/context.d.ts +17 -0
- package/dist/src/react/hooks/useQuery.d.ts +44 -2
- package/dist/src/react/hooks/useQueryActions.d.ts +55 -1
- package/dist/src/react/hooks/useQueryBasic.d.ts +42 -2
- package/dist/src/react/hooks/useQueryContext.d.ts +13 -0
- package/dist/src/react/hooks/useQueryInstance.d.ts +27 -0
- package/dist/src/react/hooks/useQueryPrefetch.d.ts +15 -1
- package/dist/src/react/hooks/useQueryStatus.d.ts +40 -0
- package/dist/src/react/hooks/useQueryTransitionContext.d.ts +14 -0
- package/dist/src/react/transition.d.ts +17 -0
- package/package.json +57 -59
- package/dist/query.cjs.map +0 -1
- package/dist/query.js.map +0 -1
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var e = Object.defineProperty, __name = (t, n) => e(t, "name", {
|
|
3
|
+
value: n,
|
|
4
|
+
configurable: !0
|
|
5
|
+
}), __commonJSMin = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports), t = /* @__PURE__ */ ((e) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(e, { get: (e, t) => (typeof require < "u" ? require : e)[t] }) : e)(function(e) {
|
|
6
|
+
if (typeof require < "u") return require.apply(this, arguments);
|
|
7
|
+
throw Error("Calling `require` for \"" + e + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
|
|
8
|
+
});
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/query/query.ts
|
|
11
|
+
function defaultFetcher(e) {
|
|
12
|
+
return async function(t, { signal: n }) {
|
|
13
|
+
let r = await e(t, { signal: n });
|
|
14
|
+
if (!r.ok) throw Error("Unable to fetch the data: " + r.statusText);
|
|
15
|
+
return await r.json();
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function createQuery(e) {
|
|
19
|
+
function defaultExpiration() {
|
|
20
|
+
return 2e3;
|
|
21
|
+
}
|
|
22
|
+
let t = e?.itemsCache ?? /* @__PURE__ */ new Map(), n = e?.resolversCache ?? /* @__PURE__ */ new Map(), r = e?.events ?? new EventTarget(), i = e?.broadcast, a = e?.expiration ?? defaultExpiration, o = e?.fetcher ?? defaultFetcher(fetch), s = e?.stale ?? !0, c = e?.removeOnError ?? !1, l = e?.fresh ?? !1;
|
|
23
|
+
function configure(e) {
|
|
24
|
+
t = e?.itemsCache ?? t, n = e?.resolversCache ?? n, r = e?.events ?? r, i = e?.broadcast ?? i, a = e?.expiration ?? a, o = e?.fetcher ?? o, s = e?.stale ?? s, c = e?.removeOnError ?? c, l = e?.fresh ?? l;
|
|
25
|
+
}
|
|
26
|
+
function emit(e, t, n) {
|
|
27
|
+
switch (r.dispatchEvent(new CustomEvent(`${t}:${e}`, { detail: n })), t) {
|
|
28
|
+
case "mutated":
|
|
29
|
+
case "resolved":
|
|
30
|
+
case "hydrated":
|
|
31
|
+
case "forgotten": i?.postMessage({
|
|
32
|
+
event: `${t}:${e}`,
|
|
33
|
+
detail: n
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function subscribe(e, t, i) {
|
|
38
|
+
r.addEventListener(`${t}:${e}`, i);
|
|
39
|
+
let a = n.get(e);
|
|
40
|
+
return t === "refetching" && a !== void 0 && emit(e, t, a.item), function() {
|
|
41
|
+
r.removeEventListener(`${t}:${e}`, i);
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
async function mutate(e, n, r) {
|
|
45
|
+
async function action(n) {
|
|
46
|
+
if (typeof n == "function") {
|
|
47
|
+
let r = n, i = t.get(e);
|
|
48
|
+
n = await r(await i?.item, i?.expiresAt);
|
|
49
|
+
}
|
|
50
|
+
return n;
|
|
51
|
+
}
|
|
52
|
+
let i = action(n);
|
|
53
|
+
emit(e, "mutating", i);
|
|
54
|
+
let a = await i, o = /* @__PURE__ */ new Date();
|
|
55
|
+
return o.setMilliseconds(o.getMilliseconds() + (r?.expiration?.(a) ?? 0)), t.set(e, {
|
|
56
|
+
item: i,
|
|
57
|
+
expiresAt: o
|
|
58
|
+
}), emit(e, "mutated", a), a;
|
|
59
|
+
}
|
|
60
|
+
async function snapshot(e) {
|
|
61
|
+
return await t.get(e)?.item;
|
|
62
|
+
}
|
|
63
|
+
function keys(e = "items") {
|
|
64
|
+
return Array.from(e === "items" ? t.keys() : n.keys());
|
|
65
|
+
}
|
|
66
|
+
function abort(e, t) {
|
|
67
|
+
let r = typeof e == "string" ? [e] : e ?? keys("resolvers");
|
|
68
|
+
for (let e of r) {
|
|
69
|
+
let r = n.get(e);
|
|
70
|
+
r !== void 0 && (r.controller.abort(t), n.delete(e), emit(e, "aborted", t));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
async function forget(e) {
|
|
74
|
+
let n;
|
|
75
|
+
n = typeof e == "string" ? [e] : Array.isArray(e) ? e : e instanceof RegExp ? keys("items").filter((t) => t.match(e)) : keys("items");
|
|
76
|
+
for (let e of n) {
|
|
77
|
+
let n = t.get(e);
|
|
78
|
+
n !== void 0 && (t.delete(e), emit(e, "forgotten", await n.item));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function hydrate(e, n, r) {
|
|
82
|
+
let i = /* @__PURE__ */ new Date(), a = Promise.resolve(n);
|
|
83
|
+
i.setMilliseconds(i.getMilliseconds() + (r?.expiration?.(n) ?? 0));
|
|
84
|
+
for (let r of typeof e == "string" ? [e] : e) t.set(r, {
|
|
85
|
+
item: a,
|
|
86
|
+
expiresAt: i
|
|
87
|
+
}), emit(r, "hydrated", n);
|
|
88
|
+
}
|
|
89
|
+
function expiration(e) {
|
|
90
|
+
return t.get(e)?.expiresAt;
|
|
91
|
+
}
|
|
92
|
+
function query(r, i) {
|
|
93
|
+
let l = i?.expiration ?? a, u = i?.fetcher ?? o, d = i?.stale ?? s, f = i?.removeOnError ?? c, p = i?.fresh ?? e?.fresh;
|
|
94
|
+
function refetch(e) {
|
|
95
|
+
let r = n.get(e);
|
|
96
|
+
if (r !== void 0) return r.item;
|
|
97
|
+
let i = new AbortController(), trigger, a = new Promise(function(r, a) {
|
|
98
|
+
trigger = async function() {
|
|
99
|
+
try {
|
|
100
|
+
let a = await u(e, { signal: i.signal }), o = n.get(e)?.item ?? Promise.resolve(a);
|
|
101
|
+
n.delete(e);
|
|
102
|
+
let s = /* @__PURE__ */ new Date();
|
|
103
|
+
s.setMilliseconds(s.getMilliseconds() + l(a)), t.set(e, {
|
|
104
|
+
item: o,
|
|
105
|
+
expiresAt: s
|
|
106
|
+
}), emit(e, "resolved", a), r(a);
|
|
107
|
+
} catch (r) {
|
|
108
|
+
n.delete(e), f && t.delete(e), emit(e, "error", r), a(r);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
});
|
|
112
|
+
return n.set(e, {
|
|
113
|
+
item: a,
|
|
114
|
+
controller: i
|
|
115
|
+
}), emit(e, "refetching", a), trigger(), a;
|
|
116
|
+
}
|
|
117
|
+
if (p) return refetch(r);
|
|
118
|
+
let m = t.get(r);
|
|
119
|
+
if (m === void 0) return refetch(r);
|
|
120
|
+
let h = m.expiresAt <= /* @__PURE__ */ new Date();
|
|
121
|
+
return h && d ? (refetch(r).catch(() => {}), m.item) : h ? refetch(r) : m.item;
|
|
122
|
+
}
|
|
123
|
+
function caches() {
|
|
124
|
+
return {
|
|
125
|
+
items: t,
|
|
126
|
+
resolvers: n
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function localEvents() {
|
|
130
|
+
return r;
|
|
131
|
+
}
|
|
132
|
+
function localBroadcast() {
|
|
133
|
+
return i;
|
|
134
|
+
}
|
|
135
|
+
function subscribeBroadcast() {
|
|
136
|
+
function onBroadcastMessage(e) {
|
|
137
|
+
r.dispatchEvent(new CustomEvent(e.data.event, { detail: e.data.detail }));
|
|
138
|
+
}
|
|
139
|
+
return i?.addEventListener("message", onBroadcastMessage), function() {
|
|
140
|
+
i?.removeEventListener("message", onBroadcastMessage);
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
async function next(e) {
|
|
144
|
+
let t = (Array.isArray(e) ? e : [e]).map((e) => once(e, "refetching")), n = (await Promise.all(t)).map((e) => e.detail);
|
|
145
|
+
return await (Array.isArray(e) ? Promise.all(n) : n[0]);
|
|
146
|
+
}
|
|
147
|
+
async function* stream(e) {
|
|
148
|
+
for (;;) yield await next(e);
|
|
149
|
+
}
|
|
150
|
+
function once(e, t) {
|
|
151
|
+
return new Promise(function(n) {
|
|
152
|
+
let r = subscribe(e, t, function(e) {
|
|
153
|
+
n(e), r();
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
async function* sequence(e, t) {
|
|
158
|
+
for (;;) yield await once(e, t);
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
query,
|
|
162
|
+
emit,
|
|
163
|
+
subscribe,
|
|
164
|
+
subscribeBroadcast,
|
|
165
|
+
mutate,
|
|
166
|
+
configure,
|
|
167
|
+
abort,
|
|
168
|
+
forget,
|
|
169
|
+
keys,
|
|
170
|
+
expiration,
|
|
171
|
+
hydrate,
|
|
172
|
+
snapshot,
|
|
173
|
+
once,
|
|
174
|
+
sequence,
|
|
175
|
+
next,
|
|
176
|
+
stream,
|
|
177
|
+
caches,
|
|
178
|
+
events: localEvents,
|
|
179
|
+
broadcast: localBroadcast
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
//#endregion
|
|
183
|
+
export { t as a, __name as i, defaultFetcher as n, __commonJSMin as r, createQuery as t };
|
|
184
|
+
|
|
185
|
+
//# sourceMappingURL=query-CGIqlfYX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-CGIqlfYX.js","names":[],"sources":["../src/query/query.ts"],"sourcesContent":["import {\n type Caches,\n type CacheType,\n type ItemsCacheItem,\n type ResolversCacheItem,\n} from 'query:cache'\nimport {\n type BroadcastPayload,\n type Configuration,\n type FetcherAdditional,\n type FetcherFunction,\n type HydrateOptions,\n type MutateOptions,\n type MutationFunction,\n type MutationValue,\n type Options,\n type Query,\n type QueryEvent,\n type SubscribeListener,\n type TriggerFunction,\n type Unsubscriber,\n} from 'query:options'\n\n/**\n * Stores the default fetcher function.\n */\nexport function defaultFetcher<T>(\n fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>\n): FetcherFunction<T> {\n return async function (key: string, { signal }: FetcherAdditional): Promise<T> {\n const response = await fetch(key, { signal })\n\n if (!response.ok) {\n throw new Error('Unable to fetch the data: ' + response.statusText)\n }\n\n return (await response.json()) as T\n }\n}\n\n/**\n * Creates a new query instance.\n */\nexport function createQuery(instanceOptions?: Configuration): Query {\n /**\n * Stores the default expiration function.\n */\n function defaultExpiration() {\n return 2000\n }\n\n /**\n * Stores the items cache.\n */\n let itemsCache = instanceOptions?.itemsCache ?? new Map<string, ItemsCacheItem>()\n\n /**\n * Stores the resolvers cache.\n */\n let resolversCache = instanceOptions?.resolversCache ?? new Map<string, ResolversCacheItem>()\n\n /**\n * Event manager.\n */\n let events = instanceOptions?.events ?? new EventTarget()\n\n /**\n * Broadcast channel. This is useful for communicating\n * between tabs and windows (browser contexts).\n *\n * By default it does not use any broadcast channel.\n * If a broadcast channel is provided, query\n * won't close automatically, therefore, the responsability\n * of closing the broadcast channel is up to the user.\n */\n let broadcast = instanceOptions?.broadcast\n\n /**\n * Stores the expiration time of an item.\n */\n let instanceExpiration = instanceOptions?.expiration ?? defaultExpiration\n\n /**\n * Determines the fetcher function to use.\n */\n let instanceFetcher = instanceOptions?.fetcher ?? defaultFetcher(fetch)\n\n /**\n * Determines if we can return a stale item.\n * If `true`, it will return the previous stale item\n * stored in the cache if it has expired. It will attempt\n * to revalidate it in the background. If `false`, the returned\n * promise will be the revalidation promise.\n */\n let instanceStale = instanceOptions?.stale ?? true\n\n /**\n * Removes the stored item if there is an error in the request.\n * By default, we don't remove the item upon failure, only the resolver\n * is removed from the cache.\n */\n let instanceRemoveOnError = instanceOptions?.removeOnError ?? false\n\n /**\n * Determines if the result should be a fresh fetched\n * instance regardless of any cached value or its expiration time.\n */\n let instanceFresh = instanceOptions?.fresh ?? false\n\n /**\n * Configures the current instance of query.\n */\n function configure(options?: Configuration): void {\n itemsCache = options?.itemsCache ?? itemsCache\n resolversCache = options?.resolversCache ?? resolversCache\n events = options?.events ?? events\n broadcast = options?.broadcast ?? broadcast\n instanceExpiration = options?.expiration ?? instanceExpiration\n instanceFetcher = options?.fetcher ?? instanceFetcher\n instanceStale = options?.stale ?? instanceStale\n instanceRemoveOnError = options?.removeOnError ?? instanceRemoveOnError\n instanceFresh = options?.fresh ?? instanceFresh\n }\n\n /**\n * Emits an event to all active subscribers for a given key.\n * Also broadcasts certain events (mutated, resolved, hydrated, forgotten)\n * to other browser contexts via the BroadcastChannel if configured.\n *\n * @param key - The cache key associated with the event.\n * @param event - The type of event to emit.\n * @param detail - The payload to include with the event.\n */\n function emit<T = unknown>(key: string, event: QueryEvent, detail: T) {\n events.dispatchEvent(new CustomEvent(`${event}:${key}`, { detail }))\n\n switch (event) {\n case 'mutated':\n case 'resolved':\n case 'hydrated':\n case 'forgotten':\n broadcast?.postMessage({ event: `${event}:${key}`, detail })\n }\n }\n\n /**\n * Subscribes to a given keyed event. The event handler\n * does have a payload parameter that will contain relevant\n * information depending on the event type.\n * If there's a pending resolver for that key, the `refetching`\n * event is fired immediatly.\n */\n function subscribe<T = unknown>(\n key: string,\n event: QueryEvent,\n listener: SubscribeListener<T>\n ): Unsubscriber {\n events.addEventListener(`${event}:${key}`, listener)\n const value = resolversCache.get(key)\n\n // For the refetching event, we want to immediatly return if there's\n // a pending resolver.\n if (event === 'refetching' && value !== undefined) {\n emit(key, event, value.item)\n }\n\n return function () {\n events.removeEventListener(`${event}:${key}`, listener)\n }\n }\n\n /**\n * Mutates the key with a given optimistic value.\n * The mutated value is considered expired and will be\n * replaced immediatly if a refetch happens when expired\n * is true. If expired is false, the value expiration time\n * is added as if it was a valid data refetched. Alternatively\n * you can provide a Date to decide when the expiration happens.\n */\n async function mutate<T = unknown>(\n key: string,\n resolver: MutationValue<T>,\n options?: MutateOptions<T>\n ): Promise<T> {\n async function action(resolver: MutationValue<T>) {\n if (typeof resolver === 'function') {\n const fn = resolver as MutationFunction<T>\n const value = itemsCache.get(key)\n const item = (await value?.item) as T\n\n resolver = await fn(item, value?.expiresAt)\n }\n\n return resolver\n }\n\n const result = action(resolver)\n\n emit(key, 'mutating', result)\n\n const item = await result\n const expiresAt = new Date()\n\n expiresAt.setMilliseconds(expiresAt.getMilliseconds() + (options?.expiration?.(item) ?? 0))\n\n itemsCache.set(key, { item: result, expiresAt: expiresAt })\n\n emit(key, 'mutated', item)\n\n return item\n }\n\n /**\n * Returns the current snapshot of the given key.\n * If the item is not in the items cache, it will return `undefined`.\n */\n async function snapshot<T = unknown>(key: string): Promise<T | undefined> {\n return (await itemsCache.get(key)?.item) as T\n }\n\n /**\n * Determines if the given key is currently resolving.\n */\n function keys(type: CacheType = 'items'): readonly string[] {\n return Array.from(type === 'items' ? itemsCache.keys() : resolversCache.keys())\n }\n\n /**\n * Aborts the active resolvers on each key\n * by calling `.abort()` on the `AbortController`.\n * The fetcher is responsible for using the\n * `AbortSignal` to cancel the job.\n * If no keys are provided, all resolvers are aborted.\n */\n function abort(cacheKeys?: string | readonly string[], reason?: unknown): void {\n const resolverKeys =\n typeof cacheKeys === 'string' ? [cacheKeys] : (cacheKeys ?? keys('resolvers'))\n\n for (const key of resolverKeys) {\n const resolver = resolversCache.get(key)\n\n if (resolver !== undefined) {\n resolver.controller.abort(reason)\n resolversCache.delete(key)\n\n emit(key, 'aborted', reason)\n }\n }\n }\n\n /**\n * Forgets the given keys from the items cache.\n * Does not remove any resolvers.\n * If no keys are provided the items cache is cleared.\n */\n async function forget(cacheKeys?: string | readonly string[] | RegExp): Promise<void> {\n let itemKeys: readonly string[]\n\n if (typeof cacheKeys === 'string') {\n itemKeys = [cacheKeys]\n } else if (Array.isArray(cacheKeys)) {\n itemKeys = cacheKeys\n } else if (cacheKeys instanceof RegExp) {\n itemKeys = keys('items').filter((key) => key.match(cacheKeys))\n } else {\n itemKeys = keys('items')\n }\n\n for (const key of itemKeys) {\n const item = itemsCache.get(key)\n\n if (item !== undefined) {\n itemsCache.delete(key)\n emit(key, 'forgotten', await item.item)\n }\n }\n }\n\n /**\n * Hydrates the given keys on the cache\n * with the given value. Hydrate should only\n * be used when you want to populate the cache.\n * Please use mutate() in most cases unless you\n * know what you are doing.\n */\n function hydrate<T = unknown>(\n keys: string | readonly string[],\n item: T,\n options?: HydrateOptions<T>\n ): void {\n const expiresAt = new Date()\n const result = Promise.resolve(item)\n\n expiresAt.setMilliseconds(expiresAt.getMilliseconds() + (options?.expiration?.(item) ?? 0))\n\n for (const key of typeof keys === 'string' ? [keys] : keys) {\n itemsCache.set(key, { item: result, expiresAt: expiresAt })\n emit(key, 'hydrated', item)\n }\n }\n\n /**\n * Returns the expiration date of a given key item.\n * If the item is not in the cache, it will return `undefined`.\n */\n function expiration(key: string): Date | undefined {\n return itemsCache.get(key)?.expiresAt\n }\n\n /**\n * Fetches the key information using a fetcher.\n * The returned promise contains the result item.\n */\n function query<T = unknown>(key: string, options?: Options<T>): Promise<T> {\n /**\n * Stores the expiration time of an item.\n */\n const expiration = options?.expiration ?? instanceExpiration\n\n /**\n * Determines the fetcher function to use.\n */\n const fetcher = (options?.fetcher ?? instanceFetcher) as FetcherFunction<T>\n\n /**\n * Determines if we can return a sale item\n * If true, it will return the previous stale item\n * stored in the cache if it has expired. It will attempt\n * to revalidate it in the background. If false, the returned\n * promise will be the revalidation promise.\n */\n const stale = options?.stale ?? instanceStale\n\n /**\n * Removes the stored item if there is an error in the request.\n * By default, we don't remove the item upon failure, only the resolver\n * is removed from the cache.\n */\n const removeOnError = options?.removeOnError ?? instanceRemoveOnError\n\n /**\n * Determines if the result should be a fresh fetched\n * instance regardless of any cached value or its expiration time.\n */\n const fresh = options?.fresh ?? instanceOptions?.fresh\n\n // Force fetching of the data.\n function refetch(key: string): Promise<T> {\n // Check if there's a pending resolver for that data.\n const pending = resolversCache.get(key)\n\n if (pending !== undefined) {\n return pending.item as Promise<T>\n }\n\n // Create the abort controller that will be\n // called when a query is aborted.\n const controller = new AbortController()\n\n let trigger: TriggerFunction = undefined\n\n // Initiate the fetching request.\n const result = new Promise<T>(function (resolve, reject) {\n trigger = async function () {\n try {\n const result = fetcher(key, { signal: controller.signal })\n\n // Awaits the fetching to get the result item.\n const item = await result\n\n const promise =\n (resolversCache.get(key)?.item as Promise<T> | undefined) ?? Promise.resolve(item)\n\n // Removes the resolver from the cache.\n resolversCache.delete(key)\n\n // Create the expiration time for the item.\n const expiresAt = new Date()\n expiresAt.setMilliseconds(expiresAt.getMilliseconds() + expiration(item))\n\n // Set the item to the cache.\n itemsCache.set(key, { item: promise, expiresAt })\n\n // Notify of the resolved item.\n emit(key, 'resolved', item)\n\n resolve(item)\n } catch (error) {\n // Remove the resolver.\n resolversCache.delete(key)\n\n // Check if the item should be removed as well.\n if (removeOnError) {\n itemsCache.delete(key)\n }\n\n // Notify of the error.\n emit(key, 'error', error)\n\n // Throw back the error.\n reject(error as Error)\n }\n }\n })\n\n // Adds the resolver to the cache.\n resolversCache.set(key, { item: result, controller })\n emit(key, 'refetching', result)\n\n // The promise executor runs synchronously,\n // so trigger is guaranteed to be defined here.\n void trigger!()\n\n return result\n }\n\n // We want to force a fresh item ignoring any current cached\n // value or its expiration time.\n if (fresh) {\n return refetch(key)\n }\n\n // Check if there's an item in the cache for the given key.\n const cached = itemsCache.get(key)\n\n if (cached === undefined) {\n // The item is not found in the items cache.\n // We need to perform a revalidation of the item.\n return refetch(key)\n }\n\n // We must check if that item has actually expired.\n // to trigger a revalidation if needed.\n const hasExpired = cached.expiresAt <= new Date()\n\n // The item has expired and the fetch is able\n // to return a stale item while revalidating\n // in the background.\n if (hasExpired && stale) {\n // We have to silence the error to avoid unhandled promises.\n // Refer to the error event if you need full controll of errors.\n refetch(key).catch(() => {})\n\n return cached.item as Promise<T>\n }\n\n // The item has expired but we dont allow stale\n // responses so we need to wait for the revalidation.\n if (hasExpired) {\n return refetch(key)\n }\n\n // The item has not yet expired, so we can return it and\n // assume it's valid since it's not yet considered stale.\n return cached.item as Promise<T>\n }\n\n /**\n * Returns the current cache instances.\n */\n function caches(): Caches {\n return { items: itemsCache, resolvers: resolversCache }\n }\n\n /**\n * Returns the event system.\n */\n function localEvents() {\n return events\n }\n\n /**\n * Returns the broadcast channel.\n */\n function localBroadcast() {\n return broadcast\n }\n\n /**\n * Subscribes to the broadcast channel\n * to listen for other browser context\n * events and reproduce them in the current\n * context.\n */\n function subscribeBroadcast(): Unsubscriber {\n function onBroadcastMessage(message: MessageEvent<BroadcastPayload>) {\n events.dispatchEvent(new CustomEvent(message.data.event, { detail: message.data.detail }))\n }\n\n broadcast?.addEventListener('message', onBroadcastMessage)\n\n return function () {\n broadcast?.removeEventListener('message', onBroadcastMessage)\n }\n }\n\n /**\n * Waits for the next refetching event on one or more keys and returns\n * the resolved values. Useful for synchronizing with query updates.\n *\n * @param keys - A single key or an object mapping property names to keys.\n * @returns A promise that resolves with the fetched value(s).\n */\n async function next<T = unknown>(keys: string | { [K in keyof T]: string }): Promise<T> {\n const iterator = (Array.isArray(keys) ? keys : [keys]) as readonly string[]\n const promises = iterator.map((key) => once(key, 'refetching'))\n const events = await Promise.all(promises)\n const details = events.map((event) => event.detail as Promise<T>)\n\n return (await (Array.isArray(keys) ? Promise.all(details) : details[0])) as T\n }\n\n /**\n * Returns an async generator that yields resolved values as they come in\n * for the specified key(s). Allows continuous streaming of query results.\n *\n * @param keys - A single key or an object mapping property names to keys.\n * @yields The resolved value(s) each time a refetch completes.\n */\n async function* stream<T = unknown>(keys: string | { [K in keyof T]: string }) {\n for (;;) {\n yield await next<T>(keys)\n }\n }\n\n /**\n * Returns the first occurrence of a specific event for a given key.\n * Subscribes to the event and automatically unsubscribes after receiving it.\n *\n * @param key - The cache key to listen for events on.\n * @param event - The type of event to wait for.\n * @returns A promise that resolves with the event details.\n */\n function once<T = unknown>(key: string, event: QueryEvent) {\n return new Promise<CustomEventInit<T>>(function (resolve) {\n const unsubscribe = subscribe<T>(key, event, function (event) {\n resolve(event)\n unsubscribe()\n })\n })\n }\n\n /**\n * Returns an async generator that yields event details each time the\n * specified event occurs for a given key. Allows iteration over a\n * continuous sequence of events.\n *\n * @param key - The cache key to listen for events on.\n * @param event - The type of event to stream.\n * @yields The event details each time the event occurs.\n */\n async function* sequence<T = unknown>(key: string, event: QueryEvent) {\n for (;;) {\n yield await once<T>(key, event)\n }\n }\n\n return {\n query,\n emit,\n subscribe,\n subscribeBroadcast,\n mutate,\n configure,\n abort,\n forget,\n keys,\n expiration,\n hydrate,\n snapshot,\n once,\n sequence,\n next,\n stream,\n caches,\n events: localEvents,\n broadcast: localBroadcast,\n }\n}\n"],"mappings":";;;;;;;;;;AA0BA,SAAgB,eACd,GACoB;AACpB,QAAO,eAAgB,GAAa,EAAE,aAAyC;EAC7E,IAAM,IAAW,MAAM,EAAM,GAAK,EAAE,WAAQ,CAAC;AAE7C,MAAI,CAAC,EAAS,GACZ,OAAU,MAAM,+BAA+B,EAAS,WAAW;AAGrE,SAAQ,MAAM,EAAS,MAA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B,SAAU,GAAS;GACxD,IAAM,IAAc,UAAa,GAAK,GAAO,SAAU,GAAO;AAE5D,IADA,EAAQ,EAAM,EACd,GAAa;KACb;IACF;;CAYJ,gBAAgB,SAAsB,GAAa,GAAmB;AACpE,UACE,OAAM,MAAM,KAAQ,GAAK,EAAM;;AAInC,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR,WAAW;EACZ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e=Object.defineProperty,__name=(t,n)=>e(t,`name`,{value:n,configurable:!0}),__commonJSMin=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);function defaultFetcher(e){return async function(t,{signal:n}){let r=await e(t,{signal:n});if(!r.ok)throw Error(`Unable to fetch the data: `+r.statusText);return await r.json()}}function createQuery(e){function defaultExpiration(){return 2e3}let t=e?.itemsCache??new Map,n=e?.resolversCache??new Map,r=e?.events??new EventTarget,i=e?.broadcast,a=e?.expiration??defaultExpiration,o=e?.fetcher??defaultFetcher(fetch),s=e?.stale??!0,c=e?.removeOnError??!1,l=e?.fresh??!1;function configure(e){t=e?.itemsCache??t,n=e?.resolversCache??n,r=e?.events??r,i=e?.broadcast??i,a=e?.expiration??a,o=e?.fetcher??o,s=e?.stale??s,c=e?.removeOnError??c,l=e?.fresh??l}function emit(e,t,n){switch(r.dispatchEvent(new CustomEvent(`${t}:${e}`,{detail:n})),t){case`mutated`:case`resolved`:case`hydrated`:case`forgotten`:i?.postMessage({event:`${t}:${e}`,detail:n})}}function subscribe(e,t,i){r.addEventListener(`${t}:${e}`,i);let a=n.get(e);return t===`refetching`&&a!==void 0&&emit(e,t,a.item),function(){r.removeEventListener(`${t}:${e}`,i)}}async function mutate(e,n,r){async function action(n){if(typeof n==`function`){let r=n,i=t.get(e);n=await r(await i?.item,i?.expiresAt)}return n}let i=action(n);emit(e,`mutating`,i);let a=await i,o=new Date;return o.setMilliseconds(o.getMilliseconds()+(r?.expiration?.(a)??0)),t.set(e,{item:i,expiresAt:o}),emit(e,`mutated`,a),a}async function snapshot(e){return await t.get(e)?.item}function keys(e=`items`){return Array.from(e===`items`?t.keys():n.keys())}function abort(e,t){let r=typeof e==`string`?[e]:e??keys(`resolvers`);for(let e of r){let r=n.get(e);r!==void 0&&(r.controller.abort(t),n.delete(e),emit(e,`aborted`,t))}}async function forget(e){let n;n=typeof e==`string`?[e]:Array.isArray(e)?e:e instanceof RegExp?keys(`items`).filter(t=>t.match(e)):keys(`items`);for(let e of n){let n=t.get(e);n!==void 0&&(t.delete(e),emit(e,`forgotten`,await n.item))}}function hydrate(e,n,r){let i=new Date,a=Promise.resolve(n);i.setMilliseconds(i.getMilliseconds()+(r?.expiration?.(n)??0));for(let r of typeof e==`string`?[e]:e)t.set(r,{item:a,expiresAt:i}),emit(r,`hydrated`,n)}function expiration(e){return t.get(e)?.expiresAt}function query(r,i){let l=i?.expiration??a,u=i?.fetcher??o,d=i?.stale??s,f=i?.removeOnError??c,p=i?.fresh??e?.fresh;function refetch(e){let r=n.get(e);if(r!==void 0)return r.item;let i=new AbortController,trigger,a=new Promise(function(r,a){trigger=async function(){try{let a=await u(e,{signal:i.signal}),o=n.get(e)?.item??Promise.resolve(a);n.delete(e);let s=new Date;s.setMilliseconds(s.getMilliseconds()+l(a)),t.set(e,{item:o,expiresAt:s}),emit(e,`resolved`,a),r(a)}catch(r){n.delete(e),f&&t.delete(e),emit(e,`error`,r),a(r)}}});return n.set(e,{item:a,controller:i}),emit(e,`refetching`,a),trigger(),a}if(p)return refetch(r);let m=t.get(r);if(m===void 0)return refetch(r);let h=m.expiresAt<=new Date;return h&&d?(refetch(r).catch(()=>{}),m.item):h?refetch(r):m.item}function caches(){return{items:t,resolvers:n}}function localEvents(){return r}function localBroadcast(){return i}function subscribeBroadcast(){function onBroadcastMessage(e){r.dispatchEvent(new CustomEvent(e.data.event,{detail:e.data.detail}))}return i?.addEventListener(`message`,onBroadcastMessage),function(){i?.removeEventListener(`message`,onBroadcastMessage)}}async function next(e){let t=(Array.isArray(e)?e:[e]).map(e=>once(e,`refetching`)),n=(await Promise.all(t)).map(e=>e.detail);return await(Array.isArray(e)?Promise.all(n):n[0])}async function*stream(e){for(;;)yield await next(e)}function once(e,t){return new Promise(function(n){let r=subscribe(e,t,function(e){n(e),r()})})}async function*sequence(e,t){for(;;)yield await once(e,t)}return{query,emit,subscribe,subscribeBroadcast,mutate,configure,abort,forget,keys,expiration,hydrate,snapshot,once,sequence,next,stream,caches,events:localEvents,broadcast:localBroadcast}}Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return __name}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return defaultFetcher}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return __commonJSMin}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return createQuery}});
|
|
2
|
+
//# sourceMappingURL=query-Do4OvbxG.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-Do4OvbxG.cjs","names":[],"sources":["../src/query/query.ts"],"sourcesContent":["import {\n type Caches,\n type CacheType,\n type ItemsCacheItem,\n type ResolversCacheItem,\n} from 'query:cache'\nimport {\n type BroadcastPayload,\n type Configuration,\n type FetcherAdditional,\n type FetcherFunction,\n type HydrateOptions,\n type MutateOptions,\n type MutationFunction,\n type MutationValue,\n type Options,\n type Query,\n type QueryEvent,\n type SubscribeListener,\n type TriggerFunction,\n type Unsubscriber,\n} from 'query:options'\n\n/**\n * Stores the default fetcher function.\n */\nexport function defaultFetcher<T>(\n fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>\n): FetcherFunction<T> {\n return async function (key: string, { signal }: FetcherAdditional): Promise<T> {\n const response = await fetch(key, { signal })\n\n if (!response.ok) {\n throw new Error('Unable to fetch the data: ' + response.statusText)\n }\n\n return (await response.json()) as T\n }\n}\n\n/**\n * Creates a new query instance.\n */\nexport function createQuery(instanceOptions?: Configuration): Query {\n /**\n * Stores the default expiration function.\n */\n function defaultExpiration() {\n return 2000\n }\n\n /**\n * Stores the items cache.\n */\n let itemsCache = instanceOptions?.itemsCache ?? new Map<string, ItemsCacheItem>()\n\n /**\n * Stores the resolvers cache.\n */\n let resolversCache = instanceOptions?.resolversCache ?? new Map<string, ResolversCacheItem>()\n\n /**\n * Event manager.\n */\n let events = instanceOptions?.events ?? new EventTarget()\n\n /**\n * Broadcast channel. This is useful for communicating\n * between tabs and windows (browser contexts).\n *\n * By default it does not use any broadcast channel.\n * If a broadcast channel is provided, query\n * won't close automatically, therefore, the responsability\n * of closing the broadcast channel is up to the user.\n */\n let broadcast = instanceOptions?.broadcast\n\n /**\n * Stores the expiration time of an item.\n */\n let instanceExpiration = instanceOptions?.expiration ?? defaultExpiration\n\n /**\n * Determines the fetcher function to use.\n */\n let instanceFetcher = instanceOptions?.fetcher ?? defaultFetcher(fetch)\n\n /**\n * Determines if we can return a stale item.\n * If `true`, it will return the previous stale item\n * stored in the cache if it has expired. It will attempt\n * to revalidate it in the background. If `false`, the returned\n * promise will be the revalidation promise.\n */\n let instanceStale = instanceOptions?.stale ?? true\n\n /**\n * Removes the stored item if there is an error in the request.\n * By default, we don't remove the item upon failure, only the resolver\n * is removed from the cache.\n */\n let instanceRemoveOnError = instanceOptions?.removeOnError ?? false\n\n /**\n * Determines if the result should be a fresh fetched\n * instance regardless of any cached value or its expiration time.\n */\n let instanceFresh = instanceOptions?.fresh ?? false\n\n /**\n * Configures the current instance of query.\n */\n function configure(options?: Configuration): void {\n itemsCache = options?.itemsCache ?? itemsCache\n resolversCache = options?.resolversCache ?? resolversCache\n events = options?.events ?? events\n broadcast = options?.broadcast ?? broadcast\n instanceExpiration = options?.expiration ?? instanceExpiration\n instanceFetcher = options?.fetcher ?? instanceFetcher\n instanceStale = options?.stale ?? instanceStale\n instanceRemoveOnError = options?.removeOnError ?? instanceRemoveOnError\n instanceFresh = options?.fresh ?? instanceFresh\n }\n\n /**\n * Emits an event to all active subscribers for a given key.\n * Also broadcasts certain events (mutated, resolved, hydrated, forgotten)\n * to other browser contexts via the BroadcastChannel if configured.\n *\n * @param key - The cache key associated with the event.\n * @param event - The type of event to emit.\n * @param detail - The payload to include with the event.\n */\n function emit<T = unknown>(key: string, event: QueryEvent, detail: T) {\n events.dispatchEvent(new CustomEvent(`${event}:${key}`, { detail }))\n\n switch (event) {\n case 'mutated':\n case 'resolved':\n case 'hydrated':\n case 'forgotten':\n broadcast?.postMessage({ event: `${event}:${key}`, detail })\n }\n }\n\n /**\n * Subscribes to a given keyed event. The event handler\n * does have a payload parameter that will contain relevant\n * information depending on the event type.\n * If there's a pending resolver for that key, the `refetching`\n * event is fired immediatly.\n */\n function subscribe<T = unknown>(\n key: string,\n event: QueryEvent,\n listener: SubscribeListener<T>\n ): Unsubscriber {\n events.addEventListener(`${event}:${key}`, listener)\n const value = resolversCache.get(key)\n\n // For the refetching event, we want to immediatly return if there's\n // a pending resolver.\n if (event === 'refetching' && value !== undefined) {\n emit(key, event, value.item)\n }\n\n return function () {\n events.removeEventListener(`${event}:${key}`, listener)\n }\n }\n\n /**\n * Mutates the key with a given optimistic value.\n * The mutated value is considered expired and will be\n * replaced immediatly if a refetch happens when expired\n * is true. If expired is false, the value expiration time\n * is added as if it was a valid data refetched. Alternatively\n * you can provide a Date to decide when the expiration happens.\n */\n async function mutate<T = unknown>(\n key: string,\n resolver: MutationValue<T>,\n options?: MutateOptions<T>\n ): Promise<T> {\n async function action(resolver: MutationValue<T>) {\n if (typeof resolver === 'function') {\n const fn = resolver as MutationFunction<T>\n const value = itemsCache.get(key)\n const item = (await value?.item) as T\n\n resolver = await fn(item, value?.expiresAt)\n }\n\n return resolver\n }\n\n const result = action(resolver)\n\n emit(key, 'mutating', result)\n\n const item = await result\n const expiresAt = new Date()\n\n expiresAt.setMilliseconds(expiresAt.getMilliseconds() + (options?.expiration?.(item) ?? 0))\n\n itemsCache.set(key, { item: result, expiresAt: expiresAt })\n\n emit(key, 'mutated', item)\n\n return item\n }\n\n /**\n * Returns the current snapshot of the given key.\n * If the item is not in the items cache, it will return `undefined`.\n */\n async function snapshot<T = unknown>(key: string): Promise<T | undefined> {\n return (await itemsCache.get(key)?.item) as T\n }\n\n /**\n * Determines if the given key is currently resolving.\n */\n function keys(type: CacheType = 'items'): readonly string[] {\n return Array.from(type === 'items' ? itemsCache.keys() : resolversCache.keys())\n }\n\n /**\n * Aborts the active resolvers on each key\n * by calling `.abort()` on the `AbortController`.\n * The fetcher is responsible for using the\n * `AbortSignal` to cancel the job.\n * If no keys are provided, all resolvers are aborted.\n */\n function abort(cacheKeys?: string | readonly string[], reason?: unknown): void {\n const resolverKeys =\n typeof cacheKeys === 'string' ? [cacheKeys] : (cacheKeys ?? keys('resolvers'))\n\n for (const key of resolverKeys) {\n const resolver = resolversCache.get(key)\n\n if (resolver !== undefined) {\n resolver.controller.abort(reason)\n resolversCache.delete(key)\n\n emit(key, 'aborted', reason)\n }\n }\n }\n\n /**\n * Forgets the given keys from the items cache.\n * Does not remove any resolvers.\n * If no keys are provided the items cache is cleared.\n */\n async function forget(cacheKeys?: string | readonly string[] | RegExp): Promise<void> {\n let itemKeys: readonly string[]\n\n if (typeof cacheKeys === 'string') {\n itemKeys = [cacheKeys]\n } else if (Array.isArray(cacheKeys)) {\n itemKeys = cacheKeys\n } else if (cacheKeys instanceof RegExp) {\n itemKeys = keys('items').filter((key) => key.match(cacheKeys))\n } else {\n itemKeys = keys('items')\n }\n\n for (const key of itemKeys) {\n const item = itemsCache.get(key)\n\n if (item !== undefined) {\n itemsCache.delete(key)\n emit(key, 'forgotten', await item.item)\n }\n }\n }\n\n /**\n * Hydrates the given keys on the cache\n * with the given value. Hydrate should only\n * be used when you want to populate the cache.\n * Please use mutate() in most cases unless you\n * know what you are doing.\n */\n function hydrate<T = unknown>(\n keys: string | readonly string[],\n item: T,\n options?: HydrateOptions<T>\n ): void {\n const expiresAt = new Date()\n const result = Promise.resolve(item)\n\n expiresAt.setMilliseconds(expiresAt.getMilliseconds() + (options?.expiration?.(item) ?? 0))\n\n for (const key of typeof keys === 'string' ? [keys] : keys) {\n itemsCache.set(key, { item: result, expiresAt: expiresAt })\n emit(key, 'hydrated', item)\n }\n }\n\n /**\n * Returns the expiration date of a given key item.\n * If the item is not in the cache, it will return `undefined`.\n */\n function expiration(key: string): Date | undefined {\n return itemsCache.get(key)?.expiresAt\n }\n\n /**\n * Fetches the key information using a fetcher.\n * The returned promise contains the result item.\n */\n function query<T = unknown>(key: string, options?: Options<T>): Promise<T> {\n /**\n * Stores the expiration time of an item.\n */\n const expiration = options?.expiration ?? instanceExpiration\n\n /**\n * Determines the fetcher function to use.\n */\n const fetcher = (options?.fetcher ?? instanceFetcher) as FetcherFunction<T>\n\n /**\n * Determines if we can return a sale item\n * If true, it will return the previous stale item\n * stored in the cache if it has expired. It will attempt\n * to revalidate it in the background. If false, the returned\n * promise will be the revalidation promise.\n */\n const stale = options?.stale ?? instanceStale\n\n /**\n * Removes the stored item if there is an error in the request.\n * By default, we don't remove the item upon failure, only the resolver\n * is removed from the cache.\n */\n const removeOnError = options?.removeOnError ?? instanceRemoveOnError\n\n /**\n * Determines if the result should be a fresh fetched\n * instance regardless of any cached value or its expiration time.\n */\n const fresh = options?.fresh ?? instanceOptions?.fresh\n\n // Force fetching of the data.\n function refetch(key: string): Promise<T> {\n // Check if there's a pending resolver for that data.\n const pending = resolversCache.get(key)\n\n if (pending !== undefined) {\n return pending.item as Promise<T>\n }\n\n // Create the abort controller that will be\n // called when a query is aborted.\n const controller = new AbortController()\n\n let trigger: TriggerFunction = undefined\n\n // Initiate the fetching request.\n const result = new Promise<T>(function (resolve, reject) {\n trigger = async function () {\n try {\n const result = fetcher(key, { signal: controller.signal })\n\n // Awaits the fetching to get the result item.\n const item = await result\n\n const promise =\n (resolversCache.get(key)?.item as Promise<T> | undefined) ?? Promise.resolve(item)\n\n // Removes the resolver from the cache.\n resolversCache.delete(key)\n\n // Create the expiration time for the item.\n const expiresAt = new Date()\n expiresAt.setMilliseconds(expiresAt.getMilliseconds() + expiration(item))\n\n // Set the item to the cache.\n itemsCache.set(key, { item: promise, expiresAt })\n\n // Notify of the resolved item.\n emit(key, 'resolved', item)\n\n resolve(item)\n } catch (error) {\n // Remove the resolver.\n resolversCache.delete(key)\n\n // Check if the item should be removed as well.\n if (removeOnError) {\n itemsCache.delete(key)\n }\n\n // Notify of the error.\n emit(key, 'error', error)\n\n // Throw back the error.\n reject(error as Error)\n }\n }\n })\n\n // Adds the resolver to the cache.\n resolversCache.set(key, { item: result, controller })\n emit(key, 'refetching', result)\n\n // The promise executor runs synchronously,\n // so trigger is guaranteed to be defined here.\n void trigger!()\n\n return result\n }\n\n // We want to force a fresh item ignoring any current cached\n // value or its expiration time.\n if (fresh) {\n return refetch(key)\n }\n\n // Check if there's an item in the cache for the given key.\n const cached = itemsCache.get(key)\n\n if (cached === undefined) {\n // The item is not found in the items cache.\n // We need to perform a revalidation of the item.\n return refetch(key)\n }\n\n // We must check if that item has actually expired.\n // to trigger a revalidation if needed.\n const hasExpired = cached.expiresAt <= new Date()\n\n // The item has expired and the fetch is able\n // to return a stale item while revalidating\n // in the background.\n if (hasExpired && stale) {\n // We have to silence the error to avoid unhandled promises.\n // Refer to the error event if you need full controll of errors.\n refetch(key).catch(() => {})\n\n return cached.item as Promise<T>\n }\n\n // The item has expired but we dont allow stale\n // responses so we need to wait for the revalidation.\n if (hasExpired) {\n return refetch(key)\n }\n\n // The item has not yet expired, so we can return it and\n // assume it's valid since it's not yet considered stale.\n return cached.item as Promise<T>\n }\n\n /**\n * Returns the current cache instances.\n */\n function caches(): Caches {\n return { items: itemsCache, resolvers: resolversCache }\n }\n\n /**\n * Returns the event system.\n */\n function localEvents() {\n return events\n }\n\n /**\n * Returns the broadcast channel.\n */\n function localBroadcast() {\n return broadcast\n }\n\n /**\n * Subscribes to the broadcast channel\n * to listen for other browser context\n * events and reproduce them in the current\n * context.\n */\n function subscribeBroadcast(): Unsubscriber {\n function onBroadcastMessage(message: MessageEvent<BroadcastPayload>) {\n events.dispatchEvent(new CustomEvent(message.data.event, { detail: message.data.detail }))\n }\n\n broadcast?.addEventListener('message', onBroadcastMessage)\n\n return function () {\n broadcast?.removeEventListener('message', onBroadcastMessage)\n }\n }\n\n /**\n * Waits for the next refetching event on one or more keys and returns\n * the resolved values. Useful for synchronizing with query updates.\n *\n * @param keys - A single key or an object mapping property names to keys.\n * @returns A promise that resolves with the fetched value(s).\n */\n async function next<T = unknown>(keys: string | { [K in keyof T]: string }): Promise<T> {\n const iterator = (Array.isArray(keys) ? keys : [keys]) as readonly string[]\n const promises = iterator.map((key) => once(key, 'refetching'))\n const events = await Promise.all(promises)\n const details = events.map((event) => event.detail as Promise<T>)\n\n return (await (Array.isArray(keys) ? Promise.all(details) : details[0])) as T\n }\n\n /**\n * Returns an async generator that yields resolved values as they come in\n * for the specified key(s). Allows continuous streaming of query results.\n *\n * @param keys - A single key or an object mapping property names to keys.\n * @yields The resolved value(s) each time a refetch completes.\n */\n async function* stream<T = unknown>(keys: string | { [K in keyof T]: string }) {\n for (;;) {\n yield await next<T>(keys)\n }\n }\n\n /**\n * Returns the first occurrence of a specific event for a given key.\n * Subscribes to the event and automatically unsubscribes after receiving it.\n *\n * @param key - The cache key to listen for events on.\n * @param event - The type of event to wait for.\n * @returns A promise that resolves with the event details.\n */\n function once<T = unknown>(key: string, event: QueryEvent) {\n return new Promise<CustomEventInit<T>>(function (resolve) {\n const unsubscribe = subscribe<T>(key, event, function (event) {\n resolve(event)\n unsubscribe()\n })\n })\n }\n\n /**\n * Returns an async generator that yields event details each time the\n * specified event occurs for a given key. Allows iteration over a\n * continuous sequence of events.\n *\n * @param key - The cache key to listen for events on.\n * @param event - The type of event to stream.\n * @yields The event details each time the event occurs.\n */\n async function* sequence<T = unknown>(key: string, event: QueryEvent) {\n for (;;) {\n yield await once<T>(key, event)\n }\n }\n\n return {\n query,\n emit,\n subscribe,\n subscribeBroadcast,\n mutate,\n configure,\n abort,\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Q,MAAO,MAAM,QAAQ,EAAK,CAAG,QAAQ,IAAI,EAAQ,CAAG,EAAQ,IAUtE,eAAgB,OAAoB,EAA2C,CAC7E,OACE,MAAM,MAAM,KAAQ,EAAK,CAY7B,SAAS,KAAkB,EAAa,EAAmB,CACzD,OAAO,IAAI,QAA4B,SAAU,EAAS,CACxD,IAAM,EAAc,UAAa,EAAK,EAAO,SAAU,EAAO,CAC5D,EAAQ,EAAM,CACd,GAAa,EACb,EACF,CAYJ,eAAgB,SAAsB,EAAa,EAAmB,CACpE,OACE,MAAM,MAAM,KAAQ,EAAK,EAAM,CAInC,MAAO,CACL,MACA,KACA,UACA,mBACA,OACA,UACA,MACA,OACA,KACA,WACA,QACA,SACA,KACA,SACA,KACA,OACA,OACA,OAAQ,YACR,UAAW,eACZ"}
|
package/dist/query.cjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
//# sourceMappingURL=query.cjs.map
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./query-Do4OvbxG.cjs`);exports.createQuery=e.t,exports.defaultFetcher=e.n;
|
package/dist/query.js
CHANGED
|
@@ -1,193 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
function k(c) {
|
|
4
|
-
return async function(h, { signal: i }) {
|
|
5
|
-
const o = await c(h, { signal: i });
|
|
6
|
-
if (!o.ok)
|
|
7
|
-
throw new Error("Unable to fetch the data: " + o.statusText);
|
|
8
|
-
return await o.json();
|
|
9
|
-
};
|
|
10
|
-
}
|
|
11
|
-
r(k, "defaultFetcher");
|
|
12
|
-
function te(c) {
|
|
13
|
-
function h() {
|
|
14
|
-
return 2e3;
|
|
15
|
-
}
|
|
16
|
-
r(h, "defaultExpiration");
|
|
17
|
-
let i = c?.itemsCache ?? /* @__PURE__ */ new Map(), o = c?.resolversCache ?? /* @__PURE__ */ new Map(), m = c?.events ?? new EventTarget(), v = c?.broadcast, p = c?.expiration ?? h, M = c?.fetcher ?? k(fetch), C = c?.stale ?? !0, $ = c?.removeOnError ?? !1, B = c?.fresh ?? !1;
|
|
18
|
-
function j(e) {
|
|
19
|
-
i = e?.itemsCache ?? i, o = e?.resolversCache ?? o, m = e?.events ?? m, v = e?.broadcast ?? v, p = e?.expiration ?? p, M = e?.fetcher ?? M, C = e?.stale ?? C, $ = e?.removeOnError ?? $, B = e?.fresh ?? B;
|
|
20
|
-
}
|
|
21
|
-
r(j, "configure");
|
|
22
|
-
function l(e, t, n) {
|
|
23
|
-
switch (m.dispatchEvent(new CustomEvent(`${t}:${e}`, { detail: n })), t) {
|
|
24
|
-
case "mutated":
|
|
25
|
-
case "resolved":
|
|
26
|
-
case "hydrated":
|
|
27
|
-
case "forgotten":
|
|
28
|
-
v?.postMessage({ event: `${t}:${e}`, detail: n });
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
r(l, "emit");
|
|
32
|
-
function F(e, t, n) {
|
|
33
|
-
m.addEventListener(`${t}:${e}`, n);
|
|
34
|
-
const s = o.get(e);
|
|
35
|
-
return t === "refetching" && s !== void 0 && l(e, t, s.item), function() {
|
|
36
|
-
m.removeEventListener(`${t}:${e}`, n);
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
r(F, "subscribe");
|
|
40
|
-
async function Q(e, t, n) {
|
|
41
|
-
async function s(d) {
|
|
42
|
-
if (typeof d == "function") {
|
|
43
|
-
const g = d, x = i.get(e), f = await x?.item;
|
|
44
|
-
d = await g(f, x?.expiresAt);
|
|
45
|
-
}
|
|
46
|
-
return d;
|
|
47
|
-
}
|
|
48
|
-
r(s, "action");
|
|
49
|
-
const a = s(t);
|
|
50
|
-
l(e, "mutating", a);
|
|
51
|
-
const u = await a, w = /* @__PURE__ */ new Date();
|
|
52
|
-
return w.setMilliseconds(w.getMilliseconds() + (n?.expiration?.(u) ?? 0)), i.set(e, { item: a, expiresAt: w }), l(e, "mutated", u), u;
|
|
53
|
-
}
|
|
54
|
-
r(Q, "mutate");
|
|
55
|
-
async function S(e) {
|
|
56
|
-
return await i.get(e)?.item;
|
|
57
|
-
}
|
|
58
|
-
r(S, "snapshot");
|
|
59
|
-
function E(e = "items") {
|
|
60
|
-
return Array.from(e === "items" ? i.keys() : o.keys());
|
|
61
|
-
}
|
|
62
|
-
r(E, "keys");
|
|
63
|
-
function U(e, t) {
|
|
64
|
-
const n = typeof e == "string" ? [e] : e ?? E("resolvers");
|
|
65
|
-
for (const s of n) {
|
|
66
|
-
const a = o.get(s);
|
|
67
|
-
a !== void 0 && (a.controller.abort(t), o.delete(s), l(s, "aborted", t));
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
r(U, "abort");
|
|
71
|
-
async function z(e) {
|
|
72
|
-
let t;
|
|
73
|
-
typeof e == "string" ? t = [e] : Array.isArray(e) ? t = e : e instanceof RegExp ? t = E("items").filter((n) => n.match(e)) : t = E("items");
|
|
74
|
-
for (const n of t) {
|
|
75
|
-
const s = i.get(n);
|
|
76
|
-
s !== void 0 && (i.delete(n), l(n, "forgotten", await s.item));
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
r(z, "forget");
|
|
80
|
-
function G(e, t, n) {
|
|
81
|
-
const s = /* @__PURE__ */ new Date(), a = Promise.resolve(t);
|
|
82
|
-
s.setMilliseconds(s.getMilliseconds() + (n?.expiration?.(t) ?? 0));
|
|
83
|
-
for (const u of typeof e == "string" ? [e] : e)
|
|
84
|
-
i.set(u, { item: a, expiresAt: s }), l(u, "hydrated", t);
|
|
85
|
-
}
|
|
86
|
-
r(G, "hydrate");
|
|
87
|
-
function H(e) {
|
|
88
|
-
return i.get(e)?.expiresAt;
|
|
89
|
-
}
|
|
90
|
-
r(H, "expiration");
|
|
91
|
-
function I(e, t) {
|
|
92
|
-
const n = t?.expiration ?? p, s = t?.fetcher ?? M, a = t?.stale ?? C, u = t?.removeOnError ?? $, w = t?.fresh ?? c?.fresh;
|
|
93
|
-
function d(f) {
|
|
94
|
-
const R = o.get(f);
|
|
95
|
-
if (R !== void 0)
|
|
96
|
-
return R.item;
|
|
97
|
-
const T = new AbortController();
|
|
98
|
-
let b;
|
|
99
|
-
const D = new Promise(function(Z, _) {
|
|
100
|
-
b = /* @__PURE__ */ r(async function() {
|
|
101
|
-
try {
|
|
102
|
-
const A = await s(f, { signal: T.signal }), O = o.get(f)?.item ?? Promise.resolve(A);
|
|
103
|
-
o.delete(f);
|
|
104
|
-
const y = /* @__PURE__ */ new Date();
|
|
105
|
-
y.setMilliseconds(y.getMilliseconds() + n(A)), i.set(f, { item: O, expiresAt: y }), l(f, "resolved", A), Z(A);
|
|
106
|
-
} catch (L) {
|
|
107
|
-
o.delete(f), u && i.delete(f), l(f, "error", L), _(L);
|
|
108
|
-
}
|
|
109
|
-
}, "trigger");
|
|
110
|
-
});
|
|
111
|
-
return o.set(f, { item: D, controller: T }), l(f, "refetching", D), b = b, b(), D;
|
|
112
|
-
}
|
|
113
|
-
if (r(d, "refetch"), w)
|
|
114
|
-
return d(e);
|
|
115
|
-
const g = i.get(e);
|
|
116
|
-
if (g === void 0)
|
|
117
|
-
return d(e);
|
|
118
|
-
const x = g.expiresAt <= /* @__PURE__ */ new Date();
|
|
119
|
-
return x && a ? (d(e).catch(() => {
|
|
120
|
-
}), g.item) : x ? d(e) : g.item;
|
|
121
|
-
}
|
|
122
|
-
r(I, "query");
|
|
123
|
-
function J() {
|
|
124
|
-
return { items: i, resolvers: o };
|
|
125
|
-
}
|
|
126
|
-
r(J, "caches");
|
|
127
|
-
function N() {
|
|
128
|
-
return m;
|
|
129
|
-
}
|
|
130
|
-
r(N, "localEvents");
|
|
131
|
-
function V() {
|
|
132
|
-
return v;
|
|
133
|
-
}
|
|
134
|
-
r(V, "localBroadcast");
|
|
135
|
-
function W() {
|
|
136
|
-
function e(t) {
|
|
137
|
-
m.dispatchEvent(new CustomEvent(t.data.event, { detail: t.data.detail }));
|
|
138
|
-
}
|
|
139
|
-
return r(e, "onBroadcastMessage"), v?.addEventListener("message", e), function() {
|
|
140
|
-
v?.removeEventListener("message", e);
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
r(W, "subscribeBroadcast");
|
|
144
|
-
async function q(e) {
|
|
145
|
-
const n = (Array.isArray(e) ? e : [e]).map((u) => P(u, "refetching")), a = (await Promise.all(n)).map((u) => u.detail);
|
|
146
|
-
return await (Array.isArray(e) ? Promise.all(a) : a[0]);
|
|
147
|
-
}
|
|
148
|
-
r(q, "next");
|
|
149
|
-
async function* X(e) {
|
|
150
|
-
for (; ; )
|
|
151
|
-
yield await q(e);
|
|
152
|
-
}
|
|
153
|
-
r(X, "stream");
|
|
154
|
-
function P(e, t) {
|
|
155
|
-
return new Promise(function(n) {
|
|
156
|
-
const s = F(e, t, function(a) {
|
|
157
|
-
n(a), s();
|
|
158
|
-
});
|
|
159
|
-
});
|
|
160
|
-
}
|
|
161
|
-
r(P, "once");
|
|
162
|
-
async function* Y(e, t) {
|
|
163
|
-
for (; ; )
|
|
164
|
-
yield await P(e, t);
|
|
165
|
-
}
|
|
166
|
-
return r(Y, "sequence"), {
|
|
167
|
-
query: I,
|
|
168
|
-
emit: l,
|
|
169
|
-
subscribe: F,
|
|
170
|
-
subscribeBroadcast: W,
|
|
171
|
-
mutate: Q,
|
|
172
|
-
configure: j,
|
|
173
|
-
abort: U,
|
|
174
|
-
forget: z,
|
|
175
|
-
keys: E,
|
|
176
|
-
expiration: H,
|
|
177
|
-
hydrate: G,
|
|
178
|
-
snapshot: S,
|
|
179
|
-
once: P,
|
|
180
|
-
sequence: Y,
|
|
181
|
-
next: q,
|
|
182
|
-
stream: X,
|
|
183
|
-
caches: J,
|
|
184
|
-
events: N,
|
|
185
|
-
broadcast: V
|
|
186
|
-
};
|
|
187
|
-
}
|
|
188
|
-
r(te, "createQuery");
|
|
189
|
-
export {
|
|
190
|
-
te as createQuery,
|
|
191
|
-
k as defaultFetcher
|
|
192
|
-
};
|
|
193
|
-
//# sourceMappingURL=query.js.map
|
|
1
|
+
import { n as e, t } from "./query-CGIqlfYX.js";
|
|
2
|
+
export { t as createQuery, e as defaultFetcher };
|
package/dist/query_react.cjs
CHANGED
|
@@ -1,22 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
* @license React
|
|
3
|
-
* react-compiler-runtime.production.js
|
|
4
|
-
*
|
|
5
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
6
|
-
*
|
|
7
|
-
* This source code is licensed under the MIT license found in the
|
|
8
|
-
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var $;function ie(){if($)return w;$=1;var t=o.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;return w.c=function(e){return t.H.useMemoCache(e)},w}s(ie,"requireReactCompilerRuntime_production");var F={};/**
|
|
10
|
-
* @license React
|
|
11
|
-
* react-compiler-runtime.development.js
|
|
12
|
-
*
|
|
13
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
14
|
-
*
|
|
15
|
-
* This source code is licensed under the MIT license found in the
|
|
16
|
-
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var j;function ce(){return j||(j=1,process.env.NODE_ENV!=="production"&&(function(){var t=o.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;F.c=function(e){var r=t.H;return r===null&&console.error(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./query-Do4OvbxG.cjs`);let t=require(`react`),n=require(`react/jsx-runtime`);var r=(0,t.createContext)({query:void 0,clearOnForget:void 0,ignoreTransitionContext:void 0});function useQueryContext(){return(0,t.use)(r)}var i=Error(`No query instance was found. Please provide one via the resource options or the query context.`);function useQueryInstance(e){let{query:t}=useQueryContext(),{query:n}=e??{},r=n??t;if(!r)throw i;return r}function useQueryActions(e,t){let{expiration:n,fetcher:r,stale:i,removeOnError:a,fresh:o}=t??{},{query:s,mutate:c,forget:l}=useQueryInstance(t);function refetch(t){return s(e,{stale:i??!1,expiration:n,fetcher:r,removeOnError:a,fresh:o,...t})}function localMutate(t,n){return c(e,t,n)}async function localForget(){await l(e)}return{refetch,mutate:localMutate,forget:localForget}}function useQueryStatus(e,n){let{expiration:r,subscribe:i}=useQueryInstance(n),[a,o]=(0,t.useState)(()=>r(e)??new Date),[s,c]=(0,t.useState)(()=>Date.now()>a.getTime()),[l,u]=(0,t.useState)(!1),[d,f]=(0,t.useState)(!1);return(0,t.useEffect)(function(){function handler(){c(!0)}let e=setTimeout(handler,a.getTime()-Date.now());return function(){clearTimeout(e)}},[a]),(0,t.useEffect)(function(){function onMutating(){f(!0)}function onMutated(){f(!1),o(r(e)??new Date)}function onHydrated(){o(r(e)??new Date)}function onResolved(){o(r(e)??new Date),u(!1)}function onForgotten(){o(r(e)??new Date)}function onRefetching(){u(!0)}function onError(){u(!1),f(!1)}let t=i(e,`mutating`,onMutating),n=i(e,`mutated`,onMutated),a=i(e,`hydrated`,onHydrated),s=i(e,`resolved`,onResolved),c=i(e,`forgotten`,onForgotten),l=i(e,`refetching`,onRefetching),d=i(e,`error`,onError);return function(){t(),n(),a(),s(),c(),l(),d()}},[e,i,r]),{expiresAt:a,isExpired:s,isRefetching:l,isMutating:d}}var a=(0,t.createContext)({isPending:void 0,startTransition:void 0});function useQueryTransitionContext(){return(0,t.use)(a)}function useQueryBasic(e,n){let{clearOnForget:r,ignoreTransitionContext:i}=useQueryContext(),{clearOnForget:a,ignoreTransitionContext:o,expiration:s,fetcher:c,stale:l,removeOnError:u,fresh:d}=n??{},{isPending:f,startTransition:p}=useQueryTransitionContext(),[m,h]=(0,t.useTransition)(),{query:g,subscribe:_}=useQueryInstance(n),v=o??i??!1,y=v?m:f??m,b=v?h:p??h,x=a??r??!1,[S,C]=(0,t.useState)((0,t.use)(g(e,{expiration:s,fetcher:c,stale:l,removeOnError:u,fresh:d}))),w=(0,t.useEffectEvent)(function(e){b(function(){C(e.detail)})}),T=(0,t.useEffectEvent)(function(e){b(async function(){let t=await e.detail;b(function(){C(t)})})}),E=(0,t.useEffectEvent)(function(e){b(function(){C(e.detail)})}),D=(0,t.useEffectEvent)(function(e){b(function(){C(e.detail)})}),O=(0,t.useEffectEvent)(function(e){b(async function(){let t=await e.detail;b(function(){C(t)})})}),k=(0,t.useEffectEvent)(function(){x&&b(async function(){let t=await g(e,{expiration:s,fetcher:c,stale:l,removeOnError:u,fresh:d});b(function(){C(t)})})});return(0,t.useEffect)(function(){let t=_(e,`resolved`,w),n=_(e,`mutating`,T),r=_(e,`mutated`,E),i=_(e,`hydrated`,D),a=_(e,`refetching`,O),o=_(e,`forgotten`,k);return function(){t(),n(),r(),i(),a(),o()}},[e,_]),{data:S,isPending:y}}function useQuery(e,t){let n=useQueryBasic(e,t),r=useQueryActions(e,t),i=useQueryStatus(e,t);return{...n,...r,...i}}function useQueryPrefetch(e,n){let{query:r}=useQueryInstance(n);(0,t.useEffect)(function(){for(let t of e)r(t)},[r,e])}var o=e.r((e=>{var t=require(`react`).__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;e.c=function(e){return t.H.useMemoCache(e)}})),s=e.r((e=>{process.env.NODE_ENV!==`production`&&(function(){var t=require(`react`).__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;e.c=function(e){var n=t.H;return n===null&&console.error(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
|
|
18
2
|
1. You might have mismatching versions of React and the renderer (such as React DOM)
|
|
19
3
|
2. You might be breaking the Rules of Hooks
|
|
20
4
|
3. You might have more than one copy of React in the same app
|
|
21
|
-
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`),
|
|
22
|
-
//# sourceMappingURL=query_react.cjs.map
|
|
5
|
+
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`),n.useMemoCache(e)}})()})),c=e.r(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=o():t.exports=s()}))();function QueryProvider(i){let a=(0,c.c)(12),{children:o,clearOnForget:s,ignoreTransitionContext:l,query:u}=i,d;a[0]===u?d=a[1]:(d=u??e.t(),a[0]=u,a[1]=d);let f=d,t2,p;a[2]===f?(t2=a[3],p=a[4]):(t2=function(){let e=new BroadcastChannel(`query`);f.configure({broadcast:e});let t=f.subscribeBroadcast();return function(){t(),e.close()}},p=[f],a[2]=f,a[3]=t2,a[4]=p),(0,t.useEffect)(t2,p);let m;a[5]!==s||a[6]!==l||a[7]!==f?(m={query:f,clearOnForget:s,ignoreTransitionContext:l},a[5]=s,a[6]=l,a[7]=f,a[8]=m):m=a[8];let h=m,g;return a[9]!==o||a[10]!==h?(g=(0,n.jsx)(r,{value:h,children:o}),a[9]=o,a[10]=h,a[11]=g):g=a[11],g}function QueryTransition(e){let t=(0,c.c)(6),{children:r,startTransition:i,isPending:o}=e,s;t[0]!==o||t[1]!==i?(s={startTransition:i,isPending:o},t[0]=o,t[1]=i,t[2]=s):s=t[2];let l=s,u;return t[3]!==r||t[4]!==l?(u=(0,n.jsx)(a,{value:l,children:r}),t[3]=r,t[4]=l,t[5]=u):u=t[5],u}function QueryPrefetch(e){let t=(0,c.c)(2),{keys:n,query:r,children:i}=e,a;return t[0]===r?a=t[1]:(a={query:r},t[0]=r,t[1]=a),useQueryPrefetch(n,a),i}function QueryPrefetchTags(e){let t=(0,c.c)(12),r,i,a;t[0]===e?(r=t[1],i=t[2],a=t[3]):({keys:i,children:r,...a}=e,t[0]=e,t[1]=r,t[2]=i,t[3]=a),useQueryPrefetch(i,a);let o;if(t[4]!==i||t[5]!==a){let t2;t[7]===a?t2=t[8]:(t2=e=>(0,n.jsx)(`link`,{rel:`preload`,href:e,as:`fetch`,...a},e),t[7]=a,t[8]=t2),o=i.map(t2),t[4]=i,t[5]=a,t[6]=o}else o=t[6];let s=o,l;return t[9]!==r||t[10]!==s?(l=(0,n.jsxs)(n.Fragment,{children:[s,r]}),t[9]=r,t[10]=s,t[11]=l):l=t[11],l}exports.Context=r,exports.ErrNoQueryInstanceFound=i,exports.QueryPrefetch=QueryPrefetch,exports.QueryPrefetchTags=QueryPrefetchTags,exports.QueryProvider=QueryProvider,exports.QueryTransition=QueryTransition,exports.TransitionContext=a,exports.useQuery=useQuery,exports.useQueryActions=useQueryActions,exports.useQueryBasic=useQueryBasic,exports.useQueryContext=useQueryContext,exports.useQueryInstance=useQueryInstance,exports.useQueryPrefetch=useQueryPrefetch,exports.useQueryStatus=useQueryStatus,exports.useQueryTransitionContext=useQueryTransitionContext;
|
|
6
|
+
//# sourceMappingURL=query_react.cjs.map
|