@metamask-previews/base-data-service 1.0.0-preview-4f4c98e → 1.0.0-preview-eb263b0ee

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +0 -1
  2. package/dist/BaseDataService.cjs +225 -0
  3. package/dist/BaseDataService.cjs.map +1 -0
  4. package/dist/{BaseDataService.d.ts → BaseDataService.d.cts} +7 -7
  5. package/dist/BaseDataService.d.cts.map +1 -0
  6. package/dist/BaseDataService.d.mts +115 -0
  7. package/dist/BaseDataService.d.mts.map +1 -0
  8. package/dist/{BaseDataService.js → BaseDataService.mjs} +17 -7
  9. package/dist/BaseDataService.mjs.map +1 -0
  10. package/dist/createServicePolicy.cjs +228 -0
  11. package/dist/createServicePolicy.cjs.map +1 -0
  12. package/dist/{createServicePolicy.d.ts → createServicePolicy.d.cts} +3 -3
  13. package/dist/createServicePolicy.d.cts.map +1 -0
  14. package/dist/createServicePolicy.d.mts +179 -0
  15. package/dist/createServicePolicy.d.mts.map +1 -0
  16. package/dist/{createServicePolicy.js → createServicePolicy.mjs} +2 -2
  17. package/dist/createServicePolicy.mjs.map +1 -0
  18. package/dist/index.cjs +20 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/{index.d.ts → index.d.cts} +7 -7
  21. package/dist/index.d.cts.map +1 -0
  22. package/dist/index.d.mts +7 -0
  23. package/dist/index.d.mts.map +1 -0
  24. package/dist/{index.js → index.mjs} +4 -4
  25. package/dist/index.mjs.map +1 -0
  26. package/dist/utils.cjs +25 -0
  27. package/dist/utils.cjs.map +1 -0
  28. package/dist/{utils.d.ts → utils.d.cts} +3 -3
  29. package/dist/utils.d.cts.map +1 -0
  30. package/dist/utils.d.mts +13 -0
  31. package/dist/utils.d.mts.map +1 -0
  32. package/dist/{utils.js → utils.mjs} +2 -2
  33. package/dist/utils.mjs.map +1 -0
  34. package/package.json +18 -14
  35. package/dist/BaseDataService.d.ts.map +0 -1
  36. package/dist/BaseDataService.js.map +0 -1
  37. package/dist/createServicePolicy.d.ts.map +0 -1
  38. package/dist/createServicePolicy.js.map +0 -1
  39. package/dist/index.d.ts.map +0 -1
  40. package/dist/index.js.map +0 -1
  41. package/dist/utils.d.ts.map +0 -1
  42. package/dist/utils.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -40,7 +40,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
40
40
 
41
41
  ### Changed
42
42
 
