@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.
Files changed (74) hide show
  1. package/README.md +117 -31
  2. package/__tests__/e2e/e2e.orpc-realtime-server.ts +181 -0
  3. package/__tests__/e2e/e2e.react-realtime.spec.tsx +181 -0
  4. package/__tests__/e2e/e2e.realtime.spec.ts +310 -0
  5. package/__tests__/features/adapter/adapter.lifecycle.spec.ts +23 -0
  6. package/__tests__/features/adapter/adapter.schema.spec.ts +19 -0
  7. package/__tests__/features/socket/socket.schema.spec.ts +179 -0
  8. package/__tests__/features/stream-adapter/stream-adapter.environment.spec.ts +163 -0
  9. package/__tests__/features/stream-adapter/stream-adapter.lifecycle.spec.ts +558 -0
  10. package/__tests__/features/stream-adapter/stream-adapter.listener-lifecycle.spec.ts +291 -0
  11. package/__tests__/features/stream-adapter/stream-adapter.protocol.spec.ts +609 -0
  12. package/__tests__/features/stream-adapter/stream-adapter.subscriptions.spec.ts +270 -0
  13. package/__tests__/features/websocket-adapter/websocket-adapter.environment.spec.ts +153 -0
  14. package/__tests__/features/websocket-adapter/websocket-adapter.handshake-error.spec.ts +80 -0
  15. package/__tests__/features/websocket-adapter/websocket-adapter.lifecycle.spec.ts +448 -0
  16. package/__tests__/features/websocket-adapter/websocket-adapter.listener-lifecycle.spec.ts +222 -0
  17. package/__tests__/features/websocket-adapter/websocket-adapter.protocol.spec.ts +415 -0
  18. package/__tests__/features/websocket-adapter/websocket-adapter.subscriptions.spec.ts +172 -0
  19. package/__tests__/utils/controlled-fetch.ts +160 -0
  20. package/__tests__/utils/controlled-websocket.ts +140 -0
  21. package/__tests__/utils/socket-error.ts +7 -0
  22. package/__tests__/utils/stream-socket.ts +54 -0
  23. package/__tests__/utils/websocket-socket.ts +45 -0
  24. package/__tests__/vitest.setup.ts +20 -0
  25. package/dist/adapter/adapter.fetch.d.ts.map +1 -1
  26. package/dist/adapter/adapter.schema.d.ts +32 -0
  27. package/dist/adapter/adapter.schema.d.ts.map +1 -1
  28. package/dist/adapter/adapter.utils.d.ts +22 -4
  29. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  30. package/dist/index.d.ts +3 -0
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.mjs +843 -13
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/socket/index.d.ts +3 -0
  35. package/dist/socket/index.d.ts.map +1 -0
  36. package/dist/socket/socket.subscriptions.d.ts +31 -0
  37. package/dist/socket/socket.subscriptions.d.ts.map +1 -0
  38. package/dist/socket/socket.types.d.ts +62 -0
  39. package/dist/socket/socket.types.d.ts.map +1 -0
  40. package/dist/socket/socket.utils.d.ts +56 -0
  41. package/dist/socket/socket.utils.d.ts.map +1 -0
  42. package/dist/stream-adapter/index.d.ts +3 -0
  43. package/dist/stream-adapter/index.d.ts.map +1 -0
  44. package/dist/stream-adapter/stream-adapter.d.ts +21 -0
  45. package/dist/stream-adapter/stream-adapter.d.ts.map +1 -0
  46. package/dist/stream-adapter/stream-adapter.types.d.ts +22 -0
  47. package/dist/stream-adapter/stream-adapter.types.d.ts.map +1 -0
  48. package/dist/stream-adapter/stream-adapter.utils.d.ts +22 -0
  49. package/dist/stream-adapter/stream-adapter.utils.d.ts.map +1 -0
  50. package/dist/websocket-adapter/index.d.ts +3 -0
  51. package/dist/websocket-adapter/index.d.ts.map +1 -0
  52. package/dist/websocket-adapter/websocket-adapter.d.ts +21 -0
  53. package/dist/websocket-adapter/websocket-adapter.d.ts.map +1 -0
  54. package/dist/websocket-adapter/websocket-adapter.types.d.ts +22 -0
  55. package/dist/websocket-adapter/websocket-adapter.types.d.ts.map +1 -0
  56. package/dist/websocket-adapter/websocket-adapter.utils.d.ts +35 -0
  57. package/dist/websocket-adapter/websocket-adapter.utils.d.ts.map +1 -0
  58. package/package.json +3 -1
  59. package/src/adapter/adapter.fetch.ts +4 -3
  60. package/src/adapter/adapter.schema.ts +57 -0
  61. package/src/adapter/adapter.utils.ts +40 -10
  62. package/src/index.ts +3 -0
  63. package/src/socket/index.ts +2 -0
  64. package/src/socket/socket.subscriptions.ts +178 -0
  65. package/src/socket/socket.types.ts +64 -0
  66. package/src/socket/socket.utils.ts +110 -0
  67. package/src/stream-adapter/index.ts +2 -0
  68. package/src/stream-adapter/stream-adapter.ts +301 -0
  69. package/src/stream-adapter/stream-adapter.types.ts +31 -0
  70. package/src/stream-adapter/stream-adapter.utils.ts +98 -0
  71. package/src/websocket-adapter/index.ts +2 -0
  72. package/src/websocket-adapter/websocket-adapter.ts +315 -0
  73. package/src/websocket-adapter/websocket-adapter.types.ts +31 -0
  74. package/src/websocket-adapter/websocket-adapter.utils.ts +119 -0
