@moon-x/react-native-sdk 0.0.1

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.js ADDED
@@ -0,0 +1,1008 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ MoonKeyProvider: () => MoonKeyProvider,
34
+ PostMessageMethod: () => import_utils7.PostMessageMethod,
35
+ PostMessageType: () => import_utils7.PostMessageType,
36
+ useAddPasskey: () => import_react5.useAddPasskey,
37
+ useAttachOAuth: () => useAttachOAuth,
38
+ useCreateWallet: () => import_react5.useCreateWallet,
39
+ useDetachOAuth: () => useDetachOAuth,
40
+ useExportKey: () => useExportKey,
41
+ useImportKey: () => import_react5.useImportKey,
42
+ useLoginWithEmail: () => import_react5.useLoginWithEmail,
43
+ useLoginWithOAuth: () => useLoginWithOAuth,
44
+ useLogout: () => import_react5.useLogout,
45
+ useMoonKey: () => useMoonKey,
46
+ useMoonKeyContext: () => useMoonKeyContext,
47
+ usePasskeyStatus: () => import_react5.usePasskeyStatus,
48
+ useRegisterPasskey: () => import_react5.useRegisterPasskey,
49
+ useRemovePasskey: () => import_react5.useRemovePasskey,
50
+ useUser: () => import_react5.useUser,
51
+ useWallets: () => import_react5.useWallets
52
+ });
53
+ module.exports = __toCommonJS(index_exports);
54
+
55
+ // src/provider.tsx
56
+ var import_react = require("react");
57
+ var import_react_native = require("react-native");
58
+ var import_react_native_webview = require("react-native-webview");
59
+
60
+ // src/sdk/sdk-authentication-methods.ts
61
+ var import_sdk = require("@moon-x/core/sdk");
62
+ var getAuthenticationMethods = (bridge, publishableKey, emailConfig, setIsAuthenticated, setUser) => (0, import_sdk.getHeadlessAuthenticationMethods)({
63
+ transport: bridge,
64
+ publishableKey,
65
+ emailConfig,
66
+ setIsAuthenticated,
67
+ setUser
68
+ });
69
+
70
+ // src/sdk/sdk-ethereum-methods.ts
71
+ var import_sdk2 = require("@moon-x/core/sdk");
72
+
73
+ // src/platform/async-storage-kv.ts
74
+ var import_async_storage = __toESM(require("@react-native-async-storage/async-storage"));
75
+ var createAsyncStorageKv = (prefix = "moonkey:") => ({
76
+ get: async (key) => import_async_storage.default.getItem(prefix + key),
77
+ set: async (key, value) => import_async_storage.default.setItem(prefix + key, value),
78
+ remove: async (key) => import_async_storage.default.removeItem(prefix + key)
79
+ });
80
+
81
+ // src/platform/rn-passkey.ts
82
+ var import_react_native_passkeys = require("react-native-passkeys");
83
+ var import_lib = require("@moon-x/core/lib");
84
+ var createRNPasskey = () => ({
85
+ assert: async ({ rpId, challenge }) => {
86
+ const credential = await (0, import_react_native_passkeys.get)({
87
+ challenge,
88
+ rpId,
89
+ allowCredentials: [],
90
+ userVerification: "preferred"
91
+ });
92
+ if (!credential) throw new Error("passkey_assertion_cancelled");
93
+ const userHandle = credential.response.userHandle;
94
+ if (!userHandle) throw new Error("user_handle_missing");
95
+ return {
96
+ rawIdB64url: credential.rawId,
97
+ userHandleB64url: userHandle
98
+ };
99
+ },
100
+ create: async ({
101
+ rpId,
102
+ rpName,
103
+ userId,
104
+ userName,
105
+ userDisplayName,
106
+ challenge,
107
+ excludeCredentials
108
+ }) => {
109
+ const credential = await (0, import_react_native_passkeys.create)({
110
+ challenge,
111
+ rp: { id: rpId, name: rpName },
112
+ user: {
113
+ id: (0, import_lib.toB64url)(userId),
114
+ name: userName,
115
+ displayName: userDisplayName
116
+ },
117
+ pubKeyCredParams: [
118
+ { type: "public-key", alg: -7 },
119
+ { type: "public-key", alg: -257 }
120
+ ],
121
+ authenticatorSelection: {
122
+ residentKey: "required",
123
+ userVerification: "preferred"
124
+ },
125
+ excludeCredentials: (excludeCredentials ?? []).map((id) => ({
126
+ id,
127
+ type: "public-key"
128
+ }))
129
+ });
130
+ if (!credential) throw new Error("passkey_registration_cancelled");
131
+ return {
132
+ rawIdB64url: credential.rawId,
133
+ clientDataJSONB64url: credential.response.clientDataJSON,
134
+ attestationObjectB64url: credential.response.attestationObject
135
+ };
136
+ }
137
+ });
138
+
139
+ // src/sdk/sdk-ethereum-methods.ts
140
+ var getEthereumSDKMethods = (bridge, publishableKey) => (0, import_sdk2.getHeadlessEthereumMethods)({
141
+ transport: bridge,
142
+ passkey: createRNPasskey(),
143
+ publishableKey
144
+ });
145
+
146
+ // src/sdk/sdk-passkey-methods.ts
147
+ var import_lib2 = require("@moon-x/core/lib");
148
+ var import_sdk3 = require("@moon-x/core/sdk");
149
+ var import_utils = require("@moon-x/core/utils");
150
+ var import_react_native_passkeys2 = require("react-native-passkeys");
151
+ var getPasskeyMethods = (bridge, publishableKey) => ({
152
+ registerPasskey: async (params) => {
153
+ const dekInfo = await bridge.send(
154
+ import_utils.PostMessageType.AUTH,
155
+ import_utils.PostMessageMethod.GET_DEK_INFO,
156
+ { publishableKey }
157
+ );
158
+ if (!dekInfo.rp_id) {
159
+ throw new Error("webauthn_rp_id_not_configured");
160
+ }
161
+ const rpId = dekInfo.rp_id;
162
+ const relyingPartyOrigin = `https://${rpId}`;
163
+ const isAdditional = (dekInfo.allow_credential_ids_b64url ?? []).length > 0;
164
+ let unlock = null;
165
+ if (isAdditional) {
166
+ unlock = await (0, import_sdk3.assertPasskeyInParent)({
167
+ transport: bridge,
168
+ passkey: createRNPasskey(),
169
+ publishableKey,
170
+ requireFreshAssertion: true
171
+ });
172
+ const allowList = dekInfo.allow_credential_ids_b64url ?? [];
173
+ if (!allowList.includes(unlock.credentialIdB64url)) {
174
+ throw new Error("unknown_passkey_for_this_account");
175
+ }
176
+ }
177
+ const beginResult = await bridge.send(
178
+ import_utils.PostMessageType.AUTH,
179
+ import_utils.PostMessageMethod.PASSKEY_REGISTER_BEGIN,
180
+ {
181
+ publishableKey,
182
+ relyingPartyOrigin,
183
+ displayName: params?.displayName,
184
+ additional: isAdditional
185
+ }
186
+ );
187
+ const options = beginResult.optionsJSON;
188
+ const token = beginResult.token;
189
+ if (!options || !token) {
190
+ throw new Error("passkey_register_begin_no_options");
191
+ }
192
+ const { userIdB64url } = (0, import_lib2.generatePasskeyUserId)();
193
+ options.user.id = userIdB64url;
194
+ if (!options.challenge) {
195
+ const challengeBytes = crypto.getRandomValues(new Uint8Array(32));
196
+ options.challenge = (0, import_lib2.toB64url)(challengeBytes);
197
+ }
198
+ const credential = await (0, import_react_native_passkeys2.create)(
199
+ options
200
+ );
201
+ if (!credential) throw new Error("passkey_register_cancelled");
202
+ await bridge.send(
203
+ import_utils.PostMessageType.AUTH,
204
+ import_utils.PostMessageMethod.PASSKEY_REGISTER_VERIFY,
205
+ {
206
+ publishableKey,
207
+ relyingPartyOrigin,
208
+ token,
209
+ credential,
210
+ userIdB64url
211
+ }
212
+ );
213
+ if (isAdditional && unlock) {
214
+ await bridge.send(
215
+ import_utils.PostMessageType.AUTH,
216
+ import_utils.PostMessageMethod.ADD_PASSKEY_WRAP,
217
+ {
218
+ publishableKey,
219
+ unlockUserHandleB64url: unlock.userHandleB64url,
220
+ unlockCredentialIdB64url: unlock.credentialIdB64url,
221
+ newUserHandleB64url: userIdB64url,
222
+ newCredentialIdB64url: credential.rawId
223
+ }
224
+ );
225
+ }
226
+ return { credential_id: credential.rawId };
227
+ }
228
+ });
229
+
230
+ // src/sdk/sdk-methods.ts
231
+ var import_sdk4 = require("@moon-x/core/sdk");
232
+ var getSDKMethods = (bridge, publishableKey, setIsAuthenticated, setUser) => (0, import_sdk4.getHeadlessGeneralMethods)({
233
+ transport: bridge,
234
+ passkey: createRNPasskey(),
235
+ storage: createAsyncStorageKv(),
236
+ publishableKey,
237
+ setIsAuthenticated,
238
+ setUser
239
+ });
240
+
241
+ // src/sdk/sdk-solana-methods.ts
242
+ var import_sdk5 = require("@moon-x/core/sdk");
243
+ var getSolanaSDKMethods = (bridge, publishableKey) => (0, import_sdk5.getHeadlessSolanaMethods)({
244
+ transport: bridge,
245
+ passkey: createRNPasskey(),
246
+ publishableKey
247
+ });
248
+
249
+ // src/sdk/create-sdk-instance.ts
250
+ var createSdkInstance = ({
251
+ bridge,
252
+ publishableKey,
253
+ emailConfig,
254
+ isAuthenticated,
255
+ user,
256
+ ready,
257
+ setIsAuthenticated,
258
+ setUser,
259
+ refreshUser
260
+ }) => ({
261
+ publishableKey,
262
+ ready,
263
+ isAuthenticated,
264
+ user,
265
+ refreshUser,
266
+ ...getAuthenticationMethods(
267
+ bridge,
268
+ publishableKey,
269
+ emailConfig,
270
+ setIsAuthenticated,
271
+ setUser
272
+ ),
273
+ ...getSDKMethods(bridge, publishableKey, setIsAuthenticated, setUser),
274
+ ...getPasskeyMethods(bridge, publishableKey),
275
+ ...getEthereumSDKMethods(bridge, publishableKey),
276
+ ...getSolanaSDKMethods(bridge, publishableKey)
277
+ });
278
+
279
+ // src/provider.tsx
280
+ var import_lib3 = require("@moon-x/core/lib");
281
+ var import_utils3 = require("@moon-x/core/utils");
282
+
283
+ // src/transport/webview-bridge.ts
284
+ var import_utils2 = require("@moon-x/core/utils");
285
+ var REQUEST_TIMEOUT_MS = 3e4;
286
+ var generateUUID = () => {
287
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
288
+ return crypto.randomUUID();
289
+ }
290
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
291
+ const r = Math.random() * 16 | 0;
292
+ const v = c === "x" ? r : r & 3 | 8;
293
+ return v.toString(16);
294
+ });
295
+ };
296
+ var bigintReplacer = (_key, value) => typeof value === "bigint" ? value.toString() : value;
297
+ var buildInjectScript = (envelope) => {
298
+ const payload = JSON.stringify(envelope, bigintReplacer);
299
+ return `
300
+ (function() {
301
+ try {
302
+ var msg = JSON.parse(${JSON.stringify(payload)});
303
+ var event;
304
+ try {
305
+ event = new MessageEvent('message', {
306
+ data: msg,
307
+ origin: window.location.origin,
308
+ source: window
309
+ });
310
+ } catch (e) {
311
+ event = document.createEvent('MessageEvent');
312
+ event.initMessageEvent(
313
+ 'message',
314
+ false,
315
+ false,
316
+ msg,
317
+ window.location.origin,
318
+ '',
319
+ window,
320
+ null
321
+ );
322
+ }
323
+ window.dispatchEvent(event);
324
+ } catch (e) {
325
+ if (window.ReactNativeWebView) {
326
+ window.ReactNativeWebView.postMessage(JSON.stringify({
327
+ __moonx_bridge_error: true,
328
+ error: String(e && e.message || e)
329
+ }));
330
+ }
331
+ }
332
+ })();
333
+ true;
334
+ `;
335
+ };
336
+ var WebViewBridge = class {
337
+ constructor(webViewRef) {
338
+ this.pending = /* @__PURE__ */ new Map();
339
+ this.oneWayHandlers = /* @__PURE__ */ new Map();
340
+ // Wire to <WebView onMessage={bridge.handleMessage}>. Demultiplexes
341
+ // by request id; one-way messages (no id, or unknown id) fall through
342
+ // to handlers registered via `register`.
343
+ this.handleMessage = (event) => {
344
+ let parsed;
345
+ try {
346
+ parsed = JSON.parse(event.nativeEvent.data);
347
+ } catch {
348
+ return;
349
+ }
350
+ if (!parsed || typeof parsed !== "object") return;
351
+ const message = parsed;
352
+ if (typeof message.id === "string" && this.pending.has(message.id)) {
353
+ const resolver = this.pending.get(message.id);
354
+ this.pending.delete(message.id);
355
+ clearTimeout(resolver.timeoutId);
356
+ if (message.success) {
357
+ resolver.resolve(message.data);
358
+ } else {
359
+ const err = new Error(message.error || "WebView bridge error");
360
+ for (const key of import_utils2.FORWARDED_ERROR_FIELDS) {
361
+ const value = message[key];
362
+ if (value !== void 0) {
363
+ err[key] = value;
364
+ }
365
+ }
366
+ resolver.reject(err);
367
+ }
368
+ return;
369
+ }
370
+ if (typeof message.type === "string" && typeof message.method === "string") {
371
+ const key = `${message.type}:${message.method}`;
372
+ const handler = this.oneWayHandlers.get(key);
373
+ if (handler) handler(message.payload);
374
+ }
375
+ };
376
+ this.webViewRef = webViewRef;
377
+ }
378
+ // Subscribe to a one-way message kind. Returns an unsubscribe fn.
379
+ register(type, method, handler) {
380
+ const key = `${type}:${method}`;
381
+ this.oneWayHandlers.set(key, handler);
382
+ return () => {
383
+ if (this.oneWayHandlers.get(key) === handler) {
384
+ this.oneWayHandlers.delete(key);
385
+ }
386
+ };
387
+ }
388
+ // Conforms to the `Transport.isReady()` half of @moon-x/core/sdk's
389
+ // interface — used by shared SDK factories to short-circuit before
390
+ // attempting to inject JS into a not-yet-mounted WebView.
391
+ isReady() {
392
+ return !!this.webViewRef.current;
393
+ }
394
+ // Request/response. Same envelope as @moon-x/core PostMessageClient.
395
+ send(type, method, payload) {
396
+ const ref = this.webViewRef.current;
397
+ if (!ref) {
398
+ return Promise.reject(new Error("webview_not_ready"));
399
+ }
400
+ const id = generateUUID();
401
+ return new Promise((resolve, reject) => {
402
+ const timeoutId = setTimeout(() => {
403
+ this.pending.delete(id);
404
+ reject(new Error("Timeout: No response from WebView"));
405
+ }, REQUEST_TIMEOUT_MS);
406
+ this.pending.set(id, {
407
+ resolve,
408
+ reject,
409
+ timeoutId
410
+ });
411
+ const envelope = { id, type, method, payload };
412
+ try {
413
+ ref.injectJavaScript(buildInjectScript(envelope));
414
+ } catch (error) {
415
+ this.pending.delete(id);
416
+ clearTimeout(timeoutId);
417
+ reject(
418
+ error instanceof Error ? error : new Error("inject_javascript_failed")
419
+ );
420
+ }
421
+ });
422
+ }
423
+ // Fire-and-forget. The iframe-app may or may not reply; we don't
424
+ // hold a resolver. Used for things like CLOSE / cleanup signals.
425
+ sendOneWay(type, method, payload) {
426
+ const ref = this.webViewRef.current;
427
+ if (!ref) return;
428
+ const id = generateUUID();
429
+ const envelope = { id, type, method, payload };
430
+ try {
431
+ ref.injectJavaScript(buildInjectScript(envelope));
432
+ } catch {
433
+ }
434
+ }
435
+ // Reject every outstanding request — wire on unmount so dangling
436
+ // promises don't dangle forever.
437
+ cleanup(reason = "webview_unmounted") {
438
+ for (const [id, resolver] of this.pending.entries()) {
439
+ clearTimeout(resolver.timeoutId);
440
+ resolver.reject(new Error(reason));
441
+ this.pending.delete(id);
442
+ }
443
+ this.oneWayHandlers.clear();
444
+ }
445
+ };
446
+
447
+ // src/provider.tsx
448
+ var import_react2 = require("@moon-x/core/react");
449
+ var import_jsx_runtime = require("react/jsx-runtime");
450
+ var DEFAULT_IFRAME_URL = "https://iframe.moonx-dev.com";
451
+ var MoonKeyContext = (0, import_react.createContext)(null);
452
+ var MoonKeyProvider = ({
453
+ publishableKey,
454
+ config,
455
+ children
456
+ }) => {
457
+ const iframeUrl = config?.iframeUrl ?? DEFAULT_IFRAME_URL;
458
+ (0, import_lib3.setAssertCacheTtlMs)(config?.security?.assertionCacheTtlMs ?? 0);
459
+ const webViewRef = (0, import_react.useRef)(null);
460
+ const bridge = (0, import_react.useMemo)(
461
+ () => new WebViewBridge(
462
+ webViewRef
463
+ ),
464
+ []
465
+ );
466
+ const [sensitiveVisible, setSensitiveVisible] = (0, import_react.useState)(false);
467
+ const cancelRef = (0, import_react.useRef)(null);
468
+ const [ready, setReady] = (0, import_react.useState)(false);
469
+ const [isAuthenticated, setIsAuthenticated] = (0, import_react.useState)(false);
470
+ const [user, setUser] = (0, import_react.useState)(null);
471
+ const { height: screenHeight } = (0, import_react_native.useWindowDimensions)();
472
+ const SHEET_TOP_OFFSET = 80;
473
+ const sheetTranslateY = (0, import_react.useRef)(new import_react_native.Animated.Value(screenHeight)).current;
474
+ const backdropOpacity = (0, import_react.useRef)(new import_react_native.Animated.Value(0)).current;
475
+ (0, import_react.useEffect)(() => {
476
+ import_react_native.Animated.parallel([
477
+ import_react_native.Animated.timing(sheetTranslateY, {
478
+ toValue: sensitiveVisible ? 0 : screenHeight,
479
+ duration: 280,
480
+ useNativeDriver: true
481
+ }),
482
+ import_react_native.Animated.timing(backdropOpacity, {
483
+ toValue: sensitiveVisible ? 0.5 : 0,
484
+ duration: 280,
485
+ useNativeDriver: true
486
+ })
487
+ ]).start();
488
+ }, [sensitiveVisible, sheetTranslateY, backdropOpacity, screenHeight]);
489
+ const initialSourceUri = (0, import_react.useMemo)(() => {
490
+ const base = iframeUrl.replace(/\/$/, "");
491
+ const sep = base.includes("?") ? "&" : "?";
492
+ return `${base}${sep}publishableKey=${encodeURIComponent(publishableKey)}`;
493
+ }, [iframeUrl, publishableKey]);
494
+ const handleMessage = (0, import_react.useCallback)(
495
+ (event) => {
496
+ bridge.handleMessage({ nativeEvent: { data: event.nativeEvent.data } });
497
+ },
498
+ [bridge]
499
+ );
500
+ const refreshUser = (0, import_react.useCallback)(async () => {
501
+ try {
502
+ const fetched = await sdkRef.current.getUser();
503
+ if (fetched) setUser(fetched);
504
+ } catch {
505
+ }
506
+ }, []);
507
+ const navigateWebView = (0, import_react.useCallback)(
508
+ (path) => {
509
+ const ref = webViewRef.current;
510
+ if (!ref) return;
511
+ const base = iframeUrl.replace(/\/$/, "");
512
+ const cleanPath = path.startsWith("/") ? path : `/${path}`;
513
+ const hasKey = /[?&]publishableKey=/.test(cleanPath);
514
+ const sep = cleanPath.includes("?") ? "&" : "?";
515
+ const target = hasKey ? `${base}${cleanPath}` : `${base}${cleanPath}${sep}publishableKey=${encodeURIComponent(publishableKey)}`;
516
+ ref.injectJavaScript(
517
+ `window.location.href = ${JSON.stringify(target)}; true;`
518
+ );
519
+ },
520
+ [iframeUrl, publishableKey]
521
+ );
522
+ const runSensitiveFlow = (0, import_react.useCallback)(
523
+ (options) => {
524
+ setSensitiveVisible(true);
525
+ navigateWebView(options.flowPath);
526
+ return new Promise((resolve) => {
527
+ let finished = false;
528
+ const finish = () => {
529
+ if (finished) return;
530
+ finished = true;
531
+ setSensitiveVisible(false);
532
+ navigateWebView("/");
533
+ if (cancelRef.current === finish) cancelRef.current = null;
534
+ resolve();
535
+ };
536
+ cancelRef.current = finish;
537
+ if (options.onMount) {
538
+ Promise.resolve(options.onMount({ bridge, cancel: finish })).catch(
539
+ () => {
540
+ }
541
+ );
542
+ }
543
+ });
544
+ },
545
+ [bridge, navigateWebView]
546
+ );
547
+ const sdk = (0, import_react.useMemo)(
548
+ () => createSdkInstance({
549
+ bridge,
550
+ publishableKey,
551
+ emailConfig: config?.emailConfig,
552
+ isAuthenticated,
553
+ user,
554
+ ready,
555
+ setIsAuthenticated,
556
+ setUser,
557
+ refreshUser
558
+ }),
559
+ [
560
+ bridge,
561
+ publishableKey,
562
+ config?.emailConfig,
563
+ isAuthenticated,
564
+ user,
565
+ ready,
566
+ refreshUser
567
+ ]
568
+ );
569
+ const sdkRef = (0, import_react.useRef)(sdk);
570
+ (0, import_react.useEffect)(() => {
571
+ sdkRef.current = sdk;
572
+ }, [sdk]);
573
+ (0, import_react.useEffect)(() => {
574
+ return () => {
575
+ bridge.cleanup("provider_unmounted");
576
+ };
577
+ }, [bridge]);
578
+ (0, import_react.useEffect)(() => {
579
+ let cancelled = false;
580
+ const unregister = bridge.register(
581
+ import_utils3.PostMessageType.INIT,
582
+ import_utils3.PostMessageMethod.READY,
583
+ () => {
584
+ if (!cancelled) setReady(true);
585
+ }
586
+ );
587
+ const fallback = setTimeout(() => {
588
+ if (!cancelled) setReady(true);
589
+ }, 2e3);
590
+ return () => {
591
+ cancelled = true;
592
+ unregister();
593
+ clearTimeout(fallback);
594
+ };
595
+ }, [bridge]);
596
+ (0, import_react.useEffect)(() => {
597
+ if (!ready || isAuthenticated) return;
598
+ let cancelled = false;
599
+ let attempt = 0;
600
+ const maxAttempts = 4;
601
+ const tryRestore = async () => {
602
+ if (cancelled) return;
603
+ attempt += 1;
604
+ try {
605
+ const session = await sdkRef.current.getCurrentSession();
606
+ if (cancelled) return;
607
+ if (session) {
608
+ setIsAuthenticated(true);
609
+ try {
610
+ const u = await sdkRef.current.getUser();
611
+ if (!cancelled && u) setUser(u);
612
+ } catch {
613
+ }
614
+ return;
615
+ }
616
+ if (attempt < maxAttempts) {
617
+ const delay = 200 * 2 ** (attempt - 1);
618
+ setTimeout(tryRestore, delay);
619
+ }
620
+ } catch {
621
+ if (!cancelled && attempt < maxAttempts) {
622
+ const delay = 200 * 2 ** (attempt - 1);
623
+ setTimeout(tryRestore, delay);
624
+ }
625
+ }
626
+ };
627
+ tryRestore();
628
+ return () => {
629
+ cancelled = true;
630
+ };
631
+ }, [ready, isAuthenticated]);
632
+ const contextValue = (0, import_react.useMemo)(
633
+ () => ({
634
+ sdk,
635
+ _bridge: bridge,
636
+ _runSensitiveFlow: runSensitiveFlow,
637
+ _oauthRedirectUri: config?.oauthRedirectUri
638
+ }),
639
+ [sdk, bridge, runSensitiveFlow, config?.oauthRedirectUri]
640
+ );
641
+ const closeLabel = config?.sensitiveModalCopy?.closeLabel ?? "Done";
642
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MoonKeyContext.Provider, { value: contextValue, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react2.SDKProvider, { value: sdk, children: [
643
+ children,
644
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
645
+ import_react_native.Animated.View,
646
+ {
647
+ style: [styles.backdrop, { opacity: backdropOpacity }],
648
+ pointerEvents: sensitiveVisible ? "auto" : "none",
649
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
650
+ import_react_native.Pressable,
651
+ {
652
+ style: import_react_native.StyleSheet.absoluteFill,
653
+ onPress: () => cancelRef.current?.()
654
+ }
655
+ )
656
+ }
657
+ ),
658
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
659
+ import_react_native.Animated.View,
660
+ {
661
+ style: [
662
+ styles.sheetContainer,
663
+ {
664
+ top: SHEET_TOP_OFFSET,
665
+ transform: [{ translateY: sheetTranslateY }]
666
+ }
667
+ ],
668
+ pointerEvents: sensitiveVisible ? "auto" : "none",
669
+ children: [
670
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.View, { style: styles.sheetGrabber }),
671
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react_native.View, { style: styles.modalChrome, children: [
672
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.View, { style: styles.modalTitleSpacer }),
673
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
674
+ import_react_native.Pressable,
675
+ {
676
+ onPress: () => cancelRef.current?.(),
677
+ hitSlop: 12,
678
+ style: styles.closeButton,
679
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.Text, { style: styles.closeButtonText, children: closeLabel })
680
+ }
681
+ )
682
+ ] }),
683
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
684
+ import_react_native_webview.WebView,
685
+ {
686
+ ref: webViewRef,
687
+ source: { uri: initialSourceUri },
688
+ onMessage: handleMessage,
689
+ webviewDebuggingEnabled: __DEV__,
690
+ javaScriptEnabled: true,
691
+ domStorageEnabled: true,
692
+ sharedCookiesEnabled: import_react_native.Platform.OS === "ios",
693
+ thirdPartyCookiesEnabled: import_react_native.Platform.OS === "android",
694
+ startInLoadingState: false,
695
+ originWhitelist: ["https://*", "http://*"],
696
+ style: styles.webView
697
+ }
698
+ )
699
+ ]
700
+ }
701
+ )
702
+ ] }) });
703
+ };
704
+ var useMoonKeyContext = () => {
705
+ const ctx = (0, import_react.useContext)(MoonKeyContext);
706
+ if (!ctx) {
707
+ throw new Error("useMoonKey must be used within a MoonKeyProvider");
708
+ }
709
+ return ctx;
710
+ };
711
+ var styles = import_react_native.StyleSheet.create({
712
+ backdrop: {
713
+ position: "absolute",
714
+ top: 0,
715
+ bottom: 0,
716
+ left: 0,
717
+ right: 0,
718
+ backgroundColor: "#000",
719
+ zIndex: 999
720
+ },
721
+ // Sheet-style container: rendered as a card that slides up from the
722
+ // bottom. `top` is set inline by the provider to leave room above
723
+ // for the host app's content visible through the dimmed backdrop.
724
+ // `bottom: 0` so the WebView fills the remaining height.
725
+ sheetContainer: {
726
+ position: "absolute",
727
+ bottom: 0,
728
+ left: 0,
729
+ right: 0,
730
+ backgroundColor: "#0a0a0a",
731
+ borderTopLeftRadius: 14,
732
+ borderTopRightRadius: 14,
733
+ overflow: "hidden",
734
+ zIndex: 1e3,
735
+ shadowColor: "#000",
736
+ shadowOpacity: 0.4,
737
+ shadowRadius: 20,
738
+ shadowOffset: { width: 0, height: -4 },
739
+ elevation: 16
740
+ },
741
+ sheetGrabber: {
742
+ width: 36,
743
+ height: 4,
744
+ borderRadius: 2,
745
+ backgroundColor: "#333",
746
+ alignSelf: "center",
747
+ marginTop: 8,
748
+ marginBottom: 4
749
+ },
750
+ webView: {
751
+ flex: 1
752
+ },
753
+ modalChrome: {
754
+ flexDirection: "row",
755
+ alignItems: "center",
756
+ justifyContent: "space-between",
757
+ paddingTop: 8,
758
+ paddingBottom: 12,
759
+ paddingHorizontal: 16,
760
+ backgroundColor: "#0a0a0a",
761
+ borderBottomWidth: import_react_native.StyleSheet.hairlineWidth,
762
+ borderBottomColor: "#222"
763
+ },
764
+ // Empty flex spacer keeps the close button right-aligned without
765
+ // a title taking up the left side. The iframe-app's flow page
766
+ // renders its own header inside the WebView, so a duplicate title
767
+ // here was redundant.
768
+ modalTitleSpacer: {
769
+ flex: 1
770
+ },
771
+ closeButton: {
772
+ paddingHorizontal: 8,
773
+ paddingVertical: 4
774
+ },
775
+ closeButtonText: {
776
+ color: "#3b82f6",
777
+ fontSize: 17,
778
+ fontWeight: "600"
779
+ }
780
+ });
781
+
782
+ // src/hooks/index.ts
783
+ var import_react5 = require("@moon-x/core/react");
784
+
785
+ // src/hooks/use-attach-oauth.ts
786
+ var import_utils4 = require("@moon-x/core/utils");
787
+ var import_react3 = require("react");
788
+
789
+ // src/lib/oauth-deep-link.ts
790
+ var openOAuthFlow = async ({
791
+ authUrl,
792
+ redirectUri
793
+ }) => {
794
+ const [{ openAuthSessionAsync, dismissAuthSession }, Linking] = await Promise.all([
795
+ import("expo-web-browser"),
796
+ import("expo-linking")
797
+ ]);
798
+ const result = await openAuthSessionAsync(authUrl, redirectUri);
799
+ if (result.type === "cancel" || result.type === "dismiss") {
800
+ throw new Error("oauth_cancelled");
801
+ }
802
+ if (result.type !== "success" || !result.url) {
803
+ dismissAuthSession?.();
804
+ throw new Error(`oauth_failed:${result.type}`);
805
+ }
806
+ const parsed = Linking.parse(result.url);
807
+ if (parsed && parsed.queryParams && parsed.queryParams.error) {
808
+ throw new Error(`oauth_provider_error:${String(parsed.queryParams.error)}`);
809
+ }
810
+ return { redirectUrl: result.url };
811
+ };
812
+ var parseOAuthRedirect = async (redirectUrl) => {
813
+ const Linking = await import("expo-linking");
814
+ const parsed = Linking.parse(redirectUrl);
815
+ const q = parsed.queryParams || {};
816
+ return {
817
+ code: typeof q.code === "string" ? q.code : void 0,
818
+ state: typeof q.state === "string" ? q.state : void 0,
819
+ token: typeof q.token === "string" ? q.token : void 0,
820
+ error: typeof q.error === "string" ? q.error : void 0,
821
+ raw: redirectUrl
822
+ };
823
+ };
824
+
825
+ // src/hooks/use-attach-oauth.ts
826
+ var useAttachOAuth = (params) => {
827
+ const { sdk, _bridge, _oauthRedirectUri } = useMoonKeyContext();
828
+ const [state, setState] = (0, import_react3.useState)({ status: "idle" });
829
+ return {
830
+ state,
831
+ attachOAuth: async (provider) => {
832
+ setState({ status: "starting" });
833
+ try {
834
+ const redirectUri = params?.redirectUri || _oauthRedirectUri;
835
+ if (!redirectUri) throw new Error("oauth_redirect_uri_missing");
836
+ const startResult = await _bridge.send(
837
+ import_utils4.PostMessageType.AUTH,
838
+ import_utils4.PostMessageMethod.START_OAUTH,
839
+ {
840
+ publishableKey: sdk.publishableKey,
841
+ provider,
842
+ attach: true,
843
+ login_redirect_url: redirectUri
844
+ }
845
+ );
846
+ if (!startResult.redirect_url) {
847
+ throw new Error("start_oauth_failed");
848
+ }
849
+ setState({ status: "redirecting" });
850
+ const { redirectUrl } = await openOAuthFlow({
851
+ authUrl: startResult.redirect_url,
852
+ redirectUri
853
+ });
854
+ const parsed = await parseOAuthRedirect(redirectUrl);
855
+ if (parsed.error) throw new Error(parsed.error);
856
+ setState({ status: "verifying" });
857
+ await _bridge.send(
858
+ import_utils4.PostMessageType.AUTH,
859
+ import_utils4.PostMessageMethod.ATTACH_OAUTH,
860
+ {
861
+ publishableKey: sdk.publishableKey,
862
+ provider,
863
+ code: parsed.code,
864
+ token: parsed.token,
865
+ state: parsed.state
866
+ }
867
+ );
868
+ setState({ status: "complete" });
869
+ } catch (e) {
870
+ const err = e instanceof Error ? e : new Error(String(e));
871
+ setState({ status: "error", error: err });
872
+ throw err;
873
+ }
874
+ },
875
+ reset: () => setState({ status: "idle" })
876
+ };
877
+ };
878
+
879
+ // src/hooks/use-detach-oauth.ts
880
+ var import_utils5 = require("@moon-x/core/utils");
881
+ var useDetachOAuth = () => {
882
+ const { sdk, _bridge } = useMoonKeyContext();
883
+ return {
884
+ detachOAuth: async (idpUserId) => {
885
+ await _bridge.send(
886
+ import_utils5.PostMessageType.AUTH,
887
+ import_utils5.PostMessageMethod.DETACH_OAUTH,
888
+ { publishableKey: sdk.publishableKey, idpUserId }
889
+ );
890
+ }
891
+ };
892
+ };
893
+
894
+ // src/hooks/use-export-key.ts
895
+ var import_lib4 = require("@moon-x/core/lib");
896
+ var import_sdk6 = require("@moon-x/core/sdk");
897
+ var useExportKey = () => {
898
+ const { sdk, _bridge, _runSensitiveFlow } = useMoonKeyContext();
899
+ return {
900
+ exportKey: (wallet) => (0, import_lib4.withClearOnFailure)(async () => {
901
+ const { userHandleB64url, credentialIdB64url } = await (0, import_sdk6.assertPasskeyInParent)({
902
+ transport: _bridge,
903
+ passkey: createRNPasskey(),
904
+ publishableKey: sdk.publishableKey,
905
+ requireFreshAssertion: true
906
+ });
907
+ const params = new URLSearchParams({
908
+ publishableKey: sdk.publishableKey,
909
+ wallet_id: wallet.id ?? "",
910
+ wallet_type: wallet.wallet_type ?? "",
911
+ user_handle_b64url: userHandleB64url,
912
+ credential_id_b64url: credentialIdB64url
913
+ });
914
+ await _runSensitiveFlow({
915
+ title: "Export key",
916
+ flowPath: `/export-key?${params.toString()}`,
917
+ // No completion postMessage in v1 — the user-tap-Done path
918
+ // resolves the promise via the modal's cancel handler. The
919
+ // promise simply waits for runSensitiveFlow to settle, which
920
+ // happens when the user dismisses.
921
+ onMount: () => Promise.resolve()
922
+ });
923
+ })
924
+ };
925
+ };
926
+
927
+ // src/hooks/use-login-with-oauth.ts
928
+ var import_utils6 = require("@moon-x/core/utils");
929
+ var import_react4 = require("react");
930
+ var useLoginWithOAuth = (params) => {
931
+ const { sdk, _bridge, _oauthRedirectUri } = useMoonKeyContext();
932
+ const [state, setState] = (0, import_react4.useState)({ status: "idle" });
933
+ return {
934
+ state,
935
+ loginWithOAuth: async (provider) => {
936
+ setState({ status: "starting" });
937
+ try {
938
+ const redirectUri = params?.redirectUri || _oauthRedirectUri;
939
+ if (!redirectUri) {
940
+ throw new Error("oauth_redirect_uri_missing");
941
+ }
942
+ const startResult = await _bridge.send(
943
+ import_utils6.PostMessageType.AUTH,
944
+ import_utils6.PostMessageMethod.START_OAUTH,
945
+ {
946
+ publishableKey: sdk.publishableKey,
947
+ provider,
948
+ login_redirect_url: redirectUri
949
+ }
950
+ );
951
+ if (!startResult.redirect_url) {
952
+ throw new Error("start_oauth_failed");
953
+ }
954
+ setState({ status: "redirecting" });
955
+ const { redirectUrl } = await openOAuthFlow({
956
+ authUrl: startResult.redirect_url,
957
+ redirectUri
958
+ });
959
+ const parsed = await parseOAuthRedirect(redirectUrl);
960
+ if (parsed.error) throw new Error(parsed.error);
961
+ if (!parsed.code && !parsed.token) {
962
+ throw new Error("oauth_no_code_or_token");
963
+ }
964
+ setState({ status: "verifying" });
965
+ const result = await sdk.verifyOAuth({
966
+ provider,
967
+ code: parsed.code,
968
+ token: parsed.token,
969
+ state: parsed.state
970
+ });
971
+ setState({ status: "complete", user: result?.user ?? result ?? null });
972
+ } catch (e) {
973
+ const err = e instanceof Error ? e : new Error(String(e));
974
+ setState({ status: "error", error: err });
975
+ throw err;
976
+ }
977
+ },
978
+ reset: () => setState({ status: "idle" })
979
+ };
980
+ };
981
+
982
+ // src/hooks/use-moonkey.ts
983
+ var useMoonKey = () => useMoonKeyContext().sdk;
984
+
985
+ // src/index.ts
986
+ var import_utils7 = require("@moon-x/core/utils");
987
+ // Annotate the CommonJS export names for ESM import in node:
988
+ 0 && (module.exports = {
989
+ MoonKeyProvider,
990
+ PostMessageMethod,
991
+ PostMessageType,
992
+ useAddPasskey,
993
+ useAttachOAuth,
994
+ useCreateWallet,
995
+ useDetachOAuth,
996
+ useExportKey,
997
+ useImportKey,
998
+ useLoginWithEmail,
999
+ useLoginWithOAuth,
1000
+ useLogout,
1001
+ useMoonKey,
1002
+ useMoonKeyContext,
1003
+ usePasskeyStatus,
1004
+ useRegisterPasskey,
1005
+ useRemovePasskey,
1006
+ useUser,
1007
+ useWallets
1008
+ });