@graphql-tools/url-loader 7.17.0-alpha-20221025082811-e8a80d4e → 7.17.0-alpha-20230111114622-a9ecd8f6

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 (33) hide show
  1. package/cjs/index.js +15 -413
  2. package/esm/index.js +16 -414
  3. package/package.json +11 -12
  4. package/typings/defaultAsyncFetch.d.cts +1 -2
  5. package/typings/defaultAsyncFetch.d.ts +1 -2
  6. package/typings/defaultSyncFetch.d.cts +1 -6
  7. package/typings/defaultSyncFetch.d.ts +1 -6
  8. package/typings/index.d.cts +10 -60
  9. package/typings/index.d.ts +10 -60
  10. package/cjs/event-stream/addCancelToResponseStream.js +0 -26
  11. package/cjs/event-stream/handleAsyncIterable.js +0 -25
  12. package/cjs/event-stream/handleEventStreamResponse.js +0 -31
  13. package/cjs/event-stream/handleReadableStream.js +0 -64
  14. package/cjs/handleMultipartMixedResponse.js +0 -57
  15. package/cjs/utils.js +0 -33
  16. package/esm/event-stream/addCancelToResponseStream.js +0 -21
  17. package/esm/event-stream/handleAsyncIterable.js +0 -21
  18. package/esm/event-stream/handleEventStreamResponse.js +0 -26
  19. package/esm/event-stream/handleReadableStream.js +0 -60
  20. package/esm/handleMultipartMixedResponse.js +0 -53
  21. package/esm/utils.js +0 -27
  22. package/typings/event-stream/addCancelToResponseStream.d.cts +0 -2
  23. package/typings/event-stream/addCancelToResponseStream.d.ts +0 -2
  24. package/typings/event-stream/handleAsyncIterable.d.cts +0 -1
  25. package/typings/event-stream/handleAsyncIterable.d.ts +0 -1
  26. package/typings/event-stream/handleEventStreamResponse.d.cts +0 -3
  27. package/typings/event-stream/handleEventStreamResponse.d.ts +0 -3
  28. package/typings/event-stream/handleReadableStream.d.cts +0 -2
  29. package/typings/event-stream/handleReadableStream.d.ts +0 -2
  30. package/typings/handleMultipartMixedResponse.d.cts +0 -2
  31. package/typings/handleMultipartMixedResponse.d.ts +0 -2
  32. package/typings/utils.d.cts +0 -25
  33. package/typings/utils.d.ts +0 -25
package/cjs/index.js CHANGED
@@ -2,23 +2,17 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.UrlLoader = exports.SubscriptionProtocol = void 0;
4
4
  const tslib_1 = require("tslib");
5
- /* eslint-disable no-case-declarations */
6
- /// <reference lib="dom" />
7
5
  const graphql_1 = require("graphql");
8
6
  const utils_1 = require("@graphql-tools/utils");
9
7
  const wrap_1 = require("@graphql-tools/wrap");
10
- const graphql_ws_1 = require("graphql-ws");
11
8
  const isomorphic_ws_1 = tslib_1.__importDefault(require("isomorphic-ws"));
12
- const extract_files_1 = require("extract-files");
13
9
  const value_or_promise_1 = require("value-or-promise");
14
10
  const defaultAsyncFetch_js_1 = require("./defaultAsyncFetch.js");
15
11
  const defaultSyncFetch_js_1 = require("./defaultSyncFetch.js");
16
- const handleMultipartMixedResponse_js_1 = require("./handleMultipartMixedResponse.js");
17
- const handleEventStreamResponse_js_1 = require("./event-stream/handleEventStreamResponse.js");
18
- const addCancelToResponseStream_js_1 = require("./event-stream/addCancelToResponseStream.js");
19
- const fetch_1 = require("@whatwg-node/fetch");
20
- const utils_js_1 = require("./utils.js");
21
- const asyncImport = (moduleName) => Promise.resolve().then(() => tslib_1.__importStar(require(moduleName)));
12
+ const executor_graphql_ws_1 = require("@graphql-tools/executor-graphql-ws");
13
+ const executor_http_1 = require("@graphql-tools/executor-http");
14
+ const executor_legacy_ws_1 = require("@graphql-tools/executor-legacy-ws");
15
+ const asyncImport = (moduleName) => { var _a; return _a = moduleName, Promise.resolve().then(() => tslib_1.__importStar(require(_a))); };
22
16
  const syncImport = (moduleName) => require(moduleName);
