@chainstream-io/sdk 0.1.20 → 0.1.22

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.
@@ -4,7 +4,6 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
4
4
 
5
5
  // src/stream/stream.ts
6
6
  import { Centrifuge } from "@chainstream-io/centrifuge";
7
- import { createRequire } from "module";
8
7
 
9
8
  // src/stream/stream.fields.ts
10
9
  var CEL_FIELD_MAPPINGS = {
@@ -269,62 +268,100 @@ var StreamApi = class {
269
268
  constructor(context) {
270
269
  __publicField(this, "realtimeClient");
271
270
  __publicField(this, "listenersMap");
272
- __publicField(this, "getTokenValue");
273
- const realtimeEndpoint = context.streamUrl;
274
- this.getTokenValue = async () => {
275
- return typeof context.accessToken === "string" ? context.accessToken : await context.accessToken.getToken();
276
- };
277
- let wsImpl = void 0;
278
- if (typeof process !== "undefined" && process.versions?.node) {
279
- try {
280
- const require2 = createRequire(import.meta.url);
281
- wsImpl = require2("ws");
282
- } catch {
283
- }
284
- }
285
- if (!wsImpl && typeof WebSocket !== "undefined") {
286
- wsImpl = WebSocket;
271
+ __publicField(this, "context");
272
+ __publicField(this, "initPromise", null);
273
+ this.context = context;
274
+ this.listenersMap = /* @__PURE__ */ new Map();
275
+ }
276
+ /**
277
+ * Initialize Centrifuge client with current token
278
+ * This is called lazily when connect() is called
279
+ */
280
+ async initClient() {
281
+ if (this.realtimeClient) {
282
+ return;
287
283
  }
284
+ const token = await this.getTokenValue();
285
+ const realtimeEndpoint = this.buildWsUrl(this.context.streamUrl, token);
288
286
  this.realtimeClient = new Centrifuge(realtimeEndpoint, {
289
- ...wsImpl && { websocket: wsImpl },
290
287
  getToken: async (_ctx) => {
291
- const token = await this.getTokenValue();
292
- this.realtimeClient.setHttpHeaders({
293
- Authorization: `Bearer ${token}`,
294
- "User-Agent": `chainstream-io/sdk/javascript`
295
- });
296
- return token;
288
+ return this.getTokenValue();
297
289
  }
298
290
  });
299
291
  this.realtimeClient.on("connected", () => {
300
292
  console.log("[streaming] connected");
301
- }).on("disconnected", (err) => {
302
- console.warn("[streaming] disconnected", err);
293
+ }).on("disconnected", (ctx) => {
294
+ console.warn("[streaming] disconnected", ctx);
303
295
  }).on("error", (err) => {
304
296
  console.error("[streaming] error: ", err);
305
297
  });
306
- this.listenersMap = /* @__PURE__ */ new Map();
307
298
  }
308
- async connect() {
309
- const token = await this.getTokenValue();
310
- this.realtimeClient.setHttpHeaders({
311
- Authorization: `Bearer ${token}`
299
+ /**
300
+ * Wait for initialization to complete
301
+ * If not initialized, auto-connect first
302
+ */
303
+ async ensureInitialized() {
304
+ if (!this.initPromise) {
305
+ this.connect();
306
+ }
307
+ await this.initPromise;
308
+ }
309
+ /**
310
+ * Get token value from string or TokenProvider
311
+ */
312
+ async getTokenValue() {
313
+ return typeof this.context.accessToken === "string" ? this.context.accessToken : await this.context.accessToken.getToken();
314
+ }
315
+ /**
316
+ * Build WebSocket URL with token as query parameter
317
+ */
318
+ buildWsUrl(endpoint, token) {
319
+ const url = new URL(endpoint);
320
+ url.searchParams.set("token", token);
321
+ return url.toString();
322
+ }
323
+ /**
324
+ * Connect to the WebSocket server.
325
+ * This is automatically called when you use subscribe methods if not already connected.
326
+ * You can also call this method manually for explicit control.
327
+ */
328
+ connect() {
329
+ this.initPromise = this.initClient().then(() => {
330
+ this.realtimeClient.connect();
312
331
  });
313
- this.realtimeClient.connect();
332
+ }
333
+ /**
334
+ * Disconnect from the WebSocket server.
335
+ * All subscriptions will be automatically removed.
336
+ */
337
+ disconnect() {
338
+ if (this.realtimeClient) {
339
+ this.realtimeClient.disconnect();
340
+ }
341
+ }
342
+ /**
343
+ * Check if the WebSocket is currently connected.
344
+ */
345
+ isConnected() {
346
+ return this.realtimeClient?.state === "connected";
314
347
  }
315
348
  /**
316
349
  * Start batching commands for efficient bulk operations
317
350
  * All subscription commands after this call will be batched until stopBatching is called
318
351
  */
319
352
  startBatching() {
320
- this.realtimeClient.startBatching();
353
+ if (this.realtimeClient) {
354
+ this.realtimeClient.startBatching();
355
+ }
321
356
  }
322
357
  /**
323
358
  * Stop batching and flush all collected commands to the server
324
359
  * This will send all batched subscription commands in a single network request
325
360
  */
326
361
  stopBatching() {
327
- this.realtimeClient.stopBatching();
362
+ if (this.realtimeClient) {
363
+ this.realtimeClient.stopBatching();
364
+ }
328
365
  }
329
366
  /**
330
367
  * Batch subscribe method that accepts a function containing subscription calls
@@ -354,26 +391,31 @@ var StreamApi = class {
354
391
  });
355
392
  }
356
393
  subscribe(channel, fn, filter, methodName) {
357
- let sub = this.realtimeClient.getSubscription(channel);
358
394
  let listeners = this.listenersMap.get(channel);
359
- if (!sub) {
395
+ if (!listeners) {
360
396
  listeners = /* @__PURE__ */ new Set();
361
397
  this.listenersMap.set(channel, listeners);
362
- console.log("[xrealtime] create new sub: ", channel);
363
- const processedFilter = filter && methodName ? replaceFilterFields(filter, methodName) : filter;
364
- sub = this.realtimeClient.newSubscription(channel, {
365
- delta: "fossil",
366
- ...processedFilter && { filter: processedFilter }
367
- });
368
- sub.on("subscribed", () => {
369
- console.log("[xrealtime] subscribed", channel);
370
- }).on("unsubscribed", () => {
371
- console.log("[xrealtime] unsubscribed", channel);
372
- }).on("publication", (ctx) => {
373
- listeners?.forEach((it) => it(ctx.data));
374
- }).subscribe();
375
398
  }
376
- listeners?.add(fn);
399
+ listeners.add(fn);
400
+ this.ensureInitialized().then(() => {
401
+ let sub = this.realtimeClient.getSubscription(channel);
402
+ if (!sub) {
403
+ console.log("[xrealtime] create new sub: ", channel);
404
+ const processedFilter = filter && methodName ? replaceFilterFields(filter, methodName) : filter;
405
+ sub = this.realtimeClient.newSubscription(channel, {
406
+ delta: "fossil",
407
+ ...processedFilter && { filter: processedFilter }
408
+ });
409
+ sub.on("subscribed", () => {
410
+ console.log("[xrealtime] subscribed", channel);
411
+ }).on("unsubscribed", () => {
412
+ console.log("[xrealtime] unsubscribed", channel);
413
+ }).on("publication", (ctx) => {
414
+ const currentListeners = this.listenersMap.get(channel);
415
+ currentListeners?.forEach((it) => it(ctx.data));
416
+ }).subscribe();
417
+ }
418
+ });
377
419
  return new StreamUnsubscrible(this, channel, fn);
378
420
  }
379
421
  unsubscribe(channel, fn) {
@@ -385,12 +427,14 @@ var StreamApi = class {
385
427
  console.log("unsubscribe, remain listeners: ", listeners.size);
386
428
  if (listeners.size === 0) {
387
429
  console.log("unsubscribe channel: ", channel);
388
- const sub = this.realtimeClient.getSubscription(channel);
389
- if (sub) {
390
- sub.unsubscribe();
391
- this.realtimeClient.removeSubscription(sub);
392
- }
393
430
  this.listenersMap.delete(channel);
431
+ this.ensureInitialized().then(() => {
432
+ const sub = this.realtimeClient.getSubscription(channel);
433
+ if (sub) {
434
+ sub.unsubscribe();
435
+ this.realtimeClient.removeSubscription(sub);
436
+ }
437
+ });
394
438
  }
395
439
  }
396
440
  formatScientificNotation(value) {