@metamask-previews/base-data-service 2.1.0-preview-6ebaf4e52 → 2.1.0-preview-b6e8e7385
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/CHANGELOG.md +0 -11
- package/dist/BaseDataService.d.ts +2 -43
- package/dist/BaseDataService.d.ts.map +1 -1
- package/dist/BaseDataService.js +4 -212
- package/dist/BaseDataService.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -10,20 +10,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
10
10
|
### Added
|
|
11
11
|
|
|
12
12
|
- Add support for Node.js 26 ([#10981](https://github.com/MetaMask/core/pull/10981))
|
|
13
|
-
- Add `onQueryStateChange` option to the protected `fetchQuery` method ([#11162](https://github.com/MetaMask/core/pull/11162))
|
|
14
|
-
- The callback receives the query state with serialized errors, first with the cached state if one exists, then on every update until the fetch has settled and the query is idle.
|
|
15
|
-
- Errors thrown by the callback are logged and ignored.
|
|
16
|
-
- This option is not available on `fetchInfiniteQuery`.
|
|
17
|
-
- Export `CacheUpdatedState`, `DataServiceQueryState`, `QueryStateChangeHandler` and `SerializedQueryError` types ([#11162](https://github.com/MetaMask/core/pull/11162))
|
|
18
13
|
|
|
19
14
|
### Changed
|
|
20
15
|
|
|
21
|
-
- **BREAKING:** Serialize query errors in `:cacheUpdated` and `:cacheUpdated:${hash}` event payloads as `{ name, message }` plus the error's own JSON safe properties and its `cause` instead of the thrown value ([#11162](https://github.com/MetaMask/core/pull/11162))
|
|
22
|
-
- This applies to both `error` and `fetchFailureReason` on each query state.
|
|
23
|
-
- Own properties such as `code` or `httpStatus` are kept when they are JSON safe, and an `Error` cause is serialized the same way. The `stack`, non JSON values, circular references and values nested more than 5 levels deep are dropped.
|
|
24
|
-
- Non `Error` thrown values are serialized with the name `Error`.
|
|
25
|
-
- Consumers that read non JSON properties or the `stack` from these errors, or that relied on `instanceof Error`, must adapt.
|
|
26
|
-
- Queries in `:cacheUpdated` and `:cacheUpdated:${hash}` event payloads no longer include the non serializable `promise` field of an in flight fetch, so payloads stay JSON safe ([#11162](https://github.com/MetaMask/core/pull/11162))
|
|
27
16
|
- Bump `@tanstack/query-core` from `^5.89.0` to `^5.103.2` ([#10511](https://github.com/MetaMask/core/pull/10511))
|
|
28
17
|
- Bump `@metamask/utils` from `^12.0.0` to `^12.0.1` ([#11107](https://github.com/MetaMask/core/pull/11107))
|
|
29
18
|
- Bump `uuid` from `^11.1.1` to `^14.0.2` ([#10941](https://github.com/MetaMask/core/pull/10941), [#11179](https://github.com/MetaMask/core/pull/11179), [#11305](https://github.com/MetaMask/core/pull/11305))
|
|
@@ -18,47 +18,11 @@ export type MutationKey = Key;
|
|
|
18
18
|
* events.
|
|
19
19
|
*/
|
|
20
20
|
export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
|
|
21
|
-
/**
|
|
22
|
-
* A JSON safe representation of an error thrown by a query.
|
|
23
|
-
*
|
|
24
|
-
* Besides `name` and `message`, it carries the error's own enumerable
|
|
25
|
-
* properties that are JSON safe (for example `code` or `httpStatus`) and its
|
|
26
|
-
* `cause`, which is itself serialized the same way when it is an `Error`.
|
|
27
|
-
* The `stack` is never included.
|
|
28
|
-
*/
|
|
29
|
-
export type SerializedQueryError = {
|
|
30
|
-
name: string;
|
|
31
|
-
message: string;
|
|
32
|
-
cause?: SerializedQueryError | Json;
|
|
33
|
-
[key: string]: SerializedQueryError | Json | undefined;
|
|
34
|
-
};
|
|
35
|
-
/**
|
|
36
|
-
* The dehydrated state published in `:cacheUpdated` payloads, where query
|
|
37
|
-
* errors are serialized and the in flight `promise` is omitted so the payload
|
|
38
|
-
* survives JSON round trips.
|
|
39
|
-
*/
|
|
40
|
-
export type CacheUpdatedState = Omit<DehydratedState, 'queries'> & {
|
|
41
|
-
queries: (Omit<DehydratedState['queries'][number], 'state' | 'promise'> & {
|
|
42
|
-
state: DataServiceQueryState;
|
|
43
|
-
})[];
|
|
44
|
-
};
|
|
45
|
-
/**
|
|
46
|
-
* The state of a single query, as reported to `onQueryStateChange` handlers.
|
|
47
|
-
* Errors are serialized so the state is JSON safe.
|
|
48
|
-
*/
|
|
49
|
-
export type DataServiceQueryState = Omit<DehydratedState['queries'][number]['state'], 'error' | 'fetchFailureReason'> & {
|
|
50
|
-
error: SerializedQueryError | null;
|
|
51
|
-
fetchFailureReason: SerializedQueryError | null;
|
|
52
|
-
};
|
|
53
|
-
/**
|
|
54
|
-
* A callback that receives the state of a query as it changes.
|
|
55
|
-
*/
|
|
56
|
-
export type QueryStateChangeHandler = (state: DataServiceQueryState) => void;
|
|
57
21
|
export type DataServiceGranularCacheUpdatedPayload = {
|
|
58
22
|
objectType: 'query' | 'mutation';
|
|
59
23
|
} & ({
|
|
60
24
|
type: 'added' | 'updated';
|
|
61
|
-
state:
|
|
25
|
+
state: DehydratedState;
|
|
62
26
|
} | {
|
|
63
27
|
type: 'removed';
|
|
64
28
|
state: null;
|
|
@@ -119,16 +83,11 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
119
83
|
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
120
84
|
* @param options.queryFn - The query function.
|
|
121
85
|
* @param options.responseStruct - An optional struct for validating the response of the query function.
|
|
122
|
-
* @param options.onQueryStateChange - An optional callback that receives the
|
|
123
|
-
* state of the query (with serialized errors) as it changes. It is called
|
|
124
|
-
* once with the current state if the query is already cached, then with
|
|
125
|
-
* every update until the fetch has settled and the query is idle.
|
|
126
86
|
* @returns The query results.
|
|
127
87
|
*/
|
|
128
|
-
protected fetchQuery<TQueryFnData extends Json, TError = DefaultError, TDataStruct extends Struct<TQueryFnData> | undefined = undefined, TData = TDataStruct extends Struct<infer StructType> ? StructType : TQueryFnData, TQueryKey extends QueryKey = QueryKey>({ queryFn, responseStruct,
|
|
88
|
+
protected fetchQuery<TQueryFnData extends Json, TError = DefaultError, TDataStruct extends Struct<TQueryFnData> | undefined = undefined, TData = TDataStruct extends Struct<infer StructType> ? StructType : TQueryFnData, TQueryKey extends QueryKey = QueryKey>({ queryFn, responseStruct, ...options }: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay' | 'queryFn'>, 'queryKey'> & {
|
|
129
89
|
queryFn: QueryFunction<TQueryFnData, TQueryKey>;
|
|
130
90
|
responseStruct?: TDataStruct;
|
|
131
|
-
onQueryStateChange?: QueryStateChangeHandler;
|
|
132
91
|
}): Promise<TData>;
|
|
133
92
|
/**
|
|
134
93
|
* Fetch a paginated query.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.d.ts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,eAAe,EAChB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EACV,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC5B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAE/C,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EACL,YAAY,EAEZ,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,8BAA8B,EAC9B,aAAa,EACb,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,SAAS,EAET,iBAAiB,EACjB,YAAY,EACZ,aAAa,EACb,YAAY,EAIZ,gBAAgB,EACjB,MAAM,sBAAsB,CAAC;AAK9B,OAAO,EAEL,0BAA0B,EAE3B,MAAM,0BAA0B,CAAC;AAMlC;;;GAGG;AACH,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,IAAI,E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amask/utils';
|
|
2
2
|
import { QueryClient, dehydrate, hydrate, hashKey, } from '@tanstack/query-core';
|
|
3
3
|
import deepEqual from 'fast-deep-equal';
|
|
4
4
|
import { debounce } from 'lodash-es';
|
|
@@ -7,135 +7,6 @@ import { createServicePolicy, } from './createServicePolicy.js';
|
|
|
7
7
|
import { createModuleLogger, projectLogger } from './loggers.js';
|
|
8
8
|
import { processMutationResponse, processQueryResponse } from './utils.js';
|
|
9
9
|
const log = createModuleLogger(projectLogger, 'BaseDataService');
|
|
10
|
-
/**
|
|
11
|
-
* How deep error properties are followed when serializing. Values nested
|
|
12
|
-
* deeper than this are dropped.
|
|
13
|
-
*/
|
|
14
|
-
const MAX_SERIALIZED_ERROR_DEPTH = 5;
|
|
15
|
-
/**
|
|
16
|
-
* Error properties that are never copied from the error's own properties.
|
|
17
|
-
* `name` and `message` are always set explicitly, `cause` is handled
|
|
18
|
-
* separately because it is usually not enumerable, and `stack` is excluded.
|
|
19
|
-
*/
|
|
20
|
-
const RESERVED_ERROR_KEYS = new Set(['name', 'message', 'stack', 'cause']);
|
|
21
|
-
/**
|
|
22
|
-
* Convert a value into a JSON safe value, or `undefined` if it cannot be
|
|
23
|
-
* represented safely.
|
|
24
|
-
*
|
|
25
|
-
* @param value - The value to convert.
|
|
26
|
-
* @param depth - How deep the value is nested inside the top level error.
|
|
27
|
-
* @param ancestors - The objects currently being serialized, to detect cycles.
|
|
28
|
-
* @returns The JSON safe value, or `undefined` if the value should be dropped.
|
|
29
|
-
*/
|
|
30
|
-
function toJsonSafe(value, depth, ancestors) {
|
|
31
|
-
if (depth > MAX_SERIALIZED_ERROR_DEPTH) {
|
|
32
|
-
return undefined;
|
|
33
|
-
}
|
|
34
|
-
if (value === null ||
|
|
35
|
-
typeof value === 'string' ||
|
|
36
|
-
typeof value === 'boolean') {
|
|
37
|
-
return value;
|
|
38
|
-
}
|
|
39
|
-
if (typeof value === 'number') {
|
|
40
|
-
return Number.isFinite(value) ? value : undefined;
|
|
41
|
-
}
|
|
42
|
-
if (typeof value !== 'object' || ancestors.has(value)) {
|
|
43
|
-
return undefined;
|
|
44
|
-
}
|
|
45
|
-
if (value instanceof Error) {
|
|
46
|
-
return serializeErrorObject(value, depth, ancestors);
|
|
47
|
-
}
|
|
48
|
-
ancestors.add(value);
|
|
49
|
-
try {
|
|
50
|
-
if (Array.isArray(value)) {
|
|
51
|
-
return value.map((item) => (toJsonSafe(item, depth + 1, ancestors) ?? null));
|
|
52
|
-
}
|
|
53
|
-
const prototype = Object.getPrototypeOf(value);
|
|
54
|
-
if (prototype !== Object.prototype && prototype !== null) {
|
|
55
|
-
return undefined;
|
|
56
|
-
}
|
|
57
|
-
const result = {};
|
|
58
|
-
for (const [key, item] of Object.entries(value)) {
|
|
59
|
-
const safe = toJsonSafe(item, depth + 1, ancestors);
|
|
60
|
-
if (safe !== undefined) {
|
|
61
|
-
result[key] = safe;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
return result;
|
|
65
|
-
}
|
|
66
|
-
finally {
|
|
67
|
-
ancestors.delete(value);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Serialize an `Error` with its own JSON safe properties and its `cause`.
|
|
72
|
-
*
|
|
73
|
-
* @param error - The error to serialize.
|
|
74
|
-
* @param depth - How deep the error is nested inside the top level error.
|
|
75
|
-
* @param ancestors - The objects currently being serialized, to detect cycles.
|
|
76
|
-
* @returns The serialized error.
|
|
77
|
-
*/
|
|
78
|
-
function serializeErrorObject(error, depth, ancestors) {
|
|
79
|
-
ancestors.add(error);
|
|
80
|
-
try {
|
|
81
|
-
const result = {
|
|
82
|
-
name: error.name,
|
|
83
|
-
message: getErrorMessage(error),
|
|
84
|
-
};
|
|
85
|
-
for (const key of Object.keys(error)) {
|
|
86
|
-
if (!RESERVED_ERROR_KEYS.has(key)) {
|
|
87
|
-
const safe = toJsonSafe(error[key], depth + 1, ancestors);
|
|
88
|
-
if (safe !== undefined) {
|
|
89
|
-
result[key] = safe;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
const cause = toJsonSafe(error.cause, depth + 1, ancestors);
|
|
94
|
-
if (cause !== undefined) {
|
|
95
|
-
result.cause = cause;
|
|
96
|
-
}
|
|
97
|
-
return result;
|
|
98
|
-
}
|
|
99
|
-
finally {
|
|
100
|
-
ancestors.delete(error);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* Convert a thrown value into a JSON safe error.
|
|
105
|
-
*
|
|
106
|
-
* For an `Error`, this keeps its `name`, `message`, own JSON safe properties
|
|
107
|
-
* and `cause`. Any other thrown value is reported with the name `Error`.
|
|
108
|
-
*
|
|
109
|
-
* @param error - The raw error stored on a query, if any.
|
|
110
|
-
* @returns The serialized error, or null if there is no error.
|
|
111
|
-
*/
|
|
112
|
-
function serializeQueryError(error) {
|
|
113
|
-
if (error === null) {
|
|
114
|
-
return null;
|
|
115
|
-
}
|
|
116
|
-
if (!(error instanceof Error)) {
|
|
117
|
-
return { name: 'Error', message: getErrorMessage(error) };
|
|
118
|
-
}
|
|
119
|
-
try {
|
|
120
|
-
return serializeErrorObject(error, 0, new WeakSet());
|
|
121
|
-
}
|
|
122
|
-
catch {
|
|
123
|
-
return { name: error.name, message: getErrorMessage(error) };
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
/**
|
|
127
|
-
* Serialize the errors held by a query state so it survives JSON round trips.
|
|
128
|
-
*
|
|
129
|
-
* @param state - The raw query state.
|
|
130
|
-
* @returns The query state with `error` and `fetchFailureReason` serialized.
|
|
131
|
-
*/
|
|
132
|
-
function serializeQueryState(state) {
|
|
133
|
-
return {
|
|
134
|
-
...state,
|
|
135
|
-
error: serializeQueryError(state.error),
|
|
136
|
-
fetchFailureReason: serializeQueryError(state.fetchFailureReason),
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
10
|
/*
|
|
140
11
|
* Defaults to apply to all data service queries if no default option specified.
|
|
141
12
|
*/
|
|
@@ -225,24 +96,16 @@ export class BaseDataService {
|
|
|
225
96
|
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
226
97
|
* @param options.queryFn - The query function.
|
|
227
98
|
* @param options.responseStruct - An optional struct for validating the response of the query function.
|
|
228
|
-
* @param options.onQueryStateChange - An optional callback that receives the
|
|
229
|
-
* state of the query (with serialized errors) as it changes. It is called
|
|
230
|
-
* once with the current state if the query is already cached, then with
|
|
231
|
-
* every update until the fetch has settled and the query is idle.
|
|
232
99
|
* @returns The query results.
|
|
233
100
|
*/
|
|
234
|
-
async fetchQuery({ queryFn, responseStruct,
|
|
235
|
-
|
|
101
|
+
async fetchQuery({ queryFn, responseStruct, ...options }) {
|
|
102
|
+
return this.#queryClient.fetchQuery({
|
|
236
103
|
...options,
|
|
237
104
|
queryFn: async (context) => {
|
|
238
105
|
const response = await this.#policy.execute(() => queryFn(context));
|
|
239
106
|
return processQueryResponse(options.queryKey, response, responseStruct);
|
|
240
107
|
},
|
|
241
108
|
});
|
|
242
|
-
if (!onQueryStateChange) {
|
|
243
|
-
return runFetch();
|
|
244
|
-
}
|
|
245
|
-
return this.#withQueryStateChange(options.queryKey, onQueryStateChange, runFetch);
|
|
246
109
|
}
|
|
247
110
|
/**
|
|
248
111
|
* Fetch a paginated query.
|
|
@@ -370,69 +233,6 @@ export class BaseDataService {
|
|
|
370
233
|
this.messenger.clearSubscriptions();
|
|
371
234
|
this.messenger.clearActions();
|
|
372
235
|
}
|
|
373
|
-
/**
|
|
374
|
-
* Run a fetch while reporting the state of its query to a handler.
|
|
375
|
-
*
|
|
376
|
-
* The handler receives the current state up front if the query is cached,
|
|
377
|
-
* then every `updated` cache event for the query. It is
|
|
378
|
-
* unsubscribed once the fetch has settled and the last reported state is
|
|
379
|
-
* idle, so a background fetch that outlives this call is still reported
|
|
380
|
-
* until it finishes. Errors thrown by the handler are logged and ignored.
|
|
381
|
-
*
|
|
382
|
-
* @param queryKey - The key of the query being fetched.
|
|
383
|
-
* @param handler - The callback receiving query states.
|
|
384
|
-
* @param runFetch - The function performing the fetch.
|
|
385
|
-
* @returns The result of the fetch.
|
|
386
|
-
*/
|
|
387
|
-
async #withQueryStateChange(queryKey, handler, runFetch) {
|
|
388
|
-
const notify = (state) => {
|
|
389
|
-
try {
|
|
390
|
-
handler(state);
|
|
391
|
-
}
|
|
392
|
-
catch (error) {
|
|
393
|
-
log('onQueryStateChange handler threw', error);
|
|
394
|
-
}
|
|
395
|
-
};
|
|
396
|
-
const eventType = `${this.name}:cacheUpdated:${hashKey(queryKey)}`;
|
|
397
|
-
let settled = false;
|
|
398
|
-
let idle = true;
|
|
399
|
-
const unsubscribe = (handlerToRemove) => {
|
|
400
|
-
try {
|
|
401
|
-
this.#messenger.unsubscribe(eventType, handlerToRemove);
|
|
402
|
-
}
|
|
403
|
-
catch {
|
|
404
|
-
// The subscription was already cleared, e.g. by `destroy`.
|
|
405
|
-
}
|
|
406
|
-
};
|
|
407
|
-
const listener = (payload) => {
|
|
408
|
-
// `added` only carries the blank state built right before the fetch
|
|
409
|
-
// starts (pending and idle), and `removed` carries no state at all.
|
|
410
|
-
if (payload.type !== 'updated') {
|
|
411
|
-
return;
|
|
412
|
-
}
|
|
413
|
-
const { state } = payload.state.queries[0];
|
|
414
|
-
idle = state.fetchStatus === 'idle';
|
|
415
|
-
notify(state);
|
|
416
|
-
if (settled && idle) {
|
|
417
|
-
unsubscribe(listener);
|
|
418
|
-
}
|
|
419
|
-
};
|
|
420
|
-
const current = this.#queryClient.getQueryState(queryKey);
|
|
421
|
-
if (current) {
|
|
422
|
-
idle = current.fetchStatus === 'idle';
|
|
423
|
-
notify(serializeQueryState(current));
|
|
424
|
-
}
|
|
425
|
-
this.#messenger.subscribe(eventType, listener);
|
|
426
|
-
try {
|
|
427
|
-
return await runFetch();
|
|
428
|
-
}
|
|
429
|
-
finally {
|
|
430
|
-
settled = true;
|
|
431
|
-
if (idle) {
|
|
432
|
-
unsubscribe(listener);
|
|
433
|
-
}
|
|
434
|
-
}
|
|
435
|
-
}
|
|
436
236
|
/**
|
|
437
237
|
* Publish `cacheUpdated` events when the query or mutation cache is updated.
|
|
438
238
|
*
|
|
@@ -441,7 +241,7 @@ export class BaseDataService {
|
|
|
441
241
|
* @param hash - The hash of the query or mutation.
|
|
442
242
|
*/
|
|
443
243
|
#publishCacheUpdate(objectType, eventType, hash) {
|
|
444
|
-
const
|
|
244
|
+
const state = eventType === 'added' || eventType === 'updated'
|
|
445
245
|
? dehydrate(this.#queryClient, {
|
|
446
246
|
shouldDehydrateQuery: (query) => objectType === 'query' && query.queryHash === hash,
|
|
447
247
|
shouldDehydrateMutation: (mutation) => objectType === 'mutation' &&
|
|
@@ -449,14 +249,6 @@ export class BaseDataService {
|
|
|
449
249
|
hashKey(mutation.options.mutationKey) === hash,
|
|
450
250
|
})
|
|
451
251
|
: null;
|
|
452
|
-
const state = dehydrated && {
|
|
453
|
-
...dehydrated,
|
|
454
|
-
// The in flight `promise` is not JSON safe, so it is left out.
|
|
455
|
-
queries: dehydrated.queries.map(({ promise: _promise, ...query }) => ({
|
|
456
|
-
...query,
|
|
457
|
-
state: serializeQueryState(query.state),
|
|
458
|
-
})),
|
|
459
|
-
};
|
|
460
252
|
this.#messenger.publish(`${this.name}:cacheUpdated`, {
|
|
461
253
|
type: eventType,
|
|
462
254
|
objectType,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.js","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE5E,OAAO,EAYL,WAAW,EAKX,SAAS,EACT,OAAO,EACP,OAAO,GAER,MAAM,sBAAsB,CAAC;AAC9B,OAAO,SAAS,MAAM,iBAAiB,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAiB,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,EAAE,IAAI,MAAM,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E,CAAC;YAC7B,OAAO;QACT,CAAC;QAED,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,IAAI,CAAC,kBAAkB,CAAC,IAAI,CACjE,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QAEF,IAAI,CAAC,YAAY,EAAE,CAAC;YAClB,OAAO;QACT,CAAC;QAED,MAAM,KAAK,GAAG,YAAyC,CAAC;QAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,IAAI,CAAC,kBAAkB,CAAC,MAAM,EAAE,CAAC;YACnE,MAAM,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;YACF,OAAO;QACT,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,YAAY,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;CACF","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n MessengerActions,\n MessengerEvents,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\nimport { Struct } from '@metamask/superstruct';\nimport { Duration, getErrorMessage, inMilliseconds } from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport {\n DefaultError,\n DefaultOptions,\n DehydratedState,\n FetchQueryOptions,\n InfiniteData,\n InfiniteQueryPageParamsOptions,\n CancelOptions,\n InvalidateOptions,\n InvalidateQueryFilters,\n MutationOptions,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\n QueryFilters,\n QueryFunction,\n WithRequired,\n dehydrate,\n hydrate,\n hashKey,\n MutationFunction,\n} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\nimport { debounce, DebouncedFunc } from 'lodash-es';\nimport { v4 as uuidV4 } from 'uuid';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\nimport { createModuleLogger, projectLogger } from './loggers.js';\nimport { processMutationResponse, processQueryResponse } from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'BaseDataService');\n\n/**\n * Data service mutations and queries use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\ntype Key = [string, ...Json[]] | readonly [string, ...Json[]];\n\n/*\n * Data service queries use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\nexport type QueryKey = Key;\n\n/*\n * Data service mutations use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\nexport type MutationKey = Key;\n\n/**\n * The supertype of all messengers, scoped to a namespace.\n *\n * @template Namespace - The namespace for the messenger's own actions and\n * events.\n */\nexport type BaseMessenger<Namespace extends string> = Messenger<\n Namespace,\n ActionConstraint,\n EventConstraint,\n // Use `any` to allow any parent to be set. `any` is harmless in a type constraint anyway,\n // it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\n/**\n * A JSON safe representation of an error thrown by a query.\n *\n * Besides `name` and `message`, it carries the error's own enumerable\n * properties that are JSON safe (for example `code` or `httpStatus`) and its\n * `cause`, which is itself serialized the same way when it is an `Error`.\n * The `stack` is never included.\n */\nexport type SerializedQueryError = {\n name: string;\n message: string;\n cause?: SerializedQueryError | Json;\n [key: string]: SerializedQueryError | Json | undefined;\n};\n\n/**\n * The dehydrated state published in `:cacheUpdated` payloads, where query\n * errors are serialized and the in flight `promise` is omitted so the payload\n * survives JSON round trips.\n */\nexport type CacheUpdatedState = Omit<DehydratedState, 'queries'> & {\n queries: (Omit<DehydratedState['queries'][number], 'state' | 'promise'> & {\n state: DataServiceQueryState;\n })[];\n};\n\n/**\n * The state of a single query, as reported to `onQueryStateChange` handlers.\n * Errors are serialized so the state is JSON safe.\n */\nexport type DataServiceQueryState = Omit<\n DehydratedState['queries'][number]['state'],\n 'error' | 'fetchFailureReason'\n> & {\n error: SerializedQueryError | null;\n fetchFailureReason: SerializedQueryError | null;\n};\n\n/**\n * A callback that receives the state of a query as it changes.\n */\nexport type QueryStateChangeHandler = (state: DataServiceQueryState) => void;\n\n/**\n * How deep error properties are followed when serializing. Values nested\n * deeper than this are dropped.\n */\nconst MAX_SERIALIZED_ERROR_DEPTH = 5;\n\n/**\n * Error properties that are never copied from the error's own properties.\n * `name` and `message` are always set explicitly, `cause` is handled\n * separately because it is usually not enumerable, and `stack` is excluded.\n */\nconst RESERVED_ERROR_KEYS = new Set(['name', 'message', 'stack', 'cause']);\n\n/**\n * Convert a value into a JSON safe value, or `undefined` if it cannot be\n * represented safely.\n *\n * @param value - The value to convert.\n * @param depth - How deep the value is nested inside the top level error.\n * @param ancestors - The objects currently being serialized, to detect cycles.\n * @returns The JSON safe value, or `undefined` if the value should be dropped.\n */\nfunction toJsonSafe(\n value: unknown,\n depth: number,\n ancestors: WeakSet<object>,\n): SerializedQueryError | Json | undefined {\n if (depth > MAX_SERIALIZED_ERROR_DEPTH) {\n return undefined;\n }\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'boolean'\n ) {\n return value;\n }\n if (typeof value === 'number') {\n return Number.isFinite(value) ? value : undefined;\n }\n if (typeof value !== 'object' || ancestors.has(value)) {\n return undefined;\n }\n if (value instanceof Error) {\n return serializeErrorObject(value, depth, ancestors);\n }\n\n ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n return value.map(\n (item) => (toJsonSafe(item, depth + 1, ancestors) ?? null) as Json,\n );\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n return undefined;\n }\n const result: Record<string, Json> = {};\n for (const [key, item] of Object.entries(value)) {\n const safe = toJsonSafe(item, depth + 1, ancestors);\n if (safe !== undefined) {\n result[key] = safe as Json;\n }\n }\n return result;\n } finally {\n ancestors.delete(value);\n }\n}\n\n/**\n * Serialize an `Error` with its own JSON safe properties and its `cause`.\n *\n * @param error - The error to serialize.\n * @param depth - How deep the error is nested inside the top level error.\n * @param ancestors - The objects currently being serialized, to detect cycles.\n * @returns The serialized error.\n */\nfunction serializeErrorObject(\n error: Error,\n depth: number,\n ancestors: WeakSet<object>,\n): SerializedQueryError {\n ancestors.add(error);\n try {\n const result: SerializedQueryError = {\n name: error.name,\n message: getErrorMessage(error),\n };\n for (const key of Object.keys(error)) {\n if (!RESERVED_ERROR_KEYS.has(key)) {\n const safe = toJsonSafe(\n (error as unknown as Record<string, unknown>)[key],\n depth + 1,\n ancestors,\n );\n if (safe !== undefined) {\n result[key] = safe;\n }\n }\n }\n const cause = toJsonSafe(error.cause, depth + 1, ancestors);\n if (cause !== undefined) {\n result.cause = cause;\n }\n return result;\n } finally {\n ancestors.delete(error);\n }\n}\n\n/**\n * Convert a thrown value into a JSON safe error.\n *\n * For an `Error`, this keeps its `name`, `message`, own JSON safe properties\n * and `cause`. Any other thrown value is reported with the name `Error`.\n *\n * @param error - The raw error stored on a query, if any.\n * @returns The serialized error, or null if there is no error.\n */\nfunction serializeQueryError(error: unknown): SerializedQueryError | null {\n if (error === null) {\n return null;\n }\n if (!(error instanceof Error)) {\n return { name: 'Error', message: getErrorMessage(error) };\n }\n try {\n return serializeErrorObject(error, 0, new WeakSet());\n } catch {\n return { name: error.name, message: getErrorMessage(error) };\n }\n}\n\n/**\n * Serialize the errors held by a query state so it survives JSON round trips.\n *\n * @param state - The raw query state.\n * @returns The query state with `error` and `fetchFailureReason` serialized.\n */\nfunction serializeQueryState(\n state: DehydratedState['queries'][number]['state'],\n): DataServiceQueryState {\n return {\n ...state,\n error: serializeQueryError(state.error),\n fetchFailureReason: serializeQueryError(state.fetchFailureReason),\n };\n}\n\nexport type DataServiceGranularCacheUpdatedPayload = {\n objectType: 'query' | 'mutation';\n} & (\n | { type: 'added' | 'updated'; state: CacheUpdatedState }\n | {\n type: 'removed';\n state: null;\n }\n);\n\nexport type DataServiceCacheUpdatedPayload =\n DataServiceGranularCacheUpdatedPayload & {\n hash: string;\n };\n\ntype CacheUpdatedType = DataServiceCacheUpdatedPayload['type'];\n\nexport type DataServiceInvalidateQueriesAction<ServiceName extends string> = {\n type: `${ServiceName}:invalidateQueries`;\n handler: BaseDataService<\n ServiceName,\n BaseMessenger<ServiceName>\n >['invalidateQueries'];\n};\n\nexport type DataServiceActions<ServiceName extends string> =\n DataServiceInvalidateQueriesAction<ServiceName>;\n\ntype DataServiceAllowedActions =\n | StorageServiceGetItemAction\n | StorageServiceSetItemAction\n | StorageServiceRemoveItemAction;\n\nexport type DataServiceCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated`;\n payload: [DataServiceCacheUpdatedPayload];\n};\n\nexport type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated:${string}`;\n payload: [DataServiceGranularCacheUpdatedPayload];\n};\n\nexport type DataServiceEvents<ServiceName extends string> =\n | DataServiceCacheUpdatedEvent<ServiceName>\n | DataServiceGranularCacheUpdatedEvent<ServiceName>;\n\n/*\n * Defaults to apply to all data service queries if no default option specified.\n */\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\n },\n mutations: {\n retry: false,\n },\n};\n\nexport const STORAGE_SERVICE_KEY = 'cache';\n\n/**\n * Options for persistence configuration.\n */\nexport type PersistenceConfiguration = {\n /**\n * The maximum age before the cache is treated as expired in milliseconds.\n * This is relevant for rehydrating the state during initialization,\n * if the cached state is too old it will be discarded.\n */\n maxAge: number;\n /**\n * The number of milliseconds to wait before triggering persistence following a cache update.\n */\n writeDelay?: number;\n /**\n * The maximum number of milliseconds to wait between persistence writes.\n */\n maxWriteDelay?: number;\n};\n\ntype PersistedCache = {\n state: DehydratedState;\n timestamp: number;\n};\n\nexport class BaseDataService<\n ServiceName extends string,\n ServiceMessenger extends BaseMessenger<ServiceName>,\n> {\n public readonly name: ServiceName;\n\n readonly #messenger: Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n\n readonly #externalMessenger: Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n\n protected messenger: ServiceMessenger;\n\n readonly #policy: ServicePolicy;\n\n readonly #queryClient: QueryClient;\n\n readonly #queryCacheUnsubscribe: () => void;\n\n readonly #mutationCacheUnsubscribe: () => void;\n\n readonly #debouncedPersist?: DebouncedFunc<() => void>;\n\n readonly #persistenceConfig?: PersistenceConfiguration;\n\n constructor({\n name,\n messenger,\n queryClientConfig = {},\n policyOptions,\n persistenceConfig,\n }: {\n name: ServiceName;\n messenger: DataServiceActions<ServiceName>['type'] extends\n | MessengerActions<ServiceMessenger>['type']\n | DataServiceAllowedActions['type']\n ? DataServiceEvents<ServiceName>['type'] extends MessengerEvents<ServiceMessenger>['type']\n ? ServiceMessenger\n : never\n : never;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n persistenceConfig?: PersistenceConfiguration;\n }) {\n this.name = name;\n\n // We store two narrowly-typed messengers alongside the generic public one:\n // - #messenger handles the service's own action registration and event publishing\n // - #externalMessenger handles calls to external actions\n // Splitting them avoids TypeScript issues with mixing template-literals with regular strings\n this.#messenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n this.#externalMessenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n this.messenger = messenger;\n\n this.#queryClient = new QueryClient({\n ...queryClientConfig,\n defaultOptions: {\n queries: {\n ...QUERY_CLIENT_DEFAULTS.queries,\n ...queryClientConfig.defaultOptions?.queries,\n },\n mutations: {\n ...QUERY_CLIENT_DEFAULTS.mutations,\n ...queryClientConfig.defaultOptions?.mutations,\n },\n },\n });\n\n this.#persistenceConfig = persistenceConfig;\n\n this.#policy = createServicePolicy(policyOptions);\n\n this.#debouncedPersist =\n this.#persistenceConfig &&\n debounce(\n () => {\n this.#persistCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n },\n this.#persistenceConfig.writeDelay ??\n inMilliseconds(10, Duration.Second),\n {\n maxWait:\n this.#persistenceConfig.maxWriteDelay ??\n inMilliseconds(1, Duration.Minute),\n },\n );\n\n this.#queryCacheUnsubscribe = this.#queryClient\n .getQueryCache()\n .subscribe((event) => {\n log('Query cache event emitted', event);\n if (['added', 'updated', 'removed'].includes(event.type)) {\n this.#publishCacheUpdate(\n 'query',\n event.type as CacheUpdatedType,\n event.query.queryHash,\n );\n\n this.#debouncedPersist?.();\n }\n });\n\n log('Subscribing to mutation cache');\n this.#mutationCacheUnsubscribe = this.#queryClient\n .getMutationCache()\n .subscribe((event) => {\n log('Mutation cache event emitted', event);\n if (\n ['added', 'updated', 'removed'].includes(event.type) &&\n event.mutation?.options.mutationKey !== undefined\n ) {\n const mutationHash = hashKey(event.mutation.options.mutationKey);\n this.#publishCacheUpdate(\n 'mutation',\n event.type as CacheUpdatedType,\n mutationHash,\n );\n\n this.#debouncedPersist?.();\n }\n });\n\n this.#messenger.registerActionHandler(\n `${this.name}:invalidateQueries`,\n this.invalidateQueries.bind(this),\n );\n }\n\n /**\n * Fetch a query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.queryFn - The query function.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @param options.onQueryStateChange - An optional callback that receives the\n * state of the query (with serialized errors) as it changes. It is called\n * once with the current state if the query is already cached, then with\n * every update until the fetch has settled and the query is idle.\n * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >({\n queryFn,\n responseStruct,\n onQueryStateChange,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey>;\n responseStruct?: TDataStruct;\n onQueryStateChange?: QueryStateChangeHandler;\n }): Promise<TData> {\n const runFetch = async (): Promise<TData> =>\n this.#queryClient.fetchQuery({\n ...options,\n queryFn: async (context) => {\n const response = await this.#policy.execute(() => queryFn(context));\n return processQueryResponse(\n options.queryKey,\n response,\n responseStruct,\n );\n },\n });\n\n if (!onQueryStateChange) {\n return runFetch();\n }\n\n return this.#withQueryStateChange(\n options.queryKey,\n onQueryStateChange,\n runFetch,\n );\n }\n\n /**\n * Fetch a paginated query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @param pageParam - An optional page parameter.\n * @returns The query result, exclusively the requested page is returned.\n */\n protected async fetchInfiniteQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData extends TQueryFnData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n {\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>,\n TQueryKey,\n TPageParam\n >,\n 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'\n >,\n 'queryKey'\n > &\n InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;\n responseStruct?: TDataStruct;\n },\n pageParam?: TPageParam,\n ): Promise<TData> {\n const cache = this.#queryClient.getQueryCache();\n\n const query = cache.find<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>\n >({\n queryKey: options.queryKey,\n });\n\n if (!query?.state.data || !pageParam) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: pageParam ?? options.initialPageParam,\n queryFn: async (context) => {\n const response = await this.#policy.execute(async () =>\n options.queryFn({\n ...context,\n pageParam: context.meta?.pageParam ?? context.pageParam,\n }),\n );\n return processQueryResponse(\n options.queryKey,\n response,\n responseStruct,\n );\n },\n });\n\n return result.pages[0];\n }\n\n const { pages, pageParams } = query.state.data;\n const next = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n\n const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';\n\n const result = await query.fetch(\n { ...query.options, meta: { pageParam } },\n { meta: { fetchMore: { direction } } },\n );\n\n const pageIndex = result.pageParams.findIndex((param) =>\n deepEqual(param, pageParam),\n );\n\n return result.pages[pageIndex];\n }\n\n /**\n * Execute a mutation (e.g. a request that is expected to change server-side data).\n * Unlike `fetchQuery`, the request will not be cached or retried.\n *\n * @param options - The options defining the mutation. Keep in mind that `mutationKey` and `mutationFn` are required when using data services.\n * Additionally, `retry` and `retryDelay` are not available.\n * @param options.mutationFn - The mutation function.\n * @param options.responseStruct - An optional struct for validating the response of the mutation function.\n * @param options.globalId - A string which uniquely identifies this mutation\n * between the query client in this data service\n * and the one that `createUIQueryClient` in `@metamask/react-data-query` holds.\n * This global ID will be stored in the `meta` data of the created mutation\n * and included in `:cacheUpdated` payloads. Defaults to a UUID.\n * @returns The mutation results.\n */\n protected async executeMutation<\n TMutationFnData extends Json,\n TDataStruct extends Struct<TMutationFnData> | undefined = undefined,\n TData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TMutationFnData,\n TError = DefaultError,\n TOnMutateResult = unknown,\n TMutationKey extends MutationKey = MutationKey,\n >({\n mutationFn,\n responseStruct,\n globalId = uuidV4(),\n ...options\n }: OmitKeyof<\n MutationOptions<TData, TError, Record<never, never>, TOnMutateResult>,\n 'retry' | 'retryDelay' | 'mutationKey' | 'mutationFn'\n > & {\n mutationKey: TMutationKey;\n mutationFn: MutationFunction<TMutationFnData, Record<never, never>>;\n responseStruct?: TDataStruct;\n globalId?: string;\n }): Promise<TData> {\n const mutationCache = this.#queryClient.getMutationCache();\n const mutation = mutationCache.build<\n TData,\n TError,\n Record<never, never>,\n TOnMutateResult\n >(this.#queryClient, {\n ...options,\n meta: {\n ...options.meta,\n globalId,\n },\n mutationFn: async (...args) => {\n // To guard against mutations being retried, we deliberately execute the\n // mutation function through the circuit breaker policy alone, rather\n // than through `this.#policy` (which is a combination of both a\n // circuit breaker policy and retry policy).\n const response = await this.#policy.circuitBreakerPolicy.execute(() =>\n mutationFn(...args),\n );\n // Type assertion: TypeScript is not able to unify the type that this\n // function returns with `TData` at compile-time. We can still typecheck\n // the arguments, though.\n return processMutationResponse(\n options.mutationKey,\n response,\n responseStruct,\n ) as TData;\n },\n });\n // We purposely pass an empty set of variables because this method is\n // intended to be used internally by the data service, not end users, and\n // the data service has full control of `mutationFn` anyway.\n return await mutation.execute({});\n }\n\n /**\n * Invalidate queries serviced by this data service.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @param options - Additional optional options for query invalidations.\n * @returns Nothing.\n */\n async invalidateQueries(\n filters?: InvalidateQueryFilters<QueryKey>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\n }\n\n /**\n * Cancel in-flight queries serviced by this data service.\n *\n * Use this in your subclass if you need to abort a concurrent fetch before\n * starting a forced refresh (e.g. `Cache-Control: no-cache` reads), so a\n * slower non-fresh request cannot overwrite the result.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @param cancelOptions - Optional options for cancelling the queries.\n * @returns Nothing.\n */\n protected async cancelQueries(\n filters?: QueryFilters<QueryKey>,\n cancelOptions?: CancelOptions,\n ): Promise<void> {\n await this.#queryClient.cancelQueries(filters, cancelOptions);\n }\n\n /**\n * Initialize the service, rehydrating the cache with persisted data if possible.\n */\n init(): void {\n this.#loadCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n }\n\n /**\n * Prepares the service for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n */\n destroy(): void {\n this.#debouncedPersist?.cancel();\n this.#queryCacheUnsubscribe();\n this.#mutationCacheUnsubscribe();\n // `QueryClient.clear()` clears both caches, but `MutationCache.clear()`\n // only drops its references to mutations without clearing their pending\n // garbage-collection timers. We destroy each mutation first so those timers\n // are cleared and do not keep the process alive.\n for (const mutation of this.#queryClient.getMutationCache().getAll()) {\n mutation.destroy();\n }\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Run a fetch while reporting the state of its query to a handler.\n *\n * The handler receives the current state up front if the query is cached,\n * then every `updated` cache event for the query. It is\n * unsubscribed once the fetch has settled and the last reported state is\n * idle, so a background fetch that outlives this call is still reported\n * until it finishes. Errors thrown by the handler are logged and ignored.\n *\n * @param queryKey - The key of the query being fetched.\n * @param handler - The callback receiving query states.\n * @param runFetch - The function performing the fetch.\n * @returns The result of the fetch.\n */\n async #withQueryStateChange<Result>(\n queryKey: QueryKey,\n handler: QueryStateChangeHandler,\n runFetch: () => Promise<Result>,\n ): Promise<Result> {\n const notify = (state: DataServiceQueryState): void => {\n try {\n handler(state);\n } catch (error) {\n log('onQueryStateChange handler threw', error);\n }\n };\n\n const eventType = `${this.name}:cacheUpdated:${hashKey(queryKey)}` as const;\n let settled = false;\n let idle = true;\n\n const unsubscribe = (\n handlerToRemove: (\n payload: DataServiceGranularCacheUpdatedPayload,\n ) => void,\n ): void => {\n try {\n this.#messenger.unsubscribe(eventType, handlerToRemove);\n } catch {\n // The subscription was already cleared, e.g. by `destroy`.\n }\n };\n\n const listener = (\n payload: DataServiceGranularCacheUpdatedPayload,\n ): void => {\n // `added` only carries the blank state built right before the fetch\n // starts (pending and idle), and `removed` carries no state at all.\n if (payload.type !== 'updated') {\n return;\n }\n const { state } = payload.state.queries[0];\n idle = state.fetchStatus === 'idle';\n notify(state);\n if (settled && idle) {\n unsubscribe(listener);\n }\n };\n\n const current = this.#queryClient.getQueryState(queryKey);\n if (current) {\n idle = current.fetchStatus === 'idle';\n notify(serializeQueryState(current));\n }\n\n this.#messenger.subscribe(eventType, listener);\n\n try {\n return await runFetch();\n } finally {\n settled = true;\n if (idle) {\n unsubscribe(listener);\n }\n }\n }\n\n /**\n * Publish `cacheUpdated` events when the query or mutation cache is updated.\n *\n * @param objectType - The type of object updated (\"query\" or \"mutation\").\n * @param eventType - What happened to the query or mutation (\"added\" or \"updated\").\n * @param hash - The hash of the query or mutation.\n */\n #publishCacheUpdate(\n objectType: 'query' | 'mutation',\n eventType: CacheUpdatedType,\n hash: string,\n ): void {\n const dehydrated =\n eventType === 'added' || eventType === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) =>\n objectType === 'query' && query.queryHash === hash,\n shouldDehydrateMutation: (mutation) =>\n objectType === 'mutation' &&\n mutation.options.mutationKey !== undefined &&\n hashKey(mutation.options.mutationKey) === hash,\n })\n : null;\n const state = dehydrated && {\n ...dehydrated,\n // The in flight `promise` is not JSON safe, so it is left out.\n queries: dehydrated.queries.map(({ promise: _promise, ...query }) => ({\n ...query,\n state: serializeQueryState(query.state),\n })),\n };\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type: eventType,\n objectType,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type: eventType,\n objectType,\n state,\n } as DataServiceGranularCacheUpdatedPayload,\n );\n }\n\n /**\n * Persist the query client cache using the StorageService, if the cache is not empty.\n *\n * @returns Nothing.\n */\n async #persistCache(): Promise<void> {\n const state = dehydrate(this.#queryClient, {\n // This is the default, but we specify it to be explicit.\n shouldDehydrateQuery: (query) => query.state.status === 'success',\n });\n\n if (state.queries.length === 0 && state.mutations.length === 0) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n const cache: PersistedCache = {\n timestamp: Date.now(),\n state,\n };\n\n await this.#externalMessenger.call(\n 'StorageService:setItem',\n this.name,\n STORAGE_SERVICE_KEY,\n cache as unknown as Json,\n );\n }\n\n /**\n * Load the query client cache from the StorageService, if persistence is configured\n * and the persisted cache is not expired.\n *\n * @returns Nothing.\n */\n async #loadCache(): Promise<void> {\n if (!this.#persistenceConfig) {\n return;\n }\n\n const { result: untypedCache } = await this.#externalMessenger.call(\n 'StorageService:getItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n\n if (!untypedCache) {\n return;\n }\n\n const cache = untypedCache as unknown as PersistedCache;\n\n if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n hydrate(this.#queryClient, cache.state);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"BaseDataService.js","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,EAYL,WAAW,EAKX,SAAS,EACT,OAAO,EACP,OAAO,GAER,MAAM,sBAAsB,CAAC;AAC9B,OAAO,SAAS,MAAM,iBAAiB,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAiB,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,EACL,mBAAmB,GAGpB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAE3E,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,iBAAiB,CA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,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,EACnB,KAAwB,CACzB,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,UAAU;QACd,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC;YAC7B,OAAO;QACT,CAAC;QAED,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,IAAI,CAAC,kBAAkB,CAAC,IAAI,CACjE,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QAEF,IAAI,CAAC,YAAY,EAAE,CAAC;YAClB,OAAO;QACT,CAAC;QAED,MAAM,KAAK,GAAG,YAAyC,CAAC;QAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,IAAI,CAAC,kBAAkB,CAAC,MAAM,EAAE,CAAC;YACnE,MAAM,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;YACF,OAAO;QACT,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,YAAY,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;CACF","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n MessengerActions,\n MessengerEvents,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\nimport { Struct } from '@metamask/superstruct';\nimport { Duration, inMilliseconds } from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport {\n DefaultError,\n DefaultOptions,\n DehydratedState,\n FetchQueryOptions,\n InfiniteData,\n InfiniteQueryPageParamsOptions,\n CancelOptions,\n InvalidateOptions,\n InvalidateQueryFilters,\n MutationOptions,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\n QueryFilters,\n QueryFunction,\n WithRequired,\n dehydrate,\n hydrate,\n hashKey,\n MutationFunction,\n} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\nimport { debounce, DebouncedFunc } from 'lodash-es';\nimport { v4 as uuidV4 } from 'uuid';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\nimport { createModuleLogger, projectLogger } from './loggers.js';\nimport { processMutationResponse, processQueryResponse } from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'BaseDataService');\n\n/**\n * Data service mutations and queries use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\ntype Key = [string, ...Json[]] | readonly [string, ...Json[]];\n\n/*\n * Data service queries use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\nexport type QueryKey = Key;\n\n/*\n * Data service mutations use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\nexport type MutationKey = Key;\n\n/**\n * The supertype of all messengers, scoped to a namespace.\n *\n * @template Namespace - The namespace for the messenger's own actions and\n * events.\n */\nexport type BaseMessenger<Namespace extends string> = Messenger<\n Namespace,\n ActionConstraint,\n EventConstraint,\n // Use `any` to allow any parent to be set. `any` is harmless in a type constraint anyway,\n // it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\nexport type DataServiceGranularCacheUpdatedPayload = {\n objectType: 'query' | 'mutation';\n} & (\n | { type: 'added' | 'updated'; state: DehydratedState }\n | {\n type: 'removed';\n state: null;\n }\n);\n\nexport type DataServiceCacheUpdatedPayload =\n DataServiceGranularCacheUpdatedPayload & {\n hash: string;\n };\n\ntype CacheUpdatedType = DataServiceCacheUpdatedPayload['type'];\n\nexport type DataServiceInvalidateQueriesAction<ServiceName extends string> = {\n type: `${ServiceName}:invalidateQueries`;\n handler: BaseDataService<\n ServiceName,\n BaseMessenger<ServiceName>\n >['invalidateQueries'];\n};\n\nexport type DataServiceActions<ServiceName extends string> =\n DataServiceInvalidateQueriesAction<ServiceName>;\n\ntype DataServiceAllowedActions =\n | StorageServiceGetItemAction\n | StorageServiceSetItemAction\n | StorageServiceRemoveItemAction;\n\nexport type DataServiceCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated`;\n payload: [DataServiceCacheUpdatedPayload];\n};\n\nexport type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated:${string}`;\n payload: [DataServiceGranularCacheUpdatedPayload];\n};\n\nexport type DataServiceEvents<ServiceName extends string> =\n | DataServiceCacheUpdatedEvent<ServiceName>\n | DataServiceGranularCacheUpdatedEvent<ServiceName>;\n\n/*\n * Defaults to apply to all data service queries if no default option specified.\n */\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\n },\n mutations: {\n retry: false,\n },\n};\n\nexport const STORAGE_SERVICE_KEY = 'cache';\n\n/**\n * Options for persistence configuration.\n */\nexport type PersistenceConfiguration = {\n /**\n * The maximum age before the cache is treated as expired in milliseconds.\n * This is relevant for rehydrating the state during initialization,\n * if the cached state is too old it will be discarded.\n */\n maxAge: number;\n /**\n * The number of milliseconds to wait before triggering persistence following a cache update.\n */\n writeDelay?: number;\n /**\n * The maximum number of milliseconds to wait between persistence writes.\n */\n maxWriteDelay?: number;\n};\n\ntype PersistedCache = {\n state: DehydratedState;\n timestamp: number;\n};\n\nexport class BaseDataService<\n ServiceName extends string,\n ServiceMessenger extends BaseMessenger<ServiceName>,\n> {\n public readonly name: ServiceName;\n\n readonly #messenger: Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n\n readonly #externalMessenger: Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n\n protected messenger: ServiceMessenger;\n\n readonly #policy: ServicePolicy;\n\n readonly #queryClient: QueryClient;\n\n readonly #queryCacheUnsubscribe: () => void;\n\n readonly #mutationCacheUnsubscribe: () => void;\n\n readonly #debouncedPersist?: DebouncedFunc<() => void>;\n\n readonly #persistenceConfig?: PersistenceConfiguration;\n\n constructor({\n name,\n messenger,\n queryClientConfig = {},\n policyOptions,\n persistenceConfig,\n }: {\n name: ServiceName;\n messenger: DataServiceActions<ServiceName>['type'] extends\n | MessengerActions<ServiceMessenger>['type']\n | DataServiceAllowedActions['type']\n ? DataServiceEvents<ServiceName>['type'] extends MessengerEvents<ServiceMessenger>['type']\n ? ServiceMessenger\n : never\n : never;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n persistenceConfig?: PersistenceConfiguration;\n }) {\n this.name = name;\n\n // We store two narrowly-typed messengers alongside the generic public one:\n // - #messenger handles the service's own action registration and event publishing\n // - #externalMessenger handles calls to external actions\n // Splitting them avoids TypeScript issues with mixing template-literals with regular strings\n this.#messenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n this.#externalMessenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n this.messenger = messenger;\n\n this.#queryClient = new QueryClient({\n ...queryClientConfig,\n defaultOptions: {\n queries: {\n ...QUERY_CLIENT_DEFAULTS.queries,\n ...queryClientConfig.defaultOptions?.queries,\n },\n mutations: {\n ...QUERY_CLIENT_DEFAULTS.mutations,\n ...queryClientConfig.defaultOptions?.mutations,\n },\n },\n });\n\n this.#persistenceConfig = persistenceConfig;\n\n this.#policy = createServicePolicy(policyOptions);\n\n this.#debouncedPersist =\n this.#persistenceConfig &&\n debounce(\n () => {\n this.#persistCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n },\n this.#persistenceConfig.writeDelay ??\n inMilliseconds(10, Duration.Second),\n {\n maxWait:\n this.#persistenceConfig.maxWriteDelay ??\n inMilliseconds(1, Duration.Minute),\n },\n );\n\n this.#queryCacheUnsubscribe = this.#queryClient\n .getQueryCache()\n .subscribe((event) => {\n log('Query cache event emitted', event);\n if (['added', 'updated', 'removed'].includes(event.type)) {\n this.#publishCacheUpdate(\n 'query',\n event.type as CacheUpdatedType,\n event.query.queryHash,\n );\n\n this.#debouncedPersist?.();\n }\n });\n\n log('Subscribing to mutation cache');\n this.#mutationCacheUnsubscribe = this.#queryClient\n .getMutationCache()\n .subscribe((event) => {\n log('Mutation cache event emitted', event);\n if (\n ['added', 'updated', 'removed'].includes(event.type) &&\n event.mutation?.options.mutationKey !== undefined\n ) {\n const mutationHash = hashKey(event.mutation.options.mutationKey);\n this.#publishCacheUpdate(\n 'mutation',\n event.type as CacheUpdatedType,\n mutationHash,\n );\n\n this.#debouncedPersist?.();\n }\n });\n\n this.#messenger.registerActionHandler(\n `${this.name}:invalidateQueries`,\n this.invalidateQueries.bind(this),\n );\n }\n\n /**\n * Fetch a query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.queryFn - The query function.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >({\n queryFn,\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey>;\n responseStruct?: TDataStruct;\n }): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: async (context) => {\n const response = await this.#policy.execute(() => queryFn(context));\n return processQueryResponse(options.queryKey, response, responseStruct);\n },\n });\n }\n\n /**\n * Fetch a paginated query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @param pageParam - An optional page parameter.\n * @returns The query result, exclusively the requested page is returned.\n */\n protected async fetchInfiniteQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData extends TQueryFnData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n {\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>,\n TQueryKey,\n TPageParam\n >,\n 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'\n >,\n 'queryKey'\n > &\n InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;\n responseStruct?: TDataStruct;\n },\n pageParam?: TPageParam,\n ): Promise<TData> {\n const cache = this.#queryClient.getQueryCache();\n\n const query = cache.find<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>\n >({\n queryKey: options.queryKey,\n });\n\n if (!query?.state.data || !pageParam) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: pageParam ?? options.initialPageParam,\n queryFn: async (context) => {\n const response = await this.#policy.execute(async () =>\n options.queryFn({\n ...context,\n pageParam: context.meta?.pageParam ?? context.pageParam,\n }),\n );\n return processQueryResponse(\n options.queryKey,\n response,\n responseStruct,\n );\n },\n });\n\n return result.pages[0];\n }\n\n const { pages, pageParams } = query.state.data;\n const next = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n\n const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';\n\n const result = await query.fetch(\n { ...query.options, meta: { pageParam } },\n { meta: { fetchMore: { direction } } },\n );\n\n const pageIndex = result.pageParams.findIndex((param) =>\n deepEqual(param, pageParam),\n );\n\n return result.pages[pageIndex];\n }\n\n /**\n * Execute a mutation (e.g. a request that is expected to change server-side data).\n * Unlike `fetchQuery`, the request will not be cached or retried.\n *\n * @param options - The options defining the mutation. Keep in mind that `mutationKey` and `mutationFn` are required when using data services.\n * Additionally, `retry` and `retryDelay` are not available.\n * @param options.mutationFn - The mutation function.\n * @param options.responseStruct - An optional struct for validating the response of the mutation function.\n * @param options.globalId - A string which uniquely identifies this mutation\n * between the query client in this data service\n * and the one that `createUIQueryClient` in `@metamask/react-data-query` holds.\n * This global ID will be stored in the `meta` data of the created mutation\n * and included in `:cacheUpdated` payloads. Defaults to a UUID.\n * @returns The mutation results.\n */\n protected async executeMutation<\n TMutationFnData extends Json,\n TDataStruct extends Struct<TMutationFnData> | undefined = undefined,\n TData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TMutationFnData,\n TError = DefaultError,\n TOnMutateResult = unknown,\n TMutationKey extends MutationKey = MutationKey,\n >({\n mutationFn,\n responseStruct,\n globalId = uuidV4(),\n ...options\n }: OmitKeyof<\n MutationOptions<TData, TError, Record<never, never>, TOnMutateResult>,\n 'retry' | 'retryDelay' | 'mutationKey' | 'mutationFn'\n > & {\n mutationKey: TMutationKey;\n mutationFn: MutationFunction<TMutationFnData, Record<never, never>>;\n responseStruct?: TDataStruct;\n globalId?: string;\n }): Promise<TData> {\n const mutationCache = this.#queryClient.getMutationCache();\n const mutation = mutationCache.build<\n TData,\n TError,\n Record<never, never>,\n TOnMutateResult\n >(this.#queryClient, {\n ...options,\n meta: {\n ...options.meta,\n globalId,\n },\n mutationFn: async (...args) => {\n // To guard against mutations being retried, we deliberately execute the\n // mutation function through the circuit breaker policy alone, rather\n // than through `this.#policy` (which is a combination of both a\n // circuit breaker policy and retry policy).\n const response = await this.#policy.circuitBreakerPolicy.execute(() =>\n mutationFn(...args),\n );\n // Type assertion: TypeScript is not able to unify the type that this\n // function returns with `TData` at compile-time. We can still typecheck\n // the arguments, though.\n return processMutationResponse(\n options.mutationKey,\n response,\n responseStruct,\n ) as TData;\n },\n });\n // We purposely pass an empty set of variables because this method is\n // intended to be used internally by the data service, not end users, and\n // the data service has full control of `mutationFn` anyway.\n return await mutation.execute({});\n }\n\n /**\n * Invalidate queries serviced by this data service.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @param options - Additional optional options for query invalidations.\n * @returns Nothing.\n */\n async invalidateQueries(\n filters?: InvalidateQueryFilters<QueryKey>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\n }\n\n /**\n * Cancel in-flight queries serviced by this data service.\n *\n * Use this in your subclass if you need to abort a concurrent fetch before\n * starting a forced refresh (e.g. `Cache-Control: no-cache` reads), so a\n * slower non-fresh request cannot overwrite the result.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @param cancelOptions - Optional options for cancelling the queries.\n * @returns Nothing.\n */\n protected async cancelQueries(\n filters?: QueryFilters<QueryKey>,\n cancelOptions?: CancelOptions,\n ): Promise<void> {\n await this.#queryClient.cancelQueries(filters, cancelOptions);\n }\n\n /**\n * Initialize the service, rehydrating the cache with persisted data if possible.\n */\n init(): void {\n this.#loadCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n }\n\n /**\n * Prepares the service for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n */\n destroy(): void {\n this.#debouncedPersist?.cancel();\n this.#queryCacheUnsubscribe();\n this.#mutationCacheUnsubscribe();\n // `QueryClient.clear()` clears both caches, but `MutationCache.clear()`\n // only drops its references to mutations without clearing their pending\n // garbage-collection timers. We destroy each mutation first so those timers\n // are cleared and do not keep the process alive.\n for (const mutation of this.#queryClient.getMutationCache().getAll()) {\n mutation.destroy();\n }\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when the query or mutation cache is updated.\n *\n * @param objectType - The type of object updated (\"query\" or \"mutation\").\n * @param eventType - What happened to the query or mutation (\"added\" or \"updated\").\n * @param hash - The hash of the query or mutation.\n */\n #publishCacheUpdate(\n objectType: 'query' | 'mutation',\n eventType: CacheUpdatedType,\n hash: string,\n ): void {\n const state =\n eventType === 'added' || eventType === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) =>\n objectType === 'query' && query.queryHash === hash,\n shouldDehydrateMutation: (mutation) =>\n objectType === 'mutation' &&\n mutation.options.mutationKey !== undefined &&\n hashKey(mutation.options.mutationKey) === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type: eventType,\n objectType,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type: eventType,\n objectType,\n state,\n } as DataServiceGranularCacheUpdatedPayload,\n );\n }\n\n /**\n * Persist the query client cache using the StorageService, if the cache is not empty.\n *\n * @returns Nothing.\n */\n async #persistCache(): Promise<void> {\n const state = dehydrate(this.#queryClient, {\n // This is the default, but we specify it to be explicit.\n shouldDehydrateQuery: (query) => query.state.status === 'success',\n });\n\n if (state.queries.length === 0 && state.mutations.length === 0) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n const cache: PersistedCache = {\n timestamp: Date.now(),\n state,\n };\n\n await this.#externalMessenger.call(\n 'StorageService:setItem',\n this.name,\n STORAGE_SERVICE_KEY,\n cache as unknown as Json,\n );\n }\n\n /**\n * Load the query client cache from the StorageService, if persistence is configured\n * and the persisted cache is not expired.\n *\n * @returns Nothing.\n */\n async #loadCache(): Promise<void> {\n if (!this.#persistenceConfig) {\n return;\n }\n\n const { result: untypedCache } = await this.#externalMessenger.call(\n 'StorageService:getItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n\n if (!untypedCache) {\n return;\n }\n\n const cache = untypedCache as unknown as PersistedCache;\n\n if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n hydrate(this.#queryClient, cache.state);\n }\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export type { Event as CockatielEvent, FailureReason as CockatielFailureReason, } from 'cockatiel';
|
|
2
2
|
export { BrokenCircuitError, EventEmitter as CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, } from 'cockatiel';
|
|
3
|
-
export type {
|
|
3
|
+
export type { DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey, MutationKey, PersistenceConfiguration, } from './BaseDataService.js';
|
|
4
4
|
export { BaseDataService } from './BaseDataService.js';
|
|
5
5
|
export { DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, createServicePolicy, } from './createServicePolicy.js';
|
|
6
6
|
export type { CreateServicePolicyOptions, ServicePolicy, } from './createServicePolicy.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,MAAM,WAAW,CAAC;AAEnB,YAAY,EACV,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,MAAM,WAAW,CAAC;AAEnB,YAAY,EACV,kBAAkB,EAClB,iBAAiB,EACjB,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,EACR,WAAW,EACX,wBAAwB,GACzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,0BAA0B,CAAC;AAClC,YAAY,EACV,0BAA0B,EAC1B,aAAa,GACd,MAAM,0BAA0B,CAAC"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,MAAM,WAAW,CAAC;AAcnB,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,0BAA0B,CAAC","sourcesContent":["export type {\n Event as CockatielEvent,\n FailureReason as CockatielFailureReason,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n EventEmitter as CockatielEventEmitter,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n} from 'cockatiel';\n\nexport type {\n DataServiceActions,\n DataServiceEvents,\n DataServiceCacheUpdatedPayload,\n DataServiceGranularCacheUpdatedPayload,\n DataServiceInvalidateQueriesAction,\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n QueryKey,\n MutationKey,\n PersistenceConfiguration,\n} from './BaseDataService.js';\nexport { BaseDataService } from './BaseDataService.js';\n\nexport {\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n createServicePolicy,\n} from './createServicePolicy.js';\nexport type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/base-data-service",
|
|
3
|
-
"version": "2.1.0-preview-
|
|
3
|
+
"version": "2.1.0-preview-b6e8e7385",
|
|
4
4
|
"description": "Provides utilities for building data services",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"registry": "https://registry.npmjs.org/"
|
|
33
33
|
},
|
|
34
34
|
"scripts": {
|
|
35
|
+
"allow-scripts": "yarn workspace @metamask/core-monorepo run allow-scripts",
|
|
35
36
|
"build": "tsc --project tsconfig.build.json",
|
|
36
37
|
"build:all": "tsc --build tsconfig.build.json --verbose",
|
|
37
38
|
"build:clean": "yarn build:only-clean && yarn build",
|