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