{"name":"@solid-primitives/storage","version":"1.3.2","keywords":["localStorage","sessionStorage","cookies","solid","primitives"],"author":{"name":"Alex Lohr","email":"alex.lohr@logmein.com"},"license":"MIT","_id":"@solid-primitives/storage@1.3.2","maintainers":[{"name":"thetarnav.","email":"gthetarnav@gmail.com"},{"name":"lexlohr","email":"alex.th.kloss.77@googlemail.com"},{"name":"davedbase","email":"dave.dibiase@gmail.com"}],"homepage":"https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage","bugs":{"url":"https://github.com/solidjs-community/solid-primitives/issues"},"dist":{"shasum":"ea204d443c39c8098faf6c4787851dbea4e56323","tarball":"http://registry-npm.ywwl.com/@solid-primitives/storage/download/@solid-primitives/storage-1.3.2.tgz","fileCount":19,"integrity":"sha512-l9OkMfdkfNJ8mT+7KeNBqfmnMI9nOU3hwePSKT9FVs3uMKR892UCIYUu6tQ2QyaGjOFeAgPTQSLOhh0RcSUkTw==","signatures":[{"sig":"MEUCIQC00MyN2zVQK2kxv7JVCklf5jqcb/FJ2FaOv/wDbqpuMAIgLbJx2XbtmVctoFi6Jx7sOm1H1tNAqA+jaQgxqdba6Ys=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":83260,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjCRwbACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmoPGA//fs1t3nYr3iccbnjZ6TcDvggLuNhWJ3cFOYU1wAeEdzHO5BpR\r\ndy+xunx+KuewdCd0cqmZjqNMJQ8KEIDjfb9VpnuxelX0Er2+eVTXksPcdKKN\r\nbFXR5FmscgAXx6xULKP+rQa/DqqZmnhQblp1fC7HFO9yN7dDUfmbBuGjQ9Kw\r\nOTBs/7kI0WiRSr02OtmBONelM5OHR4CPtKiZOYjc3S9ohIEHsyhig4kODJYP\r\nHyCgPUSmoJwC16dorhCZtD8E1TOWZqVS1wyeqOlwFSsa54Eo45AsM/dSYCes\r\nMq5jfX88mWKd/EeMFOLPN1boPwGFSzQkj8nm025K28pnEoZNWsENHF10lQ81\r\nG81RivYHyNg6e2vNMetrH7Gd6ScjIkJb3WRUm4+UOmntXsQprLl5eCEQ5Kgw\r\n3w65H2Fo3VKsHIsVnOpYYOT6LWqsxQEbE4Ebe3BTFTPEIuwIbu1q8ON5tB+J\r\n/BIXFBIIeRoQ7HT0G67gMZ/8n4Y4wfwd5zg9Fe5fXrlmbJgAtlMEDpOSgdVM\r\n064dblzR7heZ8pcDPtHM5CLqn1ScwU8hwvN1zmUHRu2z3m4e//QLemTmMBBg\r\n0fFMvQxA3Na+KW6BXz0r5syvi1r1PjREXgOC8nt13giO/L7vh3i1k0Pri8w5\r\n9AZD7ZuvD9skYX2YsGUkakFtz3JrtRq38Lg=\r\n=DSv6\r\n-----END PGP SIGNATURE-----\r\n","size":10793,"noattachment":false,"key":"/@solid-primitives/storage/-/@solid-primitives/storage-1.3.2.tgz"},"main":"./dist/index.cjs","type":"module","_from":"file:solid-primitives-storage-1.3.2.tgz","types":"./dist/index.d.ts","module":"./dist/index.js","private":false,"scripts":{"test":"uvu -r solid-register","build":"tsup"},"_npmUser":{"name":"thetarnav.","email":"gthetarnav@gmail.com"},"_resolved":"/tmp/1e91ecf8349169640c18c15210a57f48/solid-primitives-storage-1.3.2.tgz","primitive":{"list":["createStorage","createCookieStorage","createAsyncStorage","createStorageSignal","createLocalStorage","createSessionStorage"],"name":"storage","stage":3,"category":"Browser APIs"},"_integrity":"sha512-l9OkMfdkfNJ8mT+7KeNBqfmnMI9nOU3hwePSKT9FVs3uMKR892UCIYUu6tQ2QyaGjOFeAgPTQSLOhh0RcSUkTw==","repository":{"url":"git+https://github.com/solidjs-community/solid-primitives.git","type":"git"},"_npmVersion":"8.11.0","description":"Primitive that provides reactive wrappers for storage access","directories":{},"sideEffects":false,"_nodeVersion":"17.9.1","_hasShrinkwrap":false,"devDependencies":{"uvu":"^0.5.6","tsup":"^6.2.2","jsdom":"^20.0.0","prettier":"^2.7.1","solid-js":"^1.5.1","typescript":"^4.7.4","solid-register":"^0.2.5"},"peerDependencies":{"solid-js":"^1.3.1"},"_npmOperationalInternal":{"tmp":"tmp/storage_1.3.2_1661541403387_0.13182026362138322","host":"s3://npm-registry-packages"},"readme":"<p>\n  <img width=\"100%\" src=\"https://assets.solidjs.com/banner?type=Primitives&background=tiles&project=Storage\" alt=\"Solid Primitives Storage\">\n</p>\n\n# @solid-primitives/storage\n\n[![turborepo](https://img.shields.io/badge/built%20with-turborepo-cc00ff.svg?style=for-the-badge&logo=turborepo)](https://turborepo.org/)\n[![size](https://img.shields.io/bundlephobia/minzip/@solid-primitives/storage?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/storage)\n[![size](https://img.shields.io/npm/v/@solid-primitives/storage?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/storage)\n[![stage](https://img.shields.io/endpoint?style=for-the-badge&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives#contribution-process)\n\nCreates a primitive to reactively access both synchronous and asynchronous persistent storage APIs similar\nto `localStorage`.\n\n## Installation\n\n```\nnpm install @solid-primitives/storage\n# or\nyarn add @solid-primitives/storage\n```\n\n## How to use it\n\n`makePersisted` allows you to persist a signal or store in any synchronous or asynchronous Storage API:\n\n```ts\nconst [signal, setSignal] = makePersisted(createSignal(\"initial\"), {storage: sessionStorage});\nconst [store, setStore] = makePersisted(createStore({test: true}), {name: \"testing\"});\ntype PersistedOptions<Type, StorageOptions> = {\n  // localStorage is default\n  storage?: Storage | StorageWithOptions | AsyncStorage | AsyncStorageWithOptions,\n  // only required for storage APIs with options\n  storageOptions?: StorageOptions,\n  // key in the storage API\n  name?: \"...\",\n  // JSON.stringify is the default\n  serialize?: (value: Type) => value.toString(),\n  // JSON.parse is the default\n  deserialize?: (value: string) => Type(value),\n  // sync API (see below)\n  sync?: PersistenceSyncAPI\n};\n```\n\n- if no storage is given in options, `localStorage` is used\n- if no name is given in options, a unique identifier from `solid-js` will be the default\n- initial values of signals or stores are not persisted, so they can be safely changed\n- values persisted in asynchronous storage APIs will not overwrite already changed signals or stores\n- setting a persisted signal to undefined or null will remove the item from the storage\n- to use `makePersisted` with other state management APIs, you need some adapter that will project your API to either\n  the output of `createSignal` or `createStore`\n\n### Using `makePersisted` with resources\n\nInstead of wrapping the resource itself, it is far simpler to use the `storage` option of the resource to provide a\npersisted signal or [deep signal](../resource/#createdeepsignal):\n\n```ts\nconst [resource] = createResource(fetcher, { storage: makePersisted(createSignal()) });\n```\n\nIf you are using an asynchronous storage to persist the state of a resource, it might receive an update due to being\ninitialized from the storage before or after the fetcher resolved. If the initialization resolves after the fetcher, its\nresult is discarded not to overwrite more current data.\n\n### Different storage APIs\n\n#### LocalStorage, SessionStorage\n\nIn the browser, we already have `localStorage`, which persists values for the same hostname indefinitely,\nand `sessionStorage`, which does the same for the duration of the browser session, but loses persistence after closing\nthe browser.\n\n#### CookieStorage\n\nAs another storage, `cookieStorage` from this package can be used, which is a `localStorage`-like API to set cookies. It\nwill work in the browser and on solid-start, by parsing the `Cookie` and `Set-Cookie` header and altering\nthe `Set-Cookie` header. Using it in the server without solid-start will not cause errors, but reading and setting cookies\nwill not work, unless you supply `getRequestHeaders() => Headers` and `getResponseHeaders => Headers` to the options.\n\n```ts\n// for example, in express.js request and response headers can usually be accessed like this:\nconst cs = cookieStorage.withOptions({\n  getRequestHeaders: () => req.headers,\n  getResponseHeaders: () => res.headers,\n});\n```\n\n> Please mind that `cookieStorage` **doesn't care** about the path and domain when reading cookies. This might cause issues\n> when using multiple cookies with the same key, but different path or domain.\n\n`cookieStorage` has been augmented with the `.withOptions` method that binds options to the other methods. This allows you\nto use predefined options for your persisted state:\n\n```ts\nconst [state, setState] = makePersisted(createSignal(), {\n  storage: cookieStorage.withOptions({ expires: new Date(+new Date() + 3e10) }),\n});\n```\n\n#### TauriStorage\n\n[Tauri](https://tauri.app) is a lightweight run-time for desktop (and soon also mobile) applications utilizing web front-end frameworks. While it supports `localStorage` and `sessionStorage`, it also has its own store plugin with the benefit of improved stability. To use it, install the required modules both on the side of JavaScript and Rust after setting up the project with the help of their command-line interface:\n\n```bash\nnpm run tauri add store\n```\n\nAlso, it requires a few permissions in `capabilities/default.json`:\n\n```js\n{\n  // other defaults\n  \"permissions\": [\n    // other permissions\n    \"store:allow-get\",\n    \"store:allow-set\",\n    \"store:allow-delete\",\n    \"store:allow-keys\",\n    \"store:allow-clear\"\n  ]\n}\n```\n\nLastly, initialize the plugin in the setup:\n\n```rs\nfn main() {\n    tauri::Builder::default()\n        // initialize store plugin:\n        .plugin(tauri_plugin_store::Builder::new().build())\n        .run(tauri::generate_context!())\n        .expect(\"error while running tauri application\");\n}\n```\n\nOnce these preparations are finished, `tauriStorage(name?: string)` can be used as another storage option. To fallback to localStorage if the app does not run within tauri, you can check for `window.__TAURI_INTERNALS__`:\n\n```ts\nimport { tauriStorage } from \"@solid-primitives/storage/tauri\";\n\nconst storage = window.__TAURI_INTERNALS__ ? tauriStorage() : localStorage;\n```\n\n#### IndexedDB, WebSQL\n\nThere is also [`localForage`](https://localforage.github.io/localForage/), which uses `IndexedDB`, `WebSQL`\nor `localStorage` to provide an asynchronous Storage API that can ideally store much more than the few Megabytes that\nare available in most browsers.\n\n#### Multiplexed storages\n\nYou may want to persist your state to multiple storages as a fallback solution (e.g. localStorage vs. cookieStorage so it\nworks offline and on the server).\n\nIn order to do so, you can use `multiplexStorage`:\n\n```ts\nconst [mode, setMode] = makePersisted(createSignal(\"dark\"), {\n  name: \"mode\",\n  storage: multiplexStorage(localStorage, cookieStorage),\n});\n```\n\nIf none of your storage APIs is asynchronous, the resulting API is synchronous, otherwise it is async. For the getItem\noperation, the first storage that returns a valid value will be the source of truth. So you need to await deletion and\nwriting before you can rely on the result in case of asynchronous storages.\n\n### Sync API\n\nThe storage API has an interesting functionality: if you set an item in one instance of the same page, other instances\nare notified of the change via the storage event so they can elect to automatically update.\n\n#### storageSync\n\nWith `storageSync`, you can use exactly this API in order to sync to external updates to the same storage.\n\n```ts\nconst [state, setState] = makePersisted(createSignal(), { sync: storageSync });\n```\n\n#### messageSync\n\nWith `messageSync`, you can recreate the same functionality for other storages within the client using either the post message API\nor broadcast channel API. If no argument is given, it is using post message, otherwise provide the broadcast channel as argument\n\n```ts\nconst [state, setState] = makePersisted(createSignal(), {\n  storage: customStorage,\n  sync: messageSync(),\n});\n```\n\n#### wsSync\n\nWith `wsSync`, you can create your synchronization API based on a web socket connection (either created yourself or by our\n`@solid-primitives/websocket` package); this allows synchronization between client and server.\n\n```ts\nconst [state, setState] = makePersisted(createSignal(), { sync: wsSync(makeWs(...)) });\n```\n\n#### multiplexSync\n\nYou can also multiplex different synchronization APIs using multiplexSync:\n\n```ts\nconst [state, setState] = makePersisted(createSignal(), {\n  sync: multiplexSync(storageSync, wsSync(ws)),\n});\n```\n\n#### Custom synchronization API\n\nIf you want to create your own sync API, you can use the following pattern:\n\n```ts\nexport type PersistenceSyncData = {\n  key: string;\n  newValue: string | null | undefined;\n  timeStamp: number;\n  url?: string;\n};\n\nexport type PersistenceSyncCallback = (data: PersistenceSyncData) => void;\n\nexport type PersistenceSyncAPI = [\n  /** subscribes to sync */\n  subscribe: (subscriber: PersistenceSyncCallback) => void,\n  update: (key: string, value: string | null | undefined) => void,\n];\n```\n\nYou can use APIs like Pusher or a WebRTC data connection to synchronize your state.\n\n### Tools\n\nIf you want to build your own Storage and don't want to do a `.clear()` method yourself:\n\n```ts\nconst storageWithClearMethod = addClearMethod(storage_without_clear_method);\n```\n\nIf your storage API supports options and you want to add predefined options so it behaves like an API without options,\nyou can add a `.withOptions` method:\n\n```ts\nconst customStorage = addWithOptionsMethod(storage_supporting_options);\nconst boundCustomStorage = customStorage.withOptions(myOptions);\n```\n\n---\n\n### Deprecated primitives:\n\nThe previous implementation proved to be confusing and cumbersome for most people who just wanted to persist their\nsignals and stores, so they are now deprecated and will soon be removed from this package.\n\n`createStorage` is meant to wrap any `localStorage`-like API to be as accessible as\na [Solid Store](https://www.solidjs.com/docs/latest/api#createstore). The main differences are\n\n- that this store is persisted in whatever API is used,\n- that you can only use the topmost layer of the object and\n- that you have additional methods in an object as the third part of the returned tuple:\n\n```ts\nconst [store, setStore, {\n  remove: (key: string) => void;\n  clear: () => void;\n  toJSON: () => ({[key: string]: string });\n}]\n= createStorage({api: sessionStorage, prefix: 'my-app'});\n\nsetStore('key', 'value');\nstore.key; // 'value'\n```\n\nThe props object support the following parameters:\n\n`api`\n: An array of or a single `localStorage`-like storage API; default will be `localStorage` if it exists; an empty array\nor no API will not throw an error, but only ever get `null` and not actually persist anything\n\n`prefix`\n: A string that will be prefixed every key inside the API on set and get operations\n\n`serializer / deserializer`\n: A set of function to filter the input and output; the `serializer` takes an arbitrary object and returns a string,\ne.g. `JSON.stringify`, whereas the `deserializer` takes a string and returns the requested object again.\n\n`options`\n: For APIs that support options as third argument in the `getItem` and `setItem` method (see helper\ntype `StorageWithOptions<O>`), you can add options they will receive on every operation.\n\n---\n\nThere are a number of convenience Methods primed with common storage APIs and our own version to use cookies:\n\n```ts\ncreateLocalStorage();\ncreateSessionStorage();\ncreateCookieStorage();\n```\n\n---\n\n#### Asynchronous storage APIs\n\nIn case you have APIs that persist data on the server or via `ServiceWorker` in\na [`CookieStore`](https://wicg.github.io/cookie-store/#CookieStore), you can wrap them into an asynchronous\nstorage (`AsyncStorage` or `AsyncStorageWithOptions` API) and use them with `createAsyncStorage`:\n\n```ts\ntype CookieStoreOptions = {\n  path: string;\n  domain: string;\n  expires: DOMTimeStamp;\n  sameSite: \"None\" | \"Lax\" | \"Strict\"\n}\nconst CookieStoreAPI: AsyncStorageWithOptions<CookieStoreOptions> = {\n  getItem: (key) => cookieStore.get(key),\n  getAll: () => cookieStore.getAll(),\n  setItem: (key: string, value: string, options: CookieStoreOptions = {}) => cookieStore.set({\n    ...options, name, value\n  }),\n  removeItem: (key) => cookieStore.delete(key),\n  clear: async () => {\n    const all = await cookieStore.getAll();\n    for (const key of all) {\n      await cookieStore.delete(key);\n    }\n  },\n  key: async (index: number) => {\n    const all = await cookieStore.getAll();\n    return Object.keys(all)[index];\n  }\n}\n)\n;\n\nconst [cookies, setCookie, {\n  remove: (key: string) => void;\n  clear: () => void;\n  toJSON: () => ({[key: string]: string\n})\n;\n}]\n= createAsyncStorage({api: CookieStoreAPI, prefix: 'my-app', sync: false});\n\nawait setStore('key', 'value');\nawait store.key; // 'value'\n```\n\nIt works exactly like a synchronous storage, with the exception that you have to `await` every single return value. Once\nthe `CookieStore` API becomes more prevalent, we will integrate support out of the box.\n\nIf you cannot use `document.cookie`, you can overwrite the entry point using the following tuple:\n\n```ts\nimport {cookieStorage} from '@solid-primitives/storage';\n\ncookieStorage._cookies = [object\n:\n{\n  [name\n:\n  string\n]:\n  CookieProxy\n}\n,\nname: string\n]\n;\n```\n\nIf you need to abstract an API yourself, you can use a getter and a setter:\n\n```ts\nconst CookieAbstraction = {\n  get cookie() {\n    return myCookieJar.toString()\n  }\n  set cookie(cookie) {\n    const data = {};\n    cookie.replace(/([^=]+)=(?:([^;]+);?)/g, (_, key, value) => {\n      data[key] = value\n    });\n    myCookieJar.set(data);\n  }\n}\ncookieStorage._cookies = [CookieAbstraction, 'cookie'];\n```\n\n---\n\n`createStorageSignal` is meant for those cases when you only need to conveniently access a single value instead of full\naccess to the storage API:\n\n```ts\nconst [value, setValue] = createStorageSignal(\"value\", { api: cookieStorage });\n\nsetValue(\"value\");\nvalue(); // 'value'\n```\n\nAs a convenient additional method, you can also use `createCookieStorageSignal(key, initialValue, options)`.\n\n---\n\n### Options\n\nThe properties of your `createStorage`/`createAsyncStorage`/`createStorageSignal` props are:\n\n- `api`: the (synchronous or\n  asynchronous) [Storage-like API](https://developer.mozilla.org/de/docs/Web/API/Web_Storage_API), default\n  is `localStorage`\n- `deserializer` (optional): a `deserializer` or parser for the stored data\n- `serializer` (optional): a `serializer` or string converter for the stored data\n- `options` (optional): default options for the set-call of Storage-like API, if supported\n- `prefix` (optional): a prefix for the Storage keys\n- `sync` (optional): if set to\n  false, [event synchronization](https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent) is disabled\n\n## Demo\n\n[Live Demo](https://primitives.solidjs.community/playground/storage) - [Sources](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage/dev)\n\n## Changelog\n\nSee [CHANGELOG.md](./CHANGELOG.md)\n","publish_time":1661541403602,"_cnpm_publish_time":1661541403602,"dist-tags":{"beta":"1.3.7-beta.0","latest":"4.4.0","next":"5.0.0-next.8"}}