@metamask-previews/base-data-service 0.1.3-preview-1203ebcfc → 0.1.3-preview-72f0609be
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +0 -2
- package/dist/BaseDataService.cjs +6 -76
- package/dist/BaseDataService.cjs.map +1 -1
- package/dist/BaseDataService.d.cts +1 -26
- package/dist/BaseDataService.d.cts.map +1 -1
- package/dist/BaseDataService.d.mts +1 -26
- package/dist/BaseDataService.d.mts.map +1 -1
- package/dist/BaseDataService.mjs +6 -77
- package/dist/BaseDataService.mjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -7
package/CHANGELOG.md
CHANGED
|
@@ -9,8 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
### Added
|
|
11
11
|
|
|
12
|
-
- Add support for cache persistence ([#9445](https://github.com/MetaMask/core/pull/9445))
|
|
13
|
-
- Persistence can be configured by passing a `persistenceConfig` option to the constructor.
|
|
14
12
|
- Add `createServicePolicy` and related symbols, copied from `@metamask/controller-utils` ([#9418](https://github.com/MetaMask/core/pull/9418))
|
|
15
13
|
- Added functions:
|
|
16
14
|
`createServicePolicy`
|
package/dist/BaseDataService.cjs
CHANGED
|
@@ -13,14 +13,13 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
13
13
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
14
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
15
|
};
|
|
16
|
-
var _BaseDataService_instances, _BaseDataService_messenger,
|
|
16
|
+
var _BaseDataService_instances, _BaseDataService_messenger, _BaseDataService_policy, _BaseDataService_queryClient, _BaseDataService_queryCacheUnsubscribe, _BaseDataService_publishCacheUpdate;
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
-
exports.BaseDataService =
|
|
18
|
+
exports.BaseDataService = void 0;
|
|
19
19
|
const messenger_1 = require("@metamask/messenger");
|
|
20
20
|
const utils_1 = require("@metamask/utils");
|
|
21
21
|
const query_core_1 = require("@tanstack/query-core");
|
|
22
22
|
const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
|
|
23
|
-
const lodash_1 = require("lodash");
|
|
24
23
|
const createServicePolicy_1 = require("./createServicePolicy.cjs");
|
|
25
24
|
// Defaults to apply to all data service queries if no default option specified
|
|
26
25
|
const QUERY_CLIENT_DEFAULTS = {
|
|
@@ -29,24 +28,17 @@ const QUERY_CLIENT_DEFAULTS = {
|
|
|
29
28
|
staleTime: (0, utils_1.inMilliseconds)(1, utils_1.Duration.Minute),
|
|
30
29
|
},
|
|
31
30
|
};
|
|
32
|
-
exports.STORAGE_SERVICE_KEY = 'cache';
|
|
33
31
|
class BaseDataService {
|
|
34
|
-
constructor({ name, messenger, queryClientConfig = {}, policyOptions,
|
|
32
|
+
constructor({ name, messenger, queryClientConfig = {}, policyOptions, }) {
|
|
35
33
|
_BaseDataService_instances.add(this);
|
|
36
34
|
_BaseDataService_messenger.set(this, void 0);
|
|
37
|
-
_BaseDataService_externalMessenger.set(this, void 0);
|
|
38
35
|
_BaseDataService_policy.set(this, void 0);
|
|
39
36
|
_BaseDataService_queryClient.set(this, void 0);
|
|
40
37
|
_BaseDataService_queryCacheUnsubscribe.set(this, void 0);
|
|
41
|
-
_BaseDataService_debouncedPersist.set(this, void 0);
|
|
42
|
-
_BaseDataService_persistenceConfig.set(this, void 0);
|
|
43
38
|
this.name = name;
|
|
44
|
-
// We
|
|
45
|
-
//
|
|
46
|
-
// - #externalMessenger handles calls to external actions
|
|
47
|
-
// Splitting them avoids TypeScript issues with mixing template-literals with regular strings
|
|
39
|
+
// We are storing a separately typed messenger for known actions and events provided by data services
|
|
40
|
+
// and a generic public one that is typed using the generic parameters and accessible to implementations.
|
|
48
41
|
__classPrivateFieldSet(this, _BaseDataService_messenger, messenger, "f");
|
|
49
|
-
__classPrivateFieldSet(this, _BaseDataService_externalMessenger, messenger, "f");
|
|
50
42
|
this.messenger = messenger;
|
|
51
43
|
__classPrivateFieldSet(this, _BaseDataService_queryClient, new query_core_1.QueryClient({
|
|
52
44
|
...queryClientConfig,
|
|
@@ -58,24 +50,12 @@ class BaseDataService {
|
|
|
58
50
|
mutations: queryClientConfig.defaultOptions?.mutations,
|
|
59
51
|
},
|
|
60
52
|
}), "f");
|
|
61
|
-
__classPrivateFieldSet(this, _BaseDataService_persistenceConfig, persistenceConfig, "f");
|
|
62
53
|
__classPrivateFieldSet(this, _BaseDataService_policy, (0, createServicePolicy_1.createServicePolicy)(policyOptions), "f");
|
|
63
|
-
__classPrivateFieldSet(this, _BaseDataService_debouncedPersist, __classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f") &&
|
|
64
|
-
(0, lodash_1.debounce)(() => {
|
|
65
|
-
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_persistCache).call(this).catch(
|
|
66
|
-
/* istanbul ignore next */
|
|
67
|
-
(error) => __classPrivateFieldGet(this, _BaseDataService_messenger, "f").captureException?.(error));
|
|
68
|
-
}, __classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f").writeDelay ??
|
|
69
|
-
(0, utils_1.inMilliseconds)(10, utils_1.Duration.Second), {
|
|
70
|
-
maxWait: __classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f").maxWriteDelay ??
|
|
71
|
-
(0, utils_1.inMilliseconds)(1, utils_1.Duration.Minute),
|
|
72
|
-
}), "f");
|
|
73
54
|
__classPrivateFieldSet(this, _BaseDataService_queryCacheUnsubscribe, __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
|
|
74
55
|
.getQueryCache()
|
|
75
56
|
.subscribe((event) => {
|
|
76
57
|
if (['added', 'updated', 'removed'].includes(event.type)) {
|
|
77
58
|
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this, event.query.queryHash, event.type);
|
|
78
|
-
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.call(this);
|
|
79
59
|
}
|
|
80
60
|
}), "f");
|
|
81
61
|
__classPrivateFieldGet(this, _BaseDataService_messenger, "f").registerActionHandler(`${this.name}:invalidateQueries`, this.invalidateQueries.bind(this));
|
|
@@ -140,20 +120,11 @@ class BaseDataService {
|
|
|
140
120
|
async invalidateQueries(filters, options) {
|
|
141
121
|
return __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").invalidateQueries(filters, options);
|
|
142
122
|
}
|
|
143
|
-
/**
|
|
144
|
-
* Initialize the service, rehydrating the cache with persisted data if possible.
|
|
145
|
-
*/
|
|
146
|
-
init() {
|
|
147
|
-
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_loadCache).call(this).catch(
|
|
148
|
-
/* istanbul ignore next */
|
|
149
|
-
(error) => __classPrivateFieldGet(this, _BaseDataService_messenger, "f").captureException?.(error));
|
|
150
|
-
}
|
|
151
123
|
/**
|
|
152
124
|
* Prepares the service for garbage collection. This should be extended
|
|
153
125
|
* by any subclasses to clean up any additional connections or events.
|
|
154
126
|
*/
|
|
155
127
|
destroy() {
|
|
156
|
-
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.cancel();
|
|
157
128
|
__classPrivateFieldGet(this, _BaseDataService_queryCacheUnsubscribe, "f").call(this);
|
|
158
129
|
__classPrivateFieldGet(this, _BaseDataService_queryClient, "f").clear();
|
|
159
130
|
this.messenger.clearSubscriptions();
|
|
@@ -161,7 +132,7 @@ class BaseDataService {
|
|
|
161
132
|
}
|
|
162
133
|
}
|
|
163
134
|
exports.BaseDataService = BaseDataService;
|
|
164
|
-
_BaseDataService_messenger = new WeakMap(),
|
|
135
|
+
_BaseDataService_messenger = new WeakMap(), _BaseDataService_policy = new WeakMap(), _BaseDataService_queryClient = new WeakMap(), _BaseDataService_queryCacheUnsubscribe = new WeakMap(), _BaseDataService_instances = new WeakSet(), _BaseDataService_publishCacheUpdate = function _BaseDataService_publishCacheUpdate(hash, type) {
|
|
165
136
|
const state = type === 'added' || type === 'updated'
|
|
166
137
|
? (0, query_core_1.dehydrate)(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
|
|
167
138
|
shouldDehydrateQuery: (query) => query.queryHash === hash,
|
|
@@ -176,46 +147,5 @@ _BaseDataService_messenger = new WeakMap(), _BaseDataService_externalMessenger =
|
|
|
176
147
|
type,
|
|
177
148
|
state,
|
|
178
149
|
});
|
|
179
|
-
}, _BaseDataService_persistCache =
|
|
180
|
-
/**
|
|
181
|
-
* Persist the query client cache using the StorageService, if the cache is not empty.
|
|
182
|
-
*
|
|
183
|
-
* @returns Nothing.
|
|
184
|
-
*/
|
|
185
|
-
async function _BaseDataService_persistCache() {
|
|
186
|
-
const state = (0, query_core_1.dehydrate)(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
|
|
187
|
-
// This is the default, but we specify it to be explicit.
|
|
188
|
-
shouldDehydrateQuery: (query) => query.state.status === 'success',
|
|
189
|
-
});
|
|
190
|
-
if (state.queries.length === 0 && state.mutations.length === 0) {
|
|
191
|
-
await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:removeItem', this.name, exports.STORAGE_SERVICE_KEY);
|
|
192
|
-
return;
|
|
193
|
-
}
|
|
194
|
-
const cache = {
|
|
195
|
-
timestamp: Date.now(),
|
|
196
|
-
state,
|
|
197
|
-
};
|
|
198
|
-
await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:setItem', this.name, exports.STORAGE_SERVICE_KEY, cache);
|
|
199
|
-
}, _BaseDataService_loadCache =
|
|
200
|
-
/**
|
|
201
|
-
* Load the query client cache from the StorageService, if persistence is configured
|
|
202
|
-
* and the persisted cache is not expired.
|
|
203
|
-
*
|
|
204
|
-
* @returns Nothing.
|
|
205
|
-
*/
|
|
206
|
-
async function _BaseDataService_loadCache() {
|
|
207
|
-
if (!__classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f")) {
|
|
208
|
-
return;
|
|
209
|
-
}
|
|
210
|
-
const { result: untypedCache } = await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:getItem', this.name, exports.STORAGE_SERVICE_KEY);
|
|
211
|
-
if (!untypedCache) {
|
|
212
|
-
return;
|
|
213
|
-
}
|
|
214
|
-
const cache = untypedCache;
|
|
215
|
-
if (Date.now() - cache.timestamp >= __classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f").maxAge) {
|
|
216
|
-
await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:removeItem', this.name, exports.STORAGE_SERVICE_KEY);
|
|
217
|
-
return;
|
|
218
|
-
}
|
|
219
|
-
(0, query_core_1.hydrate)(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), cache.state);
|
|
220
150
|
};
|
|
221
151
|
//# sourceMappingURL=BaseDataService.cjs.map
|
|
@@ -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,mEAI+B;AAiD/B,+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;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AC1C,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';\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\ntype 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\ntype 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<TPageData extends Json>(\n filters?: InvalidateQueryFilters<TPageData>,\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;AAC7B,2CAA2D;AAE3D,qDAa8B;AAC9B,sEAAwC;AAExC,mEAI+B;AA4C/B,+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;AAEF,MAAa,eAAe;IA4B1B,YAAY,EACV,IAAI,EACJ,SAAS,EACT,iBAAiB,GAAG,EAAE,EACtB,aAAa,GAMd;;QAxBQ,6CAIP;QAIO,0CAAuB;QAEvB,+CAA0B;QAE1B,yDAAmC;QAa1C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,qGAAqG;QACrG,yGAAyG;QACzG,uBAAA,IAAI,8BAAc,SAIjB,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,qBA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,KAAK,CAAC,iBAAiB,CACrB,OAA2C,EAC3C,OAA2B;QAE3B,OAAO,uBAAA,IAAI,oCAAa,CAAC,iBAAiB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC/D,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,uBAAA,IAAI,8CAAuB,MAA3B,IAAI,CAAyB,CAAC;QAC9B,uBAAA,IAAI,oCAAa,CAAC,KAAK,EAAE,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,kBAAkB,EAAE,CAAC;QACpC,IAAI,CAAC,SAAS,CAAC,YAAY,EAAE,CAAC;IAChC,CAAC;CAiCF;AAtOD,0CAsOC;0TAzBqB,IAAY,EAAE,IAAsB;IACtD,MAAM,KAAK,GACT,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,SAAS;QACpC,CAAC,CAAC,IAAA,sBAAS,EAAC,uBAAA,IAAI,oCAAa,EAAE;YAC3B,oBAAoB,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,KAAK,IAAI;SAC1D,CAAC;QACJ,CAAC,CAAC,IAAI,CAAC;IAEX,uBAAA,IAAI,kCAAW,CAAC,OAAO,CACrB,GAAG,IAAI,CAAC,IAAI,eAAwB,EACpC;QACE,IAAI;QACJ,IAAI;QACJ,KAAK;KAC4B,CACpC,CAAC;IAEF,uBAAA,IAAI,kCAAW,CAAC,OAAO,CACrB,GAAG,IAAI,CAAC,IAAI,iBAAiB,IAAI,EAAW,EAC5C;QACE,IAAI;QACJ,KAAK;KACoC,CAC5C,CAAC;AACJ,CAAC","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n} from '@metamask/messenger';\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} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy';\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\ntype DataServiceActions<ServiceName extends string> =\n DataServiceInvalidateQueriesAction<ServiceName>;\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\ntype 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 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 protected messenger: ServiceMessenger;\n\n readonly #policy: ServicePolicy;\n\n readonly #queryClient: QueryClient;\n\n readonly #queryCacheUnsubscribe: () => void;\n\n constructor({\n name,\n messenger,\n queryClientConfig = {},\n policyOptions,\n }: {\n name: ServiceName;\n messenger: ServiceMessenger;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n }) {\n this.name = name;\n\n // We are storing a separately typed messenger for known actions and events provided by data services\n // and a generic public one that is typed using the generic parameters and accessible to implementations.\n this.#messenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\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.#policy = createServicePolicy(policyOptions);\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 });\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<TPageData extends Json>(\n filters?: InvalidateQueryFilters<TPageData>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\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.#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"]}
|
|
@@ -25,36 +25,15 @@ export type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {
|
|
|
25
25
|
type: `${ServiceName}:cacheUpdated:${string}`;
|
|
26
26
|
payload: [DataServiceGranularCacheUpdatedPayload];
|
|
27
27
|
};
|
|
28
|
-
export declare const STORAGE_SERVICE_KEY = "cache";
|
|
29
|
-
/**
|
|
30
|
-
* Options for persistence configuration.
|
|
31
|
-
*/
|
|
32
|
-
export type PersistenceConfiguration = {
|
|
33
|
-
/**
|
|
34
|
-
* The maximum age before the cache is treated as expired in milliseconds.
|
|
35
|
-
* This is relevant for rehydrating the state during initialization,
|
|
36
|
-
* if the cached state is too old it will be discarded.
|
|
37
|
-
*/
|
|
38
|
-
maxAge: number;
|
|
39
|
-
/**
|
|
40
|
-
* The number of milliseconds to wait before triggering persistence following a cache update.
|
|
41
|
-
*/
|
|
42
|
-
writeDelay?: number;
|
|
43
|
-
/**
|
|
44
|
-
* The maximum number of milliseconds to wait between persistence writes.
|
|
45
|
-
*/
|
|
46
|
-
maxWriteDelay?: number;
|
|
47
|
-
};
|
|
48
28
|
export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends Messenger<ServiceName, ActionConstraint, EventConstraint, any>> {
|
|
49
29
|
#private;
|
|
50
30
|
readonly name: ServiceName;
|
|
51
31
|
protected messenger: ServiceMessenger;
|
|
52
|
-
constructor({ name, messenger, queryClientConfig, policyOptions,
|
|
32
|
+
constructor({ name, messenger, queryClientConfig, policyOptions, }: {
|
|
53
33
|
name: ServiceName;
|
|
54
34
|
messenger: ServiceMessenger;
|
|
55
35
|
queryClientConfig?: QueryClientConfig;
|
|
56
36
|
policyOptions?: CreateServicePolicyOptions;
|
|
57
|
-
persistenceConfig?: PersistenceConfiguration;
|
|
58
37
|
});
|
|
59
38
|
/**
|
|
60
39
|
* Fetch a query.
|
|
@@ -81,10 +60,6 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
81
60
|
* @returns Nothing.
|
|
82
61
|
*/
|
|
83
62
|
invalidateQueries<TPageData extends Json>(filters?: InvalidateQueryFilters<TPageData>, options?: InvalidateOptions): Promise<void>;
|
|
84
|
-
/**
|
|
85
|
-
* Initialize the service, rehydrating the cache with persisted data if possible.
|
|
86
|
-
*/
|
|
87
|
-
init(): void;
|
|
88
63
|
/**
|
|
89
64
|
* Prepares the service for garbage collection. This should be extended
|
|
90
65
|
* by any subclasses to clean up any additional connections or events.
|
|
@@ -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;
|
|
1
|
+
{"version":3,"file":"BaseDataService.d.cts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAE7B,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAC5C,OAAO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AGG;IACH,OAAO,IAAI,IAAI;CAsChB"}
|
|
@@ -25,36 +25,15 @@ export type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {
|
|
|
25
25
|
type: `${ServiceName}:cacheUpdated:${string}`;
|
|
26
26
|
payload: [DataServiceGranularCacheUpdatedPayload];
|
|
27
27
|
};
|
|
28
|
-
export declare const STORAGE_SERVICE_KEY = "cache";
|
|
29
|
-
/**
|
|
30
|
-
* Options for persistence configuration.
|
|
31
|
-
*/
|
|
32
|
-
export type PersistenceConfiguration = {
|
|
33
|
-
/**
|
|
34
|
-
* The maximum age before the cache is treated as expired in milliseconds.
|
|
35
|
-
* This is relevant for rehydrating the state during initialization,
|
|
36
|
-
* if the cached state is too old it will be discarded.
|
|
37
|
-
*/
|
|
38
|
-
maxAge: number;
|
|
39
|
-
/**
|
|
40
|
-
* The number of milliseconds to wait before triggering persistence following a cache update.
|
|
41
|
-
*/
|
|
42
|
-
writeDelay?: number;
|
|
43
|
-
/**
|
|
44
|
-
* The maximum number of milliseconds to wait between persistence writes.
|
|
45
|
-
*/
|
|
46
|
-
maxWriteDelay?: number;
|
|
47
|
-
};
|
|
48
28
|
export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends Messenger<ServiceName, ActionConstraint, EventConstraint, any>> {
|
|
49
29
|
#private;
|
|
50
30
|
readonly name: ServiceName;
|
|
51
31
|
protected messenger: ServiceMessenger;
|
|
52
|
-
constructor({ name, messenger, queryClientConfig, policyOptions,
|
|
32
|
+
constructor({ name, messenger, queryClientConfig, policyOptions, }: {
|
|
53
33
|
name: ServiceName;
|
|
54
34
|
messenger: ServiceMessenger;
|
|
55
35
|
queryClientConfig?: QueryClientConfig;
|
|
56
36
|
policyOptions?: CreateServicePolicyOptions;
|
|
57
|
-
persistenceConfig?: PersistenceConfiguration;
|
|
58
37
|
});
|
|
59
38
|
/**
|
|
60
39
|
* Fetch a query.
|
|
@@ -81,10 +60,6 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
81
60
|
* @returns Nothing.
|
|
82
61
|
*/
|
|
83
62
|
invalidateQueries<TPageData extends Json>(filters?: InvalidateQueryFilters<TPageData>, options?: InvalidateOptions): Promise<void>;
|
|
84
|
-
/**
|
|
85
|
-
* Initialize the service, rehydrating the cache with persisted data if possible.
|
|
86
|
-
*/
|
|
87
|
-
init(): void;
|
|
88
63
|
/**
|
|
89
64
|
* Prepares the service for garbage collection. This should be extended
|
|
90
65
|
* by any subclasses to clean up any additional connections or events.
|
|
@@ -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;
|
|
1
|
+
{"version":3,"file":"BaseDataService.d.mts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAE7B,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAC5C,OAAO,EAEL,eAAe,EACf,yBAAyB,EACzB,iBAAiB,EAEjB,iBAAiB,EACjB,sBAAsB,EACtB,SAAS,EAET,iBAAiB,EACjB,YAAY,EAEb,6BAA6B;AAG9B,OAAO,EAEL,0BAA0B,EAE3B,kCAA8B;AAG/B,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,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AAO,GAAG,YAAY,CACvB,EACD,UAAU,GAAG,SAAS,CACvB,GACA,OAAO,CAAC,KAAK,CAAC;IAQjB;;;;;;;OAOG;cACa,kBAAkB,CAChC,YAAY,SAAS,IAAI,EACzB,MAAM,GAAG,OAAO,EAChB,KAAK,SAAS,YAAY,GAAG,YAAY,EACzC,SAAS,SAAS,QAAQ,GAAG,QAAQ,EACrC,UAAU,SAAS,IAAI,GAAG,IAAI,EAE9B,OAAO,EAAE,YAAY,CACnB,SAAS,CACP,yBAAyB,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,EACjE,OAAO,GAAG,YAAY,CACvB,EACD,UAAU,GAAG,SAAS,CACvB,EACD,SAAS,CAAC,EAAE,UAAU,GACrB,OAAO,CAAC,KAAK,CAAC;IA2CjB;;;;;;OAMG;IACG,iBAAiB,CAAC,SAAS,SAAS,IAAI,EAC5C,OAAO,CAAC,EAAE,sBAAsB,CAAC,SAAS,CAAC,EAC3C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,IAAI,CAAC;IAIhB;;;OAGG;IACH,OAAO,IAAI,IAAI;CAsChB"}
|
package/dist/BaseDataService.mjs
CHANGED
|
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _BaseDataService_instances, _BaseDataService_messenger,
|
|
12
|
+
var _BaseDataService_instances, _BaseDataService_messenger, _BaseDataService_policy, _BaseDataService_queryClient, _BaseDataService_queryCacheUnsubscribe, _BaseDataService_publishCacheUpdate;
|
|
13
13
|
function $importDefault(module) {
|
|
14
14
|
if (module?.__esModule) {
|
|
15
15
|
return module.default;
|
|
@@ -18,11 +18,9 @@ function $importDefault(module) {
|
|
|
18
18
|
}
|
|
19
19
|
import { Messenger } from "@metamask/messenger";
|
|
20
20
|
import { Duration, inMilliseconds } from "@metamask/utils";
|
|
21
|
-
import { QueryClient, dehydrate
|
|
21
|
+
import { QueryClient, dehydrate } from "@tanstack/query-core";
|
|
22
22
|
import $deepEqual from "fast-deep-equal";
|
|
23
23
|
const deepEqual = $importDefault($deepEqual);
|
|
24
|
-
import $lodash from "lodash";
|
|
25
|
-
const { debounce } = $lodash;
|
|
26
24
|
import { createServicePolicy } from "./createServicePolicy.mjs";
|
|
27
25
|
// Defaults to apply to all data service queries if no default option specified
|
|
28
26
|
const QUERY_CLIENT_DEFAULTS = {
|
|
@@ -31,24 +29,17 @@ const QUERY_CLIENT_DEFAULTS = {
|
|
|
31
29
|
staleTime: inMilliseconds(1, Duration.Minute),
|
|
32
30
|
},
|
|
33
31
|
};
|
|
34
|
-
export const STORAGE_SERVICE_KEY = 'cache';
|
|
35
32
|
export class BaseDataService {
|
|
36
|
-
constructor({ name, messenger, queryClientConfig = {}, policyOptions,
|
|
33
|
+
constructor({ name, messenger, queryClientConfig = {}, policyOptions, }) {
|
|
37
34
|
_BaseDataService_instances.add(this);
|
|
38
35
|
_BaseDataService_messenger.set(this, void 0);
|
|
39
|
-
_BaseDataService_externalMessenger.set(this, void 0);
|
|
40
36
|
_BaseDataService_policy.set(this, void 0);
|
|
41
37
|
_BaseDataService_queryClient.set(this, void 0);
|
|
42
38
|
_BaseDataService_queryCacheUnsubscribe.set(this, void 0);
|
|
43
|
-
_BaseDataService_debouncedPersist.set(this, void 0);
|
|
44
|
-
_BaseDataService_persistenceConfig.set(this, void 0);
|
|
45
39
|
this.name = name;
|
|
46
|
-
// We
|
|
47
|
-
//
|
|
48
|
-
// - #externalMessenger handles calls to external actions
|
|
49
|
-
// Splitting them avoids TypeScript issues with mixing template-literals with regular strings
|
|
40
|
+
// We are storing a separately typed messenger for known actions and events provided by data services
|
|
41
|
+
// and a generic public one that is typed using the generic parameters and accessible to implementations.
|
|
50
42
|
__classPrivateFieldSet(this, _BaseDataService_messenger, messenger, "f");
|
|
51
|
-
__classPrivateFieldSet(this, _BaseDataService_externalMessenger, messenger, "f");
|
|
52
43
|
this.messenger = messenger;
|
|
53
44
|
__classPrivateFieldSet(this, _BaseDataService_queryClient, new QueryClient({
|
|
54
45
|
...queryClientConfig,
|
|
@@ -60,24 +51,12 @@ export class BaseDataService {
|
|
|
60
51
|
mutations: queryClientConfig.defaultOptions?.mutations,
|
|
61
52
|
},
|
|
62
53
|
}), "f");
|
|
63
|
-
__classPrivateFieldSet(this, _BaseDataService_persistenceConfig, persistenceConfig, "f");
|
|
64
54
|
__classPrivateFieldSet(this, _BaseDataService_policy, createServicePolicy(policyOptions), "f");
|
|
65
|
-
__classPrivateFieldSet(this, _BaseDataService_debouncedPersist, __classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f") &&
|
|
66
|
-
debounce(() => {
|
|
67
|
-
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_persistCache).call(this).catch(
|
|
68
|
-
/* istanbul ignore next */
|
|
69
|
-
(error) => __classPrivateFieldGet(this, _BaseDataService_messenger, "f").captureException?.(error));
|
|
70
|
-
}, __classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f").writeDelay ??
|
|
71
|
-
inMilliseconds(10, Duration.Second), {
|
|
72
|
-
maxWait: __classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f").maxWriteDelay ??
|
|
73
|
-
inMilliseconds(1, Duration.Minute),
|
|
74
|
-
}), "f");
|
|
75
55
|
__classPrivateFieldSet(this, _BaseDataService_queryCacheUnsubscribe, __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
|
|
76
56
|
.getQueryCache()
|
|
77
57
|
.subscribe((event) => {
|
|
78
58
|
if (['added', 'updated', 'removed'].includes(event.type)) {
|
|
79
59
|
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this, event.query.queryHash, event.type);
|
|
80
|
-
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.call(this);
|
|
81
60
|
}
|
|
82
61
|
}), "f");
|
|
83
62
|
__classPrivateFieldGet(this, _BaseDataService_messenger, "f").registerActionHandler(`${this.name}:invalidateQueries`, this.invalidateQueries.bind(this));
|
|
@@ -142,27 +121,18 @@ export class BaseDataService {
|
|
|
142
121
|
async invalidateQueries(filters, options) {
|
|
143
122
|
return __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").invalidateQueries(filters, options);
|
|
144
123
|
}
|
|
145
|
-
/**
|
|
146
|
-
* Initialize the service, rehydrating the cache with persisted data if possible.
|
|
147
|
-
*/
|
|
148
|
-
init() {
|
|
149
|
-
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_loadCache).call(this).catch(
|
|
150
|
-
/* istanbul ignore next */
|
|
151
|
-
(error) => __classPrivateFieldGet(this, _BaseDataService_messenger, "f").captureException?.(error));
|
|
152
|
-
}
|
|
153
124
|
/**
|
|
154
125
|
* Prepares the service for garbage collection. This should be extended
|
|
155
126
|
* by any subclasses to clean up any additional connections or events.
|
|
156
127
|
*/
|
|
157
128
|
destroy() {
|
|
158
|
-
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.cancel();
|
|
159
129
|
__classPrivateFieldGet(this, _BaseDataService_queryCacheUnsubscribe, "f").call(this);
|
|
160
130
|
__classPrivateFieldGet(this, _BaseDataService_queryClient, "f").clear();
|
|
161
131
|
this.messenger.clearSubscriptions();
|
|
162
132
|
this.messenger.clearActions();
|
|
163
133
|
}
|
|
164
134
|
}
|
|
165
|
-
_BaseDataService_messenger = new WeakMap(),
|
|
135
|
+
_BaseDataService_messenger = new WeakMap(), _BaseDataService_policy = new WeakMap(), _BaseDataService_queryClient = new WeakMap(), _BaseDataService_queryCacheUnsubscribe = new WeakMap(), _BaseDataService_instances = new WeakSet(), _BaseDataService_publishCacheUpdate = function _BaseDataService_publishCacheUpdate(hash, type) {
|
|
166
136
|
const state = type === 'added' || type === 'updated'
|
|
167
137
|
? dehydrate(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
|
|
168
138
|
shouldDehydrateQuery: (query) => query.queryHash === hash,
|
|
@@ -177,46 +147,5 @@ _BaseDataService_messenger = new WeakMap(), _BaseDataService_externalMessenger =
|
|
|
177
147
|
type,
|
|
178
148
|
state,
|
|
179
149
|
});
|
|
180
|
-
}, _BaseDataService_persistCache =
|
|
181
|
-
/**
|
|
182
|
-
* Persist the query client cache using the StorageService, if the cache is not empty.
|
|
183
|
-
*
|
|
184
|
-
* @returns Nothing.
|
|
185
|
-
*/
|
|
186
|
-
async function _BaseDataService_persistCache() {
|
|
187
|
-
const state = dehydrate(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
|
|
188
|
-
// This is the default, but we specify it to be explicit.
|
|
189
|
-
shouldDehydrateQuery: (query) => query.state.status === 'success',
|
|
190
|
-
});
|
|
191
|
-
if (state.queries.length === 0 && state.mutations.length === 0) {
|
|
192
|
-
await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:removeItem', this.name, STORAGE_SERVICE_KEY);
|
|
193
|
-
return;
|
|
194
|
-
}
|
|
195
|
-
const cache = {
|
|
196
|
-
timestamp: Date.now(),
|
|
197
|
-
state,
|
|
198
|
-
};
|
|
199
|
-
await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:setItem', this.name, STORAGE_SERVICE_KEY, cache);
|
|
200
|
-
}, _BaseDataService_loadCache =
|
|
201
|
-
/**
|
|
202
|
-
* Load the query client cache from the StorageService, if persistence is configured
|
|
203
|
-
* and the persisted cache is not expired.
|
|
204
|
-
*
|
|
205
|
-
* @returns Nothing.
|
|
206
|
-
*/
|
|
207
|
-
async function _BaseDataService_loadCache() {
|
|
208
|
-
if (!__classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f")) {
|
|
209
|
-
return;
|
|
210
|
-
}
|
|
211
|
-
const { result: untypedCache } = await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:getItem', this.name, STORAGE_SERVICE_KEY);
|
|
212
|
-
if (!untypedCache) {
|
|
213
|
-
return;
|
|
214
|
-
}
|
|
215
|
-
const cache = untypedCache;
|
|
216
|
-
if (Date.now() - cache.timestamp >= __classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f").maxAge) {
|
|
217
|
-
await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:removeItem', this.name, STORAGE_SERVICE_KEY);
|
|
218
|
-
return;
|
|
219
|
-
}
|
|
220
|
-
hydrate(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), cache.state);
|
|
221
150
|
};
|
|
222
151
|
//# sourceMappingURL=BaseDataService.mjs.map
|
|
@@ -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,EASL,WAAW,EAGX,SAAS,EACT,OAAO,EACR,6BAA6B;AAC9B,OAAO,UAAS,wBAAwB;;;;AAGxC,OAAO,EACL,mBAAmB,EAGpB,kCAA8B;AAiD/B,+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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AAC,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/D,MAAM,uBAAA,IAAI,0CAAmB,CAAC,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} 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';\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\ntype 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\ntype 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<TPageData extends Json>(\n filters?: InvalidateQueryFilters<TPageData>,\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;AAC7B,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,wBAAwB;AAE3D,OAAO,EASL,WAAW,EAGX,SAAS,EACV,6BAA6B;AAC9B,OAAO,UAAS,wBAAwB;;AAExC,OAAO,EACL,mBAAmB,EAGpB,kCAA8B;AA4C/B,+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,OAAO,eAAe;IA4B1B,YAAY,EACV,IAAI,EACJ,SAAS,EACT,iBAAiB,GAAG,EAAE,EACtB,aAAa,GAMd;;QAxBQ,6CAIP;QAIO,0CAAuB;QAEvB,+CAA0B;QAE1B,yDAAmC;QAa1C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,qGAAqG;QACrG,yGAAyG;QACzG,uBAAA,IAAI,8BAAc,SAIjB,MAAA,CAAC;QACF,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAE3B,uBAAA,IAAI,gCAAgB,IAAI,WAAW,CAAC;YAClC,GAAG,iBAAiB;YACpB,cAAc,EAAE;gBACd,OAAO,EAAE;oBACP,GAAG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AAiB,CACrB,OAA2C,EAC3C,OAA2B;QAE3B,OAAO,uBAAA,IAAI,oCAAa,CAAC,iBAAiB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC/D,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,uBAAA,IAAI,8CAAuB,MAA3B,IAAI,CAAyB,CAAC;QAC9B,uBAAA,IAAI,oCAAa,CAAC,KAAK,EAAE,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,kBAAkB,EAAE,CAAC;QACpC,IAAI,CAAC,SAAS,CAAC,YAAY,EAAE,CAAC;IAChC,CAAC;CAiCF;0TAzBqB,IAAY,EAAE,IAAsB;IACtD,MAAM,KAAK,GACT,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,SAAS;QACpC,CAAC,CAAC,SAAS,CAAC,uBAAA,IAAI,oCAAa,EAAE;YAC3B,oBAAoB,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,KAAK,IAAI;SAC1D,CAAC;QACJ,CAAC,CAAC,IAAI,CAAC;IAEX,uBAAA,IAAI,kCAAW,CAAC,OAAO,CACrB,GAAG,IAAI,CAAC,IAAI,eAAwB,EACpC;QACE,IAAI;QACJ,IAAI;QACJ,KAAK;KAC4B,CACpC,CAAC;IAEF,uBAAA,IAAI,kCAAW,CAAC,OAAO,CACrB,GAAG,IAAI,CAAC,IAAI,iBAAiB,IAAI,EAAW,EAC5C;QACE,IAAI;QACJ,KAAK;KACoC,CAC5C,CAAC;AACJ,CAAC","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n} from '@metamask/messenger';\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} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy';\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\ntype DataServiceActions<ServiceName extends string> =\n DataServiceInvalidateQueriesAction<ServiceName>;\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\ntype 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 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 protected messenger: ServiceMessenger;\n\n readonly #policy: ServicePolicy;\n\n readonly #queryClient: QueryClient;\n\n readonly #queryCacheUnsubscribe: () => void;\n\n constructor({\n name,\n messenger,\n queryClientConfig = {},\n policyOptions,\n }: {\n name: ServiceName;\n messenger: ServiceMessenger;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n }) {\n this.name = name;\n\n // We are storing a separately typed messenger for known actions and events provided by data services\n // and a generic public one that is typed using the generic parameters and accessible to implementations.\n this.#messenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\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.#policy = createServicePolicy(policyOptions);\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 });\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<TPageData extends Json>(\n filters?: InvalidateQueryFilters<TPageData>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\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.#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"]}
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAKA,uCAQmB;AAPjB,+GAAA,kBAAkB,OAAA;AAClB,kHAAA,YAAY,OAAyB;AACrC,yGAAA,YAAY,OAAA;AACZ,4GAAA,eAAe,OAAA;AACf,+GAAA,kBAAkB,OAAA;AAClB,sGAAA,SAAS,OAAA;AACT,uGAAA,UAAU,OAAA;
|
|
1
|
+
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAKA,uCAQmB;AAPjB,+GAAA,kBAAkB,OAAA;AAClB,kHAAA,YAAY,OAAyB;AACrC,yGAAA,YAAY,OAAA;AACZ,4GAAA,eAAe,OAAA;AACf,+GAAA,kBAAkB,OAAA;AAClB,sGAAA,SAAS,OAAA;AACT,uGAAA,UAAU,OAAA;AAWZ,yDAAoD;AAA3C,kHAAA,eAAe,OAAA;AAExB,iEAM+B;AAL7B,qIAAA,8BAA8B,OAAA;AAC9B,iIAAA,0BAA0B,OAAA;AAC1B,uIAAA,gCAAgC,OAAA;AAChC,0HAAA,mBAAmB,OAAA;AACnB,0HAAA,mBAAmB,OAAA","sourcesContent":["export type {\n Event as CockatielEvent,\n FailureReason as CockatielFailureReason,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n EventEmitter as CockatielEventEmitter,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n} from 'cockatiel';\n\nexport type {\n DataServiceCacheUpdatedPayload,\n DataServiceGranularCacheUpdatedPayload,\n DataServiceInvalidateQueriesAction,\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n QueryKey,\n} from './BaseDataService';\nexport { BaseDataService } from './BaseDataService';\n\nexport {\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n createServicePolicy,\n} from './createServicePolicy';\nexport type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy';\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export type { Event as CockatielEvent, FailureReason as CockatielFailureReason, } from "cockatiel";
|
|
2
2
|
export { BrokenCircuitError, EventEmitter as CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, } from "cockatiel";
|
|
3
|
-
export type { DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey,
|
|
3
|
+
export type { DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey, } from "./BaseDataService.cjs";
|
|
4
4
|
export { BaseDataService } from "./BaseDataService.cjs";
|
|
5
5
|
export { DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, createServicePolicy, } from "./createServicePolicy.cjs";
|
|
6
6
|
export type { CreateServicePolicyOptions, ServicePolicy, } from "./createServicePolicy.cjs";
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,kBAAkB;AAEnB,YAAY,EACV,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,
|
|
1
|
+
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,kBAAkB;AAEnB,YAAY,EACV,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,GACT,8BAA0B;AAC3B,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAEpD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,GACpB,kCAA8B;AAC/B,YAAY,EACV,0BAA0B,EAC1B,aAAa,GACd,kCAA8B"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export type { Event as CockatielEvent, FailureReason as CockatielFailureReason, } from "cockatiel";
|
|
2
2
|
export { BrokenCircuitError, EventEmitter as CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, } from "cockatiel";
|
|
3
|
-
export type { DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey,
|
|
3
|
+
export type { DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey, } from "./BaseDataService.mjs";
|
|
4
4
|
export { BaseDataService } from "./BaseDataService.mjs";
|
|
5
5
|
export { DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, createServicePolicy, } from "./createServicePolicy.mjs";
|
|
6
6
|
export type { CreateServicePolicyOptions, ServicePolicy, } from "./createServicePolicy.mjs";
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,kBAAkB;AAEnB,YAAY,EACV,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,
|
|
1
|
+
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,kBAAkB;AAEnB,YAAY,EACV,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,GACT,8BAA0B;AAC3B,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAEpD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,GACpB,kCAA8B;AAC/B,YAAY,EACV,0BAA0B,EAC1B,aAAa,GACd,kCAA8B"}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,EACX,kBAAkB;
|
|
1
|
+
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,EACX,kBAAkB;AAUnB,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAEpD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,EACpB,kCAA8B","sourcesContent":["export type {\n Event as CockatielEvent,\n FailureReason as CockatielFailureReason,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n EventEmitter as CockatielEventEmitter,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n} from 'cockatiel';\n\nexport type {\n DataServiceCacheUpdatedPayload,\n DataServiceGranularCacheUpdatedPayload,\n DataServiceInvalidateQueriesAction,\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n QueryKey,\n} from './BaseDataService';\nexport { BaseDataService } from './BaseDataService';\n\nexport {\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n createServicePolicy,\n} from './createServicePolicy';\nexport type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy';\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-
|
|
3
|
+
"version": "0.1.3-preview-72f0609be",
|
|
4
4
|
"description": "Provides utilities for building data services",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -44,8 +44,6 @@
|
|
|
44
44
|
"build:docs": "typedoc",
|
|
45
45
|
"changelog:update": "../../scripts/update-changelog.sh @metamask/base-data-service",
|
|
46
46
|
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/base-data-service",
|
|
47
|
-
"lint:tsconfigs": "tsx ../../scripts/lint-tsconfigs/lint-tsconfigs.mts",
|
|
48
|
-
"lint:tsconfigs:fix": "tsx ../../scripts/lint-tsconfigs/lint-tsconfigs.mts --fix",
|
|
49
47
|
"messenger-action-types:check": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --check",
|
|
50
48
|
"messenger-action-types:generate": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --generate",
|
|
51
49
|
"publish:preview": "yarn npm publish --tag preview",
|
|
@@ -57,18 +55,15 @@
|
|
|
57
55
|
},
|
|
58
56
|
"dependencies": {
|
|
59
57
|
"@metamask/messenger": "^2.0.0",
|
|
60
|
-
"@metamask/storage-service": "^1.0.2",
|
|
61
58
|
"@metamask/utils": "^11.11.0",
|
|
62
59
|
"@tanstack/query-core": "^4.43.0",
|
|
63
60
|
"cockatiel": "^3.1.2",
|
|
64
|
-
"fast-deep-equal": "^3.1.3"
|
|
65
|
-
"lodash": "^4.17.21"
|
|
61
|
+
"fast-deep-equal": "^3.1.3"
|
|
66
62
|
},
|
|
67
63
|
"devDependencies": {
|
|
68
64
|
"@metamask/auto-changelog": "^6.1.0",
|
|
69
65
|
"@ts-bridge/cli": "^0.6.4",
|
|
70
66
|
"@types/jest": "^29.5.14",
|
|
71
|
-
"@types/lodash": "^4.14.191",
|
|
72
67
|
"deepmerge": "^4.2.2",
|
|
73
68
|
"jest": "^29.7.0",
|
|
74
69
|
"nock": "^13.3.1",
|