@tensorspark/dravix-code 0.0.0-stage → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,181 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import * as os from 'os';
4
+ const UNDO_DIR = path.join(os.homedir(), '.dravix-code', 'undo');
5
+ let currentSession = null;
6
+ // Initialize undo directory
7
+ function ensureUndoDir() {
8
+ fs.mkdirSync(UNDO_DIR, { recursive: true });
9
+ }
10
+ // Generate unique session ID
11
+ function generateSessionId() {
12
+ return Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
13
+ }
14
+ // Start a new undo session (before a batch of operations)
15
+ export function startUndoSession() {
16
+ ensureUndoDir();
17
+ const id = generateSessionId();
18
+ currentSession = {
19
+ id,
20
+ timestamp: new Date().toISOString(),
21
+ operations: [],
22
+ };
23
+ return id;
24
+ }
25
+ // Backup a file before modification
26
+ export function backupFile(filePath, cwd) {
27
+ try {
28
+ if (!fs.existsSync(filePath))
29
+ return null;
30
+ const relPath = path.relative(cwd, filePath).replace(/\\/g, '/');
31
+ const backupId = currentSession?.id ?? generateSessionId();
32
+ const backupDir = path.join(UNDO_DIR, backupId);
33
+ fs.mkdirSync(backupDir, { recursive: true });
34
+ // Create backup with path-based naming
35
+ const backupName = relPath.replace(/[/\\]/g, '__');
36
+ const backupPath = path.join(backupDir, backupName);
37
+ fs.copyFileSync(filePath, backupPath);
38
+ return backupPath;
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }
44
+ // Record a write operation for undo
45
+ export function recordWrite(filePath, backupPath) {
46
+ if (!currentSession)
47
+ return;
48
+ currentSession.operations.push({
49
+ type: 'write',
50
+ path: filePath,
51
+ backupPath: backupPath ?? undefined,
52
+ });
53
+ }
54
+ // Record an edit operation for undo
55
+ export function recordEdit(filePath, backupPath) {
56
+ if (!currentSession)
57
+ return;
58
+ currentSession.operations.push({
59
+ type: 'edit',
60
+ path: filePath,
61
+ backupPath: backupPath ?? undefined,
62
+ });
63
+ }
64
+ // Record a delete operation for undo
65
+ export function recordDelete(filePath) {
66
+ if (!currentSession)
67
+ return;
68
+ let content = '';
69
+ try {
70
+ content = fs.readFileSync(filePath, 'utf-8');
71
+ }
72
+ catch { /* ignore */ }
73
+ currentSession.operations.push({
74
+ type: 'delete',
75
+ path: filePath,
76
+ deletedContent: content || undefined,
77
+ });
78
+ }
79
+ // Save the current undo session
80
+ export function saveUndoSession() {
81
+ if (!currentSession || currentSession.operations.length === 0)
82
+ return;
83
+ ensureUndoDir();
84
+ const sessionPath = path.join(UNDO_DIR, `${currentSession.id}.json`);
85
+ fs.writeFileSync(sessionPath, JSON.stringify(currentSession, null, 2), 'utf-8');
86
+ }
87
+ // Undo the last session
88
+ export function undoLastSession(cwd) {
89
+ ensureUndoDir();
90
+ // Find the most recent session file
91
+ const files = fs.readdirSync(UNDO_DIR)
92
+ .filter(f => f.endsWith('.json'))
93
+ .sort()
94
+ .reverse();
95
+ if (files.length === 0) {
96
+ return { success: false, message: 'No undo history found' };
97
+ }
98
+ const sessionPath = path.join(UNDO_DIR, files[0]);
99
+ const session = JSON.parse(fs.readFileSync(sessionPath, 'utf-8'));
100
+ let restored = 0;
101
+ let errors = 0;
102
+ // Process operations in reverse order
103
+ for (const op of session.operations.reverse()) {
104
+ try {
105
+ if (op.type === 'write' || op.type === 'edit') {
106
+ // Restore from backup
107
+ if (op.backupPath && fs.existsSync(op.backupPath)) {
108
+ fs.copyFileSync(op.backupPath, op.path);
109
+ restored++;
110
+ }
111
+ else {
112
+ errors++;
113
+ }
114
+ }
115
+ else if (op.type === 'delete') {
116
+ // Recreate the deleted file
117
+ if (op.deletedContent !== undefined) {
118
+ fs.mkdirSync(path.dirname(op.path), { recursive: true });
119
+ fs.writeFileSync(op.path, op.deletedContent, 'utf-8');
120
+ restored++;
121
+ }
122
+ else {
123
+ errors++;
124
+ }
125
+ }
126
+ }
127
+ catch {
128
+ errors++;
129
+ }
130
+ }
131
+ // Clean up session file and backup directory
132
+ try {
133
+ fs.unlinkSync(sessionPath);
134
+ const backupDir = path.join(UNDO_DIR, session.id);
135
+ if (fs.existsSync(backupDir)) {
136
+ fs.rmSync(backupDir, { recursive: true });
137
+ }
138
+ }
139
+ catch { /* ignore */ }
140
+ const msg = `Undone: ${restored} operation(s) restored` +
141
+ (errors > 0 ? `, ${errors} error(s)` : '') +
142
+ ` from ${new Date(session.timestamp).toLocaleString()}`;
143
+ return { success: restored > 0, message: msg };
144
+ }
145
+ // Get list of available undo sessions
146
+ export function listUndoSessions() {
147
+ ensureUndoDir();
148
+ const files = fs.readdirSync(UNDO_DIR).filter(f => f.endsWith('.json'));
149
+ return files.map(f => {
150
+ try {
151
+ const session = JSON.parse(fs.readFileSync(path.join(UNDO_DIR, f), 'utf-8'));
152
+ return {
153
+ id: session.id,
154
+ timestamp: session.timestamp,
155
+ ops: session.operations.length,
156
+ };
157
+ }
158
+ catch {
159
+ return { id: f.replace('.json', ''), timestamp: '', ops: 0 };
160
+ }
161
+ }).sort((a, b) => b.timestamp.localeCompare(a.timestamp));
162
+ }
163
+ // Clean up old undo sessions (older than 7 days)
164
+ export function cleanupOldSessions() {
165
+ ensureUndoDir();
166
+ const files = fs.readdirSync(UNDO_DIR).filter(f => f.endsWith('.json'));
167
+ const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000;
168
+ for (const f of files) {
169
+ try {
170
+ const session = JSON.parse(fs.readFileSync(path.join(UNDO_DIR, f), 'utf-8'));
171
+ if (new Date(session.timestamp).getTime() < cutoff) {
172
+ fs.unlinkSync(path.join(UNDO_DIR, f));
173
+ const backupDir = path.join(UNDO_DIR, session.id);
174
+ if (fs.existsSync(backupDir)) {
175
+ fs.rmSync(backupDir, { recursive: true });
176
+ }
177
+ }
178
+ }
179
+ catch { /* ignore */ }
180
+ }
181
+ }
@@ -0,0 +1,60 @@
1
+ const USAGE_URL = 'https://dravix.app/cli-usage.php';
2
+ export async function checkUsage(cliToken) {
3
+ try {
4
+ const res = await fetch(USAGE_URL, {
5
+ method: 'POST',
6
+ headers: { 'Content-Type': 'application/json' },
7
+ body: JSON.stringify({ action: 'check', token: cliToken }),
8
+ });
9
+ if (!res.ok)
10
+ return null;
11
+ return await res.json();
12
+ }
13
+ catch {
14
+ return null;
15
+ }
16
+ }
17
+ export async function reportUsage(cliToken, tokens) {
18
+ try {
19
+ const res = await fetch(USAGE_URL, {
20
+ method: 'POST',
21
+ headers: { 'Content-Type': 'application/json' },
22
+ body: JSON.stringify({ action: 'add', token: cliToken, tokens }),
23
+ });
24
+ if (!res.ok)
25
+ return null;
26
+ return await res.json();
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ // Estimate tokens from text (~4 chars per token)
33
+ export function estimateTokens(text) {
34
+ return Math.max(1, Math.ceil(text.length / 4));
35
+ }
36
+ // Format time until reset — uses server-side seconds to avoid timezone issues
37
+ export function formatResetTime(info) {
38
+ const secs = typeof info === 'string'
39
+ ? Math.max(0, Math.floor((new Date(info).getTime() - Date.now()) / 1000))
40
+ : (info.reset_in_seconds ?? 0);
41
+ if (secs <= 0)
42
+ return 'soon';
43
+ const h = Math.floor(secs / 3600);
44
+ const m = Math.floor((secs % 3600) / 60);
45
+ if (h > 0)
46
+ return `${h}h ${m}m`;
47
+ return `${m}m`;
48
+ }
49
+ // Format number with K suffix
50
+ export function fmtNum(n) {
51
+ return n >= 1000 ? (n / 1000).toFixed(1).replace('.0', '') + 'k' : String(n);
52
+ }
53
+ // Progress bar: ████████░░░░ pct%
54
+ export function usageBar(used, limit, width = 18) {
55
+ const pct = Math.min(Math.round((used / limit) * 100), 100);
56
+ const filled = Math.round((pct / 100) * width);
57
+ const empty = width - filled;
58
+ const bar = '█'.repeat(filled) + '░'.repeat(empty);
59
+ return { bar, pct };
60
+ }