forked from onlook-dev/onlook
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathindex.ts
More file actions
109 lines (94 loc) · 2.68 KB
/
index.ts
File metadata and controls
109 lines (94 loc) · 2.68 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import fs from 'fs-extra';
import path from 'path';
import crypto from 'crypto';
export interface Rule {
id: string;
content: string;
createdAt: Date;
updatedAt: Date;
tags?: string[];
}
export class LongTermMemory {
private rulesDir: string;
private rules: Map<string, Rule>;
constructor(rulesDir: string = path.join(process.cwd(), 'rules')) {
this.rulesDir = rulesDir;
this.rules = new Map();
}
async init() {
await this.initialize();
}
private async initialize() {
try {
await fs.ensureDir(this.rulesDir);
await this.loadRules();
} catch (error) {
console.error('Failed to initialize long-term memory:', error);
}
}
private async loadRules() {
try {
const files = await fs.readdir(this.rulesDir);
for (const file of files) {
if (file.endsWith('.json')) {
const rulePath = path.join(this.rulesDir, file);
const ruleData = await fs.readJson(rulePath);
this.rules.set(ruleData.id, {
...ruleData,
createdAt: new Date(ruleData.createdAt),
updatedAt: new Date(ruleData.updatedAt)
});
}
}
} catch (error) {
console.error('Failed to load rules:', error);
}
}
async addRule(rule: Omit<Rule, 'id' | 'createdAt' | 'updatedAt'>): Promise<Rule> {
const newRule: Rule = {
...rule,
id: crypto.randomUUID(),
createdAt: new Date(),
updatedAt: new Date()
};
const rulePath = path.join(this.rulesDir, `${newRule.id}.json`);
await fs.writeJson(rulePath, newRule);
this.rules.set(newRule.id, newRule);
return newRule;
}
async updateRule(id: string, updates: Partial<Omit<Rule, 'id' | 'createdAt'>>): Promise<Rule | null> {
const existingRule = this.rules.get(id);
if (!existingRule) return null;
const updatedRule: Rule = {
...existingRule,
...updates,
updatedAt: new Date()
};
const rulePath = path.join(this.rulesDir, `${id}.json`);
await fs.writeJson(rulePath, updatedRule);
this.rules.set(id, updatedRule);
return updatedRule;
}
async deleteRule(id: string): Promise<boolean> {
const rulePath = path.join(this.rulesDir, `${id}.json`);
try {
await fs.remove(rulePath);
this.rules.delete(id);
return true;
} catch (error) {
console.error('Failed to delete rule:', error);
return false;
}
}
getRule(id: string): Rule | null {
return this.rules.get(id) || null;
}
getAllRules(): Rule[] {
return Array.from(this.rules.values());
}
getRulesByTag(tag: string): Rule[] {
return Array.from(this.rules.values()).filter(rule =>
rule.tags?.includes(tag)
);
}
}