43
- - **BREAKING:** Bump minimum Node.js version to 22 ([#9168](https://github.com/MetaMask/core/pull/9168))
44
43
  - **BREAKING:** Remove `TPageData` type parameter from `invalidateQueries` method ([#9526](https://github.com/MetaMask/core/pull/9526))
45
44
  - This is technically a breaking change, but this was not used in any of our codebases
46
45
  - **BREAKING:** Bump `@tanstack/query-core` from `^4.43.0` to `^5.62.16` ([#9712](https://github.com/MetaMask/core/pull/9712))
@@ -0,0 +1,225 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ 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");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ var _BaseDataService_instances, _BaseDataService_messenger, _BaseDataService_externalMessenger, _BaseDataService_policy, _BaseDataService_queryClient, _BaseDataService_queryCacheUnsubscribe, _BaseDataService_debouncedPersist, _BaseDataService_persistenceConfig, _BaseDataService_publishCacheUpdate, _BaseDataService_persistCache, _BaseDataService_loadCache;
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.BaseDataService = exports.STORAGE_SERVICE_KEY = void 0;
19
+ const messenger_1 = require("@metamask/messenger");
20
+ const superstruct_1 = require("@metamask/superstruct");
21
+ const utils_1 = require("@metamask/utils");
22
+ const query_core_1 = require("@tanstack/query-core");
23
+ const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
24
+ const lodash_1 = require("lodash");
25
+ const createServicePolicy_js_1 = require("./createServicePolicy.cjs");
26
+ const utils_js_1 = require("./utils.cjs");
27
+ // Defaults to apply to all data service queries if no default option specified
28
+ const QUERY_CLIENT_DEFAULTS = {
29
+ queries: {
30
+ retry: false,
31
+ staleTime: (0, utils_1.inMilliseconds)(1, utils_1.Duration.Minute),
32
+ },
33
+ };
34
+ exports.STORAGE_SERVICE_KEY = 'cache';
35
+ class BaseDataService {
36
+ constructor({ name, messenger, queryClientConfig = {}, policyOptions, persistenceConfig, }) {
37
+ _BaseDataService_instances.add(this);
38
+ _BaseDataService_messenger.set(this, void 0);
39
+ _BaseDataService_externalMessenger.set(this, void 0);
40
+ _BaseDataService_policy.set(this, void 0);
41
+ _BaseDataService_queryClient.set(this, void 0);
42
+ _BaseDataService_queryCacheUnsubscribe.set(this, void 0);
43
+ _BaseDataService_debouncedPersist.set(this, void 0);
44
+ _BaseDataService_persistenceConfig.set(this, void 0);
45
+ this.name = name;
46
+ // We store two narrowly-typed messengers alongside the generic public one:
47
+ // - #messenger handles the service's own action registration and event publishing
48
+ // - #externalMessenger handles calls to external actions
49
+ // Splitting them avoids TypeScript issues with mixing template-literals with regular strings
50
+ __classPrivateFieldSet(this, _BaseDataService_messenger, messenger, "f");
51
+ __classPrivateFieldSet(this, _BaseDataService_externalMessenger, messenger, "f");
52
+ this.messenger = messenger;
53
+ __classPrivateFieldSet(this, _BaseDataService_queryClient, new query_core_1.QueryClient({
54
+ ...queryClientConfig,
55
+ defaultOptions: {
56
+ queries: {
57
+ ...QUERY_CLIENT_DEFAULTS.queries,
58
+ ...queryClientConfig.defaultOptions?.queries,
59
+ },
60
+ mutations: queryClientConfig.defaultOptions?.mutations,
61
+ },
62
+ }), "f");
63
+ __classPrivateFieldSet(this, _BaseDataService_persistenceConfig, persistenceConfig, "f");
64
+ __classPrivateFieldSet(this, _BaseDataService_policy, (0, createServicePolicy_js_1.createServicePolicy)(policyOptions), "f");
65
+ __classPrivateFieldSet(this, _BaseDataService_debouncedPersist, __classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f") &&
66
+ (0, lodash_1.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
+ (0, utils_1.inMilliseconds)(10, utils_1.Duration.Second), {
72
+ maxWait: __classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f").maxWriteDelay ??
73
+ (0, utils_1.inMilliseconds)(1, utils_1.Duration.Minute),
74
+ }), "f");
75
+ __classPrivateFieldSet(this, _BaseDataService_queryCacheUnsubscribe, __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
76
+ .getQueryCache()
77
+ .subscribe((event) => {
78
+ if (['added', 'updated', 'removed'].includes(event.type)) {
79
+ __classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this, event.query.queryHash, event.type);
80
+ __classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.call(this);
81
+ }
82
+ }), "f");
83
+ __classPrivateFieldGet(this, _BaseDataService_messenger, "f").registerActionHandler(`${this.name}:invalidateQueries`, this.invalidateQueries.bind(this));
84
+ }
85
+ /**
86
+ * Fetch a query.
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`.
90
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
91
+ * @returns The query results.
92
+ */
93
+ async fetchQuery({ responseStruct, ...options }) {
94
+ return __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchQuery({
95
+ ...options,
96
+ queryFn: async (context) => {
97
+ const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn(context));
98
+ return (0, utils_js_1.processQueryResponse)(options.queryKey, response, responseStruct);
99
+ },
100
+ });
101
+ }
102
+ /**
103
+ * Fetch a paginated query.
104
+ *
105
+ * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
106
+ * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
107
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
108
+ * @param pageParam - An optional page parameter.
109
+ * @returns The query result, exclusively the requested page is returned.
110
+ */
111
+ async fetchInfiniteQuery({ responseStruct, ...options }, pageParam) {
112
+ const cache = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").getQueryCache();
113
+ const query = cache.find({
114
+ queryKey: options.queryKey,
115
+ });
116
+ if (!query?.state.data || !pageParam) {
117
+ const result = await __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchInfiniteQuery({
118
+ ...options,
119
+ initialPageParam: pageParam ?? options.initialPageParam,
120
+ queryFn: async (context) => {
121
+ const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(async () => options.queryFn({
122
+ ...context,
123
+ pageParam: context.meta?.pageParam ?? context.pageParam,
124
+ }));
125
+ return (0, utils_js_1.processQueryResponse)(options.queryKey, response, responseStruct);
126
+ },
127
+ });
128
+ return result.pages[0];
129
+ }
130
+ const { pages, pageParams } = query.state.data;
131
+ const next = options.getNextPageParam(pages[pages.length - 1], pages, pageParams[pageParams.length - 1], pageParams);
132
+ const direction = (0, fast_deep_equal_1.default)(pageParam, next) ? 'forward' : 'backward';
133
+ const result = await query.fetch({ ...query.options, meta: { pageParam } }, { meta: { fetchMore: { direction } } });
134
+ const pageIndex = result.pageParams.findIndex((param) => (0, fast_deep_equal_1.default)(param, pageParam));
135
+ return result.pages[pageIndex];
136
+ }
137
+ /**
138
+ * Invalidate queries serviced by this data service.
139
+ *
140
+ * @param filters - Optional filter for selecting specific queries.
141
+ * @param options - Additional optional options for query invalidations.
142
+ * @returns Nothing.
143
+ */
144
+ async invalidateQueries(filters, options) {
145
+ return __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").invalidateQueries(filters, options);
146
+ }
147
+ /**
148
+ * Initialize the service, rehydrating the cache with persisted data if possible.
149
+ */
150
+ init() {
151
+ __classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_loadCache).call(this).catch(
152
+ /* istanbul ignore next */
153
+ (error) => __classPrivateFieldGet(this, _BaseDataService_messenger, "f").captureException?.(error));
154
+ }
155
+ /**
156
+ * Prepares the service for garbage collection. This should be extended
157
+ * by any subclasses to clean up any additional connections or events.
158
+ */
159
+ destroy() {
160
+ __classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.cancel();
161
+ __classPrivateFieldGet(this, _BaseDataService_queryCacheUnsubscribe, "f").call(this);
162
+ __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").clear();
163
+ this.messenger.clearSubscriptions();
164
+ this.messenger.clearActions();
165
+ }
166
+ }
167
+ exports.BaseDataService = BaseDataService;
168
+ _BaseDataService_messenger = new WeakMap(), _BaseDataService_externalMessenger = new WeakMap(), _BaseDataService_policy = new WeakMap(), _BaseDataService_queryClient = new WeakMap(), _BaseDataService_queryCacheUnsubscribe = new WeakMap(), _BaseDataService_debouncedPersist = new WeakMap(), _BaseDataService_persistenceConfig = new WeakMap(), _BaseDataService_instances = new WeakSet(), _BaseDataService_publishCacheUpdate = function _BaseDataService_publishCacheUpdate(hash, type) {
169
+ const state = type === 'added' || type === 'updated'
170
+ ? (0, query_core_1.dehydrate)(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
171
+ shouldDehydrateQuery: (query) => query.queryHash === hash,
172
+ })
173
+ : null;
174
+ __classPrivateFieldGet(this, _BaseDataService_messenger, "f").publish(`${this.name}:cacheUpdated`, {
175
+ type,
176
+ hash,
177
+ state,
178
+ });
179
+ __classPrivateFieldGet(this, _BaseDataService_messenger, "f").publish(`${this.name}:cacheUpdated:${hash}`, {
180
+ type,
181
+ state,
182
+ });
183
+ }, _BaseDataService_persistCache =
184
+ /**
185
+ * Persist the query client cache using the StorageService, if the cache is not empty.
186
+ *
187
+ * @returns Nothing.
188
+ */
189
+ async function _BaseDataService_persistCache() {
190
+ const state = (0, query_core_1.dehydrate)(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
191
+ // This is the default, but we specify it to be explicit.
192
+ shouldDehydrateQuery: (query) => query.state.status === 'success',
193
+ });
194
+ if (state.queries.length === 0 && state.mutations.length === 0) {
195
+ await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:removeItem', this.name, exports.STORAGE_SERVICE_KEY);
196
+ return;
197
+ }
198
+ const cache = {
199
+ timestamp: Date.now(),
200
+ state,
201
+ };
202
+ await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:setItem', this.name, exports.STORAGE_SERVICE_KEY, cache);
203
+ }, _BaseDataService_loadCache =
204
+ /**
205
+ * Load the query client cache from the StorageService, if persistence is configured
206
+ * and the persisted cache is not expired.
207
+ *
208
+ * @returns Nothing.
209
+ */
210
+ async function _BaseDataService_loadCache() {
211
+ if (!__classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f")) {
212
+ return;
213
+ }
214
+ const { result: untypedCache } = await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:getItem', this.name, exports.STORAGE_SERVICE_KEY);
215
+ if (!untypedCache) {
216
+ return;
217
+ }
218
+ const cache = untypedCache;
219
+ if (Date.now() - cache.timestamp >= __classPrivateFieldGet(this, _BaseDataService_persistenceConfig, "f").maxAge) {
220
+ await __classPrivateFieldGet(this, _BaseDataService_externalMessenger, "f").call('StorageService:removeItem', this.name, exports.STORAGE_SERVICE_KEY);
221
+ return;
222
+ }
223
+ (0, query_core_1.hydrate)(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), cache.state);
224
+ };
225
+ //# sourceMappingURL=BaseDataService.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseDataService.cjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,mDAM6B;AAM7B,uDAA+C;AAC/C,2CAA2D;AAE3D,qDAgB8B;AAC9B,sEAAwC;AACxC,mCAAiD;AAEjD,sEAIkC;AAClC,0CAAkD;AAiElD,+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,GAalB;;QAzCQ,6CAIP;QAEO,qDAGP;QAIO,0CAAuB;QAEvB,+CAA0B;QAE1B,yDAAmC;QAEnC,oDAA8C;QAE9C,qDAA8C;QAqBrD,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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G,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,0CAAmB,CAAC,MAAM,EAAE,CAAC;QACnE,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,2BAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,IAAA,oBAAO,EAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n MessengerActions,\n MessengerEvents,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\nimport { Struct } from '@metamask/superstruct';\nimport { Duration, inMilliseconds } from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport {\n DefaultError,\n DefaultOptions,\n DehydratedState,\n FetchQueryOptions,\n InfiniteData,\n InfiniteQueryPageParamsOptions,\n InvalidateOptions,\n InvalidateQueryFilters,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\n QueryFunction,\n WithRequired,\n dehydrate,\n hydrate,\n} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\nimport { debounce, DebouncedFunc } from 'lodash';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\nimport { processQueryResponse } from './utils.js';\n\n// Data service queries use the following format: ['ServiceActionName', ...params]\nexport type QueryKey = [string, ...Json[]];\n\n/**\n * The supertype of all messengers, scoped to a namespace.\n *\n * @template Namespace - The namespace for the messenger's own actions and\n * events.\n */\nexport type BaseMessenger<Namespace extends string> = Messenger<\n Namespace,\n ActionConstraint,\n EventConstraint,\n // Use `any` to allow any parent to be set. `any` is harmless in a type constraint anyway,\n // it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\nexport type DataServiceGranularCacheUpdatedPayload =\n | { type: 'added' | 'updated'; state: DehydratedState }\n | {\n type: 'removed';\n state: null;\n };\n\nexport type DataServiceCacheUpdatedPayload =\n DataServiceGranularCacheUpdatedPayload & {\n hash: string;\n };\n\ntype CacheUpdatedType = DataServiceCacheUpdatedPayload['type'];\n\nexport type DataServiceInvalidateQueriesAction<ServiceName extends string> = {\n type: `${ServiceName}:invalidateQueries`;\n handler: BaseDataService<\n ServiceName,\n BaseMessenger<ServiceName>\n >['invalidateQueries'];\n};\n\nexport type DataServiceActions<ServiceName extends string> =\n DataServiceInvalidateQueriesAction<ServiceName>;\n\ntype DataServiceAllowedActions =\n | StorageServiceGetItemAction\n | StorageServiceSetItemAction\n | StorageServiceRemoveItemAction;\n\nexport type DataServiceCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated`;\n payload: [DataServiceCacheUpdatedPayload];\n};\n\nexport type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated:${string}`;\n payload: [DataServiceGranularCacheUpdatedPayload];\n};\n\nexport type DataServiceEvents<ServiceName extends string> =\n | DataServiceCacheUpdatedEvent<ServiceName>\n | DataServiceGranularCacheUpdatedEvent<ServiceName>;\n\n// Defaults to apply to all data service queries if no default option specified\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\n },\n};\n\nexport const STORAGE_SERVICE_KEY = 'cache';\n\n/**\n * Options for persistence configuration.\n */\nexport type PersistenceConfiguration = {\n /**\n * The maximum age before the cache is treated as expired in milliseconds.\n * This is relevant for rehydrating the state during initialization,\n * if the cached state is too old it will be discarded.\n */\n maxAge: number;\n /**\n * The number of milliseconds to wait before triggering persistence following a cache update.\n */\n writeDelay?: number;\n /**\n * The maximum number of milliseconds to wait between persistence writes.\n */\n maxWriteDelay?: number;\n};\n\ntype PersistedCache = {\n state: DehydratedState;\n timestamp: number;\n};\n\nexport class BaseDataService<\n ServiceName extends string,\n ServiceMessenger extends BaseMessenger<ServiceName>,\n> {\n public readonly name: ServiceName;\n\n readonly #messenger: Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n\n readonly #externalMessenger: Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n\n protected messenger: ServiceMessenger;\n\n readonly #policy: ServicePolicy;\n\n readonly #queryClient: QueryClient;\n\n readonly #queryCacheUnsubscribe: () => void;\n\n readonly #debouncedPersist?: DebouncedFunc<() => void>;\n\n readonly #persistenceConfig?: PersistenceConfiguration;\n\n constructor({\n name,\n messenger,\n queryClientConfig = {},\n policyOptions,\n persistenceConfig,\n }: {\n name: ServiceName;\n messenger: DataServiceActions<ServiceName>['type'] extends\n | MessengerActions<ServiceMessenger>['type']\n | DataServiceAllowedActions['type']\n ? DataServiceEvents<ServiceName>['type'] extends MessengerEvents<ServiceMessenger>['type']\n ? ServiceMessenger\n : never\n : never;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n persistenceConfig?: PersistenceConfiguration;\n }) {\n this.name = name;\n\n // We store two narrowly-typed messengers alongside the generic public one:\n // - #messenger handles the service's own action registration and event publishing\n // - #externalMessenger handles calls to external actions\n // Splitting them avoids TypeScript issues with mixing template-literals with regular strings\n this.#messenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n this.#externalMessenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n this.messenger = messenger;\n\n this.#queryClient = new QueryClient({\n ...queryClientConfig,\n defaultOptions: {\n queries: {\n ...QUERY_CLIENT_DEFAULTS.queries,\n ...queryClientConfig.defaultOptions?.queries,\n },\n mutations: queryClientConfig.defaultOptions?.mutations,\n },\n });\n\n this.#persistenceConfig = persistenceConfig;\n\n this.#policy = createServicePolicy(policyOptions);\n\n this.#debouncedPersist =\n this.#persistenceConfig &&\n debounce(\n () => {\n this.#persistCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n },\n this.#persistenceConfig.writeDelay ??\n inMilliseconds(10, Duration.Second),\n {\n maxWait:\n this.#persistenceConfig.maxWriteDelay ??\n inMilliseconds(1, Duration.Minute),\n },\n );\n\n this.#queryCacheUnsubscribe = this.#queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (['added', 'updated', 'removed'].includes(event.type)) {\n this.#publishCacheUpdate(\n event.query.queryHash,\n event.type as CacheUpdatedType,\n );\n\n this.#debouncedPersist?.();\n }\n });\n\n this.#messenger.registerActionHandler(\n `${this.name}:invalidateQueries`,\n this.invalidateQueries.bind(this),\n );\n }\n\n /**\n * Fetch a query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >({\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey>;\n responseStruct?: TDataStruct;\n }): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: async (context) => {\n const response = await this.#policy.execute(() =>\n options.queryFn(context),\n );\n return processQueryResponse(options.queryKey, response, responseStruct);\n },\n });\n }\n\n /**\n * Fetch a paginated query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @param pageParam - An optional page parameter.\n * @returns The query result, exclusively the requested page is returned.\n */\n protected async fetchInfiniteQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData extends TQueryFnData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n {\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>,\n TQueryKey,\n TPageParam\n >,\n 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'\n >,\n 'queryKey'\n > &\n InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;\n responseStruct?: TDataStruct;\n },\n pageParam?: TPageParam,\n ): Promise<TData> {\n const cache = this.#queryClient.getQueryCache();\n\n const query = cache.find<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>\n >({\n queryKey: options.queryKey,\n });\n\n if (!query?.state.data || !pageParam) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: pageParam ?? options.initialPageParam,\n queryFn: async (context) => {\n const response = await this.#policy.execute(async () =>\n options.queryFn({\n ...context,\n pageParam: context.meta?.pageParam ?? context.pageParam,\n }),\n );\n return processQueryResponse(\n options.queryKey,\n response,\n responseStruct,\n );\n },\n });\n\n return result.pages[0];\n }\n\n const { pages, pageParams } = query.state.data;\n const next = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n\n const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';\n\n const result = await query.fetch(\n { ...query.options, meta: { pageParam } },\n { meta: { fetchMore: { direction } } },\n );\n\n const pageIndex = result.pageParams.findIndex((param) =>\n deepEqual(param, pageParam),\n );\n\n return result.pages[pageIndex];\n }\n\n /**\n * Invalidate queries serviced by this data service.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @param options - Additional optional options for query invalidations.\n * @returns Nothing.\n */\n async invalidateQueries(\n filters?: InvalidateQueryFilters<QueryKey>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\n }\n\n /**\n * Initialize the service, rehydrating the cache with persisted data if possible.\n */\n init(): void {\n this.#loadCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n }\n\n /**\n * Prepares the service for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n */\n destroy(): void {\n this.#debouncedPersist?.cancel();\n this.#queryCacheUnsubscribe();\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when a given query changes.\n *\n * @param hash The hash of the query.\n * @param type The type of cache update.\n */\n #publishCacheUpdate(hash: string, type: CacheUpdatedType): void {\n const state =\n type === 'added' || type === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) => query.queryHash === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type,\n state,\n } as DataServiceGranularCacheUpdatedPayload,\n );\n }\n\n /**\n * Persist the query client cache using the StorageService, if the cache is not empty.\n *\n * @returns Nothing.\n */\n async #persistCache(): Promise<void> {\n const state = dehydrate(this.#queryClient, {\n // This is the default, but we specify it to be explicit.\n shouldDehydrateQuery: (query) => query.state.status === 'success',\n });\n\n if (state.queries.length === 0 && state.mutations.length === 0) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n const cache: PersistedCache = {\n timestamp: Date.now(),\n state,\n };\n\n await this.#externalMessenger.call(\n 'StorageService:setItem',\n this.name,\n STORAGE_SERVICE_KEY,\n cache as unknown as Json,\n );\n }\n\n /**\n * Load the query client cache from the StorageService, if persistence is configured\n * and the persisted cache is not expired.\n *\n * @returns Nothing.\n */\n async #loadCache(): Promise<void> {\n if (!this.#persistenceConfig) {\n return;\n }\n\n const { result: untypedCache } = await this.#externalMessenger.call(\n 'StorageService:getItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n\n if (!untypedCache) {\n return;\n }\n\n const cache = untypedCache as unknown as PersistedCache;\n\n if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n hydrate(this.#queryClient, cache.state);\n }\n}\n"]}
@@ -1,9 +1,9 @@
1
- import { Messenger, ActionConstraint, EventConstraint, MessengerActions, MessengerEvents } from '@metamask/messenger';
2
- import type { StorageServiceGetItemAction, StorageServiceRemoveItemAction, StorageServiceSetItemAction } from '@metamask/storage-service';
3
- import { Struct } from '@metamask/superstruct';
4
- import type { Json } from '@metamask/utils';
5
- import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from '@tanstack/query-core';
6
- import { CreateServicePolicyOptions } from './createServicePolicy.js';
1
+ import { Messenger, ActionConstraint, EventConstraint, MessengerActions, MessengerEvents } from "@metamask/messenger";
2
+ import type { StorageServiceGetItemAction, StorageServiceRemoveItemAction, StorageServiceSetItemAction } from "@metamask/storage-service";
3
+ import { Struct } from "@metamask/superstruct";
4
+ import type { Json } from "@metamask/utils";
5
+ import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from "@tanstack/query-core";
6
+ import { CreateServicePolicyOptions } from "./createServicePolicy.cjs";
7
7
  export type QueryKey = [string, ...Json[]];
