@metamask-previews/base-data-service 2.0.0-preview-0a1dd02ad → 2.1.0-preview-452564c37

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 CHANGED
@@ -7,9 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.1.0]
11
+
12
+ ### Added
13
+
14
+ - Add `executeMutation` protected method to `BaseDataService` to allow for making server-state-mutating requests ([#9324](https://github.com/MetaMask/core/pull/9324))
15
+ - These kinds of requests are never retried, unlike queries.
16
+ - To use this, create a method in your data service class which takes whatever arguments you need, plus a optional final argument called `globalId`; then call `executeMutation` with a `mutationKey`, `globalId`, and `mutationFn`. See `ExampleDataService` in this package for an example.
17
+ - A `MutationKey` type is also available.
18
+ - Add protected `cancelQueries` so subclasses can abort in-flight reads before a forced refresh ([#10454](https://github.com/MetaMask/core/pull/10454))
19
+
10
20
  ### Changed
11
21
 
22
+ - The payload for `:cacheUpdated` and `:cacheUpdated:${hash}` events now includes an `objectType` property, which is either "query" or "mutation" ([#9324](https://github.com/MetaMask/core/pull/9324))
12
23
  - Bump `@metamask/utils` from `^11.12.0` to `^12.0.0` ([#10192](https://github.com/MetaMask/core/pull/10192))
24
+ - Add `uuid` `^11.1.1` as a dependency ([#9324](https://github.com/MetaMask/core/pull/9324))
25
+ - Bump `@tanstack/query-core` from `^5.62.16` to `^5.89.0` ([#9324](https://github.com/MetaMask/core/pull/9324))
26
+ - Bump `cockatiel` from `^3.1.2` to `^3.2.1` ([#10436](https://github.com/MetaMask/core/pull/10436))
27
+ - Bump `lodash-es` from `^4.17.21` to `^4.18.1` ([#10447](https://github.com/MetaMask/core/pull/10447))
13
28
 
14
29
  ## [2.0.0]
15
30
 
@@ -100,7 +115,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
100
115
 
101
116
  - Initial release ([#8039](https://github.com/MetaMask/core/pull/8039), [#8292](https://github.com/MetaMask/core/pull/8292))
102
117
 
103
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@2.0.0...HEAD
118
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@2.1.0...HEAD
119
+ [2.1.0]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@2.0.0...@metamask/base-data-service@2.1.0
104
120
  [2.0.0]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@1.0.0...@metamask/base-data-service@2.0.0
105
121
  [1.0.0]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@0.1.3...@metamask/base-data-service@1.0.0
106
122
  [0.1.3]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@0.1.2...@metamask/base-data-service@0.1.3
@@ -2,9 +2,15 @@ import { Messenger, ActionConstraint, EventConstraint, MessengerActions, Messeng
2
2
  import type { StorageServiceGetItemAction, StorageServiceRemoveItemAction, StorageServiceSetItemAction } from '@metamask/storage-service';
3
3
  import { Struct } from '@metamask/superstruct';
4
4
  import type { Json } from '@metamask/utils';
5
- import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from '@tanstack/query-core';
5
+ import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, CancelOptions, InvalidateOptions, InvalidateQueryFilters, MutationOptions, OmitKeyof, QueryClientConfig, QueryFilters, QueryFunction, WithRequired, MutationFunction } from '@tanstack/query-core';
6
6
  import { CreateServicePolicyOptions } from './createServicePolicy.js';
7
- export type QueryKey = [string, ...Json[]] | readonly [string, ...Json[]];
7
+ /**
8
+ * Data service mutations and queries use the following format:
9
+ * `['${ServiceName}:${ActionName}', ...params]`
10
+ */
11
+ type Key = [string, ...Json[]] | readonly [string, ...Json[]];
12
+ export type QueryKey = Key;
13
+ export type MutationKey = Key;
8
14
  /**
9
15
  * The supertype of all messengers, scoped to a namespace.
10
16
  *
@@ -13,12 +19,14 @@ export type QueryKey = [string, ...Json[]] | readonly [string, ...Json[]];
13
19
  */
14
20
  export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
15
21
  export type DataServiceGranularCacheUpdatedPayload = {
22
+ objectType: 'query' | 'mutation';
23
+ } & ({
16
24
  type: 'added' | 'updated';
17
25
  state: DehydratedState;
18
26
  } | {
19
27
  type: 'removed';
20
28
  state: null;
21
- };
29
+ });
22
30
  export type DataServiceCacheUpdatedPayload = DataServiceGranularCacheUpdatedPayload & {
23
31
  hash: string;
24
32
  };
@@ -73,10 +81,11 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
73
81
  *
74
82
  * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
75
83
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
84
+ * @param options.queryFn - The query function.
76
85
  * @param options.responseStruct - An optional struct for validating the response of the query function.
77
86
  * @returns The query results.
78
87
  */
79
- 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>({ responseStruct, ...options }: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay' | 'queryFn'>, 'queryKey'> & {
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'> & {
80
89
  queryFn: QueryFunction<TQueryFnData, TQueryKey>;
81
90
  responseStruct?: TDataStruct;
82
91
  }): Promise<TData>;
@@ -93,6 +102,27 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
93
102
  queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
94
103
  responseStruct?: TDataStruct;
95
104
  }, pageParam?: TPageParam): Promise<TData>;
105
+ /**
106
+ * Execute a mutation (e.g. a request that is expected to change server-side data).
107
+ * Unlike `fetchQuery`, the request will not be cached or retried.
108
+ *
109
+ * @param options - The options defining the mutation. Keep in mind that `mutationKey` and `mutationFn` are required when using data services.
110
+ * Additionally, `retry` and `retryDelay` are not available.
111
+ * @param options.mutationFn - The mutation function.
112
+ * @param options.responseStruct - An optional struct for validating the response of the mutation function.
113
+ * @param options.globalId - A string which uniquely identifies this mutation
114
+ * between the query client in this data service
115
+ * and the one that `createUIQueryClient` in `@metamask/react-data-query` holds.
116
+ * This global ID will be stored in the `meta` data of the created mutation
117
+ * and included in `:cacheUpdated` payloads. Defaults to a UUID.
118
+ * @returns The mutation results.
119
+ */
120
+ protected executeMutation<TMutationFnData extends Json, TDataStruct extends Struct<TMutationFnData> | undefined = undefined, TData = TDataStruct extends Struct<infer StructType> ? StructType : TMutationFnData, TError = DefaultError, TOnMutateResult = unknown, TMutationKey extends MutationKey = MutationKey>({ mutationFn, responseStruct, globalId, ...options }: OmitKeyof<MutationOptions<TData, TError, Record<never, never>, TOnMutateResult>, 'retry' | 'retryDelay' | 'mutationKey' | 'mutationFn'> & {
121
+ mutationKey: TMutationKey;
122
+ mutationFn: MutationFunction<TMutationFnData, Record<never, never>>;
123
+ responseStruct?: TDataStruct;
124
+ globalId?: string;
125
+ }): Promise<TData>;
96
126
  /**
97
127
  * Invalidate queries serviced by this data service.
98
128
  *
@@ -101,6 +131,18 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
101
131
  * @returns Nothing.
102
132
  */
103
133
  invalidateQueries(filters?: InvalidateQueryFilters<QueryKey>, options?: InvalidateOptions): Promise<void>;
134
+ /**
135
+ * Cancel in-flight queries serviced by this data service.
136
+ *
137
+ * Use this in your subclass if you need to abort a concurrent fetch before
138
+ * starting a forced refresh (e.g. `Cache-Control: no-cache` reads), so a
139
+ * slower non-fresh request cannot overwrite the result.
140
+ *
141
+ * @param filters - Optional filter for selecting specific queries.
142
+ * @param cancelOptions - Optional options for cancelling the queries.
143
+ * @returns Nothing.
144
+ */
145
+ protected cancelQueries(filters?: QueryFilters<QueryKey>, cancelOptions?: CancelOptions): Promise<void>;
104
146
  /**
105
147
  * Initialize the service, rehydrating the cache with persisted data if possible.
106
148
  */
@@ -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,iBAAiB,EACjB,sBAAsB,EACtB,SAAS,EAET,iBAAiB,EACjB,aAAa,EACb,YAAY,EAGb,MAAM,sBAAsB,CAAC;AAI9B,OAAO,EAEL,0BAA0B,EAE3B,MAAM,0BAA0B,CAAC;AAIlC,MAAM,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;AAE1E;;;;;GAKG;AACH,MAAM,MAAM,aAAa,CAAC,SAAS,SAAS,MAAM,IAAI,SAAS,CAC7D,SAAS,EACT,gBAAgB,EAChB,eAAe,E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,EACd,QAAmB,EACnB,GAAG,OAAO,EACX,EAAE,SAAS,CACV,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,eAAe,CAAC,EACrE,OAAO,GAAG,YAAY,GAAG,aAAa,GAAG,YAAY,CACtD,GAAG;QACF,WAAW,EAAE,YAAY,CAAC;QAC1B,UAAU,EAAE,gBAAgB,CAAC,eAAe,EAAE,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QACpE,cAAc,CAAC,EAAE,WAAW,CAAC;QAC7B,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,GAAG,OAAO,CAAC,KAAK,CAAC,CAmCjB;IAED;;;;;;OAMG;IACG,iBAAiB,CACrB,OAAO,CAAC,EAAE,sBAAsB,CAAC,QAAQ,CAAC,EAC1C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAEf;IAED;;;;;;;;;;OAUG;IACH,UAAgB,aAAa,CAC3B,OAAO,CAAC,EAAE,YAAY,CAAC,QAAQ,CAAC,EAChC,aAAa,CAAC,EAAE,aAAa,GAC5B,OAAO,CAAC,IAAI,CAAC,CAEf;IAED;;OAEG;IACH,IAAI,IAAI,IAAI,CAKX;IAED;;;OAGG;IACH,OAAO,IAAI,IAAI,CAcd;CAgHF"}
@@ -1,15 +1,23 @@
1
1
  import { Duration, inMilliseconds } from '@metamask/utils';
2
- import { QueryClient, dehydrate, hydrate, } from '@tanstack/query-core';
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';
5
+ import { v4 as uuidV4 } from 'uuid';
5
6
  import { createServicePolicy, } from './createServicePolicy.js';
6
- import { processQueryResponse } from './utils.js';
7
- // Defaults to apply to all data service queries if no default option specified
7
+ import { createModuleLogger, projectLogger } from './loggers.js';
8
+ import { processMutationResponse, processQueryResponse } from './utils.js';
9
+ const log = createModuleLogger(projectLogger, 'BaseDataService');
10
+ /*
11
+ * Defaults to apply to all data service queries if no default option specified.
12
+ */
8
13
  const QUERY_CLIENT_DEFAULTS = {
9
14
  queries: {
10
15
  retry: false,
11
16
  staleTime: inMilliseconds(1, Duration.Minute),
12
17
  },
18
+ mutations: {
19
+ retry: false,
20
+ },
13
21
  };
14
22
  export const STORAGE_SERVICE_KEY = 'cache';
15
23
  export class BaseDataService {
@@ -20,6 +28,7 @@ export class BaseDataService {
20
28
  #policy;
21
29
  #queryClient;
22
30
  #queryCacheUnsubscribe;
31
+ #mutationCacheUnsubscribe;
23
32
  #debouncedPersist;
24
33
  #persistenceConfig;
25
34
  constructor({ name, messenger, queryClientConfig = {}, policyOptions, persistenceConfig, }) {
@@ -38,7 +47,10 @@ export class BaseDataService {
38
47
  ...QUERY_CLIENT_DEFAULTS.queries,
39
48
  ...queryClientConfig.defaultOptions?.queries,
40
49
  },
41
- mutations: queryClientConfig.defaultOptions?.mutations,
50
+ mutations: {
51
+ ...QUERY_CLIENT_DEFAULTS.mutations,
52
+ ...queryClientConfig.defaultOptions?.mutations,
53
+ },
42
54
  },
43
55
  });
44
56
  this.#persistenceConfig = persistenceConfig;
@@ -57,8 +69,21 @@ export class BaseDataService {
57
69
  this.#queryCacheUnsubscribe = this.#queryClient
58
70
  .getQueryCache()
59
71
  .subscribe((event) => {
72
+ log('Query cache event emitted', event);
60
73
  if (['added', 'updated', 'removed'].includes(event.type)) {
61
- this.#publishCacheUpdate(event.query.queryHash, event.type);
74
+ this.#publishCacheUpdate('query', event.type, event.query.queryHash);
75
+ this.#debouncedPersist?.();
76
+ }
77
+ });
78
+ log('Subscribing to mutation cache');
79
+ this.#mutationCacheUnsubscribe = this.#queryClient
80
+ .getMutationCache()
81
+ .subscribe((event) => {
82
+ log('Mutation cache event emitted', event);
83
+ if (['added', 'updated', 'removed'].includes(event.type) &&
84
+ event.mutation?.options.mutationKey !== undefined) {
85
+ const mutationHash = hashKey(event.mutation.options.mutationKey);
86
+ this.#publishCacheUpdate('mutation', event.type, mutationHash);
62
87
  this.#debouncedPersist?.();
63
88
  }
64
89
  });
@@ -69,14 +94,15 @@ export class BaseDataService {
69
94
  *
70
95
  * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
71
96
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
97
+ * @param options.queryFn - The query function.
72
98
  * @param options.responseStruct - An optional struct for validating the response of the query function.
73
99
  * @returns The query results.
74
100
  */
75
- async fetchQuery({ responseStruct, ...options }) {
101
+ async fetchQuery({ queryFn, responseStruct, ...options }) {
76
102
  return this.#queryClient.fetchQuery({
77
103
  ...options,
78
104
  queryFn: async (context) => {
79
- const response = await this.#policy.execute(() => options.queryFn(context));
105
+ const response = await this.#policy.execute(() => queryFn(context));
80
106
  return processQueryResponse(options.queryKey, response, responseStruct);
81
107
  },
82
108
  });
@@ -116,6 +142,46 @@ export class BaseDataService {
116
142
  const pageIndex = result.pageParams.findIndex((param) => deepEqual(param, pageParam));
117
143
  return result.pages[pageIndex];
118
144
  }
145
+ /**
146
+ * Execute a mutation (e.g. a request that is expected to change server-side data).
147
+ * Unlike `fetchQuery`, the request will not be cached or retried.
148
+ *
149
+ * @param options - The options defining the mutation. Keep in mind that `mutationKey` and `mutationFn` are required when using data services.
150
+ * Additionally, `retry` and `retryDelay` are not available.
151
+ * @param options.mutationFn - The mutation function.
152
+ * @param options.responseStruct - An optional struct for validating the response of the mutation function.
153
+ * @param options.globalId - A string which uniquely identifies this mutation
154
+ * between the query client in this data service
155
+ * and the one that `createUIQueryClient` in `@metamask/react-data-query` holds.
156
+ * This global ID will be stored in the `meta` data of the created mutation
157
+ * and included in `:cacheUpdated` payloads. Defaults to a UUID.
158
+ * @returns The mutation results.
159
+ */
160
+ async executeMutation({ mutationFn, responseStruct, globalId = uuidV4(), ...options }) {
161
+ const mutationCache = this.#queryClient.getMutationCache();
162
+ const mutation = mutationCache.build(this.#queryClient, {
163
+ ...options,
164
+ meta: {
165
+ ...options.meta,
166
+ globalId,
167
+ },
168
+ mutationFn: async (...args) => {
169
+ // To guard against mutations being retried, we deliberately execute the
170
+ // mutation function through the circuit breaker policy alone, rather
171
+ // than through `this.#policy` (which is a combination of both a
172
+ // circuit breaker policy and retry policy).
173
+ const response = await this.#policy.circuitBreakerPolicy.execute(() => mutationFn(...args));
174
+ // Type assertion: TypeScript is not able to unify the type that this
175
+ // function returns with `TData` at compile-time. We can still typecheck
176
+ // the arguments, though.
177
+ return processMutationResponse(options.mutationKey, response, responseStruct);
178
+ },
179
+ });
180
+ // We purposely pass an empty set of variables because this method is
181
+ // intended to be used internally by the data service, not end users, and
182
+ // the data service has full control of `mutationFn` anyway.
183
+ return await mutation.execute({});
184
+ }
119
185
  /**
120
186
  * Invalidate queries serviced by this data service.
121
187
  *
@@ -126,6 +192,20 @@ export class BaseDataService {
126
192
  async invalidateQueries(filters, options) {
127
193
  return this.#queryClient.invalidateQueries(filters, options);
128
194
  }
195
+ /**
196
+ * Cancel in-flight queries serviced by this data service.
197
+ *
198
+ * Use this in your subclass if you need to abort a concurrent fetch before
199
+ * starting a forced refresh (e.g. `Cache-Control: no-cache` reads), so a
200
+ * slower non-fresh request cannot overwrite the result.
201
+ *
202
+ * @param filters - Optional filter for selecting specific queries.
203
+ * @param cancelOptions - Optional options for cancelling the queries.
204
+ * @returns Nothing.
205
+ */
206
+ async cancelQueries(filters, cancelOptions) {
207
+ await this.#queryClient.cancelQueries(filters, cancelOptions);
208
+ }
129
209
  /**
130
210
  * Initialize the service, rehydrating the cache with persisted data if possible.
131
211
  */
@@ -141,29 +221,43 @@ export class BaseDataService {
141
221
  destroy() {
142
222
  this.#debouncedPersist?.cancel();
143
223
  this.#queryCacheUnsubscribe();
224
+ this.#mutationCacheUnsubscribe();
225
+ // `QueryClient.clear()` clears both caches, but `MutationCache.clear()`
226
+ // only drops its references to mutations without clearing their pending
227
+ // garbage-collection timers. We destroy each mutation first so those timers
228
+ // are cleared and do not keep the process alive.
229
+ for (const mutation of this.#queryClient.getMutationCache().getAll()) {
230
+ mutation.destroy();
231
+ }
144
232
  this.#queryClient.clear();
145
233
  this.messenger.clearSubscriptions();
146
234
  this.messenger.clearActions();
147
235
  }
148
236
  /**
149
- * Publish `cacheUpdated` events when a given query changes.
237
+ * Publish `cacheUpdated` events when the query or mutation cache is updated.
150
238
  *
151
- * @param hash The hash of the query.
152
- * @param type The type of cache update.
239
+ * @param objectType - The type of object updated ("query" or "mutation").
240
+ * @param eventType - What happened to the query or mutation ("added" or "updated").
241
+ * @param hash - The hash of the query or mutation.
153
242
  */
154
- #publishCacheUpdate(hash, type) {
155
- const state = type === 'added' || type === 'updated'
243
+ #publishCacheUpdate(objectType, eventType, hash) {
244
+ const state = eventType === 'added' || eventType === 'updated'
156
245
  ? dehydrate(this.#queryClient, {
157
- shouldDehydrateQuery: (query) => query.queryHash === hash,
246
+ shouldDehydrateQuery: (query) => objectType === 'query' && query.queryHash === hash,
247
+ shouldDehydrateMutation: (mutation) => objectType === 'mutation' &&
248
+ mutation.options.mutationKey !== undefined &&
249
+ hashKey(mutation.options.mutationKey) === hash,
158
250
  })
159
251
  : null;
160
252
  this.#messenger.publish(`${this.name}:cacheUpdated`, {
161
- type,
253
+ type: eventType,
254
+ objectType,
162
255
  hash,
163
256
  state,
164
257
  });
165
258
  this.#messenger.publish(`${this.name}:cacheUpdated:${hash}`, {
166
- type,
259
+ type: eventType,
260
+ objectType,
167
261
  state,
168
262
  });
169
263
  }
@@ -1 +1 @@
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,EAUL,WAAW,EAIX,SAAS,EACT,OAAO,GACR,MAAM,sBAAsB,CAAC;AAC9B,OAAO,SAAS,MAAM,iBAAiB,CAAC;AACxC,OAAO,EAAE,QA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AI,EACT,mBAAmB,CACpB,CAAC;YACF,OAAO;QACT,CAAC;QAED,MAAM,KAAK,GAAmB;YAC5B,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;YACrB,KAAK;SACN,CAAC;QAEF,MAAM,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAChC,wBAAwB,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 InvalidateOptions,\n InvalidateQueryFilters,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\n QueryFunction,\n WithRequired,\n dehydrate,\n hydrate,\n} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\nimport { debounce, DebouncedFunc } from 'lodash-es';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\nimport { processQueryResponse } from './utils.js';\n\n// Data service queries use the following format: ['ServiceActionName', ...params]\nexport type QueryKey = [string, ...Json[]] | readonly [string, ...Json[]];\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 | { type: 'added' | 'updated'; state: DehydratedState }\n | {\n type: 'removed';\n state: null;\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// Defaults to apply to all data service queries if no default option specified\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\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 #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: queryClientConfig.defaultOptions?.mutations,\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 if (['added', 'updated', 'removed'].includes(event.type)) {\n this.#publishCacheUpdate(\n event.query.queryHash,\n event.type as CacheUpdatedType,\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.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 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(() =>\n options.queryFn(context),\n );\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 * 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 * 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.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when a given query changes.\n *\n * @param hash The hash of the query.\n * @param type The type of cache update.\n */\n #publishCacheUpdate(hash: string, type: CacheUpdatedType): void {\n const state =\n type === 'added' || type === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) => query.queryHash === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type,\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":"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,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 { DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey, PersistenceConfiguration, } from './BaseDataService.js';
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';
@@ -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,kBAAkB,EAClB,iBAAiB,EACjB,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,EACR,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"}
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;AAanB,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 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"]}
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"]}
@@ -0,0 +1,4 @@
1
+ import { createModuleLogger } from '@metamask/utils';
2
+ export declare const projectLogger: import("debug").Debugger;
3
+ export { createModuleLogger };
4
+ //# sourceMappingURL=loggers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loggers.d.ts","sourceRoot":"","sources":["../src/loggers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1E,eAAO,MAAM,aAAa,0BAA2C,CAAC;AAEtE,OAAO,EAAE,kBAAkB,EAAE,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { createProjectLogger, createModuleLogger } from '@metamask/utils';
2
+ export const projectLogger = createProjectLogger('base-data-service');
3
+ export { createModuleLogger };
4
+ //# sourceMappingURL=loggers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loggers.js","sourceRoot":"","sources":["../src/loggers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1E,MAAM,CAAC,MAAM,aAAa,GAAG,mBAAmB,CAAC,mBAAmB,CAAC,CAAC;AAEtE,OAAO,EAAE,kBAAkB,EAAE,CAAC","sourcesContent":["import { createProjectLogger, createModuleLogger } from '@metamask/utils';\n\nexport const projectLogger = createProjectLogger('base-data-service');\n\nexport { createModuleLogger };\n"]}
package/dist/utils.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Struct } from '@metamask/superstruct';
2
- import type { QueryKey } from './BaseDataService.js';
2
+ import type { MutationKey, QueryKey } from './BaseDataService.js';
3
3
  /**
4
4
  * Process query responses, validating them using Superstruct if a struct is defined.
5
5
  *
@@ -10,4 +10,17 @@ import type { QueryKey } from './BaseDataService.js';
10
10
  * @throws If the query response does not match the struct.
11
11
  */
12
12
  export declare function processQueryResponse<Response>(queryKey: QueryKey, response: Response, struct?: Struct<Response>): Response;
13
+ /**
14
+ * Process mutation responses, validating them using Superstruct if a struct is defined.
15
+ *
16
+ * @param mutationKey - The mutation key.
17
+ * @param response - The mutation response
18
+ * @param struct - The struct defining the schema for the mutation response.
19
+ * @returns The mutation response, coerced by Superstruct if needed.
20
+ * @throws If the mutation response does not match the struct.
21
+ * @template InputResponse - The type of the response data being validated, e.g. `Json`.
22
+ * @template ResponseStruct - The struct used to validate and decode the response,
23
+ * e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.
24
+ */
25
+ export declare function processMutationResponse<InputResponse, ResponseStruct extends Struct<any> | undefined = undefined>(mutationKey: MutationKey, response: InputResponse, struct?: ResponseStruct): ResponseStruct extends Struct<infer StructType> ? StructType : InputResponse;
13
26
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,MAAM,uBAAuB,CAAC;AAEzD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAErD;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAC3C,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,QAAQ,EAClB,MAAM,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC,GACxB,QAAQ,CAcV"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,MAAM,uBAAuB,CAAC;AAEzD,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAElE;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAC3C,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,QAAQ,EAClB,MAAM,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC,GACxB,QAAQ,CAcV;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CACrC,aAAa,EAOb,cAAc,SAAS,MAAM,CAAC,GAAG,CAAC,GAAG,SAAS,GAAG,SAAS,EAE1D,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,aAAa,EACvB,MAAM,CAAC,EAAE,cAAc,GAGtB,cAAc,SAAS,MAAM,CAAC,MAAM,UAAU,CAAC,GAC9C,UAAU,GACV,aAAa,CA6BhB"}
package/dist/utils.js CHANGED
@@ -18,4 +18,34 @@ export function processQueryResponse(queryKey, response, struct) {
18
18
  }
19
19
  return result;
20
20
  }
21
+ /**
22
+ * Process mutation responses, validating them using Superstruct if a struct is defined.
23
+ *
24
+ * @param mutationKey - The mutation key.
25
+ * @param response - The mutation response
26
+ * @param struct - The struct defining the schema for the mutation response.
27
+ * @returns The mutation response, coerced by Superstruct if needed.
28
+ * @throws If the mutation response does not match the struct.
29
+ * @template InputResponse - The type of the response data being validated, e.g. `Json`.
30
+ * @template ResponseStruct - The struct used to validate and decode the response,
31
+ * e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.
32
+ */
33
+ export function processMutationResponse(mutationKey, response, struct) {
34
+ if (!struct) {
35
+ // Type assertion: TypeScript cannot "see" that when `struct` is
36
+ // `undefined`, `response` satisfies the `InputResponse` branch of
37
+ // `Response` (even though we stated this fact in the conditional type
38
+ // above). This is because at this point in time, `ResponseStruct` — being a
39
+ // generic — is unresolved, which makes `Response` unresolved too. This is a
40
+ // limitation of the way that generics work. Therefore, we need to help
41
+ // TypeScript out.
42
+ return response;
43
+ }
44
+ const [error, result] = validate(response, struct);
45
+ if (error) {
46
+ throw new Error(`Mutation function for "${mutationKey[0]}" returned an unexpected response: ${error.message}.`);
47
+ }
48
+ // Type assertion: See above.
49
+ return result;
50
+ }
21
51
  //# sourceMappingURL=utils.js.map
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAIzD;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAClC,QAAkB,EAClB,QAAkB,EAClB,MAAyB;IAEzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAEnD,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CACb,uBAAuB,QAAQ,CAAC,CAAC,CAAC,sCAAsC,KAAK,CAAC,OAAO,GAAG,CACzF,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Struct, validate } from '@metamask/superstruct';\n\nimport type { QueryKey } from './BaseDataService.js';\n\n/**\n * Process query responses, validating them using Superstruct if a struct is defined.\n *\n * @param queryKey - The query key.\n * @param response - The query response\n * @param struct - The struct defining the schema for the query response.\n * @returns The query response, coerced by Superstruct if needed.\n * @throws If the query response does not match the struct.\n */\nexport function processQueryResponse<Response>(\n queryKey: QueryKey,\n response: Response,\n struct?: Struct<Response>,\n): Response {\n if (!struct) {\n return response;\n }\n\n const [error, result] = validate(response, struct);\n\n if (error) {\n throw new Error(\n `Query function for \"${queryKey[0]}\" returned an unexpected response: ${error.message}.`,\n );\n }\n\n return result;\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAIzD;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAClC,QAAkB,EAClB,QAAkB,EAClB,MAAyB;IAEzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAEnD,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CACb,uBAAuB,QAAQ,CAAC,CAAC,CAAC,sCAAsC,KAAK,CAAC,OAAO,GAAG,CACzF,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,uBAAuB,CAUrC,WAAwB,EACxB,QAAuB,EACvB,MAAuB;IAavB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,gEAAgE;QAChE,kEAAkE;QAClE,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,uEAAuE;QACvE,kBAAkB;QAClB,OAAO,QAA+B,CAAC;IACzC,CAAC;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAEnD,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CACb,0BAA0B,WAAW,CAAC,CAAC,CAAC,sCAAsC,KAAK,CAAC,OAAO,GAAG,CAC/F,CAAC;IACJ,CAAC;IAED,6BAA6B;IAC7B,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Struct, validate } from '@metamask/superstruct';\n\nimport type { MutationKey, QueryKey } from './BaseDataService.js';\n\n/**\n * Process query responses, validating them using Superstruct if a struct is defined.\n *\n * @param queryKey - The query key.\n * @param response - The query response\n * @param struct - The struct defining the schema for the query response.\n * @returns The query response, coerced by Superstruct if needed.\n * @throws If the query response does not match the struct.\n */\nexport function processQueryResponse<Response>(\n queryKey: QueryKey,\n response: Response,\n struct?: Struct<Response>,\n): Response {\n if (!struct) {\n return response;\n }\n\n const [error, result] = validate(response, struct);\n\n if (error) {\n throw new Error(\n `Query function for \"${queryKey[0]}\" returned an unexpected response: ${error.message}.`,\n );\n }\n\n return result;\n}\n\n/**\n * Process mutation responses, validating them using Superstruct if a struct is defined.\n *\n * @param mutationKey - The mutation key.\n * @param response - The mutation response\n * @param struct - The struct defining the schema for the mutation response.\n * @returns The mutation response, coerced by Superstruct if needed.\n * @throws If the mutation response does not match the struct.\n * @template InputResponse - The type of the response data being validated, e.g. `Json`.\n * @template ResponseStruct - The struct used to validate and decode the response,\n * e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.\n */\nexport function processMutationResponse<\n InputResponse,\n // We have to use `Struct<any>` here, as using `Struct<InputResponse>` (or\n // even `Struct<unknown>`) would reject a more concrete, \"real world\" struct.\n // The reason is that `Struct` is an object type with methods whose signatures\n // feature the struct's content type, making `Struct` contravariant in its\n // content type. The only way to get around this is to use `any`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ResponseStruct extends Struct<any> | undefined = undefined,\n>(\n mutationKey: MutationKey,\n response: InputResponse,\n struct?: ResponseStruct,\n // We don't want this to be a type parameter as it should not be customizable\n // (it is only derived).\n): ResponseStruct extends Struct<infer StructType>\n ? StructType\n : InputResponse {\n // Because we aren't defining the return type as a type parameter,\n // we need to restate it so we can reuse it below.\n type Response =\n ResponseStruct extends Struct<infer StructType>\n ? StructType\n : InputResponse;\n\n if (!struct) {\n // Type assertion: TypeScript cannot \"see\" that when `struct` is\n // `undefined`, `response` satisfies the `InputResponse` branch of\n // `Response` (even though we stated this fact in the conditional type\n // above). This is because at this point in time, `ResponseStruct` — being a\n // generic — is unresolved, which makes `Response` unresolved too. This is a\n // limitation of the way that generics work. Therefore, we need to help\n // TypeScript out.\n return response as unknown as Response;\n }\n\n const [error, result] = validate(response, struct);\n\n if (error) {\n throw new Error(\n `Mutation function for \"${mutationKey[0]}\" returned an unexpected response: ${error.message}.`,\n );\n }\n\n // Type assertion: See above.\n return result;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/base-data-service",
3
- "version": "2.0.0-preview-0a1dd02ad",
3
+ "version": "2.1.0-preview-452564c37",
4
4
  "description": "Provides utilities for building data services",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -55,22 +55,23 @@
55
55
  "@metamask/storage-service": "^2.0.0",
56
56
  "@metamask/superstruct": "^3.4.1",
57
57
  "@metamask/utils": "^12.0.0",
58
- "@tanstack/query-core": "^5.62.16",
59
- "cockatiel": "^3.1.2",
58
+ "@tanstack/query-core": "^5.89.0",
59
+ "cockatiel": "^3.2.1",
60
60
  "fast-deep-equal": "^3.1.3",
61
- "lodash-es": "^4.17.21"
61
+ "lodash-es": "^4.18.1",
62
+ "uuid": "^11.1.1"
62
63
  },
63
64
  "devDependencies": {
64
- "@metamask/auto-changelog": "^6.1.0",
65
+ "@metamask/auto-changelog": "^6.2.1",
65
66
  "@types/jest": "^30.0.0",
66
67
  "@types/lodash-es": "^4.17.12",
67
68
  "@typescript/native": "npm:typescript@^7.0.2",
68
- "deepmerge": "^4.2.2",
69
+ "deepmerge": "^4.3.1",
69
70
  "jest": "^30.4.2",
70
- "nock": "^13.3.1",
71
- "rimraf": "^5.0.5",
72
- "ts-jest": "^29.4.11",
73
- "tsx": "^4.20.5",
71
+ "nock": "^13.5.6",
72
+ "rimraf": "^6.1.3",
73
+ "ts-jest": "^29.4.12",
74
+ "tsx": "^4.23.15",
74
75
  "typedoc": "^0.25.13",
75
76
  "typedoc-plugin-missing-exports": "^2.0.0",
76
77
  "typescript": "npm:@typescript/typescript6@^6.0.2"