@graphql-tools/url-loader 7.12.2-alpha-b93d3b57.0 → 7.12.2

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.
@@ -0,0 +1,8 @@
1
+ import { withCancel } from '@graphql-tools/utils';
2
+ export function addCancelToResponseStream(resultStream, controller) {
3
+ return withCancel(resultStream, () => {
4
+ if (!controller.signal.aborted) {
5
+ controller.abort();
6
+ }
7
+ });
8
+ }
@@ -0,0 +1,4 @@
1
+ import { fetch } from '@whatwg-node/fetch';
2
+ export const defaultAsyncFetch = async (input, init) => {
3
+ return fetch(input, init);
4
+ };
@@ -0,0 +1,10 @@
1
+ import syncFetchImported from 'sync-fetch';
2
+ export const defaultSyncFetch = (input, init) => {
3
+ if (typeof input === 'string') {
4
+ init === null || init === void 0 ? true : delete init.signal;
5
+ }
6
+ else {
7
+ delete input.signal;
8
+ }
9
+ return syncFetchImported(input, init);
10
+ };
@@ -0,0 +1,14 @@
1
+ import { inspect, isAsyncIterable } from '@graphql-tools/utils';
2
+ import { handleReadable } from './handleReadable.js';
3
+ import { handleReadableStream } from './handleReadableStream.js';
4
+ export async function handleEventStreamResponse(response) {
5
+ // node-fetch returns body as a promise so we need to resolve it
6
+ const body = await response.body;
7
+ if (body) {
8
+ if (isAsyncIterable(body)) {
9
+ return handleReadable(body);
10
+ }
11
+ return handleReadableStream(body);
12
+ }
13
+ throw new Error('Response body is expected to be a readable stream but got; ' + inspect(body));
14
+ }
@@ -1,7 +1,4 @@
1
- "use strict";
2
1
  /* eslint-disable no-labels */
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.handleReadable = void 0;
5
2
  let decodeUint8Array;