8
8
  /**
9
9
  * The supertype of all messengers, scoped to a namespace.
@@ -112,4 +112,4 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
112
112
  destroy(): void;
113
113
  }
114
114
  export {};
115
- //# sourceMappingURL=BaseDataService.d.ts.map
115
+ //# sourceMappingURL=BaseDataService.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseDataService.d.cts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAC7B,OAAO,KAAK,EACV,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC5B,kCAAkC;AACnC,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAE/C,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;AAIlC,MAAM,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;AAE3C;;;;;GAKG;AACH,MAAM,MAAM,aAAa,CAAC,SAAS,SAAS,MAAM,IAAI,SAAS,CAC7D,SAAS,EACT,gBAAgB,EAChB,eAAe,EAIf,GAAG,CACJ,CAAC;AAEF,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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IAAI,EACzB,MAAM,GAAG,YAAY,EACrB,WAAW,SAAS,MAAM,CAAC,YAAY,CAAC,GAAG,SAAS,GAAG,SAAS,EAChE,KAAK,SAAS,YAAY,GAAG,WAAW,SAAS,MAAM,CAAC,MAAM,UAAU,CAAC,GACrE,UAAU,GACV,YAAY,EAChB,SAAS,SAAS,QAAQ,GAAG,QAAQ,EACrC,UAAU,SAAS,IAAI,GAAG,IAAI,EAE9B,EACE,cAAc,EACd,GAAG,OAAO,EACX,EAAE,YAAY,CACb,SAAS,CACP,iBAAiB,CACf,YAAY,EACZ,MAAM,EACN,YAAY,CAAC,KAAK,EAAE,UAAU,CAAC,EAC/B,SAAS,EACT,UAAU,CACX,EACD,OAAO,GAAG,YAAY,GAAG,SAAS,GAAG,kBAAkB,CACxD,EACD,UAAU,CACX,GACC,8BAA8B,CAAC,YAAY,EAAE,UAAU,CAAC,GAAG;QACzD,OAAO,EAAE,aAAa,CAAC,YAAY,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC;QAC5D,cAAc,CAAC,EAAE,WAAW,CAAC;KAC9B,EACH,SAAS,CAAC,EAAE,UAAU,GACrB,OAAO,CAAC,KAAK,CAAC;IAuDjB;;;;;;OAMG;IACG,iBAAiB,CACrB,OAAO,CAAC,EAAE,sBAAsB,CAAC,QAAQ,CAAC,EAC1C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,IAAI,CAAC;IAIhB;;OAEG;IACH,IAAI,IAAI,IAAI;IAOZ;;;OAGG;IACH,OAAO,IAAI,IAAI;CA2GhB"}
@@ -0,0 +1,115 @@
1
+ import { Messenger, ActionConstraint, EventConstraint, MessengerActions, MessengerEvents } from "@metamask/messenger";
2
+ import type { StorageServiceGetItemAction, StorageServiceRemoveItemAction, StorageServiceSetItemAction } from "@metamask/storage-service";
3
+ import { Struct } from "@metamask/superstruct";
4
+ import type { Json } from "@metamask/utils";
5
+ import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from "@tanstack/query-core";
6
+ import { CreateServicePolicyOptions } from "./createServicePolicy.mjs";
7
+ export type QueryKey = [string, ...Json[]];
8
+ /**
9
+ * The supertype of all messengers, scoped to a namespace.
10
+ *
11
+ * @template Namespace - The namespace for the messenger's own actions and
12
+ * events.
13
+ */
14
+ export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
15
+ export type DataServiceGranularCacheUpdatedPayload = {
16
+ type: 'added' | 'updated';
17
+ state: DehydratedState;
18
+ } | {
19
+ type: 'removed';
20
+ state: null;
21
+ };
22
+ export type DataServiceCacheUpdatedPayload = DataServiceGranularCacheUpdatedPayload & {
23
+ hash: string;
24
+ };
25
+ export type DataServiceInvalidateQueriesAction<ServiceName extends string> = {
26
+ type: `${ServiceName}:invalidateQueries`;
27
+ handler: BaseDataService<ServiceName, BaseMessenger<ServiceName>>['invalidateQueries'];
28
+ };
29
+ export type DataServiceActions<ServiceName extends string> = DataServiceInvalidateQueriesAction<ServiceName>;
30
+ type DataServiceAllowedActions = StorageServiceGetItemAction | StorageServiceSetItemAction | StorageServiceRemoveItemAction;
31
+ export type DataServiceCacheUpdatedEvent<ServiceName extends string> = {
32
+ type: `${ServiceName}:cacheUpdated`;
33
+ payload: [DataServiceCacheUpdatedPayload];
34
+ };
35
+ export type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {
36
+ type: `${ServiceName}:cacheUpdated:${string}`;
37
+ payload: [DataServiceGranularCacheUpdatedPayload];
38
+ };
39
+ export type DataServiceEvents<ServiceName extends string> = DataServiceCacheUpdatedEvent<ServiceName> | DataServiceGranularCacheUpdatedEvent<ServiceName>;
40
+ export declare const STORAGE_SERVICE_KEY = "cache";
41
+ /**
42
+ * Options for persistence configuration.
43
+ */
44
+ export type PersistenceConfiguration = {
45
+ /**
46
+ * The maximum age before the cache is treated as expired in milliseconds.
47
+ * This is relevant for rehydrating the state during initialization,
48
+ * if the cached state is too old it will be discarded.
49
+ */
50
+ maxAge: number;
51
+ /**
52
+ * The number of milliseconds to wait before triggering persistence following a cache update.
53
+ */
54
+ writeDelay?: number;
55
+ /**
56
+ * The maximum number of milliseconds to wait between persistence writes.
57
+ */
58
+ maxWriteDelay?: number;
59
+ };
60
+ export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends BaseMessenger<ServiceName>> {
61
+ #private;
62
+ readonly name: ServiceName;
63
+ protected messenger: ServiceMessenger;
64
+ constructor({ name, messenger, queryClientConfig, policyOptions, persistenceConfig, }: {
65
+ name: ServiceName;
66
+ messenger: DataServiceActions<ServiceName>['type'] extends MessengerActions<ServiceMessenger>['type'] | DataServiceAllowedActions['type'] ? DataServiceEvents<ServiceName>['type'] extends MessengerEvents<ServiceMessenger>['type'] ? ServiceMessenger : never : never;
67
+ queryClientConfig?: QueryClientConfig;
68
+ policyOptions?: CreateServicePolicyOptions;
69
+ persistenceConfig?: PersistenceConfiguration;
70
+ });
71
+ /**
72
+ * Fetch a query.
73
+ *
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`.
76
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
77
+ * @returns The query results.
78
+ */
79
+ protected fetchQuery<TQueryFnData extends Json, TError = DefaultError, TDataStruct extends Struct<TQueryFnData> | undefined = undefined, TData = TDataStruct extends Struct<infer StructType> ? StructType : TQueryFnData, TQueryKey extends QueryKey = QueryKey>({ responseStruct, ...options }: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay' | 'queryFn'>, 'queryKey'> & {
80
+ queryFn: QueryFunction<TQueryFnData, TQueryKey>;
81
+ responseStruct?: TDataStruct;
82
+ }): Promise<TData>;
83
+ /**
84
+ * Fetch a paginated query.
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`.
88
+ * @param options.responseStruct - An optional struct for validating the response of the query function.
89
+ * @param pageParam - An optional page parameter.
90
+ * @returns The query result, exclusively the requested page is returned.
91
+ */
92
+ protected fetchInfiniteQuery<TQueryFnData extends Json, TError = DefaultError, TDataStruct extends Struct<TQueryFnData> | undefined = undefined, TData extends TQueryFnData = TDataStruct extends Struct<infer StructType> ? StructType : TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam extends Json = Json>({ responseStruct, ...options }: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, InfiniteData<TData, TPageParam>, TQueryKey, TPageParam>, 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'>, 'queryKey'> & InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {
93
+ queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
94
+ responseStruct?: TDataStruct;
95
+ }, pageParam?: TPageParam): Promise<TData>;
96
+ /**
97
+ * Invalidate queries serviced by this data service.
98
+ *
99
+ * @param filters - Optional filter for selecting specific queries.
100
+ * @param options - Additional optional options for query invalidations.
101
+ * @returns Nothing.
102
+ */
103
+ invalidateQueries(filters?: InvalidateQueryFilters<QueryKey>, options?: InvalidateOptions): Promise<void>;
104
+ /**
105
+ * Initialize the service, rehydrating the cache with persisted data if possible.
106
+ */
107
+ init(): void;
108
+ /**
109
+ * Prepares the service for garbage collection. This should be extended
110
+ * by any subclasses to clean up any additional connections or events.
111
+ */
112
+ destroy(): void;
113
+ }
114
+ export {};
115
+ //# sourceMappingURL=BaseDataService.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseDataService.d.mts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAC7B,OAA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EACT,UAAU,CACX,EACD,OAAO,GAAG,YAAY,GAAG,SAAS,GAAG,kBAAkB,CACxD,EACD,UAAU,CACX,GACC,8BAA8B,CAAC,YAAY,EAAE,UAAU,CAAC,GAAG;QACzD,OAAO,EAAE,aAAa,CAAC,YAAY,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC;QAC5D,cAAc,CAAC,EAAE,WAAW,CAAC;KAC9B,EACH,SAAS,CAAC,EAAE,UAAU,GACrB,OAAO,CAAC,KAAK,CAAC;IAuDjB;;;;;;OAMG;IACG,iBAAiB,CACrB,OAAO,CAAC,EAAE,sBAAsB,CAAC,QAAQ,CAAC,EAC1C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,IAAI,CAAC;IAIhB;;OAEG;IACH,IAAI,IAAI,IAAI;IAOZ;;;OAGG;IACH,OAAO,IAAI,IAAI;CA2GhB"}
@@ -10,12 +10,22 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
12
  var _BaseDataService_instances, _BaseDataService_messenger, _BaseDataService_externalMessenger, _BaseDataService_policy, _BaseDataService_queryClient, _BaseDataService_queryCacheUnsubscribe, _BaseDataService_debouncedPersist, _BaseDataService_persistenceConfig, _BaseDataService_publishCacheUpdate, _BaseDataService_persistCache, _BaseDataService_loadCache;
