import { mkdir, readFile, writeFile, readdir } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { homedir } from 'os';
import type { Session } from './types.js';
export class FileStore {
private basePath: string;
private sessionsPath: string;
constructor(basePath?: string) {
this.basePath = basePath?.replace(/^~/, homedir()) ?? join(homedir(), '.user-steps');
this.sessionsPath = join(this.basePath, 'sessions');
}
private async ensureDir(): Promise<void> {
if (!existsSync(this.sessionsPath)) {
await mkdir(this.sessionsPath, { recursive: true });
}
}
private getSessionPath(sessionId: string): string {
return join(this.sessionsPath, `${sessionId}.json`);
}
async write(sessionId: string, session: Session): Promise<void> {
await this.ensureDir();
const path = this.getSessionPath(sessionId);
await writeFile(path, JSON.stringify(session, null, 2), 'utf-8');
}
async read(sessionId: string): Promise<Session | null> {
const path = this.getSessionPath(sessionId);
if (!existsSync(path)) {
return null;
}
const content = await readFile(path, 'utf-8');
return JSON.parse(content) as Session;
}
async getLatestActiveSession(): Promise<Session | null> {
await this.ensureDir();
const files = await readdir(this.sessionsPath);
const jsonFiles = files.filter(f => f.endsWith('.json'));
let latestSession: Session | null = null;
let latestTime = 0;
for (const file of jsonFiles) {
const path = join(this.sessionsPath, file);
const content = await readFile(path, 'utf-8');
const session = JSON.parse(content) as Session;
if (session.status === 'active') {
const time = new Date(session.createdAt).getTime();
if (time > latestTime) {
latestTime = time;
latestSession = session;
}
}
}
return latestSession;
}
getBasePath(): string {
return this.basePath;
}
}