6
3
  if (globalThis.Buffer) {
7
4
  decodeUint8Array = uint8Array => globalThis.Buffer.from(uint8Array).toString('utf-8');
@@ -10,7 +7,7 @@ else {
10
7
  const textDecoder = new TextDecoder();
11
8
  decodeUint8Array = uint8Array => textDecoder.decode(uint8Array);
12
9
  }
13
- async function* handleReadable(readable) {
10
+ export async function* handleReadable(readable) {
14
11
  outer: for await (const chunk of readable) {
15
12
  const chunkStr = typeof chunk === 'string' ? chunk : decodeUint8Array(chunk);
16
13
  for (const part of chunkStr.split('\n\n')) {
@@ -28,4 +25,3 @@ async function* handleReadable(readable) {
28
25
  }
29
26
  }
30
27
  }
31
- exports.handleReadable = handleReadable;
@@ -1,8 +1,5 @@
1
- "use strict";
2
1
  // Based on https://github.com/Azure/fetch-event-source/blob/main/src/parse.ts
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.handleReadableStream = void 0;
5
- async function* handleReadableStream(stream) {
2
+ export async function* handleReadableStream(stream) {
6
3
  const decoder = new TextDecoder();
7
4
  const reader = stream.getReader();
8
5
  let buffer;
@@ -122,7 +119,6 @@ async function* handleReadableStream(stream) {
122
119
  reader.releaseLock();
123
120
  }
124
121
  }
125
- exports.handleReadableStream = handleReadableStream;
126
122
  function concat(a, b) {
127
123
  const res = new Uint8Array(a.length + b.length);
128
124
  res.set(a);
@@ -1,14 +1,11 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.handleMultipartMixedResponse = void 0;
4
- const node_1 = require("meros/node");
5
- const browser_1 = require("meros/browser");
6
- const utils_1 = require("@graphql-tools/utils");
7
- const merge_1 = require("dset/merge");
1
+ import { meros as merosIncomingMessage } from 'meros/node';
2
+ import { meros as merosReadableStream } from 'meros/browser';
3
+ import { mapAsyncIterator } from '@graphql-tools/utils';
4
+ import { dset } from 'dset/merge';
8
5
  function isIncomingMessage(body) {
9
6
  return body != null && typeof body === 'object' && 'pipe' in body;
10
7
  }
11
- async function handleMultipartMixedResponse(response) {
8
+ export async function handleMultipartMixedResponse(response) {
12
9
  const body = await response.body;
13
10
  const contentType = response.headers.get('content-type') || '';
14
11
  let asyncIterator;
@@ -18,20 +15,20 @@ async function handleMultipartMixedResponse(response) {
18
15
  'content-type': contentType,
19
16
  };
20
17
  // And it expects `IncomingMessage` and `node-fetch` returns `body` as `Promise<PassThrough>`
21
- asyncIterator = (await (0, node_1.meros)(body));
18
+ asyncIterator = (await merosIncomingMessage(body));
22
19
  }
23
20
  else {
24
21
  // Nothing is needed for regular `Response`.
25
- asyncIterator = (await (0, browser_1.meros)(response));
22
+ asyncIterator = (await merosReadableStream(response));
26
23
  }
27
24
  const executionResult = {};
28
- return (0, utils_1.mapAsyncIterator)(asyncIterator, (part) => {
25
+ return mapAsyncIterator(asyncIterator, (part) => {
29
26
  if (part.json) {
30
27
  const chunk = part.body;
31
28
  if (chunk.path) {
32
29
  if (chunk.data) {
33
30
  const path = ['data'];
34
- (0, merge_1.dset)(executionResult, path.concat(chunk.path), chunk.data);
31
+ dset(executionResult, path.concat(chunk.path), chunk.data);
35
32
  }
36
33
  if (chunk.errors) {
37
34
  executionResult.errors = (executionResult.errors || []).concat(chunk.errors);
@@ -49,4 +46,3 @@ async function handleMultipartMixedResponse(response) {
49
46
  }
50
47
  });
51
48
  }
52
- exports.handleMultipartMixedResponse = handleMultipartMixedResponse;
@@ -1,27 +1,23 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UrlLoader = exports.SubscriptionProtocol = void 0;
4
- const tslib_1 = require("tslib");
5
1
  /* eslint-disable no-case-declarations */
6
2
  /// <reference lib="dom" />
7
- const graphql_1 = require("graphql");
8
- const utils_1 = require("@graphql-tools/utils");
9
- const wrap_1 = require("@graphql-tools/wrap");
10
- const graphql_ws_1 = require("graphql-ws");
11
- const isomorphic_ws_1 = tslib_1.__importDefault(require("isomorphic-ws"));
12
- const extract_files_1 = require("extract-files");
13
- const value_or_promise_1 = require("value-or-promise");
14
- const graphql_live_query_1 = require("@n1ru4l/graphql-live-query");
15
- const defaultAsyncFetch_js_1 = require("./defaultAsyncFetch.js");
16
- const defaultSyncFetch_js_1 = require("./defaultSyncFetch.js");
17
- const handleMultipartMixedResponse_js_1 = require("./handleMultipartMixedResponse.js");
18
- const handleEventStreamResponse_js_1 = require("./event-stream/handleEventStreamResponse.js");
19
- const addCancelToResponseStream_js_1 = require("./addCancelToResponseStream.js");
20
- const fetch_1 = require("@whatwg-node/fetch");
21
- const utils_js_1 = require("./utils.js");
22
- const asyncImport = (moduleName) => Promise.resolve().then(() => tslib_1.__importStar(require(moduleName)));
3
+ import { print, buildASTSchema, buildSchema } from 'graphql';
4
+ import { observableToAsyncIterable, isAsyncIterable, parseGraphQLSDL, getOperationASTFromRequest, } from '@graphql-tools/utils';
5
+ import { introspectSchema, wrapSchema } from '@graphql-tools/wrap';
6
+ import { createClient } from 'graphql-ws';
7
+ import WebSocket from 'isomorphic-ws';
8
+ import { extractFiles, isExtractableFile } from 'extract-files';
9
+ import { ValueOrPromise } from 'value-or-promise';
10
+ import { isLiveQueryOperationDefinitionNode } from '@n1ru4l/graphql-live-query';
11
+ import { defaultAsyncFetch } from './defaultAsyncFetch.js';
12
+ import { defaultSyncFetch } from './defaultSyncFetch.js';
13
+ import { handleMultipartMixedResponse } from './handleMultipartMixedResponse.js';
14
+ import { handleEventStreamResponse } from './event-stream/handleEventStreamResponse.js';
15
+ import { addCancelToResponseStream } from './addCancelToResponseStream.js';
16
+ import { AbortController, FormData, File } from '@whatwg-node/fetch';
17
+ import { isBlob, isGraphQLUpload, isPromiseLike, LEGACY_WS } from './utils.js';
18
+ const asyncImport = (moduleName) => import(moduleName);
23
19
  const syncImport = (moduleName) => require(moduleName);
24
- var SubscriptionProtocol;
20
+ export var SubscriptionProtocol;
25
21
  (function (SubscriptionProtocol) {
26
22
  SubscriptionProtocol["WS"] = "WS";
27
23
  /**
@@ -36,7 +32,7 @@ var SubscriptionProtocol;
36
32
  * Use `graphql-sse` for subscriptions
37
33
  */
38
34
  SubscriptionProtocol["GRAPHQL_SSE"] = "GRAPHQL_SSE";
39
- })(SubscriptionProtocol = exports.SubscriptionProtocol || (exports.SubscriptionProtocol = {}));
35
+ })(SubscriptionProtocol || (SubscriptionProtocol = {}));
40
36
  function isCompatibleUri(uri) {
41
37
  try {
42
38
  // eslint-disable-next-line no-new
@@ -59,12 +55,12 @@ function isCompatibleUri(uri) {
59
55
  * });
60
56
  * ```
61
57
  */
62
- class UrlLoader {
58
+ export class UrlLoader {
63
59
  createFormDataFromVariables({ query, variables, operationName, extensions, }) {
64
60
  const vars = Object.assign({}, variables);
65
- const { clone, files } = (0, extract_files_1.extractFiles)(vars, 'variables', ((v) => (0, extract_files_1.isExtractableFile)(v) ||
61
+ const { clone, files } = extractFiles(vars, 'variables', ((v) => isExtractableFile(v) ||
66
62
  (v === null || v === void 0 ? void 0 : v.promise) ||
67
- (0, utils_1.isAsyncIterable)(v) ||
63
+ isAsyncIterable(v) ||
68
64
  (v === null || v === void 0 ? void 0 : v.then) ||
69
65
  typeof (v === null || v === void 0 ? void 0 : v.arrayBuffer) === 'function'));
70
66
  const map = {};
@@ -75,7 +71,7 @@ class UrlLoader {
75
71
  uploads[currIndex] = file;
76
72
  currIndex++;
77
73
  }
78
- const form = new fetch_1.FormData();
74
+ const form = new FormData();
79
75
  form.append('operations', JSON.stringify({
80
76
  query,
81
77
  variables: clone,
@@ -87,16 +83,16 @@ class UrlLoader {
87
83
  const indexStr = i.toString();
88
84
  if (upload != null) {
89
85
  const filename = upload.filename || upload.name || upload.path || `blob-${indexStr}`;
90
- if ((0, utils_js_1.isPromiseLike)(upload)) {
86
+ if (isPromiseLike(upload)) {
91
87
  return upload.then((resolvedUpload) => handleUpload(resolvedUpload, i));
92
88
  // If Blob
93
89
  }
94
- else if ((0, utils_js_1.isBlob)(upload)) {
90
+ else if (isBlob(upload)) {
95
91
  return upload.arrayBuffer().then((arrayBuffer) => {
96
- form.append(indexStr, new fetch_1.File([arrayBuffer], filename, { type: upload.type }), filename);
92
+ form.append(indexStr, new File([arrayBuffer], filename, { type: upload.type }), filename);
97
93
  });
98
94
  }
99
- else if ((0, utils_js_1.isGraphQLUpload)(upload)) {
95
+ else if (isGraphQLUpload(upload)) {
100
96
  const stream = upload.createReadStream();
101
97
  const chunks = [];
102
98
  return Promise.resolve().then(async () => {
@@ -106,15 +102,15 @@ class UrlLoader {
106
102
  }
107
103
  }
108
104
  const blobPart = new Uint8Array(chunks);
109
- form.append(indexStr, new fetch_1.File([blobPart], filename, { type: upload.mimetype }), filename);
105
+ form.append(indexStr, new File([blobPart], filename, { type: upload.mimetype }), filename);
110
106
  });
111
107
  }
112
108
  else {
113
- form.append(indexStr, new fetch_1.File([upload], filename), filename);
109
+ form.append(indexStr, new File([upload], filename), filename);
114
110
  }
115
111
  }
116
112
  }
117
- return value_or_promise_1.ValueOrPromise.all(uploads.map((upload, i) => new value_or_promise_1.ValueOrPromise(() => handleUpload(upload, i))))
113
+ return ValueOrPromise.all(uploads.map((upload, i) => new ValueOrPromise(() => handleUpload(upload, i))))
118
114
  .then(() => form)
119
115
  .resolve();
120
116
  }
@@ -151,15 +147,15 @@ class UrlLoader {
151
147
  });
152
148
  const executor = (request) => {
153
149
  var _a, _b;
154
- const controller = new fetch_1.AbortController();
150
+ const controller = new AbortController();
155
151
  let method = defaultMethod;
156
- const operationAst = (0, utils_1.getOperationASTFromRequest)(request);
152
+ const operationAst = getOperationASTFromRequest(request);
157
153
  const operationType = operationAst.operation;
158
154
  if ((options === null || options === void 0 ? void 0 : options.useGETForQueries) && operationType === 'query') {
159
155
  method = 'GET';
160
156
  }
161
157
  let accept = 'application/json, multipart/mixed';
162
- if (operationType === 'subscription' || (0, graphql_live_query_1.isLiveQueryOperationDefinitionNode)(operationAst)) {
158
+ if (operationType === 'subscription' || isLiveQueryOperationDefinitionNode(operationAst)) {
163
159
  method = 'GET';
164
160
  accept = 'text/event-stream';
165
161
  }
@@ -167,7 +163,7 @@ class UrlLoader {
167
163
  const headers = Object.assign({
168
164
  accept,
169
165
  }, options === null || options === void 0 ? void 0 : options.headers, ((_b = request.extensions) === null || _b === void 0 ? void 0 : _b.headers) || {});
170
- const query = (0, graphql_1.print)(request.document);
166
+ const query = print(request.document);
171
167
  const requestBody = {
172
168
  query,
173
169
  variables: request.variables,
@@ -183,7 +179,7 @@ class UrlLoader {
183
179
  }, options.timeout);
184
180
  }
185
181
  const credentials = (options === null || options === void 0 ? void 0 : options.credentials) !== 'disable' ? (options === null || options === void 0 ? void 0 : options.credentials) || 'same-origin' : null;
186
- return new value_or_promise_1.ValueOrPromise(() => {
182
+ return new ValueOrPromise(() => {
187
183
  switch (method) {
188
184
  case 'GET':
189
185
  const finalUrl = this.prepareGETUrl({
@@ -198,7 +194,7 @@ class UrlLoader {
198
194
  });
199
195
  case 'POST':
200
196
  if (options === null || options === void 0 ? void 0 : options.multipart) {
201
- return new value_or_promise_1.ValueOrPromise(() => this.createFormDataFromVariables(requestBody))
197
+ return new ValueOrPromise(() => this.createFormDataFromVariables(requestBody))
202
198
  .then(form => fetch(endpoint, {
203
199
  method: 'POST',
204
200
  ...(credentials != null ? { credentials } : {}),
@@ -232,10 +228,10 @@ class UrlLoader {
232
228
  }
233
229
  const contentType = fetchResult.headers.get('content-type');
234
230
  if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('text/event-stream')) {
235
- return (0, handleEventStreamResponse_js_1.handleEventStreamResponse)(fetchResult).then(resultStream => (0, addCancelToResponseStream_js_1.addCancelToResponseStream)(resultStream, controller));
231
+ return handleEventStreamResponse(fetchResult).then(resultStream => addCancelToResponseStream(resultStream, controller));
236
232
  }
237
233
  else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('multipart/mixed')) {
238
- return (0, handleMultipartMixedResponse_js_1.handleMultipartMixedResponse)(fetchResult).then(resultStream => (0, addCancelToResponseStream_js_1.addCancelToResponseStream)(resultStream, controller));
234
+ return handleMultipartMixedResponse(fetchResult).then(resultStream => addCancelToResponseStream(resultStream, controller));
239
235
  }
240
236
  return fetchResult.text();
241
237
  })
@@ -267,7 +263,7 @@ class UrlLoader {
267
263
  }
268
264
  throw new Error('No result');
269
265
  }
270
- return new value_or_promise_1.ValueOrPromise(() => executor(request))
266
+ return new ValueOrPromise(() => executor(request))
271
267
  .then(res => {
272
268
  var _a;
273
269
  result = res;
@@ -292,15 +288,15 @@ class UrlLoader {
292
288
  https: 'wss',
293
289
  http: 'ws',
294
290
  });
295
- const subscriptionClient = (0, graphql_ws_1.createClient)({
291
+ const subscriptionClient = createClient({
296
292
  url: WS_URL,
297
293
  webSocketImpl,
298
294
  connectionParams,
299
295
  lazy: true,
300
296
  });
301
297
  return ({ document, variables, operationName, extensions }) => {
302
- const query = (0, graphql_1.print)(document);
303
- return (0, utils_1.observableToAsyncIterable)({
298
+ const query = print(document);
299
+ return observableToAsyncIterable({
304
300
  subscribe: observer => {
305
301
  const unsubscribe = subscriptionClient.subscribe({
306
302
  query,
@@ -340,7 +336,7 @@ class UrlLoader {
340
336
  break;
341
337
  }
342
338
  websocket.send(JSON.stringify({
343
- type: utils_js_1.LEGACY_WS.CONNECTION_INIT,
339
+ type: LEGACY_WS.CONNECTION_INIT,
344
340
  payload,
345
341
  }));
346
342
  };
@@ -348,7 +344,7 @@ class UrlLoader {
348
344
  const cleanupWebsocket = () => {
349
345
  if (websocket != null && observerById.size === 0) {
350
346
  websocket.send(JSON.stringify({
351
- type: utils_js_1.LEGACY_WS.CONNECTION_TERMINATE,
347
+ type: LEGACY_WS.CONNECTION_TERMINATE,
352
348
  }));
353
349
  websocket.terminate();
354
350
  websocket = null;
@@ -356,7 +352,7 @@ class UrlLoader {
356
352
  };
357
353
  return function legacyExecutor(request) {
358
354
  const id = Date.now().toString();
359
- return (0, utils_1.observableToAsyncIterable)({
355
+ return observableToAsyncIterable({
360
356
  subscribe(observer) {
361
357
  ensureWebsocket();
362
358
  if (websocket == null) {
@@ -365,38 +361,38 @@ class UrlLoader {
365
361
  websocket.onmessage = event => {
366
362
  const data = JSON.parse(event.data.toString('utf-8'));
367
363
  switch (data.type) {
368
- case utils_js_1.LEGACY_WS.CONNECTION_ACK: {
364
+ case LEGACY_WS.CONNECTION_ACK: {
369
365
  if (websocket == null) {
370
366
  throw new Error(`WebSocket connection is not found!`);
371
367
  }
372
368
  websocket.send(JSON.stringify({
373
- type: utils_js_1.LEGACY_WS.START,
369
+ type: LEGACY_WS.START,
374
370
  id,
375
371
  payload: {
376
- query: (0, graphql_1.print)(request.document),
372
+ query: print(request.document),
377
373
  variables: request.variables,
378
374
  operationName: request.operationName,
379
375
  },
380
376
  }));
381
377
  break;
382
378
  }
383
- case utils_js_1.LEGACY_WS.CONNECTION_ERROR: {
379
+ case LEGACY_WS.CONNECTION_ERROR: {
384
380
  observer.error(data.payload);
385
381
  break;
386
382
  }
387
- case utils_js_1.LEGACY_WS.CONNECTION_KEEP_ALIVE: {
383
+ case LEGACY_WS.CONNECTION_KEEP_ALIVE: {
388
384
  break;
389
385
  }
390
- case utils_js_1.LEGACY_WS.DATA: {
386
+ case LEGACY_WS.DATA: {
391
387
  observer.next(data.payload);
392
388
  break;
393
389
  }
394
- case utils_js_1.LEGACY_WS.COMPLETE: {
390
+ case LEGACY_WS.COMPLETE: {
395
391
  if (websocket == null) {
396
392
  throw new Error(`WebSocket connection is not found!`);
397
393
  }
398
394
  websocket.send(JSON.stringify({
399
- type: utils_js_1.LEGACY_WS.CONNECTION_TERMINATE,
395
+ type: LEGACY_WS.CONNECTION_TERMINATE,
400
396
  }));
401
397
  observer.complete();
402
398
  cleanupWebsocket();
@@ -407,7 +403,7 @@ class UrlLoader {
407
403
  return {
408
404
  unsubscribe: () => {
409
405
  websocket === null || websocket === void 0 ? void 0 : websocket.send(JSON.stringify({
410
- type: utils_js_1.LEGACY_WS.STOP,
406
+ type: LEGACY_WS.STOP,
411
407
  id,
412
408
  }));
413
409
  cleanupWebsocket();
@@ -421,7 +417,7 @@ class UrlLoader {
421
417
  if (customFetch) {
422
418
  if (typeof customFetch === 'string') {
423
419
  const [moduleName, fetchFnName] = customFetch.split('#');
424
- return new value_or_promise_1.ValueOrPromise(() => importFn(moduleName))
420
+ return new ValueOrPromise(() => importFn(moduleName))
425
421
  .then(module => (fetchFnName ? module[fetchFnName] : module))
426
422
  .resolve();
427
423
  }
@@ -430,10 +426,10 @@ class UrlLoader {
430
426
  }
431
427
  }
432
428
  if (importFn === asyncImport) {
433
- return defaultAsyncFetch_js_1.defaultAsyncFetch;
429
+ return defaultAsyncFetch;
434
430
  }
435
431
  else {
436
- return defaultSyncFetch_js_1.defaultSyncFetch;
432
+ return defaultSyncFetch;
437
433
  }
438
434
  }
439
435
  getDefaultMethodFromOptions(method, defaultMethod) {
@@ -445,12 +441,12 @@ class UrlLoader {
445
441
  getWebSocketImpl(importFn, options) {
446
442
  if (typeof (options === null || options === void 0 ? void 0 : options.webSocketImpl) === 'string') {
447
443
  const [moduleName, webSocketImplName] = options.webSocketImpl.split('#');
448
- return new value_or_promise_1.ValueOrPromise(() => importFn(moduleName))
444
+ return new ValueOrPromise(() => importFn(moduleName))
449
445
  .then(importedModule => (webSocketImplName ? importedModule[webSocketImplName] : importedModule))
450
446
  .resolve();
451
447
  }
452
448
  else {
453
- const websocketImpl = (options === null || options === void 0 ? void 0 : options.webSocketImpl) || isomorphic_ws_1.default;
449
+ const websocketImpl = (options === null || options === void 0 ? void 0 : options.webSocketImpl) || WebSocket;
454
450
  return websocketImpl;
455
451
  }
456
452
  }
@@ -467,7 +463,7 @@ class UrlLoader {
467
463
  return this.buildHTTPExecutor(subscriptionsEndpoint, fetch, options);
468
464
  }
469
465
  else {
470
- const webSocketImpl$ = new value_or_promise_1.ValueOrPromise(() => this.getWebSocketImpl(importFn, options));
466
+ const webSocketImpl$ = new ValueOrPromise(() => this.getWebSocketImpl(importFn, options));
471
467
  const executor$ = webSocketImpl$.then(webSocketImpl => {
472
468
  if ((options === null || options === void 0 ? void 0 : options.subscriptionsProtocol) === SubscriptionProtocol.LEGACY_WS) {
473
469
  return this.buildWSLegacyExecutor(subscriptionsEndpoint, webSocketImpl, options);
@@ -480,7 +476,7 @@ class UrlLoader {
480
476
  }
481
477
  }
482
478
  getExecutor(endpoint, importFn, options) {
483
- const fetch$ = new value_or_promise_1.ValueOrPromise(() => this.getFetch(options === null || options === void 0 ? void 0 : options.customFetch, importFn));
479
+ const fetch$ = new ValueOrPromise(() => this.getFetch(options === null || options === void 0 ? void 0 : options.customFetch, importFn));
484
480
  const httpExecutor$ = fetch$.then(fetch => {
485
481
  return this.buildHTTPExecutor(endpoint, fetch, options);
486
482
  });
@@ -491,9 +487,9 @@ class UrlLoader {
491
487
  });
492
488
  // eslint-disable-next-line no-inner-declarations
493
489
  function getExecutorByRequest(request) {
494
- const operationAst = (0, utils_1.getOperationASTFromRequest)(request);
490
+ const operationAst = getOperationASTFromRequest(request);
495
491
  if (operationAst.operation === 'subscription' ||
496
- (0, graphql_live_query_1.isLiveQueryOperationDefinitionNode)(operationAst, request.variables)) {
492
+ isLiveQueryOperationDefinitionNode(operationAst, request.variables)) {
497
493
  return subscriptionExecutor$;
498
494
  }
499
495
  else {
@@ -516,12 +512,12 @@ class UrlLoader {
516
512
  }
517
513
  handleSDL(pointer, fetch, options) {
518
514
  const defaultMethod = this.getDefaultMethodFromOptions(options === null || options === void 0 ? void 0 : options.method, 'GET');
519
- return new value_or_promise_1.ValueOrPromise(() => fetch(pointer, {
515
+ return new ValueOrPromise(() => fetch(pointer, {
520
516
  method: defaultMethod,
521
517
  headers: options.headers,
522
518
  }))
523
519
  .then(response => response.text())
524
- .then(schemaString => (0, utils_1.parseGraphQLSDL)(pointer, schemaString, options))
520
+ .then(schemaString => parseGraphQLSDL(pointer, schemaString, options))
525
521
  .resolve();
526
522
  }
527
523
  async load(pointer, options) {
@@ -541,14 +537,14 @@ class UrlLoader {
541
537
  source.schema =
542
538
  source.schema ||
543
539
  (source.document
544
- ? (0, graphql_1.buildASTSchema)(source.document, options)
540
+ ? buildASTSchema(source.document, options)
545
541
  : source.rawSDL
546
- ? (0, graphql_1.buildSchema)(source.rawSDL, options)
542
+ ? buildSchema(source.rawSDL, options)
547
543
  : undefined);
548
544
  }
549
545
  else {
550
546
  executor = this.getExecutorAsync(pointer, options);
551
- source.schema = await (0, wrap_1.introspectSchema)(executor, {}, options);
547
+ source.schema = await introspectSchema(executor, {}, options);
552
548
  }
553
549
  if (!source.schema) {
554
550
  throw new Error(`Invalid introspected schema`);
@@ -557,7 +553,7 @@ class UrlLoader {
557
553
  executor = this.getExecutorAsync(options.endpoint, options);
558
554
  }
559
555
  if (executor) {
560
- source.schema = (0, wrap_1.wrapSchema)({
556
+ source.schema = wrapSchema({
561
557
  schema: source.schema,
562
558
  executor,
563
559
  batch: options === null || options === void 0 ? void 0 : options.batch,
@@ -582,14 +578,14 @@ class UrlLoader {
582
578
  source.schema =
583
579
  source.schema ||
584
580
  (source.document
585
- ? (0, graphql_1.buildASTSchema)(source.document, options)
581
+ ? buildASTSchema(source.document, options)
586
582
  : source.rawSDL
587
- ? (0, graphql_1.buildSchema)(source.rawSDL, options)
583
+ ? buildSchema(source.rawSDL, options)
588
584
  : undefined);
589
585
  }
590
586
  else {
591
587
  executor = this.getExecutorSync(pointer, options);
592
- source.schema = (0, wrap_1.introspectSchema)(executor, {}, options);
588
+ source.schema = introspectSchema(executor, {}, options);
593
589
  }
594
590
  if (!source.schema) {
595
591
  throw new Error(`Invalid introspected schema`);
@@ -598,7 +594,7 @@ class UrlLoader {
598
594
  executor = this.getExecutorSync(options.endpoint, options);
599
595
  }
600
596
  if (executor) {
601
- source.schema = (0, wrap_1.wrapSchema)({
597
+ source.schema = wrapSchema({
602
598
  schema: source.schema,
603
599
  executor,
604
600
  });
@@ -606,7 +602,6 @@ class UrlLoader {
606
602
  return [source];
607
603
  }
608
604
  }
609
- exports.UrlLoader = UrlLoader;
610
605
  function switchProtocols(pointer, protocolMap) {
611
606
  return Object.entries(protocolMap).reduce((prev, [source, target]) => prev.replace(`${source}://`, `${target}://`).replace(`${source}:\\`, `${target}:\\`), pointer);
612
607
  }
@@ -1,19 +1,13 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LEGACY_WS = exports.isPromiseLike = exports.isGraphQLUpload = exports.isBlob = void 0;
4
- function isBlob(obj) {
1
+ export function isBlob(obj) {
5
2
  return typeof obj.arrayBuffer === 'function';
6
3
  }
7
- exports.isBlob = isBlob;
8
- function isGraphQLUpload(upload) {
4
+ export function isGraphQLUpload(upload) {
9
5
  return typeof upload.createReadStream === 'function';
10
6
  }
11
- exports.isGraphQLUpload = isGraphQLUpload;
12
- function isPromiseLike(obj) {
7
+ export function isPromiseLike(obj) {
13
8
  return typeof obj.then === 'function';
14
9
  }
15
- exports.isPromiseLike = isPromiseLike;
16
- var LEGACY_WS;
10
+ export var LEGACY_WS;
17
11
  (function (LEGACY_WS) {
18
12
  LEGACY_WS["CONNECTION_INIT"] = "connection_init";
19
13
  LEGACY_WS["CONNECTION_ACK"] = "connection_ack";
@@ -25,4 +19,4 @@ var LEGACY_WS;
25
19
  LEGACY_WS["DATA"] = "data";
26
20
  LEGACY_WS["ERROR"] = "error";
27
21
  LEGACY_WS["COMPLETE"] = "complete";
28
- })(LEGACY_WS = exports.LEGACY_WS || (exports.LEGACY_WS = {}));
22
+ })(LEGACY_WS || (LEGACY_WS = {}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@graphql-tools/url-loader",
3
- "version": "7.12.2-alpha-b93d3b57.0",
3
+ "version": "7.12.2",
4
4
  "description": "A set of utils for faster development of GraphQL tools",
5
5
  "sideEffects": false,
6
6
  "peerDependencies": {
@@ -0,0 +1 @@
1
+ export declare function addCancelToResponseStream<T>(resultStream: AsyncIterable<T>, controller: AbortController): AsyncIterable<T>;
@@ -0,0 +1,3 @@
1
+ import { fetch } from '@whatwg-node/fetch';
2
+ export declare type AsyncFetchFn = typeof fetch;
3
+ export declare const defaultAsyncFetch: AsyncFetchFn;
@@ -0,0 +1,6 @@
1
+ export declare const defaultSyncFetch: SyncFetchFn;
2
+ export declare type SyncFetchFn = (input: RequestInfo, init?: RequestInit) => SyncResponse;
3
+ export declare type SyncResponse = Omit<Response, 'json' | 'text'> & {
4
+ json: () => any;
5
+ text: () => string;
6
+ };
@@ -0,0 +1,2 @@
1
+ import { ExecutionResult } from 'graphql';
2
+ export declare function handleEventStreamResponse(response: Response): Promise<AsyncGenerator<ExecutionResult>>;
@@ -0,0 +1 @@
1
+ export declare function handleReadable(readable: AsyncIterable<Uint8Array | string>): AsyncGenerator<any, void, unknown>;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Represents a message sent in an event stream
3
+ * https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format
4
+ */
5
+ export interface EventSourceMessage {
6
+ /** The event ID to set the EventSource object's last event ID value. */
7
+ id: string;
8
+ /** A string identifying the type of event described. */
9
+ event: string;
10
+ /** The event data */
11
+ data: string;
12
+ /** The reconnection interval (in milliseconds) to wait before retrying the connection */
13
+ retry?: number;
14
+ }
15
+ export declare function handleReadableStream(stream: ReadableStream<Uint8Array>): AsyncGenerator<any, void, unknown>;
@@ -0,0 +1,2 @@
1
+ import type { ExecutionResult } from 'graphql';
2
+ export declare function handleMultipartMixedResponse(response: Response): Promise<AsyncIterableIterator<ExecutionResult<import("graphql/jsutils/ObjMap").ObjMap<unknown>, import("graphql/jsutils/ObjMap").ObjMap<unknown>> | undefined>>;
@@ -0,0 +1,151 @@
1
+ /// <reference types="ws" />
2
+ /// <reference lib="dom" />
3
+ import { IntrospectionOptions } from 'graphql';
4
+ import { AsyncExecutor, Executor, SyncExecutor, Source, Loader, BaseLoaderOptions } from '@graphql-tools/utils';
5
+ import { ClientOptions } from 'graphql-ws';
6
+ import WebSocket from 'isomorphic-ws';
7
+ import { AsyncFetchFn } from './defaultAsyncFetch.js';
8
+ import { SyncFetchFn } from './defaultSyncFetch.js';
9
+ export declare type FetchFn = AsyncFetchFn | SyncFetchFn;
10
+ export declare type AsyncImportFn = (moduleName: string) => PromiseLike<any>;
11
+ export declare type SyncImportFn = (moduleName: string) => any;
12
+ declare type HeadersConfig = Record<string, string>;
13
+ interface ExecutionExtensions {
14
+ headers?: HeadersConfig;
15
+ endpoint?: string;
16
+ }
17
+ export declare enum SubscriptionProtocol {
18
+ WS = "WS",
19
+ /**
20
+ * Use legacy web socket protocol `graphql-ws` instead of the more current standard `graphql-transport-ws`
21
+ */
22
+ LEGACY_WS = "LEGACY_WS",
23
+ /**
24
+ * Use SSE for subscription instead of WebSocket
25
+ */
26
+ SSE = "SSE",
27
+ /**
28
+ * Use `graphql-sse` for subscriptions
29
+ */
30
+ GRAPHQL_SSE = "GRAPHQL_SSE"
31
+ }
32
+ /**
33
+ * Additional options for loading from a URL
34
+ */
35
+ export interface LoadFromUrlOptions extends BaseLoaderOptions, Partial<IntrospectionOptions> {
36
+ /**
37
+ * Additional headers to include when querying the original schema
38
+ */
39
+ headers?: HeadersConfig;
40
+ /**
41
+ * A custom `fetch` implementation to use when querying the original schema.
42
+ * Defaults to `cross-fetch`
43
+ */
44
+ customFetch?: FetchFn | string;
45
+ /**
46
+ * HTTP method to use when querying the original schema.
47
+ */
48
+ method?: 'GET' | 'POST';
49
+ /**
50
+ * Custom WebSocket implementation used by the loaded schema if subscriptions
51
+ * are enabled
52
+ */
53
+ webSocketImpl?: typeof WebSocket | string;
54
+ /**
55
+ * Whether to use the GET HTTP method for queries when querying the original schema
56
+ */
57
+ useGETForQueries?: boolean;
58
+ /**
59
+ * Use multipart for POST requests
60
+ */
61
+ multipart?: boolean;
62
+ /**
63
+ * Handle URL as schema SDL
64
+ */
65
+ handleAsSDL?: boolean;
66
+ /**
67
+ * Regular HTTP endpoint; defaults to the pointer
68
+ */
69
+ endpoint?: string;
70
+ /**
71
+ * Subscriptions endpoint; defaults to the endpoint given as HTTP endpoint
72
+ */
73
+ subscriptionsEndpoint?: string;
74
+ /**
75
+ * Use specific protocol for subscriptions
76
+ */
77
+ subscriptionsProtocol?: SubscriptionProtocol;
78
+ /**
79
+ * @deprecated This is no longer used. Will be removed in the next release
80
+ */
81
+ graphqlSseOptions?: any;
82
+ /**
83
+ * Retry attempts
84
+ */
85
+ retry?: number;
86
+ /**
87
+ * Timeout in milliseconds
88
+ */
89
+ timeout?: number;
90
+ /**
91
+ * Request Credentials (default: 'same-origin')
92
+ * You can pass `disable` if you don't want this to be set in `Request`
93
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
94
+ */
95
+ credentials?: RequestCredentials | 'disable';
96
+ /**
97
+ * Connection Parameters for WebSockets connection
98
+ */
99
+ connectionParams?: any;
100
+ /**
101
+ * Enable Batching
102
+ */
103
+ batch?: boolean;
104
+ }
105
+ /**
106
+ * This loader loads a schema from a URL. The loaded schema is a fully-executable,
107
+ * remote schema since it's created using [@graphql-tools/wrap](/docs/remote-schemas).
108
+ *
109
+ * ```
110
+ * const schema = await loadSchema('http://localhost:3000/graphql', {
111
+ * loaders: [
112
+ * new UrlLoader(),
113
+ * ]
114
+ * });
115
+ * ```
116
+ */
117
+ export declare class UrlLoader implements Loader<LoadFromUrlOptions> {
118
+ createFormDataFromVariables<TVariables>({ query, variables, operationName, extensions, }: {
119
+ query: string;
120
+ variables: TVariables;
121
+ operationName?: string;
122
+ extensions?: any;
123
+ }): FormData | Promise<FormData>;
124
+ prepareGETUrl({ baseUrl, query, variables, operationName, extensions, }: {
125
+ baseUrl: string;
126
+ query: string;
127
+ variables: any;
128
+ operationName?: string;
129
+ extensions?: any;
130
+ }): string;
131
+ buildHTTPExecutor(endpoint: string, fetch: SyncFetchFn, options?: LoadFromUrlOptions): SyncExecutor<any, ExecutionExtensions>;
132
+ buildHTTPExecutor(endpoint: string, fetch: AsyncFetchFn, options?: LoadFromUrlOptions): AsyncExecutor<any, ExecutionExtensions>;
133
+ buildWSExecutor(subscriptionsEndpoint: string, webSocketImpl: typeof WebSocket, connectionParams?: ClientOptions['connectionParams']): Executor;
134
+ buildWSLegacyExecutor(subscriptionsEndpoint: string, WebSocketImpl: typeof WebSocket, options?: LoadFromUrlOptions): Executor;
135
+ getFetch(customFetch: LoadFromUrlOptions['customFetch'], importFn: AsyncImportFn): PromiseLike<AsyncFetchFn> | AsyncFetchFn;
136
+ getFetch(customFetch: LoadFromUrlOptions['customFetch'], importFn: SyncImportFn): SyncFetchFn;
137
+ private getDefaultMethodFromOptions;
138
+ getWebSocketImpl(importFn: AsyncImportFn, options?: LoadFromUrlOptions): PromiseLike<typeof WebSocket>;
139
+ getWebSocketImpl(importFn: SyncImportFn, options?: LoadFromUrlOptions): typeof WebSocket;
140
+ buildSubscriptionExecutor(subscriptionsEndpoint: string, fetch: SyncFetchFn, syncImport: SyncImportFn, options?: LoadFromUrlOptions): SyncExecutor;
141
+ buildSubscriptionExecutor(subscriptionsEndpoint: string, fetch: AsyncFetchFn, asyncImport: AsyncImportFn, options?: LoadFromUrlOptions): AsyncExecutor;
142
+ getExecutor(endpoint: string, asyncImport: AsyncImportFn, options?: Omit<LoadFromUrlOptions, 'endpoint'>): AsyncExecutor;
143
+ getExecutor(endpoint: string, syncImport: SyncImportFn, options?: Omit<LoadFromUrlOptions, 'endpoint'>): SyncExecutor;
144
+ getExecutorAsync(endpoint: string, options?: Omit<LoadFromUrlOptions, 'endpoint'>): AsyncExecutor;
145
+ getExecutorSync(endpoint: string, options?: Omit<LoadFromUrlOptions, 'endpoint'>): SyncExecutor;
146
+ handleSDL(pointer: string, fetch: SyncFetchFn, options: LoadFromUrlOptions): Source;
147
+ handleSDL(pointer: string, fetch: AsyncFetchFn, options: LoadFromUrlOptions): Promise<Source>;
148
+ load(pointer: string, options: LoadFromUrlOptions): Promise<Source[]>;
149
+ loadSync(pointer: string, options: LoadFromUrlOptions): Source[];
150
+ }
151
+ export {};
@@ -0,0 +1,23 @@
1
+ /// <reference types="node" />
2
+ import type { Readable } from 'stream';
3
+ export declare function isBlob(obj: any): obj is Blob;
4
+ interface GraphQLUpload {
5
+ filename: string;
6
+ mimetype: string;
7
+ createReadStream: () => Readable;
8
+ }
9
+ export declare function isGraphQLUpload(upload: any): upload is GraphQLUpload;
10
+ export declare function isPromiseLike(obj: any): obj is PromiseLike<any>;
11
+ export declare enum LEGACY_WS {
12
+ CONNECTION_INIT = "connection_init",
13
+ CONNECTION_ACK = "connection_ack",
14
+ CONNECTION_ERROR = "connection_error",
15
+ CONNECTION_KEEP_ALIVE = "ka",
16
+ START = "start",
17
+ STOP = "stop",
18
+ CONNECTION_TERMINATE = "connection_terminate",
19
+ DATA = "data",
20
+ ERROR = "error",
21
+ COMPLETE = "complete"
22
+ }
23
+ export {};
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.addCancelToResponseStream = void 0;
4
- const utils_1 = require("@graphql-tools/utils");
5
- function addCancelToResponseStream(resultStream, controller) {
6
- return (0, utils_1.withCancel)(resultStream, () => {
7
- if (!controller.signal.aborted) {
8
- controller.abort();
9
- }
10
- });
11
- }
12
- exports.addCancelToResponseStream = addCancelToResponseStream;
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.defaultAsyncFetch = void 0;
4
- const fetch_1 = require("@whatwg-node/fetch");
5
- const defaultAsyncFetch = async (input, init) => {
6
- return (0, fetch_1.fetch)(input, init);
7
- };
8
- exports.defaultAsyncFetch = defaultAsyncFetch;
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.defaultSyncFetch = void 0;
4
- const tslib_1 = require("tslib");
5
- const sync_fetch_1 = tslib_1.__importDefault(require("sync-fetch"));
6
- const defaultSyncFetch = (input, init) => {
7
- if (typeof input === 'string') {
8
- init === null || init === void 0 ? true : delete init.signal;
9
- }
10
- else {
11
- delete input.signal;
12
- }
13
- return (0, sync_fetch_1.default)(input, init);
14
- };
15
- exports.defaultSyncFetch = defaultSyncFetch;
@@ -1,18 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.handleEventStreamResponse = void 0;
4
- const utils_1 = require("@graphql-tools/utils");
5
- const handleReadable_js_1 = require("./handleReadable.js");
6
- const handleReadableStream_js_1 = require("./handleReadableStream.js");
7
- async function handleEventStreamResponse(response) {
8
- // node-fetch returns body as a promise so we need to resolve it
9
- const body = await response.body;
10
- if (body) {
11
- if ((0, utils_1.isAsyncIterable)(body)) {
12
- return (0, handleReadable_js_1.handleReadable)(body);
13
- }
14
- return (0, handleReadableStream_js_1.handleReadableStream)(body);
15
- }
16
- throw new Error('Response body is expected to be a readable stream but got; ' + (0, utils_1.inspect)(body));
17
- }
18
- exports.handleEventStreamResponse = handleEventStreamResponse;