@randajan/vault-kit
Version:
A tiny and universal data vault that behaves like a writable file system. Store, sync, forget. Works on client and server.
157 lines (113 loc) โข 5.51 kB
Markdown
# @randajan/vault-kit
[](https://www.npmjs.com/package/@randajan/vault-kit) [](https://standardjs.com)
## ๐งฌ Universal Glue for your Data Flow
vault-kit is an ultra-lightweight, event-driven sync layer between any data producer and data consumer.
Think of it as programmable glue โ seamless, flexible, and fast.
- ๐ง System-agnostic โ Works in Node.js, browsers, or anywhere JavaScript runs.
- ๐ฆ Dual-format ready โ Distributed as both CommonJS (CJS) and ECMAScript Modules (ESM).
- ๐ Backend-agnostic โ Easily plugs into REST, WebSocket, GraphQL, localStorage, memory, custom APIs, and more.
- ๐ ๏ธ Fully modular โ Bring your own transport logic. Don't like assumptions? Perfect.
- ๐ 3-way sync โ From local to remote, remote to local, and passive remote-driven updates.
- ๐งฉ Composable โ Chainable, embeddable, stackable. Use one or many.
- ๐ Cache + Sync โ Transparent in-memory caching with lazy fetch and optimistic write.
- ๐ก Minimal, but mighty โ No dependencies. Pure logic. Easy to read. Easy to extend.
- ๐ Perfect for real-time apps โ Ideal with socket.io, signals, or any reactive system.
Use it to orchestrate state, power form sync, or bridge the gap between local UI and remote data.
Vault is your contractless API. A wire that listens. A sync pulse.
## โจ Purpose
It acts like a **virtual file system** where each file is identified by an `id`. It supports:
- **Local to Remote** updates (`vault.set โ remote.push`)
- **Remote to Local** updates (`remote.pull โ vault.get`)
- **Passive Sync** (via `remote.init`)
- **Events** triggered on any change
- **Automatic Caching** of the last known state
The `id` is passed as the second argument and is optional if `hasMany` is not used.
## ๐งฉ Options
All options are passed into the vault constructor:
```js
import createVault, { Vault } from "@randajan/vault-kit";
const vault = new Vault({ /* options */ }) || createVault({ /* options */ });
```
### General Options
| Option | Type | Description |
|---------------|---------------------------|-------------|
| `hasMany` | `boolean` | Allow multiple IDs or not |
| `readonly` | `boolean` | Prevents all modifications if `true` |
| `remote` | `object` | Remote logic (see below) |
| `ttl` | `number` | Time-to-live in ms for each value |
| `onRequest` | `function` or `string` | Hook or key for extracting data from remote result |
| `onResponse` | `function` or `string` | Hook or key for extracting data from remote result |
| `emitter` | `(emit, ctx, ...args) => void` | Custom event dispatcher |
## ๐ Remote Setup
| Key | Type | Description |
|-----------|----------------------------------|-------------|
| `init` | `(set, forget) => void` | Passive sync setup |
| `pull` | `(id, ...args) => Promise<data>` | Called during `get()` |
| `push` | `(data, id, ...args) => Promise<data>` | Called during `set()` |
| `timeout` | `number` | Optional timeout for remote operations (default 5000ms) |
If pull or push fails, all pending related operations fail together.
## โก Actions & Reactions
Actions are accessible on the client via:
```js
await vault.act.myAction(params, ...args);
```
There is **no need to declare them** on the client. On the server, define reactions:
```js
new Vault({
reactions: {
myAction: async (params, ctx) => ({ value: 42 })
},
onRequest: "value"
});
```
This extracts only the `value` from the response for store but client will still receive whole response
## ๐ฏ Behavior
- `readonly: true` blocks both `.set()` and `.act.*`
- `null` / `undefined` values **do not remove** records
- `emitter` lets you **redirect, filter, or rewrite** events
- TTL is **lazy**: entry expires on access, not in background
- `withActions` creates a proxy to call any `vault.act.action()` via property access
## โ๏ธ API Reference
Same API for single and multi-record usage:
| Method | Description |
|----------------|-------------|
| `get(id?, ...args)` | Read local or pull from remote |
| `set(data, id?, ...args)` | Save local and push to remote |
| `act(action, params, ...args)` | Calls a reaction |
| `reset(id?, ...args)` | Clears entry and resets state |
| `getStatus(id?)` | Returns current status |
| `getData(id?)` | Returns last known value |
| `has(id, ...args)` | Checks if entry exists |
| `on(fn)` | Subscribe to all updates |
| `once(fn)` | Subscribe once to update |
| `forEach(fn)` | Iterate entries |
| `collect(obj, fn)` | Iterate and collect into object |
## ๐งช Example
```js
const server = new Vault({
reactions: {
echo: async ({ text }) => ({ message: text + "!" })
},
onRequest: "message"
});
const client = new Vault({
ttl:10000,
remote: {
pull: id => fetch("/data/" + id).then(r => r.json()),
push: (data, id) => fetch("/data/" + id, { method: "POST", body: JSON.stringify(data) }),
timeout: 3000
},
onResponse: "message"
});
await vault.act.echo({ text: "Hello" }); // returns "Hello!"
```
## ๐ License
MIT ยฉ [randajan](https://github.com/randajan)