@metamask-previews/base-data-service 2.1.0-preview-9fd631f7d → 2.1.0-preview-6fbab7311

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
@@ -10,20 +10,12 @@ 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 }` objects 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
- - Consumers that read properties other than `name` and `message` from these errors, or that relied on `instanceof Error`, must adapt.
24
- - 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))
25
16
  - Bump `@tanstack/query-core` from `^5.89.0` to `^5.103.2` ([#10511](https://github.com/MetaMask/core/pull/10511))
26
17
  - Bump `@metamask/utils` from `^12.0.0` to `^12.0.1` ([#11107](https://github.com/MetaMask/core/pull/11107))
18
+ - Bump `uuid` from `^11.1.1` to `^14.0.0` ([#10941](https://github.com/MetaMask/core/pull/10941))
27
19
 
28
20
  ## [2.1.0]
29
21
 
@@ -18,40 +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
- export type SerializedQueryError = {
25
- name: string;
26
- message: string;
27
- };
28
- /**
29
- * The dehydrated state published in `:cacheUpdated` payloads, where query
30
- * errors are serialized and the in flight `promise` is omitted so the payload
31
- * survives JSON round trips.
32
- */
33
- export type CacheUpdatedState = Omit<DehydratedState, 'queries'> & {
34
- queries: (Omit<DehydratedState['queries'][number], 'state' | 'promise'> & {
35
- state: DataServiceQueryState;
36
- })[];
37
- };
38
- /**
39
- * The state of a single query, as reported to `onQueryStateChange` handlers.
40
- * Errors are serialized so the state is JSON safe.
41
- */
42
- export type DataServiceQueryState = Omit<DehydratedState['queries'][number]['state'], 'error' | 'fetchFailureReason'> & {
43
- error: SerializedQueryError | null;
44
- fetchFailureReason: SerializedQueryError | null;
45
- };
46
- /**
47
- * A callback that receives the state of a query as it changes.
48
- */
49
- export type QueryStateChangeHandler = (state: DataServiceQueryState) => void;
50
21
  export type DataServiceGranularCacheUpdatedPayload = {
51
22
  objectType: 'query' | 'mutation';
52
23
  } & ({
53
24
  type: 'added' | 'updated';
54
- state: CacheUpdatedState;
25
+ state: DehydratedState;
55
26
  } | {
56
27
  type: 'removed';
57
28
  state: null;
@@ -112,16 +83,11 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
112
83
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
113
84
  * @param options.queryFn - The query function.
114
85
  * @param options.responseStruct - An optional struct for validating the response of the query function.
115
- * @param options.onQueryStateChange - An optional callback that receives the
116
- * state of the query (with serialized errors) as it changes. It is called
117
- * once with the current state if the query is already cached, then with
118
- * every update until the fetch has settled and the query is idle.
119
86
  * @returns The query results.
120
87
  */
121
- 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, onQueryStateChange, ...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'> & {
122
89
  queryFn: QueryFunction<TQueryFnData, TQueryKey>;
123
90
  responseStruct?: TDataStruct;
124
- onQueryStateChange?: QueryStateChangeHandler;
125
91
  }): Promise<TData>;
126
92
  /**
127
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,E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AAM,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,4 +1,4 @@
1
- import { Duration, getErrorMessage, inMilliseconds } from '@metamask/utils';
1
+ import { Duration, inMilliseconds } from '@metamask/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,34 +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
- * Convert a thrown value into a JSON safe error.
12
- *
13
- * @param error - The raw error stored on a query, if any.
14
- * @returns The serialized error, or null if there is no error.
15
- */
16
- function serializeQueryError(error) {
17
- if (error === null) {
18
- return null;
19
- }
20
- return {
21
- name: error instanceof Error ? error.name : 'Error',
22
- message: getErrorMessage(error),
23
- };
24
- }
25
- /**
26
- * Serialize the errors held by a query state so it survives JSON round trips.
27
- *
28
- * @param state - The raw query state.
29
- * @returns The query state with `error` and `fetchFailureReason` serialized.
30
- */
31
- function serializeQueryState(state) {
32
- return {
33
- ...state,
34
- error: serializeQueryError(state.error),
35
- fetchFailureReason: serializeQueryError(state.fetchFailureReason),
36
- };
37
- }
38
10
  /*
39
11
  * Defaults to apply to all data service queries if no default option specified.
40
12
  */
@@ -124,24 +96,16 @@ export class BaseDataService {
124
96
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
125
97
  * @param options.queryFn - The query function.
126
98
  * @param options.responseStruct - An optional struct for validating the response of the query function.
127
- * @param options.onQueryStateChange - An optional callback that receives the
128
- * state of the query (with serialized errors) as it changes. It is called
129
- * once with the current state if the query is already cached, then with
130
- * every update until the fetch has settled and the query is idle.
131
99
  * @returns The query results.
132
100
  */
133
- async fetchQuery({ queryFn, responseStruct, onQueryStateChange, ...options }) {
134
- const runFetch = async () => this.#queryClient.fetchQuery({
101
+ async fetchQuery({ queryFn, responseStruct, ...options }) {
102
+ return this.#queryClient.fetchQuery({
135
103
  ...options,
136
104
  queryFn: async (context) => {
137
105
  const response = await this.#policy.execute(() => queryFn(context));
138
106
  return processQueryResponse(options.queryKey, response, responseStruct);
139
107
  },
140
108
  });
141
- if (!onQueryStateChange) {
142
- return runFetch();
143
- }
144
- return this.#withQueryStateChange(options.queryKey, onQueryStateChange, runFetch);
145
109
  }
146
110
  /**
147
111
  * Fetch a paginated query.
@@ -269,69 +233,6 @@ export class BaseDataService {
269
233
  this.messenger.clearSubscriptions();
270
234
  this.messenger.clearActions();
271
235
  }
272
- /**
273
- * Run a fetch while reporting the state of its query to a handler.
274
- *
275
- * The handler receives the current state up front if the query is cached,
276
- * then every `updated` cache event for the query. It is
277
- * unsubscribed once the fetch has settled and the last reported state is
278
- * idle, so a background fetch that outlives this call is still reported
279
- * until it finishes. Errors thrown by the handler are logged and ignored.
280
- *
281
- * @param queryKey - The key of the query being fetched.
282
- * @param handler - The callback receiving query states.
283
- * @param runFetch - The function performing the fetch.
284
- * @returns The result of the fetch.
285
- */
286
- async #withQueryStateChange(queryKey, handler, runFetch) {
287
- const notify = (state) => {
288
- try {
289
- handler(state);
290
- }
291
- catch (error) {
292
- log('onQueryStateChange handler threw', error);
293
- }
294
- };
295
- const eventType = `${this.name}:cacheUpdated:${hashKey(queryKey)}`;
296
- let settled = false;
297
- let idle = true;
298
- const unsubscribe = (handlerToRemove) => {
299
- try {
300
- this.#messenger.unsubscribe(eventType, handlerToRemove);
301
- }
302
- catch {
303
- // The subscription was already cleared, e.g. by `destroy`.
304
- }
305
- };
306
- const listener = (payload) => {
307
- // `added` only carries the blank state built right before the fetch
308
- // starts (pending and idle), and `removed` carries no state at all.
309
- if (payload.type !== 'updated') {
310
- return;
311
- }
312
- const { state } = payload.state.queries[0];
313
- idle = state.fetchStatus === 'idle';
314
- notify(state);
315
- if (settled && idle) {
316
- unsubscribe(listener);
317
- }
318
- };
319
- const current = this.#queryClient.getQueryState(queryKey);
320
- if (current) {
321
- idle = current.fetchStatus === 'idle';
322
- notify(serializeQueryState(current));
323
- }
324
- this.#messenger.subscribe(eventType, listener);
325
- try {
326
- return await runFetch();
327
- }
328
- finally {
329
- settled = true;
330
- if (idle) {
331
- unsubscribe(listener);
332
- }
333
- }
334
- }
335
236
  /**
336
237
  * Publish `cacheUpdated` events when the query or mutation cache is updated.
337
238
  *
@@ -340,7 +241,7 @@ export class BaseDataService {
340
241
  * @param hash - The hash of the query or mutation.
341
242
  */
342
243
  #publishCacheUpdate(objectType, eventType, hash) {
343
- const dehydrated = eventType === 'added' || eventType === 'updated'
244
+ const state = eventType === 'added' || eventType === 'updated'
344
245
  ? dehydrate(this.#queryClient, {
345
246
  shouldDehydrateQuery: (query) => objectType === 'query' && query.queryHash === hash,
346
247
  shouldDehydrateMutation: (mutation) => objectType === 'mutation' &&
@@ -348,14 +249,6 @@ export class BaseDataService {
348
249
  hashKey(mutation.options.mutationKey) === hash,
349
250
  })
350
251
  : null;
351
- const state = dehydrated && {
352
- ...dehydrated,
353
- // The in flight `promise` is not JSON safe, so it is left out.
354
- queries: dehydrated.queries.map(({ promise: _promise, ...query }) => ({
355
- ...query,
356
- state: serializeQueryState(query.state),
357
- })),
358
- };
359
252
  this.#messenger.publish(`${this.name}:cacheUpdated`, {
360
253
  type: eventType,
361
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,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,CAAC,CAAC;AAqEjE;;;;;GAKG;AACH,SAAS,mBAAmB,CAAC,KAAc;IACzC,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QACnB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO;QACL,IAAI,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO;QACnD,OAAO,EAAE,eAAe,CAAC,KAAK,CAAC;KAChC,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,mBAAmB,CAC1B,KAAkD;IAElD,OAAO;QACL,GAAG,KAAK;QACR,KAAK,EAAE,mBAAmB,CAAC,KAAK,C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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 */\nexport type SerializedQueryError = { name: string; message: string };\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 * Convert a thrown value into a JSON safe 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 return {\n name: error instanceof Error ? error.name : 'Error',\n 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":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C,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 { CacheUpdatedState, DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, DataServiceQueryState, QueryKey, QueryStateChangeHandler, SerializedQueryError, MutationKey, 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,iBAAiB,EACjB,kBAAkB,EAClB,iBAAiB,EACjB,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,qBAAqB,EACrB,QAAQ,EACR,uBAAuB,EACvB,oBAAoB,EACpB,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"}
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;AAkBnB,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 CacheUpdatedState,\n DataServiceActions,\n DataServiceEvents,\n DataServiceCacheUpdatedPayload,\n DataServiceGranularCacheUpdatedPayload,\n DataServiceInvalidateQueriesAction,\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceQueryState,\n QueryKey,\n QueryStateChangeHandler,\n SerializedQueryError,\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"]}
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-9fd631f7d",
3
+ "version": "2.1.0-preview-6fbab7311",
4
4
  "description": "Provides utilities for building data services",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -59,13 +59,13 @@
59
59
  "cockatiel": "^3.2.1",
60
60
  "fast-deep-equal": "^3.1.3",
61
61
  "lodash-es": "^4.18.1",
62
- "uuid": "^11.1.1"
62
+ "uuid": "^14.0.0"
63
63
  },
64
64
  "devDependencies": {
65
65
  "@metamask/auto-changelog": "^6.2.1",
66
66
  "@types/lodash-es": "^4.17.12",
67
67
  "@typescript/native": "npm:typescript@^7.0.2",
68
- "nock": "^13.5.6",
68
+ "nock": "^15.0.5",
69
69
  "rimraf": "^6.1.3",
70
70
  "typedoc": "^0.28.20",
71
71
  "typedoc-plugin-missing-exports": "^4.1.4",