@archlast/client 0.0.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.
- package/LICENSE +21 -0
- package/README.md +60 -0
- package/dist/admin/index.cjs +93 -0
- package/dist/admin/index.cjs.map +1 -0
- package/dist/admin/index.d.cts +51 -0
- package/dist/admin/index.d.ts +51 -0
- package/dist/admin/index.js +59 -0
- package/dist/admin/index.js.map +1 -0
- package/dist/auth/index.cjs +174 -0
- package/dist/auth/index.cjs.map +1 -0
- package/dist/auth/index.d.cts +128 -0
- package/dist/auth/index.d.ts +128 -0
- package/dist/auth/index.js +141 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/client.cjs +677 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +84 -0
- package/dist/client.d.ts +84 -0
- package/dist/client.js +642 -0
- package/dist/client.js.map +1 -0
- package/dist/function-reference.cjs +50 -0
- package/dist/function-reference.cjs.map +1 -0
- package/dist/function-reference.d.cts +22 -0
- package/dist/function-reference.d.ts +22 -0
- package/dist/function-reference.js +24 -0
- package/dist/function-reference.js.map +1 -0
- package/dist/index.cjs +1163 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +1111 -0
- package/dist/index.js.map +1 -0
- package/dist/react.cjs +455 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +137 -0
- package/dist/react.d.ts +137 -0
- package/dist/react.js +410 -0
- package/dist/react.js.map +1 -0
- package/dist/storage/index.cjs +150 -0
- package/dist/storage/index.cjs.map +1 -0
- package/dist/storage/index.d.cts +59 -0
- package/dist/storage/index.d.ts +59 -0
- package/dist/storage/index.js +117 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/trpc.cjs +66 -0
- package/dist/trpc.cjs.map +1 -0
- package/dist/trpc.d.cts +59 -0
- package/dist/trpc.d.ts +59 -0
- package/dist/trpc.js +41 -0
- package/dist/trpc.js.map +1 -0
- package/package.json +90 -0
package/dist/client.js
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
|
+
|
|
5
|
+
// src/auth/index.ts
|
|
6
|
+
import axios from "axios";
|
|
7
|
+
function resolveBaseUrl(explicit) {
|
|
8
|
+
if (explicit && explicit.trim()) return explicit.replace(/\/+$/, "");
|
|
9
|
+
if (typeof window !== "undefined" && window.location?.origin) return window.location.origin;
|
|
10
|
+
return "";
|
|
11
|
+
}
|
|
12
|
+
var ArchlastAuthClient = class {
|
|
13
|
+
constructor(options = {}) {
|
|
14
|
+
__publicField(this, "baseUrl");
|
|
15
|
+
__publicField(this, "axios");
|
|
16
|
+
__publicField(this, "appId");
|
|
17
|
+
__publicField(this, "apiKey");
|
|
18
|
+
this.baseUrl = resolveBaseUrl(options.baseUrl);
|
|
19
|
+
this.appId = options.appId;
|
|
20
|
+
this.apiKey = options.apiKey;
|
|
21
|
+
this.axios = axios.create({
|
|
22
|
+
baseURL: this.baseUrl,
|
|
23
|
+
withCredentials: !options.apiKey,
|
|
24
|
+
// Only use cookies if no API key
|
|
25
|
+
headers: {
|
|
26
|
+
"content-type": "application/json",
|
|
27
|
+
...this.appId ? { "x-archlast-app-id": this.appId } : {},
|
|
28
|
+
...options.apiKey ? { "x-api-key": options.apiKey } : {}
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Get current authentication state
|
|
34
|
+
* Uses Better-Auth's getSession endpoint
|
|
35
|
+
*/
|
|
36
|
+
async getState() {
|
|
37
|
+
try {
|
|
38
|
+
const response = await this.axios.get("/api/auth/get-session");
|
|
39
|
+
const { user, session } = response.data;
|
|
40
|
+
return {
|
|
41
|
+
user,
|
|
42
|
+
session,
|
|
43
|
+
isAuthenticated: !!user
|
|
44
|
+
};
|
|
45
|
+
} catch (error) {
|
|
46
|
+
return {
|
|
47
|
+
user: null,
|
|
48
|
+
session: null,
|
|
49
|
+
isAuthenticated: false
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Sign up new user
|
|
55
|
+
* Uses Better-Auth's email signUp endpoint
|
|
56
|
+
*/
|
|
57
|
+
async signUp(input) {
|
|
58
|
+
const response = await this.axios.post("/api/auth/sign-up/email", {
|
|
59
|
+
email: input.email,
|
|
60
|
+
password: input.password,
|
|
61
|
+
name: input.name,
|
|
62
|
+
username: input.username
|
|
63
|
+
});
|
|
64
|
+
return {
|
|
65
|
+
user: response.data.user,
|
|
66
|
+
session: null,
|
|
67
|
+
// Session is managed via cookies
|
|
68
|
+
isAuthenticated: !!response.data.user
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Sign in with email/username and password
|
|
73
|
+
* Uses Better-Auth's credential sign-in endpoint
|
|
74
|
+
*/
|
|
75
|
+
async signIn(input) {
|
|
76
|
+
if (!input.email && !input.username) {
|
|
77
|
+
throw new Error("Either email or username is required");
|
|
78
|
+
}
|
|
79
|
+
const response = await this.axios.post("/api/auth/sign-in/email", {
|
|
80
|
+
email: input.email,
|
|
81
|
+
username: input.username,
|
|
82
|
+
password: input.password
|
|
83
|
+
});
|
|
84
|
+
return {
|
|
85
|
+
user: response.data.user,
|
|
86
|
+
session: null,
|
|
87
|
+
// Session is managed via cookies
|
|
88
|
+
isAuthenticated: !!response.data.user
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Sign out and revoke session
|
|
93
|
+
* Uses Better-Auth's sign-out endpoint
|
|
94
|
+
*/
|
|
95
|
+
async signOut() {
|
|
96
|
+
const response = await this.axios.post(
|
|
97
|
+
"/api/auth/sign-out",
|
|
98
|
+
{},
|
|
99
|
+
{ withCredentials: true }
|
|
100
|
+
);
|
|
101
|
+
return response.data;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Request password reset email
|
|
105
|
+
* Uses Better-Auth's password reset flow
|
|
106
|
+
*/
|
|
107
|
+
async requestPasswordReset(email, callbackURL) {
|
|
108
|
+
const response = await this.axios.post("/api/auth/forgot-password", {
|
|
109
|
+
email,
|
|
110
|
+
redirectTo: callbackURL
|
|
111
|
+
});
|
|
112
|
+
return response.data;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Reset password with token
|
|
116
|
+
* Uses Better-Auth's reset password endpoint
|
|
117
|
+
*/
|
|
118
|
+
async resetPassword(token, password) {
|
|
119
|
+
const response = await this.axios.post("/api/auth/reset-password", {
|
|
120
|
+
token,
|
|
121
|
+
password
|
|
122
|
+
});
|
|
123
|
+
return response.data;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Verify email with token
|
|
127
|
+
* Uses Better-Auth's email verification endpoint
|
|
128
|
+
*/
|
|
129
|
+
async verifyEmail(token) {
|
|
130
|
+
const response = await this.axios.post("/api/auth/verify-email", {
|
|
131
|
+
token
|
|
132
|
+
});
|
|
133
|
+
return response.data;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
// src/storage/index.ts
|
|
138
|
+
import axios2 from "axios";
|
|
139
|
+
var StorageClient = class {
|
|
140
|
+
constructor(baseUrl, appId, options) {
|
|
141
|
+
__publicField(this, "axios");
|
|
142
|
+
this.axios = axios2.create({
|
|
143
|
+
baseURL: baseUrl,
|
|
144
|
+
withCredentials: !options?.apiKey,
|
|
145
|
+
// Only use cookies if no API key
|
|
146
|
+
headers: {
|
|
147
|
+
...appId ? { "x-archlast-app-id": appId } : {},
|
|
148
|
+
...options?.apiKey ? { "x-api-key": options.apiKey } : {}
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Upload a file
|
|
154
|
+
*/
|
|
155
|
+
async upload(file, contentType) {
|
|
156
|
+
let body = file;
|
|
157
|
+
let headers = {};
|
|
158
|
+
if (file instanceof File) {
|
|
159
|
+
const formData = new FormData();
|
|
160
|
+
formData.append("file", file);
|
|
161
|
+
body = formData;
|
|
162
|
+
} else {
|
|
163
|
+
if (contentType) {
|
|
164
|
+
headers["Content-Type"] = contentType;
|
|
165
|
+
}
|
|
166
|
+
if (file instanceof Uint8Array) {
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const response = await this.axios.post(
|
|
170
|
+
"/_archlast/storage/upload",
|
|
171
|
+
body,
|
|
172
|
+
{
|
|
173
|
+
headers
|
|
174
|
+
}
|
|
175
|
+
);
|
|
176
|
+
const data = response.data;
|
|
177
|
+
if (!data.id) throw new Error("Upload failed: No ID returned");
|
|
178
|
+
return this.hydrate(data);
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* List files
|
|
182
|
+
*/
|
|
183
|
+
async list(limit = 20, offset = 0) {
|
|
184
|
+
const response = await this.axios.get("/_archlast/storage/list", {
|
|
185
|
+
params: { limit, offset }
|
|
186
|
+
});
|
|
187
|
+
return {
|
|
188
|
+
items: response.data.items.map((item) => this.hydrate(item))
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Get file metadata
|
|
193
|
+
*/
|
|
194
|
+
async getMetadata(id) {
|
|
195
|
+
const response = await this.axios.get(`/_archlast/storage/files/${id}`);
|
|
196
|
+
return this.hydrate(response.data);
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Generate a presigned download URL
|
|
200
|
+
*/
|
|
201
|
+
async presign(id, expiresInSeconds = 300) {
|
|
202
|
+
const response = await this.axios.post("/_archlast/storage/presign", {
|
|
203
|
+
id,
|
|
204
|
+
expiresInSeconds
|
|
205
|
+
});
|
|
206
|
+
return response.data;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Delete file
|
|
210
|
+
*/
|
|
211
|
+
async delete(id) {
|
|
212
|
+
const response = await this.axios.delete(
|
|
213
|
+
`/_archlast/storage/files/${id}`
|
|
214
|
+
);
|
|
215
|
+
return response.data;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Get public URL for a file
|
|
219
|
+
*/
|
|
220
|
+
getPublicUrl(id) {
|
|
221
|
+
const base = this.axios.defaults.baseURL?.replace(/\/+$/, "") || "";
|
|
222
|
+
return `${base}/_storage/${id}`;
|
|
223
|
+
}
|
|
224
|
+
getDownloadUrl(id) {
|
|
225
|
+
const base = this.axios.defaults.baseURL?.replace(/\/+$/, "") || "";
|
|
226
|
+
return `${base}/_archlast/storage/files/${id}/download`;
|
|
227
|
+
}
|
|
228
|
+
hydrate(file) {
|
|
229
|
+
if (!file.id) throw new Error("Invalid file object: missing id");
|
|
230
|
+
return {
|
|
231
|
+
id: file.id,
|
|
232
|
+
name: file.name ?? file.fileName ?? "Untitled",
|
|
233
|
+
// Handle aliasing
|
|
234
|
+
fileName: file.fileName ?? file.name ?? null,
|
|
235
|
+
url: file.url ?? this.getPublicUrl(file.id),
|
|
236
|
+
downloadUrl: file.downloadUrl ?? this.getDownloadUrl(file.id),
|
|
237
|
+
hash: file.hash ?? "",
|
|
238
|
+
contentType: file.contentType ?? "application/octet-stream",
|
|
239
|
+
size: file.size ?? 0,
|
|
240
|
+
createdAt: file.createdAt ?? Date.now(),
|
|
241
|
+
updatedAt: file.updatedAt ?? Date.now(),
|
|
242
|
+
refCount: file.refCount ?? 1
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
// src/admin/index.ts
|
|
248
|
+
import axios3 from "axios";
|
|
249
|
+
var AdminAuthClient = class {
|
|
250
|
+
constructor(baseUrl, options) {
|
|
251
|
+
__publicField(this, "axios");
|
|
252
|
+
this.axios = axios3.create({
|
|
253
|
+
baseURL: baseUrl,
|
|
254
|
+
withCredentials: !options?.apiKey,
|
|
255
|
+
headers: {
|
|
256
|
+
...options?.apiKey ? { "x-api-key": options.apiKey } : {}
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
async signIn(email, password) {
|
|
261
|
+
const response = await this.axios.post("/_archlast/admin/auth/sign-in", {
|
|
262
|
+
email,
|
|
263
|
+
password
|
|
264
|
+
});
|
|
265
|
+
return response.data;
|
|
266
|
+
}
|
|
267
|
+
async signOut() {
|
|
268
|
+
const response = await this.axios.post("/_archlast/admin/auth/sign-out");
|
|
269
|
+
return response.data;
|
|
270
|
+
}
|
|
271
|
+
async getProfile() {
|
|
272
|
+
const response = await this.axios.get("/_archlast/admin/auth/me");
|
|
273
|
+
return response.data;
|
|
274
|
+
}
|
|
275
|
+
async getSessions() {
|
|
276
|
+
const response = await this.axios.get("/_archlast/admin/auth/sessions");
|
|
277
|
+
return response.data;
|
|
278
|
+
}
|
|
279
|
+
async revokeSession(sessionId) {
|
|
280
|
+
const response = await this.axios.post("/_archlast/admin/auth/revoke-session", {
|
|
281
|
+
sessionId
|
|
282
|
+
});
|
|
283
|
+
return response.data;
|
|
284
|
+
}
|
|
285
|
+
async signOutAll() {
|
|
286
|
+
const response = await this.axios.post("/_archlast/admin/auth/sign-out-all");
|
|
287
|
+
return response.data;
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
var AdminClient = class {
|
|
291
|
+
// Add other admin clients here (users, tenants, etc.)
|
|
292
|
+
constructor(baseUrl, options) {
|
|
293
|
+
__publicField(this, "auth");
|
|
294
|
+
this.auth = new AdminAuthClient(baseUrl, options);
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
// src/client.ts
|
|
299
|
+
var ArchlastClient = class {
|
|
300
|
+
/**
|
|
301
|
+
* @param url WebSocket URL
|
|
302
|
+
* @param httpUrl Backend HTTP URL (used for WS derivation fallback)
|
|
303
|
+
* @param appId App ID for session isolation
|
|
304
|
+
* @param authUrl Optional same-origin URL for auth requests (to avoid cross-origin cookie issues)
|
|
305
|
+
* @param options Configuration options
|
|
306
|
+
*/
|
|
307
|
+
constructor(url, httpUrl, appId, authUrl, options = {}) {
|
|
308
|
+
__publicField(this, "ws", null);
|
|
309
|
+
__publicField(this, "url");
|
|
310
|
+
__publicField(this, "listeners", /* @__PURE__ */ new Map());
|
|
311
|
+
__publicField(this, "subscriptions", /* @__PURE__ */ new Map());
|
|
312
|
+
__publicField(this, "pendingMutations", /* @__PURE__ */ new Map());
|
|
313
|
+
__publicField(this, "messageQueue", []);
|
|
314
|
+
__publicField(this, "isConnected", false);
|
|
315
|
+
__publicField(this, "reconnectAttempts", 0);
|
|
316
|
+
__publicField(this, "maxReconnectAttempts", 5);
|
|
317
|
+
__publicField(this, "reconnectDelay", 1e3);
|
|
318
|
+
__publicField(this, "reconnectTimeout", null);
|
|
319
|
+
__publicField(this, "isExplicitlyClosed", false);
|
|
320
|
+
__publicField(this, "sessionId", null);
|
|
321
|
+
// Event listeners
|
|
322
|
+
__publicField(this, "connectionListeners", /* @__PURE__ */ new Set());
|
|
323
|
+
__publicField(this, "disconnectionListeners", /* @__PURE__ */ new Set());
|
|
324
|
+
__publicField(this, "errorListeners", /* @__PURE__ */ new Set());
|
|
325
|
+
__publicField(this, "auth");
|
|
326
|
+
__publicField(this, "storage");
|
|
327
|
+
__publicField(this, "admin");
|
|
328
|
+
__publicField(this, "baseUrl");
|
|
329
|
+
__publicField(this, "appId");
|
|
330
|
+
__publicField(this, "isAdmin");
|
|
331
|
+
__publicField(this, "apiKey");
|
|
332
|
+
__publicField(this, "betterAuthCookies");
|
|
333
|
+
__publicField(this, "heartbeatInterval", null);
|
|
334
|
+
this.url = url;
|
|
335
|
+
this.appId = appId;
|
|
336
|
+
this.isAdmin = options.isAdmin ?? false;
|
|
337
|
+
this.apiKey = options.apiKey;
|
|
338
|
+
this.betterAuthCookies = options.betterAuthCookies;
|
|
339
|
+
const derivedHttpUrl = httpUrl !== void 0 ? httpUrl : url.replace(/^ws/, "http");
|
|
340
|
+
const authBaseUrl = authUrl !== void 0 ? authUrl : derivedHttpUrl;
|
|
341
|
+
this.baseUrl = authBaseUrl;
|
|
342
|
+
this.auth = new ArchlastAuthClient({ baseUrl: authBaseUrl, appId, apiKey: options.apiKey });
|
|
343
|
+
this.storage = new StorageClient(authBaseUrl, appId, { apiKey: options.apiKey });
|
|
344
|
+
this.admin = new AdminClient(authBaseUrl, { apiKey: options.apiKey });
|
|
345
|
+
if (options.autoConnect !== false) {
|
|
346
|
+
this.connect();
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Update Better-Auth cookies (call this when session changes)
|
|
351
|
+
*/
|
|
352
|
+
setBetterAuthCookies(cookies) {
|
|
353
|
+
this.betterAuthCookies = cookies;
|
|
354
|
+
if (this.isConnected) {
|
|
355
|
+
this.connect();
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Update Better-Auth API key (call this when API key changes)
|
|
360
|
+
*/
|
|
361
|
+
setApiKey(apiKey) {
|
|
362
|
+
this.apiKey = apiKey;
|
|
363
|
+
if (this.isConnected) {
|
|
364
|
+
this.connect();
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
connect() {
|
|
368
|
+
if (typeof window === "undefined") {
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
this.isExplicitlyClosed = false;
|
|
372
|
+
if (this.ws) {
|
|
373
|
+
if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
try {
|
|
377
|
+
this.ws.close();
|
|
378
|
+
} catch (e) {
|
|
379
|
+
}
|
|
380
|
+
this.ws = null;
|
|
381
|
+
}
|
|
382
|
+
try {
|
|
383
|
+
this.ws = new WebSocket(this.url);
|
|
384
|
+
} catch (e) {
|
|
385
|
+
this.handleClose();
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
this.ws.onopen = async () => {
|
|
389
|
+
console.log("Connected to Archlast Server");
|
|
390
|
+
this.isConnected = true;
|
|
391
|
+
this.reconnectAttempts = 0;
|
|
392
|
+
const headers = {};
|
|
393
|
+
if (this.appId) {
|
|
394
|
+
headers["x-archlast-app-id"] = this.appId;
|
|
395
|
+
}
|
|
396
|
+
if (this.apiKey) {
|
|
397
|
+
headers["x-api-key"] = this.apiKey;
|
|
398
|
+
}
|
|
399
|
+
const cookies = {};
|
|
400
|
+
if (this.betterAuthCookies) {
|
|
401
|
+
Object.assign(cookies, this.betterAuthCookies);
|
|
402
|
+
}
|
|
403
|
+
this.sendMessage({
|
|
404
|
+
type: "connect",
|
|
405
|
+
auth: {
|
|
406
|
+
headers: Object.keys(headers).length > 0 ? headers : void 0,
|
|
407
|
+
cookies: Object.keys(cookies).length > 0 ? cookies : void 0
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
if (this.isAdmin) {
|
|
411
|
+
this.sendMessage({
|
|
412
|
+
type: "subscribe_logs"
|
|
413
|
+
});
|
|
414
|
+
this.sendMessage({
|
|
415
|
+
type: "subscribe_admin_events"
|
|
416
|
+
});
|
|
417
|
+
} else {
|
|
418
|
+
try {
|
|
419
|
+
const state = await this.auth.getState();
|
|
420
|
+
console.log("Auth state:", state);
|
|
421
|
+
if (state.isAuthenticated) {
|
|
422
|
+
this.sendMessage({
|
|
423
|
+
type: "subscribe_logs"
|
|
424
|
+
});
|
|
425
|
+
this.sendMessage({
|
|
426
|
+
type: "subscribe_admin_events"
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
} catch (err) {
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
this.flushQueue();
|
|
433
|
+
this.resubscribeAll();
|
|
434
|
+
this.startHeartbeat();
|
|
435
|
+
};
|
|
436
|
+
this.ws.onmessage = (event) => this.handleMessage(event);
|
|
437
|
+
this.ws.onclose = () => this.handleClose();
|
|
438
|
+
this.ws.onerror = (err) => {
|
|
439
|
+
if (!this.isExplicitlyClosed) {
|
|
440
|
+
console.error("WebSocket error:", err);
|
|
441
|
+
this.ws?.close();
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
startHeartbeat() {
|
|
446
|
+
this.stopHeartbeat();
|
|
447
|
+
this.heartbeatInterval = setInterval(() => {
|
|
448
|
+
if (this.isConnected) {
|
|
449
|
+
this.sendMessage({ type: "ping" });
|
|
450
|
+
}
|
|
451
|
+
}, 3e4);
|
|
452
|
+
}
|
|
453
|
+
stopHeartbeat() {
|
|
454
|
+
if (this.heartbeatInterval) {
|
|
455
|
+
clearInterval(this.heartbeatInterval);
|
|
456
|
+
this.heartbeatInterval = null;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
handleClose() {
|
|
460
|
+
this.isConnected = false;
|
|
461
|
+
this.sessionId = null;
|
|
462
|
+
this.disconnectionListeners.forEach((l) => l("Disconnected"));
|
|
463
|
+
if (this.isExplicitlyClosed) return;
|
|
464
|
+
if (this.reconnectAttempts < this.maxReconnectAttempts) {
|
|
465
|
+
const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts);
|
|
466
|
+
console.log(`Disconnected. Reconnecting in ${delay}ms...`);
|
|
467
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
468
|
+
this.reconnectAttempts++;
|
|
469
|
+
this.connect();
|
|
470
|
+
}, delay);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
handleMessage(event) {
|
|
474
|
+
try {
|
|
475
|
+
const msg = JSON.parse(event.data);
|
|
476
|
+
if (msg.type === "data" || msg.type === "patch") {
|
|
477
|
+
const queryId = msg.queryId;
|
|
478
|
+
const data = msg.data || msg.patch;
|
|
479
|
+
const listeners = this.listeners.get(queryId);
|
|
480
|
+
if (listeners) {
|
|
481
|
+
listeners.forEach((l) => l(data));
|
|
482
|
+
}
|
|
483
|
+
} else if (msg.type === "mutationResponse") {
|
|
484
|
+
const pending = this.pendingMutations.get(msg.mutationId);
|
|
485
|
+
if (pending) {
|
|
486
|
+
clearTimeout(pending.timeout);
|
|
487
|
+
this.pendingMutations.delete(msg.mutationId);
|
|
488
|
+
if (msg.success) {
|
|
489
|
+
pending.resolve(msg.data);
|
|
490
|
+
} else {
|
|
491
|
+
pending.reject(new Error(msg.error));
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
} else if (msg.type === "connected") {
|
|
495
|
+
console.log("Session established:", msg.sessionId);
|
|
496
|
+
this.sessionId = msg.sessionId;
|
|
497
|
+
this.isConnected = true;
|
|
498
|
+
this.reconnectAttempts = 0;
|
|
499
|
+
this.connectionListeners.forEach((l) => l(msg.sessionId));
|
|
500
|
+
} else if (msg.type === "error") {
|
|
501
|
+
console.error("Server error:", msg.message);
|
|
502
|
+
this.errorListeners.forEach((l) => l(msg.message));
|
|
503
|
+
if (msg.message === "Authentication required") {
|
|
504
|
+
this.isExplicitlyClosed = true;
|
|
505
|
+
this.ws?.close();
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
} catch (e) {
|
|
509
|
+
console.error("Error handling message:", e);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
getWs() {
|
|
513
|
+
return this.ws;
|
|
514
|
+
}
|
|
515
|
+
onConnected(cb) {
|
|
516
|
+
this.connectionListeners.add(cb);
|
|
517
|
+
return () => this.connectionListeners.delete(cb);
|
|
518
|
+
}
|
|
519
|
+
onDisconnected(cb) {
|
|
520
|
+
this.disconnectionListeners.add(cb);
|
|
521
|
+
return () => this.disconnectionListeners.delete(cb);
|
|
522
|
+
}
|
|
523
|
+
onError(cb) {
|
|
524
|
+
this.errorListeners.add(cb);
|
|
525
|
+
return () => this.errorListeners.delete(cb);
|
|
526
|
+
}
|
|
527
|
+
getStatus() {
|
|
528
|
+
return this.isConnected ? "connected" : "disconnected";
|
|
529
|
+
}
|
|
530
|
+
getSessionId() {
|
|
531
|
+
return this.sessionId;
|
|
532
|
+
}
|
|
533
|
+
sendMessage(msg) {
|
|
534
|
+
const data = JSON.stringify(msg);
|
|
535
|
+
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
536
|
+
this.ws.send(data);
|
|
537
|
+
} else {
|
|
538
|
+
this.messageQueue.push(data);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
flushQueue() {
|
|
542
|
+
while (this.messageQueue.length > 0) {
|
|
543
|
+
const msg = this.messageQueue.shift();
|
|
544
|
+
if (msg) this.ws?.send(msg);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
resubscribeAll() {
|
|
548
|
+
for (const [queryId, sub] of Array.from(this.subscriptions.entries())) {
|
|
549
|
+
this.sendMessage({
|
|
550
|
+
type: "query",
|
|
551
|
+
queryId,
|
|
552
|
+
name: sub.name,
|
|
553
|
+
args: sub.args
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
getQueryId(name, args) {
|
|
558
|
+
const stableArgs = JSON.stringify(args, Object.keys(args || {}).sort());
|
|
559
|
+
return `${name}:${stableArgs}`;
|
|
560
|
+
}
|
|
561
|
+
subscribe(queryName, args, onUpdate) {
|
|
562
|
+
const queryId = this.getQueryId(queryName, args);
|
|
563
|
+
if (!this.listeners.has(queryId)) {
|
|
564
|
+
this.listeners.set(queryId, /* @__PURE__ */ new Set());
|
|
565
|
+
this.subscriptions.set(queryId, { name: queryName, args });
|
|
566
|
+
this.sendMessage({
|
|
567
|
+
type: "query",
|
|
568
|
+
queryId,
|
|
569
|
+
name: queryName,
|
|
570
|
+
args
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
this.listeners.get(queryId).add(onUpdate);
|
|
574
|
+
return () => {
|
|
575
|
+
const set = this.listeners.get(queryId);
|
|
576
|
+
if (set) {
|
|
577
|
+
set.delete(onUpdate);
|
|
578
|
+
if (set.size === 0) {
|
|
579
|
+
this.listeners.delete(queryId);
|
|
580
|
+
this.subscriptions.delete(queryId);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
async fetch(name, args) {
|
|
586
|
+
const queryId = this.getQueryId(name, args);
|
|
587
|
+
return new Promise((resolve, reject) => {
|
|
588
|
+
let resolved = false;
|
|
589
|
+
const unsubscribe = this.subscribe(name, args, (data) => {
|
|
590
|
+
if (!resolved) {
|
|
591
|
+
resolved = true;
|
|
592
|
+
unsubscribe();
|
|
593
|
+
resolve(data);
|
|
594
|
+
}
|
|
595
|
+
});
|
|
596
|
+
setTimeout(() => {
|
|
597
|
+
if (!resolved) {
|
|
598
|
+
resolved = true;
|
|
599
|
+
unsubscribe();
|
|
600
|
+
reject(new Error("Timeout waiting for data"));
|
|
601
|
+
}
|
|
602
|
+
}, 5e3);
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
async mutate(name, args) {
|
|
606
|
+
return new Promise((resolve, reject) => {
|
|
607
|
+
const mutationId = Math.random().toString(36).slice(2);
|
|
608
|
+
const timeout = setTimeout(() => {
|
|
609
|
+
this.pendingMutations.delete(mutationId);
|
|
610
|
+
reject(new Error("Mutation timeout"));
|
|
611
|
+
}, 1e4);
|
|
612
|
+
this.pendingMutations.set(mutationId, { resolve, reject, timeout });
|
|
613
|
+
this.sendMessage({
|
|
614
|
+
type: "mutation",
|
|
615
|
+
mutationId,
|
|
616
|
+
name,
|
|
617
|
+
args
|
|
618
|
+
});
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
close() {
|
|
622
|
+
this.isExplicitlyClosed = true;
|
|
623
|
+
if (this.reconnectTimeout) {
|
|
624
|
+
clearTimeout(this.reconnectTimeout);
|
|
625
|
+
this.reconnectTimeout = null;
|
|
626
|
+
}
|
|
627
|
+
if (this.ws) {
|
|
628
|
+
this.ws.onclose = null;
|
|
629
|
+
this.ws.onopen = null;
|
|
630
|
+
this.ws.onerror = null;
|
|
631
|
+
this.ws.onmessage = null;
|
|
632
|
+
this.ws.close();
|
|
633
|
+
this.ws = null;
|
|
634
|
+
}
|
|
635
|
+
this.isConnected = false;
|
|
636
|
+
this.stopHeartbeat();
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
export {
|
|
640
|
+
ArchlastClient
|
|
641
|
+
};
|
|
642
|
+
//# sourceMappingURL=client.js.map
|