/** * Base adapter utilities and factory */ import type { SecureStorageAdapter, SecureStorageOptions, StorageResult } from "./types"; /** * Create a namespaced key */ export function namespacedKey(namespace: string | undefined, key: string): string { const prefix = namespace ? `${namespace}:` : "styx:"; return `${prefix}${key}`; } /** * Create a success result */ export function ok(value: T): StorageResult { return { ok: true, value }; } /** * Create an error result */ export function err(error: string): StorageResult { return { ok: false, error }; } /** * Wrap an async operation with error handling */ export async function wrap( fn: () => Promise, errorPrefix: string ): Promise> { try { const value = await fn(); return ok(value); } catch (e) { const msg = e instanceof Error ? e.message : String(e); return err(`${errorPrefix}: ${msg}`); } } /** * Abstract base class for secure storage adapters */ export abstract class BaseSecureStorageAdapter implements SecureStorageAdapter { abstract readonly name: string; abstract readonly available: boolean; protected readonly namespace: string; protected readonly options: SecureStorageOptions; constructor(options: SecureStorageOptions = {}) { this.namespace = options.namespace ?? "styx"; this.options = options; } protected key(rawKey: string): string { return namespacedKey(this.namespace, rawKey); } abstract set(key: string, value: string): Promise>; abstract get(key: string): Promise>; abstract delete(key: string): Promise>; abstract has(key: string): Promise>; }