UNPKG

22.5 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var core = require('@urql/core');
6var jotai = require('jotai');
7var wonka = require('wonka');
8
9var DEFAULT_URL = function () {
10 try {
11 return process.env.JOTAI_URQL_DEFAULT_URL;
12 } catch (_unused) {
13 return undefined;
14 }
15}() || '/graphql';
16
17var clientAtom = jotai.atom(core.createClient({
18 url: DEFAULT_URL
19}));
20
21function _regeneratorRuntime() {
22 /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
23
24 _regeneratorRuntime = function () {
25 return exports;
26 };
27
28 var exports = {},
29 Op = Object.prototype,
30 hasOwn = Op.hasOwnProperty,
31 $Symbol = "function" == typeof Symbol ? Symbol : {},
32 iteratorSymbol = $Symbol.iterator || "@@iterator",
33 asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
34 toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
35
36 function define(obj, key, value) {
37 return Object.defineProperty(obj, key, {
38 value: value,
39 enumerable: !0,
40 configurable: !0,
41 writable: !0
42 }), obj[key];
43 }
44
45 try {
46 define({}, "");
47 } catch (err) {
48 define = function (obj, key, value) {
49 return obj[key] = value;
50 };
51 }
52
53 function wrap(innerFn, outerFn, self, tryLocsList) {
54 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
55 generator = Object.create(protoGenerator.prototype),
56 context = new Context(tryLocsList || []);
57 return generator._invoke = function (innerFn, self, context) {
58 var state = "suspendedStart";
59 return function (method, arg) {
60 if ("executing" === state) throw new Error("Generator is already running");
61
62 if ("completed" === state) {
63 if ("throw" === method) throw arg;
64 return doneResult();
65 }
66
67 for (context.method = method, context.arg = arg;;) {
68 var delegate = context.delegate;
69
70 if (delegate) {
71 var delegateResult = maybeInvokeDelegate(delegate, context);
72
73 if (delegateResult) {
74 if (delegateResult === ContinueSentinel) continue;
75 return delegateResult;
76 }
77 }
78
79 if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
80 if ("suspendedStart" === state) throw state = "completed", context.arg;
81 context.dispatchException(context.arg);
82 } else "return" === context.method && context.abrupt("return", context.arg);
83 state = "executing";
84 var record = tryCatch(innerFn, self, context);
85
86 if ("normal" === record.type) {
87 if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
88 return {
89 value: record.arg,
90 done: context.done
91 };
92 }
93
94 "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
95 }
96 };
97 }(innerFn, self, context), generator;
98 }
99
100 function tryCatch(fn, obj, arg) {
101 try {
102 return {
103 type: "normal",
104 arg: fn.call(obj, arg)
105 };
106 } catch (err) {
107 return {
108 type: "throw",
109 arg: err
110 };
111 }
112 }
113
114 exports.wrap = wrap;
115 var ContinueSentinel = {};
116
117 function Generator() {}
118
119 function GeneratorFunction() {}
120
121 function GeneratorFunctionPrototype() {}
122
123 var IteratorPrototype = {};
124 define(IteratorPrototype, iteratorSymbol, function () {
125 return this;
126 });
127 var getProto = Object.getPrototypeOf,
128 NativeIteratorPrototype = getProto && getProto(getProto(values([])));
129 NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
130 var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
131
132 function defineIteratorMethods(prototype) {
133 ["next", "throw", "return"].forEach(function (method) {
134 define(prototype, method, function (arg) {
135 return this._invoke(method, arg);
136 });
137 });
138 }
139
140 function AsyncIterator(generator, PromiseImpl) {
141 function invoke(method, arg, resolve, reject) {
142 var record = tryCatch(generator[method], generator, arg);
143
144 if ("throw" !== record.type) {
145 var result = record.arg,
146 value = result.value;
147 return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
148 invoke("next", value, resolve, reject);
149 }, function (err) {
150 invoke("throw", err, resolve, reject);
151 }) : PromiseImpl.resolve(value).then(function (unwrapped) {
152 result.value = unwrapped, resolve(result);
153 }, function (error) {
154 return invoke("throw", error, resolve, reject);
155 });
156 }
157
158 reject(record.arg);
159 }
160
161 var previousPromise;
162
163 this._invoke = function (method, arg) {
164 function callInvokeWithMethodAndArg() {
165 return new PromiseImpl(function (resolve, reject) {
166 invoke(method, arg, resolve, reject);
167 });
168 }
169
170 return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
171 };
172 }
173
174 function maybeInvokeDelegate(delegate, context) {
175 var method = delegate.iterator[context.method];
176
177 if (undefined === method) {
178 if (context.delegate = null, "throw" === context.method) {
179 if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
180 context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
181 }
182
183 return ContinueSentinel;
184 }
185
186 var record = tryCatch(method, delegate.iterator, context.arg);
187 if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
188 var info = record.arg;
189 return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
190 }
191
192 function pushTryEntry(locs) {
193 var entry = {
194 tryLoc: locs[0]
195 };
196 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
197 }
198
199 function resetTryEntry(entry) {
200 var record = entry.completion || {};
201 record.type = "normal", delete record.arg, entry.completion = record;
202 }
203
204 function Context(tryLocsList) {
205 this.tryEntries = [{
206 tryLoc: "root"
207 }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
208 }
209
210 function values(iterable) {
211 if (iterable) {
212 var iteratorMethod = iterable[iteratorSymbol];
213 if (iteratorMethod) return iteratorMethod.call(iterable);
214 if ("function" == typeof iterable.next) return iterable;
215
216 if (!isNaN(iterable.length)) {
217 var i = -1,
218 next = function next() {
219 for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
220
221 return next.value = undefined, next.done = !0, next;
222 };
223
224 return next.next = next;
225 }
226 }
227
228 return {
229 next: doneResult
230 };
231 }
232
233 function doneResult() {
234 return {
235 value: undefined,
236 done: !0
237 };
238 }
239
240 return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
241 var ctor = "function" == typeof genFun && genFun.constructor;
242 return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
243 }, exports.mark = function (genFun) {
244 return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
245 }, exports.awrap = function (arg) {
246 return {
247 __await: arg
248 };
249 }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
250 return this;
251 }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
252 void 0 === PromiseImpl && (PromiseImpl = Promise);
253 var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
254 return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
255 return result.done ? result.value : iter.next();
256 });
257 }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
258 return this;
259 }), define(Gp, "toString", function () {
260 return "[object Generator]";
261 }), exports.keys = function (object) {
262 var keys = [];
263
264 for (var key in object) keys.push(key);
265
266 return keys.reverse(), function next() {
267 for (; keys.length;) {
268 var key = keys.pop();
269 if (key in object) return next.value = key, next.done = !1, next;
270 }
271
272 return next.done = !0, next;
273 };
274 }, exports.values = values, Context.prototype = {
275 constructor: Context,
276 reset: function (skipTempReset) {
277 if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
278 },
279 stop: function () {
280 this.done = !0;
281 var rootRecord = this.tryEntries[0].completion;
282 if ("throw" === rootRecord.type) throw rootRecord.arg;
283 return this.rval;
284 },
285 dispatchException: function (exception) {
286 if (this.done) throw exception;
287 var context = this;
288
289 function handle(loc, caught) {
290 return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
291 }
292
293 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
294 var entry = this.tryEntries[i],
295 record = entry.completion;
296 if ("root" === entry.tryLoc) return handle("end");
297
298 if (entry.tryLoc <= this.prev) {
299 var hasCatch = hasOwn.call(entry, "catchLoc"),
300 hasFinally = hasOwn.call(entry, "finallyLoc");
301
302 if (hasCatch && hasFinally) {
303 if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
304 if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
305 } else if (hasCatch) {
306 if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
307 } else {
308 if (!hasFinally) throw new Error("try statement without catch or finally");
309 if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
310 }
311 }
312 }
313 },
314 abrupt: function (type, arg) {
315 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
316 var entry = this.tryEntries[i];
317
318 if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
319 var finallyEntry = entry;
320 break;
321 }
322 }
323
324 finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
325 var record = finallyEntry ? finallyEntry.completion : {};
326 return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
327 },
328 complete: function (record, afterLoc) {
329 if ("throw" === record.type) throw record.arg;
330 return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
331 },
332 finish: function (finallyLoc) {
333 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
334 var entry = this.tryEntries[i];
335 if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
336 }
337 },
338 catch: function (tryLoc) {
339 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
340 var entry = this.tryEntries[i];
341
342 if (entry.tryLoc === tryLoc) {
343 var record = entry.completion;
344
345 if ("throw" === record.type) {
346 var thrown = record.arg;
347 resetTryEntry(entry);
348 }
349
350 return thrown;
351 }
352 }
353
354 throw new Error("illegal catch attempt");
355 },
356 delegateYield: function (iterable, resultName, nextLoc) {
357 return this.delegate = {
358 iterator: values(iterable),
359 resultName: resultName,
360 nextLoc: nextLoc
361 }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
362 }
363 }, exports;
364}
365
366function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
367 try {
368 var info = gen[key](arg);
369 var value = info.value;
370 } catch (error) {
371 reject(error);
372 return;
373 }
374
375 if (info.done) {
376 resolve(value);
377 } else {
378 Promise.resolve(value).then(_next, _throw);
379 }
380}
381
382function _asyncToGenerator(fn) {
383 return function () {
384 var self = this,
385 args = arguments;
386 return new Promise(function (resolve, reject) {
387 var gen = fn.apply(self, args);
388
389 function _next(value) {
390 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
391 }
392
393 function _throw(err) {
394 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
395 }
396
397 _next(undefined);
398 });
399 };
400}
401
402function _extends() {
403 _extends = Object.assign ? Object.assign.bind() : function (target) {
404 for (var i = 1; i < arguments.length; i++) {
405 var source = arguments[i];
406
407 for (var key in source) {
408 if (Object.prototype.hasOwnProperty.call(source, key)) {
409 target[key] = source[key];
410 }
411 }
412 }
413
414 return target;
415 };
416 return _extends.apply(this, arguments);
417}
418
419var isOperationResultWithData$1 = function isOperationResultWithData(result) {
420 return 'data' in result && !result.error;
421};
422
423function atomWithQuery(createQueryArgs, getClient) {
424 if (getClient === void 0) {
425 getClient = function getClient(get) {
426 return get(clientAtom);
427 };
428 }
429
430 var queryResultAtom = jotai.atom(function (get) {
431 var args = createQueryArgs(get);
432
433 if (args.pause) {
434 return null;
435 }
436
437 var client = getClient(get);
438 var resolve = null;
439
440 var makePending = function makePending() {
441 return new Promise(function (r) {
442 resolve = r;
443 });
444 };
445
446 var resultAtom = jotai.atom(makePending());
447 var setResult = null;
448
449 var listener = function listener(result) {
450 if (!resolve && !setResult) {
451 throw new Error('setting result without mount');
452 }
453
454 if (resolve) {
455 resolve(result);
456 resolve = null;
457 }
458
459 if (setResult) {
460 setResult(result);
461 }
462 };
463
464 var subscription = null;
465 var timer;
466
467 var startQuery = function startQuery(opts) {
468 if (subscription) {
469 clearTimeout(timer);
470 subscription.unsubscribe();
471 }
472
473 subscription = wonka.pipe(client.query(args.query, args.variables, _extends({}, args.requestPolicy && {
474 requestPolicy: args.requestPolicy
475 }, args.context, opts)), wonka.subscribe(listener));
476
477 if (!setResult) {
478 timer = setTimeout(function () {
479 if (subscription) {
480 subscription.unsubscribe();
481 subscription = null;
482 }
483 }, 1000);
484 }
485 };
486
487 startQuery();
488
489 resultAtom.onMount = function (update) {
490 setResult = update;
491
492 if (subscription) {
493 clearTimeout(timer);
494 } else {
495 startQuery();
496 }
497
498 return function () {
499 setResult = null;
500
501 if (subscription) {
502 subscription.unsubscribe();
503 subscription = null;
504 }
505 };
506 };
507
508 return {
509 resultAtom: resultAtom,
510 makePending: makePending,
511 startQuery: startQuery
512 };
513 });
514 var queryAtom = jotai.atom(function (get) {
515 var queryResult = get(queryResultAtom);
516
517 if (!queryResult) {
518 return null;
519 }
520
521 var resultAtom = queryResult.resultAtom;
522 var result = get(resultAtom);
523
524 if (!isOperationResultWithData$1(result)) {
525 throw result.error;
526 }
527
528 return result;
529 }, function (get, set, action) {
530 if (action.type === 'reexecute') {
531 console.warn('DEPRECATED [atomWithQuery] use refetch instead of reexecute');
532 action.type = 'refetch';
533 }
534
535 switch (action.type) {
536 case 'refetch':
537 {
538 var queryResult = get(queryResultAtom);
539
540 if (!queryResult) {
541 throw new Error('query is paused');
542 }
543
544 var resultAtom = queryResult.resultAtom,
545 makePending = queryResult.makePending,
546 startQuery = queryResult.startQuery;
547 set(resultAtom, makePending());
548 startQuery(action.opts);
549 return;
550 }
551 }
552 });
553 return queryAtom;
554}
555
556function atomWithMutation(createQuery, getClient) {
557 if (getClient === void 0) {
558 getClient = function getClient(get) {
559 return get(clientAtom);
560 };
561 }
562
563 var operationResultAtom = jotai.atom(new Promise(function () {}));
564 var queryResultAtom = jotai.atom(function (get) {
565 return get(operationResultAtom);
566 }, function () {
567 var _ref = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(get, set, action) {
568 var client, query;
569 return _regeneratorRuntime().wrap(function _callee$(_context) {
570 while (1) {
571 switch (_context.prev = _context.next) {
572 case 0:
573 set(operationResultAtom, new Promise(function () {}));
574 client = getClient(get);
575 query = createQuery(get);
576 return _context.abrupt("return", client.mutation(query, action.variables, action.context).toPromise().then(function (result) {
577 action.callback == null ? void 0 : action.callback(result);
578
579 if (result.error) {
580 throw result.error;
581 }
582
583 set(operationResultAtom, result);
584 }));
585
586 case 4:
587 case "end":
588 return _context.stop();
589 }
590 }
591 }, _callee);
592 }));
593
594 return function (_x, _x2, _x3) {
595 return _ref.apply(this, arguments);
596 };
597 }());
598 return queryResultAtom;
599}
600
601var isOperationResultWithData = function isOperationResultWithData(result) {
602 return 'data' in result && !result.error;
603};
604
605function atomWithSubscription(createSubscriptionArgs, getClient) {
606 if (getClient === void 0) {
607 getClient = function getClient(get) {
608 return get(clientAtom);
609 };
610 }
611
612 var queryResultAtom = jotai.atom(function (get) {
613 var args = createSubscriptionArgs(get);
614
615 if (args.pause) {
616 return null;
617 }
618
619 var client = getClient(get);
620 var resolve = null;
621
622 var makePending = function makePending() {
623 return new Promise(function (r) {
624 resolve = r;
625 });
626 };
627
628 var resultAtom = jotai.atom(makePending());
629 var setResult = null;
630
631 var listener = function listener(result) {
632 if (resolve) {
633 resolve(result);
634 resolve = null;
635 }
636
637 if (setResult) {
638 setResult(result);
639 }
640 };
641
642 var subscription = null;
643 var timer;
644
645 var startSub = function startSub() {
646 if (subscription) {
647 clearTimeout(timer);
648 subscription.unsubscribe();
649 }
650
651 subscription = wonka.pipe(client.subscription(args.query, args.variables, args.context), wonka.subscribe(listener));
652
653 if (!setResult) {
654 timer = setTimeout(function () {
655 if (subscription) {
656 subscription.unsubscribe();
657 subscription = null;
658 }
659 }, 1000);
660 }
661 };
662
663 startSub();
664
665 resultAtom.onMount = function (update) {
666 setResult = update;
667
668 if (subscription) {
669 clearTimeout(timer);
670 } else {
671 startSub();
672 }
673
674 return function () {
675 setResult = null;
676
677 if (subscription) {
678 subscription.unsubscribe();
679 subscription = null;
680 }
681 };
682 };
683
684 return {
685 resultAtom: resultAtom,
686 makePending: makePending,
687 startSub: startSub
688 };
689 });
690 var queryAtom = jotai.atom(function (get) {
691 var queryResult = get(queryResultAtom);
692
693 if (!queryResult) {
694 return null;
695 }
696
697 var resultAtom = queryResult.resultAtom;
698 var result = get(resultAtom);
699
700 if (!isOperationResultWithData(result)) {
701 throw result.error;
702 }
703
704 return result;
705 }, function (get, set, action) {
706 switch (action.type) {
707 case 'refetch':
708 {
709 var queryResult = get(queryResultAtom);
710
711 if (!queryResult) {
712 throw new Error('query is paused');
713 }
714
715 var resultAtom = queryResult.resultAtom,
716 makePending = queryResult.makePending,
717 startSub = queryResult.startSub;
718 set(resultAtom, makePending());
719 startSub();
720 return;
721 }
722 }
723 });
724 return queryAtom;
725}
726
727exports.atomWithMutation = atomWithMutation;
728exports.atomWithQuery = atomWithQuery;
729exports.atomWithSubscription = atomWithSubscription;
730exports.clientAtom = clientAtom;