@wxt-dev/storage 1.2.8 → 1.3.0

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/dist/index.d.mts CHANGED
@@ -7,18 +7,18 @@ interface WxtStorage {
7
7
  * Get an item from storage, or return `null` if it doesn't exist.
8
8
  *
9
9
  * @example
10
- * await storage.getItem<number>("local:installDate");
10
+ * await storage.getItem<number>('local:installDate');
11
11
  */
12
12
  getItem<TValue>(key: StorageItemKey, opts: GetItemOptions<TValue> & {
13
13
  fallback: TValue;
14
14
  }): Promise<TValue>;
15
15
  getItem<TValue>(key: StorageItemKey, opts?: GetItemOptions<TValue>): Promise<TValue | null>;
16
16
  /**
17
- * Get multiple items from storage. The return order is guaranteed to be the same as the order
18
- * requested.
17
+ * Get multiple items from storage. The return order is guaranteed to be the
18
+ * same as the order requested.
19
19
  *
20
20
  * @example
21
- * await storage.getItems(["local:installDate", "session:someCounter"]);
21
+ * await storage.getItems(['local:installDate', 'session:someCounter']);
22
22
  */
23
23
  getItems(keys: Array<StorageItemKey | WxtStorageItem<any, any> | {
24
24
  key: StorageItemKey;
@@ -28,11 +28,11 @@ interface WxtStorage {
28
28
  value: any;
29
29
  }>>;
30
30
  /**
31
- * Return an object containing metadata about the key. Object is stored at `key + "$"`. If value
32
- * is not an object, it returns an empty object.
31
+ * Return an object containing metadata about the key. Object is stored at
32
+ * `key + "$"`. If value is not an object, it returns an empty object.
33
33
  *
34
34
  * @example
35
- * await storage.getMeta("local:installDate");
35
+ * await storage.getMeta('local:installDate');
36
36
  */
37
37
  getMeta<T extends Record<string, unknown>>(key: StorageItemKey): Promise<T>;
38
38
  /**
@@ -46,21 +46,22 @@ interface WxtStorage {
46
46
  meta: any;
47
47
  }>>;
48
48
  /**
49
- * Set a value in storage. Setting a value to `null` or `undefined` is equivalent to calling
50
- * `removeItem`.
49
+ * Set a value in storage. Setting a value to `null` or `undefined` is
50
+ * equivalent to calling `removeItem`.
51
51
  *
52
52
  * @example
53
- * await storage.setItem<number>("local:installDate", Date.now());
53
+ * await storage.setItem<number>('local:installDate', Date.now());
54
54
  */
55
55
  setItem<T>(key: StorageItemKey, value: T | null): Promise<void>;
56
56
  /**
57
- * Set multiple values in storage. If a value is set to `null` or `undefined`, the key is removed.
57
+ * Set multiple values in storage. If a value is set to `null` or `undefined`,
58
+ * the key is removed.
58
59
  *
59
60
  * @example
60
- * await storage.setItem([
61
+ * await storage.setItem([
61
62
  * { key: "local:installDate", value: Date.now() },
62
63
  * { key: "session:someCounter, value: 5 },
63
- * ]);
64
+ * ]);
64
65
  */
65
66
  setItems(values: Array<{
66
67
  key: StorageItemKey;
@@ -70,11 +71,11 @@ interface WxtStorage {
70
71
  value: any;
71
72
  }>): Promise<void>;
72
73
  /**
73
- * Sets metadata properties. If some properties are already set, but are not included in the
74
- * `properties` parameter, they will not be removed.
74
+ * Sets metadata properties. If some properties are already set, but are not
75
+ * included in the `properties` parameter, they will not be removed.
75
76
  *
76
77
  * @example
77
- * await storage.setMeta("local:installDate", { appVersion });
78
+ * await storage.setMeta('local:installDate', { appVersion });
78
79
  */
79
80
  setMeta<T extends Record<string, unknown>>(key: StorageItemKey, properties: T | null): Promise<void>;
80
81
  /**
@@ -93,12 +94,10 @@ interface WxtStorage {
93
94
  * Removes an item from storage.
94
95
  *
95
96
  * @example
96
- * await storage.removeItem("local:installDate");
97
+ * await storage.removeItem('local:installDate');
97
98
  */
98
99
  removeItem(key: StorageItemKey, opts?: RemoveItemOptions): Promise<void>;
99
- /**
100
- * Remove a list of keys from storage.
101
- */
100
+ /** Remove a list of keys from storage. */
102
101
  removeItems(keys: Array<StorageItemKey | WxtStorageItem<any, any> | {
103
102
  key: StorageItemKey;
104
103
  options?: RemoveItemOptions;
@@ -106,37 +105,32 @@ interface WxtStorage {
106
105
  item: WxtStorageItem<any, any>;
107
106
  options?: RemoveItemOptions;
108
107
  }>): Promise<void>;
109
- /**
110
- * Removes all items from the provided storage area.
111
- */
108
+ /** Removes all items from the provided storage area. */
112
109
  clear(base: StorageArea): Promise<void>;
113
110
  /**
114
111
  * Remove the entire metadata for a key, or specific properties by name.
115
112
  *
116
113
  * @example
117
- * // Remove all metadata properties from the item
118
- * await storage.removeMeta("local:installDate");
114
+ * // Remove all metadata properties from the item
115
+ * await storage.removeMeta('local:installDate');
119
116
  *
120
- * // Remove only specific the "v" field
121
- * await storage.removeMeta("local:installDate", "v")
117
+ * // Remove only specific the "v" field
118
+ * await storage.removeMeta('local:installDate', 'v');
122
119
  */
123
120
  removeMeta(key: StorageItemKey, properties?: string | string[]): Promise<void>;
124
- /**
125
- * Return all the items in storage.
126
- */
121
+ /** Return all the items in storage. */
127
122
  snapshot(base: StorageArea, opts?: SnapshotOptions): Promise<Record<string, unknown>>;
128
123
  /**
129
- * Restores the results of `snapshot`. If new properties have been saved since the snapshot, they are
130
- * not overridden. Only values existing in the snapshot are overridden.
124
+ * Restores the results of `snapshot`. If new properties have been saved since
125
+ * the snapshot, they are not overridden. Only values existing in the snapshot
126
+ * are overridden.
131
127
  */
132
128
  restoreSnapshot(base: StorageArea, data: any): Promise<void>;
133
- /**
134
- * Watch for changes to a specific key in storage.
135
- */
129
+ /** Watch for changes to a specific key in storage. */
136
130
  watch<T>(key: StorageItemKey, cb: WatchCallback<T | null>): Unwatch;
137
- /**
138
- * Remove all watch listeners.
139
- */
131
+ /** Watch for changes to a specific key's metadata in storage. */
132
+ watchMeta<T extends Record<string, unknown>>(key: StorageItemKey, cb: WatchCallback<T>): Unwatch;
133
+ /** Remove all watch listeners. */
140
134
  unwatch(): void;
141
135
  /**
142
136
  * Define a storage item with a default value, type, or versioning.
@@ -156,64 +150,43 @@ interface WxtStorage {
156
150
  defineItem<TValue, TMetadata extends Record<string, unknown> = {}>(key: StorageItemKey, options: WxtStorageItemOptions<TValue>): WxtStorageItem<TValue | null, TMetadata>;
157
151
  }
158
152
  interface WxtStorageItem<TValue, TMetadata extends Record<string, unknown>> {
159
- /**
160
- * The storage key passed when creating the storage item.
161
- */
153
+ /** The storage key passed when creating the storage item. */
162
154
  key: StorageItemKey;
163
- /**
164
- * @deprecated Renamed to fallback, use it instead.
165
- */
155
+ /** @deprecated Renamed to fallback, use it instead. */
166
156
  defaultValue: TValue;
167
- /**
168
- * The value provided by the `fallback` option.
169
- */
157
+ /** The value provided by the `fallback` option. */
170
158
  fallback: TValue;
171
- /**
172
- * Get the latest value from storage.
173
- */
159
+ /** Get the latest value from storage. */
174
160
  getValue(): Promise<TValue>;
175
- /**
176
- * Get metadata.
177
- */
161
+ /** Get metadata. */
178
162
  getMeta(): Promise<NullablePartial<TMetadata>>;
179
- /**
180
- * Set the value in storage.
181
- */
163
+ /** Set the value in storage. */
182
164
  setValue(value: TValue): Promise<void>;
183
- /**
184
- * Set metadata properties.
185
- */
165
+ /** Set metadata properties. */
186
166
  setMeta(properties: NullablePartial<TMetadata>): Promise<void>;
187
- /**
188
- * Remove the value from storage.
189
- */
167
+ /** Remove the value from storage. */
190
168
  removeValue(opts?: RemoveItemOptions): Promise<void>;
191
- /**
192
- * Remove all metadata or certain properties from metadata.
193
- */
169
+ /** Remove all metadata or certain properties from metadata. */
194
170
  removeMeta(properties?: string[]): Promise<void>;
195
- /**
196
- * Listen for changes to the value in storage.
197
- */
171
+ /** Listen for changes to the value in storage. */
198
172
  watch(cb: WatchCallback<TValue>): Unwatch;
173
+ /** Listen for changes to the metadata in storage. */
174
+ watchMeta(cb: WatchCallback<NullablePartial<TMetadata>>): Unwatch;
199
175
  /**
200
- * If there are migrations defined on the storage item, migrate to the latest version.
176
+ * If there are migrations defined on the storage item, migrate to the latest
177
+ * version.
201
178
  *
202
- * **This function is ran automatically whenever the extension updates**, so you don't have to call it
203
- * manually.
179
+ * **This function is ran automatically whenever the extension updates**, so
180
+ * you don't have to call it manually.
204
181
  */
205
182
  migrate(): Promise<void>;
206
183
  }
207
184
  type StorageArea = 'local' | 'session' | 'sync' | 'managed';
208
185
  type StorageItemKey = `${StorageArea}:${string}`;
209
186
  interface GetItemOptions<T> {
210
- /**
211
- * @deprecated Renamed to `fallback`, use it instead.
212
- */
187
+ /** @deprecated Renamed to `fallback`, use it instead. */
213
188
  defaultValue?: T;
214
- /**
215
- * Default value returned when `getItem` would otherwise return `null`.
216
- */
189
+ /** Default value returned when `getItem` would otherwise return `null`. */
217
190
  fallback?: T;
218
191
  }
219
192
  interface RemoveItemOptions {
@@ -226,19 +199,15 @@ interface RemoveItemOptions {
226
199
  }
227
200
  interface SnapshotOptions {
228
201
  /**
229
- * Exclude a list of keys. The storage area prefix should be removed since the snapshot is for a
230
- * specific storage area already.
202
+ * Exclude a list of keys. The storage area prefix should be removed since the
203
+ * snapshot is for a specific storage area already.
231
204
  */
232
205
  excludeKeys?: string[];
233
206
  }
234
207
  interface WxtStorageItemOptions<T> {
235
- /**
236
- * @deprecated Renamed to `fallback`, use it instead.
237
- */
208
+ /** @deprecated Renamed to `fallback`, use it instead. */
238
209
  defaultValue?: T;
239
- /**
240
- * Default value returned when `getValue` would otherwise return `null`.
241
- */
210
+ /** Default value returned when `getValue` would otherwise return `null`. */
242
211
  fallback?: T;
243
212
  /**
244
213
  * If passed, a value in storage will be initialized immediately after
@@ -248,39 +217,36 @@ interface WxtStorageItemOptions<T> {
248
217
  */
249
218
  init?: () => T | Promise<T>;
250
219
  /**
251
- * Provide a version number for the storage item to enable migrations. When changing the version
252
- * in the future, migration functions will be ran on application startup.
220
+ * Provide a version number for the storage item to enable migrations. When
221
+ * changing the version in the future, migration functions will be ran on
222
+ * application startup.
253
223
  */
254
224
  version?: number;
255
225
  /**
256
- * A map of version numbers to the functions used to migrate the data to that version.
226
+ * A map of version numbers to the functions used to migrate the data to that
227
+ * version.
257
228
  */
258
229
  migrations?: Record<number, (oldValue: any) => any>;
259
230
  /**
260
231
  * Print debug logs, such as migration process.
232
+ *
261
233
  * @default false
262
234
  */
263
235
  debug?: boolean;
264
- /**
265
- * A callback function that runs on migration complete.
266
- */
236
+ /** A callback function that runs on migration complete. */
267
237
  onMigrationComplete?: (migratedValue: T, targetVersion: number) => void;
268
238
  }
269
239
  type StorageAreaChanges = {
270
240
  [key: string]: Browser.storage.StorageChange;
271
241
  };
272
242
  /**
273
- * Same as `Partial`, but includes `| null`. It makes all the properties of an object optional and
274
- * nullable.
243
+ * Same as `Partial`, but includes `| null`. It makes all the properties of an
244
+ * object optional and nullable.
275
245
  */
276
246
  type NullablePartial<T> = { [key in keyof T]+?: T[key] | undefined | null };
277
- /**
278
- * Callback called when a value in storage is changed.
279
- */
247
+ /** Callback called when a value in storage is changed. */
280
248
  type WatchCallback<T> = (newValue: T, oldValue: T) => void;
281
- /**
282
- * Call to remove a watch listener
283
- */
249
+ /** Call to remove a watch listener */
284
250
  type Unwatch = () => void;
285
251
  declare class MigrationError extends Error {
286
252
  key: string;
package/dist/index.mjs CHANGED
@@ -1,12 +1,36 @@
1
1
  import { browser } from "@wxt-dev/browser";
2
- import { Mutex } from "async-mutex";
3
- import { dequal } from "dequal/lite";
4
-
2
+ import { withLock } from "superlock";
3
+ //#region ../../node_modules/.bun/dequal@2.0.3/node_modules/dequal/lite/index.mjs
4
+ var has = Object.prototype.hasOwnProperty;
5
+ function dequal(foo, bar) {
6
+ var ctor, len;
7
+ if (foo === bar) return true;
8
+ if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
9
+ if (ctor === Date) return foo.getTime() === bar.getTime();
10
+ if (ctor === RegExp) return foo.toString() === bar.toString();
11
+ if (ctor === Array) {
12
+ if ((len = foo.length) === bar.length) while (len-- && dequal(foo[len], bar[len]));
13
+ return len === -1;
14
+ }
15
+ if (!ctor || typeof foo === "object") {
16
+ len = 0;
17
+ for (ctor in foo) {
18
+ if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;
19
+ if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;
20
+ }
21
+ return Object.keys(bar).length === len;
22
+ }
23
+ }
24
+ return foo !== foo && bar !== bar;
25
+ }
26
+ //#endregion
5
27
  //#region src/index.ts
6
28
  /**
7
- * Simplified storage APIs with support for versioned fields, snapshots, metadata, and item definitions.
29
+ * Simplified storage APIs with support for versioned fields, snapshots,
30
+ * metadata, and item definitions.
8
31
  *
9
32
  * See [the guide](https://wxt.dev/storage.html) for more information.
33
+ *
10
34
  * @module @wxt-dev/storage
11
35
  */
12
36
  const storage = createStorage();
@@ -46,7 +70,7 @@ function createStorage() {
46
70
  return newFields;
47
71
  };
48
72
  const getValueOrFallback = (value, fallback) => value ?? fallback ?? null;
49
- const getMetaValue = (properties) => typeof properties === "object" && !Array.isArray(properties) ? properties : {};
73
+ const getMetaValue = (properties) => properties != null && typeof properties === "object" && !Array.isArray(properties) ? properties : {};
50
74
  const getItem = async (driver, driverKey, opts) => {
51
75
  return getValueOrFallback(await driver.getItem(driverKey), opts?.fallback ?? opts?.defaultValue);
52
76
  };
@@ -79,6 +103,7 @@ function createStorage() {
79
103
  }
80
104
  };
81
105
  const watch = (driver, driverKey, cb) => driver.watch(driverKey, cb);
106
+ const watchMeta = (driver, driverKey, cb) => watch(driver, getMetaKey(driverKey), (newValue, oldValue) => cb(getMetaValue(newValue), getMetaValue(oldValue)));
82
107
  return {
83
108
  getItem: async (key, opts) => {
84
109
  const { driver, driverKey } = resolveKey(key);
@@ -247,6 +272,10 @@ function createStorage() {
247
272
  const { driver, driverKey } = resolveKey(key);
248
273
  return watch(driver, driverKey, cb);
249
274
  },
275
+ watchMeta: (key, cb) => {
276
+ const { driver, driverKey } = resolveKey(key);
277
+ return watchMeta(driver, driverKey, cb);
278
+ },
250
279
  unwatch() {
251
280
  Object.values(drivers).forEach((driver) => {
252
281
  driver.unwatch();
@@ -290,9 +319,9 @@ function createStorage() {
290
319
  const migrationsDone = opts?.migrations == null ? Promise.resolve() : migrate().catch((err) => {
291
320
  console.error(`[@wxt-dev/storage] Migration failed for ${key}`, err);
292
321
  });
293
- const initMutex = new Mutex();
322
+ const initLock = withLock();
294
323
  const getFallback = () => opts?.fallback ?? opts?.defaultValue ?? null;
295
- const getOrInitValue = () => initMutex.runExclusive(async () => {
324
+ const getOrInitValue = () => initLock(async () => {
296
325
  const value = await driver.getItem(driverKey);
297
326
  if (value != null || opts?.init == null) return value;
298
327
  const newValue = await opts.init();
@@ -338,6 +367,7 @@ function createStorage() {
338
367
  return await removeMeta(driver, driverKey, properties);
339
368
  },
340
369
  watch: (cb) => watch(driver, driverKey, (newValue, oldValue) => cb(newValue ?? getFallback(), oldValue ?? getFallback())),
370
+ watchMeta: (cb) => watchMeta(driver, driverKey, cb),
341
371
  migrate
342
372
  };
343
373
  }
@@ -421,6 +451,5 @@ var MigrationError = class extends Error {
421
451
  this.version = version;
422
452
  }
423
453
  };
424
-
425
454
  //#endregion
426
- export { MigrationError, storage };
455
+ export { MigrationError, storage };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@wxt-dev/storage",
3
3
  "description": "Web extension storage API provided by WXT, supports all browsers.",
4
- "version": "1.2.8",
4
+ "version": "1.3.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -24,17 +24,26 @@
24
24
  },
25
25
  "license": "MIT",
26
26
  "funding": "https://github.com/sponsors/wxt-dev",
27
+ "scripts": {
28
+ "build": "buildc -- tsdown --deps.onlyBundle dequal",
29
+ "check": "buildc --deps-only -- check",
30
+ "test": "buildc --deps-only -- vitest",
31
+ "test:coverage": "bun run test run --coverage",
32
+ "prepack": "bun run build"
33
+ },
27
34
  "dependencies": {
28
- "async-mutex": "^0.5.0",
29
- "dequal": "^2.0.3",
30
- "@wxt-dev/browser": "^0.1.37"
35
+ "@wxt-dev/browser": ">=0.1",
36
+ "superlock": "^1.3.2"
31
37
  },
32
38
  "devDependencies": {
39
+ "@aklinker1/buildc": "^1.1.7",
33
40
  "@webext-core/fake-browser": "^1.3.4",
34
- "oxlint": "^1.43.0",
35
- "publint": "^0.3.17",
36
- "typescript": "^5.9.3",
37
- "vitest": "^4.0.18"
41
+ "dequal": "^2.0.3",
42
+ "oxlint": "^1.63.0",
43
+ "publint": "^0.3.18",
44
+ "tsdown": "^0.21.0",
45
+ "typescript": "^6.0.3",
46
+ "vitest": "^4.1.10"
38
47
  },
39
48
  "module": "./dist/index.mjs",
40
49
  "types": "./dist/index.d.mts",
@@ -46,10 +55,5 @@
46
55
  },
47
56
  "files": [
48
57
  "dist"
49
- ],
50
- "scripts": {
51
- "build": "buildc -- tsdown",
52
- "check": "buildc --deps-only -- check",
53
- "test": "buildc --deps-only -- vitest"
54
- }
55
- }
58
+ ]
59
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 Aaron
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.