@mmstack/resource 19.6.0 → 19.6.2
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/README.md +132 -20
- package/fesm2022/mmstack-resource.mjs +691 -189
- package/fesm2022/mmstack-resource.mjs.map +1 -1
- package/index.d.ts +1 -0
- package/lib/infinite-query.d.ts +81 -0
- package/lib/mutation-resource.d.ts +20 -1
- package/lib/options.d.ts +5 -6
- package/lib/query-resource.d.ts +47 -5
- package/lib/util/cache/cache-interceptor.d.ts +4 -0
- package/lib/util/cache/cache.d.ts +60 -6
- package/lib/util/cache/index.d.ts +1 -1
- package/lib/util/cache/public_api.d.ts +1 -1
- package/lib/util/dedupe-interceptor.d.ts +6 -0
- package/lib/util/hash-request.d.ts +9 -2
- package/lib/util/refresh.d.ts +31 -3
- package/lib/util/sensors.d.ts +2 -0
- package/lib/util/share-pending.d.ts +12 -0
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { type HttpResourceRequest } from '@angular/common/http';
|
|
2
|
+
import { type Signal } from '@angular/core';
|
|
3
|
+
import { type PAUSED, type QueryResourceOptions, type QueryResourceRef, type RequestContext } from './query-resource';
|
|
4
|
+
/**
|
|
5
|
+
* Context passed to an infinite query's request fn: the {@link RequestContext}
|
|
6
|
+
* (so the fn can return `ctx.paused` to pause the resource, exactly like
|
|
7
|
+
* `queryResource`) plus the `pageParam` addressing the page to load.
|
|
8
|
+
*/
|
|
9
|
+
export type InfiniteRequestContext<TPageParam> = RequestContext & {
|
|
10
|
+
pageParam: TPageParam;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Options for {@link infiniteQueryResource}. Extends {@link QueryResourceOptions}
|
|
14
|
+
* (minus `defaultValue` — the aggregate value is always the `pages` array) with the
|
|
15
|
+
* pagination contract.
|
|
16
|
+
*/
|
|
17
|
+
export type InfiniteQueryResourceOptions<TPage, TRaw = TPage, TPageParam = unknown> = Omit<QueryResourceOptions<TPage, TRaw>, 'defaultValue'> & {
|
|
18
|
+
/** The page param the FIRST page is requested with (e.g. `0`, `1`, or a cursor seed). */
|
|
19
|
+
initialPageParam: TPageParam;
|
|
20
|
+
/**
|
|
21
|
+
* Derives the NEXT page's param from the freshly loaded page (and all pages so far).
|
|
22
|
+
* Return `null`/`undefined` to signal "no more pages" — `hasNextPage` flips false
|
|
23
|
+
* and `fetchNextPage()` becomes a no-op.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* // cursor-based
|
|
27
|
+
* getNextPageParam: (last) => last.nextCursor;
|
|
28
|
+
* // offset-based
|
|
29
|
+
* getNextPageParam: (last, all) => (last.items.length < PAGE_SIZE ? null : all.length);
|
|
30
|
+
*/
|
|
31
|
+
getNextPageParam: (lastPage: NoInfer<TPage>, allPages: NoInfer<TPage>[]) => TPageParam | null | undefined;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* A paginated query resource. `pages` accumulates every loaded page in order;
|
|
35
|
+
* `fetchNextPage()` loads the next one (no-op while one is in flight or when
|
|
36
|
+
* exhausted). Inherits the underlying query's `status`/`error`/`isLoading` and
|
|
37
|
+
* its features (cache, retry, circuit breaker, refresh).
|
|
38
|
+
*/
|
|
39
|
+
export type InfiniteQueryResourceRef<TPage> = {
|
|
40
|
+
/** Every page loaded so far, in load order. */
|
|
41
|
+
pages: Signal<TPage[]>;
|
|
42
|
+
/** `true` once the first page is in and `getNextPageParam` keeps producing params. */
|
|
43
|
+
hasNextPage: Signal<boolean>;
|
|
44
|
+
/** `true` while a page request beyond the first is in flight. */
|
|
45
|
+
isFetchingNextPage: Signal<boolean>;
|
|
46
|
+
/** The underlying query's loading state (first page + subsequent pages). */
|
|
47
|
+
isLoading: Signal<boolean>;
|
|
48
|
+
status: QueryResourceRef<TPage | undefined>['status'];
|
|
49
|
+
error: QueryResourceRef<TPage | undefined>['error'];
|
|
50
|
+
/** Loads the next page. No-op while loading or when `hasNextPage()` is false. */
|
|
51
|
+
fetchNextPage: () => void;
|
|
52
|
+
/** Reloads the CURRENT page param — the freshly loaded page replaces its slot. */
|
|
53
|
+
reload: () => boolean;
|
|
54
|
+
/** Drops all pages and refetches from `initialPageParam`. */
|
|
55
|
+
reset: () => void;
|
|
56
|
+
destroy: () => void;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Creates a paginated HTTP resource over {@link queryResource}: one page request at a
|
|
60
|
+
* time, accumulated into a `pages` signal — cursor- and offset-based pagination both
|
|
61
|
+
* fit through `getNextPageParam`. Each page request inherits the full queryResource
|
|
62
|
+
* feature set (caching per page, retries, circuit breaker, refresh triggers).
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```ts
|
|
66
|
+
* const posts = infiniteQueryResource<PostPage, PostPage, number>(
|
|
67
|
+
* ({ pageParam }) => ({ url: '/api/posts', params: { page: pageParam } }),
|
|
68
|
+
* {
|
|
69
|
+
* initialPageParam: 0,
|
|
70
|
+
* getNextPageParam: (last, all) => (last.items.length < 20 ? null : all.length),
|
|
71
|
+
* cache: true,
|
|
72
|
+
* },
|
|
73
|
+
* );
|
|
74
|
+
*
|
|
75
|
+
* // template:
|
|
76
|
+
* // @for (page of posts.pages(); track $index) { ... }
|
|
77
|
+
* // <button (click)="posts.fetchNextPage()" [disabled]="!posts.hasNextPage()">More</button>
|
|
78
|
+
* const flat = computed(() => posts.pages().flatMap((p) => p.items));
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
export declare function infiniteQueryResource<TPage, TRaw = TPage, TPageParam = unknown>(request: (ctx: InfiniteRequestContext<TPageParam>) => HttpResourceRequest | string | undefined | typeof PAUSED, options: InfiniteQueryResourceOptions<TPage, TRaw, TPageParam>): InfiniteQueryResourceRef<TPage>;
|
|
@@ -36,7 +36,7 @@ type NextRequest<TMethod extends HttpResourceRequest['method'], TMutation> = TMe
|
|
|
36
36
|
* };
|
|
37
37
|
* ```
|
|
38
38
|
*/
|
|
39
|
-
export type MutationResourceOptions<TResult, TRaw = TResult, TMutation = TResult, TCTX = void, TICTX = TCTX, TError = unknown> = Omit<QueryResourceOptions<TResult, TRaw>, 'equal' | 'onError' | 'keepPrevious' | 'refresh' | 'cache'> & {
|
|
39
|
+
export type MutationResourceOptions<TResult, TRaw = TResult, TMutation = TResult, TCTX = void, TICTX = TCTX, TError = unknown> = Omit<QueryResourceOptions<TResult, TRaw>, 'equal' | 'onError' | 'keepPrevious' | 'refresh' | 'cache' | 'pause'> & {
|
|
40
40
|
/**
|
|
41
41
|
* A callback function that is called before the mutation request is made.
|
|
42
42
|
* @param value The value being mutated (the `body` of the request).
|
|
@@ -66,6 +66,25 @@ export type MutationResourceOptions<TResult, TRaw = TResult, TMutation = TResult
|
|
|
66
66
|
* @default false
|
|
67
67
|
*/
|
|
68
68
|
queue?: boolean;
|
|
69
|
+
/**
|
|
70
|
+
* Cache entries to invalidate after a SUCCESSFUL mutation — the declarative
|
|
71
|
+
* alternative to calling `injectQueryCache().invalidatePrefix(...)` in `onSuccess`.
|
|
72
|
+
*
|
|
73
|
+
* Each string is a URL prefix matched against auto-generated `GET` cache keys
|
|
74
|
+
* (`GET:${url}:...`): `'/api/posts'` invalidates `/api/posts` with any query params,
|
|
75
|
+
* plus subpaths like `/api/posts/123` — and all `varyHeaders` variants of each.
|
|
76
|
+
* Note that plain prefix matching also catches sibling paths sharing the prefix
|
|
77
|
+
* (`/api/posts-archive`); pass `'/api/posts/'` or the exact URL to narrow.
|
|
78
|
+
*
|
|
79
|
+
* Entries keyed by a custom `hash` function follow that function's shape, not the
|
|
80
|
+
* auto-key shape — invalidate those manually via `injectQueryCache().invalidateWhere`.
|
|
81
|
+
*
|
|
82
|
+
* The function form receives the mutation result and the mutated value:
|
|
83
|
+
* ```ts
|
|
84
|
+
* invalidates: (saved) => [`/api/posts`, `/api/users/${saved.authorId}`]
|
|
85
|
+
* ```
|
|
86
|
+
*/
|
|
87
|
+
invalidates?: string[] | ((value: NoInfer<TResult>, mutation: NoInfer<TMutation>) => string[]);
|
|
69
88
|
equal?: ValueEqualityFn<TMutation>;
|
|
70
89
|
};
|
|
71
90
|
/**
|
package/lib/options.d.ts
CHANGED
|
@@ -1,19 +1,18 @@
|
|
|
1
1
|
import { InjectionToken, type Injector, type Provider, type ResourceRef } from '@angular/core';
|
|
2
|
-
import { type RegisterOptions } from '@mmstack/primitives';
|
|
3
2
|
import { type CircuitBreakerOptions, type RetryOptions } from './util';
|
|
4
3
|
/**
|
|
5
4
|
* Auto-registration into the nearest transition scope, as a resource OPTION:
|
|
6
|
-
* - `
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
5
|
+
* - `'suspend'` — register as *suspending*: the boundary holds its placeholder until this
|
|
6
|
+
* resource has a value (full Suspense). The right choice for data the subtree can't render without;
|
|
7
|
+
* - `'indicator'` — register for the pending indicator + hold-stale only (does NOT block first
|
|
8
|
+
* paint). The right choice for in-region data: the boundary shows the held value with `aria-busy`;
|
|
10
9
|
* - `false` / omitted — don't register.
|
|
11
10
|
*
|
|
12
11
|
* Defaultable via `provideResourceOptions` / `provideQueryResourceOptions` and overridable
|
|
13
12
|
* (including opting out with `false`) per call — so a dev can make "all queries participate in
|
|
14
13
|
* transitions" the default and turn it off for the odd one.
|
|
15
14
|
*/
|
|
16
|
-
export type TransitionRegistration =
|
|
15
|
+
export type TransitionRegistration = false | 'indicator' | 'suspend';
|
|
17
16
|
/** Options common to every resource kind (the base layer for the options-injection system). */
|
|
18
17
|
export type CommonResourceOptions = {
|
|
19
18
|
/** Auto-registration into the nearest transition scope. */
|
package/lib/query-resource.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { type HttpHeaders, type HttpResourceOptions, type HttpResourceRef, type HttpResourceRequest } from '@angular/common/http';
|
|
2
2
|
import { type Provider, type Signal, type WritableSignal } from '@angular/core';
|
|
3
|
+
import { type PauseOption } from '@mmstack/primitives';
|
|
3
4
|
import { type CommonResourceOptions } from './options';
|
|
5
|
+
import { type RefreshOptions } from './util';
|
|
6
|
+
export { type RefreshOptions } from './util';
|
|
4
7
|
/**
|
|
5
8
|
* Options for configuring caching behavior of a `queryResource`.
|
|
6
9
|
* - `true`: Enables caching with default settings.
|
|
@@ -42,6 +45,17 @@ type ResourceCacheOptions = true | {
|
|
|
42
45
|
* @default false - By default, the cache entry is not persisted.
|
|
43
46
|
*/
|
|
44
47
|
persist?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Request headers whose values should partition the cache key — e.g.
|
|
50
|
+
* `['Authorization']` gives each user their own entries, `['Accept-Language']`
|
|
51
|
+
* separates per-language responses. Header values are one-way digested into the
|
|
52
|
+
* key (never embedded raw), so secrets don't end up in persisted/broadcast keys.
|
|
53
|
+
* Ignored when a custom `hash` function is provided (it owns the key entirely).
|
|
54
|
+
*
|
|
55
|
+
* Note: still call `cache.clear()` on logout — the previous user's entries are
|
|
56
|
+
* unreachable under the new key but linger until their TTL.
|
|
57
|
+
*/
|
|
58
|
+
varyHeaders?: string[];
|
|
45
59
|
};
|
|
46
60
|
/**
|
|
47
61
|
* Options for configuring a `queryResource`. Extends Angular's
|
|
@@ -68,10 +82,19 @@ export type QueryResourceOptions<TResult, TRaw = TResult> = HttpResourceOptions<
|
|
|
68
82
|
*/
|
|
69
83
|
keepPrevious?: boolean;
|
|
70
84
|
/**
|
|
71
|
-
*
|
|
72
|
-
*
|
|
85
|
+
* Automatic refresh behavior. A number polls every n milliseconds; the object form
|
|
86
|
+
* composes polling with event-driven triggers:
|
|
87
|
+
*
|
|
88
|
+
* ```ts
|
|
89
|
+
* refresh: 30_000 // poll every 30s
|
|
90
|
+
* refresh: { onFocus: true, onReconnect: true } // refetch on tab refocus / back-online
|
|
91
|
+
* refresh: { interval: 60_000, onFocus: true } // both
|
|
92
|
+
* ```
|
|
93
|
+
*
|
|
94
|
+
* Triggers respect the resource's disabled/paused state (no refetch while
|
|
95
|
+
* offline, circuit-open, or paused).
|
|
73
96
|
*/
|
|
74
|
-
refresh?:
|
|
97
|
+
refresh?: RefreshOptions;
|
|
75
98
|
/**
|
|
76
99
|
* Called on every failed attempt, including each retry.
|
|
77
100
|
*
|
|
@@ -87,6 +110,20 @@ export type QueryResourceOptions<TResult, TRaw = TResult> = HttpResourceOptions<
|
|
|
87
110
|
* Options for enabling and configuring caching for the resource.
|
|
88
111
|
*/
|
|
89
112
|
cache?: ResourceCacheOptions;
|
|
113
|
+
/**
|
|
114
|
+
* Opt-in automatic pausing (off by default — existing behavior unchanged):
|
|
115
|
+
* - `true` — pause whenever the surrounding Activity boundary (`MmActivity` /
|
|
116
|
+
* `providePaused` from `@mmstack/primitives`) is paused. Outside a boundary this
|
|
117
|
+
* is a no-op, so it's safe to set app-wide via `provideQueryResourceOptions`.
|
|
118
|
+
* - a `() => boolean` predicate (a `Signal<boolean>` qualifies) — pause while it
|
|
119
|
+
* returns `true`.
|
|
120
|
+
*
|
|
121
|
+
* Pausing has the same semantics as returning `ctx.paused` from the request fn:
|
|
122
|
+
* the resource HOLDS its current value and last request (no refetch on resume if
|
|
123
|
+
* the request is unchanged) and stops background work (polling, focus/reconnect
|
|
124
|
+
* triggers). The two compose — either source can pause the resource.
|
|
125
|
+
*/
|
|
126
|
+
pause?: PauseOption;
|
|
90
127
|
/**
|
|
91
128
|
* Comparison of request object
|
|
92
129
|
*/
|
|
@@ -113,6 +150,9 @@ export declare function provideQueryResourceOptions(valueOrFn: Partial<QueryReso
|
|
|
113
150
|
* }
|
|
114
151
|
* });
|
|
115
152
|
* ```
|
|
153
|
+
*
|
|
154
|
+
* Note: a PAUSED resource also reports `'no-request'` — it holds its previous value
|
|
155
|
+
* and request, but no request is currently active.
|
|
116
156
|
*/
|
|
117
157
|
export type DisabledReason = 'offline' | 'circuit-open' | 'no-request';
|
|
118
158
|
/**
|
|
@@ -171,7 +211,10 @@ export type QueryResourceRef<TResult> = Omit<HttpResourceRef<TResult>, 'headers'
|
|
|
171
211
|
disabledReason: Signal<DisabledReason | null>;
|
|
172
212
|
/**
|
|
173
213
|
* Prefetches data for the resource, populating the cache if caching is enabled. This can be
|
|
174
|
-
* used to proactively load data before it's needed.
|
|
214
|
+
* used to proactively load data before it's needed.
|
|
215
|
+
*
|
|
216
|
+
* Resolves immediately without fetching when caching is disabled or a slow
|
|
217
|
+
* connection is detected (prefetching would compete with user-initiated requests).
|
|
175
218
|
*
|
|
176
219
|
* @param req - Optional partial request parameters to use for the prefetch. This allows you
|
|
177
220
|
* to prefetch data with different parameters than the main resource request.
|
|
@@ -235,4 +278,3 @@ export declare function queryResource<TResult, TRaw = TResult>(request: Resource
|
|
|
235
278
|
* ```
|
|
236
279
|
*/
|
|
237
280
|
export declare function queryResource<TResult, TRaw = TResult>(request: ResourceRequestFn, options?: QueryResourceOptions<TResult, TRaw>): QueryResourceRef<TResult | undefined>;
|
|
238
|
-
export {};
|
|
@@ -21,6 +21,10 @@ export declare function setCacheContext(ctx: HttpContext | undefined, opt: Omit<
|
|
|
21
21
|
* is made to the server, and the response is cached according to the configured TTL and staleness.
|
|
22
22
|
* The interceptor also respects `Cache-Control` headers from the server.
|
|
23
23
|
*
|
|
24
|
+
* Cache-enabled requests are single-flighted per cache key: N concurrent consumers of
|
|
25
|
+
* the same missing/stale entry share ONE network request. Non-cached requests are not
|
|
26
|
+
* touched — pair with `createDedupeRequestsInterceptor` to coalesce those as well.
|
|
27
|
+
*
|
|
24
28
|
* @param allowedMethods - An array of HTTP methods for which caching should be enabled.
|
|
25
29
|
* Defaults to `['GET', 'HEAD', 'OPTIONS']`.
|
|
26
30
|
*
|
|
@@ -43,8 +43,11 @@ export type CacheEntry<T> = {
|
|
|
43
43
|
updated: number;
|
|
44
44
|
stale: number;
|
|
45
45
|
useCount: number;
|
|
46
|
+
/** Timestamp of the last read/write — drives LRU eviction. */
|
|
47
|
+
lastAccessed: number;
|
|
46
48
|
expiresAt: number;
|
|
47
|
-
|
|
49
|
+
/** Absent for non-finite/over-int32 TTLs — those rely on lazy expiry instead. */
|
|
50
|
+
timeout?: ReturnType<typeof setTimeout>;
|
|
48
51
|
key: string;
|
|
49
52
|
};
|
|
50
53
|
/**
|
|
@@ -65,9 +68,27 @@ export declare class Cache<T> {
|
|
|
65
68
|
private readonly internal;
|
|
66
69
|
private readonly cleanupOpt;
|
|
67
70
|
private readonly id;
|
|
71
|
+
/** True once async hydration from the persistence layer has completed (or was empty). */
|
|
72
|
+
private hydrated;
|
|
73
|
+
/** Keys invalidated while hydration was still in flight — must not be resurrected by it. */
|
|
74
|
+
private readonly hydrationTombstones;
|
|
75
|
+
private readonly hitCount;
|
|
76
|
+
private readonly missCount;
|
|
68
77
|
/**
|
|
69
|
-
*
|
|
70
|
-
*
|
|
78
|
+
* Read-only cache statistics for debugging/observability — entry count plus
|
|
79
|
+
* request-level hit/miss counters (counted on direct lookups, e.g. the cache
|
|
80
|
+
* interceptor's, not on every reactive signal read). Render it in a debug
|
|
81
|
+
* panel; it intentionally exposes no way to mutate the cache.
|
|
82
|
+
*/
|
|
83
|
+
readonly stats: Signal<{
|
|
84
|
+
size: number;
|
|
85
|
+
hits: number;
|
|
86
|
+
misses: number;
|
|
87
|
+
}>;
|
|
88
|
+
/**
|
|
89
|
+
* Destroys the cache instance, clearing the cleanup interval and closing the
|
|
90
|
+
* cross-tab channel. Called automatically when the providing injector is destroyed
|
|
91
|
+
* (wired up by `provideQueryCache`); call it manually for caches you construct yourself.
|
|
71
92
|
*/
|
|
72
93
|
readonly destroy: () => void;
|
|
73
94
|
private readonly broadcast;
|
|
@@ -89,9 +110,11 @@ export declare class Cache<T> {
|
|
|
89
110
|
}, db?: Promise<CacheDB<T>>);
|
|
90
111
|
/** @internal */
|
|
91
112
|
private getInternal;
|
|
113
|
+
/** @internal Imperative access bookkeeping for LRU eviction. */
|
|
114
|
+
private touch;
|
|
92
115
|
/**
|
|
93
|
-
* Retrieves a cache entry
|
|
94
|
-
* for
|
|
116
|
+
* Retrieves a cache entry directly (non-reactively), updating its access bookkeeping
|
|
117
|
+
* for LRU eviction.
|
|
95
118
|
* @internal
|
|
96
119
|
* @param key - The key of the entry to retrieve.
|
|
97
120
|
* @returns The cache entry, or `null` if not found or expired.
|
|
@@ -122,13 +145,27 @@ export declare class Cache<T> {
|
|
|
122
145
|
/**
|
|
123
146
|
* Stores a value in the cache.
|
|
124
147
|
*
|
|
148
|
+
* NOTE: cached values are shared by reference across all consumers (current and
|
|
149
|
+
* future cache hits, persistence, cross-tab sync) — do not mutate a value after
|
|
150
|
+
* storing it or after reading it from the cache.
|
|
151
|
+
*
|
|
125
152
|
* @param key - The key under which to store the value.
|
|
126
153
|
* @param value - The value to store.
|
|
127
154
|
* @param staleTime - (Optional) The stale time for this entry, in milliseconds. Overrides the default `staleTime`.
|
|
128
155
|
* @param ttl - (Optional) The TTL for this entry, in milliseconds. Overrides the default `ttl`.
|
|
156
|
+
* @param persist - (Optional) Whether to also write the entry to the persistence layer (IndexedDB). Defaults to `false`.
|
|
129
157
|
*/
|
|
130
158
|
store(key: string, value: T, staleTime?: number, ttl?: number, persist?: boolean): void;
|
|
131
159
|
private storeInternal;
|
|
160
|
+
/**
|
|
161
|
+
* @internal
|
|
162
|
+
* Inserts an entry that already carries ABSOLUTE timestamps — hydration from the
|
|
163
|
+
* persistence layer and cross-tab sync messages. Never re-anchors freshness to
|
|
164
|
+
* `Date.now()`, never persists, never broadcasts.
|
|
165
|
+
*/
|
|
166
|
+
private restoreInternal;
|
|
167
|
+
/** @internal Shared writer: arms the expiry timer only within the safe delay range. */
|
|
168
|
+
private setEntry;
|
|
132
169
|
/**
|
|
133
170
|
* Invalidates (removes) a cache entry.
|
|
134
171
|
*
|
|
@@ -154,7 +191,12 @@ export declare class Cache<T> {
|
|
|
154
191
|
*/
|
|
155
192
|
invalidateWhere(predicate: (key: string) => boolean): number;
|
|
156
193
|
private invalidateInternal;
|
|
157
|
-
/**
|
|
194
|
+
/**
|
|
195
|
+
* Removes EVERY entry — memory, persisted rows, and (via broadcast) other tabs.
|
|
196
|
+
* Call on logout/auth changes so no prior user's responses survive.
|
|
197
|
+
*/
|
|
198
|
+
clear(): void;
|
|
199
|
+
/** @internal Drops expired entries, then enforces `maxSize` by the configured strategy. */
|
|
158
200
|
private cleanup;
|
|
159
201
|
}
|
|
160
202
|
/**
|
|
@@ -238,4 +280,16 @@ export declare function provideQueryCache(opt?: CacheOptions): Provider;
|
|
|
238
280
|
* }
|
|
239
281
|
*/
|
|
240
282
|
export declare function injectQueryCache<TRaw = unknown>(injector?: Injector): Cache<HttpResponse<TRaw>>;
|
|
283
|
+
/**
|
|
284
|
+
* Injects the cache statistics, including the current size of the cache and the number of hits and misses.
|
|
285
|
+
*
|
|
286
|
+
* @param injector - (Optional) The injector to use. If not provided, the current
|
|
287
|
+
* injection context is used.
|
|
288
|
+
* @returns A signal containing the cache statistics.
|
|
289
|
+
*/
|
|
290
|
+
export declare function injectCacheStats(injector?: Injector): Signal<{
|
|
291
|
+
size: number;
|
|
292
|
+
hits: number;
|
|
293
|
+
misses: number;
|
|
294
|
+
}>;
|
|
241
295
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { Cache, injectQueryCache, provideQueryCache } from './cache';
|
|
1
|
+
export { Cache, injectCacheStats, injectQueryCache, provideQueryCache, } from './cache';
|
|
2
2
|
export * from './cache-interceptor';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { Cache, injectQueryCache, provideQueryCache } from './cache';
|
|
1
|
+
export { Cache, injectQueryCache, provideQueryCache, type CacheEntry, type CleanupType, } from './cache';
|
|
2
2
|
export { createCacheInterceptor } from './cache-interceptor';
|
|
@@ -22,6 +22,12 @@ export declare function noDedupe(ctx?: HttpContext): HttpContext;
|
|
|
22
22
|
* only the first request will be sent to the server. Subsequent requests will
|
|
23
23
|
* receive the response from the first request.
|
|
24
24
|
*
|
|
25
|
+
* Relationship to `createCacheInterceptor`: the cache interceptor has built-in
|
|
26
|
+
* single-flight for CACHE-ENABLED requests (keyed by the cache key). This interceptor
|
|
27
|
+
* covers everything the cache doesn't see — non-cached resources, plain HttpClient
|
|
28
|
+
* calls, DELETEs — keyed by the request hash. Installing both is the recommended
|
|
29
|
+
* setup; where they overlap, this one degrades to a no-op passthrough.
|
|
30
|
+
*
|
|
25
31
|
* @param allowed - An array of HTTP methods for which deduplication should be enabled.
|
|
26
32
|
* Defaults to `['GET', 'DELETE', 'HEAD', 'OPTIONS']`.
|
|
27
33
|
* @param keyFn - Optional function to compute the dedupe key from a request.
|
|
@@ -5,17 +5,24 @@ type HashableRequest = {
|
|
|
5
5
|
responseType?: string;
|
|
6
6
|
params?: HttpResourceRequest['params'] | HttpRequest<unknown>['params'];
|
|
7
7
|
body?: unknown;
|
|
8
|
+
headers?: HttpResourceRequest['headers'] | HttpRequest<unknown>['headers'];
|
|
8
9
|
};
|
|
9
10
|
/**
|
|
10
11
|
* Builds a stable cache/dedupe key from an HTTP request shape (accepts both
|
|
11
12
|
* `HttpRequest` and `HttpResourceRequest`).
|
|
12
13
|
*
|
|
13
|
-
* Key composition: `${method}:${url}:${responseType}[:${params}][:${body}]`
|
|
14
|
+
* Key composition: `${method}:${url}:${responseType}[:${params}][:${body}][:${vary}]`
|
|
14
15
|
* - `method` defaults to `'GET'`, `responseType` to `'json'` (Angular defaults).
|
|
15
16
|
* - Query params are sorted alphabetically and URL-encoded for stability.
|
|
16
17
|
* - Body hashing handles `File`/`Blob`/`FormData`/`URLSearchParams`/`ArrayBuffer`
|
|
17
18
|
* and typed arrays explicitly; everything else flows through key-sorted
|
|
18
19
|
* `JSON.stringify` via `hash()`.
|
|
20
|
+
* - `varyHeaders` (opt-in) mixes the named request headers into the key so responses
|
|
21
|
+
* that differ per header (e.g. `Authorization` → per-user, `Accept-Language`) get
|
|
22
|
+
* separate entries. Known-safe content-negotiation headers (`Accept`,
|
|
23
|
+
* `Accept-Language`, `Content-Language`, `Content-Type`) embed their value raw for
|
|
24
|
+
* readable keys; all other header VALUES are one-way digested, never embedded raw —
|
|
25
|
+
* keys are persisted to IndexedDB and broadcast across tabs.
|
|
19
26
|
*/
|
|
20
|
-
export declare function hashRequest(req: HashableRequest): string;
|
|
27
|
+
export declare function hashRequest(req: HashableRequest, varyHeaders?: readonly string[]): string;
|
|
21
28
|
export {};
|
package/lib/util/refresh.d.ts
CHANGED
|
@@ -1,3 +1,31 @@
|
|
|
1
|
-
import { HttpResourceRef } from '@angular/common/http';
|
|
2
|
-
import { DestroyRef } from '@angular/core';
|
|
3
|
-
|
|
1
|
+
import { type HttpResourceRef } from '@angular/common/http';
|
|
2
|
+
import { type DestroyRef, type Injector, type Signal } from '@angular/core';
|
|
3
|
+
/**
|
|
4
|
+
* Refresh configuration for a query resource.
|
|
5
|
+
* - a `number` is shorthand for `{ interval: number }` (poll every n milliseconds)
|
|
6
|
+
* - the object form composes polling with event-driven refresh triggers
|
|
7
|
+
*/
|
|
8
|
+
export type RefreshOptions = number | {
|
|
9
|
+
/**
|
|
10
|
+
* Poll interval in milliseconds. Omit (or 0) for no polling — useful when only
|
|
11
|
+
* the event-driven triggers below are wanted.
|
|
12
|
+
*/
|
|
13
|
+
interval?: number;
|
|
14
|
+
/**
|
|
15
|
+
* Reload when the page becomes visible again (tab refocused, window restored).
|
|
16
|
+
* @default false
|
|
17
|
+
*/
|
|
18
|
+
onFocus?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Reload when the browser comes back online.
|
|
21
|
+
* @default false
|
|
22
|
+
*/
|
|
23
|
+
onReconnect?: boolean;
|
|
24
|
+
};
|
|
25
|
+
/** @internal Reactive sources + injector for the event-driven refresh triggers. */
|
|
26
|
+
export type RefreshTriggers = {
|
|
27
|
+
injector: Injector;
|
|
28
|
+
visibility: Signal<DocumentVisibilityState>;
|
|
29
|
+
online: Signal<boolean>;
|
|
30
|
+
};
|
|
31
|
+
export declare function refresh<T>(resource: HttpResourceRef<T>, destroyRef: DestroyRef, opt?: RefreshOptions, inactive?: () => boolean, triggers?: RefreshTriggers): HttpResourceRef<T>;
|
package/lib/util/sensors.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import * as i0 from "@angular/core";
|
|
2
2
|
export declare class ResourceSensors {
|
|
3
3
|
readonly networkStatus: import("@mmstack/primitives").NetworkStatusSignal;
|
|
4
|
+
readonly pageVisibility: import("@angular/core").Signal<DocumentVisibilityState>;
|
|
4
5
|
static ɵfac: i0.ɵɵFactoryDeclaration<ResourceSensors, never>;
|
|
5
6
|
static ɵprov: i0.ɵɵInjectableDeclaration<ResourceSensors>;
|
|
6
7
|
}
|
|
7
8
|
export declare function injectNetworkStatus(): import("@mmstack/primitives").NetworkStatusSignal;
|
|
9
|
+
export declare function injectPageVisibility(): import("@angular/core").Signal<DocumentVisibilityState>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type Observable } from 'rxjs';
|
|
2
|
+
/**
|
|
3
|
+
* @internal
|
|
4
|
+
* Single-flight sharing: if a pending observable is already registered under `key`,
|
|
5
|
+
* return it; otherwise create one, share it (replaying the latest event to late
|
|
6
|
+
* subscribers), and deregister it on teardown/settle.
|
|
7
|
+
*
|
|
8
|
+
* Used by both the dedupe interceptor (keyed by full request hash, app-wide) and the
|
|
9
|
+
* cache interceptor (keyed by the CACHE key, guarding the miss/stale-revalidation path)
|
|
10
|
+
* — same mechanism, different keying/scope, so it lives here exactly once.
|
|
11
|
+
*/
|
|
12
|
+
export declare function sharePending<T>(pending: Map<string, Observable<T>>, key: string, create: () => Observable<T>): Observable<T>;
|