-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
226 lines (201 loc) · 5.61 KB
/
api.ts
File metadata and controls
226 lines (201 loc) · 5.61 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import { loadConfig, getApiUrl } from "./config.js";
import {
OPENSYNC_SOURCE,
type SyncSessionPayload,
type SyncMessagePayload,
type SyncSessionRequest,
type SyncMessageRequest,
type SyncBatchRequest,
type SyncSessionResponse,
type SyncMessageResponse,
type SyncBatchResponse,
} from "./types.js";
/**
* Make an authenticated request to the OpenSync API
*/
async function apiRequest<T>(
endpoint: string,
method: "GET" | "POST" | "DELETE" = "GET",
body?: unknown
): Promise<T> {
const config = loadConfig();
if (!config) {
throw new Error("Not authenticated. Run 'cursor-sync login' first.");
}
const apiUrl = getApiUrl(config.convexUrl);
const url = `${apiUrl}${endpoint}`;
if (config.debug) {
console.error(`[cursor-sync] ${method} ${url}`);
if (body) {
console.error(`[cursor-sync] Body: ${JSON.stringify(body, null, 2)}`);
}
}
const response = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${config.apiKey}`,
},
body: body ? JSON.stringify(body) : undefined,
});
const text = await response.text();
if (config.debug) {
console.error(`[cursor-sync] Response (${response.status}): ${text}`);
}
if (!response.ok) {
throw new Error(`API error (${response.status}): ${text}`);
}
try {
return JSON.parse(text) as T;
} catch {
throw new Error(`Invalid JSON response: ${text}`);
}
}
/**
* Sync a session to OpenSync
* Sends session fields directly at top level (not wrapped)
*/
export async function syncSession(
session: SyncSessionPayload
): Promise<SyncSessionResponse> {
return apiRequest<SyncSessionResponse>("/sync/session", "POST", session);
}
/**
* Sync a message to OpenSync
* Sends message fields directly at top level (not wrapped)
*/
export async function syncMessage(
message: SyncMessagePayload
): Promise<SyncMessageResponse> {
return apiRequest<SyncMessageResponse>("/sync/message", "POST", message);
}
/**
* Batch sync sessions and messages
*/
export async function syncBatch(
sessions?: SyncSessionPayload[],
messages?: SyncMessagePayload[]
): Promise<SyncBatchResponse> {
const request: SyncBatchRequest = { sessions, messages };
return apiRequest<SyncBatchResponse>("/sync/batch", "POST", request);
}
/**
* Test API connectivity
*/
export async function testConnection(): Promise<{ success: boolean; message: string }> {
try {
const config = loadConfig();
if (!config) {
return { success: false, message: "Not authenticated" };
}
const apiUrl = getApiUrl(config.convexUrl);
const response = await fetch(`${apiUrl}/health`);
if (response.ok) {
return { success: true, message: "Connection successful" };
} else {
return { success: false, message: `Health check failed: ${response.status}` };
}
} catch (error) {
return {
success: false,
message: error instanceof Error ? error.message : "Unknown error",
};
}
}
// Response type that handles both 'success' and 'ok' field names
interface ApiResponse {
success?: boolean;
ok?: boolean;
sessionId?: string;
messageId?: string;
error?: string;
}
function isSuccessResponse(result: ApiResponse): boolean {
return result.success === true || result.ok === true;
}
/**
* Create a test session to verify full sync flow
*/
export async function createTestSession(): Promise<SyncSessionResponse> {
try {
const now = Date.now();
const testExternalId = `cursor-test-${now}`;
// Create the test session first
const testSession: SyncSessionPayload = {
externalId: testExternalId,
title: "Test Session from cursor-sync",
source: OPENSYNC_SOURCE,
project: "cursor-sync-test",
directory: process.cwd(),
startedAt: now,
endedAt: now,
totalTokens: 100,
promptTokens: 50,
completionTokens: 50,
cost: 0.001,
messageCount: 1,
toolCallCount: 0,
};
const sessionResult = await syncSession(testSession) as ApiResponse;
if (!isSuccessResponse(sessionResult)) {
return {
success: false,
error: sessionResult.error || "Session sync returned unsuccessful response",
};
}
// Create a test message linked to the session
const testMessage: SyncMessagePayload = {
sessionExternalId: testExternalId,
externalId: `${testExternalId}-msg-${now}`,
source: OPENSYNC_SOURCE,
role: "user",
textContent: "Test message from cursor-sync plugin",
parts: [{ type: "text", content: "Test message from cursor-sync plugin" }],
timestamp: now,
promptTokens: 50,
};
const messageResult = await syncMessage(testMessage) as ApiResponse;
if (!isSuccessResponse(messageResult)) {
return {
success: true,
sessionId: sessionResult.sessionId,
error: `Session created but message failed: ${messageResult.error}`,
};
}
return {
success: true,
sessionId: sessionResult.sessionId,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
};
}
}
/**
* Get usage stats
*/
export async function getStats(): Promise<{
success: boolean;
stats?: {
totalSessions: number;
totalTokens: number;
totalCost: number;
};
error?: string;
}> {
try {
const stats = await apiRequest<{
totalSessions: number;
totalTokens: number;
totalCost: number;
}>("/api/stats");
return { success: true, stats };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : "Unknown error",
};
}
}