@studiolambda/query 1.0.0
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/LICENSE +21 -0
- package/README.md +15 -0
- package/dist/query.cjs +2 -0
- package/dist/query.cjs.map +1 -0
- package/dist/query.js +144 -0
- package/dist/query.js.map +1 -0
- package/dist/query_react.cjs +2 -0
- package/dist/query_react.cjs.map +1 -0
- package/dist/query_react.js +254 -0
- package/dist/query_react.js.map +1 -0
- package/dist/src/query/index.d.ts +299 -0
- package/dist/src/react/components/QueryProvider.d.ts +9 -0
- package/dist/src/react/components/QueryTransition.d.ts +7 -0
- package/dist/src/react/context.d.ts +10 -0
- package/dist/src/react/hooks/useQuery.d.ts +13 -0
- package/dist/src/react/hooks/useQueryActions.d.ts +9 -0
- package/dist/src/react/hooks/useQueryContext.d.ts +2 -0
- package/dist/src/react/hooks/useQueryInstance.d.ts +5 -0
- package/dist/src/react/hooks/useQueryStatus.d.ts +7 -0
- package/dist/src/react/hooks/useQueryTransitionContext.d.ts +2 -0
- package/dist/src/react/index.d.ts +10 -0
- package/dist/src/react/transition.d.ts +6 -0
- package/package.json +84 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Erik C. Forés
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Lambda Query
|
|
2
|
+
|
|
3
|
+
> Lightweight asynchronous data management
|
|
4
|
+
|
|
5
|
+
Lambda Query is a library created to manage asynchronous data on your code. This is generally used when you have to fetch data asynchronously for a given resource. Lambda Query allows you to manage this data by using an internal cache. It is very similar to how vercel's swr work. Lambda Query is also build to support arbitrary cache and event system, making it possible to create your own implementations.
|
|
6
|
+
|
|
7
|
+
## Documentation
|
|
8
|
+
|
|
9
|
+
Find out about the project and discover the features at the [Documentation](https://erik.cat/blog/query-docs/)
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
npm i @studiolambda/query
|
|
15
|
+
```
|
package/dist/query.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function R(t){return async function(C,{signal:d}){const c=await t(C,{signal:d});if(!c.ok)throw new Error("Unable to fetch the data: "+c.statusText);return await c.json()}}function Z(t){function C(){return 2e3}let d=(t==null?void 0:t.itemsCache)??new Map,c=(t==null?void 0:t.resolversCache)??new Map,v=(t==null?void 0:t.events)??new EventTarget,l=t==null?void 0:t.broadcast,M=(t==null?void 0:t.expiration)??C,A=(t==null?void 0:t.fetcher)??R(fetch),D=(t==null?void 0:t.stale)??!0,F=(t==null?void 0:t.removeOnError)??!1,j=(t==null?void 0:t.fresh)??!1;function q(e){d=(e==null?void 0:e.itemsCache)??d,c=(e==null?void 0:e.resolversCache)??c,v=(e==null?void 0:e.events)??v,l=(e==null?void 0:e.broadcast)??l,M=(e==null?void 0:e.expiration)??M,A=(e==null?void 0:e.fetcher)??A,D=(e==null?void 0:e.stale)??D,F=(e==null?void 0:e.removeOnError)??F,j=(e==null?void 0:e.fresh)??j}function P(e,r,f){v.addEventListener(`${r}:${e}`,f);const u=c.get(e);return r==="refetching"&&u!==void 0&&f(new CustomEvent(`${r}:${e}`,{detail:u.item})),function(){v.removeEventListener(`${r}:${e}`,f)}}async function U(e,r,f){async function u(E){var $;if(typeof E=="function"){const a=E,m=d.get(e);E=await a(m==null?void 0:m.item,m==null?void 0:m.expiresAt)}const w=new Date;return w.setMilliseconds(w.getMilliseconds()+((($=f==null?void 0:f.expiration)==null?void 0:$.call(f,E))??0)),d.set(e,{item:E,expiresAt:w}),E}const h=u(r);v.dispatchEvent(new CustomEvent(`mutating:${e}`,{detail:h}));const g=await h;return v.dispatchEvent(new CustomEvent(`mutated:${e}`,{detail:g})),l==null||l.postMessage({event:`mutated:${e}`,detail:g}),g}function b(e){var r;return(r=d.get(e))==null?void 0:r.item}function x(e="items"){return Array.from(e==="items"?d.keys():c.keys())}function z(e,r){const f=typeof e=="string"?[e]:e??x("resolvers");for(const u of f){const h=c.get(u);h!==void 0&&(h.controller.abort(r),c.delete(u),v.dispatchEvent(new CustomEvent(`aborted:${u}`,{detail:r})),l==null||l.postMessage({event:`aborted:${u}`,detail:r}))}}function G(e){let r;typeof e=="string"?r=[e]:Array.isArray(e)?r=e:e instanceof RegExp?r=x("items").filter(f=>f.match(e)):r=x("items");for(const f of r){const u=d.get(f);u!==void 0&&(d.delete(f),v.dispatchEvent(new CustomEvent(`forgotten:${f}`,{detail:u.item})),l==null||l.postMessage({event:`forgotten:${f}`,detail:u.item}))}}function H(e,r,f){var h;const u=new Date;u.setMilliseconds(u.getMilliseconds()+(((h=f==null?void 0:f.expiration)==null?void 0:h.call(f,r))??0));for(const g of typeof e=="string"?[e]:e)d.set(g,{item:r,expiresAt:u}),v.dispatchEvent(new CustomEvent(`hydrated:${g}`,{detail:r})),l==null||l.postMessage({event:`hydrated:${g}`,detail:r})}function I(e){var r;return(r=d.get(e))==null?void 0:r.expiresAt}async function J(e,r){const f=(r==null?void 0:r.expiration)??M,u=(r==null?void 0:r.fetcher)??A,h=(r==null?void 0:r.stale)??D,g=(r==null?void 0:r.removeOnError)??F,E=(r==null?void 0:r.fresh)??(t==null?void 0:t.fresh);async function w(a){try{const m=c.get(a);if(m!==void 0)return await m.item;const Q=new AbortController;async function Y(){const S=await u(a,{signal:Q.signal});c.delete(a);const T=new Date;return T.setMilliseconds(T.getMilliseconds()+f(S)),d.set(a,{item:S,expiresAt:T}),S}const L=Y();c.set(a,{item:L,controller:Q}),v.dispatchEvent(new CustomEvent(`refetching:${a}`,{detail:L}));const B=await L;return v.dispatchEvent(new CustomEvent(`resolved:${a}`,{detail:B})),l==null||l.postMessage({event:`resolved:${a}`,detail:B}),B}catch(m){throw c.delete(a),g&&d.delete(a),v.dispatchEvent(new CustomEvent(`error:${a}`,{detail:m})),l==null||l.postMessage({event:`error:${a}`,detail:m}),m}}if(E)return await w(e);const $=d.get(e);if($!==void 0){const a=$.expiresAt<=new Date;return a&&h?(w(e).catch(()=>{}),$.item):a?await w(e):$.item}return await w(e)}function N(){return{items:d,resolvers:c}}function V(){return v}function W(){return l}function X(){function e(r){v.dispatchEvent(new CustomEvent(r.data.event,{detail:r.data.detail}))}return l==null||l.addEventListener("message",e),function(){l==null||l.removeEventListener("message",e)}}return{query:J,subscribe:P,subscribeBroadcast:X,mutate:U,configure:q,abort:z,forget:G,keys:x,expiration:I,hydrate:H,snapshot:b,caches:N,events:V,broadcast:W}}exports.createQuery=Z;exports.defaultFetcher=R;
|
|
2
|
+
//# sourceMappingURL=query.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query.cjs","sources":["../src/query/index.ts"],"sourcesContent":["/**\n * Determines the shape of the Cache instance.\n */\nexport interface Cache<T = unknown> {\n /**\n * Gets an item from the cache.\n */\n readonly get: (key: string) => T | undefined\n\n /**\n * Sets an item to the cache.\n */\n readonly set: (key: string, value: T) => void\n\n /**\n * Removes a key-value pair from the cache.\n */\n readonly delete: (key: string) => void\n\n /**\n * Returns the current cached keys.\n */\n readonly keys: () => IterableIterator<string>\n}\n\n/**\n * Determines how we store items in the items cache.\n */\ninterface ItemsCacheItem<T = unknown> {\n /**\n * Stores the cache item.\n */\n readonly item: T\n\n /**\n * Determines the expiration date of the item.\n */\n readonly expiresAt: Date\n}\n\n/**\n * Determines how we store items in the resolvers cache.\n */\ninterface ResolversCacheItem<T> {\n /**\n * The resolvable item.\n */\n readonly item: Promise<T>\n\n /**\n * The abort controller for the request.\n */\n readonly controller: AbortController\n}\n\n/**\n * Represents the available configuration options\n * for a query instance.\n */\nexport interface Configuration extends Options {\n /**\n * Determines the resolved items cache to use.\n */\n readonly itemsCache?: Cache<ItemsCacheItem>\n\n /**\n * Determines the resolvers cache to use.\n */\n readonly resolversCache?: Cache<ResolversCacheItem<unknown>>\n\n /**\n * Stores the event system.\n */\n readonly events?: 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 readonly broadcast?: BroadcastChannel\n}\n\nexport interface FetcherAdditional {\n /**\n * An abort signal to cancel pending queries.\n */\n readonly signal: AbortSignal\n}\n\n/**\n * The available options for query.\n */\nexport interface Options<T = unknown> {\n /**\n * Determines the item deduplication interval.\n * This determines how many milliseconds an item\n * is considered valid.\n */\n readonly expiration?: ExpirationFunction<T>\n\n /**\n * Determines the fetcher function to use.\n */\n readonly fetcher?: FetcherFunction<T>\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 readonly stale?: boolean\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 readonly removeOnError?: boolean\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 readonly fresh?: boolean\n}\n\n/**\n * Determines the cache type.\n */\nexport type CacheType = 'resolvers' | 'items'\n\n/**\n * The mutation function type.\n */\nexport interface MutationFunction<T> {\n (previous?: T, expiresAt?: Date): T | Promise<T>\n}\n\n/**\n * The available mutation values.\n */\nexport type MutationValue<T> = T | MutationFunction<T>\n\n/**\n * The function type for the event subscription.\n */\nexport interface SubscribeFunction {\n (key: string, event: QueryEvent, listener: EventListener): Unsubscriber\n}\n\n/**\n * The broadcast payload.\n */\nexport interface BroadcastPayload {\n /**\n * The event name.\n */\n readonly event: string\n\n /**\n * The event detail.\n */\n readonly detail: unknown\n}\n\n/**\n * The function type for the broadcast subscription.\n */\nexport interface SubscribeBroadcastFunction {\n (): Unsubscriber\n}\n\n/**\n * The query function type.\n */\nexport interface QueryFunction {\n <T = unknown>(key: string, options?: Options<T>): Promise<T>\n}\n\nexport interface ExpirationFunction<T = unknown> {\n (item: T): number\n}\n\nexport interface FetcherFunction<T = unknown> {\n (key: string, additional: FetcherAdditional): Promise<T>\n}\n\n/**\n * The mutate function options.\n */\nexport interface HydrateOptions<T = unknown> {\n expiration?: ExpirationFunction<T>\n}\n\n/**\n * The mutate function options.\n */\nexport interface MutateOptions<T = unknown> {\n expiration?: ExpirationFunction<T>\n}\n\n/**\n * The mutate function type.\n */\nexport interface MutateFunction {\n <T = unknown>(key: string, item: MutationValue<T>, options?: MutateOptions<T>): Promise<T>\n}\n\n/**\n * The hydrate function type.\n */\nexport interface HydrateFunction {\n <T = unknown>(keys: string | string[], item: T, options?: HydrateOptions<T>): void\n}\n\n/**\n * The unsubscriber function.\n */\nexport type Unsubscriber = () => void\n\n/**\n * The caches available on the query.\n */\nexport interface Caches {\n /**\n * A cache that contains the resolved items alongside\n * their expiration time.\n */\n readonly items: Cache<ItemsCacheItem>\n\n /**\n * A cache that contains the resolvers alongside\n * their abort controllers.\n */\n readonly resolvers: Cache<ResolversCacheItem<unknown>>\n}\n\n/**\n * Represents the methods a query\n * should implement.\n */\nexport interface Query {\n /**\n * Configures the current instance of query.\n */\n readonly configure: (options?: Partial<Configuration>) => void\n\n /**\n * Fetches the key information using a fetcher.\n * The returned promise contains the result item.\n */\n readonly query: QueryFunction\n\n /**\n * Subscribes to a given event & key. The event handler\n * does have a payload parameter that will contain relevant\n * information depending on the event type.\n */\n readonly subscribe: SubscribeFunction\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 readonly subscribeBroadcast: SubscribeBroadcastFunction\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.\n */\n readonly mutate: MutateFunction\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 */\n readonly abort: (key?: string | string[], reason?: unknown) => void\n\n /**\n * Forgets the given keys from the cache.\n * Removes items from both, the cache and resolvers.\n */\n readonly forget: (keys?: string | string[] | RegExp) => void\n\n /**\n * Hydrates the given keys on the cache\n * with the given value and expiration time.\n */\n readonly hydrate: HydrateFunction\n\n /**\n * Returns the given keys for the given cache.\n */\n readonly keys: (cache?: CacheType) => string[]\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 readonly expiration: (key: string) => Date | undefined\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 readonly snapshot: <T = unknown>(key: string) => T | undefined\n\n /**\n * Returns the current cache instances in use.\n */\n readonly caches: () => Caches\n\n /**\n * Returns the event system in use.\n */\n readonly events: () => EventTarget\n\n /**\n * Returns the broadcast channel in use.\n */\n readonly broadcast: () => BroadcastChannel | undefined\n}\n\n/**\n * Available events on query.\n */\nexport type QueryEvent =\n | 'refetching'\n | 'resolved'\n | 'mutating'\n | 'mutated'\n | 'aborted'\n | 'forgotten'\n | 'hydrated'\n | 'error'\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 =\n instanceOptions?.resolversCache ?? new Map<string, ResolversCacheItem<unknown>>()\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 * 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(key: string, event: QueryEvent, listener: EventListener): 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 listener(new CustomEvent(`${event}:${key}`, { detail: 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\n resolver = await fn(value?.item as T, value?.expiresAt)\n }\n\n const expiresAt = new Date()\n\n expiresAt.setMilliseconds(\n expiresAt.getMilliseconds() + (options?.expiration?.(resolver) ?? 0)\n )\n\n itemsCache.set(key, { item: resolver, expiresAt: expiresAt })\n\n return resolver\n }\n\n const result = action(resolver)\n\n events.dispatchEvent(new CustomEvent(`mutating:${key}`, { detail: result }))\n\n const item = await result\n\n events.dispatchEvent(new CustomEvent(`mutated:${key}`, { detail: item }))\n broadcast?.postMessage({ event: `mutated:${key}`, detail: 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 function snapshot<T = unknown>(key: string): T | undefined {\n return 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'): 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 | 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 events.dispatchEvent(new CustomEvent(`aborted:${key}`, { detail: reason }))\n broadcast?.postMessage({ event: `aborted:${key}`, detail: 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 function forget(cacheKeys?: string | string[] | RegExp): void {\n let itemKeys: 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 events.dispatchEvent(new CustomEvent(`forgotten:${key}`, { detail: item.item }))\n broadcast?.postMessage({ event: `forgotten:${key}`, detail: 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 | string[],\n item: T,\n options?: HydrateOptions<T>\n ): void {\n const expiresAt = new Date()\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, expiresAt: expiresAt })\n events.dispatchEvent(new CustomEvent(`hydrated:${key}`, { detail: item }))\n broadcast?.postMessage({ event: `hydrated:${key}`, detail: 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 async 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 async function refetch(key: string): Promise<T> {\n try {\n // Check if there's a pending resolver for that data.\n const pending = resolversCache.get(key)\n\n if (pending !== undefined) {\n return await (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 // Initiate the fetching request.\n async function action() {\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 // 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, expiresAt })\n\n return item\n }\n\n const result = action()\n\n // Adds the resolver to the cache.\n resolversCache.set(key, { item: result, controller })\n events.dispatchEvent(new CustomEvent(`refetching:${key}`, { detail: result }))\n\n const item = await result\n\n // Notify of the resolved item.\n events.dispatchEvent(new CustomEvent(`resolved:${key}`, { detail: item }))\n broadcast?.postMessage({ event: `resolved:${key}`, detail: item })\n\n // Return back the item.\n return 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 events.dispatchEvent(new CustomEvent(`error:${key}`, { detail: error }))\n broadcast?.postMessage({ event: `error:${key}`, detail: error })\n\n // Throw back the error.\n throw error\n }\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 await 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 // 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 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 await 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 T\n }\n\n // The item is not found in the items cache.\n // We need to perform a revalidation of the item.\n return await refetch(key)\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 return {\n query,\n subscribe,\n subscribeBroadcast,\n mutate,\n configure,\n abort,\n forget,\n keys,\n expiration,\n hydrate,\n snapshot,\n caches,\n events: localEvents,\n broadcast: localBroadcast,\n }\n}\n"],"names":["defaultFetcher","fetch","key","signal","response","createQuery","instanceOptions","defaultExpiration","itemsCache","resolversCache","events","broadcast","instanceExpiration","instanceFetcher","instanceStale","instanceRemoveOnError","instanceFresh","configure","options","subscribe","event","listener","value","mutate","resolver","action","fn","expiresAt","_a","result","item","snapshot","keys","type","abort","cacheKeys","reason","resolverKeys","forget","itemKeys","hydrate","expiration","query","fetcher","stale","removeOnError","fresh","refetch","pending","controller","error","cached","hasExpired","caches","localEvents","localBroadcast","subscribeBroadcast","onBroadcastMessage","message"],"mappings":"gFA+VO,SAASA,EACdC,EACoB,CACpB,OAAO,eAAgBC,EAAa,CAAE,OAAAC,GAAyC,CAC7E,MAAMC,EAAW,MAAMH,EAAMC,EAAK,CAAE,OAAAC,EAAQ,EAExC,GAAA,CAACC,EAAS,GACZ,MAAM,IAAI,MAAM,6BA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AS,EACA,QAAAD,EACA,SAAAT,EACA,OAAAsB,EACA,OAAQC,EACR,UAAWC,CACb,CACF"}
|
package/dist/query.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
function Z(t) {
|
|
2
|
+
return async function(C, { signal: d }) {
|
|
3
|
+
const v = await t(C, { signal: d });
|
|
4
|
+
if (!v.ok)
|
|
5
|
+
throw new Error("Unable to fetch the data: " + v.statusText);
|
|
6
|
+
return await v.json();
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
function b(t) {
|
|
10
|
+
function C() {
|
|
11
|
+
return 2e3;
|
|
12
|
+
}
|
|
13
|
+
let d = (t == null ? void 0 : t.itemsCache) ?? /* @__PURE__ */ new Map(), v = (t == null ? void 0 : t.resolversCache) ?? /* @__PURE__ */ new Map(), m = (t == null ? void 0 : t.events) ?? new EventTarget(), f = t == null ? void 0 : t.broadcast, M = (t == null ? void 0 : t.expiration) ?? C, A = (t == null ? void 0 : t.fetcher) ?? Z(fetch), D = (t == null ? void 0 : t.stale) ?? !0, L = (t == null ? void 0 : t.removeOnError) ?? !1, j = (t == null ? void 0 : t.fresh) ?? !1;
|
|
14
|
+
function Q(e) {
|
|
15
|
+
d = (e == null ? void 0 : e.itemsCache) ?? d, v = (e == null ? void 0 : e.resolversCache) ?? v, m = (e == null ? void 0 : e.events) ?? m, f = (e == null ? void 0 : e.broadcast) ?? f, M = (e == null ? void 0 : e.expiration) ?? M, A = (e == null ? void 0 : e.fetcher) ?? A, D = (e == null ? void 0 : e.stale) ?? D, L = (e == null ? void 0 : e.removeOnError) ?? L, j = (e == null ? void 0 : e.fresh) ?? j;
|
|
16
|
+
}
|
|
17
|
+
function S(e, r, l) {
|
|
18
|
+
m.addEventListener(`${r}:${e}`, l);
|
|
19
|
+
const u = v.get(e);
|
|
20
|
+
return r === "refetching" && u !== void 0 && l(new CustomEvent(`${r}:${e}`, { detail: u.item })), function() {
|
|
21
|
+
m.removeEventListener(`${r}:${e}`, l);
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
async function U(e, r, l) {
|
|
25
|
+
async function u(g) {
|
|
26
|
+
var $;
|
|
27
|
+
if (typeof g == "function") {
|
|
28
|
+
const a = g, c = d.get(e);
|
|
29
|
+
g = await a(c == null ? void 0 : c.item, c == null ? void 0 : c.expiresAt);
|
|
30
|
+
}
|
|
31
|
+
const w = /* @__PURE__ */ new Date();
|
|
32
|
+
return w.setMilliseconds(
|
|
33
|
+
w.getMilliseconds() + ((($ = l == null ? void 0 : l.expiration) == null ? void 0 : $.call(l, g)) ?? 0)
|
|
34
|
+
), d.set(e, { item: g, expiresAt: w }), g;
|
|
35
|
+
}
|
|
36
|
+
const h = u(r);
|
|
37
|
+
m.dispatchEvent(new CustomEvent(`mutating:${e}`, { detail: h }));
|
|
38
|
+
const E = await h;
|
|
39
|
+
return m.dispatchEvent(new CustomEvent(`mutated:${e}`, { detail: E })), f == null || f.postMessage({ event: `mutated:${e}`, detail: E }), E;
|
|
40
|
+
}
|
|
41
|
+
function z(e) {
|
|
42
|
+
var r;
|
|
43
|
+
return (r = d.get(e)) == null ? void 0 : r.item;
|
|
44
|
+
}
|
|
45
|
+
function x(e = "items") {
|
|
46
|
+
return Array.from(e === "items" ? d.keys() : v.keys());
|
|
47
|
+
}
|
|
48
|
+
function G(e, r) {
|
|
49
|
+
const l = typeof e == "string" ? [e] : e ?? x("resolvers");
|
|
50
|
+
for (const u of l) {
|
|
51
|
+
const h = v.get(u);
|
|
52
|
+
h !== void 0 && (h.controller.abort(r), v.delete(u), m.dispatchEvent(new CustomEvent(`aborted:${u}`, { detail: r })), f == null || f.postMessage({ event: `aborted:${u}`, detail: r }));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function H(e) {
|
|
56
|
+
let r;
|
|
57
|
+
typeof e == "string" ? r = [e] : Array.isArray(e) ? r = e : e instanceof RegExp ? r = x("items").filter((l) => l.match(e)) : r = x("items");
|
|
58
|
+
for (const l of r) {
|
|
59
|
+
const u = d.get(l);
|
|
60
|
+
u !== void 0 && (d.delete(l), m.dispatchEvent(new CustomEvent(`forgotten:${l}`, { detail: u.item })), f == null || f.postMessage({ event: `forgotten:${l}`, detail: u.item }));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function I(e, r, l) {
|
|
64
|
+
var h;
|
|
65
|
+
const u = /* @__PURE__ */ new Date();
|
|
66
|
+
u.setMilliseconds(u.getMilliseconds() + (((h = l == null ? void 0 : l.expiration) == null ? void 0 : h.call(l, r)) ?? 0));
|
|
67
|
+
for (const E of typeof e == "string" ? [e] : e)
|
|
68
|
+
d.set(E, { item: r, expiresAt: u }), m.dispatchEvent(new CustomEvent(`hydrated:${E}`, { detail: r })), f == null || f.postMessage({ event: `hydrated:${E}`, detail: r });
|
|
69
|
+
}
|
|
70
|
+
function J(e) {
|
|
71
|
+
var r;
|
|
72
|
+
return (r = d.get(e)) == null ? void 0 : r.expiresAt;
|
|
73
|
+
}
|
|
74
|
+
async function N(e, r) {
|
|
75
|
+
const l = (r == null ? void 0 : r.expiration) ?? M, u = (r == null ? void 0 : r.fetcher) ?? A, h = (r == null ? void 0 : r.stale) ?? D, E = (r == null ? void 0 : r.removeOnError) ?? L, g = (r == null ? void 0 : r.fresh) ?? (t == null ? void 0 : t.fresh);
|
|
76
|
+
async function w(a) {
|
|
77
|
+
try {
|
|
78
|
+
const c = v.get(a);
|
|
79
|
+
if (c !== void 0)
|
|
80
|
+
return await c.item;
|
|
81
|
+
const q = new AbortController();
|
|
82
|
+
async function Y() {
|
|
83
|
+
const R = await u(a, { signal: q.signal });
|
|
84
|
+
v.delete(a);
|
|
85
|
+
const T = /* @__PURE__ */ new Date();
|
|
86
|
+
return T.setMilliseconds(T.getMilliseconds() + l(R)), d.set(a, { item: R, expiresAt: T }), R;
|
|
87
|
+
}
|
|
88
|
+
const B = Y();
|
|
89
|
+
v.set(a, { item: B, controller: q }), m.dispatchEvent(new CustomEvent(`refetching:${a}`, { detail: B }));
|
|
90
|
+
const F = await B;
|
|
91
|
+
return m.dispatchEvent(new CustomEvent(`resolved:${a}`, { detail: F })), f == null || f.postMessage({ event: `resolved:${a}`, detail: F }), F;
|
|
92
|
+
} catch (c) {
|
|
93
|
+
throw v.delete(a), E && d.delete(a), m.dispatchEvent(new CustomEvent(`error:${a}`, { detail: c })), f == null || f.postMessage({ event: `error:${a}`, detail: c }), c;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (g)
|
|
97
|
+
return await w(e);
|
|
98
|
+
const $ = d.get(e);
|
|
99
|
+
if ($ !== void 0) {
|
|
100
|
+
const a = $.expiresAt <= /* @__PURE__ */ new Date();
|
|
101
|
+
return a && h ? (w(e).catch(() => {
|
|
102
|
+
}), $.item) : a ? await w(e) : $.item;
|
|
103
|
+
}
|
|
104
|
+
return await w(e);
|
|
105
|
+
}
|
|
106
|
+
function P() {
|
|
107
|
+
return { items: d, resolvers: v };
|
|
108
|
+
}
|
|
109
|
+
function V() {
|
|
110
|
+
return m;
|
|
111
|
+
}
|
|
112
|
+
function W() {
|
|
113
|
+
return f;
|
|
114
|
+
}
|
|
115
|
+
function X() {
|
|
116
|
+
function e(r) {
|
|
117
|
+
m.dispatchEvent(new CustomEvent(r.data.event, { detail: r.data.detail }));
|
|
118
|
+
}
|
|
119
|
+
return f == null || f.addEventListener("message", e), function() {
|
|
120
|
+
f == null || f.removeEventListener("message", e);
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
query: N,
|
|
125
|
+
subscribe: S,
|
|
126
|
+
subscribeBroadcast: X,
|
|
127
|
+
mutate: U,
|
|
128
|
+
configure: Q,
|
|
129
|
+
abort: G,
|
|
130
|
+
forget: H,
|
|
131
|
+
keys: x,
|
|
132
|
+
expiration: J,
|
|
133
|
+
hydrate: I,
|
|
134
|
+
snapshot: z,
|
|
135
|
+
caches: P,
|
|
136
|
+
events: V,
|
|
137
|
+
broadcast: W
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
export {
|
|
141
|
+
b as createQuery,
|
|
142
|
+
Z as defaultFetcher
|
|
143
|
+
};
|
|
144
|
+
//# sourceMappingURL=query.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query.js","sources":["../src/query/index.ts"],"sourcesContent":["/**\n * Determines the shape of the Cache instance.\n */\nexport interface Cache<T = unknown> {\n /**\n * Gets an item from the cache.\n */\n readonly get: (key: string) => T | undefined\n\n /**\n * Sets an item to the cache.\n */\n readonly set: (key: string, value: T) => void\n\n /**\n * Removes a key-value pair from the cache.\n */\n readonly delete: (key: string) => void\n\n /**\n * Returns the current cached keys.\n */\n readonly keys: () => IterableIterator<string>\n}\n\n/**\n * Determines how we store items in the items cache.\n */\ninterface ItemsCacheItem<T = unknown> {\n /**\n * Stores the cache item.\n */\n readonly item: T\n\n /**\n * Determines the expiration date of the item.\n */\n readonly expiresAt: Date\n}\n\n/**\n * Determines how we store items in the resolvers cache.\n */\ninterface ResolversCacheItem<T> {\n /**\n * The resolvable item.\n */\n readonly item: Promise<T>\n\n /**\n * The abort controller for the request.\n */\n readonly controller: AbortController\n}\n\n/**\n * Represents the available configuration options\n * for a query instance.\n */\nexport interface Configuration extends Options {\n /**\n * Determines the resolved items cache to use.\n */\n readonly itemsCache?: Cache<ItemsCacheItem>\n\n /**\n * Determines the resolvers cache to use.\n */\n readonly resolversCache?: Cache<ResolversCacheItem<unknown>>\n\n /**\n * Stores the event system.\n */\n readonly events?: 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 readonly broadcast?: BroadcastChannel\n}\n\nexport interface FetcherAdditional {\n /**\n * An abort signal to cancel pending queries.\n */\n readonly signal: AbortSignal\n}\n\n/**\n * The available options for query.\n */\nexport interface Options<T = unknown> {\n /**\n * Determines the item deduplication interval.\n * This determines how many milliseconds an item\n * is considered valid.\n */\n readonly expiration?: ExpirationFunction<T>\n\n /**\n * Determines the fetcher function to use.\n */\n readonly fetcher?: FetcherFunction<T>\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 readonly stale?: boolean\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 readonly removeOnError?: boolean\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 readonly fresh?: boolean\n}\n\n/**\n * Determines the cache type.\n */\nexport type CacheType = 'resolvers' | 'items'\n\n/**\n * The mutation function type.\n */\nexport interface MutationFunction<T> {\n (previous?: T, expiresAt?: Date): T | Promise<T>\n}\n\n/**\n * The available mutation values.\n */\nexport type MutationValue<T> = T | MutationFunction<T>\n\n/**\n * The function type for the event subscription.\n */\nexport interface SubscribeFunction {\n (key: string, event: QueryEvent, listener: EventListener): Unsubscriber\n}\n\n/**\n * The broadcast payload.\n */\nexport interface BroadcastPayload {\n /**\n * The event name.\n */\n readonly event: string\n\n /**\n * The event detail.\n */\n readonly detail: unknown\n}\n\n/**\n * The function type for the broadcast subscription.\n */\nexport interface SubscribeBroadcastFunction {\n (): Unsubscriber\n}\n\n/**\n * The query function type.\n */\nexport interface QueryFunction {\n <T = unknown>(key: string, options?: Options<T>): Promise<T>\n}\n\nexport interface ExpirationFunction<T = unknown> {\n (item: T): number\n}\n\nexport interface FetcherFunction<T = unknown> {\n (key: string, additional: FetcherAdditional): Promise<T>\n}\n\n/**\n * The mutate function options.\n */\nexport interface HydrateOptions<T = unknown> {\n expiration?: ExpirationFunction<T>\n}\n\n/**\n * The mutate function options.\n */\nexport interface MutateOptions<T = unknown> {\n expiration?: ExpirationFunction<T>\n}\n\n/**\n * The mutate function type.\n */\nexport interface MutateFunction {\n <T = unknown>(key: string, item: MutationValue<T>, options?: MutateOptions<T>): Promise<T>\n}\n\n/**\n * The hydrate function type.\n */\nexport interface HydrateFunction {\n <T = unknown>(keys: string | string[], item: T, options?: HydrateOptions<T>): void\n}\n\n/**\n * The unsubscriber function.\n */\nexport type Unsubscriber = () => void\n\n/**\n * The caches available on the query.\n */\nexport interface Caches {\n /**\n * A cache that contains the resolved items alongside\n * their expiration time.\n */\n readonly items: Cache<ItemsCacheItem>\n\n /**\n * A cache that contains the resolvers alongside\n * their abort controllers.\n */\n readonly resolvers: Cache<ResolversCacheItem<unknown>>\n}\n\n/**\n * Represents the methods a query\n * should implement.\n */\nexport interface Query {\n /**\n * Configures the current instance of query.\n */\n readonly configure: (options?: Partial<Configuration>) => void\n\n /**\n * Fetches the key information using a fetcher.\n * The returned promise contains the result item.\n */\n readonly query: QueryFunction\n\n /**\n * Subscribes to a given event & key. The event handler\n * does have a payload parameter that will contain relevant\n * information depending on the event type.\n */\n readonly subscribe: SubscribeFunction\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 readonly subscribeBroadcast: SubscribeBroadcastFunction\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.\n */\n readonly mutate: MutateFunction\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 */\n readonly abort: (key?: string | string[], reason?: unknown) => void\n\n /**\n * Forgets the given keys from the cache.\n * Removes items from both, the cache and resolvers.\n */\n readonly forget: (keys?: string | string[] | RegExp) => void\n\n /**\n * Hydrates the given keys on the cache\n * with the given value and expiration time.\n */\n readonly hydrate: HydrateFunction\n\n /**\n * Returns the given keys for the given cache.\n */\n readonly keys: (cache?: CacheType) => string[]\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 readonly expiration: (key: string) => Date | undefined\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 readonly snapshot: <T = unknown>(key: string) => T | undefined\n\n /**\n * Returns the current cache instances in use.\n */\n readonly caches: () => Caches\n\n /**\n * Returns the event system in use.\n */\n readonly events: () => EventTarget\n\n /**\n * Returns the broadcast channel in use.\n */\n readonly broadcast: () => BroadcastChannel | undefined\n}\n\n/**\n * Available events on query.\n */\nexport type QueryEvent =\n | 'refetching'\n | 'resolved'\n | 'mutating'\n | 'mutated'\n | 'aborted'\n | 'forgotten'\n | 'hydrated'\n | 'error'\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 =\n instanceOptions?.resolversCache ?? new Map<string, ResolversCacheItem<unknown>>()\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 * 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(key: string, event: QueryEvent, listener: EventListener): 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 listener(new CustomEvent(`${event}:${key}`, { detail: 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\n resolver = await fn(value?.item as T, value?.expiresAt)\n }\n\n const expiresAt = new Date()\n\n expiresAt.setMilliseconds(\n expiresAt.getMilliseconds() + (options?.expiration?.(resolver) ?? 0)\n )\n\n itemsCache.set(key, { item: resolver, expiresAt: expiresAt })\n\n return resolver\n }\n\n const result = action(resolver)\n\n events.dispatchEvent(new CustomEvent(`mutating:${key}`, { detail: result }))\n\n const item = await result\n\n events.dispatchEvent(new CustomEvent(`mutated:${key}`, { detail: item }))\n broadcast?.postMessage({ event: `mutated:${key}`, detail: 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 function snapshot<T = unknown>(key: string): T | undefined {\n return 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'): 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 | 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 events.dispatchEvent(new CustomEvent(`aborted:${key}`, { detail: reason }))\n broadcast?.postMessage({ event: `aborted:${key}`, detail: 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 function forget(cacheKeys?: string | string[] | RegExp): void {\n let itemKeys: 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 events.dispatchEvent(new CustomEvent(`forgotten:${key}`, { detail: item.item }))\n broadcast?.postMessage({ event: `forgotten:${key}`, detail: 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 | string[],\n item: T,\n options?: HydrateOptions<T>\n ): void {\n const expiresAt = new Date()\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, expiresAt: expiresAt })\n events.dispatchEvent(new CustomEvent(`hydrated:${key}`, { detail: item }))\n broadcast?.postMessage({ event: `hydrated:${key}`, detail: 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 async 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 async function refetch(key: string): Promise<T> {\n try {\n // Check if there's a pending resolver for that data.\n const pending = resolversCache.get(key)\n\n if (pending !== undefined) {\n return await (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 // Initiate the fetching request.\n async function action() {\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 // 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, expiresAt })\n\n return item\n }\n\n const result = action()\n\n // Adds the resolver to the cache.\n resolversCache.set(key, { item: result, controller })\n events.dispatchEvent(new CustomEvent(`refetching:${key}`, { detail: result }))\n\n const item = await result\n\n // Notify of the resolved item.\n events.dispatchEvent(new CustomEvent(`resolved:${key}`, { detail: item }))\n broadcast?.postMessage({ event: `resolved:${key}`, detail: item })\n\n // Return back the item.\n return 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 events.dispatchEvent(new CustomEvent(`error:${key}`, { detail: error }))\n broadcast?.postMessage({ event: `error:${key}`, detail: error })\n\n // Throw back the error.\n throw error\n }\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 await 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 // 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 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 await 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 T\n }\n\n // The item is not found in the items cache.\n // We need to perform a revalidation of the item.\n return await refetch(key)\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 return {\n query,\n subscribe,\n subscribeBroadcast,\n mutate,\n configure,\n abort,\n forget,\n keys,\n expiration,\n hydrate,\n snapshot,\n caches,\n events: localEvents,\n broadcast: localBroadcast,\n }\n}\n"],"names":["defaultFetcher","fetch","key","signal","response","createQuery","instanceOptions","defaultExpiration","itemsCache","resolversCache","events","broadcast","instanceExpiration","instanceFetcher","instanceStale","instanceRemoveOnError","instanceFresh","configure","options","subscribe","event","listener","value","mutate","resolver","action","_a","fn","expiresAt","result","item","snapshot","keys","type","abort","cacheKeys","reason","resolverKeys","forget","itemKeys","hydrate","expiration","query","fetcher","stale","removeOnError","fresh","refetch","pending","controller","error","cached","hasExpired","caches","localEvents","localBroadcast","subscribeBroadcast","onBroadcastMessage","message"],"mappings":"AA+VO,SAASA,EACdC,GACoB;AACpB,SAAO,eAAgBC,GAAa,EAAE,QAAAC,KAAyC;AAC7E,UAAMC,IAAW,M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;AAAA,EAAA;AAMxD,WAAS6C,IAAc;AACd,WAAA5C;AAAA,EAAA;AAMT,WAAS6C,IAAiB;AACjB,WAAA5C;AAAA,EAAA;AAST,WAAS6C,IAAmC;AAC1C,aAASC,EAAmBC,GAAyC;AACnE,MAAAhD,EAAO,cAAc,IAAI,YAAYgD,EAAQ,KAAK,OAAO,EAAE,QAAQA,EAAQ,KAAK,OAAQ,CAAA,CAAC;AAAA,IAAA;AAGhF,WAAA/C,KAAA,QAAAA,EAAA,iBAAiB,WAAW8C,IAEhC,WAAY;AACN,MAAA9C,KAAA,QAAAA,EAAA,oBAAoB,WAAW8C;AAAA,IAC5C;AAAA,EAAA;AAGK,SAAA;AAAA,IACL,OAAAf;AAAA,IACA,WAAAvB;AAAA,IACA,oBAAAqC;AAAA,IACA,QAAAjC;AAAA,IACA,WAAAN;AAAA,IACA,OAAAiB;AAAA,IACA,QAAAI;AAAA,IACA,MAAAN;AAAA,IACA,YAAAS;AAAA,IACA,SAAAD;AAAA,IACA,UAAAT;AAAA,IACA,QAAAsB;AAAA,IACA,QAAQC;AAAA,IACR,WAAWC;AAAA,EACb;AACF;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react"),V=require("react/jsx-runtime"),Z=require("./query.cjs"),P=n.createContext({query:void 0,additional:void 0});function F(){return n.useDebugValue("useQueryContext"),n.use(P)}function h(e){n.useDebugValue("useQueryInstance");const t=F();function u(){const r=(e==null?void 0:e.query)??t.query;if(!r)throw new Error("No query instance was found. Please provide one via the resource options or the query context.");return r}return n.useMemo(u,[e,t])}const I=n.createContext({isPending:void 0,startTransition:void 0});function A(){return n.useDebugValue("useQueryTransitionContext"),n.use(I)}function O(e,t){n.useDebugValue("useQueryActions");const{query:u,mutate:r,forget:o}=h(t);function s(x){return u(e,{stale:!1,...t,...x})}const i=n.useCallback(s,[u,e,t]);function l(x,m){return r(e,x,m)}const d=n.useCallback(l,[r,e]);function c(){o(e)}const g=n.useCallback(c,[o,e]);function b(){return{refetch:i,mutate:d,forget:g}}return n.useMemo(b,[i,d,g])}function j(e){n.useDebugValue("useQueryStatus");const{expiration:t,subscribe:u}=h(),[r,o]=n.useState(t(e)??new Date),[s,i]=n.useState(Date.now()>r.getTime()),[l,d]=n.useState(!1),[c,g]=n.useState(!1);function b(){if(Date.now()>=r.getTime()){i(!0);return}i(!1);function m(){i(!0)}const C=setTimeout(m,r.getTime()-Date.now());return function(){clearTimeout(C)}}n.useEffect(b,[r]);function x(){function m(){g(!0)}function C(){g(!1),o(t(e)??new Date)}function a(){o(t(e)??new Date)}function w(){o(t(e)??new Date),d(!1)}function Q(){o(t(e)??new Date)}function q(){d(!0)}function D(){d(!1),g(!1)}const M=u(e,"mutating",m),T=u(e,"mutated",C),v=u(e,"hydrated",a),R=u(e,"resolved",w),H=u(e,"forgotten",Q),y=u(e,"refetching",q),E=u(e,"error",D);return function(){M(),T(),v(),R(),H(),y(),E()}}return n.useEffect(x,[e,u,t,o]),{expiresAt:r,isExpired:s,isRefetching:l,isMutating:c}}function _(e,t){n.useDebugValue("useQuery");const{additional:u}=F(),{isPending:r,startTransition:o}=A(),[s,i]=n.useTransition(),{query:l,expiration:d,subscribe:c}=h(t);function g(){return(t==null?void 0:t.ignoreTransitionContext)??(u==null?void 0:u.ignoreTransitionContext)??!1}const b=n.useMemo(g,[t,u]);function x(){return b?s:r??s}const m=n.useMemo(x,[r,s,b]);function C(){return b?i:o??i}const a=n.useMemo(C,[o,i,b]);function w(){return(t==null?void 0:t.clearOnForget)??(u==null?void 0:u.clearOnForget)??!1}const Q=n.useMemo(w,[t,u]);async function q(){return await l(e,t)}const D=n.useMemo(q,[l,e,t]),M=n.useRef(void 0);M.current===void 0&&(M.current=n.use(D));const[T,v]=n.useState(M.current);function R(){function B(f){a(function(){v(f.detail)})}function L(f){a(async function(){const S=await f.detail;a(function(){v(S)})})}function N(f){a(function(){v(f.detail)})}function $(f){a(function(){v(f.detail)})}function z(f){a(async function(){const S=await f.detail;a(function(){v(S)})})}function G(){Q&&a(async function(){const f=await l(e,t);a(function(){v(f)})})}const J=c(e,"resolved",B),K=c(e,"mutating",L),U=c(e,"mutated",N),W=c(e,"hydrated",$),X=c(e,"refetching",z),Y=c(e,"forgotten",G);return function(){J(),K(),U(),W(),X(),Y()}}n.useEffect(R,[l,d,c,e,Q,t,a]);const H=O(e,t),y=j(e);function E(){return{data:T,isPending:m,...H,...y}}return n.useMemo(E,[T,m,H,y])}function p({children:e,clearOnForget:t,broadcast:u,...r}){function o(){return Z.createQuery({broadcast:u,...r})}const[s]=n.useState(o);function i(){s.configure(r)}n.useEffect(i,[s,r]);function l(){if(u){s.configure({broadcast:u});const C=s.subscribeBroadcast();return function(){C()}}const x=new BroadcastChannel("query");s.configure({broadcast:x});const m=s.subscribeBroadcast();return function(){m(),x.close()}}n.useEffect(l,[s,u]);function d(){return{clearOnForget:t}}const c=n.useMemo(d,[t]);function g(){return{query:s,additional:c}}const b=n.useMemo(g,[s,c]);return V.jsx(P,{value:b,children:e})}function k({children:e,startTransition:t,isPending:u}){function r(){return{startTransition:t,isPending:u}}const o=n.useMemo(r,[t,u]);return V.jsx(I,{value:o,children:e})}exports.Context=P;exports.QueryProvider=p;exports.QueryTransition=k;exports.TransitionContext=I;exports.useQuery=_;exports.useQueryActions=O;exports.useQueryContext=F;exports.useQueryInstance=h;exports.useQueryStatus=j;exports.useQueryTransitionContext=A;
|
|
2
|
+
//# sourceMappingURL=query_react.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query_react.cjs","sources":["../src/react/context.ts","../src/react/hooks/useQueryContext.ts","../src/react/hooks/useQueryInstance.ts","../src/react/transition.ts","../src/react/hooks/useQueryTransitionContext.ts","../src/react/hooks/useQueryActions.ts","../src/react/hooks/useQueryStatus.ts","../src/react/hooks/useQuery.ts","../src/react/components/QueryProvider.tsx","../src/react/components/QueryTransition.tsx"],"sourcesContent":["import { createContext } from 'react'\nimport { Query } from 'query:index'\n\nexport interface ContextOptions {\n readonly clearOnForget?: boolean\n readonly ignoreTransitionContext?: boolean\n}\n\nexport interface ContextValue {\n readonly query?: Query\n readonly additional?: ContextOptions\n}\n\nexport const Context = createContext<ContextValue>({\n query: undefined,\n additional: undefined,\n})\n","import { Context, type ContextValue } from 'query/react:context'\nimport { use, useDebugValue } from 'react'\n\nexport function useQueryContext(): ContextValue {\n useDebugValue('useQueryContext')\n\n return use(Context)\n}\n","import { type Query } from 'query:index'\nimport { useQueryContext } from 'query/react:hooks/useQueryContext'\nimport { useDebugValue, useMemo } from 'react'\n\nexport interface QueryInstance {\n readonly query?: Query\n}\n\nexport function useQueryInstance(options?: QueryInstance): Query {\n useDebugValue('useQueryInstance')\n\n const contextOptions = useQueryContext()\n\n function query() {\n const instance = options?.query ?? contextOptions.query\n\n if (!instance) {\n throw new Error(\n 'No query instance was found. Please provide one via the resource options or the query context.'\n )\n }\n\n return instance\n }\n\n return useMemo(query, [options, contextOptions])\n}\n","import { createContext, type TransitionStartFunction } from 'react'\n\nexport interface QueryTransitionContextValue {\n readonly isPending?: boolean\n readonly startTransition?: TransitionStartFunction\n}\n\nexport const TransitionContext = createContext<QueryTransitionContextValue>({\n isPending: undefined,\n startTransition: undefined,\n})\n","import { TransitionContext, type QueryTransitionContextValue } from 'query/react:transition'\nimport { use, useDebugValue } from 'react'\n\nexport function useQueryTransitionContext(): QueryTransitionContextValue {\n useDebugValue('useQueryTransitionContext')\n\n return use(TransitionContext)\n}\n","import { MutateOptions, MutationValue, Options } from 'query:index'\nimport { useCallback, useDebugValue, useMemo } from 'react'\nimport { QueryInstance, useQueryInstance } from './useQueryInstance'\n\nexport interface QueryActions<T = unknown> {\n readonly refetch: (refetchOptions?: Options<T>) => Promise<T>\n readonly mutate: (value: MutationValue<T>, options?: MutateOptions<T>) => Promise<T>\n readonly forget: () => void\n}\n\nexport type QueryActionsOptions<T = unknown> = Options<T> & QueryInstance\n\nexport function useQueryActions<T = unknown>(\n key: string,\n options?: QueryActionsOptions<T>\n): QueryActions<T> {\n useDebugValue('useQueryActions')\n\n const { query, mutate, forget } = useQueryInstance(options)\n\n function refetchHandler(refetchOptions?: Options<T>) {\n return query<T>(key, {\n stale: false,\n ...options,\n ...refetchOptions,\n })\n }\n\n const refetch = useCallback(refetchHandler, [query, key, options])\n\n function mutateHandler<T = unknown>(value: MutationValue<T>, options?: MutateOptions<T>) {\n return mutate(key, value, options)\n }\n\n const localMutate = useCallback(mutateHandler, [mutate, key])\n\n function forgetHandler() {\n forget(key)\n }\n\n const localForget = useCallback(forgetHandler, [forget, key])\n\n function actionsHandler() {\n return { refetch, mutate: localMutate, forget: localForget }\n }\n\n return useMemo(actionsHandler, [refetch, localMutate, localForget])\n}\n","import { useDebugValue, useEffect, useState } from 'react'\nimport { useQueryInstance } from './useQueryInstance'\n\nexport interface Status {\n readonly expiresAt: Date\n readonly isExpired: boolean\n readonly isRefetching: boolean\n readonly isMutating: boolean\n}\n\nexport function useQueryStatus(key: string): Status {\n useDebugValue('useQueryStatus')\n\n const { expiration, subscribe } = useQueryInstance()\n const [expiresAt, setExpiresAt] = useState<Date>(expiration(key) ?? new Date())\n const [isExpired, setIsExpired] = useState(Date.now() > expiresAt.getTime())\n const [isRefetching, setIsRefetching] = useState(false)\n const [isMutating, setIsMutating] = useState(false)\n\n function expirationHandler() {\n if (Date.now() >= expiresAt.getTime()) {\n setIsExpired(true)\n return\n }\n\n setIsExpired(false)\n\n function handler() {\n setIsExpired(true)\n }\n\n const id = setTimeout(handler, expiresAt.getTime() - Date.now())\n\n return function () {\n clearTimeout(id)\n }\n }\n\n useEffect(expirationHandler, [expiresAt])\n\n function subscribeHandler() {\n function onMutating() {\n setIsMutating(true)\n }\n\n function onMutated() {\n setIsMutating(false)\n setExpiresAt(expiration(key) ?? new Date())\n }\n\n function onHydrated() {\n setExpiresAt(expiration(key) ?? new Date())\n }\n\n function onResolved() {\n setExpiresAt(expiration(key) ?? new Date())\n setIsRefetching(false)\n }\n\n function onForgotten() {\n setExpiresAt(expiration(key) ?? new Date())\n }\n\n function onRefetching() {\n setIsRefetching(true)\n }\n\n function onError() {\n setIsRefetching(false)\n setIsMutating(false)\n }\n\n const unsubscribeMutating = subscribe(key, 'mutating', onMutating)\n const unsubscribeMutated = subscribe(key, 'mutated', onMutated)\n const unsubscribeHydrated = subscribe(key, 'hydrated', onHydrated)\n const unsubscribeResolved = subscribe(key, 'resolved', onResolved)\n const unsubscribeForgotten = subscribe(key, 'forgotten', onForgotten)\n const unsubscribeRefetching = subscribe(key, 'refetching', onRefetching)\n const unsubscribeError = subscribe(key, 'error', onError)\n\n return function () {\n unsubscribeMutating()\n unsubscribeMutated()\n unsubscribeHydrated()\n unsubscribeResolved()\n unsubscribeForgotten()\n unsubscribeRefetching()\n unsubscribeError()\n }\n }\n\n useEffect(subscribeHandler, [key, subscribe, expiration, setExpiresAt])\n\n return { expiresAt, isExpired, isRefetching, isMutating }\n}\n","import { useEffect, use, useState, useMemo, useDebugValue, useTransition, useRef } from 'react'\nimport { ContextOptions as ContextOptions } from 'query/react:context'\nimport { Options } from 'query:index'\nimport { useQueryContext } from './useQueryContext'\nimport { QueryInstance, useQueryInstance } from './useQueryInstance'\nimport { useQueryTransitionContext } from './useQueryTransitionContext'\nimport { QueryActions, useQueryActions } from './useQueryActions'\nimport { useQueryStatus, type Status } from './useQueryStatus'\n\ntype AdditionalHooks<T> = QueryActions<T> & Status\n\nexport interface Resource<T = unknown> extends AdditionalHooks<T> {\n data: T\n isPending: boolean\n}\n\nexport type ResourceOptions<T = unknown> = ContextOptions & Options<T> & QueryInstance\n\nexport function useQuery<T = unknown>(key: string, options?: ResourceOptions<T>): Resource<T> {\n useDebugValue('useQuery')\n\n const { additional } = useQueryContext()\n\n const { isPending: isContextPending, startTransition: startContextTransition } =\n useQueryTransitionContext()\n\n const [isLocalPending, startLocalTransition] = useTransition()\n const { query, expiration, subscribe } = useQueryInstance(options)\n\n function ignoreTransitionContextHandler() {\n return options?.ignoreTransitionContext ?? additional?.ignoreTransitionContext ?? false\n }\n\n const ignoreTransitionContext = useMemo(ignoreTransitionContextHandler, [options, additional])\n\n function isPendingHandler() {\n if (ignoreTransitionContext) {\n return isLocalPending\n }\n\n return isContextPending ?? isLocalPending\n }\n\n const isPending = useMemo(isPendingHandler, [\n isContextPending,\n isLocalPending,\n ignoreTransitionContext,\n ])\n\n function startTransitionHandler() {\n if (ignoreTransitionContext) {\n return startLocalTransition\n }\n\n return startContextTransition ?? startLocalTransition\n }\n\n const startTransition = useMemo(startTransitionHandler, [\n startContextTransition,\n startLocalTransition,\n ignoreTransitionContext,\n ])\n\n function clearOnForgetHandler() {\n return options?.clearOnForget ?? additional?.clearOnForget ?? false\n }\n\n const clearOnForget = useMemo(clearOnForgetHandler, [options, additional])\n\n async function promiseHandler() {\n return await query<T>(key, options)\n }\n\n const promise = useMemo(promiseHandler, [query, key, options])\n const initial = useRef<T>(undefined)\n\n if (initial.current === undefined) {\n initial.current = use(promise)\n }\n\n const [data, setData] = useState(initial.current)\n\n function subscribeHandler() {\n function onResolved(event: Event) {\n startTransition(function () {\n setData((event as CustomEvent<T>).detail)\n })\n }\n\n function onMutating(event: Event) {\n startTransition(async function () {\n const value = await (event as CustomEvent<Promise<T>>).detail\n\n startTransition(function () {\n setData(value)\n })\n })\n }\n\n function onMutated(event: Event) {\n startTransition(function () {\n setData((event as CustomEvent<T>).detail)\n })\n }\n\n function onHydrated(event: Event) {\n startTransition(function () {\n setData((event as CustomEvent<T>).detail)\n })\n }\n\n function onRefetching(event: Event) {\n startTransition(async function () {\n const value = await (event as CustomEvent<Promise<T>>).detail\n\n startTransition(function () {\n setData(value)\n })\n })\n }\n\n function onForgotten() {\n if (clearOnForget) {\n startTransition(async function () {\n const data = await query<T>(key, options)\n\n startTransition(function () {\n setData(data)\n })\n })\n }\n }\n\n const unsubscribeResolved = subscribe(key, 'resolved', onResolved)\n const unsubscribeMutating = subscribe(key, 'mutating', onMutating)\n const unsubscribeMutated = subscribe(key, 'mutated', onMutated)\n const unsubscribeHydrated = subscribe(key, 'hydrated', onHydrated)\n const unsubscribeRefetching = subscribe(key, 'refetching', onRefetching)\n const unsubscribeForgotten = subscribe(key, 'forgotten', onForgotten)\n\n return function () {\n unsubscribeResolved()\n unsubscribeMutating()\n unsubscribeMutated()\n unsubscribeHydrated()\n unsubscribeRefetching()\n unsubscribeForgotten()\n }\n }\n\n useEffect(subscribeHandler, [\n query,\n expiration,\n subscribe,\n key,\n clearOnForget,\n options,\n startTransition,\n ])\n\n const actions = useQueryActions<T>(key, options)\n const status = useQueryStatus(key)\n\n function resourceHandler(): Resource<T> {\n return { data, isPending, ...actions, ...status }\n }\n\n return useMemo(resourceHandler, [data, isPending, actions, status])\n}\n","import { useEffect, useMemo, useState, type ReactNode } from 'react'\nimport { Context, ContextValue, type ContextOptions } from 'query/react:context'\nimport { createQuery, Query, type Configuration } from 'query:index'\n\ntype OtherProps = Configuration & ContextOptions\n\nexport interface QueryProviderProps extends OtherProps {\n children?: ReactNode\n}\n\nexport function QueryProvider({\n children,\n clearOnForget,\n broadcast,\n ...options\n}: QueryProviderProps) {\n function initial() {\n return createQuery({ broadcast, ...options })\n }\n\n const [query] = useState<Query>(initial)\n\n function reconfigure() {\n query.configure(options)\n }\n\n useEffect(reconfigure, [query, options])\n\n function broadcastCleanup() {\n if (broadcast) {\n query.configure({ broadcast })\n const unsubscribe = query.subscribeBroadcast()\n\n return function () {\n unsubscribe()\n }\n }\n\n const channel = new BroadcastChannel('query')\n\n query.configure({ broadcast: channel })\n const unsubscribe = query.subscribeBroadcast()\n\n return function () {\n unsubscribe()\n channel.close()\n }\n }\n\n useEffect(broadcastCleanup, [query, broadcast])\n\n function additionalHandler() {\n return { clearOnForget }\n }\n\n const additional = useMemo(additionalHandler, [clearOnForget])\n\n function valueHandler(): ContextValue {\n return { query, additional }\n }\n\n const value = useMemo(valueHandler, [query, additional])\n\n return <Context value={value}>{children}</Context>\n}\n","import { TransitionContext, QueryTransitionContextValue } from 'query/react:transition'\nimport { useMemo, type ReactNode, type TransitionStartFunction } from 'react'\n\nexport interface QueryTransitionProps {\n isPending: boolean\n startTransition: TransitionStartFunction\n children?: ReactNode\n}\n\nexport function QueryTransition({ children, startTransition, isPending }: QueryTransitionProps) {\n function valueHandler(): QueryTransitionContextValue {\n return { startTransition, isPending }\n }\n\n const value = useMemo(valueHandler, [startTransition, isPending])\n\n return <TransitionContext value={value}>{children}</TransitionContext>\n}\n"],"names":["Context","createContext","useQueryContext","useDebugValue","use","useQueryInstance","options","contextOptions","query","instance","useMemo","TransitionContext","useQueryTransitionContext","useQueryActions","key","mutate","forget","refetchHandler","refetchOptions","refetch","useCallback","mutateHandler","value","localMutate","forgetHandler","localForget","actionsHandler","useQueryStatus","expiration","subscribe","expiresAt","setExpiresAt","useState","isExpired","setIsExpired","isRefetching","setIsRefetching","isMutating","setIsMutating","expirationHandler","handler","id","useEffect","subscribeHandler","onMutating","onMutated","onHydrated","onResolved","onForgotten","onRefetching","onError","unsubscribeMutating","unsubscribeMutated","unsubscribeHydrated","unsubscribeResolved","unsubscribeForgotten","unsubscribeRefetching","unsubscribeError","useQuery","additional","isContextPending","startContextTransition","isLocalPending","startLocalTransition","useTransition","ignoreTransitionContextHandler","ignoreTransitionContext","isPendingHandler","isPending","startTransitionHandler","startTransition","clearOnForgetHandler","clearOnForget","promiseHandler","promise","initial","useRef","data","setData","event","actions","status","resourceHandler","QueryProvider","children","broadcast","createQuery","reconfigure","broadcastCleanup","unsubscribe","channel","additionalHandler","valueHandler","jsx","QueryTransition"],"mappings":"iKAaaA,EAAUC,EAAAA,cAA4B,CACjD,MAAO,OACP,WAAY,MACd,CAAC,ECbM,SAASC,GAAgC,CAC9CC,OAAAA,EAAAA,cAAc,iBAAiB,EAExBC,EAAAA,IAAIJ,CAAO,CACpB,CCCO,SAASK,EAAiBC,EAAgC,CAC/DH,EAAAA,cAAc,kBAAkB,EAEhC,MAAMI,EAAiBL,EAAgB,EAEvC,SA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B,OAAO,EAE5ClF,EAAM,UAAU,CAAE,UAAWkF,CAAA,CAAS,EAChC,MAAAD,EAAcjF,EAAM,mBAAmB,EAE7C,OAAO,UAAY,CACLiF,EAAA,EACZC,EAAQ,MAAM,CAChB,CAAA,CAGFhD,EAAAA,UAAU8C,EAAkB,CAAChF,EAAO6E,CAAS,CAAC,EAE9C,SAASM,GAAoB,CAC3B,MAAO,CAAE,cAAAnB,CAAc,CAAA,CAGzB,MAAMb,EAAajD,EAAA,QAAQiF,EAAmB,CAACnB,CAAa,CAAC,EAE7D,SAASoB,GAA6B,CAC7B,MAAA,CAAA,MAAEpF,EAAO,WAAAmD,CAAW,CAAA,CAG7B,MAAMrC,EAAQZ,EAAAA,QAAQkF,EAAc,CAACpF,EAAOmD,CAAU,CAAC,EAEhD,OAAAkC,EAAA,IAAC7F,EAAQ,CAAA,MAAAsB,EAAe,SAAA8D,CAAS,CAAA,CAC1C,CCvDO,SAASU,EAAgB,CAAE,SAAAV,EAAU,gBAAAd,EAAiB,UAAAF,GAAmC,CAC9F,SAASwB,GAA4C,CAC5C,MAAA,CAAE,gBAAAtB,EAAiB,UAAAF,CAAU,CAAA,CAGtC,MAAM9C,EAAQZ,EAAAA,QAAQkF,EAAc,CAACtB,EAAiBF,CAAS,CAAC,EAEzD,OAAAyB,EAAA,IAAClF,EAAkB,CAAA,MAAAW,EAAe,SAAA8D,CAAS,CAAA,CACpD"}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { createContext as S, useDebugValue as h, use as O, useMemo as f, useCallback as A, useState as T, useEffect as C, useTransition as k, useRef as nn } from "react";
|
|
2
|
+
import { jsx as L } from "react/jsx-runtime";
|
|
3
|
+
import { createQuery as tn } from "./query.js";
|
|
4
|
+
const j = S({
|
|
5
|
+
query: void 0,
|
|
6
|
+
additional: void 0
|
|
7
|
+
});
|
|
8
|
+
function N() {
|
|
9
|
+
return h("useQueryContext"), O(j);
|
|
10
|
+
}
|
|
11
|
+
function B(n) {
|
|
12
|
+
h("useQueryInstance");
|
|
13
|
+
const t = N();
|
|
14
|
+
function e() {
|
|
15
|
+
const r = (n == null ? void 0 : n.query) ?? t.query;
|
|
16
|
+
if (!r)
|
|
17
|
+
throw new Error(
|
|
18
|
+
"No query instance was found. Please provide one via the resource options or the query context."
|
|
19
|
+
);
|
|
20
|
+
return r;
|
|
21
|
+
}
|
|
22
|
+
return f(e, [n, t]);
|
|
23
|
+
}
|
|
24
|
+
const V = S({
|
|
25
|
+
isPending: void 0,
|
|
26
|
+
startTransition: void 0
|
|
27
|
+
});
|
|
28
|
+
function en() {
|
|
29
|
+
return h("useQueryTransitionContext"), O(V);
|
|
30
|
+
}
|
|
31
|
+
function rn(n, t) {
|
|
32
|
+
h("useQueryActions");
|
|
33
|
+
const { query: e, mutate: r, forget: o } = B(t);
|
|
34
|
+
function u(x) {
|
|
35
|
+
return e(n, {
|
|
36
|
+
stale: !1,
|
|
37
|
+
...t,
|
|
38
|
+
...x
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const i = A(u, [e, n, t]);
|
|
42
|
+
function d(x, m) {
|
|
43
|
+
return r(n, x, m);
|
|
44
|
+
}
|
|
45
|
+
const l = A(d, [r, n]);
|
|
46
|
+
function c() {
|
|
47
|
+
o(n);
|
|
48
|
+
}
|
|
49
|
+
const g = A(c, [o, n]);
|
|
50
|
+
function b() {
|
|
51
|
+
return { refetch: i, mutate: l, forget: g };
|
|
52
|
+
}
|
|
53
|
+
return f(b, [i, l, g]);
|
|
54
|
+
}
|
|
55
|
+
function un(n) {
|
|
56
|
+
h("useQueryStatus");
|
|
57
|
+
const { expiration: t, subscribe: e } = B(), [r, o] = T(t(n) ?? /* @__PURE__ */ new Date()), [u, i] = T(Date.now() > r.getTime()), [d, l] = T(!1), [c, g] = T(!1);
|
|
58
|
+
function b() {
|
|
59
|
+
if (Date.now() >= r.getTime()) {
|
|
60
|
+
i(!0);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
i(!1);
|
|
64
|
+
function m() {
|
|
65
|
+
i(!0);
|
|
66
|
+
}
|
|
67
|
+
const H = setTimeout(m, r.getTime() - Date.now());
|
|
68
|
+
return function() {
|
|
69
|
+
clearTimeout(H);
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
C(b, [r]);
|
|
73
|
+
function x() {
|
|
74
|
+
function m() {
|
|
75
|
+
g(!0);
|
|
76
|
+
}
|
|
77
|
+
function H() {
|
|
78
|
+
g(!1), o(t(n) ?? /* @__PURE__ */ new Date());
|
|
79
|
+
}
|
|
80
|
+
function s() {
|
|
81
|
+
o(t(n) ?? /* @__PURE__ */ new Date());
|
|
82
|
+
}
|
|
83
|
+
function D() {
|
|
84
|
+
o(t(n) ?? /* @__PURE__ */ new Date()), l(!1);
|
|
85
|
+
}
|
|
86
|
+
function Q() {
|
|
87
|
+
o(t(n) ?? /* @__PURE__ */ new Date());
|
|
88
|
+
}
|
|
89
|
+
function F() {
|
|
90
|
+
l(!0);
|
|
91
|
+
}
|
|
92
|
+
function y() {
|
|
93
|
+
l(!1), g(!1);
|
|
94
|
+
}
|
|
95
|
+
const w = e(n, "mutating", m), M = e(n, "mutated", H), v = e(n, "hydrated", s), E = e(n, "resolved", D), R = e(n, "forgotten", Q), q = e(n, "refetching", F), P = e(n, "error", y);
|
|
96
|
+
return function() {
|
|
97
|
+
w(), M(), v(), E(), R(), q(), P();
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
return C(x, [n, e, t, o]), { expiresAt: r, isExpired: u, isRefetching: d, isMutating: c };
|
|
101
|
+
}
|
|
102
|
+
function an(n, t) {
|
|
103
|
+
h("useQuery");
|
|
104
|
+
const { additional: e } = N(), { isPending: r, startTransition: o } = en(), [u, i] = k(), { query: d, expiration: l, subscribe: c } = B(t);
|
|
105
|
+
function g() {
|
|
106
|
+
return (t == null ? void 0 : t.ignoreTransitionContext) ?? (e == null ? void 0 : e.ignoreTransitionContext) ?? !1;
|
|
107
|
+
}
|
|
108
|
+
const b = f(g, [t, e]);
|
|
109
|
+
function x() {
|
|
110
|
+
return b ? u : r ?? u;
|
|
111
|
+
}
|
|
112
|
+
const m = f(x, [
|
|
113
|
+
r,
|
|
114
|
+
u,
|
|
115
|
+
b
|
|
116
|
+
]);
|
|
117
|
+
function H() {
|
|
118
|
+
return b ? i : o ?? i;
|
|
119
|
+
}
|
|
120
|
+
const s = f(H, [
|
|
121
|
+
o,
|
|
122
|
+
i,
|
|
123
|
+
b
|
|
124
|
+
]);
|
|
125
|
+
function D() {
|
|
126
|
+
return (t == null ? void 0 : t.clearOnForget) ?? (e == null ? void 0 : e.clearOnForget) ?? !1;
|
|
127
|
+
}
|
|
128
|
+
const Q = f(D, [t, e]);
|
|
129
|
+
async function F() {
|
|
130
|
+
return await d(n, t);
|
|
131
|
+
}
|
|
132
|
+
const y = f(F, [d, n, t]), w = nn(void 0);
|
|
133
|
+
w.current === void 0 && (w.current = O(y));
|
|
134
|
+
const [M, v] = T(w.current);
|
|
135
|
+
function E() {
|
|
136
|
+
function z(a) {
|
|
137
|
+
s(function() {
|
|
138
|
+
v(a.detail);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
function G(a) {
|
|
142
|
+
s(async function() {
|
|
143
|
+
const I = await a.detail;
|
|
144
|
+
s(function() {
|
|
145
|
+
v(I);
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
function J(a) {
|
|
150
|
+
s(function() {
|
|
151
|
+
v(a.detail);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
function K(a) {
|
|
155
|
+
s(function() {
|
|
156
|
+
v(a.detail);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
function U(a) {
|
|
160
|
+
s(async function() {
|
|
161
|
+
const I = await a.detail;
|
|
162
|
+
s(function() {
|
|
163
|
+
v(I);
|
|
164
|
+
});
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
function W() {
|
|
168
|
+
Q && s(async function() {
|
|
169
|
+
const a = await d(n, t);
|
|
170
|
+
s(function() {
|
|
171
|
+
v(a);
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
const X = c(n, "resolved", z), Y = c(n, "mutating", G), Z = c(n, "mutated", J), _ = c(n, "hydrated", K), $ = c(n, "refetching", U), p = c(n, "forgotten", W);
|
|
176
|
+
return function() {
|
|
177
|
+
X(), Y(), Z(), _(), $(), p();
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
C(E, [
|
|
181
|
+
d,
|
|
182
|
+
l,
|
|
183
|
+
c,
|
|
184
|
+
n,
|
|
185
|
+
Q,
|
|
186
|
+
t,
|
|
187
|
+
s
|
|
188
|
+
]);
|
|
189
|
+
const R = rn(n, t), q = un(n);
|
|
190
|
+
function P() {
|
|
191
|
+
return { data: M, isPending: m, ...R, ...q };
|
|
192
|
+
}
|
|
193
|
+
return f(P, [M, m, R, q]);
|
|
194
|
+
}
|
|
195
|
+
function fn({
|
|
196
|
+
children: n,
|
|
197
|
+
clearOnForget: t,
|
|
198
|
+
broadcast: e,
|
|
199
|
+
...r
|
|
200
|
+
}) {
|
|
201
|
+
function o() {
|
|
202
|
+
return tn({ broadcast: e, ...r });
|
|
203
|
+
}
|
|
204
|
+
const [u] = T(o);
|
|
205
|
+
function i() {
|
|
206
|
+
u.configure(r);
|
|
207
|
+
}
|
|
208
|
+
C(i, [u, r]);
|
|
209
|
+
function d() {
|
|
210
|
+
if (e) {
|
|
211
|
+
u.configure({ broadcast: e });
|
|
212
|
+
const H = u.subscribeBroadcast();
|
|
213
|
+
return function() {
|
|
214
|
+
H();
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
const x = new BroadcastChannel("query");
|
|
218
|
+
u.configure({ broadcast: x });
|
|
219
|
+
const m = u.subscribeBroadcast();
|
|
220
|
+
return function() {
|
|
221
|
+
m(), x.close();
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
C(d, [u, e]);
|
|
225
|
+
function l() {
|
|
226
|
+
return { clearOnForget: t };
|
|
227
|
+
}
|
|
228
|
+
const c = f(l, [t]);
|
|
229
|
+
function g() {
|
|
230
|
+
return { query: u, additional: c };
|
|
231
|
+
}
|
|
232
|
+
const b = f(g, [u, c]);
|
|
233
|
+
return /* @__PURE__ */ L(j, { value: b, children: n });
|
|
234
|
+
}
|
|
235
|
+
function dn({ children: n, startTransition: t, isPending: e }) {
|
|
236
|
+
function r() {
|
|
237
|
+
return { startTransition: t, isPending: e };
|
|
238
|
+
}
|
|
239
|
+
const o = f(r, [t, e]);
|
|
240
|
+
return /* @__PURE__ */ L(V, { value: o, children: n });
|
|
241
|
+
}
|
|
242
|
+
export {
|
|
243
|
+
j as Context,
|
|
244
|
+
fn as QueryProvider,
|
|
245
|
+
dn as QueryTransition,
|
|
246
|
+
V as TransitionContext,
|
|
247
|
+
an as useQuery,
|
|
248
|
+
rn as useQueryActions,
|
|
249
|
+
N as useQueryContext,
|
|
250
|
+
B as useQueryInstance,
|
|
251
|
+
un as useQueryStatus,
|
|
252
|
+
en as useQueryTransitionContext
|
|
253
|
+
};
|
|
254
|
+
//# sourceMappingURL=query_react.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query_react.js","sources":["../src/react/context.ts","../src/react/hooks/useQueryContext.ts","../src/react/hooks/useQueryInstance.ts","../src/react/transition.ts","../src/react/hooks/useQueryTransitionContext.ts","../src/react/hooks/useQueryActions.ts","../src/react/hooks/useQueryStatus.ts","../src/react/hooks/useQuery.ts","../src/react/components/QueryProvider.tsx","../src/react/components/QueryTransition.tsx"],"sourcesContent":["import { createContext } from 'react'\nimport { Query } from 'query:index'\n\nexport interface ContextOptions {\n readonly clearOnForget?: boolean\n readonly ignoreTransitionContext?: boolean\n}\n\nexport interface ContextValue {\n readonly query?: Query\n readonly additional?: ContextOptions\n}\n\nexport const Context = createContext<ContextValue>({\n query: undefined,\n additional: undefined,\n})\n","import { Context, type ContextValue } from 'query/react:context'\nimport { use, useDebugValue } from 'react'\n\nexport function useQueryContext(): ContextValue {\n useDebugValue('useQueryContext')\n\n return use(Context)\n}\n","import { type Query } from 'query:index'\nimport { useQueryContext } from 'query/react:hooks/useQueryContext'\nimport { useDebugValue, useMemo } from 'react'\n\nexport interface QueryInstance {\n readonly query?: Query\n}\n\nexport function useQueryInstance(options?: QueryInstance): Query {\n useDebugValue('useQueryInstance')\n\n const contextOptions = useQueryContext()\n\n function query() {\n const instance = options?.query ?? contextOptions.query\n\n if (!instance) {\n throw new Error(\n 'No query instance was found. Please provide one via the resource options or the query context.'\n )\n }\n\n return instance\n }\n\n return useMemo(query, [options, contextOptions])\n}\n","import { createContext, type TransitionStartFunction } from 'react'\n\nexport interface QueryTransitionContextValue {\n readonly isPending?: boolean\n readonly startTransition?: TransitionStartFunction\n}\n\nexport const TransitionContext = createContext<QueryTransitionContextValue>({\n isPending: undefined,\n startTransition: undefined,\n})\n","import { TransitionContext, type QueryTransitionContextValue } from 'query/react:transition'\nimport { use, useDebugValue } from 'react'\n\nexport function useQueryTransitionContext(): QueryTransitionContextValue {\n useDebugValue('useQueryTransitionContext')\n\n return use(TransitionContext)\n}\n","import { MutateOptions, MutationValue, Options } from 'query:index'\nimport { useCallback, useDebugValue, useMemo } from 'react'\nimport { QueryInstance, useQueryInstance } from './useQueryInstance'\n\nexport interface QueryActions<T = unknown> {\n readonly refetch: (refetchOptions?: Options<T>) => Promise<T>\n readonly mutate: (value: MutationValue<T>, options?: MutateOptions<T>) => Promise<T>\n readonly forget: () => void\n}\n\nexport type QueryActionsOptions<T = unknown> = Options<T> & QueryInstance\n\nexport function useQueryActions<T = unknown>(\n key: string,\n options?: QueryActionsOptions<T>\n): QueryActions<T> {\n useDebugValue('useQueryActions')\n\n const { query, mutate, forget } = useQueryInstance(options)\n\n function refetchHandler(refetchOptions?: Options<T>) {\n return query<T>(key, {\n stale: false,\n ...options,\n ...refetchOptions,\n })\n }\n\n const refetch = useCallback(refetchHandler, [query, key, options])\n\n function mutateHandler<T = unknown>(value: MutationValue<T>, options?: MutateOptions<T>) {\n return mutate(key, value, options)\n }\n\n const localMutate = useCallback(mutateHandler, [mutate, key])\n\n function forgetHandler() {\n forget(key)\n }\n\n const localForget = useCallback(forgetHandler, [forget, key])\n\n function actionsHandler() {\n return { refetch, mutate: localMutate, forget: localForget }\n }\n\n return useMemo(actionsHandler, [refetch, localMutate, localForget])\n}\n","import { useDebugValue, useEffect, useState } from 'react'\nimport { useQueryInstance } from './useQueryInstance'\n\nexport interface Status {\n readonly expiresAt: Date\n readonly isExpired: boolean\n readonly isRefetching: boolean\n readonly isMutating: boolean\n}\n\nexport function useQueryStatus(key: string): Status {\n useDebugValue('useQueryStatus')\n\n const { expiration, subscribe } = useQueryInstance()\n const [expiresAt, setExpiresAt] = useState<Date>(expiration(key) ?? new Date())\n const [isExpired, setIsExpired] = useState(Date.now() > expiresAt.getTime())\n const [isRefetching, setIsRefetching] = useState(false)\n const [isMutating, setIsMutating] = useState(false)\n\n function expirationHandler() {\n if (Date.now() >= expiresAt.getTime()) {\n setIsExpired(true)\n return\n }\n\n setIsExpired(false)\n\n function handler() {\n setIsExpired(true)\n }\n\n const id = setTimeout(handler, expiresAt.getTime() - Date.now())\n\n return function () {\n clearTimeout(id)\n }\n }\n\n useEffect(expirationHandler, [expiresAt])\n\n function subscribeHandler() {\n function onMutating() {\n setIsMutating(true)\n }\n\n function onMutated() {\n setIsMutating(false)\n setExpiresAt(expiration(key) ?? new Date())\n }\n\n function onHydrated() {\n setExpiresAt(expiration(key) ?? new Date())\n }\n\n function onResolved() {\n setExpiresAt(expiration(key) ?? new Date())\n setIsRefetching(false)\n }\n\n function onForgotten() {\n setExpiresAt(expiration(key) ?? new Date())\n }\n\n function onRefetching() {\n setIsRefetching(true)\n }\n\n function onError() {\n setIsRefetching(false)\n setIsMutating(false)\n }\n\n const unsubscribeMutating = subscribe(key, 'mutating', onMutating)\n const unsubscribeMutated = subscribe(key, 'mutated', onMutated)\n const unsubscribeHydrated = subscribe(key, 'hydrated', onHydrated)\n const unsubscribeResolved = subscribe(key, 'resolved', onResolved)\n const unsubscribeForgotten = subscribe(key, 'forgotten', onForgotten)\n const unsubscribeRefetching = subscribe(key, 'refetching', onRefetching)\n const unsubscribeError = subscribe(key, 'error', onError)\n\n return function () {\n unsubscribeMutating()\n unsubscribeMutated()\n unsubscribeHydrated()\n unsubscribeResolved()\n unsubscribeForgotten()\n unsubscribeRefetching()\n unsubscribeError()\n }\n }\n\n useEffect(subscribeHandler, [key, subscribe, expiration, setExpiresAt])\n\n return { expiresAt, isExpired, isRefetching, isMutating }\n}\n","import { useEffect, use, useState, useMemo, useDebugValue, useTransition, useRef } from 'react'\nimport { ContextOptions as ContextOptions } from 'query/react:context'\nimport { Options } from 'query:index'\nimport { useQueryContext } from './useQueryContext'\nimport { QueryInstance, useQueryInstance } from './useQueryInstance'\nimport { useQueryTransitionContext } from './useQueryTransitionContext'\nimport { QueryActions, useQueryActions } from './useQueryActions'\nimport { useQueryStatus, type Status } from './useQueryStatus'\n\ntype AdditionalHooks<T> = QueryActions<T> & Status\n\nexport interface Resource<T = unknown> extends AdditionalHooks<T> {\n data: T\n isPending: boolean\n}\n\nexport type ResourceOptions<T = unknown> = ContextOptions & Options<T> & QueryInstance\n\nexport function useQuery<T = unknown>(key: string, options?: ResourceOptions<T>): Resource<T> {\n useDebugValue('useQuery')\n\n const { additional } = useQueryContext()\n\n const { isPending: isContextPending, startTransition: startContextTransition } =\n useQueryTransitionContext()\n\n const [isLocalPending, startLocalTransition] = useTransition()\n const { query, expiration, subscribe } = useQueryInstance(options)\n\n function ignoreTransitionContextHandler() {\n return options?.ignoreTransitionContext ?? additional?.ignoreTransitionContext ?? false\n }\n\n const ignoreTransitionContext = useMemo(ignoreTransitionContextHandler, [options, additional])\n\n function isPendingHandler() {\n if (ignoreTransitionContext) {\n return isLocalPending\n }\n\n return isContextPending ?? isLocalPending\n }\n\n const isPending = useMemo(isPendingHandler, [\n isContextPending,\n isLocalPending,\n ignoreTransitionContext,\n ])\n\n function startTransitionHandler() {\n if (ignoreTransitionContext) {\n return startLocalTransition\n }\n\n return startContextTransition ?? startLocalTransition\n }\n\n const startTransition = useMemo(startTransitionHandler, [\n startContextTransition,\n startLocalTransition,\n ignoreTransitionContext,\n ])\n\n function clearOnForgetHandler() {\n return options?.clearOnForget ?? additional?.clearOnForget ?? false\n }\n\n const clearOnForget = useMemo(clearOnForgetHandler, [options, additional])\n\n async function promiseHandler() {\n return await query<T>(key, options)\n }\n\n const promise = useMemo(promiseHandler, [query, key, options])\n const initial = useRef<T>(undefined)\n\n if (initial.current === undefined) {\n initial.current = use(promise)\n }\n\n const [data, setData] = useState(initial.current)\n\n function subscribeHandler() {\n function onResolved(event: Event) {\n startTransition(function () {\n setData((event as CustomEvent<T>).detail)\n })\n }\n\n function onMutating(event: Event) {\n startTransition(async function () {\n const value = await (event as CustomEvent<Promise<T>>).detail\n\n startTransition(function () {\n setData(value)\n })\n })\n }\n\n function onMutated(event: Event) {\n startTransition(function () {\n setData((event as CustomEvent<T>).detail)\n })\n }\n\n function onHydrated(event: Event) {\n startTransition(function () {\n setData((event as CustomEvent<T>).detail)\n })\n }\n\n function onRefetching(event: Event) {\n startTransition(async function () {\n const value = await (event as CustomEvent<Promise<T>>).detail\n\n startTransition(function () {\n setData(value)\n })\n })\n }\n\n function onForgotten() {\n if (clearOnForget) {\n startTransition(async function () {\n const data = await query<T>(key, options)\n\n startTransition(function () {\n setData(data)\n })\n })\n }\n }\n\n const unsubscribeResolved = subscribe(key, 'resolved', onResolved)\n const unsubscribeMutating = subscribe(key, 'mutating', onMutating)\n const unsubscribeMutated = subscribe(key, 'mutated', onMutated)\n const unsubscribeHydrated = subscribe(key, 'hydrated', onHydrated)\n const unsubscribeRefetching = subscribe(key, 'refetching', onRefetching)\n const unsubscribeForgotten = subscribe(key, 'forgotten', onForgotten)\n\n return function () {\n unsubscribeResolved()\n unsubscribeMutating()\n unsubscribeMutated()\n unsubscribeHydrated()\n unsubscribeRefetching()\n unsubscribeForgotten()\n }\n }\n\n useEffect(subscribeHandler, [\n query,\n expiration,\n subscribe,\n key,\n clearOnForget,\n options,\n startTransition,\n ])\n\n const actions = useQueryActions<T>(key, options)\n const status = useQueryStatus(key)\n\n function resourceHandler(): Resource<T> {\n return { data, isPending, ...actions, ...status }\n }\n\n return useMemo(resourceHandler, [data, isPending, actions, status])\n}\n","import { useEffect, useMemo, useState, type ReactNode } from 'react'\nimport { Context, ContextValue, type ContextOptions } from 'query/react:context'\nimport { createQuery, Query, type Configuration } from 'query:index'\n\ntype OtherProps = Configuration & ContextOptions\n\nexport interface QueryProviderProps extends OtherProps {\n children?: ReactNode\n}\n\nexport function QueryProvider({\n children,\n clearOnForget,\n broadcast,\n ...options\n}: QueryProviderProps) {\n function initial() {\n return createQuery({ broadcast, ...options })\n }\n\n const [query] = useState<Query>(initial)\n\n function reconfigure() {\n query.configure(options)\n }\n\n useEffect(reconfigure, [query, options])\n\n function broadcastCleanup() {\n if (broadcast) {\n query.configure({ broadcast })\n const unsubscribe = query.subscribeBroadcast()\n\n return function () {\n unsubscribe()\n }\n }\n\n const channel = new BroadcastChannel('query')\n\n query.configure({ broadcast: channel })\n const unsubscribe = query.subscribeBroadcast()\n\n return function () {\n unsubscribe()\n channel.close()\n }\n }\n\n useEffect(broadcastCleanup, [query, broadcast])\n\n function additionalHandler() {\n return { clearOnForget }\n }\n\n const additional = useMemo(additionalHandler, [clearOnForget])\n\n function valueHandler(): ContextValue {\n return { query, additional }\n }\n\n const value = useMemo(valueHandler, [query, additional])\n\n return <Context value={value}>{children}</Context>\n}\n","import { TransitionContext, QueryTransitionContextValue } from 'query/react:transition'\nimport { useMemo, type ReactNode, type TransitionStartFunction } from 'react'\n\nexport interface QueryTransitionProps {\n isPending: boolean\n startTransition: TransitionStartFunction\n children?: ReactNode\n}\n\nexport function QueryTransition({ children, startTransition, isPending }: QueryTransitionProps) {\n function valueHandler(): QueryTransitionContextValue {\n return { startTransition, isPending }\n }\n\n const value = useMemo(valueHandler, [startTransition, isPending])\n\n return <TransitionContext value={value}>{children}</TransitionContext>\n}\n"],"names":["Context","createContext","useQueryContext","useDebugValue","use","useQueryInstance","options","contextOptions","query","instance","useMemo","TransitionContext","useQueryTransitionContext","useQueryActions","key","mutate","forget","refetchHandler","refetchOptions","refetch","useCallback","mutateHandler","value","localMutate","forgetHandler","localForget","actionsHandler","useQueryStatus","expiration","subscribe","expiresAt","setExpiresAt","useState","isExpired","setIsExpired","isRefetching","setIsRefetching","isMutating","setIsMutating","expirationHandler","handler","id","useEffect","subscribeHandler","onMutating","onMutated","onHydrated","onResolved","onForgotten","onRefetching","onError","unsubscribeMutating","unsubscribeMutated","unsubscribeHydrated","unsubscribeResolved","unsubscribeForgotten","unsubscribeRefetching","unsubscribeError","useQuery","additional","isContextPending","startContextTransition","isLocalPending","startLocalTransition","useTransition","ignoreTransitionContextHandler","ignoreTransitionContext","isPendingHandler","isPending","startTransitionHandler","startTransition","clearOnForgetHandler","clearOnForget","promiseHandler","promise","initial","useRef","data","setData","event","actions","status","resourceHandler","QueryProvider","children","broadcast","createQuery","reconfigure","broadcastCleanup","unsubscribe","channel","additionalHandler","valueHandler","jsx","QueryTransition"],"mappings":";;;AAaO,MAAMA,IAAUC,EAA4B;AAAA,EACjD,OAAO;AAAA,EACP,YAAY;AACd,CAAC;ACbM,SAASC,IAAgC;AAC9C,SAAAC,EAAc,iBAAiB,GAExBC,EAAIJ,CAAO;AACpB;ACCO,SAASK,EAAiBC,GAAgC;AAC/D,EAAAH,EAAc,kBAAkB;AAEhC,QAAMI,IAAiBL,EAAgB;AAEvC,WAASM,IAAQ;AACT,UAAAC,KAAWH,KAAA,gBAAAA,EAAS,UAASC,EAAe;AAElD,QAAI,CAACE;AACH,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAGK,WAAAA;AAAA,EAAA;AAGT,SAAOC,EAAQF,GAAO,CAACF,GAASC,CAAc,CAAC;AACjD;ACnBO,MAAMI,IAAoBV,EAA2C;AAAA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determines the shape of the Cache instance.
|
|
3
|
+
*/
|
|
4
|
+
export interface Cache<T = unknown> {
|
|
5
|
+
/**
|
|
6
|
+
* Gets an item from the cache.
|
|
7
|
+
*/
|
|
8
|
+
readonly get: (key: string) => T | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* Sets an item to the cache.
|
|
11
|
+
*/
|
|
12
|
+
readonly set: (key: string, value: T) => void;
|
|
13
|
+
/**
|
|
14
|
+
* Removes a key-value pair from the cache.
|
|
15
|
+
*/
|
|
16
|
+
readonly delete: (key: string) => void;
|
|
17
|
+
/**
|
|
18
|
+
* Returns the current cached keys.
|
|
19
|
+
*/
|
|
20
|
+
readonly keys: () => IterableIterator<string>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Determines how we store items in the items cache.
|
|
24
|
+
*/
|
|
25
|
+
interface ItemsCacheItem<T = unknown> {
|
|
26
|
+
/**
|
|
27
|
+
* Stores the cache item.
|
|
28
|
+
*/
|
|
29
|
+
readonly item: T;
|
|
30
|
+
/**
|
|
31
|
+
* Determines the expiration date of the item.
|
|
32
|
+
*/
|
|
33
|
+
readonly expiresAt: Date;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Determines how we store items in the resolvers cache.
|
|
37
|
+
*/
|
|
38
|
+
interface ResolversCacheItem<T> {
|
|
39
|
+
/**
|
|
40
|
+
* The resolvable item.
|
|
41
|
+
*/
|
|
42
|
+
readonly item: Promise<T>;
|
|
43
|
+
/**
|
|
44
|
+
* The abort controller for the request.
|
|
45
|
+
*/
|
|
46
|
+
readonly controller: AbortController;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Represents the available configuration options
|
|
50
|
+
* for a query instance.
|
|
51
|
+
*/
|
|
52
|
+
export interface Configuration extends Options {
|
|
53
|
+
/**
|
|
54
|
+
* Determines the resolved items cache to use.
|
|
55
|
+
*/
|
|
56
|
+
readonly itemsCache?: Cache<ItemsCacheItem>;
|
|
57
|
+
/**
|
|
58
|
+
* Determines the resolvers cache to use.
|
|
59
|
+
*/
|
|
60
|
+
readonly resolversCache?: Cache<ResolversCacheItem<unknown>>;
|
|
61
|
+
/**
|
|
62
|
+
* Stores the event system.
|
|
63
|
+
*/
|
|
64
|
+
readonly events?: EventTarget;
|
|
65
|
+
/**
|
|
66
|
+
* Broadcast channel. This is useful for communicating
|
|
67
|
+
* between tabs and windows (browser contexts).
|
|
68
|
+
*
|
|
69
|
+
* By default it does not use any broadcast channel.
|
|
70
|
+
* If a broadcast channel is provided, query
|
|
71
|
+
* won't close automatically, therefore, the responsability
|
|
72
|
+
* of closing the broadcast channel is up to the user.
|
|
73
|
+
*/
|
|
74
|
+
readonly broadcast?: BroadcastChannel;
|
|
75
|
+
}
|
|
76
|
+
export interface FetcherAdditional {
|
|
77
|
+
/**
|
|
78
|
+
* An abort signal to cancel pending queries.
|
|
79
|
+
*/
|
|
80
|
+
readonly signal: AbortSignal;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The available options for query.
|
|
84
|
+
*/
|
|
85
|
+
export interface Options<T = unknown> {
|
|
86
|
+
/**
|
|
87
|
+
* Determines the item deduplication interval.
|
|
88
|
+
* This determines how many milliseconds an item
|
|
89
|
+
* is considered valid.
|
|
90
|
+
*/
|
|
91
|
+
readonly expiration?: ExpirationFunction<T>;
|
|
92
|
+
/**
|
|
93
|
+
* Determines the fetcher function to use.
|
|
94
|
+
*/
|
|
95
|
+
readonly fetcher?: FetcherFunction<T>;
|
|
96
|
+
/**
|
|
97
|
+
* Determines if we can return a stale item.
|
|
98
|
+
* If `true`, it will return the previous stale item
|
|
99
|
+
* stored in the cache if it has expired. It will attempt
|
|
100
|
+
* to revalidate it in the background. If `false`, the returned
|
|
101
|
+
* promise will be the revalidation promise.
|
|
102
|
+
*/
|
|
103
|
+
readonly stale?: boolean;
|
|
104
|
+
/**
|
|
105
|
+
* Removes the stored item if there is an error in the request.
|
|
106
|
+
* By default, we don't remove the item upon failure, only the resolver
|
|
107
|
+
* is removed from the cache.
|
|
108
|
+
*/
|
|
109
|
+
readonly removeOnError?: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Determines if the result should be a fresh fetched
|
|
112
|
+
* instance regardless of any cached value or its expiration time.
|
|
113
|
+
*/
|
|
114
|
+
readonly fresh?: boolean;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Determines the cache type.
|
|
118
|
+
*/
|
|
119
|
+
export type CacheType = 'resolvers' | 'items';
|
|
120
|
+
/**
|
|
121
|
+
* The mutation function type.
|
|
122
|
+
*/
|
|
123
|
+
export interface MutationFunction<T> {
|
|
124
|
+
(previous?: T, expiresAt?: Date): T | Promise<T>;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* The available mutation values.
|
|
128
|
+
*/
|
|
129
|
+
export type MutationValue<T> = T | MutationFunction<T>;
|
|
130
|
+
/**
|
|
131
|
+
* The function type for the event subscription.
|
|
132
|
+
*/
|
|
133
|
+
export interface SubscribeFunction {
|
|
134
|
+
(key: string, event: QueryEvent, listener: EventListener): Unsubscriber;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* The broadcast payload.
|
|
138
|
+
*/
|
|
139
|
+
export interface BroadcastPayload {
|
|
140
|
+
/**
|
|
141
|
+
* The event name.
|
|
142
|
+
*/
|
|
143
|
+
readonly event: string;
|
|
144
|
+
/**
|
|
145
|
+
* The event detail.
|
|
146
|
+
*/
|
|
147
|
+
readonly detail: unknown;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* The function type for the broadcast subscription.
|
|
151
|
+
*/
|
|
152
|
+
export interface SubscribeBroadcastFunction {
|
|
153
|
+
(): Unsubscriber;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* The query function type.
|
|
157
|
+
*/
|
|
158
|
+
export interface QueryFunction {
|
|
159
|
+
<T = unknown>(key: string, options?: Options<T>): Promise<T>;
|
|
160
|
+
}
|
|
161
|
+
export interface ExpirationFunction<T = unknown> {
|
|
162
|
+
(item: T): number;
|
|
163
|
+
}
|
|
164
|
+
export interface FetcherFunction<T = unknown> {
|
|
165
|
+
(key: string, additional: FetcherAdditional): Promise<T>;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* The mutate function options.
|
|
169
|
+
*/
|
|
170
|
+
export interface HydrateOptions<T = unknown> {
|
|
171
|
+
expiration?: ExpirationFunction<T>;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* The mutate function options.
|
|
175
|
+
*/
|
|
176
|
+
export interface MutateOptions<T = unknown> {
|
|
177
|
+
expiration?: ExpirationFunction<T>;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* The mutate function type.
|
|
181
|
+
*/
|
|
182
|
+
export interface MutateFunction {
|
|
183
|
+
<T = unknown>(key: string, item: MutationValue<T>, options?: MutateOptions<T>): Promise<T>;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The hydrate function type.
|
|
187
|
+
*/
|
|
188
|
+
export interface HydrateFunction {
|
|
189
|
+
<T = unknown>(keys: string | string[], item: T, options?: HydrateOptions<T>): void;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* The unsubscriber function.
|
|
193
|
+
*/
|
|
194
|
+
export type Unsubscriber = () => void;
|
|
195
|
+
/**
|
|
196
|
+
* The caches available on the query.
|
|
197
|
+
*/
|
|
198
|
+
export interface Caches {
|
|
199
|
+
/**
|
|
200
|
+
* A cache that contains the resolved items alongside
|
|
201
|
+
* their expiration time.
|
|
202
|
+
*/
|
|
203
|
+
readonly items: Cache<ItemsCacheItem>;
|
|
204
|
+
/**
|
|
205
|
+
* A cache that contains the resolvers alongside
|
|
206
|
+
* their abort controllers.
|
|
207
|
+
*/
|
|
208
|
+
readonly resolvers: Cache<ResolversCacheItem<unknown>>;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Represents the methods a query
|
|
212
|
+
* should implement.
|
|
213
|
+
*/
|
|
214
|
+
export interface Query {
|
|
215
|
+
/**
|
|
216
|
+
* Configures the current instance of query.
|
|
217
|
+
*/
|
|
218
|
+
readonly configure: (options?: Partial<Configuration>) => void;
|
|
219
|
+
/**
|
|
220
|
+
* Fetches the key information using a fetcher.
|
|
221
|
+
* The returned promise contains the result item.
|
|
222
|
+
*/
|
|
223
|
+
readonly query: QueryFunction;
|
|
224
|
+
/**
|
|
225
|
+
* Subscribes to a given event & key. The event handler
|
|
226
|
+
* does have a payload parameter that will contain relevant
|
|
227
|
+
* information depending on the event type.
|
|
228
|
+
*/
|
|
229
|
+
readonly subscribe: SubscribeFunction;
|
|
230
|
+
/**
|
|
231
|
+
* Subscribes to the broadcast channel
|
|
232
|
+
* to listen for other browser context
|
|
233
|
+
* events and reproduce them in the current
|
|
234
|
+
* context.
|
|
235
|
+
*/
|
|
236
|
+
readonly subscribeBroadcast: SubscribeBroadcastFunction;
|
|
237
|
+
/**
|
|
238
|
+
* Mutates the key with a given optimistic value.
|
|
239
|
+
* The mutated value is considered expired and will be
|
|
240
|
+
* replaced immediatly if a refetch happens.
|
|
241
|
+
*/
|
|
242
|
+
readonly mutate: MutateFunction;
|
|
243
|
+
/**
|
|
244
|
+
* Aborts the active resolvers on each key
|
|
245
|
+
* by calling `.abort()` on the `AbortController`.
|
|
246
|
+
* The fetcher is responsible for using the
|
|
247
|
+
* `AbortSignal` to cancel the job.
|
|
248
|
+
*/
|
|
249
|
+
readonly abort: (key?: string | string[], reason?: unknown) => void;
|
|
250
|
+
/**
|
|
251
|
+
* Forgets the given keys from the cache.
|
|
252
|
+
* Removes items from both, the cache and resolvers.
|
|
253
|
+
*/
|
|
254
|
+
readonly forget: (keys?: string | string[] | RegExp) => void;
|
|
255
|
+
/**
|
|
256
|
+
* Hydrates the given keys on the cache
|
|
257
|
+
* with the given value and expiration time.
|
|
258
|
+
*/
|
|
259
|
+
readonly hydrate: HydrateFunction;
|
|
260
|
+
/**
|
|
261
|
+
* Returns the given keys for the given cache.
|
|
262
|
+
*/
|
|
263
|
+
readonly keys: (cache?: CacheType) => string[];
|
|
264
|
+
/**
|
|
265
|
+
* Returns the expiration date of a given key item.
|
|
266
|
+
* If the item is not in the cache, it will return `undefined`.
|
|
267
|
+
*/
|
|
268
|
+
readonly expiration: (key: string) => Date | undefined;
|
|
269
|
+
/**
|
|
270
|
+
* Returns the current snapshot of the given key.
|
|
271
|
+
* If the item is not in the items cache, it will return `undefined`.
|
|
272
|
+
*/
|
|
273
|
+
readonly snapshot: <T = unknown>(key: string) => T | undefined;
|
|
274
|
+
/**
|
|
275
|
+
* Returns the current cache instances in use.
|
|
276
|
+
*/
|
|
277
|
+
readonly caches: () => Caches;
|
|
278
|
+
/**
|
|
279
|
+
* Returns the event system in use.
|
|
280
|
+
*/
|
|
281
|
+
readonly events: () => EventTarget;
|
|
282
|
+
/**
|
|
283
|
+
* Returns the broadcast channel in use.
|
|
284
|
+
*/
|
|
285
|
+
readonly broadcast: () => BroadcastChannel | undefined;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Available events on query.
|
|
289
|
+
*/
|
|
290
|
+
export type QueryEvent = 'refetching' | 'resolved' | 'mutating' | 'mutated' | 'aborted' | 'forgotten' | 'hydrated' | 'error';
|
|
291
|
+
/**
|
|
292
|
+
* Stores the default fetcher function.
|
|
293
|
+
*/
|
|
294
|
+
export declare function defaultFetcher<T>(fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>): FetcherFunction<T>;
|
|
295
|
+
/**
|
|
296
|
+
* Creates a new query instance.
|
|
297
|
+
*/
|
|
298
|
+
export declare function createQuery(instanceOptions?: Configuration): Query;
|
|
299
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { ReactNode } from 'react';
|
|
2
|
+
import { ContextOptions } from '../context';
|
|
3
|
+
import { Configuration } from '../../query/index';
|
|
4
|
+
type OtherProps = Configuration & ContextOptions;
|
|
5
|
+
export interface QueryProviderProps extends OtherProps {
|
|
6
|
+
children?: ReactNode;
|
|
7
|
+
}
|
|
8
|
+
export declare function QueryProvider({ children, clearOnForget, broadcast, ...options }: QueryProviderProps): import("react/jsx-runtime").JSX.Element;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { ReactNode, TransitionStartFunction } from 'react';
|
|
2
|
+
export interface QueryTransitionProps {
|
|
3
|
+
isPending: boolean;
|
|
4
|
+
startTransition: TransitionStartFunction;
|
|
5
|
+
children?: ReactNode;
|
|
6
|
+
}
|
|
7
|
+
export declare function QueryTransition({ children, startTransition, isPending }: QueryTransitionProps): import("react/jsx-runtime").JSX.Element;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Query } from '../query/index';
|
|
2
|
+
export interface ContextOptions {
|
|
3
|
+
readonly clearOnForget?: boolean;
|
|
4
|
+
readonly ignoreTransitionContext?: boolean;
|
|
5
|
+
}
|
|
6
|
+
export interface ContextValue {
|
|
7
|
+
readonly query?: Query;
|
|
8
|
+
readonly additional?: ContextOptions;
|
|
9
|
+
}
|
|
10
|
+
export declare const Context: import('react').Context<ContextValue>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { ContextOptions as ContextOptions } from '../context';
|
|
2
|
+
import { Options } from '../../query/index';
|
|
3
|
+
import { QueryInstance } from './useQueryInstance';
|
|
4
|
+
import { QueryActions } from './useQueryActions';
|
|
5
|
+
import { Status } from './useQueryStatus';
|
|
6
|
+
type AdditionalHooks<T> = QueryActions<T> & Status;
|
|
7
|
+
export interface Resource<T = unknown> extends AdditionalHooks<T> {
|
|
8
|
+
data: T;
|
|
9
|
+
isPending: boolean;
|
|
10
|
+
}
|
|
11
|
+
export type ResourceOptions<T = unknown> = ContextOptions & Options<T> & QueryInstance;
|
|
12
|
+
export declare function useQuery<T = unknown>(key: string, options?: ResourceOptions<T>): Resource<T>;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { MutateOptions, MutationValue, Options } from '../../query/index';
|
|
2
|
+
import { QueryInstance } from './useQueryInstance';
|
|
3
|
+
export interface QueryActions<T = unknown> {
|
|
4
|
+
readonly refetch: (refetchOptions?: Options<T>) => Promise<T>;
|
|
5
|
+
readonly mutate: (value: MutationValue<T>, options?: MutateOptions<T>) => Promise<T>;
|
|
6
|
+
readonly forget: () => void;
|
|
7
|
+
}
|
|
8
|
+
export type QueryActionsOptions<T = unknown> = Options<T> & QueryInstance;
|
|
9
|
+
export declare function useQueryActions<T = unknown>(key: string, options?: QueryActionsOptions<T>): QueryActions<T>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export * from './hooks/useQuery';
|
|
2
|
+
export * from './hooks/useQueryStatus';
|
|
3
|
+
export * from './hooks/useQueryInstance';
|
|
4
|
+
export * from './hooks/useQueryContext';
|
|
5
|
+
export * from './hooks/useQueryTransitionContext';
|
|
6
|
+
export * from './hooks/useQueryActions';
|
|
7
|
+
export * from './context';
|
|
8
|
+
export * from './transition';
|
|
9
|
+
export * from './components/QueryProvider';
|
|
10
|
+
export * from './components/QueryTransition';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { TransitionStartFunction } from 'react';
|
|
2
|
+
export interface QueryTransitionContextValue {
|
|
3
|
+
readonly isPending?: boolean;
|
|
4
|
+
readonly startTransition?: TransitionStartFunction;
|
|
5
|
+
}
|
|
6
|
+
export declare const TransitionContext: import('react').Context<QueryTransitionContextValue>;
|
package/package.json
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@studiolambda/query",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "Lightweight, isomorphic and framework agnostic asynchronous data management for modern UIs",
|
|
6
|
+
"author": {
|
|
7
|
+
"name": "Erik C. Forés",
|
|
8
|
+
"email": "soc@erik.cat",
|
|
9
|
+
"url": "https://erik.cat"
|
|
10
|
+
},
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=18.0.0"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"types": "./dist/src/query/index.d.ts",
|
|
16
|
+
"main": "./dist/query.cjs",
|
|
17
|
+
"module": "./dist/query.js",
|
|
18
|
+
"exports": {
|
|
19
|
+
"./package.json": "./package.json",
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/src/query/index.d.ts",
|
|
22
|
+
"import": "./dist/query.js",
|
|
23
|
+
"require": "./dist/query.cjs"
|
|
24
|
+
},
|
|
25
|
+
"./react": {
|
|
26
|
+
"types": "./dist/src/react/index.d.ts",
|
|
27
|
+
"import": "./dist/query_react.js",
|
|
28
|
+
"require": "./dist/query_react.cjs"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"package.json"
|
|
34
|
+
],
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "vite build",
|
|
37
|
+
"dev": "vitest",
|
|
38
|
+
"test": "vitest run",
|
|
39
|
+
"test:ui": "vitest --ui --coverage",
|
|
40
|
+
"test:cover": "vitest run --coverage",
|
|
41
|
+
"prepack": "npm run build"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"react": "^19.0.0",
|
|
45
|
+
"react-dom": "^19.0.0",
|
|
46
|
+
"solid-js": "^1.9.0"
|
|
47
|
+
},
|
|
48
|
+
"peerDependenciesMeta": {
|
|
49
|
+
"react": {
|
|
50
|
+
"optional": true
|
|
51
|
+
},
|
|
52
|
+
"react-dom": {
|
|
53
|
+
"optional": true
|
|
54
|
+
},
|
|
55
|
+
"solid-js": {
|
|
56
|
+
"optional": true
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@types/node": "^22.10.2",
|
|
61
|
+
"@types/react": "19.0.1",
|
|
62
|
+
"@types/react-dom": "19.0.2",
|
|
63
|
+
"@typescript-eslint/eslint-plugin": "^8.18.0",
|
|
64
|
+
"@typescript-eslint/parser": "^8.18.0",
|
|
65
|
+
"@vitejs/plugin-react": "^4.3.4",
|
|
66
|
+
"@vitest/coverage-v8": "^2.1.8",
|
|
67
|
+
"@vitest/ui": "^2.1.8",
|
|
68
|
+
"eslint": "^9.16.0",
|
|
69
|
+
"eslint-plugin-react-hooks": "^5.1.0",
|
|
70
|
+
"eslint-plugin-react-refresh": "^0.4.16",
|
|
71
|
+
"eslint-plugin-solid": "^0.14.5",
|
|
72
|
+
"globals": "^15.13.0",
|
|
73
|
+
"happy-dom": "^15.11.7",
|
|
74
|
+
"react": "^19.0.0",
|
|
75
|
+
"react-dom": "^19.0.0",
|
|
76
|
+
"solid-js": "^1.9.3",
|
|
77
|
+
"typescript": "^5.7.2",
|
|
78
|
+
"typescript-eslint": "^8.18.0",
|
|
79
|
+
"vite": "^6.0.3",
|
|
80
|
+
"vite-plugin-dts": "^4.3.0",
|
|
81
|
+
"vite-plugin-solid": "^2.11.0",
|
|
82
|
+
"vitest": "^2.1.8"
|
|
83
|
+
}
|
|
84
|
+
}
|