All files / omnium-gatherum/src/vats/storage baggage-adapter.ts

100% Statements 15/15
100% Branches 8/8
100% Functions 6/6
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                          11x   4x 2x   2x       13x 1x   12x         4x 3x         8x 8x 7x   3x       1x  
import type { Baggage } from '@metamask/ocap-kernel';
import type { Json } from '@metamask/utils';
 
import type { StorageAdapter } from '../../controllers/storage/types.ts';
 
/**
 * Create a StorageAdapter implementation backed by vat baggage.
 * Provides synchronous persistence (baggage writes are durable).
 *
 * @param baggage - The vat baggage store.
 * @returns A StorageAdapter backed by baggage.
 */
export function makeBaggageStorageAdapter(baggage: Baggage): StorageAdapter {
  return harden({
    async get<Value extends Json>(key: string): Promise<Value | undefined> {
      if (baggage.has(key)) {
        return baggage.get(key) as Value;
      }
      return undefined;
    },
 
    async set(key: string, value: Json): Promise<void> {
      if (baggage.has(key)) {
        baggage.set(key, harden(value));
      } else {
        baggage.init(key, harden(value));
      }
    },
 
    async delete(key: string): Promise<void> {
      if (baggage.has(key)) {
        baggage.delete(key);
      }
    },
 
    async keys(prefix?: string): Promise<string[]> {
      const allKeys = [...baggage.keys()];
      if (!prefix) {
        return allKeys;
      }
      return allKeys.filter((k) => k.startsWith(prefix));
    },
  });
}
harden(makeBaggageStorageAdapter);