@hyper-fetch/graphql 7.5.2 → 8.0.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 (48) hide show
  1. package/{.eslintrc.json → .eslintrc copy.json } +1 -1
  2. package/.eslintrc.cjs +12 -0
  3. package/__tests__/constants/mutations.constants.ts +15 -0
  4. package/__tests__/constants/queries.constants.ts +24 -0
  5. package/__tests__/e2e/e2e.graphql-server.ts +135 -0
  6. package/__tests__/e2e/e2e.graphql.spec.ts +486 -0
  7. package/__tests__/features/adapter/adapter.browser.spec.ts +259 -0
  8. package/__tests__/features/adapter/adapter.server.spec.ts +234 -0
  9. package/__tests__/features/adapter/adapter.utils.spec.ts +86 -0
  10. package/__tests__/request-module.d.ts +12 -0
  11. package/__tests__/shared/callbacks.shared.ts +11 -0
  12. package/__tests__/shared/index.ts +2 -0
  13. package/__tests__/shared/progress.shared.ts +40 -0
  14. package/__tests__/tsconfig.json +23 -0
  15. package/__tests__/vitest.setup.ts +10 -0
  16. package/dist/adapter/adapter.constants.d.ts +4 -0
  17. package/dist/adapter/adapter.constants.d.ts.map +1 -0
  18. package/dist/adapter/adapter.d.ts +3 -0
  19. package/dist/adapter/adapter.d.ts.map +1 -0
  20. package/dist/adapter/adapter.types.d.ts +24 -0
  21. package/dist/adapter/adapter.types.d.ts.map +1 -0
  22. package/dist/adapter/adapter.utils.d.ts +9 -0
  23. package/dist/adapter/adapter.utils.d.ts.map +1 -0
  24. package/dist/adapter/http-adapter.fetch.d.ts +3 -0
  25. package/dist/adapter/http-adapter.fetch.d.ts.map +1 -0
  26. package/dist/adapter/index.d.ts +6 -0
  27. package/dist/adapter/index.d.ts.map +1 -0
  28. package/dist/index.d.ts +2 -34
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.mjs +183 -0
  31. package/dist/index.mjs.map +1 -0
  32. package/package.json +10 -25
  33. package/project.json +4 -0
  34. package/src/adapter/adapter.constants.ts +1 -1
  35. package/src/adapter/adapter.ts +3 -8
  36. package/src/adapter/adapter.types.ts +7 -3
  37. package/src/adapter/adapter.utils.ts +8 -3
  38. package/src/adapter/http-adapter.fetch.ts +186 -0
  39. package/src/adapter/index.ts +1 -0
  40. package/tsconfig.base.json +2 -6
  41. package/tsconfig.json +2 -6
  42. package/vite.config.ts +45 -0
  43. package/dist/browser/index.js +0 -191
  44. package/dist/browser/index.js.map +0 -7
  45. package/dist/index.js +0 -330
  46. package/dist/index.js.map +0 -7
  47. package/src/adapter/http-adapter.browser.ts +0 -148
  48. package/src/adapter/http-adapter.server.ts +0 -148
