@hyper-fetch/orpc 9.9.0 → 10.1.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.
- package/README.md +117 -31
- package/__tests__/e2e/e2e.orpc-realtime-server.ts +181 -0
- package/__tests__/e2e/e2e.react-realtime.spec.tsx +181 -0
- package/__tests__/e2e/e2e.realtime.spec.ts +310 -0
- package/__tests__/features/adapter/adapter.lifecycle.spec.ts +23 -0
- package/__tests__/features/adapter/adapter.schema.spec.ts +19 -0
- package/__tests__/features/socket/socket.schema.spec.ts +179 -0
- package/__tests__/features/stream-adapter/stream-adapter.environment.spec.ts +163 -0
- package/__tests__/features/stream-adapter/stream-adapter.lifecycle.spec.ts +558 -0
- package/__tests__/features/stream-adapter/stream-adapter.listener-lifecycle.spec.ts +291 -0
- package/__tests__/features/stream-adapter/stream-adapter.protocol.spec.ts +609 -0
- package/__tests__/features/stream-adapter/stream-adapter.subscriptions.spec.ts +270 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.environment.spec.ts +153 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.handshake-error.spec.ts +80 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.lifecycle.spec.ts +448 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.listener-lifecycle.spec.ts +222 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.protocol.spec.ts +415 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.subscriptions.spec.ts +172 -0
- package/__tests__/utils/controlled-fetch.ts +160 -0
- package/__tests__/utils/controlled-websocket.ts +140 -0
- package/__tests__/utils/socket-error.ts +7 -0
- package/__tests__/utils/stream-socket.ts +54 -0
- package/__tests__/utils/websocket-socket.ts +45 -0
- package/__tests__/vitest.setup.ts +20 -0
- package/dist/adapter/adapter.fetch.d.ts.map +1 -1
- package/dist/adapter/adapter.schema.d.ts +32 -0
- package/dist/adapter/adapter.schema.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts +22 -4
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +843 -13
- package/dist/index.mjs.map +1 -1
- package/dist/socket/index.d.ts +3 -0
- package/dist/socket/index.d.ts.map +1 -0
- package/dist/socket/socket.subscriptions.d.ts +31 -0
- package/dist/socket/socket.subscriptions.d.ts.map +1 -0
- package/dist/socket/socket.types.d.ts +62 -0
- package/dist/socket/socket.types.d.ts.map +1 -0
- package/dist/socket/socket.utils.d.ts +56 -0
- package/dist/socket/socket.utils.d.ts.map +1 -0
- package/dist/stream-adapter/index.d.ts +3 -0
- package/dist/stream-adapter/index.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.d.ts +21 -0
- package/dist/stream-adapter/stream-adapter.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.types.d.ts +22 -0
- package/dist/stream-adapter/stream-adapter.types.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.utils.d.ts +22 -0
- package/dist/stream-adapter/stream-adapter.utils.d.ts.map +1 -0
- package/dist/websocket-adapter/index.d.ts +3 -0
- package/dist/websocket-adapter/index.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.d.ts +21 -0
- package/dist/websocket-adapter/websocket-adapter.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.types.d.ts +22 -0
- package/dist/websocket-adapter/websocket-adapter.types.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.utils.d.ts +35 -0
- package/dist/websocket-adapter/websocket-adapter.utils.d.ts.map +1 -0
- package/package.json +3 -1
- package/src/adapter/adapter.fetch.ts +4 -3
- package/src/adapter/adapter.schema.ts +57 -0
- package/src/adapter/adapter.utils.ts +40 -10
- package/src/index.ts +3 -0
- package/src/socket/index.ts +2 -0
- package/src/socket/socket.subscriptions.ts +178 -0
- package/src/socket/socket.types.ts +64 -0
- package/src/socket/socket.utils.ts +110 -0
- package/src/stream-adapter/index.ts +2 -0
- package/src/stream-adapter/stream-adapter.ts +301 -0
- package/src/stream-adapter/stream-adapter.types.ts +31 -0
- package/src/stream-adapter/stream-adapter.utils.ts +98 -0
- package/src/websocket-adapter/index.ts +2 -0
- package/src/websocket-adapter/websocket-adapter.ts +315 -0
- package/src/websocket-adapter/websocket-adapter.types.ts +31 -0
- package/src/websocket-adapter/websocket-adapter.utils.ts +119 -0
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-use-before-define */
|
|
2
|
+
import type { QueryParamsType } from "@hyper-fetch/core";
|
|
3
|
+
import { stringifyQueryParams } from "@hyper-fetch/core";
|
|
4
|
+
import {
|
|
5
|
+
createReconnectingConnection,
|
|
6
|
+
getSocketError,
|
|
7
|
+
getSocketUrl,
|
|
8
|
+
getWebsocketConstructor,
|
|
9
|
+
SocketAdapter,
|
|
10
|
+
WebsocketReadyState,
|
|
11
|
+
} from "@hyper-fetch/sockets";
|
|
12
|
+
import { isORPCErrorStatus } from "@orpc/client";
|
|
13
|
+
|
|
14
|
+
import { createOrpcSerializer } from "../adapter/adapter.utils";
|
|
15
|
+
import { createOrpcSubscriptions } from "../socket/socket.subscriptions";
|
|
16
|
+
import type { OrpcSocketAdapterConfigType, OrpcSocketExtraType, OrpcSubscriptionType } from "../socket/socket.types";
|
|
17
|
+
import { getNotIteratorError, getOrpcResponseError, OrpcSocketError, toError } from "../socket/socket.utils";
|
|
18
|
+
import type { OrpcWebsocketAdapterOptionsType, OrpcWebsocketAdapterType } from "./websocket-adapter.types";
|
|
19
|
+
import type { OrpcPeerResponseMessageType } from "./websocket-adapter.utils";
|
|
20
|
+
import {
|
|
21
|
+
decodeOrpcResponseMessage,
|
|
22
|
+
encodeOrpcAbortMessage,
|
|
23
|
+
encodeOrpcRequestMessage,
|
|
24
|
+
isOrpcEventIteratorResponse,
|
|
25
|
+
} from "./websocket-adapter.utils";
|
|
26
|
+
|
|
27
|
+
/** Server side of one subscription - its request on the connection */
|
|
28
|
+
type WebsocketTransportType = { id: string; websocket: WebSocket };
|
|
29
|
+
|
|
30
|
+
type WebsocketSubscriptionType = OrpcSubscriptionType<WebsocketTransportType>;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Socket adapter for the event iterators of oRPC over one WebSocket connection. It speaks the protocol of the
|
|
34
|
+
* `RPCHandler` of `@orpc/server/ws` (the same as `@orpc/client/websocket`): every subscription is a request on the
|
|
35
|
+
* shared connection, and its events arrive as messages of that request.
|
|
36
|
+
*
|
|
37
|
+
* The adapter only subscribes. Emitting, and calling regular procedures, is not supported - use `OrpcAdapter` for
|
|
38
|
+
* them. Listeners of the same procedure and input share one request, the last one to unsubscribe aborts it.
|
|
39
|
+
* After a reconnect every running subscription starts again with the id of its last event. A subscription starts
|
|
40
|
+
* (`onStart`) when the server answers with the event iterator, and ends (`onEnd`) when the iterator finishes, fails
|
|
41
|
+
* or the server rejects the call.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* const socket = new Socket({ url: "ws://localhost:3000", adapter: OrpcWebsocketAdapter() });
|
|
45
|
+
* const sdk = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });
|
|
46
|
+
*
|
|
47
|
+
* sdk.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data }) => console.log(data));
|
|
48
|
+
*/
|
|
49
|
+
export const OrpcWebsocketAdapter = ({
|
|
50
|
+
customJsonSerializers,
|
|
51
|
+
}: OrpcSocketAdapterConfigType = {}): OrpcWebsocketAdapterType => {
|
|
52
|
+
const serializer = createOrpcSerializer(customJsonSerializers);
|
|
53
|
+
|
|
54
|
+
return new SocketAdapter<
|
|
55
|
+
OrpcSocketExtraType,
|
|
56
|
+
OrpcWebsocketAdapterOptionsType,
|
|
57
|
+
undefined,
|
|
58
|
+
undefined,
|
|
59
|
+
QueryParamsType | string,
|
|
60
|
+
typeof stringifyQueryParams
|
|
61
|
+
>({ name: "orpc-websocket", confirmsSubscriptions: true })
|
|
62
|
+
.setQueryParamsMapper(stringifyQueryParams)
|
|
63
|
+
.setConnector((bindings) => {
|
|
64
|
+
const { adapter, getQueryParams, onConnectFailed, onError } = bindings;
|
|
65
|
+
|
|
66
|
+
// The transport of the current attempt - `undefined` once it is detached
|
|
67
|
+
let websocket: WebSocket | undefined;
|
|
68
|
+
// Options of the current connection (after onConnect interceptors)
|
|
69
|
+
let options: OrpcWebsocketAdapterOptionsType | undefined;
|
|
70
|
+
// Request ids are never reused, so a late message of a stopped request can't reach a new one
|
|
71
|
+
let lastRequestId = 0;
|
|
72
|
+
// Running requests of the current connection
|
|
73
|
+
const requests = new Map<string, WebsocketSubscriptionType>();
|
|
74
|
+
|
|
75
|
+
const subscriptions = createOrpcSubscriptions<OrpcWebsocketAdapterType, WebsocketTransportType>({
|
|
76
|
+
bindings,
|
|
77
|
+
serializer,
|
|
78
|
+
start: (subscription) => startSubscription(subscription),
|
|
79
|
+
stop: (subscription) => stopSubscription(subscription),
|
|
80
|
+
release: (subscription) => {
|
|
81
|
+
releaseSubscription(subscription);
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
/** Sends a frame of the subscription, reporting the failure instead of throwing */
|
|
86
|
+
const sendFrame = (subscription: WebsocketSubscriptionType, target: WebSocket, frame: string): boolean => {
|
|
87
|
+
try {
|
|
88
|
+
target.send(frame);
|
|
89
|
+
return true;
|
|
90
|
+
} catch (error) {
|
|
91
|
+
subscriptions.report(subscription, error);
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const startSubscription = (subscription: WebsocketSubscriptionType) => {
|
|
97
|
+
// Not connected - the subscription starts on connect
|
|
98
|
+
const current = websocket;
|
|
99
|
+
if (!current || !adapter.connected) {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
lastRequestId += 1;
|
|
104
|
+
const id = lastRequestId.toString(36);
|
|
105
|
+
const { lastEventId } = subscription;
|
|
106
|
+
// The server reads it as `lastEventId` and can resume where the previous connection stopped
|
|
107
|
+
const headers =
|
|
108
|
+
lastEventId === undefined ? { ...options?.headers } : { ...options?.headers, "last-event-id": lastEventId };
|
|
109
|
+
|
|
110
|
+
let frame: string;
|
|
111
|
+
try {
|
|
112
|
+
frame = encodeOrpcRequestMessage({
|
|
113
|
+
id,
|
|
114
|
+
topic: subscription.topic,
|
|
115
|
+
payload: subscription.payload,
|
|
116
|
+
headers,
|
|
117
|
+
serializer,
|
|
118
|
+
});
|
|
119
|
+
} catch (error) {
|
|
120
|
+
// An input that can't be encoded never will be, so the subscription is over
|
|
121
|
+
subscriptions.end(subscription, error);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (sendFrame(subscription, current, frame)) {
|
|
126
|
+
subscription.transport = { id, websocket: current };
|
|
127
|
+
requests.set(id, subscription);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
/** Forgets the request of the subscription. Messages that still come for it are ignored. */
|
|
132
|
+
const releaseSubscription = (subscription: WebsocketSubscriptionType) => {
|
|
133
|
+
const { transport } = subscription;
|
|
134
|
+
subscription.transport = undefined;
|
|
135
|
+
subscription.started = false;
|
|
136
|
+
if (transport) {
|
|
137
|
+
requests.delete(transport.id);
|
|
138
|
+
}
|
|
139
|
+
return transport;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const stopSubscription = (subscription: WebsocketSubscriptionType) => {
|
|
143
|
+
const transport = releaseSubscription(subscription);
|
|
144
|
+
if (transport) {
|
|
145
|
+
sendFrame(subscription, transport.websocket, encodeOrpcAbortMessage(transport.id));
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/** The connection is gone and the server dropped every request with it */
|
|
150
|
+
const releaseAll = () => {
|
|
151
|
+
requests.forEach((subscription) => {
|
|
152
|
+
subscription.transport = undefined;
|
|
153
|
+
subscription.started = false;
|
|
154
|
+
});
|
|
155
|
+
requests.clear();
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const handleResponse = (
|
|
159
|
+
subscription: WebsocketSubscriptionType,
|
|
160
|
+
{ status, headers, body }: Extract<OrpcPeerResponseMessageType, { type: "response" }>,
|
|
161
|
+
) => {
|
|
162
|
+
// The server rejected the call before the iterator started, e.g. a failed input validation
|
|
163
|
+
if (isORPCErrorStatus(status)) {
|
|
164
|
+
subscriptions.end(subscription, getOrpcResponseError({ status, body, serializer }));
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (!isOrpcEventIteratorResponse(headers)) {
|
|
168
|
+
subscriptions.end(subscription, getNotIteratorError(subscription.topic));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
// The response of an event iterator - the subscription runs
|
|
172
|
+
subscriptions.confirm(subscription);
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const handleMessage = (frame: unknown) => {
|
|
176
|
+
let message: OrpcPeerResponseMessageType;
|
|
177
|
+
try {
|
|
178
|
+
message = decodeOrpcResponseMessage(frame);
|
|
179
|
+
} catch (error) {
|
|
180
|
+
// A frame that can't be read can't be matched to its subscription either
|
|
181
|
+
onError({ error: new OrpcSocketError({ cause: error, topic: null, payload: undefined }) });
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Late messages of stopped requests, and the abort the server sends for iterators in the input, are ignored
|
|
186
|
+
const subscription = requests.get(message.id);
|
|
187
|
+
if (!subscription || message.type === "abort") {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (message.type === "response") {
|
|
192
|
+
handleResponse(subscription, message);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
// `done` and `error` end the subscription there
|
|
196
|
+
subscriptions.receive(subscription, message.event);
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
/** Creates the transport, reporting a failed attempt when the environment or the connection details are invalid */
|
|
200
|
+
const createWebsocket = (url: string): WebSocket | null => {
|
|
201
|
+
const WebSocketConstructor = getWebsocketConstructor(options);
|
|
202
|
+
if (!WebSocketConstructor) {
|
|
203
|
+
onConnectFailed({ error: new Error("WebSocket is not available in this environment") });
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
return new WebSocketConstructor(url, options?.protocols);
|
|
208
|
+
} catch (error) {
|
|
209
|
+
onConnectFailed({ error: toError(error) });
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
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
|
+
};
|
|
237
|
+
|
|
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
|
+
};
|
|
258
|
+
|
|
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) => {
|
|
267
|
+
// A listener added by an `onConnected` callback is running already
|
|
268
|
+
if (!subscription.transport) {
|
|
269
|
+
startSubscription(subscription);
|
|
270
|
+
}
|
|
271
|
+
});
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
transport.addEventListener("close", (event) => {
|
|
275
|
+
if (attempt.isCurrent()) {
|
|
276
|
+
onTransportClosed(event);
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
// Node.js 22 reports a failed handshake with `error` only - no `close` follows and the transport stays
|
|
281
|
+
// CONNECTING. Browsers set CLOSED before the error and send the close event, which handles it as usual.
|
|
282
|
+
// Here it is treated as an abnormally closed transport (1006).
|
|
283
|
+
transport.addEventListener("error", () => {
|
|
284
|
+
if (!attempt.isCurrent() || transport.readyState !== WebsocketReadyState.CONNECTING) {
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
onTransportClosed(Object.assign(new Event("close"), { code: 1006 }));
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
transport.addEventListener("message", (event) => {
|
|
291
|
+
if (attempt.isCurrent()) {
|
|
292
|
+
handleMessage(event.data);
|
|
293
|
+
}
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
return { close: () => closeWebsocket(transport) };
|
|
297
|
+
},
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
// Throwing synchronously makes `emitter.emit()` fail right at the call site, the same as in the
|
|
301
|
+
// Server-Sent Events adapter
|
|
302
|
+
const emit = () => {
|
|
303
|
+
throw new Error("Cannot emit events in the oRPC WebSocket adapter, it only receives events of subscriptions");
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
return {
|
|
307
|
+
connect: connection.connect,
|
|
308
|
+
reconnect: connection.reconnect,
|
|
309
|
+
disconnect: connection.disconnect,
|
|
310
|
+
listen: subscriptions.listen,
|
|
311
|
+
emit,
|
|
312
|
+
dispose: connection.dispose,
|
|
313
|
+
};
|
|
314
|
+
});
|
|
315
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { QueryParamsType, stringifyQueryParams } from "@hyper-fetch/core";
|
|
2
|
+
import type { SocketAdapter } from "@hyper-fetch/sockets";
|
|
3
|
+
|
|
4
|
+
import type { OrpcSocketExtraType } from "../socket/socket.types";
|
|
5
|
+
|
|
6
|
+
/** Options of the `OrpcWebsocketAdapter`, set with the `adapterOptions` of the socket or per connection in `onConnect` */
|
|
7
|
+
export type OrpcWebsocketAdapterOptionsType = {
|
|
8
|
+
/**
|
|
9
|
+
* Connects when the socket is created. Without it, call `socket.connect()`.
|
|
10
|
+
* @default true
|
|
11
|
+
*/
|
|
12
|
+
autoConnect?: boolean;
|
|
13
|
+
/**
|
|
14
|
+
* The WebSocket constructor, e.g. from the `ws` package. Defaults to the global `WebSocket` of browsers,
|
|
15
|
+
* Node.js 22+, Bun and Deno. Pass it in runtimes without the global.
|
|
16
|
+
*/
|
|
17
|
+
WebSocket?: typeof WebSocket;
|
|
18
|
+
/** Subprotocols passed to the `WebSocket` constructor (`Sec-WebSocket-Protocol` header) */
|
|
19
|
+
protocols?: string | string[];
|
|
20
|
+
/** Headers of every subscription request, the procedures read them the same as the headers of HTTP requests */
|
|
21
|
+
headers?: Record<string, string>;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type OrpcWebsocketAdapterType = SocketAdapter<
|
|
25
|
+
OrpcSocketExtraType,
|
|
26
|
+
OrpcWebsocketAdapterOptionsType,
|
|
27
|
+
undefined,
|
|
28
|
+
undefined,
|
|
29
|
+
QueryParamsType | string,
|
|
30
|
+
typeof stringifyQueryParams
|
|
31
|
+
>;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import type { OrpcSerializerType } from "../adapter/adapter.utils";
|
|
2
|
+
import { orpcEndpointMapper } from "../adapter/adapter.utils";
|
|
3
|
+
import type { OrpcIteratorEventType } from "../socket/socket.types";
|
|
4
|
+
import { isRecord } from "../socket/socket.utils";
|
|
5
|
+
|
|
6
|
+
/** Message types of the oRPC peer protocol, used by `@orpc/server/ws` and `@orpc/client/websocket` */
|
|
7
|
+
const peerMessageType = {
|
|
8
|
+
REQUEST: 1,
|
|
9
|
+
RESPONSE: 2,
|
|
10
|
+
EVENT_ITERATOR: 3,
|
|
11
|
+
ABORT_SIGNAL: 4,
|
|
12
|
+
} as const;
|
|
13
|
+
|
|
14
|
+
/** JSON and binary parts of a binary frame are split by this byte */
|
|
15
|
+
const binaryDelimiter = 255;
|
|
16
|
+
|
|
17
|
+
/** A message the server sends for one request */
|
|
18
|
+
export type OrpcPeerResponseMessageType =
|
|
19
|
+
| { id: string; type: "response"; status: number; headers: Record<string, unknown>; body: unknown }
|
|
20
|
+
| { id: string; type: "event"; event: OrpcIteratorEventType }
|
|
21
|
+
| { id: string; type: "abort" };
|
|
22
|
+
|
|
23
|
+
const getMalformedError = (detail: string) => new TypeError(`Invalid oRPC message: ${detail}`);
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Starts the call of the procedure - the same request message as the `RPCLink` of `@orpc/client/websocket`.
|
|
27
|
+
* The input is serialized with the RPC serializer, inputs with files are not supported.
|
|
28
|
+
*/
|
|
29
|
+
export const encodeOrpcRequestMessage = ({
|
|
30
|
+
id,
|
|
31
|
+
topic,
|
|
32
|
+
payload,
|
|
33
|
+
headers,
|
|
34
|
+
serializer,
|
|
35
|
+
}: {
|
|
36
|
+
id: string;
|
|
37
|
+
topic: string;
|
|
38
|
+
payload: unknown;
|
|
39
|
+
headers: Record<string, string>;
|
|
40
|
+
serializer: OrpcSerializerType;
|
|
41
|
+
}): string => {
|
|
42
|
+
const body = serializer.serialize(payload);
|
|
43
|
+
if (body instanceof FormData) {
|
|
44
|
+
throw new TypeError(`Files in the input of "${topic}" are not supported by the oRPC WebSocket adapter`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The `POST` method is the default of the protocol, so it is not sent
|
|
48
|
+
return JSON.stringify({
|
|
49
|
+
i: id,
|
|
50
|
+
p: { u: orpcEndpointMapper(topic), b: body, h: Object.keys(headers).length > 0 ? headers : undefined },
|
|
51
|
+
});
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** Stops the call of the procedure, the server cancels its iterator */
|
|
55
|
+
export const encodeOrpcAbortMessage = (id: string): string => {
|
|
56
|
+
return JSON.stringify({ i: id, t: peerMessageType.ABORT_SIGNAL });
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const readFrameText = (frame: unknown): string => {
|
|
60
|
+
if (typeof frame === "string") {
|
|
61
|
+
return frame;
|
|
62
|
+
}
|
|
63
|
+
if (frame instanceof ArrayBuffer || ArrayBuffer.isView(frame)) {
|
|
64
|
+
const bytes =
|
|
65
|
+
frame instanceof ArrayBuffer
|
|
66
|
+
? new Uint8Array(frame)
|
|
67
|
+
: new Uint8Array(frame.buffer, frame.byteOffset, frame.byteLength);
|
|
68
|
+
// Binary frames carry a file after the delimiter, event iterators never send files
|
|
69
|
+
const end = bytes.indexOf(binaryDelimiter);
|
|
70
|
+
return new TextDecoder().decode(end === -1 ? bytes : bytes.subarray(0, end));
|
|
71
|
+
}
|
|
72
|
+
throw getMalformedError("expected a text or a binary frame");
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/** Reads a message of the server, the same as `decodeResponseMessage` of oRPC. Throws for malformed frames. */
|
|
76
|
+
export const decodeOrpcResponseMessage = (frame: unknown): OrpcPeerResponseMessageType => {
|
|
77
|
+
const message: unknown = JSON.parse(readFrameText(frame));
|
|
78
|
+
if (!isRecord(message) || typeof message.i !== "string") {
|
|
79
|
+
throw getMalformedError("expected an object with the request id");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const { i: id, t: type, p: payload } = message;
|
|
83
|
+
if (type === peerMessageType.ABORT_SIGNAL) {
|
|
84
|
+
return { id, type: "abort" };
|
|
85
|
+
}
|
|
86
|
+
if (!isRecord(payload)) {
|
|
87
|
+
throw getMalformedError("expected the payload object");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (type === peerMessageType.EVENT_ITERATOR) {
|
|
91
|
+
const { e: event, d: data, m: meta } = payload;
|
|
92
|
+
if (event !== "message" && event !== "error" && event !== "done") {
|
|
93
|
+
throw getMalformedError(`unknown event "${String(event)}"`);
|
|
94
|
+
}
|
|
95
|
+
return { id, type: "event", event: { event, data, meta: isRecord(meta) ? meta : undefined } };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Any other message is a response, the same as in oRPC
|
|
99
|
+
const { s: status = 200, h: headers = {}, b: body } = payload;
|
|
100
|
+
if (typeof status !== "number" || !isRecord(headers)) {
|
|
101
|
+
throw getMalformedError("expected the status and the headers of the response");
|
|
102
|
+
}
|
|
103
|
+
return { id, type: "response", status, headers, body };
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const flattenHeader = (header: unknown): string | undefined => {
|
|
107
|
+
if (typeof header === "string") {
|
|
108
|
+
return header;
|
|
109
|
+
}
|
|
110
|
+
return Array.isArray(header) && header.length > 0 ? header.join(", ") : undefined;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/** The same check as `isEventIteratorHeaders` of oRPC - an event stream that is not a file */
|
|
114
|
+
export const isOrpcEventIteratorResponse = (headers: Record<string, unknown>): boolean => {
|
|
115
|
+
return (
|
|
116
|
+
!!flattenHeader(headers["content-type"])?.startsWith("text/event-stream") &&
|
|
117
|
+
flattenHeader(headers["content-disposition"]) === undefined
|
|
118
|
+
);
|
|
119
|
+
};
|