@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.
- package/README.md +152 -84
- package/__tests__/e2e/e2e.conformance.spec.ts +206 -0
- package/__tests__/e2e/e2e.graphql-ws-server.ts +187 -0
- package/__tests__/e2e/e2e.graphql-ws.spec.ts +306 -0
- package/__tests__/e2e/e2e.react-subscriptions.spec.tsx +208 -0
- package/__tests__/features/adapter/adapter.browser.spec.ts +23 -5
- package/__tests__/features/adapter/adapter.document.spec.ts +17 -13
- package/__tests__/features/adapter/adapter.headers.spec.ts +65 -0
- package/__tests__/features/adapter/adapter.keys.spec.ts +235 -0
- package/__tests__/features/adapter/adapter.persisted-queries.spec.ts +207 -0
- package/__tests__/features/adapter/adapter.progress.spec.ts +39 -0
- package/__tests__/features/adapter/adapter.responses.spec.ts +162 -1
- package/__tests__/features/adapter/adapter.server.spec.ts +6 -6
- package/__tests__/features/adapter/adapter.types.spec.ts +121 -2
- package/__tests__/features/adapter/adapter.utils.spec.ts +4 -2
- package/__tests__/features/adapter/adapter.variables.spec.ts +3 -3
- package/__tests__/features/socket/socket.connection.spec.ts +892 -0
- package/__tests__/features/socket/socket.fuzz.spec.ts +329 -0
- package/__tests__/features/socket/socket.subscriptions.spec.ts +515 -0
- package/__tests__/features/socket/socket.types.spec.ts +160 -0
- package/__tests__/utils/controlled-websocket.ts +238 -0
- package/dist/adapter/adapter.constants.d.ts +5 -0
- package/dist/adapter/adapter.constants.d.ts.map +1 -1
- package/dist/adapter/adapter.types.d.ts +55 -2
- package/dist/adapter/adapter.types.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts +51 -4
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/adapter/http-adapter.fetch.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +958 -128
- package/dist/index.mjs.map +1 -1
- package/dist/socket/index.d.ts +5 -0
- package/dist/socket/index.d.ts.map +1 -0
- package/dist/socket/socket.constants.d.ts +44 -0
- package/dist/socket/socket.constants.d.ts.map +1 -0
- package/dist/socket/socket.subscriptions.d.ts +74 -0
- package/dist/socket/socket.subscriptions.d.ts.map +1 -0
- package/dist/socket/socket.types.d.ts +102 -0
- package/dist/socket/socket.types.d.ts.map +1 -0
- package/dist/socket/socket.utils.d.ts +80 -0
- package/dist/socket/socket.utils.d.ts.map +1 -0
- package/dist/socket/socket.websocket.d.ts +30 -0
- package/dist/socket/socket.websocket.d.ts.map +1 -0
- package/package.json +14 -9
- package/src/adapter/adapter.constants.ts +6 -0
- package/src/adapter/adapter.types.ts +69 -3
- package/src/adapter/adapter.utils.ts +196 -25
- package/src/adapter/http-adapter.fetch.ts +93 -43
- package/src/index.ts +1 -0
- package/src/socket/index.ts +4 -0
- package/src/socket/socket.constants.ts +59 -0
- package/src/socket/socket.subscriptions.ts +160 -0
- package/src/socket/socket.types.ts +118 -0
- package/src/socket/socket.utils.ts +150 -0
- package/src/socket/socket.websocket.ts +555 -0
- package/vite.config.ts +4 -0
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
|
-
import { Adapter, HttpMethods, Time, getErrorMessage, parseResponse, stringifyKey, stringifyQueryParams } from "@hyper-fetch/core";
|
|
1
|
+
import { Adapter, HttpMethods, Request, Time, getAdapterHeaders, getErrorMessage, parseResponse, stringifyKey, stringifyQueryParams } from "@hyper-fetch/core";
|
|
2
2
|
import { parse, print } from "graphql";
|
|
3
|
+
import { SocketAdapter, WebsocketReadyState, createReconnectingConnection, defaultShouldReconnect, getSocketError, getSocketUrl, getWebsocketConstructor } from "@hyper-fetch/sockets";
|
|
3
4
|
//#region src/adapter/adapter.constants.ts
|
|
4
5
|
var defaultTimeout = Time.SEC * 5;
|
|
6
|
+
/**
|
|
7
|
+
* GraphQL over HTTP media type first, so spec compliant servers answer with meaningful status codes,
|
|
8
|
+
* and JSON as the fallback for the others.
|
|
9
|
+
*/
|
|
10
|
+
var gqlAcceptHeader = "application/graphql-response+json, application/json;q=0.9";
|
|
5
11
|
var gqlExtra = {
|
|
6
12
|
headers: {},
|
|
7
13
|
extensions: {}
|
|
@@ -15,6 +21,23 @@ var GraphqlMethod = /* @__PURE__ */ function(GraphqlMethod) {
|
|
|
15
21
|
}({});
|
|
16
22
|
//#endregion
|
|
17
23
|
//#region src/adapter/adapter.utils.ts
|
|
24
|
+
/** Whether the request headers name the content type, also with an empty value that removes it */
|
|
25
|
+
var hasContentTypeHeader = (headers) => {
|
|
26
|
+
if (!headers) return false;
|
|
27
|
+
return (typeof Headers !== "undefined" && headers instanceof Headers ? [...headers.keys()] : (Array.isArray(headers) ? headers : Object.entries(headers)).map(([name]) => name)).some((name) => name.toLowerCase() === "content-type");
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* A POST body is always JSON (`query`, `operationName`, `variables`, `extensions`), also for an operation without
|
|
31
|
+
* variables, so it needs the JSON content type. A GET request has no body and sends the operation in the URL, so it
|
|
32
|
+
* gets none - the header would only trigger a CORS preflight. A content type given with the request always wins.
|
|
33
|
+
*/
|
|
34
|
+
var getGqlHeaders = (request) => {
|
|
35
|
+
const headers = { ...getAdapterHeaders(request) };
|
|
36
|
+
if (hasContentTypeHeader(request.headers)) return headers;
|
|
37
|
+
delete headers["Content-Type"];
|
|
38
|
+
if (request.method === GraphqlMethod.POST) headers["Content-Type"] = "application/json";
|
|
39
|
+
return headers;
|
|
40
|
+
};
|
|
18
41
|
var getDocumentOption = (request) => {
|
|
19
42
|
return request.requestOptions.document;
|
|
20
43
|
};
|
|
@@ -24,11 +47,16 @@ var getGqlDocument = (request) => {
|
|
|
24
47
|
return getDocumentOption(request) ?? request.endpoint;
|
|
25
48
|
};
|
|
26
49
|
/** Query string keys owned by the GraphQL over HTTP GET format - they win over the user query params */
|
|
27
|
-
var reservedQueryParams = [
|
|
50
|
+
var reservedQueryParams = new Set([
|
|
51
|
+
"query",
|
|
52
|
+
"operationName",
|
|
53
|
+
"variables",
|
|
54
|
+
"extensions"
|
|
55
|
+
]);
|
|
28
56
|
var isReservedQueryParam = (param) => {
|
|
29
57
|
const [rawKey] = param.split("=");
|
|
30
58
|
try {
|
|
31
|
-
return reservedQueryParams.
|
|
59
|
+
return reservedQueryParams.has(decodeURIComponent(rawKey).split("[")[0]);
|
|
32
60
|
} catch {
|
|
33
61
|
return false;
|
|
34
62
|
}
|
|
@@ -40,20 +68,31 @@ var joinQueryStrings = (...queryStrings) => {
|
|
|
40
68
|
const joined = queryStrings.map((queryString) => queryString.replace(/^\?/, "")).filter(Boolean).join("&");
|
|
41
69
|
return joined ? `?${joined}` : "";
|
|
42
70
|
};
|
|
43
|
-
|
|
71
|
+
/**
|
|
72
|
+
* Url and body of the request in the GraphQL over HTTP format.
|
|
73
|
+
* With `persisted`, the `persistedQuery` extension is sent, and the query only when `withQuery` is set.
|
|
74
|
+
*/
|
|
75
|
+
var getRequestValues = (request, queryParams = request.client.adapter.unstable_queryParamsMapper(request.queryParams), persisted) => {
|
|
44
76
|
const isPostRequest = request.method === HttpMethods.POST;
|
|
45
|
-
const
|
|
77
|
+
const document = getGqlDocument(request);
|
|
78
|
+
const query = !persisted || persisted.withQuery ? gqlEndpointMapper(document) : void 0;
|
|
79
|
+
const operationName = getGqlOperationName(document);
|
|
46
80
|
const variables = request.payload;
|
|
81
|
+
const extensions = persisted ? { persistedQuery: persisted.persistedQuery } : void 0;
|
|
47
82
|
const url = hasDocumentOption(request) ? `${request.client.url}${request.endpoint}` : request.client.url;
|
|
48
83
|
const queryString = stringifyQueryParams(queryParams);
|
|
49
84
|
return {
|
|
50
85
|
fullUrl: isPostRequest ? url + joinQueryStrings(queryString) : url + joinQueryStrings(stringifyQueryParams({
|
|
51
86
|
query,
|
|
52
|
-
|
|
87
|
+
operationName,
|
|
88
|
+
variables,
|
|
89
|
+
extensions
|
|
53
90
|
}), omitReservedQueryParams(queryString)),
|
|
54
91
|
payload: isPostRequest ? JSON.stringify({
|
|
55
92
|
query,
|
|
56
|
-
|
|
93
|
+
operationName,
|
|
94
|
+
variables,
|
|
95
|
+
extensions
|
|
57
96
|
}) : null
|
|
58
97
|
};
|
|
59
98
|
};
|
|
@@ -61,8 +100,27 @@ var gqlEndpointMapper = (endpoint) => {
|
|
|
61
100
|
if (typeof endpoint === "string") return endpoint;
|
|
62
101
|
return print(endpoint);
|
|
63
102
|
};
|
|
64
|
-
var
|
|
65
|
-
|
|
103
|
+
var findOperation = (ast) => {
|
|
104
|
+
return ast.definitions.find((def) => def.kind === "OperationDefinition");
|
|
105
|
+
};
|
|
106
|
+
var parseDocument = (document) => {
|
|
107
|
+
if (typeof document !== "string") return document;
|
|
108
|
+
try {
|
|
109
|
+
return parse(document);
|
|
110
|
+
} catch {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* Name of the first operation of the document, sent as `operationName`.
|
|
116
|
+
* Anonymous operations and documents that do not parse have none.
|
|
117
|
+
*/
|
|
118
|
+
var getGqlOperationName = (document) => {
|
|
119
|
+
const ast = parseDocument(document);
|
|
120
|
+
return ast ? findOperation(ast)?.name?.value : void 0;
|
|
121
|
+
};
|
|
122
|
+
var getOperationLabel = (ast) => {
|
|
123
|
+
const operationDefinition = findOperation(ast);
|
|
66
124
|
if (operationDefinition) {
|
|
67
125
|
if (operationDefinition.name?.value) return operationDefinition.name.value;
|
|
68
126
|
const selection = operationDefinition.selectionSet.selections[0];
|
|
@@ -70,14 +128,34 @@ var getOperationName = (ast) => {
|
|
|
70
128
|
if (selection?.kind === "InlineFragment" && selection.typeCondition) return selection.typeCondition.name.value;
|
|
71
129
|
}
|
|
72
130
|
};
|
|
131
|
+
/** Readable name of the document - the operation name or, for anonymous operations, the first selected field */
|
|
73
132
|
var gqlEndpointNameMapper = (endpoint) => {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
133
|
+
const ast = parseDocument(endpoint);
|
|
134
|
+
const name = ast ? getOperationLabel(ast) : void 0;
|
|
135
|
+
if (name) return name;
|
|
136
|
+
if (typeof endpoint !== "string") return "graphql-request";
|
|
137
|
+
const [fallbackName] = endpoint.replace(/(query|mutation|subscription)/, "").replaceAll(/[{}().,:]/g, " ").trim().split(" ");
|
|
138
|
+
return fallbackName || "graphql-request";
|
|
139
|
+
};
|
|
140
|
+
/** FNV-1a - a short and stable fingerprint of a text */
|
|
141
|
+
var hashText = (text) => {
|
|
142
|
+
let hash = 2166136261;
|
|
143
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
144
|
+
hash ^= text.charCodeAt(index);
|
|
145
|
+
hash = Math.imul(hash, 16777619);
|
|
146
|
+
}
|
|
147
|
+
return (hash >>> 0).toString(36);
|
|
148
|
+
};
|
|
149
|
+
/** Printing a DocumentNode is the costly part, and gql documents are created once, so their fingerprint is kept */
|
|
150
|
+
var documentNodeHashes = /* @__PURE__ */ new WeakMap();
|
|
151
|
+
/** Fingerprint of the document text sent as `query`. Documents with other selections get other fingerprints. */
|
|
152
|
+
var getDocumentHash = (document) => {
|
|
153
|
+
if (typeof document === "string") return hashText(document);
|
|
154
|
+
const known = documentNodeHashes.get(document);
|
|
155
|
+
if (known) return known;
|
|
156
|
+
const hash = hashText(print(document));
|
|
157
|
+
documentNodeHashes.set(document, hash);
|
|
158
|
+
return hash;
|
|
81
159
|
};
|
|
82
160
|
/**
|
|
83
161
|
* Name identifying the request in the cache, query and abort keys.
|
|
@@ -88,141 +166,893 @@ var gqlRequestNameMapper = (request) => {
|
|
|
88
166
|
return hasDocumentOption(request) ? `${name}${request.requestOptions.endpoint}` : name;
|
|
89
167
|
};
|
|
90
168
|
/**
|
|
91
|
-
* Cache and query key of a request. The variables are a part of it:
|
|
92
|
-
*
|
|
169
|
+
* Cache and query key of a request. The document fingerprint and the variables are a part of it: two documents with
|
|
170
|
+
* one operation name but other selections, or the same operation with other variables, are other queries - with their
|
|
171
|
+
* own cached data and their own place in the queue.
|
|
93
172
|
*/
|
|
94
173
|
var gqlRequestKeyMapper = (request) => {
|
|
95
|
-
const
|
|
174
|
+
const name = `${gqlRequestNameMapper(request)}@${getDocumentHash(getGqlDocument(request))}`;
|
|
175
|
+
const key = `${request.method}_${name}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
|
|
96
176
|
const variables = stringifyKey(request.payload);
|
|
97
177
|
return variables ? `${key}-${variables}` : key;
|
|
98
178
|
};
|
|
179
|
+
var escapeRegExp = (text) => text.replaceAll(/[$()*+.?[\\\]^{|}]/g, String.raw`\$&`);
|
|
180
|
+
/**
|
|
181
|
+
* Matches the cache keys of every request of a GraphQL operation - with any variables, params, query params and
|
|
182
|
+
* method. Pass it to `client.cache.invalidate()` after a mutation, so the active queries of the operation refetch, like
|
|
183
|
+
* `refetchQueries` in Apollo.
|
|
184
|
+
*
|
|
185
|
+
* - A document matches its requests on every url path of the `document` option.
|
|
186
|
+
* - A request matches the requests of its document on its own url path.
|
|
187
|
+
* - Documents with the same operation name but other selections are other operations, they do not match.
|
|
188
|
+
*
|
|
189
|
+
* @example
|
|
190
|
+
* ```ts
|
|
191
|
+
* await updateUser.send({ payload: { id: "1", name: "Ann" } });
|
|
192
|
+
* client.cache.invalidate(matchGqlOperation(GetUserDocument));
|
|
193
|
+
* ```
|
|
194
|
+
*/
|
|
195
|
+
var matchGqlOperation = (operation) => {
|
|
196
|
+
if (operation instanceof Request) {
|
|
197
|
+
const name = escapeRegExp(gqlRequestNameMapper(operation));
|
|
198
|
+
return new RegExp(`^[A-Z]+_${name}@${getDocumentHash(getGqlDocument(operation))}-`);
|
|
199
|
+
}
|
|
200
|
+
const name = escapeRegExp(gqlEndpointNameMapper(operation));
|
|
201
|
+
return new RegExp(`^[A-Z]+_${name}(?:/[^@]*)?@${getDocumentHash(operation)}-`);
|
|
202
|
+
};
|
|
203
|
+
/**
|
|
204
|
+
* SHA-256 hash of the query for automatic persisted queries, as lowercase hex.
|
|
205
|
+
* `null` when the runtime has no working Web Crypto - the full query is sent then.
|
|
206
|
+
*/
|
|
207
|
+
var getPersistedQueryHash = async (query) => {
|
|
208
|
+
const subtle = globalThis.crypto?.subtle;
|
|
209
|
+
if (!subtle) return null;
|
|
210
|
+
try {
|
|
211
|
+
const digest = await subtle.digest("SHA-256", new TextEncoder().encode(query));
|
|
212
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
213
|
+
} catch {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
/**
|
|
218
|
+
* How the server answered a hashed request it could not run: it does not know the hash yet (`"not-found"`), or it does
|
|
219
|
+
* not support persisted queries (`"not-supported"`). `null` for every other response. Servers report it by the message
|
|
220
|
+
* or by the error code.
|
|
221
|
+
*/
|
|
222
|
+
var getPersistedQueryMiss = (body) => {
|
|
223
|
+
const errors = Array.isArray(body?.errors) ? body.errors : [];
|
|
224
|
+
for (const error of errors) {
|
|
225
|
+
const { message, extensions } = error ?? {};
|
|
226
|
+
if (message === "PersistedQueryNotSupported" || extensions?.code === "PERSISTED_QUERY_NOT_SUPPORTED") return "not-supported";
|
|
227
|
+
if (message === "PersistedQueryNotFound" || extensions?.code === "PERSISTED_QUERY_NOT_FOUND") return "not-found";
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
};
|
|
99
231
|
//#endregion
|
|
100
232
|
//#region src/adapter/http-adapter.fetch.ts
|
|
101
|
-
var getGqlAdapter = () =>
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
if (timeoutMs > 0 && controller) timeoutId = setTimeout(() => {
|
|
124
|
-
timedOut = true;
|
|
125
|
-
unmountListener();
|
|
126
|
-
controller.abort();
|
|
127
|
-
}, timeoutMs);
|
|
128
|
-
onBeforeRequest();
|
|
129
|
-
onRequestStart();
|
|
130
|
-
try {
|
|
131
|
-
const init = {
|
|
132
|
-
method: request.method,
|
|
133
|
-
headers,
|
|
134
|
-
signal: controller?.signal,
|
|
135
|
-
...restOptions
|
|
136
|
-
};
|
|
137
|
-
if (payload) {
|
|
138
|
-
init.body = payload;
|
|
139
|
-
if (typeof payload === "string") {
|
|
140
|
-
const total = new Blob([payload]).size;
|
|
141
|
-
onRequestProgress({
|
|
142
|
-
total,
|
|
143
|
-
loaded: total
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
onRequestEnd();
|
|
148
|
-
const response = await fetch(fullUrl, init);
|
|
149
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
150
|
-
onResponseStart();
|
|
151
|
-
const responseHeaders = {};
|
|
152
|
-
response.headers.forEach((value, key) => {
|
|
153
|
-
responseHeaders[key] = value;
|
|
233
|
+
var getGqlAdapter = () => {
|
|
234
|
+
let persistedQueriesSupported = true;
|
|
235
|
+
return new Adapter({
|
|
236
|
+
name: "graphql",
|
|
237
|
+
defaultMethod: GraphqlMethod.POST,
|
|
238
|
+
defaultExtra: gqlExtra,
|
|
239
|
+
systemErrorStatus: 0,
|
|
240
|
+
systemErrorExtra: gqlExtra
|
|
241
|
+
}).onInitialize(({ client }) => {
|
|
242
|
+
client.setCacheKeyMapper(gqlRequestKeyMapper);
|
|
243
|
+
client.setQueryKeyMapper(gqlRequestKeyMapper);
|
|
244
|
+
client.setAbortKeyMapper((request) => {
|
|
245
|
+
return `${request.method}_${gqlRequestNameMapper(request)}-${request.cancelable}`;
|
|
246
|
+
});
|
|
247
|
+
}).setInternalErrorMapping((error) => [error]).setDevtoolsEndpointGetter((endpoint, requestOptions) => gqlEndpointNameMapper(requestOptions?.document ?? endpoint)).setEndpointMapper(gqlEndpointMapper).setHeaderMapper(getGqlHeaders).setQueryParamsMapper(stringifyQueryParams).setFetcher(async ({ request, queryParams, adapterOptions, headers, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, getAbortController, onResponseProgress, onResponseStart, onBeforeRequest, onRequestStart, onSuccess }) => {
|
|
248
|
+
const controller = getAbortController();
|
|
249
|
+
const { timeout: timeoutMs = defaultTimeout, errorPolicy = "none", persistedQueries = false, ...restOptions } = adapterOptions || {};
|
|
250
|
+
let timedOut = false;
|
|
251
|
+
let timeoutId;
|
|
252
|
+
const unmountListener = createAbortListener({
|
|
253
|
+
status: 0,
|
|
254
|
+
extra: gqlExtra
|
|
154
255
|
});
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
256
|
+
if (timeoutMs > 0 && controller) timeoutId = setTimeout(() => {
|
|
257
|
+
timedOut = true;
|
|
258
|
+
unmountListener();
|
|
259
|
+
controller.abort();
|
|
260
|
+
}, timeoutMs);
|
|
261
|
+
const sha256Hash = persistedQueries && persistedQueriesSupported ? await getPersistedQueryHash(gqlEndpointMapper(getGqlDocument(request))) : null;
|
|
262
|
+
const persistedQuery = sha256Hash ? {
|
|
263
|
+
version: 1,
|
|
264
|
+
sha256Hash
|
|
265
|
+
} : null;
|
|
266
|
+
const firstValues = getRequestValues(request, queryParams, persistedQuery ? {
|
|
267
|
+
persistedQuery,
|
|
268
|
+
withQuery: false
|
|
269
|
+
} : void 0);
|
|
270
|
+
const total = firstValues.payload ? new Blob([firstValues.payload]).size : 0;
|
|
271
|
+
onBeforeRequest();
|
|
272
|
+
onRequestStart(total ? {
|
|
273
|
+
total,
|
|
274
|
+
loaded: 0
|
|
275
|
+
} : void 0);
|
|
276
|
+
try {
|
|
277
|
+
const requestHeaders = headers;
|
|
278
|
+
const hasAcceptHeader = Object.keys(requestHeaders).some((key) => key.toLowerCase() === "accept");
|
|
279
|
+
const init = {
|
|
280
|
+
method: request.method,
|
|
281
|
+
headers: hasAcceptHeader ? requestHeaders : {
|
|
282
|
+
Accept: gqlAcceptHeader,
|
|
283
|
+
...requestHeaders
|
|
284
|
+
},
|
|
285
|
+
signal: controller?.signal,
|
|
286
|
+
...restOptions
|
|
287
|
+
};
|
|
288
|
+
const sendAttempt = (values) => {
|
|
289
|
+
return fetch(values.fullUrl, values.payload ? {
|
|
290
|
+
...init,
|
|
291
|
+
body: values.payload
|
|
292
|
+
} : init);
|
|
293
|
+
};
|
|
294
|
+
const clearTimer = () => {
|
|
295
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
296
|
+
};
|
|
297
|
+
/** Reads the body. Without `reportProgress` it reports the whole body at once, after reading it. */
|
|
298
|
+
const readBody = async (response, reportProgress) => {
|
|
299
|
+
if (!response.body || typeof response.body.getReader !== "function") return response.text();
|
|
300
|
+
const reader = response.body.getReader();
|
|
301
|
+
const contentLength = parseInt(response.headers.get("content-length") || "0", 10);
|
|
302
|
+
let receivedLength = 0;
|
|
303
|
+
const chunks = [];
|
|
304
|
+
while (true) {
|
|
305
|
+
const { done, value } = await reader.read();
|
|
306
|
+
if (done) break;
|
|
307
|
+
chunks.push(value);
|
|
308
|
+
receivedLength += value.length;
|
|
309
|
+
if (reportProgress) onResponseProgress({
|
|
310
|
+
total: contentLength || receivedLength,
|
|
311
|
+
loaded: receivedLength
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
if (!reportProgress) onResponseProgress({
|
|
315
|
+
total: receivedLength,
|
|
168
316
|
loaded: receivedLength
|
|
169
317
|
});
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
318
|
+
const allChunks = new Uint8Array(receivedLength);
|
|
319
|
+
let position = 0;
|
|
320
|
+
for (const chunk of chunks) {
|
|
321
|
+
allChunks.set(chunk, position);
|
|
322
|
+
position += chunk.length;
|
|
323
|
+
}
|
|
324
|
+
return new TextDecoder().decode(allChunks);
|
|
325
|
+
};
|
|
326
|
+
let response = await sendAttempt(firstValues);
|
|
327
|
+
onRequestEnd();
|
|
328
|
+
if (!persistedQuery) clearTimer();
|
|
329
|
+
onResponseStart();
|
|
330
|
+
let body = await readBody(response, !persistedQuery);
|
|
331
|
+
const miss = persistedQuery ? getPersistedQueryMiss(parseResponse(body)) : null;
|
|
332
|
+
if (persistedQuery && miss) {
|
|
333
|
+
if (miss === "not-supported") persistedQueriesSupported = false;
|
|
334
|
+
response = await sendAttempt(getRequestValues(request, queryParams, miss === "not-found" ? {
|
|
335
|
+
persistedQuery,
|
|
336
|
+
withQuery: true
|
|
337
|
+
} : void 0));
|
|
338
|
+
clearTimer();
|
|
339
|
+
body = await readBody(response, true);
|
|
340
|
+
} else clearTimer();
|
|
341
|
+
const responseHeaders = {};
|
|
342
|
+
response.headers.forEach((value, key) => {
|
|
343
|
+
responseHeaders[key] = value;
|
|
344
|
+
});
|
|
345
|
+
onResponseEnd();
|
|
346
|
+
unmountListener();
|
|
347
|
+
const { status } = response;
|
|
348
|
+
const parsed = parseResponse(body);
|
|
349
|
+
const data = parsed?.data ?? null;
|
|
350
|
+
const errors = Array.isArray(parsed?.errors) && parsed.errors.length === 0 ? null : parsed?.errors || null;
|
|
351
|
+
const extensions = parsed?.extensions || {};
|
|
352
|
+
const extra = errors ? {
|
|
190
353
|
headers: responseHeaders,
|
|
191
|
-
extensions
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
else onSuccess({
|
|
195
|
-
data,
|
|
196
|
-
error: errors,
|
|
197
|
-
status,
|
|
198
|
-
extra: {
|
|
354
|
+
extensions,
|
|
355
|
+
errors
|
|
356
|
+
} : {
|
|
199
357
|
headers: responseHeaders,
|
|
200
358
|
extensions
|
|
359
|
+
};
|
|
360
|
+
if (status > 399 || status === 0 || errors && !(errorPolicy === "all" && data !== null)) onError({
|
|
361
|
+
error: errors || [getErrorMessage()],
|
|
362
|
+
status,
|
|
363
|
+
extra
|
|
364
|
+
});
|
|
365
|
+
else onSuccess({
|
|
366
|
+
data,
|
|
367
|
+
status,
|
|
368
|
+
extra
|
|
369
|
+
});
|
|
370
|
+
} catch (error) {
|
|
371
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
372
|
+
unmountListener();
|
|
373
|
+
if (controller?.signal?.aborted) {
|
|
374
|
+
if (timedOut) onTimeoutError({
|
|
375
|
+
status: 0,
|
|
376
|
+
extra: gqlExtra
|
|
377
|
+
});
|
|
378
|
+
return;
|
|
201
379
|
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
205
|
-
unmountListener();
|
|
206
|
-
if (controller?.signal?.aborted) {
|
|
207
|
-
if (timedOut) onTimeoutError({
|
|
380
|
+
onError({
|
|
381
|
+
error: [error],
|
|
208
382
|
status: 0,
|
|
209
383
|
extra: gqlExtra
|
|
210
384
|
});
|
|
211
|
-
return;
|
|
212
385
|
}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
status: 0,
|
|
216
|
-
extra: gqlExtra
|
|
217
|
-
});
|
|
218
|
-
}
|
|
219
|
-
});
|
|
386
|
+
});
|
|
387
|
+
};
|
|
220
388
|
//#endregion
|
|
221
389
|
//#region src/adapter/adapter.ts
|
|
222
390
|
var GraphqlAdapter = () => {
|
|
223
391
|
return getGqlAdapter();
|
|
224
392
|
};
|
|
225
393
|
//#endregion
|
|
226
|
-
|
|
394
|
+
//#region src/socket/socket.constants.ts
|
|
395
|
+
/** Subprotocol of GraphQL over WebSocket, the protocol of `graphql-ws` */
|
|
396
|
+
var GRAPHQL_TRANSPORT_WS_PROTOCOL = "graphql-transport-ws";
|
|
397
|
+
/** Message types of the `graphql-transport-ws` protocol */
|
|
398
|
+
var GraphqlWsMessageType = {
|
|
399
|
+
CONNECTION_INIT: "connection_init",
|
|
400
|
+
CONNECTION_ACK: "connection_ack",
|
|
401
|
+
PING: "ping",
|
|
402
|
+
PONG: "pong",
|
|
403
|
+
SUBSCRIBE: "subscribe",
|
|
404
|
+
NEXT: "next",
|
|
405
|
+
ERROR: "error",
|
|
406
|
+
COMPLETE: "complete"
|
|
407
|
+
};
|
|
408
|
+
/** Close codes of the `graphql-transport-ws` protocol */
|
|
409
|
+
var GraphqlWsCloseCode = {
|
|
410
|
+
INTERNAL_SERVER_ERROR: 4500,
|
|
411
|
+
INTERNAL_CLIENT_ERROR: 4005,
|
|
412
|
+
BAD_REQUEST: 4400,
|
|
413
|
+
BAD_RESPONSE: 4004,
|
|
414
|
+
UNAUTHORIZED: 4401,
|
|
415
|
+
FORBIDDEN: 4403,
|
|
416
|
+
SUBPROTOCOL_NOT_ACCEPTABLE: 4406,
|
|
417
|
+
CONNECTION_INITIALISATION_TIMEOUT: 4408,
|
|
418
|
+
CONNECTION_ACKNOWLEDGEMENT_TIMEOUT: 4504,
|
|
419
|
+
SUBSCRIBER_ALREADY_EXISTS: 4409,
|
|
420
|
+
TOO_MANY_INITIALISATION_REQUESTS: 4429
|
|
421
|
+
};
|
|
422
|
+
/**
|
|
423
|
+
* Close codes that a retry can't fix - the same ones the `graphql-ws` client gives up on. Forbidden (4403) and the
|
|
424
|
+
* timeouts (4408, 4504) are retried, as access may be granted and the server may answer in time on the next attempt.
|
|
425
|
+
*/
|
|
426
|
+
var fatalGraphqlWsCloseCodes = new Set([
|
|
427
|
+
GraphqlWsCloseCode.INTERNAL_SERVER_ERROR,
|
|
428
|
+
GraphqlWsCloseCode.INTERNAL_CLIENT_ERROR,
|
|
429
|
+
GraphqlWsCloseCode.BAD_REQUEST,
|
|
430
|
+
GraphqlWsCloseCode.BAD_RESPONSE,
|
|
431
|
+
GraphqlWsCloseCode.UNAUTHORIZED,
|
|
432
|
+
GraphqlWsCloseCode.SUBPROTOCOL_NOT_ACCEPTABLE,
|
|
433
|
+
GraphqlWsCloseCode.SUBSCRIBER_ALREADY_EXISTS,
|
|
434
|
+
GraphqlWsCloseCode.TOO_MANY_INITIALISATION_REQUESTS
|
|
435
|
+
]);
|
|
436
|
+
/**
|
|
437
|
+
* Close codes of the WebSocket standard (1001-1999) that a retry can fix: going away, no status, abnormal closure,
|
|
438
|
+
* service restart, try again later and bad gateway. The other ones report a broken client or server, e.g. 1002
|
|
439
|
+
* (protocol error) or 1003 (unsupported data). A normal closure (1000) stays closed, as with every socket adapter.
|
|
440
|
+
*/
|
|
441
|
+
var retriedStandardCloseCodes = new Set([
|
|
442
|
+
1001,
|
|
443
|
+
1005,
|
|
444
|
+
1006,
|
|
445
|
+
1012,
|
|
446
|
+
1013,
|
|
447
|
+
1014
|
|
448
|
+
]);
|
|
449
|
+
/** Defaults of the keep-alive */
|
|
450
|
+
var defaultKeepAlive = {
|
|
451
|
+
intervalMs: Time.SEC * 10,
|
|
452
|
+
pongTimeoutMs: Time.SEC * 5
|
|
453
|
+
};
|
|
454
|
+
//#endregion
|
|
455
|
+
//#region src/socket/socket.utils.ts
|
|
456
|
+
/** The object check of the `graphql-ws` client, so both accept the same messages */
|
|
457
|
+
var isRecord = (value) => {
|
|
458
|
+
return typeof value === "object" && value !== null;
|
|
459
|
+
};
|
|
460
|
+
var toError = (value) => {
|
|
461
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
462
|
+
};
|
|
463
|
+
var isFormattedErrors = (value) => {
|
|
464
|
+
return Array.isArray(value) && value.length > 0 && value.every((error) => isRecord(error) && "message" in error);
|
|
465
|
+
};
|
|
466
|
+
var hasId = (message) => {
|
|
467
|
+
return typeof message.id === "string" && message.id.length > 0;
|
|
468
|
+
};
|
|
469
|
+
/**
|
|
470
|
+
* Reads a frame of the server. Throws when it breaks the protocol - the same checks the `graphql-ws` client makes, so
|
|
471
|
+
* a server that works with it works with the adapter.
|
|
472
|
+
*/
|
|
473
|
+
var parseServerMessage = (data) => {
|
|
474
|
+
if (typeof data !== "string") throw new TypeError("Expected a text frame");
|
|
475
|
+
const message = JSON.parse(data);
|
|
476
|
+
if (!isRecord(message) || typeof message.type !== "string") throw new TypeError("Expected a message object with a string 'type'");
|
|
477
|
+
switch (message.type) {
|
|
478
|
+
case GraphqlWsMessageType.CONNECTION_ACK:
|
|
479
|
+
case GraphqlWsMessageType.PING:
|
|
480
|
+
case GraphqlWsMessageType.PONG:
|
|
481
|
+
if (message.payload !== void 0 && message.payload !== null && !isRecord(message.payload)) throw new TypeError(`"${message.type}" expects the payload to be an object or nullish`);
|
|
482
|
+
return message;
|
|
483
|
+
case GraphqlWsMessageType.NEXT:
|
|
484
|
+
if (!hasId(message) || !isRecord(message.payload)) throw new TypeError(`"next" expects a non-empty string 'id' and an object payload`);
|
|
485
|
+
return message;
|
|
486
|
+
case GraphqlWsMessageType.ERROR:
|
|
487
|
+
if (!hasId(message) || !isFormattedErrors(message.payload)) throw new TypeError(`"error" expects a non-empty string 'id' and an array of GraphQL errors as the payload`);
|
|
488
|
+
return message;
|
|
489
|
+
case GraphqlWsMessageType.COMPLETE:
|
|
490
|
+
if (!hasId(message)) throw new TypeError(`"complete" expects a non-empty string 'id'`);
|
|
491
|
+
return message;
|
|
492
|
+
default: throw new TypeError(`Unexpected message type "${message.type}"`);
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
/** Reported to `onError` when the server breaks the protocol - the connection is closed with 4004 */
|
|
496
|
+
var getBadResponseError = (cause) => {
|
|
497
|
+
return new Error("Received a malformed GraphQL over WebSocket message", { cause });
|
|
498
|
+
};
|
|
499
|
+
/**
|
|
500
|
+
* The close reason may hold at most 123 bytes. Longer reasons are cut by the `graphql-ws` client the same way:
|
|
501
|
+
* replaced with a short generic one.
|
|
502
|
+
*/
|
|
503
|
+
var limitCloseReason = (reason, fallback) => {
|
|
504
|
+
return new TextEncoder().encode(reason).byteLength <= 123 ? reason : fallback;
|
|
505
|
+
};
|
|
506
|
+
/**
|
|
507
|
+
* The default `shouldReconnect` of the GraphQL WebSocket adapter. It gives up on the close codes a retry can't fix -
|
|
508
|
+
* bad requests, unauthorized, a missing subprotocol, protocol errors and the like, the same ones the `graphql-ws` client
|
|
509
|
+
* gives up on - and on a normal closure (1000), as every socket adapter does. Everything else is retried. The socket's
|
|
510
|
+
* own `shouldReconnect` replaces it, so call this one from yours to keep these rules.
|
|
511
|
+
*
|
|
512
|
+
* @example
|
|
513
|
+
* const socket = new Socket({
|
|
514
|
+
* url,
|
|
515
|
+
* adapter: GraphqlWsAdapter(),
|
|
516
|
+
* // Retry after a normal closure too
|
|
517
|
+
* shouldReconnect: (loss) => loss.code === 1000 || shouldReconnectGraphqlWs(loss),
|
|
518
|
+
* });
|
|
519
|
+
*/
|
|
520
|
+
var shouldReconnectGraphqlWs = (loss) => {
|
|
521
|
+
const { code } = loss;
|
|
522
|
+
if (code === void 0) return true;
|
|
523
|
+
if (fatalGraphqlWsCloseCodes.has(code)) return false;
|
|
524
|
+
if (code > 1e3 && code <= 1999 && !retriedStandardCloseCodes.has(code)) return false;
|
|
525
|
+
return defaultShouldReconnect(loss);
|
|
526
|
+
};
|
|
527
|
+
/**
|
|
528
|
+
* Error of a GraphQL subscription, reported to the `socket.onError` callbacks and to the `onEnd` of its listeners.
|
|
529
|
+
* The server ended the subscription with the `error` message - its validation or its source failed. `errors` holds what
|
|
530
|
+
* it sent.
|
|
531
|
+
*
|
|
532
|
+
* Errors of a single event do not end the subscription and come with the event in `extra.errors`.
|
|
533
|
+
*
|
|
534
|
+
* @example
|
|
535
|
+
* socket.onError(({ error }) => {
|
|
536
|
+
* if (error instanceof GraphqlSubscriptionError && error.errors[0].extensions?.code === "UNAUTHENTICATED") {
|
|
537
|
+
* logout();
|
|
538
|
+
* }
|
|
539
|
+
* });
|
|
540
|
+
*/
|
|
541
|
+
var GraphqlSubscriptionError = class extends Error {
|
|
542
|
+
/** Errors sent by the server with the `error` message */
|
|
543
|
+
errors;
|
|
544
|
+
/** Topic of the failed subscription */
|
|
545
|
+
topic;
|
|
546
|
+
/** Variables of the failed subscription */
|
|
547
|
+
payload;
|
|
548
|
+
constructor({ errors, topic, payload }) {
|
|
549
|
+
super(errors.map((error) => error.message).join("\n"));
|
|
550
|
+
this.name = "GraphqlSubscriptionError";
|
|
551
|
+
this.errors = errors;
|
|
552
|
+
this.topic = topic;
|
|
553
|
+
this.payload = payload;
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
//#endregion
|
|
557
|
+
//#region src/socket/socket.subscriptions.ts
|
|
558
|
+
/**
|
|
559
|
+
* Keeps one server subscription per topic, document and variables. Callbacks with the same ones share it, the first
|
|
560
|
+
* one starts it and the last one to leave stops it. The adapter only moves the subscriptions over its transport.
|
|
561
|
+
*/
|
|
562
|
+
var createGraphqlSubscriptions = ({ bindings: { onListen, onEvent, onError, onListenerStart, onListenerEnd }, onStart, onStop }) => {
|
|
563
|
+
const subscriptions = /* @__PURE__ */ new Map();
|
|
564
|
+
const leave = (subscription, callback) => {
|
|
565
|
+
if (!subscription.callbacks.delete(callback) || subscription.callbacks.size > 0) return;
|
|
566
|
+
if (subscriptions.get(subscription.key) === subscription) {
|
|
567
|
+
subscriptions.delete(subscription.key);
|
|
568
|
+
onStop(subscription);
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
const listen = (listener, callback) => {
|
|
572
|
+
const document = listener.options?.document ?? listener.topic;
|
|
573
|
+
let query;
|
|
574
|
+
let key;
|
|
575
|
+
try {
|
|
576
|
+
query = gqlEndpointMapper(document);
|
|
577
|
+
key = `${listener.topic}\n${query}\n${JSON.stringify(listener.payload) ?? ""}`;
|
|
578
|
+
} catch (error) {
|
|
579
|
+
onError({ error: toError(error) });
|
|
580
|
+
return onListen({
|
|
581
|
+
listener,
|
|
582
|
+
callback
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
const existing = subscriptions.get(key);
|
|
586
|
+
const subscription = existing ?? {
|
|
587
|
+
key,
|
|
588
|
+
topic: listener.topic,
|
|
589
|
+
query,
|
|
590
|
+
operationName: getGqlOperationName(document),
|
|
591
|
+
payload: listener.payload,
|
|
592
|
+
callbacks: /* @__PURE__ */ new Set(),
|
|
593
|
+
started: false
|
|
594
|
+
};
|
|
595
|
+
subscription.callbacks.add(callback);
|
|
596
|
+
const removeListener = onListen({
|
|
597
|
+
listener,
|
|
598
|
+
callback,
|
|
599
|
+
onUnmount: () => leave(subscription, callback)
|
|
600
|
+
});
|
|
601
|
+
if (!existing) {
|
|
602
|
+
subscriptions.set(key, subscription);
|
|
603
|
+
onStart(subscription);
|
|
604
|
+
} else if (existing.started) onListenerStart({
|
|
605
|
+
topic: subscription.topic,
|
|
606
|
+
callbacks: new Set([callback])
|
|
607
|
+
});
|
|
608
|
+
return removeListener;
|
|
609
|
+
};
|
|
610
|
+
/** Delivers an event to the callbacks of the subscription only */
|
|
611
|
+
const deliver = (subscription, { data, errors, extensions }) => {
|
|
612
|
+
const extra = {
|
|
613
|
+
errors,
|
|
614
|
+
extensions: extensions ?? {},
|
|
615
|
+
payload: subscription.payload
|
|
616
|
+
};
|
|
617
|
+
try {
|
|
618
|
+
onEvent({
|
|
619
|
+
topic: subscription.topic,
|
|
620
|
+
data,
|
|
621
|
+
extra,
|
|
622
|
+
callbacks: subscription.callbacks
|
|
623
|
+
});
|
|
624
|
+
} catch (error) {
|
|
625
|
+
onError({ error: toError(error) });
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
/** The subscription was sent over an acknowledged connection - after the first start and after every restart */
|
|
629
|
+
const confirm = (subscription) => {
|
|
630
|
+
subscription.started = true;
|
|
631
|
+
onListenerStart({
|
|
632
|
+
topic: subscription.topic,
|
|
633
|
+
callbacks: subscription.callbacks
|
|
634
|
+
});
|
|
635
|
+
};
|
|
636
|
+
/** The connection of the subscription dropped - it has to be sent again */
|
|
637
|
+
const unconfirm = (subscription) => {
|
|
638
|
+
subscription.started = false;
|
|
639
|
+
};
|
|
640
|
+
/**
|
|
641
|
+
* The server ended the subscription - it completed (`error: null`) or failed. Its listeners deliver what is pending
|
|
642
|
+
* and unsubscribe, and a later `listen()` with the same variables starts a new subscription from scratch.
|
|
643
|
+
*/
|
|
644
|
+
const end = (subscription, error) => {
|
|
645
|
+
subscriptions.delete(subscription.key);
|
|
646
|
+
unconfirm(subscription);
|
|
647
|
+
onListenerEnd({
|
|
648
|
+
topic: subscription.topic,
|
|
649
|
+
callbacks: subscription.callbacks,
|
|
650
|
+
error
|
|
651
|
+
});
|
|
652
|
+
};
|
|
653
|
+
/** Subscriptions with at least one callback, the ones to start when the connection is acknowledged */
|
|
654
|
+
const getAll = () => [...subscriptions.values()];
|
|
655
|
+
return {
|
|
656
|
+
listen,
|
|
657
|
+
deliver,
|
|
658
|
+
confirm,
|
|
659
|
+
unconfirm,
|
|
660
|
+
end,
|
|
661
|
+
getAll
|
|
662
|
+
};
|
|
663
|
+
};
|
|
664
|
+
//#endregion
|
|
665
|
+
//#region src/socket/socket.websocket.ts
|
|
666
|
+
/** Explains a lost connection - the protocol codes (4000+) carry the server's reason */
|
|
667
|
+
var getCloseError = (event) => {
|
|
668
|
+
if (event.code >= 4e3) return /* @__PURE__ */ new Error(`The server closed the connection with ${event.code}: ${event.reason || "no reason given"}`);
|
|
669
|
+
return new Error(getSocketError(event));
|
|
670
|
+
};
|
|
671
|
+
/**
|
|
672
|
+
* Socket adapter for GraphQL subscriptions over WebSocket. It speaks `graphql-transport-ws`, the protocol of the
|
|
673
|
+
* `graphql-ws` library - supported by Apollo Server, GraphQL Yoga, Mercurius, Hot Chocolate, Hasura and most others.
|
|
674
|
+
*
|
|
675
|
+
* - The connection counts as open once the server acknowledged `connection_init`, so the socket's
|
|
676
|
+
* `connectionTimeout` covers the whole handshake. `connectionParams` are sent with it, a function runs on every
|
|
677
|
+
* connection attempt.
|
|
678
|
+
* - Every document with one set of variables is one server subscription, shared by the listeners with those
|
|
679
|
+
* variables. Subscriptions started before the connection is acknowledged wait for it, and after a reconnect they are
|
|
680
|
+
* sent again.
|
|
681
|
+
* - The server's `ping` is answered, and `keepAlive` pings a quiet connection to notice when it died.
|
|
682
|
+
* - Reconnecting follows the socket's reconnection options. Close codes a retry can't fix (4400, 4401, 4409...) stop
|
|
683
|
+
* it - see {@link shouldReconnectGraphqlWs}.
|
|
684
|
+
* - With `lazy`, the connection is open only while there are subscriptions.
|
|
685
|
+
*
|
|
686
|
+
* Queries and mutations are sent with the `GraphqlAdapter` - `emit` throws.
|
|
687
|
+
*
|
|
688
|
+
* @example
|
|
689
|
+
* const socket = new Socket({
|
|
690
|
+
* url: "ws://localhost:4000/graphql",
|
|
691
|
+
* adapter: GraphqlWsAdapter(),
|
|
692
|
+
* adapterOptions: { connectionParams: () => ({ token: getToken() }) },
|
|
693
|
+
* });
|
|
694
|
+
*
|
|
695
|
+
* const onMessage = socket.createListener()({ topic: "OnMessage", options: { document: OnMessageDocument } });
|
|
696
|
+
* onMessage.listen(({ data, extra }) => {}, { payload: { room: "general" } });
|
|
697
|
+
*/
|
|
698
|
+
var GraphqlWsAdapter = () => new SocketAdapter({
|
|
699
|
+
name: "graphql-ws",
|
|
700
|
+
confirmsSubscriptions: true
|
|
701
|
+
}).setQueryParamsMapper(stringifyQueryParams).setConnector((bindings) => {
|
|
702
|
+
const { adapter, getQueryParams, onConnectFailed, onError } = bindings;
|
|
703
|
+
let websocket;
|
|
704
|
+
let acknowledged = false;
|
|
705
|
+
let options = adapter.adapterOptions;
|
|
706
|
+
let loseCurrent;
|
|
707
|
+
let protocolClose;
|
|
708
|
+
let pingTimer;
|
|
709
|
+
let pongTimer;
|
|
710
|
+
let lazyCloseTimer;
|
|
711
|
+
let lazyIdle = true;
|
|
712
|
+
let lastId = 0;
|
|
713
|
+
const running = /* @__PURE__ */ new Map();
|
|
714
|
+
const ids = /* @__PURE__ */ new Map();
|
|
715
|
+
const subscriptions = createGraphqlSubscriptions({
|
|
716
|
+
bindings,
|
|
717
|
+
onStart: (subscription) => startSubscription(subscription),
|
|
718
|
+
onStop: (subscription) => stopSubscription(subscription)
|
|
719
|
+
});
|
|
720
|
+
const isLazy = () => !!adapter.adapterOptions?.lazy;
|
|
721
|
+
/** Sends a message. Returns the error instead of throwing, so callers decide how to report it. */
|
|
722
|
+
const send = (message) => {
|
|
723
|
+
try {
|
|
724
|
+
websocket?.send(JSON.stringify(message));
|
|
725
|
+
return null;
|
|
726
|
+
} catch (error) {
|
|
727
|
+
return toError(error);
|
|
728
|
+
}
|
|
729
|
+
};
|
|
730
|
+
const sendOrReport = (message) => {
|
|
731
|
+
const error = send(message);
|
|
732
|
+
if (error) onError({ error });
|
|
733
|
+
return !error;
|
|
734
|
+
};
|
|
735
|
+
/**
|
|
736
|
+
* Ends the current connection because of the protocol, e.g. a malformed message. The transport is closed with
|
|
737
|
+
* the protocol `code`, so the server learns why, and the engine decides about the next attempt with it.
|
|
738
|
+
*/
|
|
739
|
+
const failConnection = (attempt, close, error) => {
|
|
740
|
+
protocolClose = close;
|
|
741
|
+
attempt.lost({
|
|
742
|
+
code: close.code,
|
|
743
|
+
reason: close.reason,
|
|
744
|
+
error
|
|
745
|
+
});
|
|
746
|
+
onError({ error });
|
|
747
|
+
};
|
|
748
|
+
/**
|
|
749
|
+
* Lazy connection
|
|
750
|
+
*/
|
|
751
|
+
const cancelLazyClose = () => {
|
|
752
|
+
clearTimeout(lazyCloseTimer);
|
|
753
|
+
lazyCloseTimer = void 0;
|
|
754
|
+
};
|
|
755
|
+
/** With `lazy`, the first subscription opens the connection */
|
|
756
|
+
const connectLazily = () => {
|
|
757
|
+
cancelLazyClose();
|
|
758
|
+
if (!isLazy() || !lazyIdle) return;
|
|
759
|
+
lazyIdle = false;
|
|
760
|
+
connection.connect();
|
|
761
|
+
};
|
|
762
|
+
/** With `lazy`, the connection closes once no subscription needs it anymore */
|
|
763
|
+
const closeLazily = () => {
|
|
764
|
+
if (!isLazy() || subscriptions.getAll().length > 0) return;
|
|
765
|
+
cancelLazyClose();
|
|
766
|
+
const close = () => {
|
|
767
|
+
lazyCloseTimer = void 0;
|
|
768
|
+
lazyIdle = true;
|
|
769
|
+
connection.disconnect();
|
|
770
|
+
};
|
|
771
|
+
const timeout = adapter.adapterOptions?.lazyCloseTimeout ?? 0;
|
|
772
|
+
if (timeout > 0) lazyCloseTimer = setTimeout(close, timeout);
|
|
773
|
+
else close();
|
|
774
|
+
};
|
|
775
|
+
/**
|
|
776
|
+
* Subscriptions
|
|
777
|
+
*/
|
|
778
|
+
const startSubscription = (subscription) => {
|
|
779
|
+
if (!websocket || !acknowledged) {
|
|
780
|
+
connectLazily();
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
cancelLazyClose();
|
|
784
|
+
lastId += 1;
|
|
785
|
+
const id = String(lastId);
|
|
786
|
+
if (sendOrReport({
|
|
787
|
+
id,
|
|
788
|
+
type: GraphqlWsMessageType.SUBSCRIBE,
|
|
789
|
+
payload: {
|
|
790
|
+
query: subscription.query,
|
|
791
|
+
operationName: subscription.operationName,
|
|
792
|
+
variables: subscription.payload
|
|
793
|
+
}
|
|
794
|
+
})) {
|
|
795
|
+
running.set(id, subscription);
|
|
796
|
+
ids.set(subscription, id);
|
|
797
|
+
subscriptions.confirm(subscription);
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
/** The server forgets the subscription - after `complete`, an error or when the connection closes */
|
|
801
|
+
const forget = (subscription) => {
|
|
802
|
+
const id = ids.get(subscription);
|
|
803
|
+
if (id !== void 0) running.delete(id);
|
|
804
|
+
ids.delete(subscription);
|
|
805
|
+
};
|
|
806
|
+
/** The connection is gone, and the server stopped every subscription of it - they are sent again on reconnect */
|
|
807
|
+
const forgetAll = () => {
|
|
808
|
+
running.forEach(subscriptions.unconfirm);
|
|
809
|
+
running.clear();
|
|
810
|
+
ids.clear();
|
|
811
|
+
};
|
|
812
|
+
const stopSubscription = (subscription) => {
|
|
813
|
+
const id = ids.get(subscription);
|
|
814
|
+
forget(subscription);
|
|
815
|
+
if (id !== void 0) sendOrReport({
|
|
816
|
+
id,
|
|
817
|
+
type: GraphqlWsMessageType.COMPLETE
|
|
818
|
+
});
|
|
819
|
+
closeLazily();
|
|
820
|
+
};
|
|
821
|
+
/** The server ended the subscription - with `complete` (`error: null`) or the `error` message */
|
|
822
|
+
const endSubscription = (subscription, error) => {
|
|
823
|
+
forget(subscription);
|
|
824
|
+
if (error) onError({ error });
|
|
825
|
+
subscriptions.end(subscription, error);
|
|
826
|
+
closeLazily();
|
|
827
|
+
};
|
|
828
|
+
/**
|
|
829
|
+
* Messages
|
|
830
|
+
*/
|
|
831
|
+
const onAcknowledged = (attempt) => {
|
|
832
|
+
acknowledged = true;
|
|
833
|
+
attempt.ready();
|
|
834
|
+
if (!attempt.isCurrent()) return;
|
|
835
|
+
subscriptions.getAll().forEach(startSubscription);
|
|
836
|
+
onHeartbeat();
|
|
837
|
+
};
|
|
838
|
+
const onSubscriptionMessage = (message) => {
|
|
839
|
+
const subscription = running.get(message.id);
|
|
840
|
+
if (!subscription) return;
|
|
841
|
+
switch (message.type) {
|
|
842
|
+
case GraphqlWsMessageType.NEXT: {
|
|
843
|
+
const { data, errors, extensions } = message.payload;
|
|
844
|
+
subscriptions.deliver(subscription, {
|
|
845
|
+
data: data ?? null,
|
|
846
|
+
errors: Array.isArray(errors) ? errors : void 0,
|
|
847
|
+
extensions
|
|
848
|
+
});
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
case GraphqlWsMessageType.ERROR:
|
|
852
|
+
endSubscription(subscription, new GraphqlSubscriptionError({
|
|
853
|
+
errors: message.payload,
|
|
854
|
+
topic: subscription.topic,
|
|
855
|
+
payload: subscription.payload
|
|
856
|
+
}));
|
|
857
|
+
return;
|
|
858
|
+
default: endSubscription(subscription, null);
|
|
859
|
+
}
|
|
860
|
+
};
|
|
861
|
+
const onMessage = (event, attempt) => {
|
|
862
|
+
onHeartbeat();
|
|
863
|
+
let message;
|
|
864
|
+
try {
|
|
865
|
+
message = parseServerMessage(event.data);
|
|
866
|
+
} catch (error) {
|
|
867
|
+
const reason = limitCloseReason(toError(error).message, "Bad response");
|
|
868
|
+
failConnection(attempt, {
|
|
869
|
+
code: GraphqlWsCloseCode.BAD_RESPONSE,
|
|
870
|
+
reason
|
|
871
|
+
}, getBadResponseError(error));
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
switch (message.type) {
|
|
875
|
+
case GraphqlWsMessageType.PING:
|
|
876
|
+
sendOrReport(message.payload ? {
|
|
877
|
+
type: GraphqlWsMessageType.PONG,
|
|
878
|
+
payload: message.payload
|
|
879
|
+
} : { type: GraphqlWsMessageType.PONG });
|
|
880
|
+
return;
|
|
881
|
+
case GraphqlWsMessageType.PONG: return;
|
|
882
|
+
case GraphqlWsMessageType.CONNECTION_ACK:
|
|
883
|
+
if (!acknowledged) onAcknowledged(attempt);
|
|
884
|
+
return;
|
|
885
|
+
default:
|
|
886
|
+
if (!acknowledged) {
|
|
887
|
+
const reason = `First message cannot be of type ${message.type}`;
|
|
888
|
+
failConnection(attempt, {
|
|
889
|
+
code: GraphqlWsCloseCode.BAD_RESPONSE,
|
|
890
|
+
reason
|
|
891
|
+
}, getBadResponseError(new Error(reason)));
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
onSubscriptionMessage(message);
|
|
895
|
+
}
|
|
896
|
+
};
|
|
897
|
+
/**
|
|
898
|
+
* Connection
|
|
899
|
+
*/
|
|
900
|
+
/** Sends `connection_init` with the connection params of the attempt */
|
|
901
|
+
const initialize = async (attempt, transport) => {
|
|
902
|
+
const connectionParams = options?.connectionParams;
|
|
903
|
+
let payload;
|
|
904
|
+
try {
|
|
905
|
+
payload = typeof connectionParams === "function" ? await connectionParams() : connectionParams;
|
|
906
|
+
} catch (error) {
|
|
907
|
+
if (attempt.isCurrent()) {
|
|
908
|
+
const cause = toError(error);
|
|
909
|
+
const reason = limitCloseReason(cause.message, "Internal client error");
|
|
910
|
+
failConnection(attempt, {
|
|
911
|
+
code: GraphqlWsCloseCode.INTERNAL_CLIENT_ERROR,
|
|
912
|
+
reason
|
|
913
|
+
}, new Error("Could not get the connection params", { cause }));
|
|
914
|
+
}
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
917
|
+
if (!attempt.isCurrent() || transport.readyState !== WebsocketReadyState.OPEN) return;
|
|
918
|
+
sendOrReport(payload ? {
|
|
919
|
+
type: GraphqlWsMessageType.CONNECTION_INIT,
|
|
920
|
+
payload
|
|
921
|
+
} : { type: GraphqlWsMessageType.CONNECTION_INIT });
|
|
922
|
+
};
|
|
923
|
+
/** Creates the transport, reporting a failed attempt when the environment or the connection details are invalid */
|
|
924
|
+
const createWebsocket = (url) => {
|
|
925
|
+
try {
|
|
926
|
+
const WebsocketConstructor = getWebsocketConstructor(options);
|
|
927
|
+
if (!WebsocketConstructor) {
|
|
928
|
+
onConnectFailed({ error: /* @__PURE__ */ new Error("WebSocket is not available in this environment") });
|
|
929
|
+
return null;
|
|
930
|
+
}
|
|
931
|
+
return new WebsocketConstructor(url, GRAPHQL_TRANSPORT_WS_PROTOCOL);
|
|
932
|
+
} catch (error) {
|
|
933
|
+
onConnectFailed({ error: toError(error) });
|
|
934
|
+
return null;
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
/**
|
|
938
|
+
* Closes a detached transport. The server stops every subscription of a closed connection on its own, so they
|
|
939
|
+
* are sent again on the next one. Resolves on the close - or on an error, as a transport that fails while
|
|
940
|
+
* closing may report only `error` (Node.js 22).
|
|
941
|
+
*/
|
|
942
|
+
const closeWebsocket = (transport) => {
|
|
943
|
+
const { code, reason } = protocolClose ?? {
|
|
944
|
+
code: 1e3,
|
|
945
|
+
reason: "Normal Closure"
|
|
946
|
+
};
|
|
947
|
+
websocket = void 0;
|
|
948
|
+
acknowledged = false;
|
|
949
|
+
loseCurrent = void 0;
|
|
950
|
+
protocolClose = void 0;
|
|
951
|
+
clearTimers();
|
|
952
|
+
forgetAll();
|
|
953
|
+
if (transport.readyState === WebsocketReadyState.CLOSED) return Promise.resolve();
|
|
954
|
+
return new Promise((resolve) => {
|
|
955
|
+
transport.addEventListener("close", () => resolve(), { once: true });
|
|
956
|
+
transport.addEventListener("error", () => resolve(), { once: true });
|
|
957
|
+
try {
|
|
958
|
+
transport.close(code, reason);
|
|
959
|
+
} catch {
|
|
960
|
+
resolve();
|
|
961
|
+
}
|
|
962
|
+
});
|
|
963
|
+
};
|
|
964
|
+
const connection = createReconnectingConnection({
|
|
965
|
+
bindings,
|
|
966
|
+
autoConnect: !adapter.adapterOptions?.lazy && (adapter.adapterOptions?.autoConnect ?? true),
|
|
967
|
+
shouldReconnect: shouldReconnectGraphqlWs,
|
|
968
|
+
open: (attempt) => {
|
|
969
|
+
options = attempt.connection.adapterOptions;
|
|
970
|
+
const transport = createWebsocket(getSocketUrl(attempt.connection.url, getQueryParams(attempt.connection.queryParams)));
|
|
971
|
+
if (!transport) return null;
|
|
972
|
+
websocket = transport;
|
|
973
|
+
acknowledged = false;
|
|
974
|
+
loseCurrent = attempt.lost;
|
|
975
|
+
/** The transport is gone - report it and let the engine decide about the next attempt */
|
|
976
|
+
const onTransportClosed = (event) => {
|
|
977
|
+
attempt.lost({
|
|
978
|
+
code: event.code,
|
|
979
|
+
reason: event.reason || void 0
|
|
980
|
+
});
|
|
981
|
+
onError({ error: getCloseError(event) });
|
|
982
|
+
};
|
|
983
|
+
transport.addEventListener("open", () => {
|
|
984
|
+
if (attempt.isCurrent()) initialize(attempt, transport);
|
|
985
|
+
});
|
|
986
|
+
transport.addEventListener("close", (event) => {
|
|
987
|
+
if (attempt.isCurrent()) onTransportClosed(event);
|
|
988
|
+
});
|
|
989
|
+
transport.addEventListener("error", () => {
|
|
990
|
+
if (!attempt.isCurrent() || transport.readyState !== WebsocketReadyState.CONNECTING) return;
|
|
991
|
+
onTransportClosed(Object.assign(new Event("close"), { code: 1006 }));
|
|
992
|
+
});
|
|
993
|
+
transport.addEventListener("message", (event) => {
|
|
994
|
+
if (attempt.isCurrent()) onMessage(event, attempt);
|
|
995
|
+
});
|
|
996
|
+
return { close: () => closeWebsocket(transport) };
|
|
997
|
+
}
|
|
998
|
+
});
|
|
999
|
+
/**
|
|
1000
|
+
* Keep-alive
|
|
1001
|
+
*/
|
|
1002
|
+
const clearTimers = () => {
|
|
1003
|
+
clearTimeout(pingTimer);
|
|
1004
|
+
clearTimeout(pongTimer);
|
|
1005
|
+
};
|
|
1006
|
+
const onHeartbeat = () => {
|
|
1007
|
+
const { enabled = false, ...keepAlive } = options?.keepAlive ?? {};
|
|
1008
|
+
const { intervalMs, pongTimeoutMs } = {
|
|
1009
|
+
...defaultKeepAlive,
|
|
1010
|
+
...keepAlive
|
|
1011
|
+
};
|
|
1012
|
+
if (!acknowledged || !enabled) return;
|
|
1013
|
+
clearTimers();
|
|
1014
|
+
pingTimer = setTimeout(() => {
|
|
1015
|
+
sendOrReport({ type: GraphqlWsMessageType.PING });
|
|
1016
|
+
pongTimer = setTimeout(() => {
|
|
1017
|
+
onHeartbeatTimeout();
|
|
1018
|
+
}, pongTimeoutMs);
|
|
1019
|
+
}, intervalMs);
|
|
1020
|
+
};
|
|
1021
|
+
/**
|
|
1022
|
+
* The server did not answer the ping - the connection is dead. Its closing handshake may never finish, so the
|
|
1023
|
+
* engine detaches the transport right away instead of waiting for its `close` event.
|
|
1024
|
+
*/
|
|
1025
|
+
const onHeartbeatTimeout = () => {
|
|
1026
|
+
const error = /* @__PURE__ */ new Error("Keep-alive timeout - the server did not answer the ping in time");
|
|
1027
|
+
loseCurrent?.({ error });
|
|
1028
|
+
onError({ error });
|
|
1029
|
+
};
|
|
1030
|
+
const emit = () => {
|
|
1031
|
+
throw new Error("Cannot emit events with the GraphQL WebSocket adapter, it supports subscriptions only");
|
|
1032
|
+
};
|
|
1033
|
+
return {
|
|
1034
|
+
connect: () => {
|
|
1035
|
+
lazyIdle = false;
|
|
1036
|
+
return connection.connect();
|
|
1037
|
+
},
|
|
1038
|
+
reconnect: () => {
|
|
1039
|
+
lazyIdle = false;
|
|
1040
|
+
return connection.reconnect();
|
|
1041
|
+
},
|
|
1042
|
+
disconnect: () => {
|
|
1043
|
+
cancelLazyClose();
|
|
1044
|
+
return connection.disconnect();
|
|
1045
|
+
},
|
|
1046
|
+
listen: subscriptions.listen,
|
|
1047
|
+
emit,
|
|
1048
|
+
dispose: () => {
|
|
1049
|
+
connection.dispose();
|
|
1050
|
+
clearTimers();
|
|
1051
|
+
cancelLazyClose();
|
|
1052
|
+
}
|
|
1053
|
+
};
|
|
1054
|
+
});
|
|
1055
|
+
//#endregion
|
|
1056
|
+
export { GRAPHQL_TRANSPORT_WS_PROTOCOL, GraphqlAdapter, GraphqlMethod, GraphqlSubscriptionError, GraphqlWsAdapter, GraphqlWsCloseCode, defaultTimeout, getGqlAdapter, getGqlDocument, getGqlHeaders, getGqlOperationName, getPersistedQueryHash, getPersistedQueryMiss, getRequestValues, gqlAcceptHeader, gqlEndpointMapper, gqlEndpointNameMapper, gqlExtra, gqlRequestKeyMapper, gqlRequestNameMapper, matchGqlOperation, shouldReconnectGraphqlWs };
|
|
227
1057
|
|
|
228
1058
|
//# sourceMappingURL=index.mjs.map
|