scalix 1.0.0 → 1.2.0

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,77 @@
1
+ export class ScalixClient {
2
+ baseURL;
3
+ apiKey;
4
+ constructor(baseURL, apiKey) {
5
+ this.baseURL = baseURL.replace(/\/+$/, '');
6
+ this.apiKey = apiKey;
7
+ }
8
+ async chatComplete(req, signal) {
9
+ const url = `${this.baseURL}/chat/completions`;
10
+ const body = JSON.stringify(req);
11
+ const response = await fetch(url, {
12
+ method: 'POST',
13
+ headers: {
14
+ 'Content-Type': 'application/json',
15
+ 'Authorization': `Bearer ${this.apiKey}`,
16
+ 'User-Agent': 'Scalix-Coder/1.0',
17
+ },
18
+ body,
19
+ signal,
20
+ });
21
+ if (!response.ok) {
22
+ const text = await response.text().catch(() => '');
23
+ throw new Error(`API request failed: ${response.status} ${response.statusText}${text ? ` — ${text.slice(0, 200)}` : ''}`);
24
+ }
25
+ if (req.stream) {
26
+ return this.parseSSEStream(response);
27
+ }
28
+ return await response.json();
29
+ }
30
+ async *parseSSEStream(response) {
31
+ const reader = response.body?.getReader();
32
+ if (!reader)
33
+ throw new Error('No response body for streaming');
34
+ const decoder = new TextDecoder();
35
+ let buffer = '';
36
+ try {
37
+ while (true) {
38
+ const { done, value } = await reader.read();
39
+ if (done)
40
+ break;
41
+ buffer += decoder.decode(value, { stream: true });
42
+ const lines = buffer.split('\n');
43
+ buffer = lines.pop() || '';
44
+ for (const line of lines) {
45
+ const trimmed = line.trim();
46
+ if (!trimmed || trimmed.startsWith(':'))
47
+ continue;
48
+ if (trimmed.startsWith('data: ')) {
49
+ const data = trimmed.slice(6);
50
+ if (data === '[DONE]')
51
+ return;
52
+ try {
53
+ yield JSON.parse(data);
54
+ }
55
+ catch {
56
+ // skip malformed chunks
57
+ }
58
+ }
59
+ }
60
+ }
61
+ if (buffer.trim().startsWith('data: ')) {
62
+ const data = buffer.trim().slice(6);
63
+ if (data !== '[DONE]') {
64
+ try {
65
+ yield JSON.parse(data);
66
+ }
67
+ catch {
68
+ // skip
69
+ }
70
+ }
71
+ }
72
+ }
73
+ finally {
74
+ reader.releaseLock();
75
+ }
76
+ }
77
+ }