13
- import { Duration, inMilliseconds } from '@metamask/utils';
14
- import { QueryClient, dehydrate, hydrate, } from '@tanstack/query-core';
15
- import deepEqual from 'fast-deep-equal';
16
- import { debounce } from 'lodash-es';
17
- import { createServicePolicy, } from './createServicePolicy.js';
18
- import { processQueryResponse } from './utils.js';
13
+ function $importDefault(module) {
14
+ if (module?.__esModule) {
15
+ return module.default;
16
+ }
17
+ return module;
18
+ }
19
+ import { Messenger } from "@metamask/messenger";
20
+ import { Struct } from "@metamask/superstruct";
21
+ import { Duration, inMilliseconds } from "@metamask/utils";
22
+ import { QueryClient, dehydrate, hydrate } from "@tanstack/query-core";
23
+ import $deepEqual from "fast-deep-equal";
24
+ const deepEqual = $importDefault($deepEqual);
25
+ import $lodash from "lodash";
26
+ const { debounce } = $lodash;
27
+ import { createServicePolicy } from "./createServicePolicy.mjs";
28
+ import { processQueryResponse } from "./utils.mjs";
19
29
  // Defaults to apply to all data service queries if no default option specified
20
30
  const QUERY_CLIENT_DEFAULTS = {
21
31
  queries: {
@@ -213,4 +223,4 @@ async function _BaseDataService_loadCache() {
213
223
  }
214
224
  hydrate(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), cache.state);
215
225
  };
