@openfeed/sdk-js 1.8.1 → 1.8.2

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/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ## [1.8.2](https://github.com/openfeed-org/sdk-js/compare/1.8.1...1.8.2) (2026-11-17)
6
+
7
+
8
+ ### Bug Fixes
9
+
10
+ * improve reconnection logic ([d94ff07](https://github.com/openfeed-org/sdk-js/commit/d94ff07f753914e01bf88b149aaa04b97c6a3748))
11
+ * retry silent connection before login, too ([5fd703e](https://github.com/openfeed-org/sdk-js/commit/5fd703ee5351f5aac1efe8470ba2279ce1d88ff5))
12
+ * update send type so it excludes empty objects ([ad9b919](https://github.com/openfeed-org/sdk-js/commit/ad9b919458c93d7c453648e5df7c3a3f93c17c73))
13
+
5
14
  ## [1.8.1](https://github.com/openfeed-org/sdk-js/compare/1.8.0...1.8.1) (2026-11-06)
6
15
 
7
16
 
package/DOCUMENTATION.md CHANGED
@@ -55,6 +55,8 @@ The `onMessageWithMetadata` callback will be called when a new message is receiv
55
55
 
56
56
  The last callback we wired is `onCredentialsRejected`, which will be called if you attempt to connect with wrong credentials or there was a second login with the same credentials. This is a terminal state - if you receive this callbacks no other callbacks will be called and no other connection attempts will be made. The only sensible thing to do in this case is to dispose the connection client object and then create a new one with the correct credentials.
57
57
 
58
+ Any other failure is retried: the client drops the connection and connects again after a few seconds. That includes a login that fails for a reason other than the credentials, and a connection that stays silent for about 15 seconds, before logging in as well as after.
59
+
58
60
  Two callbacks aren't wired in the example. `onHeartBeat` is called with each heartbeat the server sends, if you want to track that the connection is alive. `onCleanup` is used internally to clear the instrument definitions and symbol names kept for `onMessageWithMetadata` when the connection drops, so leave it as it is.
59
61
 
60
62
  It is OK not to implement all these callbacks as they all have an existing default implementation.
package/README.md CHANGED
@@ -28,12 +28,19 @@ This library uses [Conventional Commits](https://www.conventionalcommits.org/en/
28
28
 
29
29
  ### Setup
30
30
 
31
+ The project uses Yarn 4, through [Corepack](https://github.com/nodejs/corepack): run `corepack enable` once (on Node 25 or later, install Corepack first with `npm i -g corepack`). Then:
32
+
31
33
  ```shell
32
34
  yarn
35
+ yarn hooks:install
33
36
  yarn generate:version
34
37
  ```
35
38
 
36
- `generate:version` writes `generated/version.ts`, which isn't committed. The tests, the linter and the type checker all need it, so run it once after cloning (the build scripts run it themselves).
39
+ `hooks:install` installs the git hooks (`.husky/`), which check each commit message with commitlint. `yarn` doesn't install them, since this repository runs no install scripts, its dependencies' included (`enableScripts: false` in `.yarnrc.yml`).
40
+
41
+ `generate:version` writes `generated/version.ts`, which isn't committed. The tests, the linter and the type checker all need it, so run it once after cloning.
42
+
43
+ `build:ts`, `run:browser` and `run:node` run both of these themselves.
37
44
 
38
45
  ### Checks
39
46
 
@@ -59,7 +66,7 @@ Both write to `dist`. Run `build:ts` first, as it clears `dist` before building.
59
66
 
60
67
  ### Updating the proto files
61
68
 
62
- The generated code in `generated/` comes from the [openfeed-org/proto](https://github.com/openfeed-org/proto) repository, which is installed over SSH, so you need SSH access to it. You also need `protoc` on your `PATH`: download it from the [protobuf releases](https://github.com/protocolbuffers/protobuf/releases), or on macOS run `brew install protobuf`.
69
+ The generated code in `generated/` comes from the [openfeed-org/proto](https://github.com/openfeed-org/proto) repository, which `yarn generate` clones over SSH into `.proto/` (not committed), so you need SSH access to it. You also need `protoc` on your `PATH`: download it from the [protobuf releases](https://github.com/protocolbuffers/protobuf/releases), or on macOS run `brew install protobuf`.
63
70
 
64
71
  Then run:
65
72
 
@@ -67,7 +74,7 @@ Then run:
67
74
  yarn generate
68
75
  ```
69
76
 
70
- This pulls the latest proto files, generates the TypeScript code with `ts-proto`, and post-processes it (splitting encoders from decoders to keep the bundle small, and writing `generated/index.ts`). Commit the changes to `generated/` and `yarn.lock`.
77
+ This pulls the latest proto files, generates the TypeScript code with `ts-proto`, and post-processes it (splitting encoders from decoders to keep the bundle small, and writing `generated/index.ts`). Commit the changes to `generated/`.
71
78
 
72
79
  ### Releasing
73
80
 
@@ -1 +1 @@
1
- export declare const version = "1.8.1";
1
+ export declare const version = "1.8.2";
package/dist/index.js CHANGED
@@ -9826,8 +9826,8 @@ var receive = (msgEvent) => [...decodeMessages(new Uint8Array(msgEvent.data))];
9826
9826
  // src/utilities/constants.ts
9827
9827
  var TIME = {
9828
9828
  RECONNECT: 5e3,
9829
- RECONNECT_RANDOMIZE: 5e3,
9830
- CONNECTION_TIMEOUT: 15e3,
9829
+ RECONNECT_MAX: 6e4,
9830
+ CONNECTION_TIMEOUT: 2e4,
9831
9831
  SUBSCRIPTION_RETRY: 100
9832
9832
  };
9833
9833
  // src/connection/errors.ts
@@ -9883,27 +9883,33 @@ var OpenFeedConnection = class {
9883
9883
  this.socket.onclose = this.onClose;
9884
9884
  this.runConnectionWatchLoop();
9885
9885
  }
9886
- messageTriggered = false;
9886
+ lastMessageAt = performance.now();
9887
+ /**
9888
+ * Drops the connection once it has been silent for `CONNECTION_TIMEOUT`. Messages only note when they came, and the
9889
+ * timer, when it fires early, waits out the rest, so there's no timer to reset on every message.
9890
+ */
9887
9891
  runConnectionWatchLoop = async () => {
9892
+ let delay = TIME.CONNECTION_TIMEOUT;
9888
9893
  for (;;) {
9889
9894
  const wait = new ResolutionSource();
9890
- const timeoutId = setTimeout(wait.resolve, TIME.CONNECTION_TIMEOUT + Math.floor(Math.random() * TIME.RECONNECT_RANDOMIZE));
9895
+ const timeoutId = setTimeout(wait.resolve, delay);
9891
9896
  try {
9892
9897
  await Promise.race([wait.whenCompleted, this.whenDisconnectedSource.whenCompleted]);
9893
9898
  } catch {}
9894
9899
  clearTimeout(timeoutId);
9895
9900
  if (this.whenDisconnectedSource.completed) break;
9896
- if (!this.messageTriggered) {
9901
+ const silentFor = performance.now() - this.lastMessageAt;
9902
+ if (silentFor >= TIME.CONNECTION_TIMEOUT) {
9897
9903
  this.logger?.warn("Connection silent, disconnecting");
9898
9904
  this.disconnect(/* @__PURE__ */ new Error("Socket closed: Connection silent"));
9899
9905
  break;
9900
9906
  }
9901
- this.messageTriggered = false;
9907
+ delay = TIME.CONNECTION_TIMEOUT - silentFor;
9902
9908
  }
9903
9909
  };
9904
9910
  onMessage = (event) => {
9905
9911
  try {
9906
- this.messageTriggered = true;
9912
+ this.lastMessageAt = performance.now();
9907
9913
  const messages = receive(event);
9908
9914
  for (const message of messages) if (!this.handleMessage(message)) return;
9909
9915
  } catch (error) {
@@ -10052,31 +10058,32 @@ var OpenFeedConnection = class {
10052
10058
  send = (msg, requestedCorrelationId) => {
10053
10059
  const correlationId = requestedCorrelationId ?? CorrelationId.create();
10054
10060
  const token = this.connectionToken;
10055
- const msg2 = {};
10056
- if (msg.exchangeRequest !== void 0) msg2.exchangeRequest = {
10057
- ...msg.exchangeRequest,
10058
- correlationId,
10059
- token
10060
- };
10061
- else if (msg.instrumentReferenceRequest !== void 0) msg2.instrumentReferenceRequest = {
10062
- ...msg.instrumentReferenceRequest,
10063
- correlationId,
10064
- token
10065
- };
10066
- else if (msg.instrumentRequest !== void 0) msg2.instrumentRequest = {
10067
- ...msg.instrumentRequest,
10068
- correlationId,
10069
- token
10070
- };
10071
- else if (msg.listSubscriptionsRequest !== void 0) msg2.listSubscriptionsRequest = {
10072
- ...msg.listSubscriptionsRequest,
10073
- correlationId,
10074
- token
10075
- };
10076
- else if (msg.subscriptionRequest !== void 0) msg2.subscriptionRequest = {
10077
- ...msg.subscriptionRequest,
10078
- correlationId,
10079
- token
10061
+ const msg2 = {
10062
+ exchangeRequest: msg.exchangeRequest && {
10063
+ ...msg.exchangeRequest,
10064
+ correlationId,
10065
+ token
10066
+ },
10067
+ instrumentReferenceRequest: msg.instrumentReferenceRequest && {
10068
+ ...msg.instrumentReferenceRequest,
10069
+ correlationId,
10070
+ token
10071
+ },
10072
+ instrumentRequest: msg.instrumentRequest && {
10073
+ ...msg.instrumentRequest,
10074
+ correlationId,
10075
+ token
10076
+ },
10077
+ listSubscriptionsRequest: msg.listSubscriptionsRequest && {
10078
+ ...msg.listSubscriptionsRequest,
10079
+ correlationId,
10080
+ token
10081
+ },
10082
+ subscriptionRequest: msg.subscriptionRequest && {
10083
+ ...msg.subscriptionRequest,
10084
+ correlationId,
10085
+ token
10086
+ }
10080
10087
  };
10081
10088
  send(this.socket, msg2);
10082
10089
  return correlationId;
@@ -10147,7 +10154,7 @@ var OpenFeedConnection = class {
10147
10154
  };
10148
10155
  };
10149
10156
  // generated/version.ts
10150
- var version = "1.8.1";
10157
+ var version = "1.8.2";
10151
10158
  // src/utilities/client_version.ts
10152
10159
  var describeNodePlatform = async () => {
10153
10160
  const os = await import("./empty-D7pqD0vK.js");
@@ -10164,6 +10171,24 @@ var getClientVersion = async (clientId) => {
10164
10171
  const platformDescription = typeof window === "undefined" ? await describeNodePlatform() : navigator.userAgent;
10165
10172
  return `sdk-js:${version};client-id:${clientId ?? "default"};platform:${platformDescription}`;
10166
10173
  };
10174
+ // src/utilities/reconnect_backoff.ts
10175
+ /**
10176
+ * Exponential backoff with jitter for reconnects, as in `sdk-net`: each attempt doubles the delay, up to the maximum, and
10177
+ * waits a random time in its upper half, so clients dropped together don't all come back at once.
10178
+ */
10179
+ var ReconnectBackoff = class {
10180
+ delay = TIME.RECONNECT;
10181
+ /** The next wait: 5-10s, then 10-20s, 20-40s, and 30-60s from then on, until reset. */
10182
+ nextDelay = () => {
10183
+ this.delay = Math.min(this.delay * 2, TIME.RECONNECT_MAX);
10184
+ const half = this.delay / 2;
10185
+ return half + Math.floor(Math.random() * half);
10186
+ };
10187
+ /** Called once logged in, so the next disconnect starts again from the shortest wait. */
10188
+ reset = () => {
10189
+ this.delay = TIME.RECONNECT;
10190
+ };
10191
+ };
10167
10192
  // src/connection/client.ts
10168
10193
  var OpenFeedClient = class {
10169
10194
  url;
@@ -10178,6 +10203,7 @@ var OpenFeedClient = class {
10178
10203
  whenConnectedSource = new ResolutionSource();
10179
10204
  loopResetSource = new ResolutionSource();
10180
10205
  subscribeResetSource = new ResolutionSource();
10206
+ reconnectBackoff = new ReconnectBackoff();
10181
10207
  subscriptions = /* @__PURE__ */ new Map();
10182
10208
  constructor(url, username, password, listeners, logger, clientId) {
10183
10209
  this.url = url;
@@ -10204,6 +10230,7 @@ var OpenFeedClient = class {
10204
10230
  onMessage = async (event) => {
10205
10231
  const [message] = receive(event);
10206
10232
  if (message.loginResponse?.token && this.socket) {
10233
+ this.reconnectBackoff.reset();
10207
10234
  this._connection = new OpenFeedConnection(message.loginResponse.token, this.socket, this.listeners, this.logger);
10208
10235
  this.whenConnectedInternalSource.resolve(this._connection);
10209
10236
  this.whenConnectedSource.resolve(this._connection);
@@ -10231,6 +10258,12 @@ var OpenFeedClient = class {
10231
10258
  ].includes(message.loginResponse?.status?.result ?? Result.SUCCESS)) {
10232
10259
  this.logger?.warn("Received authentication error, disconnecting...");
10233
10260
  this.whenConnectedInternalSource.reject(new InvalidCredentialsError("Invalid credentials provided. Please update credentials and try again."));
10261
+ } else if (message.loginResponse) {
10262
+ const result = message.loginResponse.status?.result ?? Result.UNKNOWN_RESULT;
10263
+ const name = Result[result] ?? String(result);
10264
+ const serverMessage = message.loginResponse.status?.message ?? "";
10265
+ this.logger?.warn("Login failed, trying again:", name, serverMessage);
10266
+ this.whenConnectedInternalSource.reject(new Error(`Login failed: ${name} ${serverMessage}`.trim()));
10234
10267
  }
10235
10268
  };
10236
10269
  onError = (error) => {
@@ -10241,6 +10274,25 @@ var OpenFeedClient = class {
10241
10274
  this.logger?.log(`Socket closed: ${event.reason}`);
10242
10275
  if (!this.whenConnectedInternalSource.completed) this.whenConnectedInternalSource.reject(/* @__PURE__ */ new Error(`Socket closed: ${event.reason}`));
10243
10276
  };
10277
+ /**
10278
+ * Waits for the login, as long as the socket isn't silent. Once logged in, the connection watches for silence; until
10279
+ * then this does, so a socket that connects and then goes quiet (a half-open connection, or a server that never
10280
+ * answers the login) is dropped and tried again, instead of waiting for a close that may never come.
10281
+ */
10282
+ whenLoggedInOrSilent = async (connecting) => {
10283
+ const silent = new ResolutionSource();
10284
+ const timeoutId = setTimeout(silent.resolve, TIME.CONNECTION_TIMEOUT);
10285
+ try {
10286
+ await Promise.race([connecting.whenCompleted, silent.whenCompleted]);
10287
+ } finally {
10288
+ clearTimeout(timeoutId);
10289
+ }
10290
+ if (!connecting.completed) {
10291
+ this.logger?.warn("Connection silent before login, disconnecting");
10292
+ connecting.reject(/* @__PURE__ */ new Error("Socket closed: Connection silent"));
10293
+ }
10294
+ return connecting.whenCompleted;
10295
+ };
10244
10296
  runConnectLoop = async () => {
10245
10297
  for (;;) {
10246
10298
  if (this.socket) {
@@ -10254,7 +10306,7 @@ var OpenFeedClient = class {
10254
10306
  this.socket.onmessage = (event) => void this.onMessage(event);
10255
10307
  this.socket.onerror = this.onError;
10256
10308
  this.socket.onclose = this.onClose;
10257
- await this.whenConnectedInternalSource.whenCompleted;
10309
+ await this.whenLoggedInOrSilent(this.whenConnectedInternalSource);
10258
10310
  await this.loopResetSource.whenCompleted;
10259
10311
  } catch (e) {
10260
10312
  this.logger?.error("Error when connecting to socket:", e);
@@ -10285,8 +10337,10 @@ var OpenFeedClient = class {
10285
10337
  this.loopResetSource = new ResolutionSource();
10286
10338
  this.subscribeResetSource.resolve();
10287
10339
  this.subscribeResetSource = new ResolutionSource();
10340
+ const delay = this.reconnectBackoff.nextDelay();
10341
+ this.logger?.log(`Reconnecting in ${delay.toString()}ms`);
10288
10342
  await new Promise((resolve) => {
10289
- setTimeout(resolve, TIME.RECONNECT + Math.floor(Math.random() * TIME.RECONNECT_RANDOMIZE));
10343
+ setTimeout(resolve, delay);
10290
10344
  });
10291
10345
  }
10292
10346
  };