@@ -0,0 +1,35 @@
1
+ import { OrpcSerializerType } from '../adapter/adapter.utils';
2
+ import { OrpcIteratorEventType } from '../socket/socket.types';
3
+ /** A message the server sends for one request */
4
+ export type OrpcPeerResponseMessageType = {
5
+ id: string;
6
+ type: "response";
7
+ status: number;
8
+ headers: Record<string, unknown>;
9
+ body: unknown;
10
+ } | {
11
+ id: string;
12
+ type: "event";
13
+ event: OrpcIteratorEventType;
14
+ } | {
15
+ id: string;
16
+ type: "abort";
17
+ };
18
+ /**
19
+ * Starts the call of the procedure - the same request message as the `RPCLink` of `@orpc/client/websocket`.
20
+ * The input is serialized with the RPC serializer, inputs with files are not supported.
21
+ */
22
+ export declare const encodeOrpcRequestMessage: ({ id, topic, payload, headers, serializer, }: {
23
+ id: string;
24
+ topic: string;
25
+ payload: unknown;
26
+ headers: Record<string, string>;
27
+ serializer: OrpcSerializerType;
28
+ }) => string;
29
+ /** Stops the call of the procedure, the server cancels its iterator */
30
+ export declare const encodeOrpcAbortMessage: (id: string) => string;
31
+ /** Reads a message of the server, the same as `decodeResponseMessage` of oRPC. Throws for malformed frames. */
32
+ export declare const decodeOrpcResponseMessage: (frame: unknown) => OrpcPeerResponseMessageType;
33
+ /** The same check as `isEventIteratorHeaders` of oRPC - an event stream that is not a file */
34
+ export declare const isOrpcEventIteratorResponse: (headers: Record<string, unknown>) => boolean;
35
+ //# sourceMappingURL=websocket-adapter.utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket-adapter.utils.d.ts","sourceRoot":"","sources":["../../src/websocket-adapter/websocket-adapter.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAcpE,iDAAiD;AACjD,MAAM,MAAM,2BAA2B,GACnC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,UAAU,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GACjG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,qBAAqB,CAAA;CAAE,GAC3D;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC;AAIlC;;;GAGG;AACH,eAAO,MAAM,wBAAwB,GAAI,8CAMtC;IACD,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,UAAU,EAAE,kBAAkB,CAAC;CAChC,KAAG,MAWH,CAAC;AAEF,uEAAuE;AACvE,eAAO,MAAM,sBAAsB,GAAI,IAAI,MAAM,KAAG,MAEnD,CAAC;AAkBF,+GAA+G;AAC/G,eAAO,MAAM,yBAAyB,GAAI,OAAO,OAAO,KAAG,2BA4B1D,CAAC;AASF,8FAA8F;AAC9F,eAAO,MAAM,2BAA2B,GAAI,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAG,OAK9E,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyper-fetch/orpc",
3
- "version": "9.9.0",
3
+ "version": "10.1.0",
4
4
  "description": "oRPC adapter for Hyper Fetch",
5
5
  "author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
6
6
  "homepage": "https://hyperfetch.bettertyped.com/",
@@ -44,6 +44,7 @@
44
44
  },