package/dist/index.js DELETED
@@ -1,330 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var __async = (__this, __arguments, generator) => {
30
- return new Promise((resolve, reject) => {
31
- var fulfilled = (value) => {
32
- try {
33
- step(generator.next(value));
34
- } catch (e) {
35
- reject(e);
36
- }
37
- };
38
- var rejected = (value) => {
39
- try {
40
- step(generator.throw(value));
41
- } catch (e) {
42
- reject(e);
43
- }
44
- };
45
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
46
- step((generator = generator.apply(__this, __arguments)).next());
47
- });
48
- };
49
-
50
- // src/index.ts
51
- var index_exports = {};
52
- __export(index_exports, {
53
- GraphqlAdapter: () => GraphqlAdapter,
54
- GraphqlMethod: () => GraphqlMethod,
55
- defaultTimeout: () => defaultTimeout,
56
- getRequestValues: () => getRequestValues,
57
- gqlEndpointMapper: () => gqlEndpointMapper,
58
- gqlEndpointNameMapper: () => gqlEndpointNameMapper,
59
- gqlExtra: () => gqlExtra
60
- });
61
- module.exports = __toCommonJS(index_exports);
62
-
63
- // src/adapter/http-adapter.browser.ts
64
- var import_core = require("@hyper-fetch/core");
65
- var getGqlAdapter = () => new import_core.Adapter({
66
- name: "graphql-browser",
67
- defaultMethod: "POST" /* POST */,
68
- defaultExtra: gqlExtra,
69
- systemErrorStatus: 0,
70
- systemErrorExtra: gqlExtra
71
- }).onInitialize(({ client }) => {
72
- client.setCacheKeyMapper((request) => {
73
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${(0, import_core.stringifyKey)(request.params)}-${(0, import_core.stringifyKey)(request.queryParams)}`;
74
- });
75
- client.setQueryKeyMapper((request) => {
76
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${(0, import_core.stringifyKey)(request.params)}-${(0, import_core.stringifyKey)(request.queryParams)}`;
77
- });
78
- client.setAbortKeyMapper((request) => {
79
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;
80
- });
81
- }).setInternalErrorMapping((error) => [error]).setDevtoolsEndpointGetter(gqlEndpointNameMapper).setEndpointMapper(gqlEndpointMapper).setFetcher(
82
- (_0) => __async(null, [_0], function* ({
83
- request,
84
- adapterOptions,
85
- headers,
86
- onError,
87
- onResponseEnd,
88
- onTimeoutError,
89
- onRequestEnd,
90
- createAbortListener,
91
- onResponseProgress,
92
- onRequestProgress,
93
- onResponseStart,
94
- onBeforeRequest,
95
- onRequestStart,
96
- onSuccess
97
- }) {
98
- const { fullUrl, payload } = getRequestValues(request);
99
- const xhr = new XMLHttpRequest();
100
- xhr.timeout = defaultTimeout;
101
- const onAbort = () => xhr.abort();
102
- if (adapterOptions) {
103
- Object.entries(adapterOptions).forEach(([name, value]) => {
104
- xhr[name] = value;
105
- });
106
- }
107
- xhr.open(request.method, fullUrl, true);
108
- Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));
109
- const unmountListener = createAbortListener({ status: 0, extra: gqlExtra, onAbort });
110
- xhr.upload.onprogress = onRequestProgress;
111
- xhr.onloadstart = () => {
112
- onRequestEnd();
113
- onResponseStart();
114
- };
115
- xhr.onprogress = onResponseProgress;
116
- xhr.onloadend = () => {
117
- onResponseEnd();
118
- unmountListener();
119
- };
120
- xhr.ontimeout = () => onTimeoutError({ status: 0, extra: gqlExtra });
121
- xhr.onreadystatechange = (e) => {
122
- var _a;
123
- const event = e;
124
- const finishedState = 4;
125
- if (event.target && event.target.readyState === finishedState) {
126
- const { status } = event.target;
127
- const response = (0, import_core.parseResponse)(event.target.response);
128
- const data = (_a = response.data) != null ? _a : null;
129
- const errors = (response == null ? void 0 : response.errors) || null;
130
- const extensions = (response == null ? void 0 : response.extensions) || {};
131
- const failure = (response == null ? void 0 : response.errors) || status > 399 || status === 0;
132
- const responseHeaders = (0, import_core.getResponseHeaders)(xhr.getAllResponseHeaders());
133
- if (failure) {
134
- const error = errors || [(0, import_core.getErrorMessage)()];
135
- onError({ error, status, extra: { headers: responseHeaders, extensions } });
136
- } else {
137
- onSuccess({
138
- data,
139
- error: errors,
140
- status,
141
- extra: { headers: responseHeaders, extensions }
142
- });
143
- }
144
- }
145
- };
146
- onBeforeRequest();
147
- onRequestStart();
148
- xhr.send(payload);
149
- })
150
- );
151
-
152
- // src/adapter/http-adapter.server.ts
153
- var import_core2 = require("@hyper-fetch/core");
154
- var import_http = __toESM(require("http"));
155
- var import_https = __toESM(require("https"));
156
- var getGqlAdapter2 = () => new import_core2.Adapter({
157
- name: "graphql-server",
158
- defaultMethod: "POST" /* POST */,
159
- defaultExtra: gqlExtra,
160
- systemErrorStatus: 0,
161
- systemErrorExtra: gqlExtra
162
- }).onInitialize(({ client }) => {
163
- client.setCacheKeyMapper((request) => {
164
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${JSON.stringify(request.params)}-${JSON.stringify(request.queryParams)}`;
165
- });
166
- client.setQueryKeyMapper((request) => {
167
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${JSON.stringify(request.params)}-${JSON.stringify(request.queryParams)}`;
168
- });
169
- client.setAbortKeyMapper((request) => {
170
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;
171
- });
172
- }).setInternalErrorMapping((error) => [error]).setDevtoolsEndpointGetter(gqlEndpointNameMapper).setEndpointMapper(gqlEndpointMapper).setFetcher(
173
- (_0) => __async(null, [_0], function* ({
174
- request,
175
- adapterOptions,
176
- headers,
177
- onError,
178
- onResponseEnd,
179
- onTimeoutError,
180
- onRequestEnd,
181
- createAbortListener,
182
- getAbortController,
183
- onResponseProgress,
184
- onResponseStart,
185
- onBeforeRequest,
186
- onRequestStart,
187
- onSuccess
188
- }) {
189
- var _a;
190
- const { fullUrl, payload } = getRequestValues(request);
191
- const httpClient = request.client.url.includes("https://") ? import_https.default : import_http.default;
192
- const options = {
193
- method: request.method,
194
- headers,
195
- timeout: defaultTimeout,
196
- signal: (_a = getAbortController()) == null ? void 0 : _a.signal
197
- };
198
- Object.entries(adapterOptions || {}).forEach(([name, value]) => {
199
- options[name] = value;
200
- });
201
- onBeforeRequest();
202
- const unmountListener = createAbortListener({
203
- status: 0,
204
- extra: gqlExtra
205
- });
206
- const httpRequest = httpClient.request(fullUrl, options, (response) => {
207
- response.setEncoding("utf8");
208
- let chunks = "";
209
- const totalDownloadBytes = Number(response.headers["content-length"]);
210
- let downloadedBytes = 0;
211
- onRequestStart();
212
- response.on("data", (chunk) => {
213
- if (!chunks) {
214
- onRequestEnd();
215
- onResponseStart();
216
- }
217
- downloadedBytes += chunk.length;
218
- chunks += chunk;
219
- onResponseProgress({ total: totalDownloadBytes, loaded: downloadedBytes });
220
- });
221
- response.on("end", () => {
222
- const { statusCode = 0 } = response;
223
- const success = String(statusCode).startsWith("2") || String(statusCode).startsWith("3");
224
- if (success) {
225
- const { data, errors, extensions } = (0, import_core2.parseResponse)(chunks);
226
- onSuccess({
227
- data: data != null ? data : null,
228
- error: errors,
229
- status: statusCode,
230
- extra: { headers: response.headers, extensions: extensions != null ? extensions : {} }
231
- });
232
- } else {
233
- const result = (0, import_core2.parseErrorResponse)(chunks);
234
- const error = "errors" in result ? result.errors : null;
235
- const extensions = "extensions" in result ? result.extensions : {};
236
- onError({
237
- error: error != null ? error : [(0, import_core2.getErrorMessage)()],
238
- status: statusCode,
239
- extra: { headers: response.headers, extensions }
240
- });
241
- }
242
- unmountListener();
243
- onResponseEnd();
244
- });
245
- });
246
- httpRequest.on("timeout", () => onTimeoutError({ status: 0, extra: gqlExtra }));
247
- httpRequest.on("error", (error) => onError({ error, status: 0, extra: gqlExtra }));
248
- if (payload) {
249
- httpRequest.write(payload);
250
- }
251
- httpRequest.end();
252
- })
253
- );
254
-
255
- // src/adapter/adapter.ts
256
- var GraphqlAdapter = () => {
257
- if (typeof XMLHttpRequest !== "undefined") {
258
- return getGqlAdapter();
259
- }
260
- return getGqlAdapter2();
261
- };
262
-
263
- // src/adapter/adapter.types.ts
264
- var GraphqlMethod = /* @__PURE__ */ ((GraphqlMethod2) => {
265
- GraphqlMethod2["POST"] = "POST";
266
- GraphqlMethod2["GET"] = "GET";
267
- return GraphqlMethod2;
268
- })(GraphqlMethod || {});
269
-
270
- // src/adapter/adapter.utils.ts
271
- var import_core3 = require("@hyper-fetch/core");
272
- var import_graphql = require("graphql");
273
- var getRequestValues = (request) => {
274
- const isPostRequest = request.method === import_core3.HttpMethods.POST;
275
- const query = request.endpoint;
276
- const variables = request.payload;
277
- const fullUrl = isPostRequest ? request.client.url : request.client.url + (0, import_core3.stringifyQueryParams)({ query, variables });
278
- const payload = isPostRequest ? JSON.stringify({
279
- query,
280
- variables
281
- }) : null;
282
- return { fullUrl, payload };
283
- };
284
- var gqlEndpointMapper = (endpoint) => {
285
- if (typeof endpoint === "string") {
286
- return endpoint;
287
- }
288
- return (0, import_graphql.print)(endpoint);
289
- };
290
- var gqlEndpointNameMapper = (endpoint) => {
291
- var _a;
292
- try {
293
- const ast = (0, import_graphql.parse)(endpoint);
294
- const operationDefinition = ast.definitions.find(
295
- (def) => def.kind === "OperationDefinition"
296
- );
297
- if (operationDefinition) {
298
- if ((_a = operationDefinition.name) == null ? void 0 : _a.value) {
299
- return operationDefinition.name.value;
300
- }
301
- const selection = operationDefinition.selectionSet.selections[0];
302
- if ((selection == null ? void 0 : selection.kind) === "Field") {
303
- return selection.name.value;
304
- }
305
- }
306
- } catch (error) {
307
- }
308
- const clearedQuery = endpoint.replace(/(query|mutation|subscription)/, "").replace(/[{}().,:]/g, " ").trim();
309
- const [name] = clearedQuery.split(" ");
310
- return name || "graphql-request";
311
- };
312
-
313
- // src/adapter/adapter.constants.ts
314
- var import_core4 = require("@hyper-fetch/core");
315
- var defaultTimeout = import_core4.Time.SEC * 5;
316
- var gqlExtra = {
317
- headers: {},
318
- extensions: {}
319
- };
320
- // Annotate the CommonJS export names for ESM import in node:
321
- 0 && (module.exports = {
322
- GraphqlAdapter,
323
- GraphqlMethod,
324
- defaultTimeout,
325
- getRequestValues,
326
- gqlEndpointMapper,
327
- gqlEndpointNameMapper,
328
- gqlExtra
329
- });
330
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/index.ts", "../src/adapter/http-adapter.browser.ts", "../src/adapter/http-adapter.server.ts", "../src/adapter/adapter.ts", "../src/adapter/adapter.types.ts", "../src/adapter/adapter.utils.ts", "../src/adapter/adapter.constants.ts"],
4
- "sourcesContent": ["// rollup client entry point\n\nexport * from \"./adapter\";\n", "import {\n getResponseHeaders,\n parseResponse,\n getErrorMessage,\n Adapter,\n QueryParamsType,\n stringifyKey,\n} from \"@hyper-fetch/core\";\n\nimport {\n gqlExtra,\n GraphqlAdapterType,\n defaultTimeout,\n getRequestValues,\n GraphqlMethod,\n GraphQlExtraType,\n GraphQlEndpointType,\n gqlEndpointMapper,\n gqlEndpointNameMapper,\n} from \"adapter\";\n\nexport const getGqlAdapter = (): GraphqlAdapterType =>\n new Adapter<\n Partial<XMLHttpRequest>,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n undefined,\n GraphQlEndpointType\n >({\n name: \"graphql-browser\",\n defaultMethod: GraphqlMethod.POST,\n defaultExtra: gqlExtra,\n systemErrorStatus: 0,\n systemErrorExtra: gqlExtra,\n })\n .onInitialize(({ client }) => {\n client.setCacheKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n });\n client.setQueryKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n });\n client.setAbortKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;\n });\n })\n .setInternalErrorMapping((error) => [error])\n .setDevtoolsEndpointGetter(gqlEndpointNameMapper)\n .setEndpointMapper(gqlEndpointMapper)\n .setFetcher(\n async ({\n request,\n adapterOptions,\n headers,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n onResponseProgress,\n onRequestProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onSuccess,\n }) => {\n const { fullUrl, payload } = getRequestValues(request);\n\n const xhr = new XMLHttpRequest();\n xhr.timeout = defaultTimeout;\n\n const onAbort = () => xhr.abort();\n\n // Inject xhr options\n if (adapterOptions) {\n Object.entries(adapterOptions).forEach(([name, value]) => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n xhr[name] = value;\n });\n }\n\n // Open connection\n xhr.open(request.method, fullUrl, true);\n\n // Set Headers\n Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value as string));\n\n // Listen to abort signal\n const unmountListener = createAbortListener({ status: 0, extra: gqlExtra, onAbort });\n\n // Request handlers\n xhr.upload.onprogress = onRequestProgress;\n\n // Response handlers\n xhr.onloadstart = (): void => {\n onRequestEnd();\n onResponseStart();\n };\n\n xhr.onprogress = onResponseProgress;\n\n xhr.onloadend = () => {\n onResponseEnd();\n unmountListener();\n };\n\n /* istanbul ignore next */\n xhr.ontimeout = () => onTimeoutError({ status: 0, extra: gqlExtra });\n\n // Data handler\n xhr.onreadystatechange = (e: Event) => {\n const event = e as unknown as ProgressEvent<XMLHttpRequest>;\n const finishedState = 4;\n\n if (event.target && event.target.readyState === finishedState) {\n const { status } = event.target;\n const response = parseResponse(event.target.response);\n const data = response.data ?? null;\n const errors = response?.errors || null;\n const extensions = response?.extensions || {};\n const failure = response?.errors || status > 399 || status === 0;\n const responseHeaders = getResponseHeaders(xhr.getAllResponseHeaders());\n\n if (failure) {\n const error = errors || [getErrorMessage()];\n // delay to finish after onabort/ontimeout\n onError({ error, status, extra: { headers: responseHeaders, extensions } });\n } else {\n onSuccess({\n data,\n error: errors,\n status,\n extra: { headers: responseHeaders, extensions },\n });\n }\n }\n };\n\n // Start request\n onBeforeRequest();\n onRequestStart();\n\n xhr.send(payload);\n },\n );\n", "import { Adapter, getErrorMessage, parseErrorResponse, parseResponse, QueryParamsType } from \"@hyper-fetch/core\";\nimport http, { OutgoingHttpHeaders } from \"http\";\nimport https from \"https\";\n\nimport {\n gqlExtra,\n defaultTimeout,\n GraphqlAdapterType,\n getRequestValues,\n GraphQlExtraType,\n GraphqlMethod,\n GraphQlEndpointType,\n gqlEndpointMapper,\n gqlEndpointNameMapper,\n} from \"adapter\";\n\nexport const getGqlAdapter = (): GraphqlAdapterType =>\n new Adapter<\n Partial<XMLHttpRequest>,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n undefined,\n GraphQlEndpointType\n >({\n name: \"graphql-server\",\n defaultMethod: GraphqlMethod.POST,\n defaultExtra: gqlExtra,\n systemErrorStatus: 0,\n systemErrorExtra: gqlExtra,\n })\n .onInitialize(({ client }) => {\n client.setCacheKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${JSON.stringify(request.params)}-${JSON.stringify(request.queryParams)}`;\n });\n client.setQueryKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${JSON.stringify(request.params)}-${JSON.stringify(request.queryParams)}`;\n });\n client.setAbortKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;\n });\n })\n .setInternalErrorMapping((error) => [error])\n .setDevtoolsEndpointGetter(gqlEndpointNameMapper)\n .setEndpointMapper(gqlEndpointMapper)\n .setFetcher(\n async ({\n request,\n adapterOptions,\n headers,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n getAbortController,\n onResponseProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onSuccess,\n }) => {\n const { fullUrl, payload } = getRequestValues(request);\n\n const httpClient = request.client.url.includes(\"https://\") ? https : http;\n const options = {\n method: request.method,\n headers: headers as OutgoingHttpHeaders,\n timeout: defaultTimeout,\n signal: getAbortController()?.signal,\n } satisfies https.RequestOptions;\n\n Object.entries(adapterOptions || {}).forEach(([name, value]) => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n options[name] = value;\n });\n\n onBeforeRequest();\n\n const unmountListener = createAbortListener({\n status: 0,\n extra: gqlExtra,\n });\n\n const httpRequest = httpClient.request(fullUrl, options, (response) => {\n response.setEncoding(\"utf8\");\n\n let chunks = \"\";\n const totalDownloadBytes = Number(response.headers[\"content-length\"]);\n let downloadedBytes = 0;\n\n onRequestStart();\n\n response.on(\"data\", (chunk) => {\n /* istanbul ignore next */\n if (!chunks) {\n onRequestEnd();\n onResponseStart();\n }\n downloadedBytes += chunk.length;\n chunks += chunk;\n onResponseProgress({ total: totalDownloadBytes, loaded: downloadedBytes });\n });\n\n response.on(\"end\", () => {\n /* istanbul ignore next */\n const { statusCode = 0 } = response;\n const success = String(statusCode).startsWith(\"2\") || String(statusCode).startsWith(\"3\");\n\n if (success) {\n const { data, errors, extensions } = parseResponse(chunks);\n onSuccess({\n data: data ?? null,\n error: errors,\n status: statusCode,\n extra: { headers: response.headers as Record<string, string>, extensions: extensions ?? {} },\n });\n } else {\n // delay to finish after onabort/ontimeout\n const result = parseErrorResponse(chunks);\n /* istanbul ignore next */\n const error = \"errors\" in result ? result.errors : null;\n /* istanbul ignore next */\n const extensions = \"extensions\" in result ? result.extensions : {};\n\n onError({\n error: error ?? [getErrorMessage()],\n status: statusCode,\n extra: { headers: response.headers as Record<string, string>, extensions },\n });\n }\n\n unmountListener();\n onResponseEnd();\n });\n });\n\n /* istanbul ignore next */\n httpRequest.on(\"timeout\", () => onTimeoutError({ status: 0, extra: gqlExtra }));\n httpRequest.on(\"error\", (error) => onError({ error, status: 0, extra: gqlExtra }));\n if (payload) {\n httpRequest.write(payload);\n }\n httpRequest.end();\n },\n );\n", "import * as browser from \"@browser-adapter\";\nimport * as server from \"@server-adapter\";\n\nimport { GraphqlAdapterType } from \"./adapter.types\";\n\nexport const GraphqlAdapter = (): GraphqlAdapterType => {\n if (typeof XMLHttpRequest !== \"undefined\") {\n return browser.getGqlAdapter();\n }\n return server.getGqlAdapter();\n};\n", "import { Adapter, EmptyTypes, QueryParamsType } from \"@hyper-fetch/core\";\nimport { DocumentNode } from \"graphql/language/ast\";\n\nexport enum GraphqlMethod {\n POST = \"POST\",\n GET = \"GET\",\n}\n\nexport type GraphQlExtraType = { headers: HeadersInit; extensions: Record<string, any> };\n\nexport type GraphQlEndpointType = string | DocumentNode;\n\nexport type GraphqlAdapterType = Adapter<\n Partial<XMLHttpRequest>,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n undefined,\n GraphQlEndpointType,\n (endpoint: GraphQlEndpointType) => string\n>;\n\n// Extract\n\ntype GqlParamType = boolean | string | number | Record<string, any> | EmptyTypes;\n\nexport type ExtractGqlRouteParams<T extends string> = string extends T\n ? EmptyTypes\n : T extends `${string}query ${infer Parameters} {${infer QueryRest}`\n ? Parameters extends `${string}$${infer Param},${infer Rest}`\n ? GqlParameter<Param, Rest> &\n // eslint-disable-next-line @typescript-eslint/ban-types\n (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n : Parameters extends `${string}$${infer Param})${infer Rest}`\n ? GqlParameter<Param, Rest> &\n // eslint-disable-next-line @typescript-eslint/ban-types\n (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n : EmptyTypes\n : T extends `${string}$${infer Parameters},${infer Rest}`\n ? GqlParameter<Parameters, Rest>\n : T extends `${string}$${infer Parameters})${infer Rest}`\n ? GqlParameter<Parameters, Rest>\n : EmptyTypes;\n\nexport type GqlParameter<T extends string, Rest extends string> = T extends `${infer Param}:${string}!`\n ? { [k in Param]: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n ? // eslint-disable-next-line @typescript-eslint/ban-types\n {}\n : ExtractGqlRouteParams<Rest>)\n : T extends `${infer Param}:${string}`\n ? { [k in Param]?: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n ? // eslint-disable-next-line @typescript-eslint/ban-types\n {}\n : ExtractGqlRouteParams<Rest>)\n : EmptyTypes;\n", "import { RequestInstance, HttpMethods, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport { print, parse, OperationDefinitionNode } from \"graphql\";\n\nimport { GraphQlEndpointType } from \"adapter\";\n\nexport const getRequestValues = <R extends RequestInstance>(request: R) => {\n const isPostRequest = request.method === HttpMethods.POST;\n\n const query = request.endpoint;\n const variables = request.payload;\n\n const fullUrl = isPostRequest ? request.client.url : request.client.url + stringifyQueryParams({ query, variables });\n\n const payload = isPostRequest\n ? JSON.stringify({\n query,\n variables,\n })\n : null;\n\n return { fullUrl, payload };\n};\n\nexport const gqlEndpointMapper = <E extends GraphQlEndpointType>(endpoint: E): string => {\n if (typeof endpoint === \"string\") {\n return endpoint;\n }\n return print(endpoint);\n};\n\nexport const gqlEndpointNameMapper = (endpoint: string): string => {\n try {\n const ast = parse(endpoint);\n const operationDefinition = ast.definitions.find(\n (def): def is OperationDefinitionNode => def.kind === \"OperationDefinition\",\n );\n\n if (operationDefinition) {\n if (operationDefinition.name?.value) {\n return operationDefinition.name.value;\n }\n\n const selection = operationDefinition.selectionSet.selections[0];\n if (selection?.kind === \"Field\") {\n return selection.name.value;\n }\n }\n } catch (error) {\n // We can ignore this error and just return some fallback\n }\n\n // Fallback for invalid gql queries or something else\n const clearedQuery = endpoint\n .replace(/(query|mutation|subscription)/, \"\")\n .replace(/[{}().,:]/g, \" \")\n .trim();\n const [name] = clearedQuery.split(\" \");\n\n return name || \"graphql-request\";\n};\n", "import { Time } from \"@hyper-fetch/core\";\n\nimport { GraphQlExtraType } from \"./adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\nexport const gqlExtra: GraphQlExtraType = {\n headers: {},\n extensions: {},\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAOO;AAcA,IAAM,gBAAgB,MAC3B,IAAI,oBAQ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AAAA,EACT;AACA,aAAO,sBAAM,QAAQ;AACvB;AAEO,IAAM,wBAAwB,CAAC,aAA6B;AA9BnE;AA+BE,MAAI;AACF,UAAM,UAAM,sBAAM,QAAQ;AAC1B,UAAM,sBAAsB,IAAI,YAAY;AAAA,MAC1C,CAAC,QAAwC,IAAI,SAAS;AAAA,IACxD;AAEA,QAAI,qBAAqB;AACvB,WAAI,yBAAoB,SAApB,mBAA0B,OAAO;AACnC,eAAO,oBAAoB,KAAK;AAAA,MAClC;AAEA,YAAM,YAAY,oBAAoB,aAAa,WAAW,CAAC;AAC/D,WAAI,uCAAW,UAAS,SAAS;AAC/B,eAAO,UAAU,KAAK;AAAA,MACxB;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAAA,EAEhB;AAGA,QAAM,eAAe,SAClB,QAAQ,iCAAiC,EAAE,EAC3C,QAAQ,cAAc,GAAG,EACzB,KAAK;AACR,QAAM,CAAC,IAAI,IAAI,aAAa,MAAM,GAAG;AAErC,SAAO,QAAQ;AACjB;;;AC3DA,IAAAC,eAAqB;AAId,IAAM,iBAAiB,kBAAK,MAAM;AAElC,IAAM,WAA6B;AAAA,EACxC,SAAS,CAAC;AAAA,EACV,YAAY,CAAC;AACf;",
6
- "names": ["import_core", "getGqlAdapter", "https", "http", "getGqlAdapter", "GraphqlMethod", "import_core", "import_core"]
7
- }
@@ -1,148 +0,0 @@
1
- import {
2
- getResponseHeaders,
3
- parseResponse,
4
- getErrorMessage,
5
- Adapter,
6
- QueryParamsType,
7
- stringifyKey,
8
- } from "@hyper-fetch/core";
9
-
10
- import {
11
- gqlExtra,
12
- GraphqlAdapterType,
13
- defaultTimeout,
14
- getRequestValues,
15
- GraphqlMethod,
16
- GraphQlExtraType,
17
- GraphQlEndpointType,
18
- gqlEndpointMapper,
19
- gqlEndpointNameMapper,
20
- } from "adapter";
21
-
22
- export const getGqlAdapter = (): GraphqlAdapterType =>
23
- new Adapter<
24
- Partial<XMLHttpRequest>,
25
- GraphqlMethod,
26
- number,
27
- GraphQlExtraType,
28
- QueryParamsType | string,
29
- undefined,
30
- GraphQlEndpointType
31
- >({
32
- name: "graphql-browser",
33
- defaultMethod: GraphqlMethod.POST,
34
- defaultExtra: gqlExtra,
35
- systemErrorStatus: 0,
36
- systemErrorExtra: gqlExtra,
37
- })
38
- .onInitialize(({ client }) => {
39
- client.setCacheKeyMapper((request) => {
40
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
41
- });
42
- client.setQueryKeyMapper((request) => {
43
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
44
- });
45
- client.setAbortKeyMapper((request) => {
46
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;
47
- });
48
- })
49
- .setInternalErrorMapping((error) => [error])
50
- .setDevtoolsEndpointGetter(gqlEndpointNameMapper)
51
- .setEndpointMapper(gqlEndpointMapper)
52
- .setFetcher(
53
- async ({
54
- request,
55
- adapterOptions,
56
- headers,
57
- onError,
58
- onResponseEnd,
59
- onTimeoutError,
60
- onRequestEnd,
61
- createAbortListener,
62
- onResponseProgress,
63
- onRequestProgress,
64
- onResponseStart,
65
- onBeforeRequest,
66
- onRequestStart,
67
- onSuccess,
68
- }) => {
69
- const { fullUrl, payload } = getRequestValues(request);
70
-
71
- const xhr = new XMLHttpRequest();
72
- xhr.timeout = defaultTimeout;
73
-
74
- const onAbort = () => xhr.abort();
75
-
76
- // Inject xhr options
77
- if (adapterOptions) {
78
- Object.entries(adapterOptions).forEach(([name, value]) => {
79
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
80
- // @ts-ignore
81
- xhr[name] = value;
82
- });
83
- }
84
-
85
- // Open connection
86
- xhr.open(request.method, fullUrl, true);
87
-
88
- // Set Headers
89
- Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value as string));
90
-
91
- // Listen to abort signal
92
- const unmountListener = createAbortListener({ status: 0, extra: gqlExtra, onAbort });
93
-
94
- // Request handlers
95
- xhr.upload.onprogress = onRequestProgress;
96
-
97
- // Response handlers
98
- xhr.onloadstart = (): void => {
99
- onRequestEnd();
100
- onResponseStart();
101
- };
102
-
103
- xhr.onprogress = onResponseProgress;
104
-
105
- xhr.onloadend = () => {
106
- onResponseEnd();
107
- unmountListener();
108
- };
109
-
110
- /* istanbul ignore next */
111
- xhr.ontimeout = () => onTimeoutError({ status: 0, extra: gqlExtra });
112
-
113
- // Data handler
114
- xhr.onreadystatechange = (e: Event) => {
115
- const event = e as unknown as ProgressEvent<XMLHttpRequest>;
116
- const finishedState = 4;
117
-
118
- if (event.target && event.target.readyState === finishedState) {
119
- const { status } = event.target;
120
- const response = parseResponse(event.target.response);
121
- const data = response.data ?? null;
122
- const errors = response?.errors || null;
123
- const extensions = response?.extensions || {};
124
- const failure = response?.errors || status > 399 || status === 0;
125
- const responseHeaders = getResponseHeaders(xhr.getAllResponseHeaders());
126
-
127
- if (failure) {
128
- const error = errors || [getErrorMessage()];
129
- // delay to finish after onabort/ontimeout
130
- onError({ error, status, extra: { headers: responseHeaders, extensions } });
131
- } else {
132
- onSuccess({
133
- data,
134
- error: errors,
135
- status,
136
- extra: { headers: responseHeaders, extensions },
137
- });
138
- }
139
- }
140
- };
141
-
142
- // Start request
143
- onBeforeRequest();
144
- onRequestStart();
145
-
146
- xhr.send(payload);
147
- },
148
- );
@@ -1,148 +0,0 @@
1
- import { Adapter, getErrorMessage, parseErrorResponse, parseResponse, QueryParamsType } from "@hyper-fetch/core";
2
- import http, { OutgoingHttpHeaders } from "http";
3
- import https from "https";
4
-
5
- import {
6
- gqlExtra,
7
- defaultTimeout,
8
- GraphqlAdapterType,
9
- getRequestValues,
10
- GraphQlExtraType,
11
- GraphqlMethod,
12
- GraphQlEndpointType,
13
- gqlEndpointMapper,
14
- gqlEndpointNameMapper,
15
- } from "adapter";
16
-
17
- export const getGqlAdapter = (): GraphqlAdapterType =>
18
- new Adapter<
19
- Partial<XMLHttpRequest>,
20
- GraphqlMethod,
21
- number,
22
- GraphQlExtraType,
23
- QueryParamsType | string,
24
- undefined,
25
- GraphQlEndpointType
26
- >({
27
- name: "graphql-server",
28
- defaultMethod: GraphqlMethod.POST,
29
- defaultExtra: gqlExtra,
30
- systemErrorStatus: 0,
31
- systemErrorExtra: gqlExtra,
32
- })
33
- .onInitialize(({ client }) => {
34
- client.setCacheKeyMapper((request) => {
35
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${JSON.stringify(request.params)}-${JSON.stringify(request.queryParams)}`;
36
- });
37
- client.setQueryKeyMapper((request) => {
38
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${JSON.stringify(request.params)}-${JSON.stringify(request.queryParams)}`;
39
- });
40
- client.setAbortKeyMapper((request) => {
41
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;
42
- });
43
- })
44
- .setInternalErrorMapping((error) => [error])
45
- .setDevtoolsEndpointGetter(gqlEndpointNameMapper)
46
- .setEndpointMapper(gqlEndpointMapper)
47
- .setFetcher(
48
- async ({
49
- request,
50
- adapterOptions,
51
- headers,
52
- onError,
53
- onResponseEnd,
54
- onTimeoutError,
55
- onRequestEnd,
56
- createAbortListener,
57
- getAbortController,
58
- onResponseProgress,
59
- onResponseStart,
60
- onBeforeRequest,
61
- onRequestStart,
62
- onSuccess,
63
- }) => {
64
- const { fullUrl, payload } = getRequestValues(request);
65
-
66
- const httpClient = request.client.url.includes("https://") ? https : http;
67
- const options = {
68
- method: request.method,
69
- headers: headers as OutgoingHttpHeaders,
70
- timeout: defaultTimeout,
71
- signal: getAbortController()?.signal,
72
- } satisfies https.RequestOptions;
73
-
74
- Object.entries(adapterOptions || {}).forEach(([name, value]) => {
75
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
76
- // @ts-ignore
77
- options[name] = value;
78
- });
79
-
80
- onBeforeRequest();
81
-
82
- const unmountListener = createAbortListener({
83
- status: 0,
84
- extra: gqlExtra,
85
- });
86
-
87
- const httpRequest = httpClient.request(fullUrl, options, (response) => {
88
- response.setEncoding("utf8");
89
-
90
- let chunks = "";
91
- const totalDownloadBytes = Number(response.headers["content-length"]);
92
- let downloadedBytes = 0;
93
-
94
- onRequestStart();
95
-
96
- response.on("data", (chunk) => {
97
- /* istanbul ignore next */
98
- if (!chunks) {
99
- onRequestEnd();
100
- onResponseStart();
101
- }
102
- downloadedBytes += chunk.length;
103
- chunks += chunk;
104
- onResponseProgress({ total: totalDownloadBytes, loaded: downloadedBytes });
105
- });
106
-
107
- response.on("end", () => {
108
- /* istanbul ignore next */
109
- const { statusCode = 0 } = response;
110
- const success = String(statusCode).startsWith("2") || String(statusCode).startsWith("3");
111
-
112
- if (success) {
113
- const { data, errors, extensions } = parseResponse(chunks);
114
- onSuccess({
115
- data: data ?? null,
116
- error: errors,
117
- status: statusCode,
118
- extra: { headers: response.headers as Record<string, string>, extensions: extensions ?? {} },
119
- });
120
- } else {
121
- // delay to finish after onabort/ontimeout
122
- const result = parseErrorResponse(chunks);
123
- /* istanbul ignore next */
124
- const error = "errors" in result ? result.errors : null;
125
- /* istanbul ignore next */
126
- const extensions = "extensions" in result ? result.extensions : {};
127
-
128
- onError({
129
- error: error ?? [getErrorMessage()],
130
- status: statusCode,
131
- extra: { headers: response.headers as Record<string, string>, extensions },
132
- });
133
- }
134
-
135
- unmountListener();
136
- onResponseEnd();
137
- });
138
- });
139
-
140
- /* istanbul ignore next */
141
- httpRequest.on("timeout", () => onTimeoutError({ status: 0, extra: gqlExtra }));
142
- httpRequest.on("error", (error) => onError({ error, status: 0, extra: gqlExtra }));
143
- if (payload) {
144
- httpRequest.write(payload);
145
- }
146
- httpRequest.end();
147
- },
148
- );