@metamask-previews/base-data-service 0.1.3-preview-4758e65ff → 0.1.3-preview-bbf9454b2

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
@@ -33,11 +33,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
33
33
  - `handleAll`
34
34
  - `handleWhen`
35
35
  - Export types `DataServiceActions` and `DataServiceEvents` ([#9475](https://github.com/MetaMask/core/pull/9475))
36
+ - Add `responseStruct` option to `fetchQuery` and `fetchInfiniteQuery` for validating query responses using Superstruct ([#9540](https://github.com/MetaMask/core/pull/9540))
37
+ - When provided, the struct is used to validate the response and for inferring the return type of the query
36
38
 
37
39
  ### Changed
38
40
 
39
41
  - **BREAKING:** Remove `TPageData` type parameter from `invalidateQueries` method ([#9526](https://github.com/MetaMask/core/pull/9526))
40
42
  - This is technically a breaking change, but this was not used in any of our codebases
43
+ - **BREAKING:** Bump `@tanstack/query-core` from `^4.43.0` to `^5.62.16` ([#9712](https://github.com/MetaMask/core/pull/9712))
44
+ - The option types accepted by `fetchQuery`, `fetchInfiniteQuery`, and `invalidateQueries` now follow the query-core v5 API. Subclasses need to rename `cacheTime` to `gcTime`.
45
+ - `fetchInfiniteQuery` now requires `initialPageParam` and `getNextPageParam`, matching query-core's options for infinite queries. This also lets `TPageParam` be inferred instead of spelled out in the type parameters.
46
+ - **BREAKING:** `fetchQuery` and `fetchInfiniteQuery` now take one more type parameter: `TDataStruct` is the third parameter and the others have been shifted up ([#9540](https://github.com/MetaMask/core/pull/9540))
47
+ - **BREAKING:** Improve type safety of constructor by ensuring the messenger has required actions/events ([#9525](https://github.com/MetaMask/core/pull/9525))
48
+ - No change needed, unless the messenger being passed into the constructor was typed incorrectly.
41
49
  - Bump `@metamask/utils` from `^11.9.0` to `^11.11.0` ([#9074](https://github.com/MetaMask/core/pull/9074))
42
50
  - Bump `@metamask/controller-utils` from `^12.1.0` to `^12.3.0` ([#9058](https://github.com/MetaMask/core/pull/9058), [#9083](https://github.com/MetaMask/core/pull/9083), [#9218](https://github.com/MetaMask/core/pull/9218))
43
51
  - Bump `@metamask/messenger` from `^1.2.0` to `^2.0.0` ([#9392](https://github.com/MetaMask/core/pull/9392))
@@ -17,11 +17,13 @@ var _BaseDataService_instances, _BaseDataService_messenger, _BaseDataService_ext
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.BaseDataService = exports.STORAGE_SERVICE_KEY = void 0;
19
19
  const messenger_1 = require("@metamask/messenger");
20
+ const superstruct_1 = require("@metamask/superstruct");
20
21
  const utils_1 = require("@metamask/utils");
21
22
  const query_core_1 = require("@tanstack/query-core");
22
23
  const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
23
24
  const lodash_1 = require("lodash");
24
25
  const createServicePolicy_js_1 = require("./createServicePolicy.cjs");
26
+ const utils_js_1 = require("./utils.cjs");
25
27
  // Defaults to apply to all data service queries if no default option specified
26
28
  const QUERY_CLIENT_DEFAULTS = {
27
29
  queries: {
@@ -85,12 +87,16 @@ class BaseDataService {
85
87
  *
86
88
  * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
87
89
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
90
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
88
91
  * @returns The query results.
89
92
  */
90
- async fetchQuery(options) {
93
+ async fetchQuery({ responseStruct, ...options }) {
91
94
  return __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchQuery({
92
95
  ...options,
93
- queryFn: (context) => __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn(context)),
96
+ queryFn: async (context) => {
97
+ const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn(context));
98
+ return (0, utils_js_1.processQueryResponse)(options.queryKey, response, responseStruct);
99
+ },
94
100
  });
95
101
  }
96
102
  /**
@@ -98,35 +104,33 @@ class BaseDataService {
98
104
  *
99
105
  * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
100
106
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
107
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
101
108
  * @param pageParam - An optional page parameter.
102
109
  * @returns The query result, exclusively the requested page is returned.
103
110
  */
104
- async fetchInfiniteQuery(options, pageParam) {
111
+ async fetchInfiniteQuery({ responseStruct, ...options }, pageParam) {
105
112
  const cache = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").getQueryCache();
106
113
  const query = cache.find({
107
114
  queryKey: options.queryKey,
108
115
  });
109
- if (!query?.state.data || pageParam === undefined) {
116
+ if (!query?.state.data || !pageParam) {
110
117
  const result = await __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchInfiniteQuery({
111
118
  ...options,
112
- queryFn: (context) => __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn({
113
- ...context,
114
- pageParam: context.pageParam ?? pageParam,
115
- })),
119
+ initialPageParam: pageParam ?? options.initialPageParam,
120
+ queryFn: async (context) => {
121
+ const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(async () => options.queryFn({
122
+ ...context,
123
+ pageParam: context.meta?.pageParam ?? context.pageParam,
124
+ }));
125
+ return (0, utils_js_1.processQueryResponse)(options.queryKey, response, responseStruct);
126
+ },
116
127
  });
117
128
  return result.pages[0];
118
129
  }
119
- const { pages } = query.state.data;
120
- const previous = options.getPreviousPageParam?.(pages[0], pages);
121
- const direction = (0, fast_deep_equal_1.default)(pageParam, previous) ? 'backward' : 'forward';
122
- const result = await query.fetch(undefined, {
123
- meta: {
124
- fetchMore: {
125
- direction,
126
- pageParam,
127
- },
128
- },
129
- });
130
+ const { pages, pageParams } = query.state.data;
131
+ const next = options.getNextPageParam(pages[pages.length - 1], pages, pageParams[pageParams.length - 1], pageParams);
132
+ const direction = (0, fast_deep_equal_1.default)(pageParam, next) ? 'forward' : 'backward';
133
+ const result = await query.fetch({ ...query.options, meta: { pageParam } }, { meta: { fetchMore: { direction } } });
130
134
  const pageIndex = result.pageParams.findIndex((param) => (0, fast_deep_equal_1.default)(param, pageParam));
131
135
  return result.pages[pageIndex];
132
136
  }
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDataService.cjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,mDAI6B;AAM7B,2CAA2D;AAE3D,qDAc8B;AAC9B,sEAAwC;AACxC,mCAAiD;AAEjD,sEAIkC;AAiDlC,+EAA+E;AAC/E,MAAM,qBAAqB,GAAmB;IAC5C,OAAO,EAAE;QACP,KAAK,EAAE,KAAK;QACZ,SAAS,EAAE,IAAA,sBAAc,EAAC,CAAC,EAAE,gBAAQ,CAAC,MAAM,CAAC;KAC9C;CACF,CAAC;AAEW,QAAA,mBAAmB,GAAG,OAAO,CAAC;AA2B3C,MAAa,eAAe;IAqC1B,YAAY,EACV,IAAI,EACJ,SAAS,EACT,iBAAiB,GAAG,EAAE,EACtB,aAAa,EACb,iBAAiB,GAOlB;;QAnCQ,6CAIP;QAEO,qDAGP;QAIO,0CAAuB;QAEvB,+CAA0B;QAE1B,yDAAmC;QAEnC,oDAA8C;QAE9C,qDAA8C;QAerD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,2EAA2E;QAC3E,kFAAkF;QAClF,yDAAyD;QACzD,6FAA6F;QAC7F,uBAAA,IAAI,8BAAc,SAIjB,MAAA,CAAC;QACF,uBAAA,IAAI,sCAAsB,SAGzB,MAAA,CAAC;QACF,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAE3B,uBAAA,IAAI,gCAAgB,IAAI,wBAAW,CAAC;YAClC,GAAG,iBAAiB;YACpB,cAAc,EAAE;gBACd,OAAO,EAAE;oBACP,GAAG,qBAAqB,CAAC,OAAO;oBAChC,GAAG,iBAAiB,CAAC,cAAc,EAAE,OAAO;iBAC7C;gBAC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EACnB,KAAwB,CACzB,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,IAAI,CAAC,uBAAA,IAAI,0CAAmB,EAAE,CAAC;QAC7B,OAAO;IACT,CAAC;IAED,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CACjE,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,2BAAmB,CACpB,CAAC;IAEF,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAG,YAAyC,CAAC;IAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,0CAAmB,CAAC,MAAM,EAAE,CAAC;QACnE,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,2BAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,IAAA,oBAAO,EAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\nimport { Duration, inMilliseconds } from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport {\n DefaultOptions,\n DehydratedState,\n FetchInfiniteQueryOptions,\n FetchQueryOptions,\n InfiniteData,\n InvalidateOptions,\n InvalidateQueryFilters,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\n WithRequired,\n dehydrate,\n hydrate,\n} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\nimport { debounce, DebouncedFunc } from 'lodash';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\n\n// Data service queries use the following format: ['ServiceActionName', ...params]\nexport type QueryKey = [string, ...Json[]];\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: (\n filters?: InvalidateQueryFilters<Json>,\n options?: InvalidateOptions,\n ) => Promise<void>;\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 Messenger<\n ServiceName,\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 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: ServiceMessenger;\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 * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = unknown,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay'\n >,\n 'queryKey' | 'queryFn'\n >,\n ): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: (context) =>\n this.#policy.execute(() => options.queryFn(context)),\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 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 = unknown,\n TData extends TQueryFnData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay'\n >,\n 'queryKey' | 'queryFn'\n >,\n pageParam?: TPageParam,\n ): Promise<TData> {\n const cache = this.#queryClient.getQueryCache();\n\n const query = cache.find<TQueryFnData, TError, InfiniteData<TData>>({\n queryKey: options.queryKey,\n });\n\n if (!query?.state.data || pageParam === undefined) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n queryFn: (context) =>\n this.#policy.execute(() =>\n options.queryFn({\n ...context,\n pageParam: context.pageParam ?? pageParam,\n }),\n ),\n });\n\n return result.pages[0];\n }\n\n const { pages } = query.state.data;\n const previous = options.getPreviousPageParam?.(pages[0], pages);\n\n const direction = deepEqual(pageParam, previous) ? 'backward' : 'forward';\n\n const result = await query.fetch(undefined, {\n meta: {\n fetchMore: {\n direction,\n pageParam,\n },\n },\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<Json>,\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.cjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,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/D,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,2BAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAmB;QAC5B,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;QACrB,KAAK;KACN,CAAC;IAEF,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,2BAAmB,EACnB,KAAwB,CACzB,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,IAAI,CAAC,uBAAA,IAAI,0CAAmB,EAAE,CAAC;QAC7B,OAAO;IACT,CAAC;IAED,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CACjE,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,2BAAmB,CACpB,CAAC;IAEF,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAG,YAAyC,CAAC;IAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,0CAAmB,CAAC,MAAM,EAAE,CAAC;QACnE,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,2BAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,IAAA,oBAAO,EAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","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';\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[]];\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,8 +1,17 @@
1
- import { Messenger, ActionConstraint, EventConstraint } from "@metamask/messenger";
1
+ import { Messenger, ActionConstraint, EventConstraint, MessengerActions, MessengerEvents } from "@metamask/messenger";
2
+ import type { StorageServiceGetItemAction, StorageServiceRemoveItemAction, StorageServiceSetItemAction } from "@metamask/storage-service";
3
+ import { Struct } from "@metamask/superstruct";
2
4
  import type { Json } from "@metamask/utils";
3
- import { DehydratedState, FetchInfiniteQueryOptions, FetchQueryOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, WithRequired } from "@tanstack/query-core";
5
+ import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from "@tanstack/query-core";
4
6
  import { CreateServicePolicyOptions } from "./createServicePolicy.cjs";
5
7
  export type QueryKey = [string, ...Json[]];
8
+ /**
9
+ * The supertype of all messengers, scoped to a namespace.
10
+ *
11
+ * @template Namespace - The namespace for the messenger's own actions and
12
+ * events.
13
+ */
14
+ export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
6
15
  export type DataServiceGranularCacheUpdatedPayload = {
7
16
  type: 'added' | 'updated';
8
17
  state: DehydratedState;
@@ -15,9 +24,10 @@ export type DataServiceCacheUpdatedPayload = DataServiceGranularCacheUpdatedPayl
15
24
  };
16
25
  export type DataServiceInvalidateQueriesAction<ServiceName extends string> = {
17
26
  type: `${ServiceName}:invalidateQueries`;
18
- handler: (filters?: InvalidateQueryFilters<Json>, options?: InvalidateOptions) => Promise<void>;
27
+ handler: BaseDataService<ServiceName, BaseMessenger<ServiceName>>['invalidateQueries'];
19
28
  };
20
29
  export type DataServiceActions<ServiceName extends string> = DataServiceInvalidateQueriesAction<ServiceName>;
30
+ type DataServiceAllowedActions = StorageServiceGetItemAction | StorageServiceSetItemAction | StorageServiceRemoveItemAction;
21
31
  export type DataServiceCacheUpdatedEvent<ServiceName extends string> = {
22
32
  type: `${ServiceName}:cacheUpdated`;
23
33
  payload: [DataServiceCacheUpdatedPayload];
@@ -47,13 +57,13 @@ export type PersistenceConfiguration = {
47
57
  */
48
58
  maxWriteDelay?: number;
49
59
  };
50
- export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends Messenger<ServiceName, ActionConstraint, EventConstraint, any>> {
60
+ export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends BaseMessenger<ServiceName>> {
51
61
  #private;
52
62
  readonly name: ServiceName;
53
63
  protected messenger: ServiceMessenger;
54
64
  constructor({ name, messenger, queryClientConfig, policyOptions, persistenceConfig, }: {
55
65
  name: ServiceName;
56
- messenger: ServiceMessenger;
66
+ messenger: DataServiceActions<ServiceName>['type'] extends MessengerActions<ServiceMessenger>['type'] | DataServiceAllowedActions['type'] ? DataServiceEvents<ServiceName>['type'] extends MessengerEvents<ServiceMessenger>['type'] ? ServiceMessenger : never : never;
57
67
  queryClientConfig?: QueryClientConfig;
58
68
  policyOptions?: CreateServicePolicyOptions;
59
69
  persistenceConfig?: PersistenceConfiguration;
@@ -63,18 +73,26 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
63
73
  *
64
74
  * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
65
75
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
76
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
66
77
  * @returns The query results.
67
78
  */
68
- protected fetchQuery<TQueryFnData extends Json, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay'>, 'queryKey' | 'queryFn'>): Promise<TData>;
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'> & {
80
+ queryFn: QueryFunction<TQueryFnData, TQueryKey>;
81
+ responseStruct?: TDataStruct;
82
+ }): Promise<TData>;
69
83
  /**
70
84
  * Fetch a paginated query.
71
85
  *
72
86
  * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
73
87
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
88
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
74
89
  * @param pageParam - An optional page parameter.
75
90
  * @returns The query result, exclusively the requested page is returned.
76
91
  */
77
- protected fetchInfiniteQuery<TQueryFnData extends Json, TError = unknown, TData extends TQueryFnData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam extends Json = Json>(options: WithRequired<OmitKeyof<FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay'>, 'queryKey' | 'queryFn'>, pageParam?: TPageParam): Promise<TData>;
92
+ protected fetchInfiniteQuery<TQueryFnData extends Json, TError = DefaultError, TDataStruct extends Struct<TQueryFnData> | undefined = undefined, TData extends TQueryFnData = TDataStruct extends Struct<infer StructType> ? StructType : TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam extends Json = Json>({ responseStruct, ...options }: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, InfiniteData<TData, TPageParam>, TQueryKey, TPageParam>, 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'>, 'queryKey'> & InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {
93
+ queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
94
+ responseStruct?: TDataStruct;
95
+ }, pageParam?: TPageParam): Promise<TData>;
78
96
  /**
79
97
  * Invalidate queries serviced by this data service.
80
98
  *
@@ -82,7 +100,7 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
82
100
  * @param options - Additional optional options for query invalidations.
83
101
  * @returns Nothing.
84
102
  */
85
- invalidateQueries(filters?: InvalidateQueryFilters<Json>, options?: InvalidateOptions): Promise<void>;
103
+ invalidateQueries(filters?: InvalidateQueryFilters<QueryKey>, options?: InvalidateOptions): Promise<void>;
86
104
  /**
87
105
  * Initialize the service, rehydrating the cache with persisted data if possible.
88
106
  */
@@ -93,4 +111,5 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
93
111
  */
94
112
  destroy(): void;
95
113
  }
114
+ export {};
96
115
  //# sourceMappingURL=BaseDataService.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDataService.d.cts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAO7B,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAC5C,OAAO,EAEL,eAAe,EACf,yBAAyB,EACzB,iBAAiB,EAEjB,iBAAiB,EACjB,sBAAsB,EACtB,SAAS,EAET,iBAAiB,EACjB,YAAY,EAGb,6BAA6B;AAI9B,OAAO,EAEL,0BAA0B,EAE3B,kCAAiC;AAGlC,MAAM,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;AAE3C,MAAM,MAAM,sCAAsC,GAC9C;IAAE,IAAI,EAAE,OAAO,GAAG,SAAS,CAAC;IAAC,KAAK,EAAE,eAAe,CAAA;CAAE,GACrD;IACE,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,EAAE,IAAI,CAAC;CACb,CAAC;AAEN,MAAM,MAAM,8BAA8B,GACxC,sCAAsC,GAAG;IACvC,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAIJ,MAAM,MAAM,kCAAkC,CAAC,WAAW,SAAS,MAAM,IAAI;IAC3E,IAAI,EAAE,GAAG,WAAW,oBAAoB,CAAC;IACzC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AAS,CACP,iBAAiB,CACf,YAAY,EACZ,MAAM,EACN,YAAY,CAAC,KAAK,EAAE,UAAU,CAAC,EAC/B,SAAS,EACT,UAAU,CACX,EACD,OAAO,GAAG,YAAY,GAAG,SAAS,GAAG,kBAAkB,CACxD,EACD,UAAU,CACX,GACC,8BAA8B,CAAC,YAAY,EAAE,UAAU,CAAC,GAAG;QACzD,OAAO,EAAE,aAAa,CAAC,YAAY,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC;QAC5D,cAAc,CAAC,EAAE,WAAW,CAAC;KAC9B,EACH,SAAS,CAAC,EAAE,UAAU,GACrB,OAAO,CAAC,KAAK,CAAC;IAuDjB;;;;;;OAMG;IACG,iBAAiB,CACrB,OAAO,CAAC,EAAE,sBAAsB,CAAC,QAAQ,CAAC,EAC1C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,IAAI,CAAC;IAIhB;;OAEG;IACH,IAAI,IAAI,IAAI;IAOZ;;;OAGG;IACH,OAAO,IAAI,IAAI;CA2GhB"}
@@ -1,8 +1,17 @@
1
- import { Messenger, ActionConstraint, EventConstraint } from "@metamask/messenger";
1
+ import { Messenger, ActionConstraint, EventConstraint, MessengerActions, MessengerEvents } from "@metamask/messenger";
2
+ import type { StorageServiceGetItemAction, StorageServiceRemoveItemAction, StorageServiceSetItemAction } from "@metamask/storage-service";
3
+ import { Struct } from "@metamask/superstruct";
2
4
  import type { Json } from "@metamask/utils";
3
- import { DehydratedState, FetchInfiniteQueryOptions, FetchQueryOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, WithRequired } from "@tanstack/query-core";
5
+ import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from "@tanstack/query-core";
4
6
  import { CreateServicePolicyOptions } from "./createServicePolicy.mjs";
5
7
  export type QueryKey = [string, ...Json[]];
8
+ /**
9
+ * The supertype of all messengers, scoped to a namespace.
10
+ *
11
+ * @template Namespace - The namespace for the messenger's own actions and
12
+ * events.
13
+ */
14
+ export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
6
15
  export type DataServiceGranularCacheUpdatedPayload = {
7
16
  type: 'added' | 'updated';
8
17
  state: DehydratedState;
@@ -15,9 +24,10 @@ export type DataServiceCacheUpdatedPayload = DataServiceGranularCacheUpdatedPayl
15
24
  };
16
25
  export type DataServiceInvalidateQueriesAction<ServiceName extends string> = {
17
26
  type: `${ServiceName}:invalidateQueries`;
18
- handler: (filters?: InvalidateQueryFilters<Json>, options?: InvalidateOptions) => Promise<void>;
27
+ handler: BaseDataService<ServiceName, BaseMessenger<ServiceName>>['invalidateQueries'];
19
28
  };
20
29
  export type DataServiceActions<ServiceName extends string> = DataServiceInvalidateQueriesAction<ServiceName>;
30
+ type DataServiceAllowedActions = StorageServiceGetItemAction | StorageServiceSetItemAction | StorageServiceRemoveItemAction;
21
31
  export type DataServiceCacheUpdatedEvent<ServiceName extends string> = {
22
32
  type: `${ServiceName}:cacheUpdated`;
23
33
  payload: [DataServiceCacheUpdatedPayload];
@@ -47,13 +57,13 @@ export type PersistenceConfiguration = {
47
57
  */
48
58
  maxWriteDelay?: number;
49
59
  };
50
- export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends Messenger<ServiceName, ActionConstraint, EventConstraint, any>> {
60
+ export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends BaseMessenger<ServiceName>> {
51
61
  #private;
52
62
  readonly name: ServiceName;
53
63
  protected messenger: ServiceMessenger;
54
64
  constructor({ name, messenger, queryClientConfig, policyOptions, persistenceConfig, }: {
55
65
  name: ServiceName;
56
- messenger: ServiceMessenger;
66
+ messenger: DataServiceActions<ServiceName>['type'] extends MessengerActions<ServiceMessenger>['type'] | DataServiceAllowedActions['type'] ? DataServiceEvents<ServiceName>['type'] extends MessengerEvents<ServiceMessenger>['type'] ? ServiceMessenger : never : never;
57
67
  queryClientConfig?: QueryClientConfig;
58
68
  policyOptions?: CreateServicePolicyOptions;
59
69
  persistenceConfig?: PersistenceConfiguration;
@@ -63,18 +73,26 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
63
73
  *
64
74
  * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
65
75
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
76
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
66
77
  * @returns The query results.
67
78
  */
68
- protected fetchQuery<TQueryFnData extends Json, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay'>, 'queryKey' | 'queryFn'>): Promise<TData>;
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'> & {
80
+ queryFn: QueryFunction<TQueryFnData, TQueryKey>;
81
+ responseStruct?: TDataStruct;
82
+ }): Promise<TData>;
69
83
  /**
70
84
  * Fetch a paginated query.
71
85
  *
72
86
  * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
73
87
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
88
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
74
89
  * @param pageParam - An optional page parameter.
75
90
  * @returns The query result, exclusively the requested page is returned.
76
91
  */
77
- protected fetchInfiniteQuery<TQueryFnData extends Json, TError = unknown, TData extends TQueryFnData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam extends Json = Json>(options: WithRequired<OmitKeyof<FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay'>, 'queryKey' | 'queryFn'>, pageParam?: TPageParam): Promise<TData>;
92
+ protected fetchInfiniteQuery<TQueryFnData extends Json, TError = DefaultError, TDataStruct extends Struct<TQueryFnData> | undefined = undefined, TData extends TQueryFnData = TDataStruct extends Struct<infer StructType> ? StructType : TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam extends Json = Json>({ responseStruct, ...options }: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, InfiniteData<TData, TPageParam>, TQueryKey, TPageParam>, 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'>, 'queryKey'> & InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {
93
+ queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
94
+ responseStruct?: TDataStruct;
95
+ }, pageParam?: TPageParam): Promise<TData>;
78
96
  /**
79
97
  * Invalidate queries serviced by this data service.
80
98
  *
@@ -82,7 +100,7 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
82
100
  * @param options - Additional optional options for query invalidations.
83
101
  * @returns Nothing.
84
102
  */
85
- invalidateQueries(filters?: InvalidateQueryFilters<Json>, options?: InvalidateOptions): Promise<void>;
103
+ invalidateQueries(filters?: InvalidateQueryFilters<QueryKey>, options?: InvalidateOptions): Promise<void>;
86
104
  /**
87
105
  * Initialize the service, rehydrating the cache with persisted data if possible.
88
106
  */
@@ -93,4 +111,5 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
93
111
  */
94
112
  destroy(): void;
95
113
  }
114
+ export {};
96
115
  //# sourceMappingURL=BaseDataService.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDataService.d.mts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAO7B,OAAO,KAAK,EAAE,IAAI,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H,IAAI,IAAI,IAAI;IAOZ;;;OAGG;IACH,OAAO,IAAI,IAAI;CA2GhB"}
@@ -17,6 +17,7 @@ function $importDefault(module) {
17
17
  return module;
18
18
  }
19
19
  import { Messenger } from "@metamask/messenger";
20
+ import { Struct } from "@metamask/superstruct";
20
21
  import { Duration, inMilliseconds } from "@metamask/utils";
21
22
  import { QueryClient, dehydrate, hydrate } from "@tanstack/query-core";
22
23
  import $deepEqual from "fast-deep-equal";
@@ -24,6 +25,7 @@ const deepEqual = $importDefault($deepEqual);
24
25
  import $lodash from "lodash";
25
26
  const { debounce } = $lodash;
26
27
  import { createServicePolicy } from "./createServicePolicy.mjs";
28
+ import { processQueryResponse } from "./utils.mjs";
27
29
  // Defaults to apply to all data service queries if no default option specified
28
30
  const QUERY_CLIENT_DEFAULTS = {
29
31
  queries: {
@@ -87,12 +89,16 @@ export class BaseDataService {
87
89
  *
88
90
  * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
89
91
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
92
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
90
93
  * @returns The query results.
91
94
  */
92
- async fetchQuery(options) {
95
+ async fetchQuery({ responseStruct, ...options }) {
93
96
  return __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchQuery({
94
97
  ...options,
95
- queryFn: (context) => __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn(context)),
98
+ queryFn: async (context) => {
99
+ const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn(context));
100
+ return processQueryResponse(options.queryKey, response, responseStruct);
101
+ },
96
102
  });
97
103
  }
98
104
  /**
@@ -100,35 +106,33 @@ export class BaseDataService {
100
106
  *
101
107
  * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
102
108
  * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
109
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
103
110
  * @param pageParam - An optional page parameter.
104
111
  * @returns The query result, exclusively the requested page is returned.
105
112
  */
106
- async fetchInfiniteQuery(options, pageParam) {
113
+ async fetchInfiniteQuery({ responseStruct, ...options }, pageParam) {
107
114
  const cache = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").getQueryCache();
108
115
  const query = cache.find({
109
116
  queryKey: options.queryKey,
110
117
  });
111
- if (!query?.state.data || pageParam === undefined) {
118
+ if (!query?.state.data || !pageParam) {
112
119
  const result = await __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchInfiniteQuery({
113
120
  ...options,
114
- queryFn: (context) => __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn({
115
- ...context,
116
- pageParam: context.pageParam ?? pageParam,
117
- })),
121
+ initialPageParam: pageParam ?? options.initialPageParam,
122
+ queryFn: async (context) => {
123
+ const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(async () => options.queryFn({
124
+ ...context,
125
+ pageParam: context.meta?.pageParam ?? context.pageParam,
126
+ }));
127
+ return processQueryResponse(options.queryKey, response, responseStruct);
128
+ },
118
129
  });
119
130
  return result.pages[0];
120
131
  }
121
- const { pages } = query.state.data;
122
- const previous = options.getPreviousPageParam?.(pages[0], pages);
123
- const direction = deepEqual(pageParam, previous) ? 'backward' : 'forward';
124
- const result = await query.fetch(undefined, {
125
- meta: {
126
- fetchMore: {
127
- direction,
128
- pageParam,
129
- },
130
- },
131
- });
132
+ const { pages, pageParams } = query.state.data;
133
+ const next = options.getNextPageParam(pages[pages.length - 1], pages, pageParams[pageParams.length - 1], pageParams);
134
+ const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';
135
+ const result = await query.fetch({ ...query.options, meta: { pageParam } }, { meta: { fetchMore: { direction } } });
132
136
  const pageIndex = result.pageParams.findIndex((param) => deepEqual(param, pageParam));
133
137
  return result.pages[pageIndex];
134
138
  }
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDataService.m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,CAAC;IAED,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CACjE,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;IAEF,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAG,YAAyC,CAAC;IAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,0CAAmB,CAAC,MAAM,EAAE,CAAC;QACnE,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,OAAO,CAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\nimport { Duration, inMilliseconds } from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport {\n DefaultOptions,\n DehydratedState,\n FetchInfiniteQueryOptions,\n FetchQueryOptions,\n InfiniteData,\n InvalidateOptions,\n InvalidateQueryFilters,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\n WithRequired,\n dehydrate,\n hydrate,\n} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\nimport { debounce, DebouncedFunc } from 'lodash';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\n\n// Data service queries use the following format: ['ServiceActionName', ...params]\nexport type QueryKey = [string, ...Json[]];\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: (\n filters?: InvalidateQueryFilters<Json>,\n options?: InvalidateOptions,\n ) => Promise<void>;\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 Messenger<\n ServiceName,\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 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: ServiceMessenger;\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 * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = unknown,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay'\n >,\n 'queryKey' | 'queryFn'\n >,\n ): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: (context) =>\n this.#policy.execute(() => options.queryFn(context)),\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 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 = unknown,\n TData extends TQueryFnData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay'\n >,\n 'queryKey' | 'queryFn'\n >,\n pageParam?: TPageParam,\n ): Promise<TData> {\n const cache = this.#queryClient.getQueryCache();\n\n const query = cache.find<TQueryFnData, TError, InfiniteData<TData>>({\n queryKey: options.queryKey,\n });\n\n if (!query?.state.data || pageParam === undefined) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n queryFn: (context) =>\n this.#policy.execute(() =>\n options.queryFn({\n ...context,\n pageParam: context.pageParam ?? pageParam,\n }),\n ),\n });\n\n return result.pages[0];\n }\n\n const { pages } = query.state.data;\n const previous = options.getPreviousPageParam?.(pages[0], pages);\n\n const direction = deepEqual(pageParam, previous) ? 'backward' : 'forward';\n\n const result = await query.fetch(undefined, {\n meta: {\n fetchMore: {\n direction,\n pageParam,\n },\n },\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<Json>,\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.mjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,EACL,SAAS,EAKV,4BAA4B;AAM7B,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAC/C,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,wBAAwB;AAE3D,OAAO,E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AC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAmB;QAC5B,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;QACrB,KAAK;KACN,CAAC;IAEF,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,EACnB,KAAwB,CACzB,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,IAAI,CAAC,uBAAA,IAAI,0CAAmB,EAAE,CAAC;QAC7B,OAAO;IACT,CAAC;IAED,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CACjE,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;IAEF,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAG,YAAyC,CAAC;IAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,0CAAmB,CAAC,MAAM,EAAE,CAAC;QACnE,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,OAAO,CAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","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';\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[]];\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"]}
package/dist/utils.cjs ADDED
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.processQueryResponse = void 0;
4
+ const superstruct_1 = require("@metamask/superstruct");
5
+ /**
6
+ * Process query responses, validating them using Superstruct if a struct is defined.
7
+ *
8
+ * @param queryKey - The query key.
9
+ * @param response - The query response
10
+ * @param struct - The struct defining the schema for the query response.
11
+ * @returns The query response, coerced by Superstruct if needed.
12
+ * @throws If the query response does not match the struct.
13
+ */
14
+ function processQueryResponse(queryKey, response, struct) {
15
+ if (!struct) {
16
+ return response;
17
+ }
18
+ const [error, result] = (0, superstruct_1.validate)(response, struct);
19
+ if (error) {
20
+ throw new Error(`Query function for "${queryKey[0]}" returned an unexpected response: ${error.message}.`);
21
+ }
22
+ return result;
23
+ }
24
+ exports.processQueryResponse = processQueryResponse;
25
+ //# sourceMappingURL=utils.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,uDAAyD;AAIzD;;;;;;;;GAQG;AACH,SAAgB,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,IAAA,sBAAQ,EAAC,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;AAlBD,oDAkBC","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"]}
@@ -0,0 +1,13 @@
1
+ import { Struct } from "@metamask/superstruct";
2
+ import type { QueryKey } from "./BaseDataService.cjs";
3
+ /**
4
+ * Process query responses, validating them using Superstruct if a struct is defined.
5
+ *
6
+ * @param queryKey - The query key.
7
+ * @param response - The query response
8
+ * @param struct - The struct defining the schema for the query response.
9
+ * @returns The query response, coerced by Superstruct if needed.
10
+ * @throws If the query response does not match the struct.
11
+ */
12
+ export declare function processQueryResponse<Response>(queryKey: QueryKey, response: Response, struct?: Struct<Response>): Response;
13
+ //# sourceMappingURL=utils.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,8BAA8B;AAEzD,OAAO,KAAK,EAAE,QAAQ,EAAE,8BAA6B;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"}
@@ -0,0 +1,13 @@
1
+ import { Struct } from "@metamask/superstruct";
2
+ import type { QueryKey } from "./BaseDataService.mjs";
3
+ /**
4
+ * Process query responses, validating them using Superstruct if a struct is defined.
5
+ *
6
+ * @param queryKey - The query key.
7
+ * @param response - The query response
8
+ * @param struct - The struct defining the schema for the query response.
9
+ * @returns The query response, coerced by Superstruct if needed.
10
+ * @throws If the query response does not match the struct.
11
+ */
12
+ export declare function processQueryResponse<Response>(queryKey: QueryKey, response: Response, struct?: Struct<Response>): Response;
13
+ //# sourceMappingURL=utils.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,8BAA8B;AAEzD,OAAO,KAAK,EAAE,QAAQ,EAAE,8BAA6B;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"}
package/dist/utils.mjs ADDED
@@ -0,0 +1,21 @@
1
+ import { Struct, validate } from "@metamask/superstruct";
2
+ /**
3
+ * Process query responses, validating them using Superstruct if a struct is defined.
4
+ *
5
+ * @param queryKey - The query key.
6
+ * @param response - The query response
7
+ * @param struct - The struct defining the schema for the query response.
8
+ * @returns The query response, coerced by Superstruct if needed.
9
+ * @throws If the query response does not match the struct.
10
+ */
11
+ export function processQueryResponse(queryKey, response, struct) {
12
+ if (!struct) {
13
+ return response;
14
+ }
15
+ const [error, result] = validate(response, struct);
16
+ if (error) {
17
+ throw new Error(`Query function for "${queryKey[0]}" returned an unexpected response: ${error.message}.`);
18
+ }
19
+ return result;
20
+ }
21
+ //# sourceMappingURL=utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,8BAA8B;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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/base-data-service",
3
- "version": "0.1.3-preview-4758e65ff",
3
+ "version": "0.1.3-preview-bbf9454b2",
4
4
  "description": "Provides utilities for building data services",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -58,8 +58,9 @@
58
58
  "dependencies": {
59
59
  "@metamask/messenger": "^2.0.0",
60
60
  "@metamask/storage-service": "^1.0.2",
61
+ "@metamask/superstruct": "^3.4.1",
61
62
  "@metamask/utils": "^11.11.0",
62
- "@tanstack/query-core": "^4.43.0",
63
+ "@tanstack/query-core": "^5.62.16",
63
64
  "cockatiel": "^3.1.2",
64
65
  "fast-deep-equal": "^3.1.3",
65
66
  "lodash": "^4.17.21"