@metamask-previews/base-data-service 0.1.3-preview-d21e2aaf9 → 0.1.3-preview-6426280bb

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
@@ -40,6 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
40
40
  - This is technically a breaking change, but this was not used in any of our codebases
41
41
  - **BREAKING:** Bump `@tanstack/query-core` from `^4.43.0` to `^5.62.16` ([#9712](https://github.com/MetaMask/core/pull/9712))
42
42
  - The option types accepted by `fetchQuery`, `fetchInfiniteQuery`, and `invalidateQueries` now follow the query-core v5 API. Subclasses need to rename `cacheTime` to `gcTime`.
43
+ - `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.
43
44
  - Bump `@metamask/utils` from `^11.9.0` to `^11.11.0` ([#9074](https://github.com/MetaMask/core/pull/9074))
44
45
  - 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))
45
46
  - Bump `@metamask/messenger` from `^1.2.0` to `^2.0.0` ([#9392](https://github.com/MetaMask/core/pull/9392))
@@ -83,8 +83,13 @@ class BaseDataService {
83
83
  /**
84
84
  * Fetch a query.
85
85
  *
86
- * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
87
- * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
86
+ * @param options - The options defining the query. Note that although this
87
+ * method wraps `fetchQuery` from `@tanstack/query-core`, there are a few
88
+ * restrictions:
89
+ * - `queryKey` and `queryFn` are required
90
+ * - `queryFn` must be a function, not a skip token
91
+ * - `retry` and `retryDelay` are not available (retries can be customized
92
+ * using the constructor's `servicePolicyOptions`).
88
93
  * @returns The query results.
89
94
  */
90
95
  async fetchQuery(options) {
@@ -96,33 +101,64 @@ class BaseDataService {
96
101
  /**
97
102
  * Fetch a paginated query.
98
103
  *
99
- * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
100
- * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
104
+ * @param options - The options defining the query. Note that although this
105
+ * method wraps `fetchInfiniteQuery` from `@tanstack/query-core`, there are a
106
+ * few differences:
107
+ * - `queryKey` and `queryFn` are required
108
+ * - `queryFn` must be a function, not a skip token
109
+ * - `retry` and `retryDelay` are not available (retries can be customized
110
+ * using the constructor's `servicePolicyOptions`).
101
111
  * @param pageParam - An optional page parameter.
102
- * @returns The query result, exclusively the requested page is returned.
112
+ * @returns A page's worth of data (i.e. what `queryFn` returns). Note that
113
+ * this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`
114
+ * method, which returns all pages.
103
115
  */
104
116
  async fetchInfiniteQuery(options, pageParam) {
105
- const cache = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").getQueryCache();
106
- const query = cache.find({
117
+ // A missing per-call `pageParam` means "the first page", which uses the
118
+ // consumer's `initialPageParam`. A `null` initial param is preserved: `??`
119
+ // only falls back when the per-call param itself is missing.
120
+ const requestedPageParam = pageParam ?? options.initialPageParam;
121
+ const query = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
122
+ .getQueryCache()
123
+ .find({
107
124
  queryKey: options.queryKey,
108
125
  });
109
- if (!query?.state.data || pageParam === undefined) {
126
+ // The first page (or a cold cache) goes through query-core's
127
+ // `fetchInfiniteQuery`, which reuses the cached page while the query is
128
+ // fresh. A cold jump starts the query at the requested page by using it as
129
+ // the initial page param.
130
+ if (!query?.state.data ||
131
+ (0, fast_deep_equal_1.default)(requestedPageParam, options.initialPageParam)) {
110
132
  const result = await __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchInfiniteQuery({
111
133
  ...options,
112
- initialPageParam: pageParam ?? options.initialPageParam,
113
- queryFn: (context) => __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn({
114
- ...context,
115
- pageParam: context.meta?.pageParam ?? context.pageParam,
116
- })),
134
+ initialPageParam: requestedPageParam,
135
+ queryFn: (context) => __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn(context)),
117
136
  });
118
137
  return result.pages[0];
119
138
  }
139
+ // A later page on an existing query. v5 no longer forwards an explicit page
140
+ // param, so fetch it directly and merge it into the infinite cache,
141
+ // appending the next page or prepending an earlier one.
120
142
  const { pages, pageParams } = query.state.data;
121
- const next = options.getNextPageParam(pages[pages.length - 1], pages, pageParams[pageParams.length - 1], pageParams);
122
- const direction = (0, fast_deep_equal_1.default)(pageParam, next) ? 'forward' : 'backward';
123
- const result = await query.fetch({ ...query.options, meta: { pageParam } }, { meta: { fetchMore: { direction } } });
124
- const pageIndex = result.pageParams.findIndex((param) => (0, fast_deep_equal_1.default)(param, pageParam));
125
- return result.pages[pageIndex];
143
+ const page = (await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn({
144
+ client: __classPrivateFieldGet(this, _BaseDataService_queryClient, "f"),
145
+ queryKey: options.queryKey,
146
+ signal: new AbortController().signal,
147
+ pageParam: requestedPageParam,
148
+ direction: 'forward',
149
+ meta: options.meta,
150
+ })));
151
+ const nextPageParam = options.getNextPageParam(pages[pages.length - 1], pages, pageParams[pageParams.length - 1], pageParams);
152
+ __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").setQueryData(options.queryKey, (0, fast_deep_equal_1.default)(requestedPageParam, nextPageParam)
153
+ ? {
154
+ pages: [...pages, page],
155
+ pageParams: [...pageParams, requestedPageParam],
156
+ }
157
+ : {
158
+ pages: [page, ...pages],
159
+ pageParams: [requestedPageParam, ...pageParams],
160
+ });
161
+ return page;
126
162
  }
127
163
  /**
128
164
  * Invalidate queries serviced by this data service.
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDataService.cjs","sourceRoot":"","sources":["../src/B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AAmB,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 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';\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<QueryKey>,\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 = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & { queryFn: QueryFunction<TQueryFnData, TQueryKey> },\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 = DefaultError,\n TData extends TQueryFnData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n options: 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 },\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 === undefined) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: pageParam ?? options.initialPageParam,\n queryFn: (context) =>\n this.#policy.execute(() =>\n options.queryFn({\n ...context,\n pageParam: context.meta?.pageParam ?? context.pageParam,\n }),\n ),\n });\n\n return result.pages[0];\n }\n\n const { pages, pageParams } = query.state.data;\n const next = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n\n const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';\n\n const result = await query.fetch(\n { ...query.options, meta: { pageParam } },\n { meta: { fetchMore: { direction } } },\n );\n\n const pageIndex = result.pageParams.findIndex((param) =>\n deepEqual(param, pageParam),\n );\n\n return result.pages[pageIndex];\n }\n\n /**\n * Invalidate queries serviced by this data service.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @param options - Additional optional options for query invalidations.\n * @returns Nothing.\n */\n async invalidateQueries(\n filters?: InvalidateQueryFilters<QueryKey>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\n }\n\n /**\n * Initialize the service, rehydrating the cache with persisted data if possible.\n */\n init(): void {\n this.#loadCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n }\n\n /**\n * Prepares the service for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n */\n destroy(): void {\n this.#debouncedPersist?.cancel();\n this.#queryCacheUnsubscribe();\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when a given query changes.\n *\n * @param hash The hash of the query.\n * @param type The type of cache update.\n */\n #publishCacheUpdate(hash: string, type: CacheUpdatedType): void {\n const state =\n type === 'added' || type === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) => query.queryHash === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type,\n state,\n } as DataServiceGranularCacheUpdatedPayload,\n );\n }\n\n /**\n * Persist the query client cache using the StorageService, if the cache is not empty.\n *\n * @returns Nothing.\n */\n async #persistCache(): Promise<void> {\n const state = dehydrate(this.#queryClient, {\n // This is the default, but we specify it to be explicit.\n shouldDehydrateQuery: (query) => query.state.status === 'success',\n });\n\n if (state.queries.length === 0 && state.mutations.length === 0) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n const cache: PersistedCache = {\n timestamp: Date.now(),\n state,\n };\n\n await this.#externalMessenger.call(\n 'StorageService:setItem',\n this.name,\n STORAGE_SERVICE_KEY,\n cache as unknown as Json,\n );\n }\n\n /**\n * Load the query client cache from the StorageService, if persistence is configured\n * and the persisted cache is not expired.\n *\n * @returns Nothing.\n */\n async #loadCache(): Promise<void> {\n if (!this.#persistenceConfig) {\n return;\n }\n\n const { result: untypedCache } = await this.#externalMessenger.call(\n 'StorageService:getItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n\n if (!untypedCache) {\n return;\n }\n\n const cache = untypedCache as unknown as PersistedCache;\n\n if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n hydrate(this.#queryClient, cache.state);\n }\n}\n"]}
1
+ {"version":3,"file":"BaseDataService.cjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,mDAI6B;AAM7B,2CAA2D;AAE3D,qDAgB8B;AAC9B,sEAAwC;AACxC,mCAAiD;AAEjD,sEAIkC;AAiElC,+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;IA6B1B,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,CA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;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 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';\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: 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. Note that although this\n * method wraps `fetchQuery` from `@tanstack/query-core`, there are a few\n * restrictions:\n * - `queryKey` and `queryFn` are required\n * - `queryFn` must be a function, not a skip token\n * - `retry` and `retryDelay` are not available (retries can be customized\n * using the constructor's `servicePolicyOptions`).\n * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & {\n // @tanstack/query-core's fetchQuery function accepts a \"skip\" token, but\n // data services always provide a concrete query function.\n queryFn: QueryFunction<TQueryFnData, TQueryKey>;\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. Note that although this\n * method wraps `fetchInfiniteQuery` from `@tanstack/query-core`, there are a\n * few differences:\n * - `queryKey` and `queryFn` are required\n * - `queryFn` must be a function, not a skip token\n * - `retry` and `retryDelay` are not available (retries can be customized\n * using the constructor's `servicePolicyOptions`).\n * @param pageParam - An optional page parameter.\n * @returns A page's worth of data (i.e. what `queryFn` returns). Note that\n * this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`\n * method, which returns all pages.\n */\n protected async fetchInfiniteQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TData extends TQueryFnData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n options: 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 },\n pageParam?: TPageParam,\n ): Promise<TData> {\n // A missing per-call `pageParam` means \"the first page\", which uses the\n // consumer's `initialPageParam`. A `null` initial param is preserved: `??`\n // only falls back when the per-call param itself is missing.\n const requestedPageParam = pageParam ?? options.initialPageParam;\n\n const query = this.#queryClient\n .getQueryCache()\n .find<TQueryFnData, TError, InfiniteData<TData, TPageParam>>({\n queryKey: options.queryKey,\n });\n\n // The first page (or a cold cache) goes through query-core's\n // `fetchInfiniteQuery`, which reuses the cached page while the query is\n // fresh. A cold jump starts the query at the requested page by using it as\n // the initial page param.\n if (\n !query?.state.data ||\n deepEqual(requestedPageParam, options.initialPageParam)\n ) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: requestedPageParam,\n queryFn: (context) =>\n this.#policy.execute(() => options.queryFn(context)),\n });\n\n return result.pages[0];\n }\n\n // A later page on an existing query. v5 no longer forwards an explicit page\n // param, so fetch it directly and merge it into the infinite cache,\n // appending the next page or prepending an earlier one.\n const { pages, pageParams } = query.state.data;\n const page = (await this.#policy.execute(() =>\n options.queryFn({\n client: this.#queryClient,\n queryKey: options.queryKey,\n signal: new AbortController().signal,\n pageParam: requestedPageParam,\n direction: 'forward',\n meta: options.meta,\n }),\n )) as TData;\n const nextPageParam = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n this.#queryClient.setQueryData<InfiniteData<TData, TPageParam>>(\n options.queryKey,\n deepEqual(requestedPageParam, nextPageParam)\n ? {\n pages: [...pages, page],\n pageParams: [...pageParams, requestedPageParam],\n }\n : {\n pages: [page, ...pages],\n pageParams: [requestedPageParam, ...pageParams],\n },\n );\n\n return page;\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"]}
@@ -3,6 +3,13 @@ import type { Json } from "@metamask/utils";
3
3
  import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from "@tanstack/query-core";
4
4
  import { CreateServicePolicyOptions } from "./createServicePolicy.cjs";
5
5
  export type QueryKey = [string, ...Json[]];
6
+ /**
7
+ * The supertype of all messengers, scoped to a namespace.
8
+ *
9
+ * @template Namespace - The namespace for the messenger's own actions and
10
+ * events.
11
+ */
12
+ export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
6
13
  export type DataServiceGranularCacheUpdatedPayload = {
7
14
  type: 'added' | 'updated';
8
15
  state: DehydratedState;
@@ -15,7 +22,7 @@ export type DataServiceCacheUpdatedPayload = DataServiceGranularCacheUpdatedPayl
15
22
  };
16
23
  export type DataServiceInvalidateQueriesAction<ServiceName extends string> = {
17
24
  type: `${ServiceName}:invalidateQueries`;
18
- handler: (filters?: InvalidateQueryFilters<QueryKey>, options?: InvalidateOptions) => Promise<void>;
25
+ handler: BaseDataService<ServiceName, BaseMessenger<ServiceName>>['invalidateQueries'];
19
26
  };
20
27
  export type DataServiceActions<ServiceName extends string> = DataServiceInvalidateQueriesAction<ServiceName>;
21
28
  export type DataServiceCacheUpdatedEvent<ServiceName extends string> = {
@@ -47,7 +54,7 @@ export type PersistenceConfiguration = {
47
54
  */
48
55
  maxWriteDelay?: number;
49
56
  };
50
- export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends Messenger<ServiceName, ActionConstraint, EventConstraint, any>> {
57
+ export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends BaseMessenger<ServiceName>> {
51
58
  #private;
52
59
  readonly name: ServiceName;
53
60
  protected messenger: ServiceMessenger;
@@ -61,8 +68,13 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
61
68
  /**
62
69
  * Fetch a query.
63
70
  *
64
- * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
65
- * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
71
+ * @param options - The options defining the query. Note that although this
72
+ * method wraps `fetchQuery` from `@tanstack/query-core`, there are a few
73
+ * restrictions:
74
+ * - `queryKey` and `queryFn` are required
75
+ * - `queryFn` must be a function, not a skip token
76
+ * - `retry` and `retryDelay` are not available (retries can be customized
77
+ * using the constructor's `servicePolicyOptions`).
66
78
  * @returns The query results.
67
79
  */
68
80
  protected fetchQuery<TQueryFnData extends Json, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay' | 'queryFn'>, 'queryKey'> & {
@@ -71,10 +83,17 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
71
83
  /**
72
84
  * Fetch a paginated query.
73
85
  *
74
- * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
75
- * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
86
+ * @param options - The options defining the query. Note that although this
87
+ * method wraps `fetchInfiniteQuery` from `@tanstack/query-core`, there are a
88
+ * few differences:
89
+ * - `queryKey` and `queryFn` are required
90
+ * - `queryFn` must be a function, not a skip token
91
+ * - `retry` and `retryDelay` are not available (retries can be customized
92
+ * using the constructor's `servicePolicyOptions`).
76
93
  * @param pageParam - An optional page parameter.
77
- * @returns The query result, exclusively the requested page is returned.
94
+ * @returns A page's worth of data (i.e. what `queryFn` returns). Note that
95
+ * this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`
96
+ * method, which returns all pages.
78
97
  */
79
98
  protected fetchInfiniteQuery<TQueryFnData extends Json, TError = DefaultError, TData extends TQueryFnData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam extends Json = Json>(options: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, InfiniteData<TData, TPageParam>, TQueryKey, TPageParam>, 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'>, 'queryKey'> & InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {
80
99
  queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
@@ -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,EACL,YAAY,EAEZ,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,8BAA8B,EAC9B,iBAAiB,EACjB,sBAAsB,EACtB,SAAS,EAET,iBAAiB,EACjB,aAAa,EACb,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,EAA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C,EAAE,UAAU,GACrB,OAAO,CAAC,KAAK,CAAC;IAkEjB;;;;;;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"}
@@ -3,6 +3,13 @@ import type { Json } from "@metamask/utils";
3
3
  import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from "@tanstack/query-core";
4
4
  import { CreateServicePolicyOptions } from "./createServicePolicy.mjs";
5
5
  export type QueryKey = [string, ...Json[]];
6
+ /**
7
+ * The supertype of all messengers, scoped to a namespace.
8
+ *
9
+ * @template Namespace - The namespace for the messenger's own actions and
10
+ * events.
11
+ */
12
+ export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
6
13
  export type DataServiceGranularCacheUpdatedPayload = {
7
14
  type: 'added' | 'updated';
8
15
  state: DehydratedState;
@@ -15,7 +22,7 @@ export type DataServiceCacheUpdatedPayload = DataServiceGranularCacheUpdatedPayl
15
22
  };
16
23
  export type DataServiceInvalidateQueriesAction<ServiceName extends string> = {
17
24
  type: `${ServiceName}:invalidateQueries`;
18
- handler: (filters?: InvalidateQueryFilters<QueryKey>, options?: InvalidateOptions) => Promise<void>;
25
+ handler: BaseDataService<ServiceName, BaseMessenger<ServiceName>>['invalidateQueries'];
19
26
  };
20
27
  export type DataServiceActions<ServiceName extends string> = DataServiceInvalidateQueriesAction<ServiceName>;
21
28
  export type DataServiceCacheUpdatedEvent<ServiceName extends string> = {
@@ -47,7 +54,7 @@ export type PersistenceConfiguration = {
47
54
  */
48
55
  maxWriteDelay?: number;
49
56
  };
50
- export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends Messenger<ServiceName, ActionConstraint, EventConstraint, any>> {
57
+ export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends BaseMessenger<ServiceName>> {
51
58
  #private;
52
59
  readonly name: ServiceName;
53
60
  protected messenger: ServiceMessenger;
@@ -61,8 +68,13 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
61
68
  /**
62
69
  * Fetch a query.
63
70
  *
64
- * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
65
- * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
71
+ * @param options - The options defining the query. Note that although this
72
+ * method wraps `fetchQuery` from `@tanstack/query-core`, there are a few
73
+ * restrictions:
74
+ * - `queryKey` and `queryFn` are required
75
+ * - `queryFn` must be a function, not a skip token
76
+ * - `retry` and `retryDelay` are not available (retries can be customized
77
+ * using the constructor's `servicePolicyOptions`).
66
78
  * @returns The query results.
67
79
  */
68
80
  protected fetchQuery<TQueryFnData extends Json, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay' | 'queryFn'>, 'queryKey'> & {
@@ -71,10 +83,17 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
71
83
  /**
72
84
  * Fetch a paginated query.
73
85
  *
74
- * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
75
- * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
86
+ * @param options - The options defining the query. Note that although this
87
+ * method wraps `fetchInfiniteQuery` from `@tanstack/query-core`, there are a
88
+ * few differences:
89
+ * - `queryKey` and `queryFn` are required
90
+ * - `queryFn` must be a function, not a skip token
91
+ * - `retry` and `retryDelay` are not available (retries can be customized
92
+ * using the constructor's `servicePolicyOptions`).
76
93
  * @param pageParam - An optional page parameter.
77
- * @returns The query result, exclusively the requested page is returned.
94
+ * @returns A page's worth of data (i.e. what `queryFn` returns). Note that
95
+ * this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`
96
+ * method, which returns all pages.
78
97
  */
79
98
  protected fetchInfiniteQuery<TQueryFnData extends Json, TError = DefaultError, TData extends TQueryFnData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam extends Json = Json>(options: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, InfiniteData<TData, TPageParam>, TQueryKey, TPageParam>, 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'>, 'queryKey'> & InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {
80
99
  queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
@@ -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,EAAE,wBAAwB;AAC5C,OAAO,EACL,YAAY,EAEZ,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,8BAA8B,EAC9B,iBAAiB,EACjB,sBAAsB,EACtB,SAAS,EAET,iBAAiB,EACjB,aAAa,EACb,YAAY,EAGb,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,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Q,CAAC,EAC1C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,IAAI,CAAC;IAIhB;;OAEG;IACH,IAAI,IAAI,IAAI;IAOZ;;;OAGG;IACH,OAAO,IAAI,IAAI;CA2GhB"}
@@ -85,8 +85,13 @@ export class BaseDataService {
85
85
  /**
86
86
  * Fetch a query.
87
87
  *
88
- * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
89
- * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
88
+ * @param options - The options defining the query. Note that although this
89
+ * method wraps `fetchQuery` from `@tanstack/query-core`, there are a few
90
+ * restrictions:
91
+ * - `queryKey` and `queryFn` are required
92
+ * - `queryFn` must be a function, not a skip token
93
+ * - `retry` and `retryDelay` are not available (retries can be customized
94
+ * using the constructor's `servicePolicyOptions`).
90
95
  * @returns The query results.
91
96
  */
92
97
  async fetchQuery(options) {
@@ -98,33 +103,64 @@ export class BaseDataService {
98
103
  /**
99
104
  * Fetch a paginated query.
100
105
  *
101
- * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
102
- * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
106
+ * @param options - The options defining the query. Note that although this
107
+ * method wraps `fetchInfiniteQuery` from `@tanstack/query-core`, there are a
108
+ * few differences:
109
+ * - `queryKey` and `queryFn` are required
110
+ * - `queryFn` must be a function, not a skip token
111
+ * - `retry` and `retryDelay` are not available (retries can be customized
112
+ * using the constructor's `servicePolicyOptions`).
103
113
  * @param pageParam - An optional page parameter.
104
- * @returns The query result, exclusively the requested page is returned.
114
+ * @returns A page's worth of data (i.e. what `queryFn` returns). Note that
115
+ * this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`
116
+ * method, which returns all pages.
105
117
  */
106
118
  async fetchInfiniteQuery(options, pageParam) {
107
- const cache = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").getQueryCache();
108
- const query = cache.find({
119
+ // A missing per-call `pageParam` means "the first page", which uses the
120
+ // consumer's `initialPageParam`. A `null` initial param is preserved: `??`
121
+ // only falls back when the per-call param itself is missing.
122
+ const requestedPageParam = pageParam ?? options.initialPageParam;
123
+ const query = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
124
+ .getQueryCache()
125
+ .find({
109
126
  queryKey: options.queryKey,
110
127
  });
111
- if (!query?.state.data || pageParam === undefined) {
128
+ // The first page (or a cold cache) goes through query-core's
129
+ // `fetchInfiniteQuery`, which reuses the cached page while the query is
130
+ // fresh. A cold jump starts the query at the requested page by using it as
131
+ // the initial page param.
132
+ if (!query?.state.data ||
133
+ deepEqual(requestedPageParam, options.initialPageParam)) {
112
134
  const result = await __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchInfiniteQuery({
113
135
  ...options,
114
- initialPageParam: pageParam ?? options.initialPageParam,
115
- queryFn: (context) => __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn({
116
- ...context,
117
- pageParam: context.meta?.pageParam ?? context.pageParam,
118
- })),
136
+ initialPageParam: requestedPageParam,
137
+ queryFn: (context) => __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn(context)),
119
138
  });
120
139
  return result.pages[0];
121
140
  }
141
+ // A later page on an existing query. v5 no longer forwards an explicit page
142
+ // param, so fetch it directly and merge it into the infinite cache,
143
+ // appending the next page or prepending an earlier one.
122
144
  const { pages, pageParams } = query.state.data;
123
- const next = options.getNextPageParam(pages[pages.length - 1], pages, pageParams[pageParams.length - 1], pageParams);
124
- const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';
125
- const result = await query.fetch({ ...query.options, meta: { pageParam } }, { meta: { fetchMore: { direction } } });
126
- const pageIndex = result.pageParams.findIndex((param) => deepEqual(param, pageParam));
127
- return result.pages[pageIndex];
145
+ const page = (await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn({
146
+ client: __classPrivateFieldGet(this, _BaseDataService_queryClient, "f"),
147
+ queryKey: options.queryKey,
148
+ signal: new AbortController().signal,
149
+ pageParam: requestedPageParam,
150
+ direction: 'forward',
151
+ meta: options.meta,
152
+ })));
153
+ const nextPageParam = options.getNextPageParam(pages[pages.length - 1], pages, pageParams[pageParams.length - 1], pageParams);
154
+ __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").setQueryData(options.queryKey, deepEqual(requestedPageParam, nextPageParam)
155
+ ? {
156
+ pages: [...pages, page],
157
+ pageParams: [...pageParams, requestedPageParam],
158
+ }
159
+ : {
160
+ pages: [page, ...pages],
161
+ pageParams: [requestedPageParam, ...pageParams],
162
+ });
163
+ return page;
128
164
  }
129
165
  /**
130
166
  * Invalidate queries serviced by this data service.
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDataService.mjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,EACL,SAAS,EAGV,4BAA4B;AAM7B,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,wBAAwB;AAE3D,OAAO,EAUL,WAAW,EAIX,SAAS,EACT,OAAO,EACR,6BAA6B;AAC9B,OAAO,UAAS,wBAAwB;;;;AAGxC,OAAO,EACL,mBAAmB,EAGpB,kCAAiC;AAiDlC,+EAA+E;AAC/E,MAAM,qBAAqB,GAAmB;IAC5C,OAAO,EAAE;QACP,KAAK,EAAE,KAAK;QACZ,SAAS,EAAE,cAAc,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC;KAC9C;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,mBAAmB,GAAG,OAAO,CAAC;AA2B3C,MAAM,OAAO,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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I,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 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';\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<QueryKey>,\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 = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & { queryFn: QueryFunction<TQueryFnData, TQueryKey> },\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 = DefaultError,\n TData extends TQueryFnData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n options: 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 },\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 === undefined) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: pageParam ?? options.initialPageParam,\n queryFn: (context) =>\n this.#policy.execute(() =>\n options.queryFn({\n ...context,\n pageParam: context.meta?.pageParam ?? context.pageParam,\n }),\n ),\n });\n\n return result.pages[0];\n }\n\n const { pages, pageParams } = query.state.data;\n const next = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n\n const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';\n\n const result = await query.fetch(\n { ...query.options, meta: { pageParam } },\n { meta: { fetchMore: { direction } } },\n );\n\n const pageIndex = result.pageParams.findIndex((param) =>\n deepEqual(param, pageParam),\n );\n\n return result.pages[pageIndex];\n }\n\n /**\n * Invalidate queries serviced by this data service.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @param options - Additional optional options for query invalidations.\n * @returns Nothing.\n */\n async invalidateQueries(\n filters?: InvalidateQueryFilters<QueryKey>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\n }\n\n /**\n * Initialize the service, rehydrating the cache with persisted data if possible.\n */\n init(): void {\n this.#loadCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n }\n\n /**\n * Prepares the service for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n */\n destroy(): void {\n this.#debouncedPersist?.cancel();\n this.#queryCacheUnsubscribe();\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when a given query changes.\n *\n * @param hash The hash of the query.\n * @param type The type of cache update.\n */\n #publishCacheUpdate(hash: string, type: CacheUpdatedType): void {\n const state =\n type === 'added' || type === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) => query.queryHash === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type,\n state,\n } as DataServiceGranularCacheUpdatedPayload,\n );\n }\n\n /**\n * Persist the query client cache using the StorageService, if the cache is not empty.\n *\n * @returns Nothing.\n */\n async #persistCache(): Promise<void> {\n const state = dehydrate(this.#queryClient, {\n // This is the default, but we specify it to be explicit.\n shouldDehydrateQuery: (query) => query.state.status === 'success',\n });\n\n if (state.queries.length === 0 && state.mutations.length === 0) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n const cache: PersistedCache = {\n timestamp: Date.now(),\n state,\n };\n\n await this.#externalMessenger.call(\n 'StorageService:setItem',\n this.name,\n STORAGE_SERVICE_KEY,\n cache as unknown as Json,\n );\n }\n\n /**\n * Load the query client cache from the StorageService, if persistence is configured\n * and the persisted cache is not expired.\n *\n * @returns Nothing.\n */\n async #loadCache(): Promise<void> {\n if (!this.#persistenceConfig) {\n return;\n }\n\n const { result: untypedCache } = await this.#externalMessenger.call(\n 'StorageService:getItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n\n if (!untypedCache) {\n return;\n }\n\n const cache = untypedCache as unknown as PersistedCache;\n\n if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n hydrate(this.#queryClient, cache.state);\n }\n}\n"]}
1
+ {"version":3,"file":"BaseDataService.mjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,EACL,SAAS,EAGV,4BAA4B;AAM7B,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,wBAAwB;AAE3D,OAAO,EAUL,WAAW,EAIX,SAAS,EACT,OAAO,EACR,6BAA6B;AAC9B,OAAO,UAAS,wBAAwB;;;;AAGxC,OAAO,EACL,mBAAmB,EAGpB,kCAAiC;AAiElC,+EAA+E;AAC/E,MAAM,qBAAqB,GAAmB;IAC5C,OAAO,EAAE;QACP,KAAK,EAAE,KAAK;QACZ,SAAS,EAAE,cAAc,CAAC,CAAC,EAAE,QAAQ,CAAC,M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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} 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 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';\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: 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. Note that although this\n * method wraps `fetchQuery` from `@tanstack/query-core`, there are a few\n * restrictions:\n * - `queryKey` and `queryFn` are required\n * - `queryFn` must be a function, not a skip token\n * - `retry` and `retryDelay` are not available (retries can be customized\n * using the constructor's `servicePolicyOptions`).\n * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & {\n // @tanstack/query-core's fetchQuery function accepts a \"skip\" token, but\n // data services always provide a concrete query function.\n queryFn: QueryFunction<TQueryFnData, TQueryKey>;\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. Note that although this\n * method wraps `fetchInfiniteQuery` from `@tanstack/query-core`, there are a\n * few differences:\n * - `queryKey` and `queryFn` are required\n * - `queryFn` must be a function, not a skip token\n * - `retry` and `retryDelay` are not available (retries can be customized\n * using the constructor's `servicePolicyOptions`).\n * @param pageParam - An optional page parameter.\n * @returns A page's worth of data (i.e. what `queryFn` returns). Note that\n * this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`\n * method, which returns all pages.\n */\n protected async fetchInfiniteQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TData extends TQueryFnData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n options: 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 },\n pageParam?: TPageParam,\n ): Promise<TData> {\n // A missing per-call `pageParam` means \"the first page\", which uses the\n // consumer's `initialPageParam`. A `null` initial param is preserved: `??`\n // only falls back when the per-call param itself is missing.\n const requestedPageParam = pageParam ?? options.initialPageParam;\n\n const query = this.#queryClient\n .getQueryCache()\n .find<TQueryFnData, TError, InfiniteData<TData, TPageParam>>({\n queryKey: options.queryKey,\n });\n\n // The first page (or a cold cache) goes through query-core's\n // `fetchInfiniteQuery`, which reuses the cached page while the query is\n // fresh. A cold jump starts the query at the requested page by using it as\n // the initial page param.\n if (\n !query?.state.data ||\n deepEqual(requestedPageParam, options.initialPageParam)\n ) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: requestedPageParam,\n queryFn: (context) =>\n this.#policy.execute(() => options.queryFn(context)),\n });\n\n return result.pages[0];\n }\n\n // A later page on an existing query. v5 no longer forwards an explicit page\n // param, so fetch it directly and merge it into the infinite cache,\n // appending the next page or prepending an earlier one.\n const { pages, pageParams } = query.state.data;\n const page = (await this.#policy.execute(() =>\n options.queryFn({\n client: this.#queryClient,\n queryKey: options.queryKey,\n signal: new AbortController().signal,\n pageParam: requestedPageParam,\n direction: 'forward',\n meta: options.meta,\n }),\n )) as TData;\n const nextPageParam = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n this.#queryClient.setQueryData<InfiniteData<TData, TPageParam>>(\n options.queryKey,\n deepEqual(requestedPageParam, nextPageParam)\n ? {\n pages: [...pages, page],\n pageParams: [...pageParams, requestedPageParam],\n }\n : {\n pages: [page, ...pages],\n pageParams: [requestedPageParam, ...pageParams],\n },\n );\n\n return page;\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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/base-data-service",
3
- "version": "0.1.3-preview-d21e2aaf9",
3
+ "version": "0.1.3-preview-6426280bb",
4
4
  "description": "Provides utilities for building data services",
5
5
  "keywords": [
6
6
  "Ethereum",