UNPKG

@lens-protocol/react

Version:

Interacting with the Lens Protocol API using React.

1,216 lines (1,186 loc) 790 kB
import React, { useRef, useEffect, useContext, useState, useCallback, useMemo, useSyncExternalStore } from 'react'; import { Bootstrap, CredentialsExpiredError, LogoutReason, anonymousSessionData, SessionType, ActiveWallet, Logout, Login, UpgradeCredentials } from '@lens-protocol/domain/use-cases/authentication'; export { LogoutReason, SessionType } from '@lens-protocol/domain/use-cases/authentication'; import * as gql from '@lens-protocol/api-bindings'; import { updateSessionData, AuthChallengeDocument, AuthAuthenticateDocument, AuthRefreshDocument, RevokeAuthenticationDocument, SupportedFiatType, FragmentProfile, getSessionData, ProfileDocument, FragmentAnyPublicationInternal, isPostPublication, isCommentPublication, isMirrorPublication, isQuotePublication, PublicationDocument, LensProfileManagerRelayErrorReasonType, RelayErrorReasonType, BroadcastOnMomokaDocument, BroadcastOnchainDocument, recentTransactionsVar, TxStatus, OwnedHandlesDocument, ProfilesManagedDocument, FollowingDocument, ProfileManagersDocument, LensTransactionStatusDocument, LensTransactionStatusType, LensTransactionFailureType, createAuthApolloClient, createLensApolloClient, useSessionDataVar, sessionDataVar, useProfile as useProfile$1, UnspecifiedError, WalletAuthenticationToProfileAuthenticationDocument, DismissRecommendedProfilesDocument, ProfileRecommendationsDocument, ExploreProfilesOrderByType, ExploreProfilesDocument, ExplorePublicationsOrderByType, ExplorePublicationsDocument, FeedDocument, useFeedHighlights as useFeedHighlights$1, SearchProfilesDocument, SearchPublicationsDocument, useCurrencies as useCurrencies$1, chainType, useInvitedProfiles as useInvitedProfiles$1, InviteDocument, ProfileAlreadyInvitedDocument, InvitedProfilesDocument, useLatestPaidActions as useLatestPaidActions$1, useModuleMetadata as useModuleMetadata$1, useModuleMetadataLazyQuery, useHandleToAddressLazyQuery, omitTypename, SignFrameActionDocument, CreateFrameTypedDataDocument, useProfileAlreadyInvited, useProfileAlreadyInvitedLazyQuery, useNotifications as useNotifications$1, AddProfileInterestsDocument, RemoveProfileInterestsDocument, useWhoHaveBlocked, useProfileLazyQuery, useProfilesLazyQuery, useMutualFollowers as useMutualFollowers$1, useProfileActionHistory as useProfileActionHistory$1, FollowersDocument, useProfileManagers as useProfileManagers$1, ProfilesDocument, PeerToPeerRecommendDocument, PeerToPeerUnrecommendDocument, ReportProfileDocument, ProfileReportingReason, ProfileReportingSpamSubreason, ProfileReportingFraudSubreason, useWhoActedOnPublication as useWhoActedOnPublication$1, usePublicationBookmarks, AddPublicationBookmarkDocument, RemovePublicationBookmarkDocument, isPrimaryPublication, HideCommentDocument, UnhideCommentDocument, HidePublicationDocument, usePublicationLazyQuery, usePublicationsLazyQuery, AddPublicationNotInterestedDocument, UndoPublicationNotInterestedDocument, PublicationsDocument, AddReactionDocument, RemoveReactionDocument, PublicationReactionType, ReportPublicationDocument, PublicationReportingReason, PublicationReportingSpamSubreason, PublicationReportingSensitiveSubreason, PublicationReportingFraudSubreason, PublicationReportingIllegalSubreason, useWhoReactedPublication, useFollowRevenues, useRevenueFromPublication as useRevenueFromPublication$1, useRevenueFromPublications as useRevenueFromPublications$1, CommentOnMomokaDocument, CreateMomokaCommentTypedDataDocument, isPublicationId, CommentOnchainDocument, CreateOnchainCommentTypedDataDocument, resolveReferencePolicy, MirrorOnMomokaDocument, CreateMomokaMirrorTypedDataDocument, MirrorOnchainDocument, CreateOnchainMirrorTypedDataDocument, PostOnMomokaDocument, CreateMomokaPostTypedDataDocument, PostOnchainDocument, CreateOnchainPostTypedDataDocument, QuoteOnMomokaDocument, CreateMomokaQuoteTypedDataDocument, QuoteOnchainDocument, CreateOnchainQuoteTypedDataDocument, resolveTokenAllowanceRequest, BlockDocument, CreateBlockProfilesTypedDataDocument, ClaimProfileWithHandleDocument, resolveFollowModuleInput, GenerateLensApiRelayAddressDocument, FollowDocument, CreateFollowTypedDataDocument, TriStateValue, resolveFollowPolicy, LinkHandleToProfileDocument, CreateLinkHandleToProfileTypedDataDocument, LegacyCollectDocument, ActOnOpenActionDocument, findCollectModuleSettings, erc20Amount, SetProfileMetadataDocument, CreateOnchainSetProfileMetadataTypedDataDocument, UnblockDocument, CreateUnblockProfilesTypedDataDocument, UnfollowDocument, CreateUnfollowTypedDataDocument, UnlinkHandleFromProfileDocument, CreateUnlinkHandleFromProfileTypedDataDocument, SetFollowModuleDocument, CreateSetFollowModuleTypedDataDocument, CreateChangeProfileManagersTypedDataDocument, ChangeProfileManagerActionType, useClaimableProfiles, useLastLoggedInProfile as useLastLoggedInProfile$1, useProfilesManagedLazyQuery, useOwnedHandles as useOwnedHandles$1, useProfilesManaged as useProfilesManaged$1, useUserRateLimit } from '@lens-protocol/api-bindings'; export { ClaimProfileWithHandleErrorReasonType, CollectOpenActionModuleType, CommentRankingFilterType, ComparisonOperatorConditionType, CustomFiltersType, DecryptFailReasonType, ExploreProfilesOrderByType, ExplorePublicationType, ExplorePublicationsOrderByType, FeedEventItemType, FollowModuleType, HiddenCommentsType, LimitType, ManagedProfileVisibility, MarketplaceMetadataAttributeDisplayType, MetadataAttributeType, ModuleType, NftContractType, NotificationType, OpenActionCategoryType, OpenActionModuleType, ProfileActionHistoryType, ProfileInterestTypes, ProfilesOrderBy, PublicationContentWarningType, PublicationMetadataLicenseType, PublicationMetadataMainFocusType, PublicationMetadataTransactionType, PublicationReactionType, PublicationType, SearchPublicationType, SupportedFiatType, TriStateValue, UnspecifiedError, erc20Amount, fiatAmount, findCollectModuleSettings, isCollectModuleSettings, isCommentPublication, isMirrorPublication, isMultirecipientCollectFee, isPostPublication, isPrimaryPublication, isQuotePublication, resolveCollectPolicy, resolveFollowPolicy, resolveReferencePolicy } from '@lens-protocol/api-bindings'; import { TransactionKind, ProtocolTransactionKinds, MetaTransaction, NativeTransaction, DataTransaction, TransactionEvent, TransactionError, TransactionErrorReason, Wallet, UserRejectedError, PendingSigningRequestError, InsufficientGasError, WalletConnectionError, WalletConnectionErrorReason, ProfileReportReason, PublicationReportReason, UnsignedTransaction, isMomokaPublicationId } from '@lens-protocol/domain/entities'; export { InsufficientGasError, PendingSigningRequestError, ProfileReportReason, PublicationReportReason, TransactionError, TransactionErrorReason, UserRejectedError, WalletConnectionError, WalletConnectionErrorReason } from '@lens-protocol/domain/entities'; import { BroadcastingError, BroadcastingErrorReason, TokenAllowanceLimit, TransactionQueue, SignedOnChain, DelegableSigning, SubsidizeOffChain, PaidTransaction, TokenAllowance } from '@lens-protocol/domain/use-cases/transactions'; export { BroadcastingError, BroadcastingErrorReason, TokenAllowanceLimit } from '@lens-protocol/domain/use-cases/transactions'; import { TokenAvailability, InviteWallets, SignFrameAction } from '@lens-protocol/domain/use-cases/wallets'; export { InsufficientAllowanceError, InsufficientFundsError, WalletAlreadyInvitedError } from '@lens-protocol/domain/use-cases/wallets'; import { DateUtils, invariant, never, failure, success, InvariantError, assertError, ChainType, Kind, Amount, erc20, assertNever, BigDecimal, matic, Deferred, hasAtLeastOne, hasTwoOrMore, Denomination, CausedError, update, ether } from '@lens-protocol/shared-kernel'; export { Amount, ChainType, InvariantError, erc20, ether, fiat, matic } from '@lens-protocol/shared-kernel'; import jwtDecode from 'jwt-decode'; import isObject from 'lodash/isObject'; import { CredentialsStorageSchema, Storage, BaseStorageSchema } from '@lens-protocol/storage'; import { z } from 'zod'; import { FollowPolicyType, DismissRecommendedProfiles, ManageProfileInterests, ToggleProfileProperty, ReportProfile, BlockProfiles, isClaimReservedHandleRequest, ClaimHandleError, ClaimHandle, CreateProfile, isPaidFollowRequest, isUnknownFollowRequest, FollowProfile, LinkHandle, SetProfileMetadata, UnblockProfiles, UnfollowProfile, UnlinkHandle, UpdateFollowPolicy, UpdateProfileManagers } from '@lens-protocol/domain/use-cases/profile'; export { ClaimHandleError, FollowPolicyType } from '@lens-protocol/domain/use-cases/profile'; import { OpenActionType, ReferencePolicyType, AllOpenActionType, TogglePublicationProperty, HidePublication, ReportPublication, CreateComment, CreateMirror, CreatePost, CreateQuote, OpenAction } from '@lens-protocol/domain/use-cases/publications'; export { OpenActionType, ReferencePolicyType } from '@lens-protocol/domain/use-cases/publications'; import { erc20 as erc20$1, isTheSameAddress, isValidHandle, bigNumber, lensHub, permissionlessCreator, lensTokenHandleRegistry, publicActProxy } from '@lens-protocol/blockchain-bindings'; export { decodeData, encodeData, isValidHandle } from '@lens-protocol/blockchain-bindings'; import { ErrorCode } from '@ethersproject/logger'; import { errorCodes } from 'eth-rpc-errors'; import { hexValue } from '@ethersproject/bytes'; import { JsonRpcProvider } from '@ethersproject/providers'; import { jsx } from 'react/jsx-runtime'; import differenceBy from 'lodash/differenceBy.js'; import merge from 'lodash/merge'; import { useLazyQuery, useSuspenseQuery, useQuery } from '@apollo/client'; import { v4 } from 'uuid'; import { AddressZero, MaxUint256 } from '@ethersproject/constants'; import * as metadata from '@lens-protocol/metadata'; import { PublicationSchemaId } from '@lens-protocol/metadata'; function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function toPropertyKey(t) { var i = toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var BootstrapPresenter = /*#__PURE__*/function () { function BootstrapPresenter() { _classCallCheck(this, BootstrapPresenter); } _createClass(BootstrapPresenter, [{ key: "present", value: function present(session) { updateSessionData(session); } }]); return BootstrapPresenter; }(); function useBootstrapController(_ref) { var credentialsGateway = _ref.credentialsGateway, credentialsFactory = _ref.credentialsFactory, logout = _ref.logout, transactionQueue = _ref.transactionQueue; var isStartedRef = useRef(false); useEffect(function () { // Protects again multiple calls to start (quite likely from `useEffect` hook in concurrent mode or in development strict mode) if (isStartedRef.current) { return; } isStartedRef.current = true; var bootstrap = new Bootstrap(credentialsGateway, credentialsFactory, transactionQueue, logout, new BootstrapPresenter()); void bootstrap.execute(); }, [credentialsFactory, credentialsGateway, logout, transactionQueue]); } function _defineProperty(obj, key, value) { key = toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _regeneratorRuntime() { _regeneratorRuntime = function () { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function (t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function (t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(typeof e + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function (e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function () { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function (e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function (t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function (t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function (e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function isWalletJwtContent(decodedJwt) { return isObject(decodedJwt) && 'role' in decodedJwt && decodedJwt.role === 'wallet_refresh'; } function isProfileJwtContent(decodedJwt) { return isObject(decodedJwt) && 'role' in decodedJwt && decodedJwt.role === 'profile_refresh'; } function getTokenExpDate(token) { var decodedToken = jwtDecode(token); invariant(decodedToken.exp, 'Exp date should be provided by JWT token'); return DateUtils.secondsToMs(decodedToken.exp); } // Threshold in seconds that will mark token as expired even it's still valid // Adds some time for all communications that's required to refresh tokens var TOKEN_EXP_THRESHOLD = DateUtils.secondsToMs(3); var JwtCredentials = /*#__PURE__*/function () { function JwtCredentials(accessToken, identityToken, refreshToken) { _classCallCheck(this, JwtCredentials); this.accessToken = accessToken; this.identityToken = identityToken; this.refreshToken = refreshToken; var decodedRefreshToken = jwtDecode(refreshToken); if (isWalletJwtContent(decodedRefreshToken)) { this.address = decodedRefreshToken.id; this.authorizationId = decodedRefreshToken.authorizationId; return; } if (isProfileJwtContent(decodedRefreshToken)) { this.address = decodedRefreshToken.evmAddress; this.profileId = decodedRefreshToken.id; this.authorizationId = decodedRefreshToken.authorizationId; return; } never('Invalid JWT format'); } _createClass(JwtCredentials, [{ key: "canRefresh", value: function canRefresh() { var now = Date.now(); var tokenExpDate = getTokenExpDate(this.refreshToken); return now < tokenExpDate - TOKEN_EXP_THRESHOLD; } }, { key: "getTokenRefreshTime", value: function getTokenRefreshTime() { if (!this.accessToken) { return 0; } var now = Date.now(); var tokenExpDate = getTokenExpDate(this.accessToken); return Math.max(tokenExpDate - now - TOKEN_EXP_THRESHOLD, 0); } }]); return JwtCredentials; }(); var AuthApi = /*#__PURE__*/function () { function AuthApi(apolloClient) { _classCallCheck(this, AuthApi); this.apolloClient = apolloClient; } _createClass(AuthApi, [{ key: "generateChallenge", value: function () { var _generateChallenge = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request) { var result; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: _context.next = 2; return this.apolloClient.query({ query: AuthChallengeDocument, variables: { request: request }, // challenge to sign should be always a new one fetchPolicy: 'network-only' }); case 2: result = _context.sent; return _context.abrupt("return", { id: result.data.result.id, text: result.data.result.text }); case 4: case "end": return _context.stop(); } }, _callee, this); })); function generateChallenge(_x) { return _generateChallenge.apply(this, arguments); } return generateChallenge; }() }, { key: "generateCredentials", value: function () { var _generateCredentials = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(request) { var result, _result$data$result, accessToken, identityToken, refreshToken; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.apolloClient.mutate({ mutation: AuthAuthenticateDocument, variables: { request: request } }); case 2: result = _context2.sent; _result$data$result = result.data.result, accessToken = _result$data$result.accessToken, identityToken = _result$data$result.identityToken, refreshToken = _result$data$result.refreshToken; return _context2.abrupt("return", new JwtCredentials(accessToken, identityToken, refreshToken)); case 5: case "end": return _context2.stop(); } }, _callee2, this); })); function generateCredentials(_x2) { return _generateCredentials.apply(this, arguments); } return generateCredentials; }() }, { key: "refreshCredentials", value: function () { var _refreshCredentials = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(refreshToken) { var result, _result$data$result2, newAccessToken, newIdentityToken, newRefreshToken; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this.apolloClient.mutate({ mutation: AuthRefreshDocument, variables: { request: { refreshToken: refreshToken } } }); case 2: result = _context3.sent; _result$data$result2 = result.data.result, newAccessToken = _result$data$result2.accessToken, newIdentityToken = _result$data$result2.identityToken, newRefreshToken = _result$data$result2.refreshToken; return _context3.abrupt("return", new JwtCredentials(newAccessToken, newIdentityToken, newRefreshToken)); case 5: case "end": return _context3.stop(); } }, _callee3, this); })); function refreshCredentials(_x3) { return _refreshCredentials.apply(this, arguments); } return refreshCredentials; }() }]); return AuthApi; }(); var CredentialsFactory = /*#__PURE__*/function () { function CredentialsFactory(auth) { _classCallCheck(this, CredentialsFactory); this.auth = auth; } _createClass(CredentialsFactory, [{ key: "renewCredentials", value: function () { var _renewCredentials = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(credentials) { var newCredentials; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: if (credentials.canRefresh()) { _context.next = 2; break; } return _context.abrupt("return", failure(new CredentialsExpiredError())); case 2: _context.prev = 2; _context.next = 5; return this.auth.refreshCredentials(credentials.refreshToken); case 5: newCredentials = _context.sent; return _context.abrupt("return", success(newCredentials)); case 9: _context.prev = 9; _context.t0 = _context["catch"](2); return _context.abrupt("return", failure(new CredentialsExpiredError())); case 12: case "end": return _context.stop(); } }, _callee, this, [[2, 9]]); })); function renewCredentials(_x) { return _renewCredentials.apply(this, arguments); } return renewCredentials; }() }, { key: "issueCredentials", value: function () { var _issueCredentials = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(signer, using) { var challenge, result, credentials; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.auth.generateChallenge({ "for": using, signedBy: signer.address }); case 2: challenge = _context2.sent; _context2.next = 5; return signer.signMessage(challenge.text); case 5: result = _context2.sent; if (!result.isFailure()) { _context2.next = 8; break; } return _context2.abrupt("return", result); case 8: _context2.next = 10; return this.auth.generateCredentials({ id: challenge.id, signature: result.value }); case 10: credentials = _context2.sent; return _context2.abrupt("return", success(credentials)); case 12: case "end": return _context2.stop(); } }, _callee2, this); })); function issueCredentials(_x2, _x3) { return _issueCredentials.apply(this, arguments); } return issueCredentials; }() }]); return CredentialsFactory; }(); var CredentialsGateway = /*#__PURE__*/function () { function CredentialsGateway(credentialsStorage, apolloClient) { _classCallCheck(this, CredentialsGateway); this.credentialsStorage = credentialsStorage; this.apolloClient = apolloClient; } _createClass(CredentialsGateway, [{ key: "getCredentials", value: function () { var _getCredentials = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", this.credentialsStorage.get()); case 1: case "end": return _context.stop(); } }, _callee, this); })); function getCredentials() { return _getCredentials.apply(this, arguments); } return getCredentials; }() }, { key: "save", value: function () { var _save = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(credentials) { return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.credentialsStorage.set(credentials); case 2: case "end": return _context2.stop(); } }, _callee2, this); })); function save(_x) { return _save.apply(this, arguments); } return save; }() }, { key: "invalidate", value: function () { var _invalidate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(reason) { var credentials; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this.getCredentials(); case 2: credentials = _context3.sent; if (!credentials) { never('User is not authenticated'); } if (!(reason === LogoutReason.USER_INITIATED)) { _context3.next = 7; break; } _context3.next = 7; return this.revoke({ authorizationId: credentials.authorizationId }); case 7: _context3.next = 9; return this.credentialsStorage.reset(); case 9: case "end": return _context3.stop(); } }, _callee3, this); })); function invalidate(_x2) { return _invalidate.apply(this, arguments); } return invalidate; }() }, { key: "revoke", value: function () { var _revoke = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(request) { return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this.apolloClient.mutate({ mutation: RevokeAuthenticationDocument, variables: { request: request } }); case 2: case "end": return _context4.stop(); } }, _callee4, this); })); function revoke(_x3) { return _revoke.apply(this, arguments); } return revoke; }() }]); return CredentialsGateway; }(); var POLLING_TIME = 1000; var lastActiveTimerId = 0; var activeTimers = new Set(); function safeSetTimeoutRec(fn, endTime, timerId, options) { var msToEnd = endTime - Date.now(); setTimeout(function () { if (!activeTimers.has(timerId)) { return; } var now = Date.now(); if (now >= endTime) { activeTimers["delete"](timerId); fn(); } else { safeSetTimeoutRec(fn, endTime, timerId, options); } }, msToEnd <= options.poolingTimeout ? msToEnd : options.poolingTimeout); } /** * Safe version of `setTimeout` that should support * 1. Large milliseconds delays (larger than 2147483647) * 2. Hibernation/Sleep * * @param fn - callback to be invoked after * @param ms - milliseconds to wait * @param options - timer options * * Note: `safeSetTimeout` should be only used when really needed * as processor overhead is bigger than with normal `setTimeout` * @returns timerId Use `clearSafeTimeout(timerId)` to cancel timeout */ function setSafeTimeout(fn, ms) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { poolingTimeout: POLLING_TIME }; var timerId = ++lastActiveTimerId; activeTimers.add(timerId); safeSetTimeoutRec(fn, Date.now() + ms, timerId, options); return timerId; } /** * Cancel timeout created with `safeSetTimeout`. */ function clearSafeTimeout(timerId) { activeTimers["delete"](timerId); } /** * Stores auth credentials. * Access token is kept in memory. * Identity token is kept in memory. * Refresh token is persisted permanently. */ var CredentialsStorage = /*#__PURE__*/function () { function CredentialsStorage(refreshTokenStorage, authApi) { _classCallCheck(this, CredentialsStorage); _defineProperty(this, "refreshTimer", null); _defineProperty(this, "refreshPromise", null); _defineProperty(this, "subscribers", new Set()); _defineProperty(this, "accessToken", null); _defineProperty(this, "identityToken", null); _defineProperty(this, "logout", null); this.refreshTokenStorage = refreshTokenStorage; this.authApi = authApi; } _createClass(CredentialsStorage, [{ key: "onExpiry", value: function onExpiry(logout) { this.logout = logout; } }, { key: "set", value: function () { var _set = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(newCredentials) { var oldCredentials; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: this.accessToken = newCredentials.accessToken; this.identityToken = newCredentials.identityToken; _context.next = 4; return this.get(); case 4: oldCredentials = _context.sent; _context.next = 7; return this.refreshTokenStorage.set({ refreshToken: newCredentials.refreshToken }); case 7: this.refreshTimer = setSafeTimeout(this.refreshToken.bind(this), newCredentials.getTokenRefreshTime()); this.notifySubscribers(newCredentials, oldCredentials); case 9: case "end": return _context.stop(); } }, _callee, this); })); function set(_x) { return _set.apply(this, arguments); } return set; }() }, { key: "get", value: function () { var _get = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { var refreshToken; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.getRefreshToken(); case 2: refreshToken = _context2.sent; if (refreshToken) { _context2.next = 5; break; } return _context2.abrupt("return", null); case 5: return _context2.abrupt("return", new JwtCredentials(this.accessToken, this.identityToken, refreshToken)); case 6: case "end": return _context2.stop(); } }, _callee2, this); })); function get() { return _get.apply(this, arguments); } return get; }() }, { key: "reset", value: function () { var _reset = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: this.accessToken = null; this.cancelScheduledRefresh(); _context3.next = 4; return this.refreshTokenStorage.reset(); case 4: case "end": return _context3.stop(); } }, _callee3, this); })); function reset() { return _reset.apply(this, arguments); } return reset; }() }, { key: "subscribe", value: function subscribe(subscriber) { var _this = this; this.subscribers.add(subscriber); return { unsubscribe: function unsubscribe() { return _this.subscribers["delete"](subscriber); } }; } }, { key: "getAccessToken", value: function getAccessToken() { return this.accessToken; } }, { key: "refreshToken", value: function () { var _refreshToken = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { var result; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: if (!this.refreshPromise) { _context4.next = 2; break; } return _context4.abrupt("return", this.refreshPromise); case 2: this.refreshPromise = this.refreshCredentials(); _context4.next = 5; return this.refreshPromise; case 5: result = _context4.sent; this.refreshPromise = null; return _context4.abrupt("return", result); case 8: case "end": return _context4.stop(); } }, _callee4, this); })); function refreshToken() { return _refreshToken.apply(this, arguments); } return refreshToken; }() }, { key: "cancelScheduledRefresh", value: function cancelScheduledRefresh() { if (this.refreshTimer) { clearSafeTimeout(this.refreshTimer); } this.refreshTimer = null; } }, { key: "refreshCredentials", value: function () { var _refreshCredentials = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() { var credentials, newCredentials, _this$logout; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this.get(); case 2: credentials = _context5.sent; if (!(!credentials || !credentials.canRefresh())) { _context5.next = 5; break; } return _context5.abrupt("return", failure(new CredentialsExpiredError())); case 5: _context5.prev = 5; _context5.next = 8; return this.authApi.refreshCredentials(credentials.refreshToken); case 8: newCredentials = _context5.sent; _context5.next = 11; return this.set(newCredentials); case 11: return _context5.abrupt("return", success()); case 14: _context5.prev = 14; _context5.t0 = _context5["catch"](5); _context5.next = 18; return (_this$logout = this.logout) === null || _this$logout === void 0 ? void 0 : _this$logout.execute(LogoutReason.CREDENTIALS_EXPIRED); case 18: return _context5.abrupt("return", failure(new CredentialsExpiredError())); case 19: case "end": return _context5.stop(); } }, _callee5, this, [[5, 14]]); })); function refreshCredentials() { return _refreshCredentials.apply(this, arguments); } return refreshCredentials; }() }, { key: "notifySubscribers", value: function notifySubscribers(newCredentials, oldCredentials) { this.subscribers.forEach(function (callback) { return callback(newCredentials, oldCredentials); }); } }, { key: "getRefreshToken", value: function () { var _getRefreshToken = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() { var _result$refreshToken; var result; return _regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return this.refreshTokenStorage.get(); case 2: result = _context6.sent; return _context6.abrupt("return", (_result$refreshToken = result === null || result === void 0 ? void 0 : result.refreshToken) !== null && _result$refreshToken !== void 0 ? _result$refreshToken : null); case 4: case "end": return _context6.stop(); } }, _callee6, this); })); function getRefreshToken() { return _getRefreshToken.apply(this, arguments); } return getRefreshToken; }() }]); return CredentialsStorage; }(); var LogoutPresenter = /*#__PURE__*/function () { function LogoutPresenter() { _classCallCheck(this, LogoutPresenter); } _createClass(LogoutPresenter, [{ key: "logout", value: function logout(reason) { updateSessionData(anonymousSessionData(reason)); } }]); return LogoutPresenter; }(); function createRefreshTokenStorage(storageProvider, namespace) { var schema = new CredentialsStorageSchema("lens.".concat(namespace, ".credentials")); return Storage.createForSchema(schema, storageProvider); } /* eslint-disable no-console */ var ConsoleLoggerLevel = /*#__PURE__*/function (ConsoleLoggerLevel) { ConsoleLoggerLevel[ConsoleLoggerLevel["Info"] = 1] = "Info"; ConsoleLoggerLevel[ConsoleLoggerLevel["Warn"] = 2] = "Warn"; Consol