45
45
  "peerDependencies": {
46
46
  "@hyper-fetch/core": "*",
47
+ "@hyper-fetch/sockets": "*",
47
48
  "@orpc/client": "^1.0.0",
48
49
  "@orpc/server": "^1.0.0"
49
50
  },
@@ -56,6 +57,7 @@
56
57
  "@orpc/client": "^1.16.4",
57
58
  "@orpc/contract": "^1.16.4",
58
59
  "@orpc/server": "^1.16.4",
60
+ "ws": "^8.18.0",
59
61
  "zod": "^4.4.1"
60
62
  },
61
63
  "lint-staged": {
@@ -171,11 +171,9 @@ export const getOrpcAdapter = ({
171
171
 
172
172
  const total = getBodySize(httpRequest.body);
173
173
  if (total) {
174
- onRequestProgress({ total, loaded: total } as ProgressEvent);
174
+ onRequestProgress({ total, loaded: 0 } as ProgressEvent);
175
175
  }
176
176
 
177
- onRequestEnd();
178
-
179
177
  const response = await fetch(httpRequest.url, {
180
178
  ...restOptions,
181
179
  method: httpRequest.method,
@@ -184,6 +182,9 @@ export const getOrpcAdapter = ({
184
182
  signal: controller.signal,
185
183
  });
186
184
 
185
+ // Fetch has no upload events. The response is the first sign that the whole body was sent.
186
+ onRequestEnd();
187
+
187
188
  onResponseStart();
188
189
 
189
190
  const responseHeaders: Record<string, string> = {};
@@ -1,4 +1,5 @@
1
1
  import type { RequestModel } from "@hyper-fetch/core";
2
+ import type { ListenerModel } from "@hyper-fetch/sockets";
2
3
  import type { Client, NestedClient, ORPCError } from "@orpc/client";
3
4
  import type { AnyRouter, RouterClient } from "@orpc/server";
4
5
 
@@ -71,3 +72,59 @@ type OrpcRouterClient<Router> = Router extends OrpcAnyClient
71
72
  * const { data } = await api.planet.find.$query.setPayload({ id: 1 }).send();
72
73
  */
73
74
  export type OrpcSchema<Router extends AnyRouter | NestedClient<any>> = OrpcClientSchema<OrpcRouterClient<Router>, "">;
75
+
76
+ /** The yielded value of an event iterator output, `never` for any other output */
77
+ type OrpcIteratorValue<Output> = [Output] extends [never]
78
+ ? never
79
+ : [Output] extends [AsyncIterator<infer Value, any, any>]
80
+ ? Value
81
+ : never;
82
+
83
+ type OrpcTopic<Path extends string, Key extends string> = Path extends "" ? Key : `${Path}/${Key}`;
84
+
85
+ type OrpcListenerModel<Input, Output, Topic extends string> = ListenerModel<{
86
+ response: OrpcIteratorValue<Output>;
87
+ payload: OrpcProcedurePayload<Input>;
88
+ hasPayload: OrpcProcedureHasPayload<Input>;
89
+ topic: Topic;
90
+ }>;
91
+
92
+ /** `true` for an event iterator procedure, and for a nested router with at least one of them */
93
+ type OrpcHasIterator<Value> =
94
+ Value extends Client<any, any, infer Output, any>
95
+ ? [OrpcIteratorValue<Output>] extends [never]
96
+ ? false
97
+ : true
98
+ : Value extends NestedClient<any>
99
+ ? true extends { [Key in keyof Value]: OrpcHasIterator<Value[Key]> }[keyof Value]
100
+ ? true
101
+ : false
102
+ : false;
103
+
104
+ type OrpcSocketClientSchema<Record, Path extends string> = {
105
+ [Key in keyof Record & string as OrpcHasIterator<Record[Key]> extends true ? Key : never]: Record[Key] extends Client<
106
+ any,
107
+ infer Input,
108
+ infer Output,
109
+ any
110
+ >
111
+ ? { $listener: OrpcListenerModel<Input, Output, OrpcTopic<Path, Key>> }
112
+ : OrpcSocketClientSchema<Record[Key], OrpcTopic<Path, Key>>;
113
+ };
114
+
115
+ /**
116
+ * Maps the type of an oRPC router to the schema understood by `createSocketSdk`. Every event iterator procedure
117
+ * becomes a `$listener` - the response is the yielded value, the payload is the input and the topic is the
118
+ * procedure path. Other procedures are not a part of it, call them with `OrpcSchema` and `OrpcAdapter`.
119
+ * It takes the router, or the client type, like `ContractRouterClient<typeof contract>` for contract-first APIs.
120
+ *
121
+ * @example
122
+ * const socket = new Socket({ url: "http://localhost:3000/rpc", adapter: OrpcStreamAdapter() });
123
+ * const sdk = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });
124
+ *
125
+ * sdk.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data }) => console.log(data));
126
+ */
127
+ export type OrpcSocketSchema<Router extends AnyRouter | NestedClient<any>> = OrpcSocketClientSchema<
128
+ OrpcRouterClient<Router>,
129
+ ""
130
+ >;
@@ -57,6 +57,14 @@ export const getOrpcAbortKey = (request: RequestInstance): string => {
57
57
  return `${request.method}_${orpcEndpointMapper(request.endpoint)}-${request.cancelable}`;
58
58
  };
59
59
 
60
+ /**
61
+ * Key of a subscription - listeners of the same topic with the same input share one server subscription.
62
+ * The input is read in the wire format, so values like `Date` or `Map` stay distinct.
63
+ */
64
+ export const getOrpcSubscriptionKey = (topic: string, payload: unknown, serializer: OrpcSerializerType): string => {
65
+ return `${topic}-${getOrpcInputKey(payload, serializer)}`;
66
+ };
67
+
60
68
  /** Only the user headers, the content type depends on the encoded body and is set while sending */
61
69
  export const getOrpcHeaders = (request: RequestInstance): HeadersInit => {
62
70
  return { ...(request.headers as Record<string, string> | undefined) };
@@ -70,28 +78,28 @@ type OrpcHttpRequestType = {
70
78
  };
71
79
 
72
80
  /**
73
- * Encodes the call as described by the oRPC RPC protocol.
74
- * GET sends the input in the `data` query param. Files and urls over the length limit fall back to POST,
75
- * the same as the `RPCLink` of oRPC.
81
+ * Encodes a call of the procedure as described by the oRPC RPC protocol, for any base `url` - the client url of a
82
+ * request or the url of a socket. GET sends the input in the `data` query param. Files and urls over the length limit
83
+ * fall back to POST, the same as the `RPCLink` of oRPC.
76
84
  */
77
- export const getOrpcHttpRequest = ({
78
- request,
85
+ export const getOrpcCallRequest = ({
86
+ url: base,
79
87
  endpoint,
80
88
  queryParams,
81
89
  headers,
82
90
  payload,
83
- queryMethod,
91
+ method,
84
92
  serializer,
85
93
  }: {
86
- request: RequestInstance;
94
+ url: string;
87
95
  endpoint: string;
88
96
  queryParams: unknown;
89
97
  headers: HeadersInit;
90
98
  payload: unknown;
91
- queryMethod: OrpcQueryMethod;
99
+ method: "GET" | "POST";
92
100
  serializer: OrpcSerializerType;
93
101
  }): OrpcHttpRequestType => {
94
- const [baseUrl, baseQuery] = request.client.url.split("?");
102
+ const [baseUrl, baseQuery] = base.split("?");
95
103
  const searchParams = new URLSearchParams(baseQuery);
96
104
 
97
105
  // Mappers can return anything, so we normalize their result to the query string
@@ -107,7 +115,7 @@ export const getOrpcHttpRequest = ({
107
115
  const serialized = serializer.serialize(payload);
108
116
  const userHeaders = { ...(headers as Record<string, string>) };
109
117
 
110
- if (request.method === OrpcMethods.QUERY && queryMethod === "GET" && !(serialized instanceof FormData)) {
118
+ if (method === "GET" && !(serialized instanceof FormData)) {
111
119
  const getParams = new URLSearchParams(searchParams);
112
120
  getParams.append("data", JSON.stringify(serialized));
113
121
  const getUrl = `${url}?${getParams.toString()}`;
@@ -133,6 +141,28 @@ export const getOrpcHttpRequest = ({
133
141
  };
134
142
  };
135
143
 
144
+ /**
145
+ * Encodes the request as described by the oRPC RPC protocol.
146
+ * Queries use the `queryMethod`, mutations are always sent with POST.
147
+ */
148
+ export const getOrpcHttpRequest = ({
149
+ request,
150
+ queryMethod,
151
+ ...call
152
+ }: {
153
+ request: RequestInstance;
154
+ endpoint: string;
155
+ queryParams: unknown;
156
+ headers: HeadersInit;
157
+ payload: unknown;
158
+ queryMethod: OrpcQueryMethod;
159
+ serializer: OrpcSerializerType;
160
+ }): OrpcHttpRequestType => {
161
+ const method = request.method === OrpcMethods.QUERY && queryMethod === "GET" ? "GET" : "POST";
162
+
163
+ return getOrpcCallRequest({ ...call, url: request.client.url, method });
164
+ };
165
+
136
166
  const isRecord = (value: unknown): value is Record<string, unknown> => {
137
167
  return typeof value === "object" && value !== null;
138
168
  };
package/src/index.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  // rollup client entry point
2
2
 
3
3
  export * from "./adapter";
4
+ export * from "./socket";
5
+ export * from "./stream-adapter";
6
+ export * from "./websocket-adapter";
@@ -0,0 +1,2 @@
1
+ export type { OrpcSocketAdapterConfigType, OrpcSocketErrorOptionsType, OrpcSocketExtraType } from "./socket.types";
2
+ export { OrpcSocketError } from "./socket.utils";
@@ -0,0 +1,178 @@
1
+ import type {
2
+ ExtractAdapterExtraType,
3
+ getAdapterBindings,
4
+ ListenerCallbackType,
5
+ ListenerOfAdapter,
6
+ } from "@hyper-fetch/sockets";
7
+ import { createORPCErrorFromJson, ErrorEvent, isORPCErrorJson } from "@orpc/client";
8
+
9
+ import type { OrpcSerializerType } from "../adapter/adapter.utils";
10
+ import { getOrpcSubscriptionKey } from "../adapter/adapter.utils";
11
+ import type {
12
+ OrpcIteratorEventType,
13
+ OrpcSocketAdapterInstance,
14
+ OrpcSocketExtraType,
15
+ OrpcSubscriptionType,
16
+ } from "./socket.types";
17
+ import { deserializeOrpcData, OrpcSocketError, toError } from "./socket.utils";
18
+
19
+ type BindingsType<Adapter extends OrpcSocketAdapterInstance> = ReturnType<typeof getAdapterBindings<Adapter>>;
20
+
21
+ /**
22
+ * Keeps one server subscription per procedure and input, shared by every listener with the same topic and payload.
23
+ * The adapter starts and stops the server side, this module counts the listeners, turns the events of the server
24
+ * iterator into listener messages and errors, and reports the lifecycle of the subscription to the listeners.
25
+ *
26
+ * - `start` is called for a subscription that has no running server side. It does nothing until the adapter can
27
+ * start it, the adapter starts the rest when it connects.
28
+ * - `stop` is called when the last listener of a running subscription unsubscribes - it cancels the server side.
29
+ * - `release` forgets the server side of a subscription the server ended, without telling the server.
30
+ */
31
+ export const createOrpcSubscriptions = <Adapter extends OrpcSocketAdapterInstance, Transport>({
32
+ bindings,
33
+ serializer,
34
+ start,
35
+ stop,
36
+ release,
37
+ }: {
38
+ bindings: Pick<BindingsType<Adapter>, "onListen" | "onEvent" | "onError" | "onListenerStart" | "onListenerEnd">;
39
+ serializer: OrpcSerializerType;
40
+ start: (subscription: OrpcSubscriptionType<Transport>) => void;
41
+ stop: (subscription: OrpcSubscriptionType<Transport>) => void;
42
+ release: (subscription: OrpcSubscriptionType<Transport>) => void;
43
+ }) => {
44
+ const { onListen, onEvent, onError, onListenerStart, onListenerEnd } = bindings;
45
+ const subscriptions = new Map<string, OrpcSubscriptionType<Transport>>();
46
+
47
+ /** The callbacks of a subscription as the bindings of the adapter type them */
48
+ const callbacksOf = (subscription: OrpcSubscriptionType<Transport>) =>
49
+ subscription.callbacks as ReadonlySet<ListenerCallbackType<Adapter, any>>;
50
+
51
+ const createError = (subscription: OrpcSubscriptionType<Transport>, cause: unknown) => {
52
+ return new OrpcSocketError({ cause, topic: subscription.topic, payload: subscription.payload });
53
+ };
54
+
55
+ /**
56
+ * Reports a failure of the subscription that does not end it, e.g. a dropped stream that starts again, as an
57
+ * `OrpcSocketError`, so the user can tell which subscription failed
58
+ */
59
+ const report = (subscription: OrpcSubscriptionType<Transport>, cause: unknown) => {
60
+ onError({ error: createError(subscription, cause) });
61
+ };
62
+
63
+ /** The server confirmed the subscription - after the first start and after every restart */
64
+ const confirm = (subscription: OrpcSubscriptionType<Transport>) => {
65
+ subscription.started = true;
66
+ onListenerStart({ topic: subscription.topic, callbacks: callbacksOf(subscription) });
67
+ };
68
+
69
+ /**
70
+ * The server ended the subscription - finished it when `cause` is not set, failed it otherwise. The error is
71
+ * reported to `onError` too. The listeners unsubscribe, and a later `listen()` starts a new subscription.
72
+ */
73
+ const end = (subscription: OrpcSubscriptionType<Transport>, cause?: unknown) => {
74
+ release(subscription);
75
+ subscription.started = false;
76
+ subscriptions.delete(subscription.key);
77
+
78
+ const error = cause === undefined ? null : createError(subscription, cause);
79
+ if (error) {
80
+ onError({ error });
81
+ }
82
+ onListenerEnd({ topic: subscription.topic, callbacks: new Set(callbacksOf(subscription)), error });
83
+ };
84
+
85
+ const listen = (listener: ListenerOfAdapter<Adapter>, callback: ListenerCallbackType<Adapter, any>) => {
86
+ const key = getOrpcSubscriptionKey(listener.topic, listener.payload, serializer);
87
+ const subscription: OrpcSubscriptionType<Transport> = subscriptions.get(key) ?? {
88
+ key,
89
+ topic: listener.topic,
90
+ payload: listener.payload,
91
+ callbacks: new Set(),
92
+ lastEventId: undefined,
93
+ lastEventRetry: undefined,
94
+ transport: undefined,
95
+ started: false,
96
+ };
97
+ subscriptions.set(key, subscription);
98
+ subscription.callbacks.add(callback);
99
+
100
+ const removeListener = onListen({
101
+ listener,
102
+ callback,
103
+ onUnmount: () => {
104
+ subscription.callbacks.delete(callback);
105
+ // An ended subscription is gone already, there is nothing to cancel on the server
106
+ if (subscription.callbacks.size === 0 && subscriptions.get(key) === subscription) {
107
+ subscriptions.delete(key);
108
+ stop(subscription);
109
+ }
110
+ },
111
+ });
112
+
113
+ if (subscription.started) {
114
+ // Joined a subscription the server confirmed already
115
+ onListenerStart({ topic: subscription.topic, callbacks: new Set([callback]) });
116
+ } else if (!subscription.transport) {
117
+ start(subscription);
118
+ }
119
+
120
+ return removeListener;
121
+ };
122
+
123
+ /**
124
+ * Applies an event of the server iterator to the subscription. `done` and `error` end the subscription, then it
125
+ * returns `true`. Nothing here throws into the transport: errors of the server
126
+ * and malformed data are reported as an `OrpcSocketError`, errors thrown by listener callbacks as they are.
127
+ */
128
+ const receive = (subscription: OrpcSubscriptionType<Transport>, { event, data, meta }: OrpcIteratorEventType) => {
129
+ const id = typeof meta?.id === "string" ? meta.id : undefined;
130
+ const retry = typeof meta?.retry === "number" ? meta.retry : undefined;
131
+ // Errors carry the meta too, so a failed subscription resumes from the right place
132
+ subscription.lastEventId = id ?? subscription.lastEventId;
133
+ subscription.lastEventRetry = retry ?? subscription.lastEventRetry;
134
+
135
+ // The value returned by the iterator is not delivered, listeners receive the yielded values
136
+ if (event === "done") {
137
+ end(subscription);
138
+ return true;
139
+ }
140
+
141
+ let value: unknown;
142
+ try {
143
+ value = deserializeOrpcData(data, serializer);
144
+ } catch (error) {
145
+ if (event === "error") {
146
+ end(subscription, error);
147
+ return true;
148
+ }
149
+ report(subscription, error);
150
+ return false;
151
+ }
152
+
153
+ if (event === "error") {
154
+ // The same as the `RPCLink` of oRPC - an `ORPCError` when the data is one, the raw data otherwise
155
+ end(subscription, isORPCErrorJson(value) ? createORPCErrorFromJson(value) : new ErrorEvent({ data: value }));
156
+ return true;
157
+ }
158
+
159
+ // Every adapter of this package has the event meta as its extra type
160
+ const extra = { id, retry } satisfies OrpcSocketExtraType as ExtractAdapterExtraType<Adapter>;
161
+ try {
162
+ onEvent({ topic: subscription.topic, data: value, extra, callbacks: callbacksOf(subscription) });
163
+ } catch (error) {
164
+ onError({ error: toError(error) });
165
+ }
166
+ return false;
167
+ };
168
+
169
+ return {
170
+ listen,
171
+ receive,
172
+ report,
173
+ confirm,
174
+ end,
175
+ /** Every subscription with at least one listener */
176
+ values: () => [...subscriptions.values()],
177
+ };
178
+ };
@@ -0,0 +1,64 @@
1
+ import type { ListenerCallbackType, SocketAdapter } from "@hyper-fetch/sockets";
2
+ import type { StandardRPCCustomJsonSerializer } from "@orpc/client/standard";
3
+
4
+ /**
5
+ * Meta of the event, passed to the listeners as `extra`.
6
+ * The server sets it with `withEventMeta(value, { id, retry })`.
7
+ */
8
+ export type OrpcSocketExtraType = {
9
+ /** Id of the event. It is sent back as `last-event-id` when the subscription starts again, so the server can resume */
10
+ id: string | undefined;
11
+ /** Delay in milliseconds the server asks for before the subscription starts again after a failure */
12
+ retry: number | undefined;
13
+ };
14
+
15
+ /** Options of the `OrpcStreamAdapter` and `OrpcWebsocketAdapter` factories */
16
+ export type OrpcSocketAdapterConfigType = {
17
+ /**
18
+ * Serializers of custom types, the same as the `customJsonSerializers` option of `RPCHandler` and `RPCLink`.
19
+ * Both sides need the same list.
20
+ */
21
+ customJsonSerializers?: StandardRPCCustomJsonSerializer[];
22
+ };
23
+
24
+ /** Any socket adapter of this package, the listeners receive the event meta as `extra` */
25
+ export type OrpcSocketAdapterInstance = SocketAdapter<OrpcSocketExtraType, any, any, any, any, any>;
26
+
27
+ /** An event of the server event iterator, with the data still in the serialized `{ json, meta }` form */
28
+ export type OrpcIteratorEventType = {
29
+ event: "message" | "error" | "done";
30
+ data: unknown;
31
+ meta: { id?: unknown; retry?: unknown } | undefined;
32
+ };
33
+
34
+ /**
35
+ * One server subscription - the procedure called with one input. Every listener with the same topic and payload
36
+ * shares it. `transport` holds the adapter state of the running server side, it is empty when nothing runs.
37
+ * Once the server ends it, the subscription is gone - a later `listen()` creates a new one.
38
+ */
39
+ export type OrpcSubscriptionType<Transport> = {
40
+ key: string;
41
+ topic: string;
42
+ payload: unknown;
43
+ callbacks: Set<ListenerCallbackType<any, any>>;
44
+ /** Id of the last event, sent as `last-event-id` when the subscription starts again */
45
+ lastEventId: string | undefined;
46
+ /** Retry delay of the last event */
47
+ lastEventRetry: number | undefined;
48
+ transport: Transport | undefined;
49
+ /** `true` once the server confirmed the running server side, reset when it starts again */
50
+ started: boolean;
51
+ };
52
+
53
+ /** Details of the subscription an `OrpcSocketError` belongs to */
54
+ export type OrpcSocketErrorOptionsType = {
55
+ /**
56
+ * What went wrong - the `ORPCError` the server sent, the `ErrorEvent` of an error event without the oRPC shape,
57
+ * or the error of the transport or the decoding.
58
+ */
59
+ cause: unknown;
60
+ /** Topic of the failed subscription, `null` when the message can't be matched to a subscription */
61
+ topic: string | null;
62
+ /** Input of the failed subscription */
63
+ payload: unknown;
64
+ };
@@ -0,0 +1,110 @@
1
+ import { createORPCErrorFromJson, isORPCErrorJson, ORPCError } from "@orpc/client";
2
+ import { getMalformedResponseErrorCode } from "@orpc/client/standard";
3
+
4
+ import type { OrpcErrorType } from "../adapter/adapter.types";
5
+ import type { OrpcSerializerType } from "../adapter/adapter.utils";
6
+ import type { OrpcSocketErrorOptionsType } from "./socket.types";
7
+
8
+ export const toError = (error: unknown): Error => {
9
+ return error instanceof Error ? error : new Error(String(error));
10
+ };
11
+
12
+ export const isRecord = (value: unknown): value is Record<string, unknown> => {
13
+ return typeof value === "object" && value !== null;
14
+ };
15
+
16
+ /**
17
+ * Turns the serialized `{ json, meta }` data into the value. Anything else is not a part of the RPC protocol.
18
+ * It throws for malformed data, the same as the serializer of oRPC.
19
+ */
20
+ export const deserializeOrpcData = (data: unknown, serializer: OrpcSerializerType): unknown => {
21
+ if (data !== undefined && !isRecord(data)) {
22
+ throw new TypeError("Invalid RPC serialized data: expected the { json, meta } object");
23
+ }
24
+ return serializer.deserialize(data);
25
+ };
26
+
27
+ /**
28
+ * The error of a call the server rejected before the event iterator started, e.g. a failed input validation or
29
+ * middleware. The same as in the `RPCLink` of oRPC: an `ORPCError` from the body, or one named after the status
30
+ * when the body is not an oRPC error.
31
+ */
32
+ export const getOrpcResponseError = ({
33
+ status,
34
+ body,
35
+ serializer,
36
+ }: {
37
+ status: number;
38
+ body: unknown;
39
+ serializer: OrpcSerializerType;
40
+ }): ORPCError<string, unknown> => {
41
+ let value = body;
42
+ try {
43
+ value = deserializeOrpcData(body, serializer);
44
+ } catch {
45
+ // The raw body stays in the data of the error below
46
+ }
47
+
48
+ if (isORPCErrorJson(value)) {
49
+ return createORPCErrorFromJson(value);
50
+ }
51
+ return new ORPCError(getMalformedResponseErrorCode(status), { status, data: value });
52
+ };
53
+
54
+ /** Reported when the procedure of a listener returns a regular output instead of an event iterator */
55
+ export const getNotIteratorError = (topic: string): Error => {
56
+ return new Error(`The procedure "${topic}" did not return an event iterator`);
57
+ };
58
+
59
+ /**
60
+ * Error of an oRPC subscription, reported to the `socket.onError` callbacks. `topic` and `payload` tell which
61
+ * subscription failed. `shape` is the error the server sent, in the shape of `ORPCError.toJSON()` - it is `null` when
62
+ * the failure did not come from a procedure, e.g. a dropped stream or a malformed message. The original error is the
63
+ * `cause`.
64
+ *
65
+ * @example
66
+ * socket.onError(({ error }) => {
67
+ * if (error instanceof OrpcSocketError && error.defined && error.code === "UNAUTHORIZED") {
68
+ * logout();
69
+ * }
70
+ * });
71
+ */
72
+ export class OrpcSocketError<Code extends string = string, Data = unknown> extends Error {
73
+ /** Error sent by the server, `null` when the failure did not come from a procedure */
74
+ readonly shape: OrpcErrorType<Code, Data> | null;
75
+ /** Topic of the failed subscription, `null` when the message can't be matched to a subscription */
76
+ readonly topic: string | null;
77
+ /** Input of the failed subscription */
78
+ readonly payload: unknown;
79
+ /** The `ORPCError` sent by the server, or the error of the transport or the decoding */
80
+ declare readonly cause: unknown;
81
+
82
+ constructor({ cause, topic, payload }: OrpcSocketErrorOptionsType) {
83
+ const shape = cause instanceof ORPCError ? (cause.toJSON() as OrpcErrorType<Code, Data>) : null;
84
+ super(shape?.message ?? toError(cause).message, { cause });
85
+ this.name = "OrpcSocketError";
86
+ this.shape = shape;
87
+ this.topic = topic;
88
+ this.payload = payload;
89
+ }
90
+
91
+ /** `true` for the errors from the `.errors()` map of the procedure */
92
+ get defined(): boolean {
93
+ return this.shape?.defined ?? false;
94
+ }
95
+
96
+ /** Code of the server error, e.g. `"NOT_FOUND"` */
97
+ get code(): Code | undefined {
98
+ return this.shape?.code;
99
+ }
100
+
101
+ /** Status of the server error */
102
+ get status(): number | undefined {
103
+ return this.shape?.status;
104
+ }
105
+
106
+ /** Data of the server error */
107
+ get data(): Data | undefined {
108
+ return this.shape?.data;
109
+ }
110
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./stream-adapter";
2
+ export * from "./stream-adapter.types";