216
- //# sourceMappingURL=BaseDataService.js.map
226
+ //# sourceMappingURL=BaseDataService.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseDataService.mjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,EACL,SAAS,EAKV,4BAA4B;AAM7B,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAC/C,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,wBAAwB;AAE3D,OAAO,EAUL,WAAW,EAIX,SAAS,EACT,OAAO,EACR,6BAA6B;AAC9B,OAAO,UAAS,wBAAwB;;;;AAGxC,OAAO,EACL,mBAAmB,EAGpB,kCAAiC;AAClC,OAAO,EAAE,oBAAoB,EAAE,oBAAmB;AAiElD,+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;IA6B1B,YAAY,EACV,IAAI,EACJ,SAAS,EACT,iBAAiB,GAAG,EAAE,EACtB,aAAa,EACb,iBAAiB,GAalB;;QAzCQ,6CAIP;QAE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ACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;IAEF,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAG,YAAyC,CAAC;IAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,0CAAmB,CAAC,MAAM,EAAE,CAAC;QACnE,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,OAAO,CAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n MessengerActions,\n MessengerEvents,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\nimport { Struct } from '@metamask/superstruct';\nimport { Duration, inMilliseconds } from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport {\n DefaultError,\n DefaultOptions,\n DehydratedState,\n FetchQueryOptions,\n InfiniteData,\n InfiniteQueryPageParamsOptions,\n InvalidateOptions,\n InvalidateQueryFilters,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\n QueryFunction,\n WithRequired,\n dehydrate,\n hydrate,\n} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\nimport { debounce, DebouncedFunc } from 'lodash';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\nimport { processQueryResponse } from './utils.js';\n\n// Data service queries use the following format: ['ServiceActionName', ...params]\nexport type QueryKey = [string, ...Json[]];\n\n/**\n * The supertype of all messengers, scoped to a namespace.\n *\n * @template Namespace - The namespace for the messenger's own actions and\n * events.\n */\nexport type BaseMessenger<Namespace extends string> = Messenger<\n Namespace,\n ActionConstraint,\n EventConstraint,\n // Use `any` to allow any parent to be set. `any` is harmless in a type constraint anyway,\n // it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\nexport type DataServiceGranularCacheUpdatedPayload =\n | { type: 'added' | 'updated'; state: DehydratedState }\n | {\n type: 'removed';\n state: null;\n };\n\nexport type DataServiceCacheUpdatedPayload =\n DataServiceGranularCacheUpdatedPayload & {\n hash: string;\n };\n\ntype CacheUpdatedType = DataServiceCacheUpdatedPayload['type'];\n\nexport type DataServiceInvalidateQueriesAction<ServiceName extends string> = {\n type: `${ServiceName}:invalidateQueries`;\n handler: BaseDataService<\n ServiceName,\n BaseMessenger<ServiceName>\n >['invalidateQueries'];\n};\n\nexport type DataServiceActions<ServiceName extends string> =\n DataServiceInvalidateQueriesAction<ServiceName>;\n\ntype DataServiceAllowedActions =\n | StorageServiceGetItemAction\n | StorageServiceSetItemAction\n | StorageServiceRemoveItemAction;\n\nexport type DataServiceCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated`;\n payload: [DataServiceCacheUpdatedPayload];\n};\n\nexport type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated:${string}`;\n payload: [DataServiceGranularCacheUpdatedPayload];\n};\n\nexport type DataServiceEvents<ServiceName extends string> =\n | DataServiceCacheUpdatedEvent<ServiceName>\n | DataServiceGranularCacheUpdatedEvent<ServiceName>;\n\n// Defaults to apply to all data service queries if no default option specified\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\n },\n};\n\nexport const STORAGE_SERVICE_KEY = 'cache';\n\n/**\n * Options for persistence configuration.\n */\nexport type PersistenceConfiguration = {\n /**\n * The maximum age before the cache is treated as expired in milliseconds.\n * This is relevant for rehydrating the state during initialization,\n * if the cached state is too old it will be discarded.\n */\n maxAge: number;\n /**\n * The number of milliseconds to wait before triggering persistence following a cache update.\n */\n writeDelay?: number;\n /**\n * The maximum number of milliseconds to wait between persistence writes.\n */\n maxWriteDelay?: number;\n};\n\ntype PersistedCache = {\n state: DehydratedState;\n timestamp: number;\n};\n\nexport class BaseDataService<\n ServiceName extends string,\n ServiceMessenger extends BaseMessenger<ServiceName>,\n> {\n public readonly name: ServiceName;\n\n readonly #messenger: Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n\n readonly #externalMessenger: Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n\n protected messenger: ServiceMessenger;\n\n readonly #policy: ServicePolicy;\n\n readonly #queryClient: QueryClient;\n\n readonly #queryCacheUnsubscribe: () => void;\n\n readonly #debouncedPersist?: DebouncedFunc<() => void>;\n\n readonly #persistenceConfig?: PersistenceConfiguration;\n\n constructor({\n name,\n messenger,\n queryClientConfig = {},\n policyOptions,\n persistenceConfig,\n }: {\n name: ServiceName;\n messenger: DataServiceActions<ServiceName>['type'] extends\n | MessengerActions<ServiceMessenger>['type']\n | DataServiceAllowedActions['type']\n ? DataServiceEvents<ServiceName>['type'] extends MessengerEvents<ServiceMessenger>['type']\n ? ServiceMessenger\n : never\n : never;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n persistenceConfig?: PersistenceConfiguration;\n }) {\n this.name = name;\n\n // We store two narrowly-typed messengers alongside the generic public one:\n // - #messenger handles the service's own action registration and event publishing\n // - #externalMessenger handles calls to external actions\n // Splitting them avoids TypeScript issues with mixing template-literals with regular strings\n this.#messenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n this.#externalMessenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n this.messenger = messenger;\n\n this.#queryClient = new QueryClient({\n ...queryClientConfig,\n defaultOptions: {\n queries: {\n ...QUERY_CLIENT_DEFAULTS.queries,\n ...queryClientConfig.defaultOptions?.queries,\n },\n mutations: queryClientConfig.defaultOptions?.mutations,\n },\n });\n\n this.#persistenceConfig = persistenceConfig;\n\n this.#policy = createServicePolicy(policyOptions);\n\n this.#debouncedPersist =\n this.#persistenceConfig &&\n debounce(\n () => {\n this.#persistCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n },\n this.#persistenceConfig.writeDelay ??\n inMilliseconds(10, Duration.Second),\n {\n maxWait:\n this.#persistenceConfig.maxWriteDelay ??\n inMilliseconds(1, Duration.Minute),\n },\n );\n\n this.#queryCacheUnsubscribe = this.#queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (['added', 'updated', 'removed'].includes(event.type)) {\n this.#publishCacheUpdate(\n event.query.queryHash,\n event.type as CacheUpdatedType,\n );\n\n this.#debouncedPersist?.();\n }\n });\n\n this.#messenger.registerActionHandler(\n `${this.name}:invalidateQueries`,\n this.invalidateQueries.bind(this),\n );\n }\n\n /**\n * Fetch a query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >({\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey>;\n responseStruct?: TDataStruct;\n }): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: async (context) => {\n const response = await this.#policy.execute(() =>\n options.queryFn(context),\n );\n return processQueryResponse(options.queryKey, response, responseStruct);\n },\n });\n }\n\n /**\n * Fetch a paginated query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @param pageParam - An optional page parameter.\n * @returns The query result, exclusively the requested page is returned.\n */\n protected async fetchInfiniteQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData extends TQueryFnData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n {\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>,\n TQueryKey,\n TPageParam\n >,\n 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'\n >,\n 'queryKey'\n > &\n InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;\n responseStruct?: TDataStruct;\n },\n pageParam?: TPageParam,\n ): Promise<TData> {\n const cache = this.#queryClient.getQueryCache();\n\n const query = cache.find<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>\n >({\n queryKey: options.queryKey,\n });\n\n if (!query?.state.data || !pageParam) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: pageParam ?? options.initialPageParam,\n queryFn: async (context) => {\n const response = await this.#policy.execute(async () =>\n options.queryFn({\n ...context,\n pageParam: context.meta?.pageParam ?? context.pageParam,\n }),\n );\n return processQueryResponse(\n options.queryKey,\n response,\n responseStruct,\n );\n },\n });\n\n return result.pages[0];\n }\n\n const { pages, pageParams } = query.state.data;\n const next = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n\n const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';\n\n const result = await query.fetch(\n { ...query.options, meta: { pageParam } },\n { meta: { fetchMore: { direction } } },\n );\n\n const pageIndex = result.pageParams.findIndex((param) =>\n deepEqual(param, pageParam),\n );\n\n return result.pages[pageIndex];\n }\n\n /**\n * Invalidate queries serviced by this data service.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @param options - Additional optional options for query invalidations.\n * @returns Nothing.\n */\n async invalidateQueries(\n filters?: InvalidateQueryFilters<QueryKey>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\n }\n\n /**\n * Initialize the service, rehydrating the cache with persisted data if possible.\n */\n init(): void {\n this.#loadCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n }\n\n /**\n * Prepares the service for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n */\n destroy(): void {\n this.#debouncedPersist?.cancel();\n this.#queryCacheUnsubscribe();\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when a given query changes.\n *\n * @param hash The hash of the query.\n * @param type The type of cache update.\n */\n #publishCacheUpdate(hash: string, type: CacheUpdatedType): void {\n const state =\n type === 'added' || type === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) => query.queryHash === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type,\n state,\n } as DataServiceGranularCacheUpdatedPayload,\n );\n }\n\n /**\n * Persist the query client cache using the StorageService, if the cache is not empty.\n *\n * @returns Nothing.\n */\n async #persistCache(): Promise<void> {\n const state = dehydrate(this.#queryClient, {\n // This is the default, but we specify it to be explicit.\n shouldDehydrateQuery: (query) => query.state.status === 'success',\n });\n\n if (state.queries.length === 0 && state.mutations.length === 0) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n const cache: PersistedCache = {\n timestamp: Date.now(),\n state,\n };\n\n await this.#externalMessenger.call(\n 'StorageService:setItem',\n this.name,\n STORAGE_SERVICE_KEY,\n cache as unknown as Json,\n );\n }\n\n /**\n * Load the query client cache from the StorageService, if persistence is configured\n * and the persisted cache is not expired.\n *\n * @returns Nothing.\n */\n async #loadCache(): Promise<void> {\n if (!this.#persistenceConfig) {\n return;\n }\n\n const { result: untypedCache } = await this.#externalMessenger.call(\n 'StorageService:getItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n\n if (!untypedCache) {\n return;\n }\n\n const cache = untypedCache as unknown as PersistedCache;\n\n if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n hydrate(this.#queryClient, cache.state);\n }\n}\n"]}