@hyper-fetch/graphql 10.0.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 (57) hide show
  1. package/README.md +152 -84
  2. package/__tests__/e2e/e2e.conformance.spec.ts +206 -0
  3. package/__tests__/e2e/e2e.graphql-ws-server.ts +187 -0
  4. package/__tests__/e2e/e2e.graphql-ws.spec.ts +306 -0
  5. package/__tests__/e2e/e2e.react-subscriptions.spec.tsx +208 -0
  6. package/__tests__/features/adapter/adapter.browser.spec.ts +23 -5
  7. package/__tests__/features/adapter/adapter.document.spec.ts +17 -13
  8. package/__tests__/features/adapter/adapter.headers.spec.ts +65 -0
  9. package/__tests__/features/adapter/adapter.keys.spec.ts +235 -0
  10. package/__tests__/features/adapter/adapter.persisted-queries.spec.ts +207 -0
  11. package/__tests__/features/adapter/adapter.progress.spec.ts +39 -0
  12. package/__tests__/features/adapter/adapter.responses.spec.ts +162 -1
  13. package/__tests__/features/adapter/adapter.server.spec.ts +6 -6
  14. package/__tests__/features/adapter/adapter.types.spec.ts +121 -2
  15. package/__tests__/features/adapter/adapter.utils.spec.ts +4 -2
  16. package/__tests__/features/adapter/adapter.variables.spec.ts +3 -3
  17. package/__tests__/features/socket/socket.connection.spec.ts +892 -0
  18. package/__tests__/features/socket/socket.fuzz.spec.ts +329 -0
  19. package/__tests__/features/socket/socket.subscriptions.spec.ts +515 -0
  20. package/__tests__/features/socket/socket.types.spec.ts +160 -0
  21. package/__tests__/utils/controlled-websocket.ts +238 -0
  22. package/dist/adapter/adapter.constants.d.ts +5 -0
  23. package/dist/adapter/adapter.constants.d.ts.map +1 -1
  24. package/dist/adapter/adapter.types.d.ts +55 -2
  25. package/dist/adapter/adapter.types.d.ts.map +1 -1
  26. package/dist/adapter/adapter.utils.d.ts +51 -4
  27. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  28. package/dist/adapter/http-adapter.fetch.d.ts.map +1 -1
  29. package/dist/index.d.ts +1 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.mjs +958 -128
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/socket/index.d.ts +5 -0
  34. package/dist/socket/index.d.ts.map +1 -0
  35. package/dist/socket/socket.constants.d.ts +44 -0
  36. package/dist/socket/socket.constants.d.ts.map +1 -0
  37. package/dist/socket/socket.subscriptions.d.ts +74 -0
  38. package/dist/socket/socket.subscriptions.d.ts.map +1 -0
  39. package/dist/socket/socket.types.d.ts +102 -0
  40. package/dist/socket/socket.types.d.ts.map +1 -0
  41. package/dist/socket/socket.utils.d.ts +80 -0
  42. package/dist/socket/socket.utils.d.ts.map +1 -0
  43. package/dist/socket/socket.websocket.d.ts +30 -0
  44. package/dist/socket/socket.websocket.d.ts.map +1 -0
  45. package/package.json +14 -9
  46. package/src/adapter/adapter.constants.ts +6 -0
  47. package/src/adapter/adapter.types.ts +69 -3
  48. package/src/adapter/adapter.utils.ts +196 -25
  49. package/src/adapter/http-adapter.fetch.ts +93 -43
  50. package/src/index.ts +1 -0
  51. package/src/socket/index.ts +4 -0
  52. package/src/socket/socket.constants.ts +59 -0
  53. package/src/socket/socket.subscriptions.ts +160 -0
  54. package/src/socket/socket.types.ts +118 -0
  55. package/src/socket/socket.utils.ts +150 -0
  56. package/src/socket/socket.websocket.ts +555 -0
  57. package/vite.config.ts +4 -0
