Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

store.ts

71 lines · 2.3 KB · TypeScript
/**
 * Notification storage. JSON packageStorage, capped at 200 notifications.
 */
import { loadJson, saveJson } from '../lib/storage.ts'
import type { Notification, NotificationRules } from './types.ts'
import { defaultNotificationRules } from './types.ts'

const NOTIFICATIONS_KEY = 'factory:notifications:v1'
const RULES_KEY = 'factory:notification-rules:v1'
const MAX_NOTIFICATIONS = 200

type NotificationStore = {
	notifications: Notification[]
}

function emptyStore(): NotificationStore {
	return { notifications: [] }
}

export async function loadNotifications(): Promise<Notification[]> {
	return (await loadJson<NotificationStore>(NOTIFICATIONS_KEY, emptyStore())).notifications
}

export async function saveNotification(notification: Notification): Promise<void> {
	const store = await loadJson<NotificationStore>(NOTIFICATIONS_KEY, emptyStore())
	store.notifications.unshift(notification)
	if (store.notifications.length > MAX_NOTIFICATIONS) {
		store.notifications = store.notifications.slice(0, MAX_NOTIFICATIONS)
	}
	await saveJson(NOTIFICATIONS_KEY, store)
}

export async function markRead(ids: string[]): Promise<number> {
	const store = await loadJson<NotificationStore>(NOTIFICATIONS_KEY, emptyStore())
	let count = 0
	const idSet = new Set(ids)
	for (const n of store.notifications) {
		if (idSet.has(n.id) && n.status === 'unread') {
			n.status = 'read'
			count++
		}
	}
	if (count > 0) await saveJson(NOTIFICATIONS_KEY, store)
	return count
}

export async function markAllRead(projectId?: string): Promise<number> {
	const store = await loadJson<NotificationStore>(NOTIFICATIONS_KEY, emptyStore())
	let count = 0
	for (const n of store.notifications) {
		if (n.status === 'unread' && (!projectId || n.projectId === projectId)) {
			n.status = 'read'
			count++
		}
	}
	if (count > 0) await saveJson(NOTIFICATIONS_KEY, store)
	return count
}

export async function countUnread(projectId?: string): Promise<number> {
	const notifications = await loadNotifications()
	return notifications.filter((n) => n.status === 'unread' && (!projectId || n.projectId === projectId)).length
}

export async function loadRules(): Promise<NotificationRules> {
	return loadJson<NotificationRules>(RULES_KEY, defaultNotificationRules())
}

export async function saveRules(rules: NotificationRules): Promise<void> {
	await saveJson(RULES_KEY, rules)
}