@avantstay/graphql-ts-client 10.5.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.
@@ -0,0 +1,836 @@
1
+ "use strict";
2
+ function _array_like_to_array(arr, len) {
3
+ if (len == null || len > arr.length) len = arr.length;
4
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
+ return arr2;
6
+ }
7
+ function _array_with_holes(arr) {
8
+ if (Array.isArray(arr)) return arr;
9
+ }
10
+ function _assert_this_initialized(self) {
11
+ if (self === void 0) {
12
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
13
+ }
14
+ return self;
15
+ }
16
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
17
+ try {
18
+ var info = gen[key](arg);
19
+ var value = info.value;
20
+ } catch (error) {
21
+ reject(error);
22
+ return;
23
+ }
24
+ if (info.done) {
25
+ resolve(value);
26
+ } else {
27
+ Promise.resolve(value).then(_next, _throw);
28
+ }
29
+ }
30
+ function _async_to_generator(fn) {
31
+ return function() {
32
+ var self = this, args = arguments;
33
+ return new Promise(function(resolve, reject) {
34
+ var gen = fn.apply(self, args);
35
+ function _next(value) {
36
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
37
+ }
38
+ function _throw(err) {
39
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
40
+ }
41
+ _next(undefined);
42
+ });
43
+ };
44
+ }
45
+ function _class_call_check(instance, Constructor) {
46
+ if (!(instance instanceof Constructor)) {
47
+ throw new TypeError("Cannot call a class as a function");
48
+ }
49
+ }
50
+ function _construct(Parent, args, Class) {
51
+ if (_is_native_reflect_construct()) {
52
+ _construct = Reflect.construct;
53
+ } else {
54
+ _construct = function construct(Parent, args, Class) {
55
+ var a = [
56
+ null
57
+ ];
58
+ a.push.apply(a, args);
59
+ var Constructor = Function.bind.apply(Parent, a);
60
+ var instance = new Constructor();
61
+ if (Class) _set_prototype_of(instance, Class.prototype);
62
+ return instance;
63
+ };
64
+ }
65
+ return _construct.apply(null, arguments);
66
+ }
67
+ function _defineProperties(target, props) {
68
+ for(var i = 0; i < props.length; i++){
69
+ var descriptor = props[i];
70
+ descriptor.enumerable = descriptor.enumerable || false;
71
+ descriptor.configurable = true;
72
+ if ("value" in descriptor) descriptor.writable = true;
73
+ Object.defineProperty(target, descriptor.key, descriptor);
74
+ }
75
+ }
76
+ function _create_class(Constructor, protoProps, staticProps) {
77
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
78
+ if (staticProps) _defineProperties(Constructor, staticProps);
79
+ return Constructor;
80
+ }
81
+ function _define_property(obj, key, value) {
82
+ if (key in obj) {
83
+ Object.defineProperty(obj, key, {
84
+ value: value,
85
+ enumerable: true,
86
+ configurable: true,
87
+ writable: true
88
+ });
89
+ } else {
90
+ obj[key] = value;
91
+ }
92
+ return obj;
93
+ }
94
+ function _get_prototype_of(o) {
95
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
96
+ return o.__proto__ || Object.getPrototypeOf(o);
97
+ };
98
+ return _get_prototype_of(o);
99
+ }
100
+ function _inherits(subClass, superClass) {
101
+ if (typeof superClass !== "function" && superClass !== null) {
102
+ throw new TypeError("Super expression must either be null or a function");
103
+ }
104
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
105
+ constructor: {
106
+ value: subClass,
107
+ writable: true,
108
+ configurable: true
109
+ }
110
+ });
111
+ if (superClass) _set_prototype_of(subClass, superClass);
112
+ }
113
+ function _is_native_function(fn) {
114
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
115
+ }
116
+ function _iterable_to_array_limit(arr, i) {
117
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
118
+ if (_i == null) return;
119
+ var _arr = [];
120
+ var _n = true;
121
+ var _d = false;
122
+ var _s, _e;
123
+ try {
124
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
125
+ _arr.push(_s.value);
126
+ if (i && _arr.length === i) break;
127
+ }
128
+ } catch (err) {
129
+ _d = true;
130
+ _e = err;
131
+ } finally{
132
+ try {
133
+ if (!_n && _i["return"] != null) _i["return"]();
134
+ } finally{
135
+ if (_d) throw _e;
136
+ }
137
+ }
138
+ return _arr;
139
+ }
140
+ function _non_iterable_rest() {
141
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
142
+ }
143
+ function _object_spread(target) {
144
+ for(var i = 1; i < arguments.length; i++){
145
+ var source = arguments[i] != null ? arguments[i] : {};
146
+ var ownKeys = Object.keys(source);
147
+ if (typeof Object.getOwnPropertySymbols === "function") {
148
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
149
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
150
+ }));
151
+ }
152
+ ownKeys.forEach(function(key) {
153
+ _define_property(target, key, source[key]);
154
+ });
155
+ }
156
+ return target;
157
+ }
158
+ function ownKeys(object, enumerableOnly) {
159
+ var keys = Object.keys(object);
160
+ if (Object.getOwnPropertySymbols) {
161
+ var symbols = Object.getOwnPropertySymbols(object);
162
+ if (enumerableOnly) {
163
+ symbols = symbols.filter(function(sym) {
164
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
165
+ });
166
+ }
167
+ keys.push.apply(keys, symbols);
168
+ }
169
+ return keys;
170
+ }
171
+ function _object_spread_props(target, source) {
172
+ source = source != null ? source : {};
173
+ if (Object.getOwnPropertyDescriptors) {
174
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
175
+ } else {
176
+ ownKeys(Object(source)).forEach(function(key) {
177
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
178
+ });
179
+ }
180
+ return target;
181
+ }
182
+ function _possible_constructor_return(self, call) {
183
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
184
+ return call;
185
+ }
186
+ return _assert_this_initialized(self);
187
+ }
188
+ function _set_prototype_of(o, p) {
189
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
190
+ o.__proto__ = p;
191
+ return o;
192
+ };
193
+ return _set_prototype_of(o, p);
194
+ }
195
+ function _sliced_to_array(arr, i) {
196
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
197
+ }
198
+ function _type_of(obj) {
199
+ "@swc/helpers - typeof";
200
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
201
+ }
202
+ function _unsupported_iterable_to_array(o, minLen) {
203
+ if (!o) return;
204
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
205
+ var n = Object.prototype.toString.call(o).slice(8, -1);
206
+ if (n === "Object" && o.constructor) n = o.constructor.name;
207
+ if (n === "Map" || n === "Set") return Array.from(n);
208
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
209
+ }
210
+ function _wrap_native_super(Class) {
211
+ var _cache = typeof Map === "function" ? new Map() : undefined;
212
+ _wrap_native_super = function wrapNativeSuper(Class) {
213
+ if (Class === null || !_is_native_function(Class)) return Class;
214
+ if (typeof Class !== "function") {
215
+ throw new TypeError("Super expression must either be null or a function");
216
+ }
217
+ if (typeof _cache !== "undefined") {
218
+ if (_cache.has(Class)) return _cache.get(Class);
219
+ _cache.set(Class, Wrapper);
220
+ }
221
+ function Wrapper() {
222
+ return _construct(Class, arguments, _get_prototype_of(this).constructor);
223
+ }
224
+ Wrapper.prototype = Object.create(Class.prototype, {
225
+ constructor: {
226
+ value: Wrapper,
227
+ enumerable: false,
228
+ writable: true,
229
+ configurable: true
230
+ }
231
+ });
232
+ return _set_prototype_of(Wrapper, Class);
233
+ };
234
+ return _wrap_native_super(Class);
235
+ }
236
+ function _is_native_reflect_construct() {
237
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
238
+ if (Reflect.construct.sham) return false;
239
+ if (typeof Proxy === "function") return true;
240
+ try {
241
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
242
+ return true;
243
+ } catch (e) {
244
+ return false;
245
+ }
246
+ }
247
+ function _create_super(Derived) {
248
+ var hasNativeReflectConstruct = _is_native_reflect_construct();
249
+ return function _createSuperInternal() {
250
+ var Super = _get_prototype_of(Derived), result;
251
+ if (hasNativeReflectConstruct) {
252
+ var NewTarget = _get_prototype_of(this).constructor;
253
+ result = Reflect.construct(Super, arguments, NewTarget);
254
+ } else {
255
+ result = Super.apply(this, arguments);
256
+ }
257
+ return _possible_constructor_return(this, result);
258
+ };
259
+ }
260
+ function _ts_generator(thisArg, body) {
261
+ var f, y, t, g, _ = {
262
+ label: 0,
263
+ sent: function() {
264
+ if (t[0] & 1) throw t[1];
265
+ return t[1];
266
+ },
267
+ trys: [],
268
+ ops: []
269
+ };
270
+ return(g = {
271
+ next: verb(0),
272
+ "throw": verb(1),
273
+ "return": verb(2)
274
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
275
+ return this;
276
+ }), g);
277
+ function verb(n) {
278
+ return function(v) {
279
+ return step([
280
+ n,
281
+ v
282
+ ]);
283
+ };
284
+ }
285
+ function step(op) {
286
+ if (f) throw new TypeError("Generator is already executing.");
287
+ while(_)try {
288
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
289
+ if (y = 0, t) op = [
290
+ op[0] & 2,
291
+ t.value
292
+ ];
293
+ switch(op[0]){
294
+ case 0:
295
+ case 1:
296
+ t = op;
297
+ break;
298
+ case 4:
299
+ _.label++;
300
+ return {
301
+ value: op[1],
302
+ done: false
303
+ };
304
+ case 5:
305
+ _.label++;
306
+ y = op[1];
307
+ op = [
308
+ 0
309
+ ];
310
+ continue;
311
+ case 7:
312
+ op = _.ops.pop();
313
+ _.trys.pop();
314
+ continue;
315
+ default:
316
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
317
+ _ = 0;
318
+ continue;
319
+ }
320
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
321
+ _.label = op[1];
322
+ break;
323
+ }
324
+ if (op[0] === 6 && _.label < t[1]) {
325
+ _.label = t[1];
326
+ t = op;
327
+ break;
328
+ }
329
+ if (t && _.label < t[2]) {
330
+ _.label = t[2];
331
+ _.ops.push(op);
332
+ break;
333
+ }
334
+ if (t[2]) _.ops.pop();
335
+ _.trys.pop();
336
+ continue;
337
+ }
338
+ op = body.call(thisArg, _);
339
+ } catch (e) {
340
+ op = [
341
+ 6,
342
+ e
343
+ ];
344
+ y = 0;
345
+ } finally{
346
+ f = t = 0;
347
+ }
348
+ if (op[0] & 5) throw op[1];
349
+ return {
350
+ value: op[0] ? op[1] : void 0,
351
+ done: true
352
+ };
353
+ }
354
+ }
355
+ var __create = Object.create;
356
+ var __defProp = Object.defineProperty;
357
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
358
+ var __getOwnPropNames = Object.getOwnPropertyNames;
359
+ var __getProtoOf = Object.getPrototypeOf;
360
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
361
+ var __export = function(target, all) {
362
+ for(var name in all)__defProp(target, name, {
363
+ get: all[name],
364
+ enumerable: true
365
+ });
366
+ };
367
+ var __copyProps = function(to, from, except, desc) {
368
+ if (from && typeof from === "object" || typeof from === "function") {
369
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
370
+ try {
371
+ var _loop = function() {
372
+ var key = _step.value;
373
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
374
+ get: function() {
375
+ return from[key];
376
+ },
377
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
378
+ });
379
+ };
380
+ for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
381
+ } catch (err) {
382
+ _didIteratorError = true;
383
+ _iteratorError = err;
384
+ } finally{
385
+ try {
386
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
387
+ _iterator.return();
388
+ }
389
+ } finally{
390
+ if (_didIteratorError) {
391
+ throw _iteratorError;
392
+ }
393
+ }
394
+ }
395
+ }
396
+ return to;
397
+ };
398
+ var __toESM = function(mod, isNodeMode, target) {
399
+ return target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM
400
+ // file that has been converted to a CommonJS file using a Babel-
401
+ // compatible transform (i.e. "__esModule" has not been set), then set
402
+ // "default" to the CommonJS "module.exports" for node compatibility.
403
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
404
+ value: mod,
405
+ enumerable: true
406
+ }) : target, mod);
407
+ };
408
+ var __toCommonJS = function(mod) {
409
+ return __copyProps(__defProp({}, "__esModule", {
410
+ value: true
411
+ }), mod);
412
+ };
413
+ // src/endpoint.ts
414
+ var endpoint_exports = {};
415
+ __export(endpoint_exports, {
416
+ getApiEndpointCreator: function() {
417
+ return getApiEndpointCreator;
418
+ }
419
+ });
420
+ module.exports = __toCommonJS(endpoint_exports);
421
+ var import_moize = __toESM(require("moize"));
422
+ // src/graphqlRequest.ts
423
+ var import_axios = __toESM(require("axios"));
424
+ // src/types.ts
425
+ var GraphQLClientError = /*#__PURE__*/ function(Error1) {
426
+ _inherits(_GraphQLClientError, Error1);
427
+ var _super = _create_super(_GraphQLClientError);
428
+ function _GraphQLClientError(responseData) {
429
+ _class_call_check(this, _GraphQLClientError);
430
+ var _this;
431
+ _this = _super.call(this);
432
+ _this.responseData = responseData;
433
+ Object.setPrototypeOf(_assert_this_initialized(_this), _GraphQLClientError.prototype);
434
+ return _this;
435
+ }
436
+ _create_class(_GraphQLClientError, [
437
+ {
438
+ key: "message",
439
+ get: function get() {
440
+ return this.response.errors.map(function(it) {
441
+ return it.message;
442
+ }).join(";\n");
443
+ }
444
+ },
445
+ {
446
+ key: "response",
447
+ get: function get() {
448
+ return this.responseData;
449
+ }
450
+ }
451
+ ]);
452
+ return _GraphQLClientError;
453
+ }(_wrap_native_super(Error));
454
+ // src/graphqlRequest.ts
455
+ var sleep = function() {
456
+ var ms = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 0;
457
+ return new Promise(function(resolve) {
458
+ setTimeout(function() {
459
+ return resolve();
460
+ }, ms);
461
+ });
462
+ };
463
+ function graphqlRequest(_) {
464
+ return _graphqlRequest.apply(this, arguments);
465
+ }
466
+ function _graphqlRequest() {
467
+ _graphqlRequest = _async_to_generator(function(param) {
468
+ var _param_shouldRetry, shouldRetry, _param_axios, axios, queryName, client, query, _param_requestHeaders, requestHeaders, variables, failureMode, errorsParser, _lastResponse_errors, lastResponse, maxRetrials, trial, _errors, _errors1, _client_retryConfig, infoParams, _ref, tmp, responseData, headers, status, data, errors, warnings, _client_retryConfig1;
469
+ return _ts_generator(this, function(_state) {
470
+ switch(_state.label){
471
+ case 0:
472
+ _param_shouldRetry = param.shouldRetry, shouldRetry = _param_shouldRetry === void 0 ? true : _param_shouldRetry, _param_axios = param.axios, axios = _param_axios === void 0 ? import_axios.default : _param_axios, queryName = param.queryName, client = param.client, query = param.query, _param_requestHeaders = param.requestHeaders, requestHeaders = _param_requestHeaders === void 0 ? {} : _param_requestHeaders, variables = param.variables, failureMode = param.failureMode, errorsParser = param.errorsParser;
473
+ maxRetrials = shouldRetry ? client.retryConfig.max : 0;
474
+ trial = 0;
475
+ _state.label = 1;
476
+ case 1:
477
+ if (!true) return [
478
+ 3,
479
+ 9
480
+ ];
481
+ infoParams = _object_spread({
482
+ _q: queryName
483
+ }, trial > 0 ? {
484
+ _retrial: trial + 1
485
+ } : {});
486
+ return [
487
+ 4,
488
+ axios.post(client.url, {
489
+ query: query,
490
+ variables: variables,
491
+ operationName: queryName
492
+ }, {
493
+ params: infoParams,
494
+ headers: _object_spread({
495
+ "Content-Type": "application/json"
496
+ }, client.headers, requestHeaders),
497
+ validateStatus: function() {
498
+ return true;
499
+ }
500
+ })
501
+ ];
502
+ case 2:
503
+ _ref = _state.sent(), tmp = _ref.data, responseData = tmp === void 0 ? {} : tmp, headers = _ref.headers, status = _ref.status;
504
+ data = responseData.data, errors = responseData.errors, warnings = responseData.warnings;
505
+ if (status >= 400 && !((_errors = errors) === null || _errors === void 0 ? void 0 : _errors.length)) {
506
+ errors = [
507
+ {
508
+ message: 'Request "'.concat(queryName, '" failed with status ').concat(status)
509
+ }
510
+ ];
511
+ }
512
+ lastResponse = {
513
+ errors: errorsParser ? errorsParser(errors) : errors,
514
+ data: data,
515
+ warnings: warnings,
516
+ headers: headers,
517
+ status: status
518
+ };
519
+ if (!!((_errors1 = errors) === null || _errors1 === void 0 ? void 0 : _errors1.length)) return [
520
+ 3,
521
+ 3
522
+ ];
523
+ return [
524
+ 3,
525
+ 9
526
+ ];
527
+ case 3:
528
+ if (!(trial < maxRetrials && typeof ((_client_retryConfig = client.retryConfig) === null || _client_retryConfig === void 0 ? void 0 : _client_retryConfig.before) === "function")) return [
529
+ 3,
530
+ 7
531
+ ];
532
+ return [
533
+ 4,
534
+ (_client_retryConfig1 = client.retryConfig) === null || _client_retryConfig1 === void 0 ? void 0 : _client_retryConfig1.before({
535
+ queryName: queryName,
536
+ query: query,
537
+ variables: variables,
538
+ response: lastResponse
539
+ })
540
+ ];
541
+ case 4:
542
+ _state.sent();
543
+ if (!client.retryConfig.waitBeforeRetry) return [
544
+ 3,
545
+ 6
546
+ ];
547
+ return [
548
+ 4,
549
+ sleep(client.retryConfig.waitBeforeRetry)
550
+ ];
551
+ case 5:
552
+ _state.sent();
553
+ _state.label = 6;
554
+ case 6:
555
+ return [
556
+ 3,
557
+ 8
558
+ ];
559
+ case 7:
560
+ if (trial >= maxRetrials) {
561
+ return [
562
+ 3,
563
+ 9
564
+ ];
565
+ }
566
+ _state.label = 8;
567
+ case 8:
568
+ trial++;
569
+ return [
570
+ 3,
571
+ 1
572
+ ];
573
+ case 9:
574
+ if (failureMode === "loud" && lastResponse.errors && ((_lastResponse_errors = lastResponse.errors) === null || _lastResponse_errors === void 0 ? void 0 : _lastResponse_errors.length)) {
575
+ throw new GraphQLClientError(lastResponse);
576
+ }
577
+ return [
578
+ 2,
579
+ lastResponse
580
+ ];
581
+ }
582
+ });
583
+ });
584
+ return _graphqlRequest.apply(this, arguments);
585
+ }
586
+ // src/jsonToGraphQLQuery.ts
587
+ var import_omit = __toESM(require("lodash/omit"));
588
+ var VAR_PREFIX = "@@VAR@@";
589
+ var VAR_PREFIX_LENGTH = VAR_PREFIX.length;
590
+ var fromEntries = require("lodash/fromPairs");
591
+ var entries = require("lodash/toPairs");
592
+ var cloneDeep = require("lodash/cloneDeep");
593
+ function jsonToGraphQLQuery(param) {
594
+ var kind = param.kind, queryName = param.queryName, _param_jsonQuery = param.jsonQuery, jsonQuery = _param_jsonQuery === void 0 ? {} : _param_jsonQuery, typesTree = param.typesTree;
595
+ var variablesData = {};
596
+ var alias = jsonQuery.__alias;
597
+ var newJsonQuery = cloneDeep((0, import_omit.default)(jsonQuery, [
598
+ "__alias",
599
+ "__headers"
600
+ ]));
601
+ extractVariables({
602
+ jsonQuery: _define_property({}, queryName, newJsonQuery),
603
+ variables: variablesData,
604
+ parentType: kind === "query" ? typesTree.Query : typesTree.Mutation
605
+ });
606
+ var variablesQuery = Object.keys(variablesData).length ? "(".concat(entries(variablesData).map(function(param) {
607
+ var _param = _sliced_to_array(param, 2), queryName2 = _param[0], type = _param[1].type;
608
+ return "$".concat(queryName2, ": ").concat(type);
609
+ }).join(", "), ")") : "";
610
+ var query = "".concat(kind, " ").concat(alias || queryName).concat(variablesQuery, " { ").concat(alias ? "".concat(alias, ":") : "").concat(queryName).concat(toGraphql(newJsonQuery), " }");
611
+ var variables = fromEntries(entries(variablesData).map(function(param) {
612
+ var _param = _sliced_to_array(param, 2), k = _param[0], v = _param[1];
613
+ return [
614
+ k,
615
+ v.value
616
+ ];
617
+ }));
618
+ return {
619
+ query: query,
620
+ variables: variables
621
+ };
622
+ }
623
+ function extractVariables(param) {
624
+ var jsonQuery = param.jsonQuery, variables = param.variables, parentType = param.parentType;
625
+ if (!parentType) return;
626
+ if (jsonQuery.__args) {
627
+ Object.keys(jsonQuery.__args).forEach(function(k) {
628
+ if (typeof jsonQuery.__args[k] === "string" && jsonQuery.__args[k].startsWith(VAR_PREFIX)) return;
629
+ var variableName = "".concat(k, "_").concat(Math.random().toString(36).substr(2, 4));
630
+ if (jsonQuery.__args[k] !== void 0) {
631
+ variables[variableName] = {
632
+ type: parentType.__args[k],
633
+ value: jsonQuery.__args[k]
634
+ };
635
+ jsonQuery.__args[k] = "".concat(VAR_PREFIX, "$").concat(variableName);
636
+ }
637
+ });
638
+ }
639
+ Object.keys(jsonQuery).filter(function(k) {
640
+ return k !== "__args" && typeof jsonQuery[k] === "object";
641
+ }).forEach(function(k) {
642
+ return extractVariables({
643
+ jsonQuery: jsonQuery[k],
644
+ variables: variables,
645
+ parentType: parentType.hasOwnProperty(k) ? parentType[k] : parentType.__fields ? parentType.__fields[k] : void 0
646
+ });
647
+ });
648
+ }
649
+ function toGraphql(jsonQuery) {
650
+ var fields = entries(jsonQuery).filter(function(param) {
651
+ var _param = _sliced_to_array(param, 2), k = _param[0], v = _param[1];
652
+ return k !== "__args" && v !== false && v !== void 0;
653
+ }).map(function(param) {
654
+ var _param = _sliced_to_array(param, 2), k = _param[0], v = _param[1];
655
+ return typeof v === "object" ? "".concat(k).concat(toGraphql(v)) : k;
656
+ }).join(" ");
657
+ var validArgs = jsonQuery.__args ? entries(jsonQuery.__args).filter(function(param) {
658
+ var _param = _sliced_to_array(param, 2), _ = _param[0], v = _param[1];
659
+ return v !== void 0;
660
+ }) : [];
661
+ var argsQuery = validArgs.length ? "(".concat(validArgs.map(function(param) {
662
+ var _param = _sliced_to_array(param, 2), k = _param[0], v = _param[1];
663
+ return "".concat(k, ":").concat(v.substr(VAR_PREFIX_LENGTH));
664
+ }).join(","), ")") : "";
665
+ return "".concat(argsQuery, " ").concat(fields ? "{ ".concat(fields, " }") : "");
666
+ }
667
+ // src/logging.ts
668
+ function logRequest(logInfo) {
669
+ var identifier = "%c#graphql-ts-client ".concat(logInfo.kind, " ").concat(logInfo.queryName);
670
+ var identifierStyles = "color: transparent; font-size: 0px";
671
+ console.groupCollapsed("%c#graphql-ts-client %c".concat(logInfo.kind, " %c").concat(logInfo.queryName, " %c(").concat(logInfo.duration.toFixed(2), "ms)"), "color: #f90", "color: #999", "color: ".concat(logInfo.response ? "unset" : "#f00", "; font-weight: bold"), "color: #999");
672
+ console.groupCollapsed("%cQuery ".concat(identifier), "color: #999", identifierStyles);
673
+ console.log(logInfo.formatGraphQL(logInfo.query) + identifier, identifierStyles);
674
+ console.groupEnd();
675
+ console.groupCollapsed("%cVariables ".concat(identifier), "color: #999", identifierStyles);
676
+ console.log(JSON.stringify(logInfo.variables, null, " ") + identifier, identifierStyles);
677
+ console.groupEnd();
678
+ console.groupCollapsed("%cTrace ".concat(identifier), "color: #999", identifierStyles);
679
+ console.trace(identifier, identifierStyles);
680
+ console.groupEnd();
681
+ if (logInfo.response) {
682
+ console.log("%cResponse".padEnd(15, " ") + identifier, "color: #999", identifierStyles, logInfo.response);
683
+ }
684
+ if (logInfo.error) {
685
+ console.log("%cError".padEnd(15, " ") + identifier, "color: #999", identifierStyles, logInfo.error);
686
+ }
687
+ console.groupEnd();
688
+ }
689
+ // src/endpoint.ts
690
+ var executeListeners = function(listeners, data) {
691
+ return setTimeout(function() {
692
+ return listeners.forEach(function(runResponseListener) {
693
+ return runResponseListener(data);
694
+ });
695
+ });
696
+ };
697
+ var getApiEndpointCreator = function(apiConfig) {
698
+ return function(kind, queryName) {
699
+ var rawEndpoint = function() {
700
+ var _ref = _async_to_generator(function(failureMode, jsonQuery) {
701
+ var _jsonQuery, _jsonQuery1, _jsonQuery2, _jsonQuery___alias, alias, _jsonQuery___retry, shouldRetry, _jsonQuery___headers, requestHeaders, _jsonToGraphQLQuery, query, variables, start, logOptions, responseListenerData, _data, _ref, data, errors, warnings, headers, status, response, error;
702
+ return _ts_generator(this, function(_state) {
703
+ switch(_state.label){
704
+ case 0:
705
+ alias = (_jsonQuery___alias = (_jsonQuery = jsonQuery) === null || _jsonQuery === void 0 ? void 0 : _jsonQuery.__alias) !== null && _jsonQuery___alias !== void 0 ? _jsonQuery___alias : queryName;
706
+ shouldRetry = (_jsonQuery___retry = (_jsonQuery1 = jsonQuery) === null || _jsonQuery1 === void 0 ? void 0 : _jsonQuery1.__retry) !== null && _jsonQuery___retry !== void 0 ? _jsonQuery___retry : true;
707
+ requestHeaders = (_jsonQuery___headers = (_jsonQuery2 = jsonQuery) === null || _jsonQuery2 === void 0 ? void 0 : _jsonQuery2.__headers) !== null && _jsonQuery___headers !== void 0 ? _jsonQuery___headers : {};
708
+ _jsonToGraphQLQuery = jsonToGraphQLQuery({
709
+ kind: kind,
710
+ queryName: queryName,
711
+ jsonQuery: jsonQuery,
712
+ typesTree: apiConfig.typesTree
713
+ }), query = _jsonToGraphQLQuery.query, variables = _jsonToGraphQLQuery.variables;
714
+ start = +/* @__PURE__ */ new Date();
715
+ logOptions = {
716
+ kind: kind,
717
+ queryName: alias,
718
+ formatGraphQL: apiConfig.formatGraphQL,
719
+ requestHeaders: requestHeaders,
720
+ query: query,
721
+ variables: variables
722
+ };
723
+ responseListenerData = {
724
+ queryName: alias,
725
+ query: apiConfig.formatGraphQL(query),
726
+ variables: variables
727
+ };
728
+ _state.label = 1;
729
+ case 1:
730
+ _state.trys.push([
731
+ 1,
732
+ 3,
733
+ ,
734
+ 4
735
+ ]);
736
+ return [
737
+ 4,
738
+ graphqlRequest({
739
+ shouldRetry: shouldRetry,
740
+ failureMode: failureMode,
741
+ queryName: alias,
742
+ client: apiConfig.getClient(),
743
+ requestHeaders: requestHeaders,
744
+ query: query,
745
+ variables: variables,
746
+ errorsParser: apiConfig.errorsParser
747
+ })
748
+ ];
749
+ case 2:
750
+ _ref = _state.sent(), data = _ref.data, errors = _ref.errors, warnings = _ref.warnings, headers = _ref.headers, status = _ref.status;
751
+ response = {
752
+ data: data,
753
+ warnings: warnings,
754
+ headers: headers,
755
+ status: status,
756
+ errors: errors
757
+ };
758
+ if (apiConfig.verbose && globalThis.document) {
759
+ logRequest(_object_spread_props(_object_spread({}, logOptions), {
760
+ response: response,
761
+ duration: +/* @__PURE__ */ new Date() - start
762
+ }));
763
+ }
764
+ executeListeners(apiConfig.responseListeners, _object_spread_props(_object_spread({}, responseListenerData), {
765
+ response: response
766
+ }));
767
+ return [
768
+ 2,
769
+ {
770
+ data: (_data = data) === null || _data === void 0 ? void 0 : _data[alias],
771
+ errors: errors,
772
+ warnings: warnings,
773
+ headers: headers,
774
+ status: status
775
+ }
776
+ ];
777
+ case 3:
778
+ error = _state.sent();
779
+ if (apiConfig.verbose && globalThis.document) {
780
+ logRequest(_object_spread_props(_object_spread({}, logOptions), {
781
+ error: error,
782
+ duration: +/* @__PURE__ */ new Date() - start
783
+ }));
784
+ }
785
+ executeListeners(apiConfig.responseListeners, _object_spread_props(_object_spread({}, responseListenerData), {
786
+ response: error.response
787
+ }));
788
+ throw error;
789
+ case 4:
790
+ return [
791
+ 2
792
+ ];
793
+ }
794
+ });
795
+ });
796
+ return function rawEndpoint(failureMode, jsonQuery) {
797
+ return _ref.apply(this, arguments);
798
+ };
799
+ }();
800
+ var endpoint = function() {
801
+ var _ref = _async_to_generator(function(jsonQuery) {
802
+ var data;
803
+ return _ts_generator(this, function(_state) {
804
+ switch(_state.label){
805
+ case 0:
806
+ return [
807
+ 4,
808
+ rawEndpoint("loud", jsonQuery)
809
+ ];
810
+ case 1:
811
+ data = _state.sent().data;
812
+ return [
813
+ 2,
814
+ data
815
+ ];
816
+ }
817
+ });
818
+ });
819
+ return function endpoint(jsonQuery) {
820
+ return _ref.apply(this, arguments);
821
+ };
822
+ }();
823
+ var memoizeeOptions = {
824
+ maxAge: apiConfig.maxAge,
825
+ isSerialized: true
826
+ };
827
+ endpoint.raw = rawEndpoint.bind(null, "silent");
828
+ endpoint.memo = (0, import_moize.default)(endpoint, memoizeeOptions);
829
+ endpoint.memoRaw = (0, import_moize.default)(endpoint.raw, memoizeeOptions);
830
+ return endpoint;
831
+ };
832
+ };
833
+ // Annotate the CommonJS export names for ESM import in node:
834
+ 0 && (module.exports = {
835
+ getApiEndpointCreator: getApiEndpointCreator
836
+ });