@hyper-fetch/orpc 10.0.0 → 10.1.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.
@@ -2,7 +2,7 @@
2
2
  import type { QueryParamsType } from "@hyper-fetch/core";
3
3
  import { parseResponse, stringifyQueryParams } from "@hyper-fetch/core";
4
4
  import type { SocketConnectionType } from "@hyper-fetch/sockets";
5
- import { SocketAdapter } from "@hyper-fetch/sockets";
5
+ import { createReconnectingConnection, SocketAdapter } from "@hyper-fetch/sockets";
6
6
  import { isORPCErrorStatus } from "@orpc/client";
7
7
 
8
8
  import { createOrpcSerializer, getOrpcCallRequest, orpcEndpointMapper } from "../adapter/adapter.utils";
@@ -58,25 +58,11 @@ export const OrpcStreamAdapter = ({
58
58
  >({ name: "orpc-stream", confirmsSubscriptions: true })
59
59
  .setQueryParamsMapper(stringifyQueryParams)
60
60
  .setConnector((bindings) => {
61
- const {
62
- socket,
63
- adapter,
64
- getQueryParams,
65
- onConnect,
66
- onConnectFailed,
67
- onReconnect,
68
- onDisconnect,
69
- onConnected,
70
- onDisconnected,
71
- } = bindings;
72
-
73
- const autoConnect = adapter.adapterOptions?.autoConnect ?? true;
61
+ const { socket, adapter, getQueryParams, onConnectFailed } = bindings;
74
62
 
75
63
  // Details of the current connection (after onConnect interceptors), every stream is opened with them.
76
64
  // Set only while the adapter is connected.
77
65
  let connection: SocketConnectionType<OrpcStreamAdapterType> | undefined;
78
- // Connection attempt in progress - concurrent `connect()` calls join it
79
- let pendingConnection: Promise<boolean> | undefined;
80
66
 
81
67
  const subscriptions = createOrpcSubscriptions<OrpcStreamAdapterType, StreamTransportType>({
82
68
  bindings,
@@ -111,11 +97,9 @@ export const OrpcStreamAdapter = ({
111
97
  }
112
98
 
113
99
  const transport: StreamTransportType = { controller: undefined, timer: undefined, attempts, timedOut: false };
100
+ // Going offline closes the connection and stops the wait, coming back online starts the stream right away
114
101
  transport.timer = setTimeout(() => {
115
- // Offline the stream waits for the network and starts again when the app is back online
116
- if (socket.appManager.isOnline) {
117
- startStream(subscription, attempts);
118
- }
102
+ startStream(subscription, attempts);
119
103
  }, subscription.lastEventRetry ?? socket.reconnectTime);
120
104
  subscription.transport = transport;
121
105
  };
@@ -256,84 +240,43 @@ export const OrpcStreamAdapter = ({
256
240
  );
257
241
  };
258
242
 
259
- const openConnection = async (): Promise<boolean> => {
260
- const details = await onConnect();
261
- if (!details) {
262
- return adapter.connected;
263
- }
264
-
265
- if (typeof (details.adapterOptions?.fetch ?? globalThis.fetch) !== "function") {
266
- onConnectFailed({ error: new Error("fetch is not available in this environment") });
267
- return false;
268
- }
269
-
270
- connection = details;
271
- onConnected();
272
- [...subscriptions.values()].forEach((subscription) => {
273
- // A listener added by an `onConnected` callback is running already
274
- if (!subscription.transport) {
275
- startStream(subscription, 0);
276
- }
277
- });
278
- return true;
279
- };
280
-
281
- const connect = (): Promise<boolean> => {
282
- // Another attempt is already on its way (e.g. the automatic one) - resolve together with it
283
- if (adapter.connecting && pendingConnection) {
284
- return pendingConnection;
285
- }
286
-
287
- const attempt = openConnection();
288
- pendingConnection = attempt;
289
- const release = () => {
290
- if (pendingConnection === attempt) {
291
- pendingConnection = undefined;
292
- }
293
- };
294
- attempt.then(release, release);
295
-
296
- return attempt;
297
- };
298
-
299
243
  /** Aborts every stream. Listeners stay registered and keep the id of their last event for the next connection. */
300
- const closeConnection = async ({ manual }: { manual: boolean }): Promise<boolean> => {
301
- const wasActive = adapter.connected || adapter.connecting;
302
- connection = undefined;
303
- [...subscriptions.values()].forEach(stopStream);
304
-
305
- onDisconnect();
306
- if (!manual) {
307
- // Closing the previous streams is a part of reconnecting - only `disconnect()` keeps the socket closed
308
- adapter.setForceClosed(false);
309
- }
310
- if (wasActive) {
311
- onDisconnected();
312
- }
313
- return true;
244
+ const stopStreams = () => {
245
+ subscriptions.values().forEach(stopStream);
314
246
  };
315
247
 
316
- /** Manual disconnect - the socket stays closed until `connect()` or `reconnect()` is called */
317
- const disconnect = (): Promise<boolean> => {
318
- return closeConnection({ manual: true });
319
- };
320
-
321
- const reconnect = async () => {
322
- // Reconnecting is a request to be connected, also after a manual disconnect
323
- adapter.setForceClosed(false);
248
+ /**
249
+ * There is no shared transport - the connection is the set of streams opened with its details. It is ready at
250
+ * once, and it is never lost as a whole: every stream fails and starts again on its own (`scheduleRestart`).
251
+ */
252
+ const connectionLifecycle = createReconnectingConnection({
253
+ bindings,
254
+ autoConnect: adapter.adapterOptions?.autoConnect ?? true,
255
+ open: (attempt) => {
256
+ const details = attempt.connection;
257
+ if (typeof (details.adapterOptions?.fetch ?? globalThis.fetch) !== "function") {
258
+ onConnectFailed({ error: new Error("fetch is not available in this environment") });
259
+ return null;
260
+ }
324
261
 
325
- await onReconnect({
326
- disconnect: () => closeConnection({ manual: false }),
327
- connect: async () => {
328
- // `disconnect()` called in the meantime wins over the reconnection
329
- if (adapter.forceClosed) {
330
- adapter.setReconnectionAttempts(0);
331
- return false;
262
+ connection = details;
263
+ attempt.ready();
264
+ subscriptions.values().forEach((subscription) => {
265
+ // A listener added by an `onConnected` callback is running already
266
+ if (!subscription.transport) {
267
+ startStream(subscription, 0);
332
268
  }
333
- return connect();
334
- },
335
- });
336
- };
269
+ });
270
+
271
+ return {
272
+ close: () => {
273
+ // The engine closes an attempt before it opens the next one, so these are always the current details
274
+ connection = undefined;
275
+ stopStreams();
276
+ },
277
+ };
278
+ },
279
+ });
337
280
 
338
281
  // Event iterators only send data from the server. Throwing synchronously makes `emitter.emit()` fail right at
339
282
  // the call site, the same as in the Server-Sent Events adapter.
@@ -341,40 +284,17 @@ export const OrpcStreamAdapter = ({
341
284
  throw new Error("Cannot emit events in the oRPC stream adapter, it only receives events of subscriptions");
342
285
  };
343
286
 
344
- // Initialize
345
- if (autoConnect) {
346
- connect();
347
- }
348
-
349
- const unmountOnline = socket.appManager.events.onOnline(() => {
350
- if (connection) {
351
- // Streams that failed while offline start again right away
352
- [...subscriptions.values()].forEach((subscription) => {
353
- const { transport } = subscription;
354
- if (transport && !transport.controller) {
355
- clearTimeout(transport.timer);
356
- startStream(subscription, transport.attempts);
357
- }
358
- });
359
- return;
360
- }
361
- // A socket disconnected on purpose stays closed until `connect()` or `reconnect()` is called
362
- if (autoConnect && !adapter.forceClosed) {
363
- connect();
364
- }
365
- });
366
-
367
287
  return {
368
- connect,
369
- reconnect,
370
- disconnect,
288
+ connect: connectionLifecycle.connect,
289
+ reconnect: connectionLifecycle.reconnect,
290
+ disconnect: connectionLifecycle.disconnect,
371
291
  listen: subscriptions.listen,
372
292
  emit,
373
- // Nothing of this connector outlives the socket - no online subscription, no running or waiting streams
293
+ // Nothing of this connector outlives the socket - no app manager subscriptions, no running or waiting streams
374
294
  dispose: () => {
375
- unmountOnline();
295
+ connectionLifecycle.dispose();
376
296
  connection = undefined;
377
- [...subscriptions.values()].forEach(stopStream);
297
+ stopStreams();
378
298
  },
379
299
  };
380
300
  });
@@ -2,6 +2,7 @@
2
2
  import type { QueryParamsType } from "@hyper-fetch/core";
3
3
  import { stringifyQueryParams } from "@hyper-fetch/core";
4
4
  import {
5
+ createReconnectingConnection,
5
6
  getSocketError,
6
7
  getSocketUrl,
7
8
  getWebsocketConstructor,
@@ -60,29 +61,12 @@ export const OrpcWebsocketAdapter = ({
60
61
  >({ name: "orpc-websocket", confirmsSubscriptions: true })
61
62
  .setQueryParamsMapper(stringifyQueryParams)
62
63
  .setConnector((bindings) => {
63
- const {
64
- socket,
65
- adapter,
66
- getQueryParams,
67
- onConnect,
68
- onConnectFailed,
69
- onReconnect,
70
- onDisconnect,
71
- onConnected,
72
- onDisconnected,
73
- onError,
74
- } = bindings;
64
+ const { adapter, getQueryParams, onConnectFailed, onError } = bindings;
75
65
 
76
- const autoConnect = adapter.adapterOptions?.autoConnect ?? true;
77
-
78
- // The transport in use. Events of any other instance (replaced or closed on purpose) are ignored.
66
+ // The transport of the current attempt - `undefined` once it is detached
79
67
  let websocket: WebSocket | undefined;
80
68
  // Options of the current connection (after onConnect interceptors)
81
69
  let options: OrpcWebsocketAdapterOptionsType | undefined;
82
- // Connection attempt in progress - concurrent `connect()` calls join it
83
- let pendingConnection: Promise<boolean> | undefined;
84
- // Connection timeout while connecting, reconnection delay after the connection was lost
85
- let timeout: ReturnType<typeof setTimeout> | undefined;
86
70
  // Request ids are never reused, so a late message of a stopped request can't reach a new one
87
71
  let lastRequestId = 0;
88
72
  // Running requests of the current connection
@@ -212,176 +196,106 @@ export const OrpcWebsocketAdapter = ({
212
196
  subscriptions.receive(subscription, message.event);
213
197
  };
214
198
 
215
- /** Starts over after `delay` - the connection timeout while connecting, the reconnect delay after a loss */
216
- const scheduleReconnect = (delay = socket.reconnectTime) => {
217
- clearTimeout(timeout);
218
- timeout = setTimeout(() => {
219
- reconnect();
220
- }, delay);
221
- };
222
-
223
- const openConnection = async (): Promise<boolean> => {
224
- const connection = await onConnect();
225
- if (!connection) {
226
- return adapter.connected;
227
- }
228
-
229
- clearTimeout(timeout);
230
- options = connection.adapterOptions;
231
- const url = getSocketUrl(connection.url, getQueryParams(connection.queryParams));
232
-
199
+ /** Creates the transport, reporting a failed attempt when the environment or the connection details are invalid */
200
+ const createWebsocket = (url: string): WebSocket | null => {
233
201
  const WebSocketConstructor = getWebsocketConstructor(options);
234
202
  if (!WebSocketConstructor) {
235
203
  onConnectFailed({ error: new Error("WebSocket is not available in this environment") });
236
- return false;
204
+ return null;
237
205
  }
238
-
239
- let instance: WebSocket;
240
206
  try {
241
- instance = new WebSocketConstructor(url, options?.protocols);
207
+ return new WebSocketConstructor(url, options?.protocols);
242
208
  } catch (error) {
243
209
  onConnectFailed({ error: toError(error) });
244
- return false;
210
+ return null;
245
211
  }
246
- // Binary frames are read synchronously, so messages keep their order
247
- instance.binaryType = "arraybuffer";
248
- websocket = instance;
249
- const isCurrent = () => websocket === instance;
212
+ };
213
+
214
+ /**
215
+ * Closes a detached transport. The server cancels every subscription of the connection, the listeners stay
216
+ * registered and keep the id of their last event for the next connection. Resolves on the close - or on an
217
+ * error, as a transport that fails while closing may report only `error` (Node.js 22).
218
+ */
219
+ const closeWebsocket = (transport: WebSocket): Promise<void> => {
220
+ // The engine closes an attempt before it opens the next one, so this is always the current transport
221
+ websocket = undefined;
222
+ releaseAll();
223
+ if (transport.readyState === WebsocketReadyState.CLOSED) {
224
+ return Promise.resolve();
225
+ }
226
+ return new Promise<void>((resolve) => {
227
+ transport.addEventListener("close", () => resolve(), { once: true });
228
+ transport.addEventListener("error", () => resolve(), { once: true });
229
+ try {
230
+ transport.close(1000);
231
+ } catch {
232
+ // Closing a transport that never connected may throw in some runtimes - it is detached already
233
+ resolve();
234
+ }
235
+ });
236
+ };
250
237
 
251
- // Connection timeout - when the server does not answer in time, start over
252
- scheduleReconnect(socket.connectionTimeout);
238
+ const connection = createReconnectingConnection({
239
+ bindings,
240
+ autoConnect: adapter.adapterOptions?.autoConnect ?? true,
241
+ open: (attempt) => {
242
+ options = attempt.connection.adapterOptions;
243
+ const url = getSocketUrl(attempt.connection.url, getQueryParams(attempt.connection.queryParams));
244
+ const transport = createWebsocket(url);
245
+ if (!transport) {
246
+ return null;
247
+ }
248
+ // Binary frames are read synchronously, so messages keep their order
249
+ transport.binaryType = "arraybuffer";
250
+ websocket = transport;
251
+
252
+ /** The transport is gone - report it and let the engine decide about the next attempt */
253
+ const onTransportClosed = (event: Pick<CloseEvent, "code"> & Partial<Pick<CloseEvent, "reason">> & Event) => {
254
+ // The socket is reported as disconnected first, then the error that explains why
255
+ attempt.lost({ code: event.code, reason: event.reason || undefined });
256
+ onError({ error: new Error(getSocketError(event)) });
257
+ };
253
258
 
254
- return new Promise<boolean>((resolve) => {
255
- // A closed instance never opens, so the open event always belongs to the current one
256
- instance.addEventListener("open", () => {
257
- clearTimeout(timeout);
258
- onConnected();
259
- [...subscriptions.values()].forEach((subscription) => {
259
+ transport.addEventListener("open", () => {
260
+ // Ignored for a replaced transport
261
+ attempt.ready();
262
+ // A replaced transport, or a connected callback that closed the connection, starts nothing
263
+ if (!attempt.isCurrent()) {
264
+ return;
265
+ }
266
+ subscriptions.values().forEach((subscription) => {
260
267
  // A listener added by an `onConnected` callback is running already
261
268
  if (!subscription.transport) {
262
269
  startSubscription(subscription);
263
270
  }
264
271
  });
265
- resolve(true);
266
272
  });
267
273
 
268
- /** The transport is gone - report it and get the connection back unless it was closed normally */
269
- const onTransportClosed = (event: Pick<CloseEvent, "code"> & Event) => {
270
- websocket = undefined;
271
- clearTimeout(timeout);
272
- releaseAll();
273
- onDisconnected();
274
- onError({ error: new Error(getSocketError(event)) });
275
-
276
- // The connection was lost or closed by the server with an error - try to get it back
277
- if (event.code !== 1000) {
278
- scheduleReconnect();
279
- }
280
- };
281
-
282
- instance.addEventListener("close", (event) => {
283
- resolve(false);
284
- if (!isCurrent()) {
285
- return;
274
+ transport.addEventListener("close", (event) => {
275
+ if (attempt.isCurrent()) {
276
+ onTransportClosed(event);
286
277
  }
287
- onTransportClosed(event);
288
278
  });
289
279
 
290
280
  // Node.js 22 reports a failed handshake with `error` only - no `close` follows and the transport stays
291
281
  // CONNECTING. Browsers set CLOSED before the error and send the close event, which handles it as usual.
292
- // Here the transport is detached and treated as an abnormally closed one (1006).
293
- instance.addEventListener("error", () => {
294
- if (!isCurrent() || instance.readyState !== WebsocketReadyState.CONNECTING) {
282
+ // Here it is treated as an abnormally closed transport (1006).
283
+ transport.addEventListener("error", () => {
284
+ if (!attempt.isCurrent() || transport.readyState !== WebsocketReadyState.CONNECTING) {
295
285
  return;
296
286
  }
297
- resolve(false);
298
- try {
299
- instance.close();
300
- } catch {
301
- // Closing a transport that never connected may throw in some runtimes - it is detached already
302
- }
303
287
  onTransportClosed(Object.assign(new Event("close"), { code: 1006 }));
304
288
  });
305
289
 
306
- instance.addEventListener("message", (event) => {
307
- if (isCurrent()) {
290
+ transport.addEventListener("message", (event) => {
291
+ if (attempt.isCurrent()) {
308
292
  handleMessage(event.data);
309
293
  }
310
294
  });
311
- });
312
- };
313
295
 
314
- const connect = (): Promise<boolean> => {
315
- // Another attempt is already on its way (e.g. the automatic one) - resolve together with it
316
- if (adapter.connecting && pendingConnection) {
317
- return pendingConnection;
318
- }
319
-
320
- const attempt = openConnection();
321
- pendingConnection = attempt;
322
- const release = () => {
323
- if (pendingConnection === attempt) {
324
- pendingConnection = undefined;
325
- }
326
- };
327
- attempt.then(release, release);
328
-
329
- return attempt;
330
- };
331
-
332
- /**
333
- * Closes the transport and resets the connection state. The server cancels every subscription of the
334
- * connection, the listeners stay registered and keep the id of their last event for the next connection.
335
- */
336
- const closeConnection = async ({ manual }: { manual: boolean }): Promise<boolean> => {
337
- clearTimeout(timeout);
338
-
339
- const current = websocket;
340
- websocket = undefined;
341
- releaseAll();
342
-
343
- const wasActive = adapter.connected || adapter.connecting;
344
- onDisconnect();
345
- if (!manual) {
346
- // Closing the previous transport is a part of reconnecting - only `disconnect()` keeps the socket closed
347
- adapter.setForceClosed(false);
348
- }
349
- if (wasActive) {
350
- onDisconnected();
351
- }
352
-
353
- if (!current) {
354
- return true;
355
- }
356
- return new Promise<boolean>((resolve) => {
357
- current.addEventListener("close", () => resolve(true), { once: true });
358
- // A transport that fails while closing may report only `error` (Node.js 22) - don't wait for a close
359
- current.addEventListener("error", () => resolve(true), { once: true });
360
- current.close(1000);
361
- });
362
- };
363
-
364
- /** Manual disconnect - the socket stays closed until `connect()` or `reconnect()` is called */
365
- const disconnect = (): Promise<boolean> => {
366
- return closeConnection({ manual: true });
367
- };
368
-
369
- const reconnect = async () => {
370
- // Reconnecting is a request to be connected, also after a manual disconnect
371
- adapter.setForceClosed(false);
372
-
373
- await onReconnect({
374
- disconnect: () => closeConnection({ manual: false }),
375
- connect: async () => {
376
- // `disconnect()` called while the previous transport was closing wins over the reconnection
377
- if (adapter.forceClosed) {
378
- adapter.setReconnectionAttempts(0);
379
- return false;
380
- }
381
- return connect();
382
- },
383
- });
384
- };
296
+ return { close: () => closeWebsocket(transport) };
297
+ },
298
+ });
385
299
 
386
300
  // Throwing synchronously makes `emitter.emit()` fail right at the call site, the same as in the
387
301
  // Server-Sent Events adapter
@@ -389,29 +303,13 @@ export const OrpcWebsocketAdapter = ({
389
303
  throw new Error("Cannot emit events in the oRPC WebSocket adapter, it only receives events of subscriptions");
390
304
  };
391
305
 
392
- // Initialize
393
- if (autoConnect) {
394
- connect();
395
- }
396
-
397
- const unmountOnline = socket.appManager.events.onOnline(() => {
398
- // A socket disconnected on purpose stays closed until `connect()` or `reconnect()` is called
399
- if (autoConnect && !adapter.connected && !adapter.forceClosed) {
400
- connect();
401
- }
402
- });
403
-
404
306
  return {
405
- connect,
406
- reconnect,
407
- disconnect,
307
+ connect: connection.connect,
308
+ reconnect: connection.reconnect,
309
+ disconnect: connection.disconnect,
408
310
  listen: subscriptions.listen,
409
311
  emit,
410
- // Nothing of this connector outlives the socket - no online subscription, no pending reconnect
411
- dispose: () => {
412
- unmountOnline();
413
- clearTimeout(timeout);
414
- },
312
+ dispose: connection.dispose,
415
313
  };
416
314
  });
417
315
  };