23
17
  var SubscriptionProtocol;
24
18
  (function (SubscriptionProtocol) {
@@ -59,422 +53,30 @@ function isCompatibleUri(uri) {
59
53
  * ```
60
54
  */
61
55
  class UrlLoader {
62
- createFormDataFromVariables({ query, variables, operationName, extensions, }) {
63
- const vars = Object.assign({}, variables);
64
- const { clone, files } = (0, extract_files_1.extractFiles)(vars, 'variables', ((v) => (0, extract_files_1.isExtractableFile)(v) ||
65
- (v === null || v === void 0 ? void 0 : v.promise) ||
66
- (0, utils_1.isAsyncIterable)(v) ||
67
- (v === null || v === void 0 ? void 0 : v.then) ||
68
- typeof (v === null || v === void 0 ? void 0 : v.arrayBuffer) === 'function'));
69
- if (files.size === 0) {
70
- return JSON.stringify({
71
- query,
72
- variables,
73
- operationName,
74
- extensions,
75
- });
76
- }
77
- const map = {};
78
- const uploads = [];
79
- let currIndex = 0;
80
- for (const [file, curr] of files) {
81
- map[currIndex] = curr;
82
- uploads[currIndex] = file;
83
- currIndex++;
84
- }
85
- const form = new fetch_1.FormData();
86
- form.append('operations', JSON.stringify({
87
- query,
88
- variables: clone,
89
- operationName,
90
- extensions,
91
- }));
92
- form.append('map', JSON.stringify(map));
93
- function handleUpload(upload, i) {
94
- const indexStr = i.toString();
95
- if (upload != null) {
96
- const filename = upload.filename || upload.name || upload.path || `blob-${indexStr}`;
97
- if ((0, utils_js_1.isPromiseLike)(upload)) {
98
- return upload.then((resolvedUpload) => handleUpload(resolvedUpload, i));
99
- // If Blob
100
- }
101
- else if ((0, utils_js_1.isBlob)(upload)) {
102
- form.append(indexStr, upload, filename);
103
- }
104
- else if ((0, utils_js_1.isGraphQLUpload)(upload)) {
105
- const stream = upload.createReadStream();
106
- const chunks = [];
107
- return Promise.resolve().then(async () => {
108
- for await (const chunk of stream) {
109
- if (chunk) {
110
- chunks.push(...chunk);
111
- }
112
- }
113
- const blobPart = new Uint8Array(chunks);
114
- form.append(indexStr, new fetch_1.File([blobPart], filename, { type: upload.mimetype }), filename);
115
- });
116
- }
117
- else {
118
- form.append(indexStr, new fetch_1.File([upload], filename), filename);
119
- }
120
- }
121
- }
122
- return value_or_promise_1.ValueOrPromise.all(uploads.map((upload, i) => new value_or_promise_1.ValueOrPromise(() => handleUpload(upload, i))))
123
- .then(() => form)
124
- .resolve();
125
- }
126
- prepareGETUrl({ baseUrl, query, variables, operationName, extensions, }) {
127
- const HTTP_URL = switchProtocols(baseUrl, {
128
- wss: 'https',
129
- ws: 'http',
130
- });
131
- const dummyHostname = 'https://dummyhostname.com';
132
- const validUrl = HTTP_URL.startsWith('http')
133
- ? HTTP_URL
134
- : HTTP_URL.startsWith('/')
135
- ? `${dummyHostname}${HTTP_URL}`
136
- : `${dummyHostname}/${HTTP_URL}`;
137
- const urlObj = new URL(validUrl);
138
- urlObj.searchParams.set('query', (0, graphql_1.stripIgnoredCharacters)(query));
139
- if (variables && Object.keys(variables).length > 0) {
140
- urlObj.searchParams.set('variables', JSON.stringify(variables));
141
- }
142
- if (operationName) {
143
- urlObj.searchParams.set('operationName', operationName);
144
- }
145
- if (extensions) {
146
- urlObj.searchParams.set('extensions', JSON.stringify(extensions));
147
- }
148
- const finalUrl = urlObj.toString().replace(dummyHostname, '');
149
- return finalUrl;
150
- }
151
- buildHTTPExecutor(initialEndpoint, fetch, options) {
152
- const defaultMethod = this.getDefaultMethodFromOptions(options === null || options === void 0 ? void 0 : options.method, 'POST');
56
+ buildHTTPExecutor(initialEndpoint, fetchFn, options) {
153
57
  const HTTP_URL = switchProtocols(initialEndpoint, {
154
58
  wss: 'https',
155
59
  ws: 'http',
156
60
  });
157
- const executor = (request) => {
158
- var _a, _b;
159
- const controller = (0, addCancelToResponseStream_js_1.cancelNeeded)() ? new fetch_1.AbortController() : undefined;
160
- let method = defaultMethod;
161
- const operationAst = (0, utils_1.getOperationASTFromRequest)(request);
162
- const operationType = operationAst.operation;
163
- if ((options === null || options === void 0 ? void 0 : options.useGETForQueries) && operationType === 'query') {
164
- method = 'GET';
165
- }
166
- let accept = 'application/graphql-response+json, application/json, multipart/mixed';
167
- if (operationType === 'subscription' || (0, utils_js_1.isLiveQueryOperationDefinitionNode)(operationAst)) {
168
- method = 'GET';
169
- accept = 'text/event-stream';
170
- }
171
- const endpoint = ((_a = request.extensions) === null || _a === void 0 ? void 0 : _a.endpoint) || HTTP_URL;
172
- const headers = Object.assign({
173
- accept,
174
- }, options === null || options === void 0 ? void 0 : options.headers, ((_b = request.extensions) === null || _b === void 0 ? void 0 : _b.headers) || {});
175
- const query = (0, graphql_1.print)(request.document);
176
- const requestBody = {
177
- query,
178
- variables: request.variables,
179
- operationName: request.operationName,
180
- extensions: request.extensions,
181
- };
182
- let timeoutId;
183
- if (options === null || options === void 0 ? void 0 : options.timeout) {
184
- timeoutId = setTimeout(() => {
185
- if (!(controller === null || controller === void 0 ? void 0 : controller.signal.aborted)) {
186
- controller === null || controller === void 0 ? void 0 : controller.abort();
187
- }
188
- }, options.timeout);
189
- }
190
- return new value_or_promise_1.ValueOrPromise(() => {
191
- switch (method) {
192
- case 'GET':
193
- const finalUrl = this.prepareGETUrl({
194
- baseUrl: endpoint,
195
- ...requestBody,
196
- });
197
- return fetch(finalUrl, {
198
- method: 'GET',
199
- ...((options === null || options === void 0 ? void 0 : options.credentials) != null ? { credentials: options.credentials } : {}),
200
- headers,
201
- signal: controller === null || controller === void 0 ? void 0 : controller.signal,
202
- }, request.context, request.info);
203
- case 'POST':
204
- return new value_or_promise_1.ValueOrPromise(() => this.createFormDataFromVariables(requestBody))
205
- .then(body => fetch(endpoint, {
206
- method: 'POST',
207
- ...((options === null || options === void 0 ? void 0 : options.credentials) != null ? { credentials: options.credentials } : {}),
208
- body,
209
- headers: {
210
- ...headers,
211
- ...(typeof body === 'string' ? { 'content-type': 'application/json' } : {}),
212
- },
213
- signal: controller === null || controller === void 0 ? void 0 : controller.signal,
214
- }, request.context, request.info))
215
- .resolve();
216
- }
217
- })
218
- .then((fetchResult) => {
219
- if (timeoutId != null) {
220
- clearTimeout(timeoutId);
221
- }
222
- // Retry should respect HTTP Errors
223
- if ((options === null || options === void 0 ? void 0 : options.retry) != null && !fetchResult.status.toString().startsWith('2')) {
224
- throw new Error(fetchResult.statusText || `HTTP Error: ${fetchResult.status}`);
225
- }
226
- const contentType = fetchResult.headers.get('content-type');
227
- if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('text/event-stream')) {
228
- return (0, handleEventStreamResponse_js_1.handleEventStreamResponse)(fetchResult, controller);
229
- }
230
- else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('multipart/mixed')) {
231
- return (0, handleMultipartMixedResponse_js_1.handleMultipartMixedResponse)(fetchResult, controller);
232
- }
233
- return fetchResult.text();
234
- })
235
- .then(result => {
236
- if (typeof result === 'string') {
237
- if (result) {
238
- return JSON.parse(result);
239
- }
240
- }
241
- else {
242
- return result;
243
- }
244
- })
245
- .catch((e) => {
246
- if (typeof e === 'string') {
247
- return {
248
- errors: [
249
- (0, utils_1.createGraphQLError)(e, {
250
- extensions: {
251
- requestBody,
252
- },
253
- }),
254
- ],
255
- };
256
- }
257
- else if (e.name === 'GraphQLError') {
258
- return {
259
- errors: [e],
260
- };
261
- }
262
- else if (e.name === 'TypeError' && e.message === 'fetch failed') {
263
- return {
264
- errors: [
265
- (0, utils_1.createGraphQLError)(`fetch failed to ${endpoint}`, {
266
- extensions: {
267
- requestBody,
268
- },
269
- originalError: e,
270
- }),
271
- ],
272
- };
273
- }
274
- else if (e.message) {
275
- return {
276
- errors: [
277
- (0, utils_1.createGraphQLError)(e.message, {
278
- extensions: {
279
- requestBody,
280
- },
281
- originalError: e,
282
- }),
283
- ],
284
- };
285
- }
286
- else {
287
- return {
288
- errors: [
289
- (0, utils_1.createGraphQLError)('Unknown error', {
290
- extensions: {
291
- requestBody,
292
- },
293
- originalError: e,
294
- }),
295
- ],
296
- };
297
- }
298
- })
299
- .resolve();
300
- };
301
- if ((options === null || options === void 0 ? void 0 : options.retry) != null) {
302
- return function retryExecutor(request) {
303
- let result;
304
- let attempt = 0;
305
- function retryAttempt() {
306
- attempt++;
307
- if (attempt > options.retry) {
308
- if (result != null) {
309
- return result;
310
- }
311
- return {
312
- errors: [(0, utils_1.createGraphQLError)('No response returned from fetch')],
313
- };
314
- }
315
- return new value_or_promise_1.ValueOrPromise(() => executor(request))
316
- .then(res => {
317
- var _a;
318
- result = res;
319
- if ((_a = result === null || result === void 0 ? void 0 : result.errors) === null || _a === void 0 ? void 0 : _a.length) {
320
- return retryAttempt();
321
- }
322
- return result;
323
- })
324
- .resolve();
325
- }
326
- return retryAttempt();
327
- };
328
- }
329
- return executor;
61
+ return (0, executor_http_1.buildHTTPExecutor)({
62
+ endpoint: HTTP_URL,
63
+ fetch: fetchFn,
64
+ ...options,
65
+ });
330
66
  }
331
67
  buildWSExecutor(subscriptionsEndpoint, webSocketImpl, connectionParams) {
332
68
  const WS_URL = switchProtocols(subscriptionsEndpoint, {
333
69
  https: 'wss',
334
70
  http: 'ws',
335
71
  });
336
- let executorConnectionParams = {};
337
- const subscriptionClient = (0, graphql_ws_1.createClient)({
338
- url: WS_URL,
339
- webSocketImpl,
340
- connectionParams: () => {
341
- const optionsConnectionParams = (typeof connectionParams === 'function' ? connectionParams() : connectionParams) || {};
342
- return Object.assign(optionsConnectionParams, executorConnectionParams);
343
- },
344
- lazy: true,
345
- });
346
- return ({ document, variables, operationName, extensions }) => {
347
- // additional connection params can be supplied through the "webSocketConnectionParams" field in extensions.
348
- // TODO: connection params only from the FIRST operation in lazy mode will be used (detect connectionParams changes and reconnect, too implicit?)
349
- if ((extensions === null || extensions === void 0 ? void 0 : extensions['webSocketConnectionParams']) && typeof (extensions === null || extensions === void 0 ? void 0 : extensions['webSocketConnectionParams']) === 'object') {
350
- executorConnectionParams = Object.assign(executorConnectionParams, extensions['webSocketConnectionParams']);
351
- }
352
- const query = (0, graphql_1.print)(document);
353
- return (0, utils_1.observableToAsyncIterable)({
354
- subscribe: observer => {
355
- const unsubscribe = subscriptionClient.subscribe({
356
- query,
357
- variables: variables,
358
- operationName,
359
- extensions,
360
- }, observer);
361
- return {
362
- unsubscribe,
363
- };
364
- },
365
- });
366
- };
72
+ return (0, executor_graphql_ws_1.buildGraphQLWSExecutor)(WS_URL, webSocketImpl, connectionParams);
367
73
  }
368
74
  buildWSLegacyExecutor(subscriptionsEndpoint, WebSocketImpl, options) {
369
75
  const WS_URL = switchProtocols(subscriptionsEndpoint, {
370
76
  https: 'wss',
371
77
  http: 'ws',
372
78
  });
373
- const observerById = new Map();
374
- let executorConnectionParams = {};
375
- let websocket = null;
376
- const ensureWebsocket = () => {
377
- websocket = new WebSocketImpl(WS_URL, 'graphql-ws', {
378
- followRedirects: true,
379
- headers: options === null || options === void 0 ? void 0 : options.headers,
380
- rejectUnauthorized: false,
381
- skipUTF8Validation: true,
382
- });
383
- websocket.onopen = () => {
384
- let payload = {};
385
- switch (typeof (options === null || options === void 0 ? void 0 : options.connectionParams)) {
386
- case 'function':
387
- payload = options === null || options === void 0 ? void 0 : options.connectionParams();
388
- break;
389
- case 'object':
390
- payload = options === null || options === void 0 ? void 0 : options.connectionParams;
391
- break;
392
- }
393
- payload = Object.assign(payload, executorConnectionParams);
394
- websocket.send(JSON.stringify({
395
- type: utils_js_1.LEGACY_WS.CONNECTION_INIT,
396
- payload,
397
- }));
398
- };
399
- };
400
- const cleanupWebsocket = () => {
401
- if (websocket != null && observerById.size === 0) {
402
- websocket.send(JSON.stringify({
403
- type: utils_js_1.LEGACY_WS.CONNECTION_TERMINATE,
404
- }));
405
- websocket.terminate();
406
- websocket = null;
407
- }
408
- };
409
- return function legacyExecutor(request) {
410
- var _a, _b;
411
- // additional connection params can be supplied through the "webSocketConnectionParams" field in extensions.
412
- // TODO: connection params only from the FIRST operation in lazy mode will be used (detect connectionParams changes and reconnect, too implicit?)
413
- if (((_a = request.extensions) === null || _a === void 0 ? void 0 : _a['webSocketConnectionParams']) &&
414
- typeof ((_b = request.extensions) === null || _b === void 0 ? void 0 : _b['webSocketConnectionParams']) === 'object') {
415
- executorConnectionParams = Object.assign(executorConnectionParams, request.extensions['webSocketConnectionParams']);
416
- }
417
- const id = Date.now().toString();
418
- return (0, utils_1.observableToAsyncIterable)({
419
- subscribe(observer) {
420
- ensureWebsocket();
421
- if (websocket == null) {
422
- throw new Error(`WebSocket connection is not found!`);
423
- }
424
- websocket.onmessage = event => {
425
- const data = JSON.parse(event.data.toString('utf-8'));
426
- switch (data.type) {
427
- case utils_js_1.LEGACY_WS.CONNECTION_ACK: {
428
- if (websocket == null) {
429
- throw new Error(`WebSocket connection is not found!`);
430
- }
431
- websocket.send(JSON.stringify({
432
- type: utils_js_1.LEGACY_WS.START,
433
- id,
434
- payload: {
435
- query: (0, graphql_1.print)(request.document),
436
- variables: request.variables,
437
- operationName: request.operationName,
438
- },
439
- }));
440
- break;
441
- }
442
- case utils_js_1.LEGACY_WS.CONNECTION_ERROR: {
443
- observer.error(data.payload);
444
- break;
445
- }
446
- case utils_js_1.LEGACY_WS.CONNECTION_KEEP_ALIVE: {
447
- break;
448
- }
449
- case utils_js_1.LEGACY_WS.DATA: {
450
- observer.next(data.payload);
451
- break;
452
- }
453
- case utils_js_1.LEGACY_WS.COMPLETE: {
454
- if (websocket == null) {
455
- throw new Error(`WebSocket connection is not found!`);
456
- }
457
- websocket.send(JSON.stringify({
458
- type: utils_js_1.LEGACY_WS.CONNECTION_TERMINATE,
459
- }));
460
- observer.complete();
461
- cleanupWebsocket();
462
- break;
463
- }
464
- }
465
- };
466
- return {
467
- unsubscribe: () => {
468
- websocket === null || websocket === void 0 ? void 0 : websocket.send(JSON.stringify({
469
- type: utils_js_1.LEGACY_WS.STOP,
470
- id,
471
- }));
472
- cleanupWebsocket();
473
- },
474
- };
475
- },
476
- });
477
- };
79
+ return (0, executor_legacy_ws_1.buildWSLegacyExecutor)(WS_URL, WebSocketImpl, options);
478
80
  }
479
81
  getFetch(customFetch, importFn) {
480
82
  if (customFetch) {
@@ -551,7 +153,7 @@ class UrlLoader {
551
153
  // eslint-disable-next-line no-inner-declarations
552
154
  function getExecutorByRequest(request) {
553
155
  const operationAst = (0, utils_1.getOperationASTFromRequest)(request);
554
- if (operationAst.operation === 'subscription' || (0, utils_js_1.isLiveQueryOperationDefinitionNode)(operationAst)) {
156
+ if (operationAst.operation === 'subscription' || (0, executor_http_1.isLiveQueryOperationDefinitionNode)(operationAst)) {
555
157
  return subscriptionExecutor$;
556
158
  }
557
159
  else {
@@ -606,7 +208,7 @@ class UrlLoader {
606
208
  }
607
209
  else {
608
210
  executor = this.getExecutorAsync(pointer, options);
609
- source.schema = await (0, wrap_1.introspectSchema)(executor, {}, options);
211
+ source.schema = await (0, wrap_1.schemaFromExecutor)(executor, {}, options);
610
212
  }
611
213
  if (!source.schema) {
612
214
  throw new Error(`Invalid introspected schema`);
@@ -647,7 +249,7 @@ class UrlLoader {
647
249
  }
648
250
  else {
649
251
  executor = this.getExecutorSync(pointer, options);
650
- source.schema = (0, wrap_1.introspectSchema)(executor, {}, options);
252
+ source.schema = (0, wrap_1.schemaFromExecutor)(executor, {}, options);
651
253
  }
652
254
  if (!source.schema) {
653
255
  throw new Error(`Invalid introspected schema`);