@moon-x/react-native-sdk 0.24.0 → 0.26.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.
package/dist/index.mjs CHANGED
@@ -3,21 +3,23 @@ import {
3
3
  createContext,
4
4
  useCallback,
5
5
  useContext,
6
- useEffect,
6
+ useEffect as useEffect2,
7
+ useLayoutEffect,
7
8
  useMemo,
8
9
  useReducer,
9
- useRef,
10
- useState
10
+ useRef as useRef2,
11
+ useState as useState2,
12
+ useSyncExternalStore
11
13
  } from "react";
12
14
  import {
13
15
  Animated,
14
16
  AppState,
15
17
  Platform,
16
- Pressable,
17
- StyleSheet,
18
- Text,
18
+ Pressable as Pressable2,
19
+ StyleSheet as StyleSheet2,
20
+ Text as Text2,
19
21
  useWindowDimensions,
20
- View
22
+ View as View2
21
23
  } from "react-native";
22
24
  import { WebView } from "react-native-webview";
23
25
 
@@ -211,7 +213,8 @@ var getPasskeyMethods = (bridge, publishableKey, configuredRelyingPartyOrigin) =
211
213
  passkey: createRNPasskey(),
212
214
  publishableKey,
213
215
  relyingPartyOrigin,
214
- scopes: SCOPES_ADD_PASSKEY
216
+ scopes: SCOPES_ADD_PASSKEY,
217
+ requestOtpCode: params?.requestOtpCode
215
218
  });
216
219
  if (result.credentialIdB64url && !allowList.includes(result.credentialIdB64url)) {
217
220
  throw new Error("unknown_passkey_for_this_account");
@@ -468,6 +471,67 @@ var getTronSDKMethods = (bridge, publishableKey, relyingPartyOrigin) => getHeadl
468
471
  relyingPartyOrigin
469
472
  });
470
473
 
474
+ // src/sdk/session-methods.ts
475
+ function getSessionMethods(bridge, publishableKey, relyingPartyOrigin, session, sessionResume) {
476
+ const auth = (callbacks) => getAuthenticationMethods(
477
+ bridge,
478
+ publishableKey,
479
+ callbacks?.setIsAuthenticated
480
+ );
481
+ const general = (callbacks, setUser) => getSDKMethods(
482
+ bridge,
483
+ publishableKey,
484
+ relyingPartyOrigin,
485
+ callbacks?.setIsAuthenticated,
486
+ setUser
487
+ );
488
+ const mutate = async (operation, profile) => {
489
+ const callbacks = session.beginAuthOperation();
490
+ try {
491
+ const result = await operation(callbacks);
492
+ if (profile === "await") await callbacks.refreshUser();
493
+ if (profile === "background") void callbacks.refreshUser();
494
+ return result;
495
+ } finally {
496
+ callbacks.finish();
497
+ }
498
+ };
499
+ const login = (operation, profile) => mutate(async (callbacks) => {
500
+ const release = await sessionResume?.beginLogin();
501
+ let succeeded = false;
502
+ try {
503
+ const result = await operation(callbacks);
504
+ succeeded = true;
505
+ return result;
506
+ } finally {
507
+ release?.(succeeded);
508
+ }
509
+ }, profile);
510
+ return {
511
+ loginWithCode: (params) => login((callbacks) => auth(callbacks).loginWithCode(params), "await"),
512
+ loginWithMoonPayCustomerToken: (params) => login((callbacks) => auth(callbacks).loginWithMoonPayCustomerToken(params), "background"),
513
+ verifyOAuth: (params) => login((callbacks) => auth(callbacks).verifyOAuth(params), "await"),
514
+ // Drop the resume key first, so a failed iframe logout cannot leave a key
515
+ // that brings the session back on the next launch.
516
+ logout: () => mutate((callbacks) => sessionResume ? sessionResume.logout(() => general(callbacks).logout()) : general(callbacks).logout(), "none"),
517
+ getUser: () => general(void 0, session.captureUserWrite()).getUser(),
518
+ linkEmailWithCode: async (params) => {
519
+ const refreshUser = session.captureUserRefresh();
520
+ const result = await auth().linkEmailWithCode(params);
521
+ await refreshUser();
522
+ return result;
523
+ },
524
+ // The account's email changes, so the provider's user is read again
525
+ // before the change resolves, the same as a link.
526
+ confirmEmailChangeNewCode: async (params) => {
527
+ const refreshUser = session.captureUserRefresh();
528
+ const result = await auth().confirmEmailChangeNewCode(params);
529
+ await refreshUser();
530
+ return result;
531
+ }
532
+ };
533
+ }
534
+
471
535
  // src/sdk/create-sdk-instance.ts