@@ -1,7 +1,7 @@
1
1
  import type { DefaultMapperType, QueryParamsType } from "@hyper-fetch/core";
2
2
  import { parseResponse, getErrorMessage, Adapter, stringifyQueryParams } from "@hyper-fetch/core";
3
3
 
4
- import { gqlExtra, defaultTimeout } from "./adapter.constants";
4
+ import { gqlExtra, defaultTimeout, gqlAcceptHeader } from "./adapter.constants";
5
5
  import type {
6
6
  GraphqlAdapterType,
7
7
  GraphQlExtraType,
@@ -11,6 +11,10 @@ import type {
11
11
  } from "./adapter.types";
12
12
  import { GraphqlMethod } from "./adapter.types";
13
13
  import {
14
+ getGqlDocument,
15
+ getGqlHeaders,
16
+ getPersistedQueryHash,
17
+ getPersistedQueryMiss,
14
18
  getRequestValues,
15
19
  gqlEndpointMapper,
16
20
  gqlEndpointNameMapper,
@@ -18,8 +22,11 @@ import {
18
22
  gqlRequestNameMapper,
19
23
  } from "./adapter.utils";
20
24
 
21
- export const getGqlAdapter = (): GraphqlAdapterType =>
22
- new Adapter<
25
+ export const getGqlAdapter = (): GraphqlAdapterType => {
26
+ // Turned off for this adapter once the server reports that it does not support persisted queries
27
+ let persistedQueriesSupported = true;
28
+
29
+ return new Adapter<
23
30
  FetchGraphqlAdapterOptionsType,
24
31
  GraphqlMethod,
25
32
  number,
@@ -51,6 +58,7 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
51
58
  gqlEndpointNameMapper(requestOptions?.document ?? endpoint),
52
59
  )
53
60
  .setEndpointMapper(gqlEndpointMapper)
61
+ .setHeaderMapper(getGqlHeaders)
54
62
  .setQueryParamsMapper(stringifyQueryParams)
55
63
  .setFetcher(
56
64
  async ({
@@ -68,13 +76,15 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
68
76
  onResponseStart,
69
77
  onBeforeRequest,
70
78
  onRequestStart,
71
- onRequestProgress,
72
79
  onSuccess,
73
80
  }) => {
74
- const { fullUrl, payload } = getRequestValues(request, queryParams);
75
-
76
81
  const controller = getAbortController();
77
- const { timeout: timeoutMs = defaultTimeout, ...restOptions } = adapterOptions || {};
82
+ const {
83
+ timeout: timeoutMs = defaultTimeout,
84
+ errorPolicy = "none",
85
+ persistedQueries = false,
86
+ ...restOptions
87
+ } = adapterOptions || {};
78
88
 
79
89
  let timedOut = false;
80
90
  let timeoutId: ReturnType<typeof setTimeout> | undefined;
@@ -84,6 +94,7 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
84
94
  extra: gqlExtra,
85
95
  });
86
96
 
97
+ // One timeout for the whole operation - a persisted query miss and the request that registers it
87
98
  if (timeoutMs > 0 && controller) {
88
99
  timeoutId = setTimeout(() => {
89
100
  timedOut = true;
@@ -92,44 +103,48 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
92
103
  }, timeoutMs);
93
104
  }
94
105
 
106
+ // The hashed request goes first. Without Web Crypto the hash is null and the full query is sent.
107
+ const sha256Hash =
108
+ persistedQueries && persistedQueriesSupported
109
+ ? await getPersistedQueryHash(gqlEndpointMapper(getGqlDocument(request)))
110
+ : null;
111
+ const persistedQuery = sha256Hash ? ({ version: 1, sha256Hash } as const) : null;
112
+ const firstValues = getRequestValues(
113
+ request,
114
+ queryParams,
115
+ persistedQuery ? { persistedQuery, withQuery: false } : undefined,
116
+ );
117
+ const total = firstValues.payload ? new Blob([firstValues.payload]).size : 0;
118
+
95
119
  onBeforeRequest();
96
- onRequestStart();
120
+ onRequestStart(total ? { total, loaded: 0 } : undefined);
97
121
 
98
122
  try {
123
+ const requestHeaders = headers as Record<string, string>;
124
+ const hasAcceptHeader = Object.keys(requestHeaders).some((key) => key.toLowerCase() === "accept");
99
125
  const init: RequestInit = {
100
126
  method: request.method,
101
- headers: headers as Record<string, string>,
127
+ headers: hasAcceptHeader ? requestHeaders : { Accept: gqlAcceptHeader, ...requestHeaders },
102
128
  signal: controller?.signal,
103
129
  ...restOptions,
104
130
  };
105
131
 
106
- if (payload) {
107
- init.body = payload;
132
+ const sendAttempt = (values: { fullUrl: string; payload: string | null }) => {
133
+ return fetch(values.fullUrl, values.payload ? { ...init, body: values.payload } : init);
134
+ };
108
135
 
109
- if (typeof payload === "string") {
110
- const total = new Blob([payload]).size;
111
- onRequestProgress({ total, loaded: total } as ProgressEvent);
136
+ const clearTimer = () => {
137
+ if (timeoutId) {
138
+ clearTimeout(timeoutId);
112
139
  }
113
- }
114
-
115
- onRequestEnd();
116
-
117
- const response = await fetch(fullUrl, init);
118
-
119
- if (timeoutId) {
120
- clearTimeout(timeoutId);
121
- }
122
-
123
- onResponseStart();
124
-
125
- const responseHeaders: Record<string, string> = {};
126
- response.headers.forEach((value, key) => {
127
- responseHeaders[key] = value;
128
- });
140
+ };
129
141
 
130
- let body: string;
142
+ /** Reads the body. Without `reportProgress` it reports the whole body at once, after reading it. */
143
+ const readBody = async (response: Response, reportProgress: boolean) => {
144
+ if (!response.body || typeof response.body.getReader !== "function") {
145
+ return response.text();
146
+ }
131
147
 
132
- if (response.body && typeof response.body.getReader === "function") {
133
148
  const reader = response.body.getReader();
134
149
  const contentLength = parseInt(response.headers.get("content-length") || "0", 10);
135
150
  let receivedLength = 0;
@@ -144,7 +159,13 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
144
159
  }
145
160
  chunks.push(value);
146
161
  receivedLength += value.length;
147
- onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);
162
+ if (reportProgress) {
163
+ onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);
164
+ }
165
+ }
166
+
167
+ if (!reportProgress) {
168
+ onResponseProgress({ total: receivedLength, loaded: receivedLength } as ProgressEvent);
148
169
  }
149
170
 
150
171
  const allChunks = new Uint8Array(receivedLength);
@@ -154,11 +175,39 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
154
175
  allChunks.set(chunk, position);
155
176
  position += chunk.length;
156
177
  }
157
- body = new TextDecoder().decode(allChunks);
178
+ return new TextDecoder().decode(allChunks);
179
+ };
180
+
181
+ let response = await sendAttempt(firstValues);
182
+ // Fetch has no upload events. The response is the first sign that the whole body was sent.
183
+ onRequestEnd();
184
+ // The timeout covers the time to the response headers. A hashed request can still be a miss, so it waits.
185
+ if (!persistedQuery) {
186
+ clearTimer();
187
+ }
188
+ onResponseStart();
189
+
190
+ // A hashed request can be a miss, so its body is reported only once it is known to be the answer
191
+ let body = await readBody(response, !persistedQuery);
192
+
193
+ const miss = persistedQuery ? getPersistedQueryMiss(parseResponse(body)) : null;
194
+ if (persistedQuery && miss) {
195
+ if (miss === "not-supported") {
196
+ persistedQueriesSupported = false;
197
+ }
198
+ const persisted = miss === "not-found" ? { persistedQuery, withQuery: true } : undefined;
199
+ response = await sendAttempt(getRequestValues(request, queryParams, persisted));
200
+ clearTimer();
201
+ body = await readBody(response, true);
158
202
  } else {
159
- body = await response.text();
203
+ clearTimer();
160
204
  }
