npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@sl1900/svelte-webext-stores

v0.0.15

Published

Svelte stores that synchronizes to WebExtension storage.

Downloads

2

Readme

svelte-webext-stores

Svelte stores that are synchronized with extension storage.

Note: This library is currently in alpha development, and is subject to breaking changes with or without warning.

Features

  • Different storage types support: chrome.storage (either MV2 or MV3), browser.storage (including webextension-polyfill), and even non-extension storage such as window.localStorage and window.sessionStorage are supported out of the box.
  • Automatically synchronizes to and from storage backend.
  • TypeScript support: This library is fully written in TypeScript, and the distributed package includes TypeScript declarations.
  • Custom implementations: Create and use your own custom storage backends or synchronized stores by implementing IStorageBackend or ISyncStore respectively.

Getting started

Installation

npm install -D svelte-webext-stores

or

yarn add -D svelte-webext-stores

Quick Usage

storage.js

import { webExtStores } from 'svelte-webext-stores';

// Instantiate default store handler, which is backed by MV2 chrome.storage.local
const stores = webExtStores();
// Register a new synchronized store with storage key 'count' and default value of 1
export const count = stores.addSyncStore('count', 1);

App.svelte

<script>
  import { count } from './storage.js';

  function addCount() {
    $count += 1;
  }
</script>

<button on:click={addCount}>Count: {$count}</button>

Advanced Usage

Storage Backends

This library supports and exports the following storage options out of the box. To use a provided storage option, simply import it and pass it into webExtStores.

| Storage | Description | | --- | --- | | storageMV2 | Chrome Manifest Version 2 (callback API). | | storageMV3 | Chrome Manifest Version 3 (Promise API). | | storageWebExt | Mozilla WebExtension (browser API), including webextension-polyfill. | | storageLegacy | Legacy/non-extension storage (localStorage or sessionStorage). |

To set the storage area/type, pass the corresponding string parameter.

| Storage | Allowed parameter | Default | --- | --- | --- | | storageMV2, storageMV3, storageWebExt | 'local' | 'sync' | 'managed' | 'local' | | storageLegacy | 'session' | 'local' | 'session'

Example:

import { webExtStores, storageWebExt } from 'svelte-webext-stores';

// Uses the Mozilla WebExtension browser API in the 'sync' area.
const stores = webExtStores(storageWebExt('sync'));

More information on the IStorageBackend interface that is implemented by all the above storage backends can be found here.

Synchronized Stores

All provided synchronized stores below implements the ISyncStore interface. More information can be found here.

SyncStore

Standard store that synchronizes to the storage backend. Uses Svelte writable to implement the Svelte store contract.

WebExtStores.addSyncStore<T>(
  key: string,
  defaultValue: T,
  syncFromExternal = true,
  versionedOptions?: VersionedOptions
): SyncStore<T>

| Parameter | Description | | --- | --- | | key | Storage key | | defaultValue | Store's default value | | syncFromExternal | Whether store should be updated when storage value is updated externally | | versionedOptions | Enables options for migrating storage values from an older version to a newer version |

Aside from methods derived from ISyncStore, SyncStore also contains the following methods:

| Methods | Signature | Description | | --- | --- | --- | | ready | ready: () => Promise<void> | Ensure that any async initialization process (such as initial update from backend) has been completed. You typically don't need to manually call this unless you wish to sync the store to the storage backend before any of get(), set(), subscribe() or update() is called. | | reset | reset: () => Promise<void> | Reset store value to default value. | | update | update: (updater: (value: T) => T) => Promise<void> | Update value using callback and inform subscribers. |

LookupStore

Synchronized store for Record<string, any> objects. LookupStore is derived from and is functionally similar to SyncStore, with additional convenience methods for getting and setting the stored object's property values using property keys.

WebExtStores.addLookupStore<T extends Record<string, any>>(
  key: string,
  defaultValue: T,
  syncFromExternal = true,
  versionedOptions?: VersionedOptions<T>
): LookupStore<T>

| Methods | Signature | Description | | --- | --- | --- | | getItem | getItem: <R extends T[keyof T]>(key: keyof T) => Promise<R> | Get property value. | | setItem | setItem: <V extends T[keyof T]>(key: keyof T, value: V) => Promise<void> | Set property value. |

Example:

import { webExtStores } from 'svelte-webext-stores';

const stores = webExtStores();
export const obj = stores.addLookupStore('obj', { a: 1, b: false, c: '3' });


const a = await obj.getItem('a'); // Returns 1
await obj.setItem('b', true); // Object is now { a: 1, b: false, c: '3' }

You can also easily add these convenience methods to your custom ISyncStore implementations. More information can be found here.

Versioned Store Values and Migration

SyncStore and its derivatives has the optional parameter versionedOptions. When the parameter is provided, it keeps track of the current store's version to enable ease of migrating values from an older store version to the current version. This can be useful to migrate breaking changes on the stored data without reseting its value to default.

VersionedOptions properties are as follows:

| Property | Type | Descrption | | --- | --- | --- | | version | number | Current version number. Do not use -1. | | seperator | string | Separator between key and version. | | migrations | Map<number, (oldValue: any) => T> | Map for migrating values. Keys are the old version to match against, and values are callbacks that accepts the value found from the given old version and returns the corresponding value for the current version. Use the key -1 to migrate from a versionless store. |

SyncStores that are provided with the versionedOptions parameter are stored as ${key}${seperator}${version} internally. When an older version that matches any of the keys in the Map is found, its value is passed to the callback, the returned value is stored and the old version is removed.

// Initial store
export const size = stores.addSyncStore('size', 500);

// Example usage in svelte
window.resizeTo($size, $size);
// To migrate to a new value, replace the old declaration
const sizeMigrations = new Map();
sizeMigrations.set(-1, (oldValue) => `${oldValue}x${oldValue * 2}`);

export const size = stores.addSyncStore(
  'size',
  '500x1000',
  true,
  {
    version: 1,
    seperator: '$',
    migrations: sizeMigrations
  }
);

// Example usage in svelte
const [width, height] = $size.split('x');
window.resizeTo(width, height);