472
536
  var makeRelyingPartyOriginResolver = (bridge, publishableKey, configuredOrigin) => {
473
537
  let cached = configuredOrigin || null;
@@ -495,7 +559,9 @@ var createSdkInstance = ({
495
559
  revalidatedAt,
496
560
  setIsAuthenticated,
497
561
  setUser,
498
- refreshUser
562
+ refreshUser,
563
+ session,
564
+ sessionResume
499
565
  }) => ({
500
566
  publishableKey,
501
567
  ready,
@@ -503,6 +569,11 @@ var createSdkInstance = ({
503
569
  isAuthenticated,
504
570
  user,
505
571
  refreshUser,
572
+ sessionStatus: session?.getSnapshot().sessionStatus ?? (isAuthenticated ? "authenticated" : "restoring"),
573
+ sessionError: session?.getSnapshot().sessionError ?? null,
574
+ retrySession: session?.retrySession ?? (() => {
575
+ throw new Error("session_recovery_unavailable");
576
+ }),
506
577
  ...getAuthenticationMethods(
507
578
  bridge,
508
579
  publishableKey,
@@ -521,11 +592,355 @@ var createSdkInstance = ({
521
592
  ...getFundingSDKMethods(bridge, publishableKey),
522
593
  ...getSolanaSDKMethods(bridge, publishableKey, relyingPartyOrigin),
523
594
  ...getBitcoinSDKMethods(bridge, publishableKey, relyingPartyOrigin),
524
- ...getTronSDKMethods(bridge, publishableKey, relyingPartyOrigin)
595
+ ...getTronSDKMethods(bridge, publishableKey, relyingPartyOrigin),
596
+ ...session ? getSessionMethods(bridge, publishableKey, relyingPartyOrigin, session, sessionResume) : {}
525
597
  });
526
598
 
527
599
  // src/provider.tsx
528
- import { PostMessageMethod as PostMessageMethod3, PostMessageType as PostMessageType3 } from "@moon-x/core/utils";
600
+ import { PostMessageMethod as PostMessageMethod4, PostMessageType as PostMessageType4 } from "@moon-x/core/utils";
601
+
602
+ // src/components/presence-otp-prompt.tsx
603
+ import { useEffect, useRef, useState } from "react";
604
+ import {
605
+ Modal,
606
+ Pressable,
607
+ StyleSheet,
608
+ Text,
609
+ TextInput,
610
+ View
611
+ } from "react-native";
612
+ import { registerPresenceOtpCodeProvider } from "@moon-x/core/sdk";
613
+
614
+ // src/components/presence-otp-gate.ts
615
+ var createPresenceOtpGate = () => {
616
+ let cancelledChallengeId = null;
617
+ return {
618
+ evaluate(request) {
619
+ if (request.attempt === 1) {
620
+ cancelledChallengeId = null;
621
+ }
622
+ if (request.challengeId && cancelledChallengeId === request.challengeId) {
623
+ return "cancelled";
624
+ }
625
+ return "prompt";
626
+ },
627
+ markCancelled(challengeId) {
628
+ cancelledChallengeId = challengeId ?? null;
629
+ }
630
+ };
631
+ };
632
+
633
+ // src/components/presence-otp-controller.ts
634
+ var IDLE_PRESENCE_OTP_STATE = {
635
+ request: null,
636
+ submitting: false,
637
+ invalidCode: false
638
+ };
639
+ var createPresenceOtpController = (onChange) => {
640
+ const gate = createPresenceOtpGate();
641
+ let active;
642
+ let pending = null;
643
+ const waiting = [];
644
+ let state = IDLE_PRESENCE_OTP_STATE;
645
+ let disposed = false;
646
+ const set = (next) => {
647
+ state = next;
648
+ if (!disposed) onChange(next);
649
+ };
650
+ const takePending = () => {
651
+ const current = pending;
652
+ pending = null;
653
+ return current;
654
+ };
655
+ const show = (next) => {
656
+ active = { challengeId: next.request.challengeId };
657
+ if (gate.evaluate(next.request) === "cancelled") {
658
+ next.reject(new Error("presence_otp_cancelled"));
659
+ return;
660
+ }
661
+ takePending()?.reject(new Error("presence_otp_replaced"));
662
+ pending = next;
663
+ set({
664
+ request: next.request,
665
+ submitting: false,
666
+ invalidCode: next.request.error === "invalid code"
667
+ });
668
+ };
669
+ return {
670
+ getState: () => state,
671
+ requestCode: (request) => new Promise((resolve, reject) => {
672
+ if (disposed) {
673
+ reject(new Error("presence_otp_cancelled"));
674
+ return;
675
+ }
676
+ const next = { request, resolve, reject };
677
+ if (!active || active.challengeId === request.challengeId) {
678
+ show(next);
679
+ } else {
680
+ waiting.push(next);
681
+ }
682
+ }),
683
+ submit: (code) => {
684
+ const current = takePending();
685
+ if (!current) return false;
686
+ current.resolve(code);
687
+ set({ ...state, submitting: true, invalidCode: false });
688
+ return true;
689
+ },
690
+ cancel: () => {
691
+ if (state.submitting || !pending) return false;
692
+ gate.markCancelled(pending.request.challengeId);
693
+ takePending()?.reject(new Error("presence_otp_cancelled"));
694
+ set(IDLE_PRESENCE_OTP_STATE);
695
+ return true;
696
+ },
697
+ expire: (request) => {
698
+ if (pending?.request !== request) return;
699
+ takePending()?.reject(new Error("presence_otp_expired"));
700
+ set(IDLE_PRESENCE_OTP_STATE);
701
+ },
702
+ settled: (request) => {
703
+ if (!active || active.challengeId !== request.challengeId) return;
704
+ active = void 0;
705
+ takePending()?.reject(new Error("presence_otp_cancelled"));
706
+ const next = waiting.shift();
707
+ if (next) {
708
+ show(next);
709
+ } else {
710
+ set(IDLE_PRESENCE_OTP_STATE);
711
+ }
712
+ },
713
+ dispose: () => {
714
+ const error = new Error("presence_otp_cancelled");
715
+ takePending()?.reject(error);
716
+ for (const next of waiting.splice(0)) next.reject(error);
717
+ active = void 0;
718
+ state = IDLE_PRESENCE_OTP_STATE;
719
+ disposed = true;
720
+ }
721
+ };
722
+ };
723
+
724
+ // src/components/presence-otp-prompt.tsx
725
+ import { jsx, jsxs } from "react/jsx-runtime";
726
+ var DEFAULT_COPY = {
727
+ title: "Check your email",
728
+ description: "Enter the verification code we sent to confirm this wallet action.",
729
+ hint: "Didn't get it? Check spam, or cancel and try again in a minute.",
730
+ verify: "Verify",
731
+ verifying: "Verifying...",
732
+ cancel: "Cancel",
733
+ invalidCode: "That code was incorrect. Try again.",
734
+ incompleteCode: "Enter the 6-digit code."
735
+ };
736
+ var DEFAULT_COLORS = {
737
+ background: "#0a0a0a",
738
+ surface: "#141414",
739
+ border: "#333",
740
+ text: "#fafafa",
741
+ mutedText: "#a1a1aa",
742
+ accent: "#3b82f6",
743
+ accentText: "#fff",
744
+ error: "#f87171"
745
+ };
746
+ var OTP_LENGTH = 6;
747
+ var PresenceOtpPrompt = ({
748
+ publishableKey,
749
+ options
750
+ }) => {
751
+ const [state, setState] = useState(
752
+ IDLE_PRESENCE_OTP_STATE
753
+ );
754
+ const [code, setCode] = useState("");
755
+ const [incomplete, setIncomplete] = useState(false);
756
+ const controllerRef = useRef(null);
757
+ const copy = { ...DEFAULT_COPY, ...options?.copy };
758
+ const colors = { ...DEFAULT_COLORS, ...options?.colors };
759
+ useEffect(() => {
760
+ const controller = createPresenceOtpController(setState);
761
+ controllerRef.current = controller;
762
+ const unregister = registerPresenceOtpCodeProvider(
763
+ publishableKey,
764
+ controller.requestCode,
765
+ controller.settled
766
+ );
767
+ return () => {
768
+ unregister();
769
+ controller.dispose();
770
+ controllerRef.current = null;
771
+ setState(IDLE_PRESENCE_OTP_STATE);
772
+ };
773
+ }, [publishableKey]);
774
+ useEffect(() => {
775
+ setCode("");
776
+ setIncomplete(false);
777
+ }, [state.request]);
778
+ useEffect(() => {
779
+ const request = state.request;
780
+ if (!request?.expiresAt || state.submitting) return;
781
+ const expire = () => controllerRef.current?.expire(request);
782
+ const remainingMs = request.expiresAt * 1e3 - Date.now();
783
+ if (remainingMs <= 0) {
784
+ expire();
785
+ return;
786
+ }
787
+ const timer = setTimeout(expire, remainingMs);
788
+ return () => clearTimeout(timer);
789
+ }, [state.request, state.submitting]);
790
+ const close = () => {
791
+ controllerRef.current?.cancel();
792
+ };
793
+ const submit = () => {
794
+ const normalized = code.trim();
795
+ if (!/^\d{6}$/.test(normalized)) {
796
+ setIncomplete(true);
797
+ return;
798
+ }
799
+ controllerRef.current?.submit(normalized);
800
+ };
801
+ const submitting = state.submitting;
802
+ const error = incomplete ? copy.incompleteCode : state.invalidCode ? copy.invalidCode : null;
803
+ const complete = code.length === OTP_LENGTH;
804
+ return /* @__PURE__ */ jsx(
805
+ Modal,
806
+ {
807
+ visible: state.request !== null,
808
+ transparent: true,
809
+ animationType: "fade",
810
+ onRequestClose: close,
811
+ children: /* @__PURE__ */ jsx(View, { style: styles.backdrop, children: /* @__PURE__ */ jsxs(View, { style: [styles.card, { backgroundColor: colors.background }], children: [
812
+ /* @__PURE__ */ jsx(Text, { style: [styles.title, { color: colors.text }], children: copy.title }),
813
+ /* @__PURE__ */ jsx(Text, { style: [styles.body, { color: colors.mutedText }], children: copy.description }),
814
+ /* @__PURE__ */ jsx(
815
+ TextInput,
816
+ {
817
+ autoFocus: true,
818
+ style: [
819
+ styles.input,
820
+ {
821
+ borderColor: colors.border,
822
+ backgroundColor: colors.surface,
823
+ color: colors.text
824
+ }
825
+ ],
826
+ value: code,
827
+ onChangeText: (next) => {
828
+ setCode(next.replace(/\D/g, "").slice(0, OTP_LENGTH));
829
+ setIncomplete(false);
830
+ },
831
+ onSubmitEditing: submit,
832
+ editable: !submitting,
833
+ keyboardType: "number-pad",
834
+ textContentType: "oneTimeCode",
835
+ autoComplete: "sms-otp",
836
+ maxLength: OTP_LENGTH,
837
+ placeholder: "123456",
838
+ placeholderTextColor: colors.mutedText,
839
+ accessibilityLabel: "Verification code",
840
+ returnKeyType: "done"
841
+ }
842
+ ),
843
+ error !== null && /* @__PURE__ */ jsx(
844
+ Text,
845
+ {
846
+ style: [styles.error, { color: colors.error }],
847
+ accessibilityLiveRegion: "polite",
848
+ children: error
849
+ }
850
+ ),
851
+ /* @__PURE__ */ jsx(
852
+ Pressable,
853
+ {
854
+ onPress: submit,
855
+ disabled: submitting || !complete,
856
+ style: [
857
+ styles.primaryButton,
858
+ { backgroundColor: colors.accent },
859
+ (submitting || !complete) && styles.primaryButtonDisabled
860
+ ],
861
+ accessibilityRole: "button",
862
+ children: /* @__PURE__ */ jsx(Text, { style: [styles.primaryButtonText, { color: colors.accentText }], children: submitting ? copy.verifying : copy.verify })
863
+ }
864
+ ),
865
+ /* @__PURE__ */ jsx(
866
+ Pressable,
867
+ {
868
+ onPress: close,
869
+ disabled: submitting,
870
+ style: [styles.ghostButton, submitting && styles.primaryButtonDisabled],
871
+ accessibilityRole: "button",
872
+ children: /* @__PURE__ */ jsx(Text, { style: [styles.ghostButtonText, { color: colors.mutedText }], children: copy.cancel })
873
+ }
874
+ ),
875
+ /* @__PURE__ */ jsx(Text, { style: [styles.hint, { color: colors.mutedText }], children: copy.hint })
876
+ ] }) })
877
+ }
878
+ );
879
+ };
880
+ var styles = StyleSheet.create({
881
+ backdrop: {
882
+ flex: 1,
883
+ alignItems: "center",
884
+ justifyContent: "center",
885
+ padding: 16,
886
+ backgroundColor: "rgba(0, 0, 0, 0.45)"
887
+ },
888
+ card: {
889
+ width: "100%",
890
+ maxWidth: 384,
891
+ padding: 24,
892
+ borderRadius: 14
893
+ },
894
+ title: {
895
+ fontSize: 20,
896
+ fontWeight: "600"
897
+ },
898
+ body: {
899
+ fontSize: 14,
900
+ marginTop: 8
901
+ },
902
+ input: {
903
+ marginTop: 16,
904
+ paddingVertical: 12,
905
+ paddingHorizontal: 16,
906
+ borderRadius: 12,
907
+ borderWidth: StyleSheet.hairlineWidth,
908
+ fontSize: 24,
909
+ letterSpacing: 8,
910
+ textAlign: "center"
911
+ },
912
+ error: {
913
+ fontSize: 13,
914
+ marginTop: 8
915
+ },
916
+ primaryButton: {
917
+ marginTop: 16,
918
+ paddingVertical: 12,
919
+ borderRadius: 12,
920
+ alignItems: "center"
921
+ },
922
+ primaryButtonDisabled: {
923
+ opacity: 0.5
924
+ },
925
+ primaryButtonText: {
926
+ fontSize: 16,
927
+ fontWeight: "600"
928
+ },
929
+ ghostButton: {
930
+ marginTop: 8,
931
+ paddingVertical: 12,
932
+ alignItems: "center"
933
+ },
934
+ ghostButtonText: {
935
+ fontSize: 15,
936
+ fontWeight: "500"
937
+ },
938
+ hint: {
939
+ fontSize: 12,
940
+ marginTop: 4,
941
+ textAlign: "center"
942
+ }
943
+ });
529
944
 
530
945
  // src/transport/webview-bridge.ts
531
946
  import {
@@ -689,7 +1104,8 @@ var WebViewBridge = class {
689
1104
  // ride out the iframe-app mount race; everything else makes a single attempt.
690
1105
  async send(type, method, payload) {
691
1106
  const isSigningPreparation = method === "GET_DEK_INFO" && payload !== null && typeof payload === "object" && "signingWalletId" in payload && payload.signingWalletId !== void 0;
692
- if (isSigningPreparation || !RETRYABLE_METHODS.has(method)) {
1107
+ const isResumeCheck = method === "IS_AUTHENTICATED" && payload !== null && typeof payload === "object" && "resumeSessionId" in payload && payload.resumeSessionId !== void 0;
1108
+ if (isSigningPreparation || isResumeCheck || !RETRYABLE_METHODS.has(method)) {
693
1109
  return this.sendOnce(
694
1110
  type,
695
1111
  method,
@@ -816,31 +1232,524 @@ var webViewLifecycleReducer = (state, action) => {
816
1232
  }
817
1233
  };
818
1234
 
819
- // src/session-recovery.ts
820
- var createSessionRevalidationGate = () => {
821
- let inFlight = false;
1235
+ // src/native-session.ts
1236
+ function createNativeSession(reads) {
1237
+ let snapshot = {
1238
+ isAuthenticated: false,
1239
+ user: null,
1240
+ revalidatedAt: 0,
1241
+ sessionStatus: "restoring",
1242
+ sessionError: null
1243
+ };
1244
+ const listeners = /* @__PURE__ */ new Set();
1245
+ const holds = /* @__PURE__ */ new Set();
1246
+ let holdSequence = 0;
1247
+ let replaceableFinish = null;
1248
+ let mounted = false;
1249
+ let ready = false;
1250
+ let pending = true;
822
1251
  let generation = 0;
1252
+ let profileSequence = 0;
1253
+ let run = null;
1254
+ let timer;
1255
+ const publish = (patch) => {
1256
+ snapshot = { ...snapshot, ...patch };
1257
+ listeners.forEach((listener) => listener());
1258
+ };
1259
+ const cancelRestore = () => {
1260
+ run = null;
1261
+ clearTimeout(timer);
1262
+ timer = void 0;
1263
+ };
1264
+ const confirmedAt = () => Math.max(Date.now(), snapshot.revalidatedAt + 1);
1265
+ const captureUserWrite = () => {
1266
+ const capturedGeneration = generation;
1267
+ const sequence = ++profileSequence;
1268
+ return (user) => {
1269
+ if (!mounted || generation !== capturedGeneration || profileSequence !== sequence || !snapshot.isAuthenticated) return;
1270
+ if (user && typeof user === "object") publish({ user });
1271
+ };
1272
+ };
1273
+ const refreshUser = async () => {
1274
+ const write = captureUserWrite();
1275
+ try {
1276
+ write(await reads.getUser());
1277
+ } catch {
1278
+ }
1279
+ };
1280
+ const retrySession = () => {
1281
+ if (!mounted || run) return;
1282
+ pending = true;
1283
+ if (!ready || holds.size > 0) return;
1284
+ pending = false;
1285
+ const current = {};
1286
+ run = current;
1287
+ const capturedGeneration = generation;
1288
+ const isCurrent = () => mounted && ready && run === current && generation === capturedGeneration && holds.size === 0;
1289
+ let attempts = 0;
1290
+ let missing = 0;
1291
+ let lastError = null;
1292
+ let resumeSettled = !reads.resume;
1293
+ publish({ sessionStatus: "restoring", sessionError: null });
1294
+ const restore = async () => {
1295
+ if (!isCurrent()) return;
1296
+ attempts++;
1297
+ try {
1298
+ const session = await reads.getCurrentSession();
1299
+ if (!isCurrent()) return;
1300
+ if (session === null && !resumeSettled && reads.resume) {
1301
+ const resumed = await reads.resume();
1302
+ if (!isCurrent()) return;
1303
+ resumeSettled = true;
1304
+ if (resumed) {
1305
+ attempts--;
1306
+ void restore();
1307
+ return;
1308
+ }
1309
+ }
1310
+ if (session === null) {
1311
+ missing++;
1312
+ } else {
1313
+ if (!session || typeof session !== "object" || !("accessToken" in session) || typeof session.accessToken !== "string" || !session.accessToken) {
1314
+ throw new Error("The session response is invalid. Retry the session check.");
1315
+ }
1316
+ publish({ isAuthenticated: true, sessionStatus: "authenticated", sessionError: null, revalidatedAt: confirmedAt() });
1317
+ await refreshUser();
1318
+ if (isCurrent()) run = null;
1319
+ return;
1320
+ }
1321
+ } catch (error) {
1322
+ if (!isCurrent()) return;
1323
+ lastError = error instanceof Error ? error : new Error(String(error));
1324
+ }
1325
+ if (!isCurrent()) return;
1326
+ if (attempts < 5) {
1327
+ timer = setTimeout(() => {
1328
+ timer = void 0;
1329
+ void restore();
1330
+ }, 200 * 2 ** (attempts - 1));
1331
+ return;
1332
+ }
1333
+ run = null;
1334
+ if (missing === 5) {
1335
+ generation++;
1336
+ profileSequence++;
1337
+ publish({ isAuthenticated: false, user: null, sessionStatus: "signed-out", sessionError: null, revalidatedAt: confirmedAt() });
1338
+ } else {
1339
+ publish({ sessionStatus: "error", sessionError: lastError ?? new Error("The session check failed. Retry the check.") });
1340
+ }
1341
+ };
1342
+ void restore();
1343
+ };
1344
+ const beginAuthFlow = ({ replaceSession = false } = {}) => {
1345
+ if (!mounted) throw new Error("provider_unmounted");
1346
+ if (replaceSession) {
1347
+ generation++;
1348
+ profileSequence++;
1349
+ }
1350
+ const capturedGeneration = generation;
1351
+ const id = ++holdSequence;
1352
+ holds.add(id);
1353
+ cancelRestore();
1354
+ pending = true;
1355
+ const finish = () => {
1356
+ if (!holds.delete(id)) return;
1357
+ if (holds.size === 0 && pending) retrySession();
1358
+ };
1359
+ if (replaceSession) {
1360
+ const previous = replaceableFinish;
1361
+ replaceableFinish = finish;
1362
+ previous?.();
1363
+ }
1364
+ return Object.assign(finish, {
1365
+ assertCurrent: () => {
1366
+ if (!mounted || generation !== capturedGeneration) throw new Error("session_changed");
1367
+ }
1368
+ });
1369
+ };
823
1370
  return {
824
- begin: () => {
825
- inFlight = true;
826
- generation += 1;
827
- return generation;
1371
+ getSnapshot: () => snapshot,
1372
+ subscribe: (listener) => {
1373
+ listeners.add(listener);
1374
+ return () => {
1375
+ listeners.delete(listener);
1376
+ };
1377
+ },
1378
+ mount: () => {
1379
+ mounted = true;
1380
+ if (pending) retrySession();
828
1381
  },
829
- request: ({ error, authFlowsInFlight, revalidate }) => {
830
- if (error.message !== "no_session") return;
831
- if (authFlowsInFlight > 0 || inFlight) return;
832
- inFlight = true;
833
- revalidate();
1382
+ unmount: () => {
1383
+ mounted = false;
1384
+ generation++;
1385
+ profileSequence++;
1386
+ holds.clear();
1387
+ cancelRestore();
1388
+ pending = true;
1389
+ },
1390
+ setReady: (value) => {
1391
+ if (ready === value) return;
1392
+ ready = value;
1393
+ if (value) {
1394
+ retrySession();
1395
+ return;
1396
+ }
1397
+ generation++;
1398
+ profileSequence++;
1399
+ cancelRestore();
1400
+ pending = true;
1401
+ publish({ sessionStatus: "restoring", sessionError: null });
834
1402
  },
835
- finish: (finishedGeneration) => {
836
- if (finishedGeneration !== generation) return;
837
- inFlight = false;
1403
+ retrySession,
1404
+ /** Replaces an active check: a suspended WebView can drop requests it had in flight. */
1405
+ restartSession: () => {
1406
+ cancelRestore();
1407
+ retrySession();
1408
+ },
1409
+ beginAuthFlow,
1410
+ captureUserWrite,
1411
+ captureUserRefresh: () => {
1412
+ const capturedGeneration = generation;
1413
+ return async () => {
1414
+ if (mounted && generation === capturedGeneration) await refreshUser();
1415
+ };
1416
+ },
1417
+ refreshUser,
1418
+ beginAuthOperation: () => {
1419
+ const finish = beginAuthFlow();
1420
+ const replaced = replaceableFinish;
1421
+ replaceableFinish = null;
1422
+ replaced?.();
1423
+ let capturedGeneration = ++generation;
1424
+ profileSequence++;
1425
+ const current = () => mounted && generation === capturedGeneration;
1426
+ return {
1427
+ finish,
1428
+ setIsAuthenticated: (value) => {
1429
+ if (!current()) return;
1430
+ capturedGeneration = ++generation;
1431
+ profileSequence++;
1432
+ pending = false;
1433
+ publish({
1434
+ isAuthenticated: value,
1435
+ user: null,
1436
+ sessionError: null,
1437
+ sessionStatus: value ? "authenticated" : "signed-out",
1438
+ revalidatedAt: confirmedAt()
1439
+ });
1440
+ },
1441
+ refreshUser: async () => {
1442
+ if (current()) await refreshUser();
1443
+ }
1444
+ };
1445
+ }
1446
+ };
1447
+ }
1448
+
1449
+ // src/session-resume.ts
1450
+ import {
1451
+ createSessionResumeKeyPair,
1452
+ SESSION_RESUME_CHALLENGE_PATTERN,
1453
+ SESSION_RESUME_SESSION_ID_PATTERN,
1454
+ sessionResumePublicKeyOf,
1455
+ signSessionResume
1456
+ } from "@moon-x/core/sdk";
1457
+ import { PostMessageMethod as PostMessageMethod3, PostMessageType as PostMessageType3 } from "@moon-x/core/utils";
1458
+ var LOGOUT_TOMBSTONE = '{"loggedOut":true}';
1459
+ var sharedStates = /* @__PURE__ */ new Map();
1460
+ var sharedState = (publishableKey) => {
1461
+ let state = sharedStates.get(publishableKey);
1462
+ if (!state) {
1463
+ state = {
1464
+ queue: Promise.resolve(),
1465
+ blockCache: void 0,
1466
+ installId: void 0,
1467
+ logoutGeneration: 0,
1468
+ bindSequence: 0,
1469
+ loginsInProgress: 0,
1470
+ bindDeferred: false
1471
+ };
1472
+ sharedStates.set(publishableKey, state);
1473
+ }
1474
+ return state;
1475
+ };
1476
+ var storageKey = (publishableKey) => (
1477
+ // expo-secure-store keys allow only alphanumerics, ".", "-" and "_".
1478
+ `moonx.session_resume.${publishableKey.replace(/[^A-Za-z0-9._-]/g, "_")}`
1479
+ );
1480
+ var parseRecord = (raw) => {
1481
+ if (!raw) return null;
1482
+ try {
1483
+ const value = JSON.parse(raw);
1484
+ if (typeof value.privateKey !== "string" || typeof value.publicKey !== "string") return null;
1485
+ if (sessionResumePublicKeyOf(value.privateKey) !== value.publicKey) return null;
1486
+ const sessionId = typeof value.sessionId === "string" && SESSION_RESUME_SESSION_ID_PATTERN.test(value.sessionId) ? value.sessionId : void 0;
1487
+ return {
1488
+ privateKey: value.privateKey,
1489
+ publicKey: value.publicKey,
1490
+ ...typeof value.installId === "string" ? { installId: value.installId } : {},
1491
+ ...sessionId ? { sessionId } : {}
1492
+ };
1493
+ } catch {
1494
+ return null;
1495
+ }
1496
+ };
1497
+ var createNativeSessionResume = ({
1498
+ bridge,
1499
+ publishableKey,
1500
+ storage,
1501
+ blockStore
1502
+ }) => {
1503
+ const key = storageKey(publishableKey);
1504
+ const blockKey = `session_resume_blocked:${publishableKey}`;
1505
+ const shared = sharedState(publishableKey);
1506
+ const withLock = (run) => {
1507
+ const next = shared.queue.then(run, run);
1508
+ shared.queue = next.catch(() => void 0);
1509
+ return next;
1510
+ };
1511
+ const blockState = async () => {
1512
+ if (shared.blockCache === void 0) {
1513
+ const stored = await blockStore.get(blockKey);
1514
+ shared.blockCache = stored === null ? null : stored === "logout" ? "logout" : "blocked";
1515
+ }
1516
+ return shared.blockCache;
1517
+ };
1518
+ const isBlocked = async () => await blockState() !== null;
1519
+ const isLoggedOut = async () => await blockState() === "logout" || await storage.getItem(key) === LOGOUT_TOMBSTONE;
1520
+ const writeBlock = async (state) => {
1521
+ shared.blockCache = state;
1522
+ try {
1523
+ if (state) await blockStore.set(blockKey, state === "logout" ? "logout" : "1");
1524
+ else await blockStore.remove(blockKey);
1525
+ return true;
1526
+ } catch {
1527
+ return false;
1528
+ }
1529
+ };
1530
+ const setBlocked = async (value) => {
1531
+ let current;
1532
+ try {
1533
+ current = await blockState();
1534
+ } catch {
1535
+ return value ? writeBlock("logout") : false;
1536
+ }
1537
+ if (current === "logout") return value ? writeBlock("logout") : true;
1538
+ return writeBlock(value ? "blocked" : null);
1539
+ };
1540
+ const installKey = `session_resume_install:${publishableKey}`;
1541
+ const installId = async () => {
1542
+ if (shared.installId) return shared.installId;
1543
+ const stored = await blockStore.get(installKey);
1544
+ if (stored) return shared.installId = stored;
1545
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
1546
+ const created = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1547
+ await blockStore.set(installKey, created);
1548
+ return shared.installId = created;
1549
+ };
1550
+ const read = async () => {
1551
+ const record = parseRecord(await storage.getItem(key));
1552
+ if (!record) return null;
1553
+ if (record.installId === await installId()) return record;
1554
+ await clearKey();
1555
+ return null;
1556
+ };
1557
+ const write = async (record) => storage.setItem(key, JSON.stringify({ ...record, installId: await installId() }));
1558
+ const clearKey = async () => {
1559
+ for (let attempt = 0; attempt < 2; attempt++) {
1560
+ try {
1561
+ await storage.removeItem(key);
1562
+ await setBlocked(false);
1563
+ return "deleted";
1564
+ } catch {
1565
+ }
1566
+ }
1567
+ let tombstoned = false;
1568
+ try {
1569
+ await storage.setItem(key, "{}");
1570
+ tombstoned = true;
1571
+ } catch {
1572
+ }
1573
+ const markerPersisted = await setBlocked(true);
1574
+ if (!tombstoned && !markerPersisted) {
1575
+ console.warn(
1576
+ "MoonX: could not invalidate the session resume key in either store; it is blocked until the app restarts."
1577
+ );
1578
+ return "unrecorded";
1579
+ }
1580
+ return "invalidated";
1581
+ };
1582
+ const invalidateUnreadable = async () => {
1583
+ if (await setBlocked(true)) return true;
1584
+ try {
1585
+ await storage.setItem(key, LOGOUT_TOMBSTONE);
1586
+ return true;
1587
+ } catch {
1588
+ return false;
1589
+ }
1590
+ };
1591
+ const replace = async (record) => {
1592
+ try {
1593
+ await write(record);
1594
+ return true;
1595
+ } catch {
1596
+ await clearKey();
1597
+ return false;
838
1598
  }
839
1599
  };
1600
+ const forgetRecordedSession = async (record) => {
1601
+ try {
1602
+ await write({ privateKey: record.privateKey, publicKey: record.publicKey });
1603
+ return true;
1604
+ } catch {
1605
+ return await clearKey() !== "unrecorded";
1606
+ }
1607
+ };
1608
+ const bind = async () => {
1609
+ if (shared.loginsInProgress > 0) {
1610
+ shared.bindDeferred = true;
1611
+ return;
1612
+ }
1613
+ const sequence = ++shared.bindSequence;
1614
+ const isLatest = () => shared.bindSequence === sequence;
1615
+ await withLock(async () => {
1616
+ if (!isLatest()) return;
1617
+ try {
1618
+ if (await isLoggedOut()) return;
1619
+ } catch {
1620
+ await invalidateUnreadable();
1621
+ return;
1622
+ }
1623
+ let record;
1624
+ try {
1625
+ record = await read();
1626
+ } catch {
1627
+ await invalidateUnreadable();
1628
+ return;
1629
+ }
1630
+ if (!record) {
1631
+ record = createSessionResumeKeyPair();
1632
+ try {
1633
+ await write(record);
1634
+ } catch {
1635
+ return;
1636
+ }
1637
+ }
1638
+ let result = null;
1639
+ try {
1640
+ result = await bridge.send(
1641
+ PostMessageType3.AUTH,
1642
+ PostMessageMethod3.SESSION_RESUME_BIND,
1643
+ { publishableKey, publicKey: record.publicKey }
1644
+ );
1645
+ } catch {
1646
+ }
1647
+ if (!isLatest()) return;
1648
+ if (result?.bound && SESSION_RESUME_SESSION_ID_PATTERN.test(result.sessionId)) {
1649
+ if (record.sessionId === result.sessionId || await replace({ ...record, sessionId: result.sessionId })) {
1650
+ await setBlocked(false);
1651
+ }
1652
+ return;
1653
+ }
1654
+ if (record.sessionId && result?.sessionId !== record.sessionId) {
1655
+ await replace({ privateKey: record.privateKey, publicKey: record.publicKey });
1656
+ }
1657
+ });
1658
+ };
1659
+ const resume = () => withLock(async () => {
1660
+ if (await isBlocked()) return false;
1661
+ const record = await read();
1662
+ const sessionId = record?.sessionId;
1663
+ if (!record || !sessionId) return false;
1664
+ const check = await bridge.send(
1665
+ PostMessageType3.AUTH,
1666
+ PostMessageMethod3.IS_AUTHENTICATED,
1667
+ { publishableKey, resumeSessionId: sessionId }
1668
+ );
1669
+ if (check?.isAuthenticated === true) return true;
1670
+ if (check?.resumeRejected) {
1671
+ await clearKey();
1672
+ return false;
1673
+ }
1674
+ const challenge = check?.resumeChallenge;
1675
+ if (typeof challenge !== "string" || !SESSION_RESUME_CHALLENGE_PATTERN.test(challenge)) return false;
1676
+ const signature = signSessionResume(record.privateKey, sessionId, challenge);
1677
+ if (!signature) return false;
1678
+ const resumed = await bridge.send(
1679
+ PostMessageType3.AUTH,
1680
+ PostMessageMethod3.SESSION_RESUME,
1681
+ { publishableKey, sessionId, challenge, signature }
1682
+ );
1683
+ if (resumed?.resumeRejected) {
1684
+ await clearKey();
1685
+ return false;
1686
+ }
1687
+ return resumed?.isAuthenticated === true;
1688
+ });
1689
+ const logout = (run) => withLock(async () => {
1690
+ shared.logoutGeneration++;
1691
+ if (await clearKey() !== "deleted") {
1692
+ console.warn("MoonX: could not delete the session resume key; continuing logout to revoke the session.");
1693
+ }
1694
+ if (!await writeBlock("logout")) {
1695
+ try {
1696
+ await storage.setItem(key, LOGOUT_TOMBSTONE);
1697
+ } catch {
1698
+ }
1699
+ }
1700
+ return run();
1701
+ });
1702
+ const cancelPendingBinds = () => {
1703
+ shared.bindSequence++;
1704
+ };
1705
+ const forgetSession = () => withLock(async () => {
1706
+ let record;
1707
+ try {
1708
+ record = await read();
1709
+ } catch {
1710
+ if (!await invalidateUnreadable()) throw new Error("session_resume_storage_unavailable");
1711
+ return;
1712
+ }
1713
+ if (record?.sessionId && !await forgetRecordedSession(record) && !await invalidateUnreadable()) {
1714
+ throw new Error("session_resume_storage_unavailable");
1715
+ }
1716
+ });
1717
+ const clearLogoutBlock = (generation) => withLock(async () => {
1718
+ if (shared.logoutGeneration !== generation) return;
1719
+ try {
1720
+ if (await blockState() === "logout") await writeBlock(null);
1721
+ if (await storage.getItem(key) === LOGOUT_TOMBSTONE) await storage.removeItem(key);
1722
+ } catch {
1723
+ }
1724
+ });
1725
+ const beginLogin = async () => {
1726
+ shared.loginsInProgress++;
1727
+ const generation = shared.logoutGeneration;
1728
+ cancelPendingBinds();
1729
+ let released = false;
1730
+ const release = (succeeded = false) => {
1731
+ if (released) return;
1732
+ released = true;
1733
+ shared.loginsInProgress--;
1734
+ const cleared = succeeded ? clearLogoutBlock(generation) : Promise.resolve();
1735
+ if (shared.loginsInProgress === 0 && shared.bindDeferred) {
1736
+ shared.bindDeferred = false;
1737
+ void cleared.then(() => bind());
1738
+ }
1739
+ };
1740
+ try {
1741
+ await forgetSession();
1742
+ } catch (error) {
1743
+ release();
1744
+ throw error;
1745
+ }
1746
+ return release;
1747
+ };
1748
+ return { bind, beginLogin, cancelPendingBinds, resume, logout };
840
1749
  };
841
1750
 
842
1751
  // src/provider.tsx
843
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
1752
+ import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
844
1753
  var DEFAULT_IFRAME_URL = "https://x-iframe.moonpay.com";
845
1754
  var MoonXContext = createContext(null);
846
1755
  var MoonXProvider = ({
@@ -849,9 +1758,12 @@ var MoonXProvider = ({
849
1758
  children
850
1759
  }) => {
851
1760
  validatePublishableKey(publishableKey);
1761
+ return /* @__PURE__ */ jsx2(NativeProvider, { publishableKey, config, children }, JSON.stringify([publishableKey, config?.iframeUrl ?? DEFAULT_IFRAME_URL]));
1762
+ };
1763
+ var NativeProvider = ({ publishableKey, config, children }) => {
852
1764
  const iframeUrl = config?.iframeUrl ?? DEFAULT_IFRAME_URL;
853
1765
  const relyingPartyOrigin = config?.relyingPartyOrigin ?? "";
854
- const webViewRef = useRef(null);
1766
+ const webViewRef = useRef2(null);
855
1767
  const bridge = useMemo(
856
1768
  () => new WebViewBridge(
857
1769
  webViewRef
@@ -862,9 +1774,9 @@ var MoonXProvider = ({
862
1774
  () => makeRelyingPartyOriginResolver(bridge, publishableKey, relyingPartyOrigin),
863
1775
  [bridge, publishableKey, relyingPartyOrigin]
864
1776
  );
865
- const [sensitiveVisible, setSensitiveVisible] = useState(false);
866
- const [captchaChallengeVisible, setCaptchaChallengeVisible] = useState(false);
867
- const cancelRef = useRef(null);
1777
+ const [sensitiveVisible, setSensitiveVisible] = useState2(false);
1778
+ const [captchaChallengeVisible, setCaptchaChallengeVisible] = useState2(false);
1779
+ const cancelRef = useRef2(null);
868
1780
  const webViewVisible = sensitiveVisible || captchaChallengeVisible;
869
1781
  const [
870
1782
  {
@@ -874,43 +1786,52 @@ var MoonXProvider = ({
874
1786
  },
875
1787
  dispatchWebViewLifecycle
876
1788
  ] = useReducer(webViewLifecycleReducer, initialWebViewLifecycleState);
877
- const [isAuthenticated, setIsAuthenticated] = useState(false);
878
- const [user, setUser] = useState(null);
879
- const [revalidatedAt, setRevalidatedAt] = useState(0);
880
- const [restoreNonce, setRestoreNonce] = useState(0);
881
- const authFlowsInFlightRef = useRef(0);
882
- const sessionRevalidationGate = useMemo(
883
- () => createSessionRevalidationGate(),
884
- []
1789
+ const sessionResumeStorage = config?.sessionResumeStorage;
1790
+ const sessionResume = useMemo(
1791
+ () => sessionResumeStorage ? createNativeSessionResume({
1792
+ bridge,
1793
+ publishableKey,
1794
+ storage: sessionResumeStorage,
1795
+ blockStore: createAsyncStorageKv()
1796
+ }) : void 0,
1797
+ [bridge, publishableKey, sessionResumeStorage]
885
1798
  );
886
- const beginAuthFlow = useCallback(() => {
887
- authFlowsInFlightRef.current += 1;
888
- let finished = false;
889
- return () => {
890
- if (finished) return;
891
- finished = true;
892
- authFlowsInFlightRef.current = Math.max(
893
- 0,
894
- authFlowsInFlightRef.current - 1
895
- );
896
- if (authFlowsInFlightRef.current === 0) {
897
- setRestoreNonce((value) => value + 1);
898
- }
899
- };
900
- }, []);
901
- useEffect(() => {
1799
+ const session = useMemo(
1800
+ () => createNativeSession({
1801
+ getCurrentSession: () => bridge.send(PostMessageType4.AUTH, PostMessageMethod4.GET_CURRENT_SESSION, { publishableKey }),
1802
+ getUser: () => bridge.send(PostMessageType4.AUTH, PostMessageMethod4.GET_USER, { publishableKey }),
1803
+ resume: sessionResume?.resume
1804
+ }),
1805
+ [bridge, publishableKey, sessionResume]
1806
+ );
1807
+ const sessionSnapshot = useSyncExternalStore(session.subscribe, session.getSnapshot, session.getSnapshot);
1808
+ const { isAuthenticated, user, revalidatedAt } = sessionSnapshot;
1809
+ const { beginAuthFlow, refreshUser } = session;
1810
+ useLayoutEffect(() => {
1811
+ session.mount();
1812
+ return session.unmount;
1813
+ }, [session]);
1814
+ useEffect2(() => {
1815
+ session.setReady(ready);
1816
+ }, [session, ready]);
1817
+ const { sessionStatus } = sessionSnapshot;
1818
+ useEffect2(() => {
1819
+ if (!sessionResume || !ready || sessionStatus !== "authenticated") return;
1820
+ void sessionResume.bind();
1821
+ }, [sessionResume, ready, sessionStatus, revalidatedAt]);
1822
+ useEffect2(() => {
902
1823
  const subscription = AppState.addEventListener("change", (nextState) => {
903
1824
  if (nextState === "active") {
904
- setRestoreNonce((value) => value + 1);
1825
+ session.restartSession();
905
1826
  }
906
1827
  });
907
1828
  return () => subscription.remove();
908
- }, []);
1829
+ }, [session]);
909
1830
  const { height: screenHeight } = useWindowDimensions();
910
1831
  const SHEET_TOP_OFFSET = 80;
911
- const sheetTranslateY = useRef(new Animated.Value(screenHeight)).current;
912
- const backdropOpacity = useRef(new Animated.Value(0)).current;
913
- useEffect(() => {
1832
+ const sheetTranslateY = useRef2(new Animated.Value(screenHeight)).current;
1833
+ const backdropOpacity = useRef2(new Animated.Value(0)).current;
1834
+ useEffect2(() => {
914
1835
  Animated.parallel([
915
1836
  Animated.timing(sheetTranslateY, {
916
1837
  toValue: webViewVisible ? 0 : screenHeight,
@@ -935,13 +1856,6 @@ var MoonXProvider = ({
935
1856
  },
936
1857
  [bridge]
937
1858
  );
938
- const refreshUser = useCallback(async () => {
939
- try {
940
- const fetched = await sdkRef.current.getUser();
941
- if (fetched) setUser(fetched);
942
- } catch {
943
- }
944
- }, []);
945
1859
  const navigateWebView = useCallback(
946
1860
  (path) => {
947
1861
  const ref = webViewRef.current;
@@ -1013,9 +1927,9 @@ var MoonXProvider = ({
1013
1927
  user,
1014
1928
  ready,
1015
1929
  revalidatedAt,
1016
- setIsAuthenticated,
1017
- setUser,
1018
- refreshUser
1930
+ refreshUser,
1931
+ session,
1932
+ sessionResume
1019
1933
  }),
1020
1934
  [
1021
1935
  bridge,
@@ -1025,22 +1939,24 @@ var MoonXProvider = ({
1025
1939
  user,
1026
1940
  ready,
1027
1941
  revalidatedAt,
1028
- refreshUser
1942
+ refreshUser,
1943
+ session,
1944
+ sessionResume,
1945
+ sessionSnapshot
1029
1946
  ]
1030
1947
  );
1031
- const sdkRef = useRef(sdk);
1032
- useEffect(() => {
1033
- sdkRef.current = sdk;
1034
- }, [sdk]);
1035
- useEffect(() => {
1948
+ const sessionResumeRef = useRef2(sessionResume);
1949
+ sessionResumeRef.current = sessionResume;
1950
+ useEffect2(() => {
1036
1951
  return () => {
1952
+ sessionResumeRef.current?.cancelPendingBinds();
1037
1953
  bridge.cleanup("provider_unmounted");
1038
1954
  };
1039
1955
  }, [bridge]);
1040
- useEffect(
1956
+ useEffect2(
1041
1957
  () => bridge.register(
1042
- PostMessageType3.INIT,
1043
- PostMessageMethod3.CAPTCHA_CHALLENGE_VISIBILITY,
1958
+ PostMessageType4.INIT,
1959
+ PostMessageMethod4.CAPTCHA_CHALLENGE_VISIBILITY,
1044
1960
  (payload) => {
1045
1961
  if (typeof payload?.visible === "boolean") {
1046
1962
  setCaptchaChallengeVisible(payload.visible);
@@ -1049,21 +1965,17 @@ var MoonXProvider = ({
1049
1965
  ),
1050
1966
  [bridge]
1051
1967
  );
1052
- useEffect(() => {
1968
+ useEffect2(() => {
1053
1969
  const unsubscribe = bridge.onResponseError((error) => {
1054
- sessionRevalidationGate.request({
1055
- error,
1056
- authFlowsInFlight: authFlowsInFlightRef.current,
1057
- revalidate: () => setRestoreNonce((value) => value + 1)
1058
- });
1970
+ if (error.message === "no_session") session.retrySession();
1059
1971
  });
1060
1972
  return unsubscribe;
1061
- }, [bridge, sessionRevalidationGate]);
1062
- useEffect(() => {
1973
+ }, [bridge, session]);
1974
+ useEffect2(() => {
1063
1975
  let cancelled = false;
1064
1976
  const unregister = bridge.register(
1065
- PostMessageType3.INIT,
1066
- PostMessageMethod3.READY,
1977
+ PostMessageType4.INIT,
1978
+ PostMessageMethod4.READY,
1067
1979
  () => {
1068
1980
  if (!cancelled) dispatchWebViewLifecycle({ type: "ready" });
1069
1981
  }
@@ -1077,64 +1989,6 @@ var MoonXProvider = ({
1077
1989
  clearTimeout(fallback);
1078
1990
  };
1079
1991
  }, [bridge, webViewRecoveryNonce]);
1080
- useEffect(() => {
1081
- if (!ready) return;
1082
- const revalidationGeneration = sessionRevalidationGate.begin();
1083
- let cancelled = false;
1084
- let attempt = 0;
1085
- const maxAttempts = 5;
1086
- const timers = /* @__PURE__ */ new Set();
1087
- const schedule = (callback, delay) => {
1088
- const timer = setTimeout(() => {
1089
- timers.delete(timer);
1090
- callback();
1091
- }, delay);
1092
- timers.add(timer);
1093
- };
1094
- const tryRestore = async () => {
1095
- if (cancelled || authFlowsInFlightRef.current > 0) return;
1096
- attempt += 1;
1097
- try {
1098
- const session = await sdkRef.current.getCurrentSession();
1099
- if (cancelled || authFlowsInFlightRef.current > 0) return;
1100
- if (session) {
1101
- setIsAuthenticated(true);
1102
- try {
1103
- const u = await sdkRef.current.getUser();
1104
- if (!cancelled && u) setUser(u);
1105
- } catch {
1106
- }
1107
- if (!cancelled) setRevalidatedAt(Date.now());
1108
- sessionRevalidationGate.finish(revalidationGeneration);
1109
- return;
1110
- }
1111
- if (attempt < maxAttempts) {
1112
- const delay = 200 * 2 ** (attempt - 1);
1113
- schedule(tryRestore, delay);
1114
- } else if (!cancelled) {
1115
- setIsAuthenticated(false);
1116
- setUser(null);
1117
- setRevalidatedAt(Date.now());
1118
- sessionRevalidationGate.finish(revalidationGeneration);
1119
- }
1120
- } catch {
1121
- if (authFlowsInFlightRef.current > 0) return;
1122
- if (!cancelled && attempt < maxAttempts) {
1123
- const delay = 200 * 2 ** (attempt - 1);
1124
- schedule(tryRestore, delay);
1125
- } else if (!cancelled) {
1126
- setRevalidatedAt(Date.now());
1127
- sessionRevalidationGate.finish(revalidationGeneration);
1128
- }
1129
- }
1130
- };
1131
- schedule(tryRestore, restoreNonce > 0 ? 150 : 0);
1132
- return () => {
1133
- cancelled = true;
1134
- timers.forEach(clearTimeout);
1135
- timers.clear();
1136
- };
1137
- }, [ready, restoreNonce, sessionRevalidationGate]);
1138
1992
  const contextValue = useMemo(
1139
1993
  () => ({
1140
1994
  sdk,
@@ -1154,17 +2008,24 @@ var MoonXProvider = ({
1154
2008
  ]
1155
2009
  );
1156
2010
  const closeLabel = config?.sensitiveModalCopy?.closeLabel ?? "Done";
1157
- return /* @__PURE__ */ jsx(MoonXContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs(SDKProvider, { value: sdk, children: [
2011
+ return /* @__PURE__ */ jsx2(MoonXContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs2(SDKProvider, { value: sdk, children: [
1158
2012
  children,
1159
- /* @__PURE__ */ jsx(
2013
+ config?.presenceOtpPrompt !== false && /* @__PURE__ */ jsx2(
2014
+ PresenceOtpPrompt,
2015
+ {
2016
+ publishableKey,
2017
+ options: config?.presenceOtpPrompt
2018
+ }
2019
+ ),
2020
+ /* @__PURE__ */ jsx2(
1160
2021
  Animated.View,
1161
2022
  {
1162
- style: [styles.backdrop, { opacity: backdropOpacity }],
2023
+ style: [styles2.backdrop, { opacity: backdropOpacity }],
1163
2024
  pointerEvents: webViewVisible ? "auto" : "none",
1164
- children: /* @__PURE__ */ jsx(
1165
- Pressable,
2025
+ children: /* @__PURE__ */ jsx2(
2026
+ Pressable2,
1166
2027
  {
1167
- style: StyleSheet.absoluteFill,
2028
+ style: StyleSheet2.absoluteFill,
1168
2029
  onPress: () => {
1169
2030
  if (sensitiveVisible) cancelRef.current?.();
1170
2031
  }
@@ -1172,11 +2033,11 @@ var MoonXProvider = ({
1172
2033
  )
1173
2034
  }
1174
2035
  ),
1175
- /* @__PURE__ */ jsxs(
2036
+ /* @__PURE__ */ jsxs2(
1176
2037
  Animated.View,
1177
2038
  {
1178
2039
  style: [
1179
- styles.sheetContainer,
2040
+ styles2.sheetContainer,
1180
2041
  {
1181
2042
  top: captchaChallengeVisible ? 0 : SHEET_TOP_OFFSET,
1182
2043
  transform: [{ translateY: sheetTranslateY }]
@@ -1184,34 +2045,38 @@ var MoonXProvider = ({
1184
2045
  ],
1185
2046
  pointerEvents: webViewVisible ? "auto" : "none",
1186
2047
  children: [
1187
- sensitiveVisible && /* @__PURE__ */ jsxs(Fragment, { children: [
1188
- /* @__PURE__ */ jsx(View, { style: styles.sheetGrabber }),
1189
- /* @__PURE__ */ jsxs(View, { style: styles.modalChrome, children: [
1190
- /* @__PURE__ */ jsx(View, { style: styles.modalTitleSpacer }),
1191
- /* @__PURE__ */ jsx(
1192
- Pressable,
2048
+ sensitiveVisible && /* @__PURE__ */ jsxs2(Fragment, { children: [
2049
+ /* @__PURE__ */ jsx2(View2, { style: styles2.sheetGrabber }),
2050
+ /* @__PURE__ */ jsxs2(View2, { style: styles2.modalChrome, children: [
2051
+ /* @__PURE__ */ jsx2(View2, { style: styles2.modalTitleSpacer }),
2052
+ /* @__PURE__ */ jsx2(
2053
+ Pressable2,
1193
2054
  {
1194
2055
  onPress: () => cancelRef.current?.(),
1195
2056
  hitSlop: 12,
1196
- style: styles.closeButton,
1197
- children: /* @__PURE__ */ jsx(Text, { style: styles.closeButtonText, children: closeLabel })
2057
+ style: styles2.closeButton,
2058
+ children: /* @__PURE__ */ jsx2(Text2, { style: styles2.closeButtonText, children: closeLabel })
1198
2059
  }
1199
2060
  )
1200
2061
  ] })
1201
2062
  ] }),
1202
- /* @__PURE__ */ jsx(
2063
+ /* @__PURE__ */ jsx2(
1203
2064
  WebView,
1204
2065
  {
1205
2066
  ref: webViewRef,
1206
2067
  source: { uri: initialSourceUri },
1207
2068
  onMessage: handleMessage,
1208
2069
  onContentProcessDidTerminate: () => {
2070
+ session.setReady(false);
1209
2071
  dispatchWebViewLifecycle({ type: "recover", remount: false });
2072
+ sessionResume?.cancelPendingBinds();
1210
2073
  bridge.rejectAllPending("webview_process_terminated");
1211
2074
  webViewRef.current?.reload();
1212
2075
  },
1213
2076
  onRenderProcessGone: () => {
2077
+ session.setReady(false);
1214
2078
  dispatchWebViewLifecycle({ type: "recover", remount: true });
2079
+ sessionResume?.cancelPendingBinds();
1215
2080
  bridge.rejectAllPending("webview_process_terminated");
1216
2081
  },
1217
2082
  webviewDebuggingEnabled: __DEV__,
@@ -1221,7 +2086,7 @@ var MoonXProvider = ({
1221
2086
  thirdPartyCookiesEnabled: Platform.OS === "android",
1222
2087
  startInLoadingState: false,
1223
2088
  originWhitelist: ["https://*", "http://*"],
1224
- style: styles.webView
2089
+ style: styles2.webView
1225
2090
  },
1226
2091
  webViewKey
1227
2092
  )
@@ -1237,7 +2102,7 @@ var useMoonXContext = () => {
1237
2102
  }
1238
2103
  return ctx;
1239
2104
  };
1240
- var styles = StyleSheet.create({
2105
+ var styles2 = StyleSheet2.create({
1241
2106
  backdrop: {
1242
2107
  position: "absolute",
1243
2108
  top: 0,
@@ -1287,7 +2152,7 @@ var styles = StyleSheet.create({
1287
2152
  paddingBottom: 12,
1288
2153
  paddingHorizontal: 16,
1289
2154
  backgroundColor: "#0a0a0a",
1290
- borderBottomWidth: StyleSheet.hairlineWidth,
2155
+ borderBottomWidth: StyleSheet2.hairlineWidth,
1291
2156
  borderBottomColor: "#222"
1292
2157
  },
1293
2158
  // Empty flex spacer keeps the close button right-aligned without
@@ -1312,6 +2177,7 @@ var styles = StyleSheet.create({
1312
2177
  import {
1313
2178
  useAddPasskey,
1314
2179
  useBulkImport,
2180
+ useChangeEmail,
1315
2181
  useCreateWallet,
1316
2182
  useEphemeralSigner,
1317
2183
  useImportKey,
@@ -1325,16 +2191,16 @@ import {
1325
2191
  } from "@moon-x/core/react";
1326
2192
 
1327
2193
  // src/hooks/use-app-config.ts
1328
- import { PostMessageMethod as PostMessageMethod4, PostMessageType as PostMessageType4 } from "@moon-x/core/utils";
1329
- import { useEffect as useEffect2, useState as useState2 } from "react";
2194
+ import { PostMessageMethod as PostMessageMethod5, PostMessageType as PostMessageType5 } from "@moon-x/core/utils";
2195
+ import { useEffect as useEffect3, useState as useState3 } from "react";
1330
2196
  var useAppConfig = (publishableKey) => {
1331
2197
  const { sdk, _bridge } = useMoonXContext();
1332
2198
  const resolvedKey = publishableKey ?? sdk.publishableKey;
1333
2199
  const ready = sdk.ready;
1334
- const [appConfig, setAppConfig] = useState2(null);
1335
- const [isLoading, setIsLoading] = useState2(true);
1336
- const [error, setError] = useState2(null);
1337
- useEffect2(() => {
2200
+ const [appConfig, setAppConfig] = useState3(null);
2201
+ const [isLoading, setIsLoading] = useState3(true);
2202
+ const [error, setError] = useState3(null);
2203
+ useEffect3(() => {
1338
2204
  if (!resolvedKey) {
1339
2205
  setIsLoading(false);
1340
2206
  return;
@@ -1348,7 +2214,7 @@ var useAppConfig = (publishableKey) => {
1348
2214
  setError(null);
1349
2215
  setAppConfig(null);
1350
2216
  try {
1351
- const config = await _bridge.send(PostMessageType4.AUTH, PostMessageMethod4.GET_APP_CONFIG, {
2217
+ const config = await _bridge.send(PostMessageType5.AUTH, PostMessageMethod5.GET_APP_CONFIG, {
1352
2218
  publishableKey: resolvedKey
1353
2219
  });
1354
2220
  if (!cancelled) setAppConfig(config);
@@ -1369,8 +2235,8 @@ var useAppConfig = (publishableKey) => {
1369
2235
  };
1370
2236
 
1371
2237
  // src/hooks/use-attach-oauth.ts
1372
- import { PostMessageMethod as PostMessageMethod5, PostMessageType as PostMessageType5 } from "@moon-x/core/utils";
1373
- import { useState as useState3 } from "react";
2238
+ import { PostMessageMethod as PostMessageMethod6, PostMessageType as PostMessageType6 } from "@moon-x/core/utils";
2239
+ import { useState as useState4 } from "react";
1374
2240
 
1375
2241
  // src/lib/oauth-deep-link.ts
1376
2242
  var openOAuthFlow = async ({
@@ -1411,7 +2277,7 @@ var parseOAuthRedirect = async (redirectUrl) => {
1411
2277
  // src/hooks/use-attach-oauth.ts
1412
2278
  var useAttachOAuth = (params) => {
1413
2279
  const { sdk, _bridge, _oauthRedirectUri } = useMoonXContext();
1414
- const [state, setState] = useState3({ status: "idle" });
2280
+ const [state, setState] = useState4({ status: "idle" });
1415
2281
  return {
1416
2282
  state,
1417
2283
  attachOAuth: async (provider) => {
@@ -1420,8 +2286,8 @@ var useAttachOAuth = (params) => {
1420
2286
  const redirectUri = params?.redirectUri || _oauthRedirectUri;
1421
2287
  if (!redirectUri) throw new Error("oauth_redirect_uri_missing");
1422
2288
  const startResult = await _bridge.send(
1423
- PostMessageType5.AUTH,
1424
- PostMessageMethod5.START_OAUTH,
2289
+ PostMessageType6.AUTH,
2290
+ PostMessageMethod6.START_OAUTH,
1425
2291
  {
1426
2292
  publishableKey: sdk.publishableKey,
1427
2293
  provider,
@@ -1441,8 +2307,8 @@ var useAttachOAuth = (params) => {
1441
2307
  if (parsed.error) throw new Error(parsed.error);
1442
2308
  setState({ status: "verifying" });
1443
2309
  await _bridge.send(
1444
- PostMessageType5.AUTH,
1445
- PostMessageMethod5.ATTACH_OAUTH,
2310
+ PostMessageType6.AUTH,
2311
+ PostMessageMethod6.ATTACH_OAUTH,
1446
2312
  {
1447
2313
  publishableKey: sdk.publishableKey,
1448
2314
  provider,
@@ -1463,14 +2329,14 @@ var useAttachOAuth = (params) => {
1463
2329
  };
1464
2330
 
1465
2331
  // src/hooks/use-detach-oauth.ts
1466
- import { PostMessageMethod as PostMessageMethod6, PostMessageType as PostMessageType6 } from "@moon-x/core/utils";
2332
+ import { PostMessageMethod as PostMessageMethod7, PostMessageType as PostMessageType7 } from "@moon-x/core/utils";
1467
2333
  var useDetachOAuth = () => {
1468
2334
  const { sdk, _bridge } = useMoonXContext();
1469
2335
  return {
1470
2336
  detachOAuth: async (idpUserId) => {
1471
2337
  await _bridge.send(
1472
- PostMessageType6.AUTH,
1473
- PostMessageMethod6.DETACH_OAUTH,
2338
+ PostMessageType7.AUTH,
2339
+ PostMessageMethod7.DETACH_OAUTH,
1474
2340
  { publishableKey: sdk.publishableKey, idpUserId }
1475
2341
  );
1476
2342
  }
@@ -1479,7 +2345,7 @@ var useDetachOAuth = () => {
1479
2345
 
1480
2346
  // src/hooks/use-export-key.ts
1481
2347
  import { getInternalPresenceTokens as getInternalPresenceTokens2, SCOPES_EXPORT_KEY } from "@moon-x/core/sdk";
1482
- import { PostMessageMethod as PostMessageMethod7, PostMessageType as PostMessageType7 } from "@moon-x/core/utils";
2348
+ import { PostMessageMethod as PostMessageMethod8, PostMessageType as PostMessageType8 } from "@moon-x/core/utils";
1483
2349
  var parseExportKeyResult = (value) => {
1484
2350
  if (!value || typeof value !== "object" || !("status" in value)) {
1485
2351
  return { status: "failed", error: "invalid_export_key_result" };
@@ -1523,8 +2389,8 @@ var useExportKey = () => {
1523
2389
  title: "Export key",
1524
2390
  flowPath: `/export-key?${params.toString()}#${secrets.toString()}`,
1525
2391
  onMount: ({ bridge, setResult }) => bridge.register(
1526
- PostMessageType7.WALLET,
1527
- PostMessageMethod7.EXPORT_KEY_RESULT,
2392
+ PostMessageType8.WALLET,
2393
+ PostMessageMethod8.EXPORT_KEY_RESULT,
1528
2394
  (result) => {
1529
2395
  setResult(parseExportKeyResult(result));
1530
2396
  }
@@ -1570,56 +2436,77 @@ var useLoginWithEmail = (callbacks) => {
1570
2436
  };
1571
2437
 
1572
2438
  // src/hooks/use-login-with-oauth.ts
1573
- import { PostMessageMethod as PostMessageMethod8, PostMessageType as PostMessageType8 } from "@moon-x/core/utils";
1574
- import { useState as useState4 } from "react";
2439
+ import { PostMessageMethod as PostMessageMethod9, PostMessageType as PostMessageType9 } from "@moon-x/core/utils";
2440
+ import { useEffect as useEffect4, useRef as useRef3, useState as useState5 } from "react";
1575
2441
  var useLoginWithOAuth = (params) => {
1576
2442
  const { sdk, _bridge, _oauthRedirectUri, _beginAuthFlow } = useMoonXContext();
1577
- const [state, setState] = useState4({ status: "idle" });
2443
+ const [state, setState] = useState5({ status: "idle" });
2444
+ const activeFlow = useRef3(null);
2445
+ const mounted = useRef3(true);
2446
+ useEffect4(() => {
2447
+ mounted.current = true;
2448
+ return () => {
2449
+ mounted.current = false;
2450
+ };
2451
+ }, []);
1578
2452
  return {
1579
2453
  state,
1580
2454
  loginWithOAuth: async (provider) => {
1581
- const finishAuthFlow = _beginAuthFlow();
1582
- setState({ status: "starting" });
2455
+ const finishAuthFlow = _beginAuthFlow({ replaceSession: true });
2456
+ const previousFlow = activeFlow.current;
2457
+ activeFlow.current = finishAuthFlow;
2458
+ previousFlow?.();
2459
+ const assertCurrent = () => {
2460
+ if (activeFlow.current !== finishAuthFlow) throw new Error("session_changed");
2461
+ finishAuthFlow.assertCurrent();
2462
+ };
2463
+ const update = (next) => {
2464
+ if (mounted.current && activeFlow.current === finishAuthFlow) setState(next);
2465
+ };
2466
+ update({ status: "starting" });
1583
2467
  try {
1584
2468
  const redirectUri = params?.redirectUri || _oauthRedirectUri;
1585
2469
  if (!redirectUri) {
1586
2470
  throw new Error("oauth_redirect_uri_missing");
1587
2471
  }
1588
2472
  const startResult = await _bridge.send(
1589
- PostMessageType8.AUTH,
1590
- PostMessageMethod8.START_OAUTH,
2473
+ PostMessageType9.AUTH,
2474
+ PostMessageMethod9.START_OAUTH,
1591
2475
  {
1592
2476
  publishableKey: sdk.publishableKey,
1593
2477
  provider,
1594
2478
  login_redirect_url: redirectUri
1595
2479
  }
1596
2480
  );
2481
+ assertCurrent();
1597
2482
  if (!startResult.redirect_url) {
1598
2483
  throw new Error("start_oauth_failed");
1599
2484
  }
1600
- setState({ status: "redirecting" });
2485
+ update({ status: "redirecting" });
1601
2486
  const { redirectUrl } = await openOAuthFlow({
1602
2487
  authUrl: startResult.redirect_url,
1603
2488
  redirectUri
1604
2489
  });
1605
2490
  const parsed = await parseOAuthRedirect(redirectUrl);
2491
+ assertCurrent();
1606
2492
  if (parsed.error) throw new Error(parsed.error);
1607
2493
  if (!parsed.code && !parsed.token) {
1608
2494
  throw new Error("oauth_no_code_or_token");
1609
2495
  }
1610
- setState({ status: "verifying" });
2496
+ update({ status: "verifying" });
1611
2497
  const result = await sdk.verifyOAuth({
1612
2498
  provider,
1613
2499
  code: parsed.code,
1614
2500
  token: parsed.token,
1615
2501
  state: parsed.state
1616
2502
  });
1617
- setState({ status: "complete", user: result?.user ?? result ?? null });
2503
+ update({ status: "complete", user: result?.user ?? result ?? null });
1618
2504
  } catch (e) {
1619
2505
  const err = e instanceof Error ? e : new Error(String(e));
1620
- setState({ status: "error", error: err });
2506
+ update({ status: "error", error: err });
1621
2507
  throw err;
1622
2508
  } finally {
2509
+ if (activeFlow.current === finishAuthFlow) activeFlow.current = null;
1623
2510
  finishAuthFlow();
1624
2511
  }
1625
2512
  },
@@ -1631,17 +2518,17 @@ var useLoginWithOAuth = (params) => {
1631
2518
  var useMoonX = () => useMoonXContext().sdk;
1632
2519
 
1633
2520
  // src/external-wallets/use-external-wallets.ts
1634
- import { useCallback as useCallback3, useEffect as useEffect3, useRef as useRef2, useState as useState5 } from "react";
2521
+ import { useCallback as useCallback3, useEffect as useEffect5, useRef as useRef4, useState as useState6 } from "react";
1635
2522
  var useExternalWallets = (connectors) => {
1636
- const [wallets, setWallets] = useState5([]);
1637
- const [connected, setConnected] = useState5(
2523
+ const [wallets, setWallets] = useState6([]);
2524
+ const [connected, setConnected] = useState6(
1638
2525
  null
1639
2526
  );
1640
- const [status, setStatus] = useState5("idle");
1641
- const [error, setError] = useState5(null);
1642
- const [refreshNonce, setRefreshNonce] = useState5(0);
1643
- const unsubscribeRef = useRef2(null);
1644
- useEffect3(() => {
2527
+ const [status, setStatus] = useState6("idle");
2528
+ const [error, setError] = useState6(null);
2529
+ const [refreshNonce, setRefreshNonce] = useState6(0);
2530
+ const unsubscribeRef = useRef4(null);
2531
+ useEffect5(() => {
1645
2532
  let cancelled = false;
1646
2533
  void Promise.all(
1647
2534
  connectors.map(async (connector) => ({
@@ -1655,7 +2542,7 @@ var useExternalWallets = (connectors) => {
1655
2542
  cancelled = true;
1656
2543
  };
1657
2544
  }, [connectors, refreshNonce]);
1658
- useEffect3(
2545
+ useEffect5(
1659
2546
  () => () => {
1660
2547
  unsubscribeRef.current?.();
1661
2548
  },
@@ -1995,22 +2882,23 @@ var restoreWalletConnectSession = (options) => {
1995
2882
 
1996
2883
  // src/index.ts
1997
2884
  import { MOONPAY_CONSUMER_SESSION_ERROR_CODES } from "@moon-x/core/sdk";
1998
- import { registerPresenceOtpCodeProvider } from "@moon-x/core/sdk";
1999
- import { PostMessageMethod as PostMessageMethod9, PostMessageType as PostMessageType9 } from "@moon-x/core/utils";
2885
+ import { registerPresenceOtpCodeProvider as registerPresenceOtpCodeProvider2 } from "@moon-x/core/sdk";
2886
+ import { PostMessageMethod as PostMessageMethod10, PostMessageType as PostMessageType10 } from "@moon-x/core/utils";
2000
2887
  export {
2001
2888
  MOONPAY_CONSUMER_SESSION_ERROR_CODES,
2002
2889
  MoonXProvider as MoonKeyProvider,
2003
2890
  MoonXProvider,
2004
- PostMessageMethod9 as PostMessageMethod,
2005
- PostMessageType9 as PostMessageType,
2891
+ PostMessageMethod10 as PostMessageMethod,
2892
+ PostMessageType10 as PostMessageType,
2006
2893
  connectWalletConnect,
2007
2894
  listWalletConnectSessions,
2008
- registerPresenceOtpCodeProvider,
2895
+ registerPresenceOtpCodeProvider2 as registerPresenceOtpCodeProvider,
2009
2896
  restoreWalletConnectSession,
2010
2897
  useAddPasskey,
2011
2898
  useAppConfig,
2012
2899
  useAttachOAuth,
2013
2900
  useBulkImport,
2901
+ useChangeEmail,
2014
2902
  useCreateWallet,
2015
2903
  useDetachOAuth,
2016
2904
  useEphemeralSigner,