161
205
 
206
+ const responseHeaders: Record<string, string> = {};
207
+ response.headers.forEach((value, key) => {
208
+ responseHeaders[key] = value;
209
+ });
210
+
162
211
  onResponseEnd();
163
212
  unmountListener();
164
213
 
@@ -168,18 +217,18 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
168
217
  // An empty `errors` list is not a failure
169
218
  const errors = Array.isArray(parsed?.errors) && parsed.errors.length === 0 ? null : parsed?.errors || null;
170
219
  const extensions = parsed?.extensions || {};
171
- const failure = errors || status > 399 || status === 0;
220
+ const extra = errors
221
+ ? { headers: responseHeaders, extensions, errors }
222
+ : { headers: responseHeaders, extensions };
223
+ const failedStatus = status > 399 || status === 0;
224
+ const keepsPartialData = errorPolicy === "all" && data !== null;
225
+ const failure = failedStatus || (errors && !keepsPartialData);
172
226
 
173
227
  if (failure) {
174
228
  const error = errors || [getErrorMessage()];
175
- onError({ error, status, extra: { headers: responseHeaders, extensions } });
229
+ onError({ error, status, extra });
176
230
  } else {
177
- onSuccess({
178
- data,
179
- error: errors,
180
- status,
181
- extra: { headers: responseHeaders, extensions },
182
- });
231
+ onSuccess({ data, status, extra });
183
232
  }
