@metamask-previews/storage-service 0.0.0-preview-d6fe4594
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 +14 -0
- package/LICENSE +6 -0
- package/LICENSE.APACHE2 +201 -0
- package/LICENSE.MIT +21 -0
- package/README.md +118 -0
- package/dist/InMemoryStorageAdapter.cjs +124 -0
- package/dist/InMemoryStorageAdapter.cjs.map +1 -0
- package/dist/InMemoryStorageAdapter.d.cts +72 -0
- package/dist/InMemoryStorageAdapter.d.cts.map +1 -0
- package/dist/InMemoryStorageAdapter.d.mts +72 -0
- package/dist/InMemoryStorageAdapter.d.mts.map +1 -0
- package/dist/InMemoryStorageAdapter.mjs +120 -0
- package/dist/InMemoryStorageAdapter.mjs.map +1 -0
- package/dist/StorageService-method-action-types.cjs +7 -0
- package/dist/StorageService-method-action-types.cjs.map +1 -0
- package/dist/StorageService-method-action-types.d.cts +78 -0
- package/dist/StorageService-method-action-types.d.cts.map +1 -0
- package/dist/StorageService-method-action-types.d.mts +78 -0
- package/dist/StorageService-method-action-types.d.mts.map +1 -0
- package/dist/StorageService-method-action-types.mjs +6 -0
- package/dist/StorageService-method-action-types.mjs.map +1 -0
- package/dist/StorageService.cjs +200 -0
- package/dist/StorageService.cjs.map +1 -0
- package/dist/StorageService.d.cts +145 -0
- package/dist/StorageService.d.cts.map +1 -0
- package/dist/StorageService.d.mts +145 -0
- package/dist/StorageService.d.mts.map +1 -0
- package/dist/StorageService.mjs +196 -0
- package/dist/StorageService.mjs.map +1 -0
- package/dist/index.cjs +14 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +6 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +6 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +7 -0
- package/dist/index.mjs.map +1 -0
- package/dist/types.cjs +12 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.cts +148 -0
- package/dist/types.d.cts.map +1 -0
- package/dist/types.d.mts +148 -0
- package/dist/types.d.mts.map +1 -0
- package/dist/types.mjs +9 -0
- package/dist/types.mjs.map +1 -0
- package/package.json +72 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
2
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
4
|
+
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");
|
|
5
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
6
|
+
};
|
|
7
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
8
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
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
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
|
+
};
|
|
12
|
+
var _InMemoryStorageAdapter_storage;
|
|
13
|
+
import { STORAGE_KEY_PREFIX } from "./types.mjs";
|
|
14
|
+
/**
|
|
15
|
+
* In-memory storage adapter (default fallback).
|
|
16
|
+
* Implements the {@link StorageAdapter} interface using a Map.
|
|
17
|
+
*
|
|
18
|
+
* ⚠️ **Warning**: Data is NOT persisted - lost on restart.
|
|
19
|
+
*
|
|
20
|
+
* **Suitable for:**
|
|
21
|
+
* - Testing (isolated, no mocking needed)
|
|
22
|
+
* - Development (quick start, zero config)
|
|
23
|
+
* - Temporary/ephemeral data
|
|
24
|
+
*
|
|
25
|
+
* **Not suitable for:**
|
|
26
|
+
* - Production (unless data is truly ephemeral)
|
|
27
|
+
* - Data that needs to persist across restarts
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* const adapter = new InMemoryStorageAdapter();
|
|
32
|
+
* await adapter.setItem('SnapController', 'snap-id:sourceCode', 'const x = 1;');
|
|
33
|
+
* const value = await adapter.getItem('SnapController', 'snap-id:sourceCode'); // 'const x = 1;'
|
|
34
|
+
* // After restart: data is lost
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export class InMemoryStorageAdapter {
|
|
38
|
+
/**
|
|
39
|
+
* Constructs a new InMemoryStorageAdapter.
|
|
40
|
+
*/
|
|
41
|
+
constructor() {
|
|
42
|
+
// Explicitly implement StorageAdapter interface
|
|
43
|
+
/**
|
|
44
|
+
* Internal storage map.
|
|
45
|
+
*/
|
|
46
|
+
_InMemoryStorageAdapter_storage.set(this, void 0);
|
|
47
|
+
__classPrivateFieldSet(this, _InMemoryStorageAdapter_storage, new Map(), "f");
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Retrieve an item from in-memory storage.
|
|
51
|
+
* Deserializes JSON data from storage.
|
|
52
|
+
*
|
|
53
|
+
* @param namespace - The controller namespace.
|
|
54
|
+
* @param key - The data key.
|
|
55
|
+
* @returns The parsed JSON data, or null if not found.
|
|
56
|
+
*/
|
|
57
|
+
async getItem(namespace, key) {
|
|
58
|
+
const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;
|
|
59
|
+
const serialized = __classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").get(fullKey);
|
|
60
|
+
if (!serialized) {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
return JSON.parse(serialized);
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
// istanbul ignore next - defensive error handling for corrupted data
|
|
68
|
+
console.error(`Failed to parse stored data for ${fullKey}:`, error);
|
|
69
|
+
// istanbul ignore next
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Store an item in in-memory storage.
|
|
75
|
+
* Serializes JSON data to string.
|
|
76
|
+
*
|
|
77
|
+
* @param namespace - The controller namespace.
|
|
78
|
+
* @param key - The data key.
|
|
79
|
+
* @param value - The JSON value to store.
|
|
80
|
+
*/
|
|
81
|
+
async setItem(namespace, key, value) {
|
|
82
|
+
const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;
|
|
83
|
+
__classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").set(fullKey, JSON.stringify(value));
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Remove an item from in-memory storage.
|
|
87
|
+
*
|
|
88
|
+
* @param namespace - The controller namespace.
|
|
89
|
+
* @param key - The data key.
|
|
90
|
+
*/
|
|
91
|
+
async removeItem(namespace, key) {
|
|
92
|
+
const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;
|
|
93
|
+
__classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").delete(fullKey);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Get all keys for a namespace.
|
|
97
|
+
* Returns keys without the 'storage:namespace:' prefix.
|
|
98
|
+
*
|
|
99
|
+
* @param namespace - The namespace to get keys for.
|
|
100
|
+
* @returns Array of keys (without prefix) for this namespace.
|
|
101
|
+
*/
|
|
102
|
+
async getAllKeys(namespace) {
|
|
103
|
+
const prefix = `${STORAGE_KEY_PREFIX}${namespace}:`;
|
|
104
|
+
return Array.from(__classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").keys())
|
|
105
|
+
.filter((key) => key.startsWith(prefix))
|
|
106
|
+
.map((key) => key.slice(prefix.length));
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Clear all items for a namespace.
|
|
110
|
+
*
|
|
111
|
+
* @param namespace - The namespace to clear.
|
|
112
|
+
*/
|
|
113
|
+
async clear(namespace) {
|
|
114
|
+
const prefix = `${STORAGE_KEY_PREFIX}${namespace}:`;
|
|
115
|
+
const keysToDelete = Array.from(__classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").keys()).filter((key) => key.startsWith(prefix));
|
|
116
|
+
keysToDelete.forEach((key) => __classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").delete(key));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
_InMemoryStorageAdapter_storage = new WeakMap();
|
|
120
|
+
//# sourceMappingURL=InMemoryStorageAdapter.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InMemoryStorageAdapter.mjs","sourceRoot":"","sources":["../src/InMemoryStorageAdapter.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,OAAO,EAAE,kBAAkB,EAAE,oBAAgB;AAE7C;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,OAAO,sBAAsB;IAOjC;;OAEG;IACH;QATA,gDAAgD;QAChD;;WAEG;QACM,kDAA8B;QAMrC,uBAAA,IAAI,mCAAY,IAAI,GAAG,EAAE,MAAA,CAAC;IAC5B,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,OAAO,CAAC,SAAiB,EAAE,GAAW;QAC1C,MAAM,OAAO,GAAG,GAAG,kBAAkB,GAAG,SAAS,IAAI,GAAG,EAAE,CAAC;QAC3D,MAAM,UAAU,GAAG,uBAAA,IAAI,uCAAS,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAE9C,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC;QACd,CAAC;QAED,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAS,CAAC;QACxC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,qEAAqE;YACrE,OAAO,CAAC,KAAK,CAAC,mCAAmC,OAAO,GAAG,EAAE,KAAK,CAAC,CAAC;YACpE,uBAAuB;YACvB,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,OAAO,CAAC,SAAiB,EAAE,GAAW,EAAE,KAAW;QACvD,MAAM,OAAO,GAAG,GAAG,kBAAkB,GAAG,SAAS,IAAI,GAAG,EAAE,CAAC;QAC3D,uBAAA,IAAI,uCAAS,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;IACpD,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,UAAU,CAAC,SAAiB,EAAE,GAAW;QAC7C,MAAM,OAAO,GAAG,GAAG,kBAAkB,GAAG,SAAS,IAAI,GAAG,EAAE,CAAC;QAC3D,uBAAA,IAAI,uCAAS,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,UAAU,CAAC,SAAiB;QAChC,MAAM,MAAM,GAAG,GAAG,kBAAkB,GAAG,SAAS,GAAG,CAAC;QACpD,OAAO,KAAK,CAAC,IAAI,CAAC,uBAAA,IAAI,uCAAS,CAAC,IAAI,EAAE,CAAC;aACpC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;aACvC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IAC5C,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,KAAK,CAAC,SAAiB;QAC3B,MAAM,MAAM,GAAG,GAAG,kBAAkB,GAAG,SAAS,GAAG,CAAC;QACpD,MAAM,YAAY,GAAG,KAAK,CAAC,IAAI,CAAC,uBAAA,IAAI,uCAAS,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CACnE,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,CACvB,CAAC;QACF,YAAY,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,uBAAA,IAAI,uCAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF","sourcesContent":["import type { Json } from '@metamask/utils';\n\nimport type { StorageAdapter } from './types';\nimport { STORAGE_KEY_PREFIX } from './types';\n\n/**\n * In-memory storage adapter (default fallback).\n * Implements the {@link StorageAdapter} interface using a Map.\n *\n * ⚠️ **Warning**: Data is NOT persisted - lost on restart.\n *\n * **Suitable for:**\n * - Testing (isolated, no mocking needed)\n * - Development (quick start, zero config)\n * - Temporary/ephemeral data\n *\n * **Not suitable for:**\n * - Production (unless data is truly ephemeral)\n * - Data that needs to persist across restarts\n *\n * @example\n * ```typescript\n * const adapter = new InMemoryStorageAdapter();\n * await adapter.setItem('SnapController', 'snap-id:sourceCode', 'const x = 1;');\n * const value = await adapter.getItem('SnapController', 'snap-id:sourceCode'); // 'const x = 1;'\n * // After restart: data is lost\n * ```\n */\nexport class InMemoryStorageAdapter implements StorageAdapter {\n // Explicitly implement StorageAdapter interface\n /**\n * Internal storage map.\n */\n readonly #storage: Map<string, string>;\n\n /**\n * Constructs a new InMemoryStorageAdapter.\n */\n constructor() {\n this.#storage = new Map();\n }\n\n /**\n * Retrieve an item from in-memory storage.\n * Deserializes JSON data from storage.\n *\n * @param namespace - The controller namespace.\n * @param key - The data key.\n * @returns The parsed JSON data, or null if not found.\n */\n async getItem(namespace: string, key: string): Promise<Json | null> {\n const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;\n const serialized = this.#storage.get(fullKey);\n\n if (!serialized) {\n return null;\n }\n\n try {\n return JSON.parse(serialized) as Json;\n } catch (error) {\n // istanbul ignore next - defensive error handling for corrupted data\n console.error(`Failed to parse stored data for ${fullKey}:`, error);\n // istanbul ignore next\n return null;\n }\n }\n\n /**\n * Store an item in in-memory storage.\n * Serializes JSON data to string.\n *\n * @param namespace - The controller namespace.\n * @param key - The data key.\n * @param value - The JSON value to store.\n */\n async setItem(namespace: string, key: string, value: Json): Promise<void> {\n const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;\n this.#storage.set(fullKey, JSON.stringify(value));\n }\n\n /**\n * Remove an item from in-memory storage.\n *\n * @param namespace - The controller namespace.\n * @param key - The data key.\n */\n async removeItem(namespace: string, key: string): Promise<void> {\n const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;\n this.#storage.delete(fullKey);\n }\n\n /**\n * Get all keys for a namespace.\n * Returns keys without the 'storage:namespace:' prefix.\n *\n * @param namespace - The namespace to get keys for.\n * @returns Array of keys (without prefix) for this namespace.\n */\n async getAllKeys(namespace: string): Promise<string[]> {\n const prefix = `${STORAGE_KEY_PREFIX}${namespace}:`;\n return Array.from(this.#storage.keys())\n .filter((key) => key.startsWith(prefix))\n .map((key) => key.slice(prefix.length));\n }\n\n /**\n * Clear all items for a namespace.\n *\n * @param namespace - The namespace to clear.\n */\n async clear(namespace: string): Promise<void> {\n const prefix = `${STORAGE_KEY_PREFIX}${namespace}:`;\n const keysToDelete = Array.from(this.#storage.keys()).filter((key) =>\n key.startsWith(prefix),\n );\n keysToDelete.forEach((key) => this.#storage.delete(key));\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"StorageService-method-action-types.cjs","sourceRoot":"","sources":["../src/StorageService-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated by `scripts/generate-method-action-types.ts`.\n * Do not edit manually.\n */\n\nimport type { StorageService } from './StorageService';\n\n/**\n * Store large JSON data in storage.\n *\n * ⚠️ **Designed for large values (100KB+), not many small ones.**\n * Each storage operation has I/O overhead. For best performance,\n * store one large object rather than many small key-value pairs.\n *\n * @example Good: Store entire cache as one value\n * ```typescript\n * await service.setItem('TokenList', 'cache', { '0x1': [...], '0x38': [...] });\n * ```\n *\n * @example Avoid: Many small values\n * ```typescript\n * // ❌ Don't do this - too many small writes\n * await service.setItem('TokenList', 'cache:0x1', [...]);\n * await service.setItem('TokenList', 'cache:0x38', [...]);\n * ```\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n * @param value - JSON data to store (should be 100KB+ for optimal use).\n */\nexport type StorageServiceSetItemAction = {\n type: `StorageService:setItem`;\n handler: StorageService['setItem'];\n};\n\n/**\n * Retrieve JSON data from storage.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n * @returns Parsed JSON data or null if not found.\n */\nexport type StorageServiceGetItemAction = {\n type: `StorageService:getItem`;\n handler: StorageService['getItem'];\n};\n\n/**\n * Remove data from storage.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n */\nexport type StorageServiceRemoveItemAction = {\n type: `StorageService:removeItem`;\n handler: StorageService['removeItem'];\n};\n\n/**\n * Get all keys for a namespace.\n * Delegates to storage adapter which handles filtering.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @returns Array of keys (without prefix) for this namespace.\n */\nexport type StorageServiceGetAllKeysAction = {\n type: `StorageService:getAllKeys`;\n handler: StorageService['getAllKeys'];\n};\n\n/**\n * Clear all data for a namespace.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n */\nexport type StorageServiceClearAction = {\n type: `StorageService:clear`;\n handler: StorageService['clear'];\n};\n\n/**\n * Union of all StorageService action types.\n */\nexport type StorageServiceMethodActions =\n | StorageServiceSetItemAction\n | StorageServiceGetItemAction\n | StorageServiceRemoveItemAction\n | StorageServiceGetAllKeysAction\n | StorageServiceClearAction;\n"]}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is auto generated by `scripts/generate-method-action-types.ts`.
|
|
3
|
+
* Do not edit manually.
|
|
4
|
+
*/
|
|
5
|
+
import type { StorageService } from "./StorageService.cjs";
|
|
6
|
+
/**
|
|
7
|
+
* Store large JSON data in storage.
|
|
8
|
+
*
|
|
9
|
+
* ⚠️ **Designed for large values (100KB+), not many small ones.**
|
|
10
|
+
* Each storage operation has I/O overhead. For best performance,
|
|
11
|
+
* store one large object rather than many small key-value pairs.
|
|
12
|
+
*
|
|
13
|
+
* @example Good: Store entire cache as one value
|
|
14
|
+
* ```typescript
|
|
15
|
+
* await service.setItem('TokenList', 'cache', { '0x1': [...], '0x38': [...] });
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @example Avoid: Many small values
|
|
19
|
+
* ```typescript
|
|
20
|
+
* // ❌ Don't do this - too many small writes
|
|
21
|
+
* await service.setItem('TokenList', 'cache:0x1', [...]);
|
|
22
|
+
* await service.setItem('TokenList', 'cache:0x38', [...]);
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
26
|
+
* @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').
|
|
27
|
+
* @param value - JSON data to store (should be 100KB+ for optimal use).
|
|
28
|
+
*/
|
|
29
|
+
export type StorageServiceSetItemAction = {
|
|
30
|
+
type: `StorageService:setItem`;
|
|
31
|
+
handler: StorageService['setItem'];
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Retrieve JSON data from storage.
|
|
35
|
+
*
|
|
36
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
37
|
+
* @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').
|
|
38
|
+
* @returns Parsed JSON data or null if not found.
|
|
39
|
+
*/
|
|
40
|
+
export type StorageServiceGetItemAction = {
|
|
41
|
+
type: `StorageService:getItem`;
|
|
42
|
+
handler: StorageService['getItem'];
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Remove data from storage.
|
|
46
|
+
*
|
|
47
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
48
|
+
* @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').
|
|
49
|
+
*/
|
|
50
|
+
export type StorageServiceRemoveItemAction = {
|
|
51
|
+
type: `StorageService:removeItem`;
|
|
52
|
+
handler: StorageService['removeItem'];
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Get all keys for a namespace.
|
|
56
|
+
* Delegates to storage adapter which handles filtering.
|
|
57
|
+
*
|
|
58
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
59
|
+
* @returns Array of keys (without prefix) for this namespace.
|
|
60
|
+
*/
|
|
61
|
+
export type StorageServiceGetAllKeysAction = {
|
|
62
|
+
type: `StorageService:getAllKeys`;
|
|
63
|
+
handler: StorageService['getAllKeys'];
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Clear all data for a namespace.
|
|
67
|
+
*
|
|
68
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
69
|
+
*/
|
|
70
|
+
export type StorageServiceClearAction = {
|
|
71
|
+
type: `StorageService:clear`;
|
|
72
|
+
handler: StorageService['clear'];
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Union of all StorageService action types.
|
|
76
|
+
*/
|
|
77
|
+
export type StorageServiceMethodActions = StorageServiceSetItemAction | StorageServiceGetItemAction | StorageServiceRemoveItemAction | StorageServiceGetAllKeysAction | StorageServiceClearAction;
|
|
78
|
+
//# sourceMappingURL=StorageService-method-action-types.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"StorageService-method-action-types.d.cts","sourceRoot":"","sources":["../src/StorageService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,6BAAyB;AAEvD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,wBAAwB,CAAC;IAC/B,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,CAAC;CACpC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,wBAAwB,CAAC;IAC/B,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,CAAC;CACpC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,cAAc,CAAC,YAAY,CAAC,CAAC;CACvC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,cAAc,CAAC,YAAY,CAAC,CAAC;CACvC,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC,IAAI,EAAE,sBAAsB,CAAC;IAC7B,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC;CAClC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,2BAA2B,GACnC,2BAA2B,GAC3B,2BAA2B,GAC3B,8BAA8B,GAC9B,8BAA8B,GAC9B,yBAAyB,CAAC"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is auto generated by `scripts/generate-method-action-types.ts`.
|
|
3
|
+
* Do not edit manually.
|
|
4
|
+
*/
|
|
5
|
+
import type { StorageService } from "./StorageService.mjs";
|
|
6
|
+
/**
|
|
7
|
+
* Store large JSON data in storage.
|
|
8
|
+
*
|
|
9
|
+
* ⚠️ **Designed for large values (100KB+), not many small ones.**
|
|
10
|
+
* Each storage operation has I/O overhead. For best performance,
|
|
11
|
+
* store one large object rather than many small key-value pairs.
|
|
12
|
+
*
|
|
13
|
+
* @example Good: Store entire cache as one value
|
|
14
|
+
* ```typescript
|
|
15
|
+
* await service.setItem('TokenList', 'cache', { '0x1': [...], '0x38': [...] });
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @example Avoid: Many small values
|
|
19
|
+
* ```typescript
|
|
20
|
+
* // ❌ Don't do this - too many small writes
|
|
21
|
+
* await service.setItem('TokenList', 'cache:0x1', [...]);
|
|
22
|
+
* await service.setItem('TokenList', 'cache:0x38', [...]);
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
26
|
+
* @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').
|
|
27
|
+
* @param value - JSON data to store (should be 100KB+ for optimal use).
|
|
28
|
+
*/
|
|
29
|
+
export type StorageServiceSetItemAction = {
|
|
30
|
+
type: `StorageService:setItem`;
|
|
31
|
+
handler: StorageService['setItem'];
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Retrieve JSON data from storage.
|
|
35
|
+
*
|
|
36
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
37
|
+
* @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').
|
|
38
|
+
* @returns Parsed JSON data or null if not found.
|
|
39
|
+
*/
|
|
40
|
+
export type StorageServiceGetItemAction = {
|
|
41
|
+
type: `StorageService:getItem`;
|
|
42
|
+
handler: StorageService['getItem'];
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Remove data from storage.
|
|
46
|
+
*
|
|
47
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
48
|
+
* @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').
|
|
49
|
+
*/
|
|
50
|
+
export type StorageServiceRemoveItemAction = {
|
|
51
|
+
type: `StorageService:removeItem`;
|
|
52
|
+
handler: StorageService['removeItem'];
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Get all keys for a namespace.
|
|
56
|
+
* Delegates to storage adapter which handles filtering.
|
|
57
|
+
*
|
|
58
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
59
|
+
* @returns Array of keys (without prefix) for this namespace.
|
|
60
|
+
*/
|
|
61
|
+
export type StorageServiceGetAllKeysAction = {
|
|
62
|
+
type: `StorageService:getAllKeys`;
|
|
63
|
+
handler: StorageService['getAllKeys'];
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Clear all data for a namespace.
|
|
67
|
+
*
|
|
68
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
69
|
+
*/
|
|
70
|
+
export type StorageServiceClearAction = {
|
|
71
|
+
type: `StorageService:clear`;
|
|
72
|
+
handler: StorageService['clear'];
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Union of all StorageService action types.
|
|
76
|
+
*/
|
|
77
|
+
export type StorageServiceMethodActions = StorageServiceSetItemAction | StorageServiceGetItemAction | StorageServiceRemoveItemAction | StorageServiceGetAllKeysAction | StorageServiceClearAction;
|
|
78
|
+
//# sourceMappingURL=StorageService-method-action-types.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"StorageService-method-action-types.d.mts","sourceRoot":"","sources":["../src/StorageService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,6BAAyB;AAEvD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,wBAAwB,CAAC;IAC/B,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,CAAC;CACpC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,wBAAwB,CAAC;IAC/B,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,CAAC;CACpC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,cAAc,CAAC,YAAY,CAAC,CAAC;CACvC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,cAAc,CAAC,YAAY,CAAC,CAAC;CACvC,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC,IAAI,EAAE,sBAAsB,CAAC;IAC7B,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC;CAClC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,2BAA2B,GACnC,2BAA2B,GAC3B,2BAA2B,GAC3B,8BAA8B,GAC9B,8BAA8B,GAC9B,yBAAyB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"StorageService-method-action-types.mjs","sourceRoot":"","sources":["../src/StorageService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated by `scripts/generate-method-action-types.ts`.\n * Do not edit manually.\n */\n\nimport type { StorageService } from './StorageService';\n\n/**\n * Store large JSON data in storage.\n *\n * ⚠️ **Designed for large values (100KB+), not many small ones.**\n * Each storage operation has I/O overhead. For best performance,\n * store one large object rather than many small key-value pairs.\n *\n * @example Good: Store entire cache as one value\n * ```typescript\n * await service.setItem('TokenList', 'cache', { '0x1': [...], '0x38': [...] });\n * ```\n *\n * @example Avoid: Many small values\n * ```typescript\n * // ❌ Don't do this - too many small writes\n * await service.setItem('TokenList', 'cache:0x1', [...]);\n * await service.setItem('TokenList', 'cache:0x38', [...]);\n * ```\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n * @param value - JSON data to store (should be 100KB+ for optimal use).\n */\nexport type StorageServiceSetItemAction = {\n type: `StorageService:setItem`;\n handler: StorageService['setItem'];\n};\n\n/**\n * Retrieve JSON data from storage.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n * @returns Parsed JSON data or null if not found.\n */\nexport type StorageServiceGetItemAction = {\n type: `StorageService:getItem`;\n handler: StorageService['getItem'];\n};\n\n/**\n * Remove data from storage.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n */\nexport type StorageServiceRemoveItemAction = {\n type: `StorageService:removeItem`;\n handler: StorageService['removeItem'];\n};\n\n/**\n * Get all keys for a namespace.\n * Delegates to storage adapter which handles filtering.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @returns Array of keys (without prefix) for this namespace.\n */\nexport type StorageServiceGetAllKeysAction = {\n type: `StorageService:getAllKeys`;\n handler: StorageService['getAllKeys'];\n};\n\n/**\n * Clear all data for a namespace.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n */\nexport type StorageServiceClearAction = {\n type: `StorageService:clear`;\n handler: StorageService['clear'];\n};\n\n/**\n * Union of all StorageService action types.\n */\nexport type StorageServiceMethodActions =\n | StorageServiceSetItemAction\n | StorageServiceGetItemAction\n | StorageServiceRemoveItemAction\n | StorageServiceGetAllKeysAction\n | StorageServiceClearAction;\n"]}
|
|
@@ -0,0 +1,200 @@
|
|
|
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 _StorageService_messenger, _StorageService_storage;
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.StorageService = void 0;
|
|
16
|
+
const InMemoryStorageAdapter_1 = require("./InMemoryStorageAdapter.cjs");
|
|
17
|
+
const types_1 = require("./types.cjs");
|
|
18
|
+
// === MESSENGER ===
|
|
19
|
+
const MESSENGER_EXPOSED_METHODS = [
|
|
20
|
+
'setItem',
|
|
21
|
+
'getItem',
|
|
22
|
+
'removeItem',
|
|
23
|
+
'getAllKeys',
|
|
24
|
+
'clear',
|
|
25
|
+
];
|
|
26
|
+
/**
|
|
27
|
+
* StorageService provides a platform-agnostic way for controllers to store
|
|
28
|
+
* large, infrequently accessed data outside of memory/Redux state.
|
|
29
|
+
*
|
|
30
|
+
* **Use cases:**
|
|
31
|
+
* - Snap source code (6+ MB that's rarely accessed)
|
|
32
|
+
* - Token metadata caches (4+ MB of cached data)
|
|
33
|
+
* - Large cached responses from APIs
|
|
34
|
+
* - Any data > 100 KB that's not frequently accessed
|
|
35
|
+
*
|
|
36
|
+
* **Benefits:**
|
|
37
|
+
* - Reduces memory usage (data stays on disk)
|
|
38
|
+
* - Faster Redux persist (less data to serialize)
|
|
39
|
+
* - Faster app startup (less data to parse)
|
|
40
|
+
* - Lazy loading (data loaded only when needed)
|
|
41
|
+
*
|
|
42
|
+
* **Platform Support:**
|
|
43
|
+
* - Mobile: FilesystemStorage adapter
|
|
44
|
+
* - Extension: IndexedDB adapter
|
|
45
|
+
* - Tests/Dev: InMemoryStorageAdapter (default)
|
|
46
|
+
*
|
|
47
|
+
* @example Using the service via messenger
|
|
48
|
+
*
|
|
49
|
+
* ```typescript
|
|
50
|
+
* // In a controller
|
|
51
|
+
* type AllowedActions =
|
|
52
|
+
* | StorageServiceSetItemAction
|
|
53
|
+
* | StorageServiceGetItemAction;
|
|
54
|
+
*
|
|
55
|
+
* class SnapController extends BaseController {
|
|
56
|
+
* async storeSnapSourceCode(snapId: string, sourceCode: string) {
|
|
57
|
+
* await this.messenger.call(
|
|
58
|
+
* 'StorageService:setItem',
|
|
59
|
+
* 'SnapController',
|
|
60
|
+
* `${snapId}:sourceCode`,
|
|
61
|
+
* sourceCode,
|
|
62
|
+
* );
|
|
63
|
+
* }
|
|
64
|
+
*
|
|
65
|
+
* async getSnapSourceCode(snapId: string): Promise<string | null> {
|
|
66
|
+
* const result = await this.messenger.call(
|
|
67
|
+
* 'StorageService:getItem',
|
|
68
|
+
* 'SnapController',
|
|
69
|
+
* `${snapId}:sourceCode`,
|
|
70
|
+
* );
|
|
71
|
+
* return result as string | null; // Caller must validate/cast
|
|
72
|
+
* }
|
|
73
|
+
* }
|
|
74
|
+
* ```
|
|
75
|
+
*
|
|
76
|
+
* @example Initializing in a client
|
|
77
|
+
*
|
|
78
|
+
* ```typescript
|
|
79
|
+
* // Mobile
|
|
80
|
+
* const service = new StorageService({
|
|
81
|
+
* messenger: storageServiceMessenger,
|
|
82
|
+
* storage: filesystemStorageAdapter, // Platform-specific
|
|
83
|
+
* });
|
|
84
|
+
*
|
|
85
|
+
* // Extension
|
|
86
|
+
* const service = new StorageService({
|
|
87
|
+
* messenger: storageServiceMessenger,
|
|
88
|
+
* storage: indexedDBAdapter, // Platform-specific
|
|
89
|
+
* });
|
|
90
|
+
*
|
|
91
|
+
* // Tests (uses in-memory by default)
|
|
92
|
+
* const service = new StorageService({
|
|
93
|
+
* messenger: storageServiceMessenger,
|
|
94
|
+
* // No storage - uses InMemoryStorageAdapter
|
|
95
|
+
* });
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
class StorageService {
|
|
99
|
+
/**
|
|
100
|
+
* Constructs a new StorageService.
|
|
101
|
+
*
|
|
102
|
+
* @param options - The options.
|
|
103
|
+
* @param options.messenger - The messenger suited for this service.
|
|
104
|
+
* @param options.storage - Storage adapter for persisting data.
|
|
105
|
+
* If not provided, uses InMemoryStorageAdapter (data lost on restart).
|
|
106
|
+
*/
|
|
107
|
+
constructor({ messenger, storage }) {
|
|
108
|
+
/**
|
|
109
|
+
* The messenger suited for this service.
|
|
110
|
+
*/
|
|
111
|
+
_StorageService_messenger.set(this, void 0);
|
|
112
|
+
/**
|
|
113
|
+
* The storage adapter for persisting data.
|
|
114
|
+
*/
|
|
115
|
+
_StorageService_storage.set(this, void 0);
|
|
116
|
+
this.name = types_1.SERVICE_NAME;
|
|
117
|
+
__classPrivateFieldSet(this, _StorageService_messenger, messenger, "f");
|
|
118
|
+
__classPrivateFieldSet(this, _StorageService_storage, storage ?? new InMemoryStorageAdapter_1.InMemoryStorageAdapter(), "f");
|
|
119
|
+
// Warn if using in-memory storage (data won't persist)
|
|
120
|
+
if (!storage) {
|
|
121
|
+
console.warn(`${types_1.SERVICE_NAME}: No storage adapter provided. Using in-memory storage. ` +
|
|
122
|
+
'Data will be lost on restart. Provide a storage adapter for persistence.');
|
|
123
|
+
}
|
|
124
|
+
// Register messenger actions
|
|
125
|
+
__classPrivateFieldGet(this, _StorageService_messenger, "f").registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Store large JSON data in storage.
|
|
129
|
+
*
|
|
130
|
+
* ⚠️ **Designed for large values (100KB+), not many small ones.**
|
|
131
|
+
* Each storage operation has I/O overhead. For best performance,
|
|
132
|
+
* store one large object rather than many small key-value pairs.
|
|
133
|
+
*
|
|
134
|
+
* @example Good: Store entire cache as one value
|
|
135
|
+
* ```typescript
|
|
136
|
+
* await service.setItem('TokenList', 'cache', { '0x1': [...], '0x38': [...] });
|
|
137
|
+
* ```
|
|
138
|
+
*
|
|
139
|
+
* @example Avoid: Many small values
|
|
140
|
+
* ```typescript
|
|
141
|
+
* // ❌ Don't do this - too many small writes
|
|
142
|
+
* await service.setItem('TokenList', 'cache:0x1', [...]);
|
|
143
|
+
* await service.setItem('TokenList', 'cache:0x38', [...]);
|
|
144
|
+
* ```
|
|
145
|
+
*
|
|
146
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
147
|
+
* @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').
|
|
148
|
+
* @param value - JSON data to store (should be 100KB+ for optimal use).
|
|
149
|
+
*/
|
|
150
|
+
async setItem(namespace, key, value) {
|
|
151
|
+
// Adapter handles serialization and wrapping with metadata
|
|
152
|
+
await __classPrivateFieldGet(this, _StorageService_storage, "f").setItem(namespace, key, value);
|
|
153
|
+
// Publish event so other controllers can react to changes
|
|
154
|
+
// Event type: StorageService:itemSet:namespace
|
|
155
|
+
// Payload: [key, value]
|
|
156
|
+
__classPrivateFieldGet(this, _StorageService_messenger, "f").publish(`${types_1.SERVICE_NAME}:itemSet:${namespace}`, key, value);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Retrieve JSON data from storage.
|
|
160
|
+
*
|
|
161
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
162
|
+
* @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').
|
|
163
|
+
* @returns Parsed JSON data or null if not found.
|
|
164
|
+
*/
|
|
165
|
+
async getItem(namespace, key) {
|
|
166
|
+
// Adapter handles deserialization and unwrapping
|
|
167
|
+
return await __classPrivateFieldGet(this, _StorageService_storage, "f").getItem(namespace, key);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Remove data from storage.
|
|
171
|
+
*
|
|
172
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
173
|
+
* @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').
|
|
174
|
+
*/
|
|
175
|
+
async removeItem(namespace, key) {
|
|
176
|
+
// Adapter builds full storage key (e.g., mobile: 'storageService:namespace:key')
|
|
177
|
+
await __classPrivateFieldGet(this, _StorageService_storage, "f").removeItem(namespace, key);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Get all keys for a namespace.
|
|
181
|
+
* Delegates to storage adapter which handles filtering.
|
|
182
|
+
*
|
|
183
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
184
|
+
* @returns Array of keys (without prefix) for this namespace.
|
|
185
|
+
*/
|
|
186
|
+
async getAllKeys(namespace) {
|
|
187
|
+
return await __classPrivateFieldGet(this, _StorageService_storage, "f").getAllKeys(namespace);
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Clear all data for a namespace.
|
|
191
|
+
*
|
|
192
|
+
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
193
|
+
*/
|
|
194
|
+
async clear(namespace) {
|
|
195
|
+
await __classPrivateFieldGet(this, _StorageService_storage, "f").clear(namespace);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
exports.StorageService = StorageService;
|
|
199
|
+
_StorageService_messenger = new WeakMap(), _StorageService_storage = new WeakMap();
|
|
200
|
+
//# sourceMappingURL=StorageService.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"StorageService.cjs","sourceRoot":"","sources":["../src/StorageService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,yEAAkE;AAMlE,uCAAuC;AAEvC,oBAAoB;AAEpB,MAAM,yBAAyB,GAAG;IAChC,SAAS;IACT,SAAS;IACT,YAAY;IACZ,YAAY;IACZ,OAAO;CACC,CAAC;AAEX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuEG;AACH,MAAa,cAAc;IAgBzB;;;;;;;OAOG;IACH,YAAY,EAAE,SAAS,EAAE,OAAO,EAAyB;QAlBzD;;WAEG;QACM,4CAAoC;QAE7C;;WAEG;QACM,0CAAyB;QAWhC,IAAI,CAAC,IAAI,GAAG,oBAAY,CAAC;QACzB,uBAAA,IAAI,6BAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,2BAAY,OAAO,IAAI,IAAI,+CAAsB,EAAE,MAAA,CAAC;QAExD,uDAAuD;QACvD,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,CAAC,IAAI,CACV,GAAG,oBAAY,0DAA0D;gBACvE,0EAA0E,CAC7E,CAAC;QACJ,CAAC;QAED,6BAA6B;QAC7B,uBAAA,IAAI,iCAAW,CAAC,4BAA4B,CAC1C,IAAI,EACJ,yBAAyB,CAC1B,CAAC;IACJ,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,KAAK,CAAC,OAAO,CAAC,SAAiB,EAAE,GAAW,EAAE,KAAW;QACvD,2DAA2D;QAC3D,MAAM,uBAAA,IAAI,+BAAS,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;QAEnD,0DAA0D;QAC1D,+CAA+C;QAC/C,wBAAwB;QACxB,uBAAA,IAAI,iCAAW,CAAC,OAAO,CACrB,GAAG,oBAAY,YAAY,SAAS,EAAW,EAC/C,GAAG,EACH,KAAK,CACN,CAAC;IACJ,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,OAAO,CAAC,SAAiB,EAAE,GAAW;QAC1C,iDAAiD;QACjD,OAAO,MAAM,uBAAA,IAAI,+BAAS,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;IACrD,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,UAAU,CAAC,SAAiB,EAAE,GAAW;QAC7C,iFAAiF;QACjF,MAAM,uBAAA,IAAI,+BAAS,CAAC,UAAU,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;IACjD,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,UAAU,CAAC,SAAiB;QAChC,OAAO,MAAM,uBAAA,IAAI,+BAAS,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;IACnD,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,KAAK,CAAC,SAAiB;QAC3B,MAAM,uBAAA,IAAI,+BAAS,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IACvC,CAAC;CACF;AA3HD,wCA2HC","sourcesContent":["import type { Json } from '@metamask/utils';\n\nimport { InMemoryStorageAdapter } from './InMemoryStorageAdapter';\nimport type {\n StorageAdapter,\n StorageServiceMessenger,\n StorageServiceOptions,\n} from './types';\nimport { SERVICE_NAME } from './types';\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'setItem',\n 'getItem',\n 'removeItem',\n 'getAllKeys',\n 'clear',\n] as const;\n\n/**\n * StorageService provides a platform-agnostic way for controllers to store\n * large, infrequently accessed data outside of memory/Redux state.\n *\n * **Use cases:**\n * - Snap source code (6+ MB that's rarely accessed)\n * - Token metadata caches (4+ MB of cached data)\n * - Large cached responses from APIs\n * - Any data > 100 KB that's not frequently accessed\n *\n * **Benefits:**\n * - Reduces memory usage (data stays on disk)\n * - Faster Redux persist (less data to serialize)\n * - Faster app startup (less data to parse)\n * - Lazy loading (data loaded only when needed)\n *\n * **Platform Support:**\n * - Mobile: FilesystemStorage adapter\n * - Extension: IndexedDB adapter\n * - Tests/Dev: InMemoryStorageAdapter (default)\n *\n * @example Using the service via messenger\n *\n * ```typescript\n * // In a controller\n * type AllowedActions =\n * | StorageServiceSetItemAction\n * | StorageServiceGetItemAction;\n *\n * class SnapController extends BaseController {\n * async storeSnapSourceCode(snapId: string, sourceCode: string) {\n * await this.messenger.call(\n * 'StorageService:setItem',\n * 'SnapController',\n * `${snapId}:sourceCode`,\n * sourceCode,\n * );\n * }\n *\n * async getSnapSourceCode(snapId: string): Promise<string | null> {\n * const result = await this.messenger.call(\n * 'StorageService:getItem',\n * 'SnapController',\n * `${snapId}:sourceCode`,\n * );\n * return result as string | null; // Caller must validate/cast\n * }\n * }\n * ```\n *\n * @example Initializing in a client\n *\n * ```typescript\n * // Mobile\n * const service = new StorageService({\n * messenger: storageServiceMessenger,\n * storage: filesystemStorageAdapter, // Platform-specific\n * });\n *\n * // Extension\n * const service = new StorageService({\n * messenger: storageServiceMessenger,\n * storage: indexedDBAdapter, // Platform-specific\n * });\n *\n * // Tests (uses in-memory by default)\n * const service = new StorageService({\n * messenger: storageServiceMessenger,\n * // No storage - uses InMemoryStorageAdapter\n * });\n * ```\n */\nexport class StorageService {\n /**\n * The name of the service.\n */\n readonly name: typeof SERVICE_NAME;\n\n /**\n * The messenger suited for this service.\n */\n readonly #messenger: StorageServiceMessenger;\n\n /**\n * The storage adapter for persisting data.\n */\n readonly #storage: StorageAdapter;\n\n /**\n * Constructs a new StorageService.\n *\n * @param options - The options.\n * @param options.messenger - The messenger suited for this service.\n * @param options.storage - Storage adapter for persisting data.\n * If not provided, uses InMemoryStorageAdapter (data lost on restart).\n */\n constructor({ messenger, storage }: StorageServiceOptions) {\n this.name = SERVICE_NAME;\n this.#messenger = messenger;\n this.#storage = storage ?? new InMemoryStorageAdapter();\n\n // Warn if using in-memory storage (data won't persist)\n if (!storage) {\n console.warn(\n `${SERVICE_NAME}: No storage adapter provided. Using in-memory storage. ` +\n 'Data will be lost on restart. Provide a storage adapter for persistence.',\n );\n }\n\n // Register messenger actions\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Store large JSON data in storage.\n *\n * ⚠️ **Designed for large values (100KB+), not many small ones.**\n * Each storage operation has I/O overhead. For best performance,\n * store one large object rather than many small key-value pairs.\n *\n * @example Good: Store entire cache as one value\n * ```typescript\n * await service.setItem('TokenList', 'cache', { '0x1': [...], '0x38': [...] });\n * ```\n *\n * @example Avoid: Many small values\n * ```typescript\n * // ❌ Don't do this - too many small writes\n * await service.setItem('TokenList', 'cache:0x1', [...]);\n * await service.setItem('TokenList', 'cache:0x38', [...]);\n * ```\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n * @param value - JSON data to store (should be 100KB+ for optimal use).\n */\n async setItem(namespace: string, key: string, value: Json): Promise<void> {\n // Adapter handles serialization and wrapping with metadata\n await this.#storage.setItem(namespace, key, value);\n\n // Publish event so other controllers can react to changes\n // Event type: StorageService:itemSet:namespace\n // Payload: [key, value]\n this.#messenger.publish(\n `${SERVICE_NAME}:itemSet:${namespace}` as const,\n key,\n value,\n );\n }\n\n /**\n * Retrieve JSON data from storage.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n * @returns Parsed JSON data or null if not found.\n */\n async getItem(namespace: string, key: string): Promise<Json | null> {\n // Adapter handles deserialization and unwrapping\n return await this.#storage.getItem(namespace, key);\n }\n\n /**\n * Remove data from storage.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n */\n async removeItem(namespace: string, key: string): Promise<void> {\n // Adapter builds full storage key (e.g., mobile: 'storageService:namespace:key')\n await this.#storage.removeItem(namespace, key);\n }\n\n /**\n * Get all keys for a namespace.\n * Delegates to storage adapter which handles filtering.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @returns Array of keys (without prefix) for this namespace.\n */\n async getAllKeys(namespace: string): Promise<string[]> {\n return await this.#storage.getAllKeys(namespace);\n }\n\n /**\n * Clear all data for a namespace.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n */\n async clear(namespace: string): Promise<void> {\n await this.#storage.clear(namespace);\n }\n}\n"]}
|