@bazariodev/hopper
v2.0.1
Published
Memory and IndexedDB history, FIFO outboxes, and native key-value storage.
Readme
@bazariodev/hopper
Hopper stores bounded JSON history, FIFO upload batches, and native IndexedDB values. The application controls data access, account scope, and delivery.
Install
pnpm add @bazariodev/hopperNode.js: ^22.12.0 || ^24.0.0 || >=26.0.0. No peer dependencies.
Persistent entries need IndexedDB. Protected history and outboxes also need Web Locks.
| Entry | Runtime imports |
| --- | --- |
| Root | None |
| /indexeddb, /outbox/indexeddb | Baton, Coordination |
| /outbox | Coordination |
| /key-value/indexeddb | None |
Usage
import { createMemoryStore } from '@bazariodev/hopper';
const store = createMemoryStore({ maxTotalSize: 1_000_000 });
store.write({
runId: 'capture-1',
seq: 1,
at: Date.now(),
sample: { value: 42 },
});
const records = await store.query({ buckets: ['default'] });Supply a nonempty runId, a nonnegative safe integer seq, and a finite millisecond at.
Optional bucket must be a string. Its default is default. Other fields hold JSON data.
Persistent history
import { createIndexedDbStore } from '@bazariodev/hopper/indexeddb';
const scope = authenticatedSession.storageKey;
const store = createIndexedDbStore({
databaseName: JSON.stringify(['diagnostics', scope, 'history']),
lockName: JSON.stringify(['diagnostics-owner', scope, 'history']),
});
store.write({ runId: 'capture-1', seq: 1, at: Date.now(), bucket: 'samples', value: 42 });
await store.flush();The application supplies authenticatedSession.storageKey after authentication.
Use distinct, stable account scopes. All writers of one database must use the same lock name.
Key-value storage
import { createIndexedDbKeyValueStore } from '@bazariodev/hopper/key-value/indexeddb';
const files = createIndexedDbKeyValueStore({
databaseName: 'attachments',
storeName: 'files',
});
await files.set('draft|audio', new File(['sample'], 'audio.txt', { type: 'text/plain' }));
const saved = await files.get('draft|audio');
if (saved instanceof File) console.log(saved.name);Supply nonempty database and store names. Keys and prefixes must be strings; empty strings are valid. Values use native structured cloning. Validate returned values.
Upload outbox
import { createMemoryOutbox } from '@bazariodev/hopper/outbox';
const outbox = createMemoryOutbox({ maxRecords: 1000 });
outbox.write({ sample: 42 });
const batch = await outbox.nextBatch(100, outbox.capture());
if (batch) {
const { records, token } = batch;
// Supply sendBatch. Acknowledge only after complete acceptance.
await sendBatch(records, token);
await outbox.acknowledge(token);
}For persistent batches, supply database and lock names in the initial options:
import { createIndexedDbOutbox } from '@bazariodev/hopper/outbox/indexeddb';
const outbox = await createIndexedDbOutbox({
databaseName: JSON.stringify(['diagnostics', scope, 'outbox']),
lockName: JSON.stringify(['diagnostics-owner', scope, 'outbox']),
maxRecords: 1000,
});Here scope is the authenticated account scope above. Use separate databases for history and outboxes.
Behavior
History uses bucket, buckets, and PerBucket option names. Update callers; previous names have no aliases.
IndexedDB history uses schema version 2 and upgrades compatible version-1 history atomically.
A conflicting stored bucket payload aborts the upgrade and preserves the old database.
Outbox and key-value schemas do not change. Docket logging areas use its /storage adapter.
History
- History copies and freezes JSON. The first retained
(runId, seq)wins. Clear and eviction release that identity. Queries sort byat,runId, thenseq. Time bounds are inclusive. Missing buckets select all;[]selects none. - Size limits count JSON characters, not bytes. Capacity loss counts as dropped records; age expiry does not.
Cycle retention removes oldest records. Rotate removes the complete window and supplies one fixed snapshot.
Pending rotation uses cycle retention. Recording and cleanup do not wait for the callback.
Callback failure reports
rotation; removed records are not restored. - IndexedDB flush covers earlier writes and waits for transaction completion. Query flushes first. Storage failure selects bounded memory fallback. Failed batches are dropped. Recovery retries when access permits. The recovery interval is ten minutes.
- Initial lock failure selects memory for the instance.
allowUnprotected: truepermits unlocked persistence. This option can bypass another owner. Check status. Unexpected ownership loss stops recording. - Opens have a ten-second deadline. An unsettled native request prevents another open on that instance. Valid late connections can recover a live store. Incompatible schemas remain unchanged.
Outboxes
- Outboxes keep FIFO order and duplicates. They copy and freeze JSON objects. Bound record size in the application. Capacity includes the protected batch. Evict oldest unprotected records; drop new records if all capacity is protected.
- A batch stays protected until acknowledgement. Repeated claims return its token and records, including after reopen. Capture limits a new batch to earlier writes. Repeated acknowledgement is safe. Use tokens for backend deduplication within the original account scope. Delivery can repeat after a lost response.
- Persistent opening restores records and the protected batch. It requires exclusive ownership and has no memory fallback. Flush means storage completion, not upload acceptance. Acknowledgement removes only its batch. Later writes need flush.
- Failed outbox storage blocks writes and preserves the batch for explicit retry. Ownership loss or closure is terminal. Clear invalidates captures and tokens. Stop the upload processor before clear or shutdown.
Key-value
- Key-value storage opens on first use. It preserves supported native and falsy values.
Missing keys and stored
undefinedreturnundefined. New databases start at version 1. Existing stores need out-of-line keys, no key generator, and no indexes. Missing or incompatible targets reject unchanged. Sibling stores remain unchanged. - Calls run in instance order and wait for transaction completion. Tabs have no shared call-order guarantee.
Keep input unchanged until
set()settles.deleteMany()copies keys at call time and deletes atomically. keys(prefix)returns matching string keys in native order without value reads. Concurrent writes can follow enumeration. No lock, fallback, expiry, or capacity limit applies. Failed mutations are never replayed.
Cleanup and privacy
- Stop is terminal and repeatable. History and outbox writes after stop do nothing.
Key-value stop rejects unstarted and later calls. Active calls keep their results; all accepted calls settle before stop.
History stop attempts a final flush.
stop({ discard: true })drops unstarted and fallback records. Discard cannot undo active or committed transactions. Normal stop retains memory history. - Stopped history query and clear remain available. Clear discards earlier local work and awaits disk erasure. Rotation snapshots become invalid after clear or stop. Started callbacks can finish later.
- Use
clearIndexedDbStore(options)for stopped history andclearIndexedDbOutbox(options)for stopped outboxes. Supply the original database and lock names. Both preserve compatible schemas and leave absent databases absent. Failure does not prove erasure. Retain old account names for retry. - Privacy: Hopper does not redact or upload data. The application owns consent, credentials, isolation, and deletion. Stop preserves committed records. Clear cannot erase exported or caller-held copies. Page exit cannot guarantee a flush. Native commit does not guarantee survival of a power failure. Hopper installs no page lifecycle handlers.
API
| Port | Methods |
| --- | --- |
| History | write(record), query({ buckets?, from?, to? }?), flush(), clear(), stop({ discard? }?), getStatus() |
| Outbox | write(record), capture(), nextBatch(limit, boundary), acknowledge(token), flush(), clear(), stop(), getStatus() |
| Key-value | get(key), set(key, value), deleteMany(keys), keys(prefix), stop() |
Only write, capture, and getStatus are synchronous. Other methods return promises.
Call methods on their instance. History status includes mode, droppedRecords, unavailableHistory,
unprotected, and canRecover. Outbox status includes mode, pendingRecords, batchRecords,
droppedRecords, and an optional error.
History options
| Option | Default or requirement |
| --- | --- |
| defaultMaxSizePerBucket, maxTotalSize | 1,000,000 and 16,000,000 JSON characters |
| maxSizePerBucket, maxRecordsPerBucket | {}; limits for named buckets |
| maxAgeMs | 86,400,000 milliseconds |
| defaultMaxRecordsPerBucket | Memory: Number.MAX_SAFE_INTEGER; IndexedDB: 20,000 |
| overflowStrategy | 'cycle'; also accepts 'rotate' |
| onRotate(source), isRotationEnabled() | No callback; rotation enabled |
| now, scheduler | Date.now; host setTimeout and clearTimeout |
| onError(error), onStatusChange() | Optional; status notification is IndexedDB-only |
| databaseName | Required nonempty string for IndexedDB |
| lockName | JSON.stringify(['bazario:hopper:indexeddb', databaseName]) |
| indexedDB, locks | Host capabilities; injectable |
| keyRange | Native port; injected indexedDB defaults to null for cursor scans |
| allowUnprotected | false |
| flushIntervalMs, maxBatchSize | 1,000 milliseconds; 250 records |
| maxQueuedRecords, maxQueuedSize | 1,000 records; 4,000,000 JSON characters |
| fallback | Separate memory budgets; rotation stays with the parent |
All size, age, count, and batch limits must be positive safe integers.
Outboxes require maxRecords. Persistent outboxes also accept indexedDB, locks, scheduler, and onError.
Key-value options are databaseName, storeName, and optional indexedDB.
The root exports validateQuery, validateStoreOptions, STORE_MODES, ERROR_CODES, and OVERFLOW_STRATEGIES.
/outbox exports OUTBOX_MODES. Validators start no storage work.
validateQuery() returns a record predicate. validateStoreOptions() checks budgets and rotation.
import { copyRecords } from '@bazariodev/hopper';
await copyRecords(source, destination, { maxChunkRecords: 100 });
await store.stop();Supply source and destination. Copy reads once and flushes before and between chunks.
Defaults: 100 records and 1,000,000 characters (maxChunkSize). Oversized records travel alone.
Destination retention still applies. Copy completion does not prove that every record was retained.
Errors
Invalid history input or options throw TypeError. JSON conversion errors propagate from writes.
History reports open, write, read, quota, overflow, ownership, clear, upgrade, or rotation.
Read failures return bounded fallback. Callback failures are contained. Persistent operations can reject.
Outboxes validate capacities, limits, captures, tokens, and records. Failed storage permits explicit retry.
Cleanup helpers reject invalid options through promises before platform access. Cleanup failures use clear.
Key-value input errors reject with TypeError; invalid factory options throw. Native errors remain unchanged.
Key-value stop errors use Error('Key-value store is stopped') without a code. Open deadlines use code: 'open'.
TypeScript
import { createMemoryStore, type HopperRecord } from '@bazariodev/hopper';
type Sample = HopperRecord & Readonly<{ value: number }>;
const store = createMemoryStore<Sample>();
store.write({ runId: 'capture-1', seq: 1, at: Date.now(), bucket: 'samples', value: 42 });ESM and CommonJS include declarations. Memory entries need ES2022; persistent entries also need DOM.
History and outbox types require JSON data. Native types, functions, BigInt, and broad object fields are rejected.
JavaScript writes follow JSON conversion.
Factories infer optional-bucket inputs. RecordStore and RecordSink aliases default to required-bucket records.
Use HopperRecordInput for optional-bucket ports and JsonRecord<T> for generic wrappers. Queries always supply bucket.
RecordSource<T>, RecordSink<T>, and RecordStore<T> are structural ports. Key-value get() returns Promise<unknown>.
License
MIT.