184
233
  } catch (error: any) {
185
234
  if (timeoutId) clearTimeout(timeoutId);
@@ -197,3 +246,4 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
197
246
  }
198
247
  },
199
248
  );
249
+ };
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  // rollup client entry point
2
2
 
3
3
  export * from "./adapter";
4
+ export * from "./socket";
@@ -0,0 +1,4 @@
1
+ export * from "./socket.types";
2
+ export * from "./socket.websocket";
3
+ export { GRAPHQL_TRANSPORT_WS_PROTOCOL, GraphqlWsCloseCode } from "./socket.constants";
4
+ export { GraphqlSubscriptionError, shouldReconnectGraphqlWs } from "./socket.utils";
@@ -0,0 +1,59 @@
1
+ import { Time } from "@hyper-fetch/core";
2
+
3
+ /** Subprotocol of GraphQL over WebSocket, the protocol of `graphql-ws` */
4
+ export const GRAPHQL_TRANSPORT_WS_PROTOCOL = "graphql-transport-ws";
5
+
6
+ /** Message types of the `graphql-transport-ws` protocol */
7
+ export const GraphqlWsMessageType = {
8
+ CONNECTION_INIT: "connection_init",
9
+ CONNECTION_ACK: "connection_ack",
10
+ PING: "ping",
11
+ PONG: "pong",
12
+ SUBSCRIBE: "subscribe",
13
+ NEXT: "next",
14
+ ERROR: "error",
15
+ COMPLETE: "complete",
16
+ } as const;
17
+
18
+ /** Close codes of the `graphql-transport-ws` protocol */
19
+ export const GraphqlWsCloseCode = {
20
+ INTERNAL_SERVER_ERROR: 4500,
21
+ INTERNAL_CLIENT_ERROR: 4005,
22
+ BAD_REQUEST: 4400,
23
+ BAD_RESPONSE: 4004,
24
+ UNAUTHORIZED: 4401,
25
+ FORBIDDEN: 4403,
26
+ SUBPROTOCOL_NOT_ACCEPTABLE: 4406,
27
+ CONNECTION_INITIALISATION_TIMEOUT: 4408,
28
+ CONNECTION_ACKNOWLEDGEMENT_TIMEOUT: 4504,
29
+ SUBSCRIBER_ALREADY_EXISTS: 4409,
30
+ TOO_MANY_INITIALISATION_REQUESTS: 4429,
31
+ } as const;
32
+
33
+ /**
34
+ * Close codes that a retry can't fix - the same ones the `graphql-ws` client gives up on. Forbidden (4403) and the
35
+ * timeouts (4408, 4504) are retried, as access may be granted and the server may answer in time on the next attempt.
36
+ */
37
+ export const fatalGraphqlWsCloseCodes: ReadonlySet<number> = new Set([
38
+ GraphqlWsCloseCode.INTERNAL_SERVER_ERROR,
39
+ GraphqlWsCloseCode.INTERNAL_CLIENT_ERROR,
40
+ GraphqlWsCloseCode.BAD_REQUEST,
41
+ GraphqlWsCloseCode.BAD_RESPONSE,
42
+ GraphqlWsCloseCode.UNAUTHORIZED,
43
+ GraphqlWsCloseCode.SUBPROTOCOL_NOT_ACCEPTABLE,
44
+ GraphqlWsCloseCode.SUBSCRIBER_ALREADY_EXISTS,
45
+ GraphqlWsCloseCode.TOO_MANY_INITIALISATION_REQUESTS,
46
+ ]);
47
+
48
+ /**
49
+ * Close codes of the WebSocket standard (1001-1999) that a retry can fix: going away, no status, abnormal closure,
50
+ * service restart, try again later and bad gateway. The other ones report a broken client or server, e.g. 1002
51
+ * (protocol error) or 1003 (unsupported data). A normal closure (1000) stays closed, as with every socket adapter.
52
+ */
53
+ export const retriedStandardCloseCodes: ReadonlySet<number> = new Set([1001, 1005, 1006, 1012, 1013, 1014]);
54
+
55
+ /** Defaults of the keep-alive */
56
+ export const defaultKeepAlive = {
57
+ intervalMs: Time.SEC * 10,
58
+ pongTimeoutMs: Time.SEC * 5,
59
+ };
@@ -0,0 +1,160 @@
1
+ import type { ListenerCallbackType, SocketAdapterInstance } from "@hyper-fetch/sockets";
2
+ import type { GraphQLFormattedError } from "graphql";
3
+
4
+ import { getGqlOperationName, gqlEndpointMapper } from "../adapter/adapter.utils";
5
+ import type { GraphqlWsExtraType, GraphqlWsListenerOptionsType } from "./socket.types";
6
+ import { toError } from "./socket.utils";
7
+
8
+ type CallbackType = ListenerCallbackType<SocketAdapterInstance, any>;
9
+
10
+ /** One server subscription: a document with one set of variables, shared by every callback listening to it */
11
+ export type GraphqlSubscriptionType = {
12
+ /** Topic, document and encoded variables - one server subscription per key */
13
+ key: string;
14
+ topic: string;
15
+ /** Printed document, sent as `query` */
16
+ query: string;
17
+ operationName: string | undefined;
18
+ /** Variables as the listener has them, sent with the subscription and passed to the callbacks in `extra` */
19
+ payload: unknown;
20
+ callbacks: Set<CallbackType>;
21
+ /** The subscription was sent over the current acknowledged connection */
22
+ started: boolean;
23
+ };
24
+
25
+ /** What the subscriptions need from the listener - the topic, the document and the variables */
26
+ type GraphqlListenerType = { topic: string; payload?: unknown; options?: GraphqlWsListenerOptionsType };
27
+
28
+ /** The adapter bindings used by the subscriptions */
29
+ type GraphqlBindingsType = {
30
+ onListen: (options: {
31
+ listener: GraphqlListenerType;
32
+ callback: CallbackType;
33
+ onUnmount?: VoidFunction;
34
+ }) => () => void;
35
+ onEvent: (options: {
36
+ topic: string;
37
+ data: unknown;
38
+ extra: GraphqlWsExtraType;
39
+ callbacks?: ReadonlySet<CallbackType>;
40
+ }) => void;
41
+ onError: (options: { error: Error }) => void;
42
+ onListenerStart: (options: { topic: string; callbacks: ReadonlySet<CallbackType> }) => void;
43
+ onListenerEnd: (options: { topic: string; callbacks: ReadonlySet<CallbackType>; error: Error | null }) => void;
44
+ };
45
+
46
+ /**
47
+ * Keeps one server subscription per topic, document and variables. Callbacks with the same ones share it, the first
48
+ * one starts it and the last one to leave stops it. The adapter only moves the subscriptions over its transport.
49
+ */
50
+ export const createGraphqlSubscriptions = ({
51
+ bindings: { onListen, onEvent, onError, onListenerStart, onListenerEnd },
52
+ onStart,
53
+ onStop,
54
+ }: {
55
+ bindings: GraphqlBindingsType;
56
+ /** The first callback joined - start the subscription when the connection is acknowledged */
57
+ onStart: (subscription: GraphqlSubscriptionType) => void;
58
+ /** The last callback left - stop the subscription on the server */
59
+ onStop: (subscription: GraphqlSubscriptionType) => void;
60
+ }) => {
61
+ const subscriptions = new Map<string, GraphqlSubscriptionType>();
62
+
63
+ const leave = (subscription: GraphqlSubscriptionType, callback: CallbackType) => {
64
+ if (!subscription.callbacks.delete(callback) || subscription.callbacks.size > 0) {
65
+ return;
66
+ }
67
+ // A subscription ended by the server is not running anymore - its listeners leave on their own, nothing to stop
68
+ if (subscriptions.get(subscription.key) === subscription) {
69
+ subscriptions.delete(subscription.key);
70
+ onStop(subscription);
71
+ }
72
+ };
73
+
74
+ const listen = (listener: GraphqlListenerType, callback: CallbackType) => {
75
+ const document = listener.options?.document ?? listener.topic;
76
+ let query: string;
77
+ let key: string;
78
+ try {
79
+ query = gqlEndpointMapper(document);
80
+ // `undefined` variables are not sent - the subscription has none
81
+ key = `${listener.topic}\n${query}\n${JSON.stringify(listener.payload) ?? ""}`;
82
+ } catch (error) {
83
+ // Nothing can be sent to the server - the callback is registered, so unsubscribing still works
84
+ onError({ error: toError(error) });
85
+ return onListen({ listener, callback });
86
+ }
87
+
88
+ const existing = subscriptions.get(key);
89
+ const subscription: GraphqlSubscriptionType = existing ?? {
90
+ key,
91
+ topic: listener.topic,
92
+ query,
93
+ operationName: getGqlOperationName(document),
94
+ payload: listener.payload,
95
+ callbacks: new Set(),
96
+ started: false,
97
+ };
98
+ subscription.callbacks.add(callback);
99
+
100
+ const removeListener = onListen({ listener, callback, onUnmount: () => leave(subscription, callback) });
101
+
102
+ if (!existing) {
103
+ subscriptions.set(key, subscription);
104
+ onStart(subscription);
105
+ } else if (existing.started) {
106
+ // Joined a subscription that is running already - only this callback has to hear about it
107
+ onListenerStart({ topic: subscription.topic, callbacks: new Set([callback]) });
108
+ }
109
+
110
+ return removeListener;
111
+ };
112
+
113
+ /** Delivers an event to the callbacks of the subscription only */
114
+ const deliver = (
115
+ subscription: GraphqlSubscriptionType,
116
+ { data, errors, extensions }: { data: unknown; errors: GraphQLFormattedError[] | undefined; extensions: unknown },
117
+ ) => {
118
+ const extra: GraphqlWsExtraType = {
119
+ errors,
120
+ extensions: (extensions as Record<string, unknown> | undefined) ?? {},
121
+ payload: subscription.payload,
122
+ };
123
+ try {
124
+ onEvent({ topic: subscription.topic, data, extra, callbacks: subscription.callbacks });
125
+ } catch (error) {
126
+ // A throwing callback must not break the transport, the other callbacks got the event already
127
+ onError({ error: toError(error) });
128
+ }
129
+ };
130
+
131
+ /** The subscription was sent over an acknowledged connection - after the first start and after every restart */
132
+ const confirm = (subscription: GraphqlSubscriptionType) => {
133
+ // eslint-disable-next-line no-param-reassign
134
+ subscription.started = true;
135
+ onListenerStart({ topic: subscription.topic, callbacks: subscription.callbacks });
136
+ };
137
+
138
+ /** The connection of the subscription dropped - it has to be sent again */
139
+ const unconfirm = (subscription: GraphqlSubscriptionType) => {
140
+ // eslint-disable-next-line no-param-reassign
141
+ subscription.started = false;
142
+ };
143
+
144
+ /**
145
+ * The server ended the subscription - it completed (`error: null`) or failed. Its listeners deliver what is pending
146
+ * and unsubscribe, and a later `listen()` with the same variables starts a new subscription from scratch.
147
+ */
148
+ const end = (subscription: GraphqlSubscriptionType, error: Error | null) => {
149
+ // Only running subscriptions can be ended, and a running one is always the subscription of its key.
150
+ // It is removed first, so the listeners leaving below don't stop it again.
151
+ subscriptions.delete(subscription.key);
152
+ unconfirm(subscription);
153
+ onListenerEnd({ topic: subscription.topic, callbacks: subscription.callbacks, error });
154
+ };
155
+
156
+ /** Subscriptions with at least one callback, the ones to start when the connection is acknowledged */
157
+ const getAll = () => [...subscriptions.values()];
158
+
159
+ return { listen, deliver, confirm, unconfirm, end, getAll };
160
+ };
@@ -0,0 +1,118 @@
1
+ import type { QueryParamsType, stringifyQueryParams } from "@hyper-fetch/core";
2
+ import type { SocketAdapter } from "@hyper-fetch/sockets";
3
+ import type { GraphQLFormattedError } from "graphql";
4
+
5
+ import type { GraphQlEndpointType } from "../adapter/adapter.types";
6
+
7
+ /**
8
+ * The `extra` of every subscription event, received by `listen` callbacks next to the `data`.
9
+ */
10
+ export type GraphqlWsExtraType = {
11
+ /**
12
+ * Errors of the event. The server sends them next to the `data` when resolving the event failed in part - the
13
+ * subscription keeps running. `undefined` when the event has none.
14
+ *
15
+ * A subscription the server can't execute at all, e.g. with missing variables, gets one event with these errors and
16
+ * `null` data, and then it completes.
17
+ */
18
+ errors?: GraphQLFormattedError[];
19
+ /** The `extensions` of the event, `{}` when the server sent none */
20
+ extensions: Record<string, unknown>;
21
+ /**
22
+ * Variables of the subscription the event belongs to. Listeners of one topic with other variables are separate
23
+ * subscriptions, so it tells them apart where events of every subscription meet, like `socket.events.onListenerEvent`.
24
+ */
25
+ payload: unknown;
26
+ };
27
+
28
+ /** Payload of `connection_init`, read by the server in `onConnect` as `ctx.connectionParams`, e.g. an auth token */
29
+ export type GraphqlWsConnectionParamsType = Record<string, unknown>;
30
+
31
+ /**
32
+ * Keep-alive of the connection. The client sends `ping` when the connection is quiet and treats it as lost when the
33
+ * `pong` does not arrive in time - the only way to notice a connection that died without a close, e.g. behind a proxy.
34
+ */
35
+ export type GraphqlWsKeepAliveOptionsType = {
36
+ enabled: boolean;
37
+ /**
38
+ * How long the connection can be quiet before the client sends `ping`, in milliseconds.
39
+ * @default 10000
40
+ */
41
+ intervalMs?: number;
42
+ /**
43
+ * How long the client waits for `pong` before it reconnects, in milliseconds.
44
+ * @default 5000
45
+ */
46
+ pongTimeoutMs?: number;
47
+ };
48
+
49
+ /**
50
+ * Options of the GraphQL WebSocket connection, passed as `adapterOptions` to the `Socket`.
51
+ * They can be changed per connection attempt with `socket.onConnect`.
52
+ */
53
+ export type GraphqlWsAdapterOptionsType = {
54
+ /**
55
+ * Connect when the socket is created. Only the first connection depends on it - a socket connected by hand also
56
+ * reconnects after a lost connection and when the app goes back online. Ignored with `lazy`.
57
+ * @default true
58
+ */
59
+ autoConnect?: boolean;
60
+ /**
61
+ * Connect when the first subscription starts and close the connection when the last one stops, after
62
+ * `lazyCloseTimeout`. A socket without subscriptions holds no connection.
63
+ * @default false
64
+ */
65
+ lazy?: boolean;
66
+ /**
67
+ * With `lazy`, how long the connection stays open after the last subscription stopped, in milliseconds. A
68
+ * subscription started in this time reuses the connection.
69
+ * @default 0
70
+ */
71
+ lazyCloseTimeout?: number;
72
+ /**
73
+ * The `WebSocket` class to use, for example from the `ws` package. Defaults to the global one
74
+ * (browsers, Node.js 22+, Bun, Deno).
75
+ */
76
+ WebSocket?: typeof WebSocket;
77
+ /**
78
+ * Sent with `connection_init` on every connection, before any subscription starts. A function runs on every
79
+ * connection attempt, so a reconnect sends a fresh token. When it throws or rejects, the connection is closed with
80
+ * 4005 and not retried.
81
+ */
82
+ connectionParams?:
83
+ | GraphqlWsConnectionParamsType
84
+ | (() => GraphqlWsConnectionParamsType | undefined | Promise<GraphqlWsConnectionParamsType | undefined>);
85
+ /** Sends `ping` on a quiet connection and reconnects when the server does not answer */
86
+ keepAlive?: GraphqlWsKeepAliveOptionsType;
87
+ };
88
+
89
+ /**
90
+ * Options of a listener, set with `options` in `createListener` or with `listener.setOptions()`.
91
+ */
92
+ export type GraphqlWsListenerOptionsType = {
93
+ /**
94
+ * The subscription document. A typed document (graphql-codegen, gql.tada) types the listener's data and variables.
95
+ * When it is omitted, the `topic` is sent as the document.
96
+ */
97
+ document?: GraphQlEndpointType;
98
+ };
99
+
100
+ /** Socket adapter speaking the GraphQL over WebSocket protocol (`graphql-transport-ws`) */
101
+ export type GraphqlWsAdapterType = SocketAdapter<
102
+ GraphqlWsExtraType,
103
+ GraphqlWsAdapterOptionsType,
104
+ GraphqlWsListenerOptionsType,
105
+ undefined,
106
+ QueryParamsType | string,
107
+ typeof stringifyQueryParams
108
+ >;
109
+
110
+ /** Details of the subscription a {@link GraphqlSubscriptionError} belongs to */
111
+ export type GraphqlSubscriptionErrorOptionsType = {
112
+ /** Errors sent by the server with the `error` message */
113
+ errors: GraphQLFormattedError[];
114
+ /** Topic of the failed subscription */
115
+ topic: string;
116
+ /** Variables of the failed subscription */
117
+ payload: unknown;
118
+ };