import { vi, type Mock } from 'vitest'; import type { SecretEntry, SecretStore } from '@waggle/core'; import { setConnectorCredential, type ConnectorCredentialInput, } from '../../src/connectors/connector-credentials.js'; export type MockSecretStore = { [K in keyof SecretStore]: Mock }; /** An expiry in the past, for credentials that should read as expired. */ export const EXPIRED_AT = '2020-01-01T00:00:00.000Z'; /** A seed credential from the `{ value, isExpired }` shape the connector tests use. */ export function seedCredential( cred: { value: string; isExpired: boolean }, type: ConnectorCredentialInput['type'] = 'bearer', ): ConnectorCredentialInput { return { type, value: cred.value, expiresAt: cred.isExpired ? EXPIRED_AT : undefined }; } export interface SecretStoreSeed { /** Connector credentials by connector id, stored with setConnectorCredential. */ connectors?: Record; /** Plain secrets by name, such as `connector:jira:email`. */ secrets?: Record; } /** * A Map-backed SecretStore for connector tests. Every method is a vitest spy. * The seed is written before the spies exist, so it does not show up in their calls. */ export function createMemorySecretStore(seed: SecretStoreSeed = {}): MockSecretStore { const entries = new Map(); const store: SecretStore = { get: name => entries.get(name) ?? null, set: (name, value, metadata) => { entries.set(name, { name, value, metadata, updatedAt: new Date().toISOString() }); }, setAsync: async (name, value, metadata) => store.set(name, value, metadata), writeBatch: (batch) => { for (const name of batch.delete ?? []) entries.delete(name); for (const { name, value, metadata } of batch.set ?? []) store.set(name, value, metadata); }, delete: name => entries.delete(name), deleteAsync: async name => store.delete(name), list: () => [...entries.values()].map(({ name, metadata, updatedAt }) => ({ name, metadata, updatedAt })), has: name => entries.has(name), }; for (const [connectorId, credential] of Object.entries(seed.connectors ?? {})) { setConnectorCredential(store, connectorId, credential); } for (const [name, value] of Object.entries(seed.secrets ?? {})) { store.set(name, value); } return { get: vi.fn(store.get), set: vi.fn(store.set), setAsync: vi.fn(store.setAsync), writeBatch: vi.fn(store.writeBatch), delete: vi.fn(store.delete), deleteAsync: vi.fn(store.deleteAsync), list: vi.fn(store.list), has: vi.fn(store.has), }; }