@mocanetwork/airkit-connector 1.2.0-beta.3 → 1.2.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.
@@ -1,6 +1,2962 @@
1
1
  'use strict';
2
2
 
3
- var airkit = require('@mocanetwork/airkit');
3
+ /******************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
18
+
19
+ var extendStatics = function (d, b) {
20
+ extendStatics = Object.setPrototypeOf || {
21
+ __proto__: []
22
+ } instanceof Array && function (d, b) {
23
+ d.__proto__ = b;
24
+ } || function (d, b) {
25
+ for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
26
+ };
27
+ return extendStatics(d, b);
28
+ };
29
+ function __extends(d, b) {
30
+ if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
31
+ extendStatics(d, b);
32
+ function __() {
33
+ this.constructor = d;
34
+ }
35
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36
+ }
37
+ function __values(o) {
38
+ var s = typeof Symbol === "function" && Symbol.iterator,
39
+ m = s && o[s],
40
+ i = 0;
41
+ if (m) return m.call(o);
42
+ if (o && typeof o.length === "number") return {
43
+ next: function () {
44
+ if (o && i >= o.length) o = undefined;
45
+ return {
46
+ value: o && o[i++],
47
+ done: !o
48
+ };
49
+ }
50
+ };
51
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
52
+ }
53
+ function __read(o, n) {
54
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
55
+ if (!m) return o;
56
+ var i = m.call(o),
57
+ r,
58
+ ar = [],
59
+ e;
60
+ try {
61
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
62
+ } catch (error) {
63
+ e = {
64
+ error: error
65
+ };
66
+ } finally {
67
+ try {
68
+ if (r && !r.done && (m = i["return"])) m.call(i);
69
+ } finally {
70
+ if (e) throw e.error;
71
+ }
72
+ }
73
+ return ar;
74
+ }
75
+ function __spreadArray(to, from, pack) {
76
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
77
+ if (ar || !(i in from)) {
78
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
79
+ ar[i] = from[i];
80
+ }
81
+ }
82
+ return to.concat(ar || Array.prototype.slice.call(from));
83
+ }
84
+ function __classPrivateFieldGet$1(receiver, state, kind, f) {
85
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
86
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
87
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
88
+ }
89
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
90
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
91
+ return f ? f.value = value : state.set(receiver, value), value;
92
+ }
93
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
94
+ var e = new Error(message);
95
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
96
+ };
97
+ const AirAuthMessageTypes = {
98
+ AUTH_SETUP_COMPLETED: "air_auth_setup_completed",
99
+ INITIALIZATION_REQUEST: "air_auth_initialization_request",
100
+ INITIALIZATION_RESPONSE: "air_auth_initialization_response",
101
+ LOGIN_REQUEST: "air_auth_login_request",
102
+ LOGIN_RESPONSE: "air_auth_login_response",
103
+ LOGIN_WALLET_RESPONSE: "air_auth_login_wallet_response",
104
+ USER_INFO_REQUEST: "air_auth_user_info_request",
105
+ USER_INFO_RESPONSE: "air_auth_user_info_response",
106
+ PARTNER_USER_INFO_REQUEST: "air_auth_partner_user_info_request",
107
+ PARTNER_USER_INFO_RESPONSE: "air_auth_partner_user_info_response",
108
+ REFRESH_TOKEN_REQUEST: "air_auth_refresh_token_request",
109
+ REFRESH_TOKEN_RESPONSE: "air_auth_refresh_token_response",
110
+ WALLET_TOKEN_REQUEST: "air_auth_wallet_token_request",
111
+ WALLET_TOKEN_RESPONSE: "air_auth_wallet_token_response",
112
+ INIT_WALLET_COMMUNICATION: "air_auth_init_wallet_communication",
113
+ IFRAME_VISIBILITY_REQUEST: "air_auth_iframe_visibility_request",
114
+ SETUP_WALLET_REQUEST: "air_auth_setup_wallet_request",
115
+ SETUP_WALLET_RESPONSE: "air_auth_setup_wallet_response",
116
+ SIGN_SIWE_MESSAGE_REQUEST: "air_auth_sign_siwe_message_request",
117
+ SIGN_SIWE_MESSAGE_RESPONSE: "air_auth_sign_siwe_message_response",
118
+ CROSS_PARTNER_TOKEN_REQUEST: "air_auth_cross_partner_token_request",
119
+ CROSS_PARTNER_TOKEN_RESPONSE: "air_auth_cross_partner_token_response",
120
+ PARTNER_ACCESS_TOKEN_REQUEST: "air_auth_partner_access_token_request",
121
+ PARTNER_ACCESS_TOKEN_RESPONSE: "air_auth_partner_access_token_response",
122
+ LOGOUT_REQUEST: "air_auth_logout_request",
123
+ LOGOUT_RESPONSE: "air_auth_logout_response",
124
+ RESET_WALLET_COMMUNICATION: "air_auth_reset_wallet_communication"
125
+ };
126
+ const AirWalletMessageTypes = {
127
+ SERVICE_STARTED: "air_service_started",
128
+ INITIALIZATION_REQUEST: "air_initialization_request",
129
+ INITIALIZATION_RESPONSE: "air_initialization_response",
130
+ INIT_AUTH_COMMUNICATION: "air_init_auth_communication",
131
+ WALLET_INITIALIZED: "air_wallet_initialized",
132
+ WALLET_LOGIN_REQUEST: "air_wallet_login_request",
133
+ WALLET_LOGIN_RESPONSE: "air_wallet_login_response",
134
+ SETUP_OR_UPDATE_MFA_REQUEST: "air_setup_mfa_request",
135
+ SETUP_OR_UPDATE_MFA_RESPONSE: "air_setup_mfa_response",
136
+ CLAIM_ID_REQUEST: "air_claim_id_request",
137
+ CLAIM_ID_RESPONSE: "air_claim_id_response",
138
+ DEPLOY_SMART_ACCOUNT_REQUEST: "air_deploy_smart_account_request",
139
+ DEPLOY_SMART_ACCOUNT_RESPONSE: "air_deploy_smart_account_response",
140
+ GRANT_PERMISSIONS_REQUEST: "air_grant_permissions_request",
141
+ GRANT_PERMISSIONS_RESPONSE: "air_grant_permissions_response",
142
+ EXECUTE_ACTION_REQUEST: "air_execute_action_request",
143
+ EXECUTE_ACTION_RESPONSE: "air_execute_action_response",
144
+ REVOKE_PERMISSIONS_REQUEST: "air_revoke_permissions_request",
145
+ REVOKE_PERMISSIONS_RESPONSE: "air_revoke_permissions_response",
146
+ LIST_ALL_SESSION_KEY_SCOPES_REQUEST: "air_list_all_session_key_scopes_request",
147
+ LIST_ALL_SESSION_KEY_SCOPES_RESPONSE: "air_list_all_session_key_scopes_response",
148
+ WALLET_IFRAME_VISIBILITY_REQUEST: "air_wallet_iframe_visibility_request",
149
+ OPEN_WINDOW_REQUEST: "air_open_window_request",
150
+ OPEN_WINDOW_RESPONSE: "air_open_window_response",
151
+ OPEN_WINDOW_RETRY_REQUEST: "air_open_window_retry_request",
152
+ OPEN_WINDOW_RETRY_RESPONSE: "air_open_window_retry_response",
153
+ WINDOW_CLOSED: "air_window_closed",
154
+ IS_SMART_ACCOUNT_DEPLOYED_REQUEST: "air_is_smart_account_deployed_request",
155
+ IS_SMART_ACCOUNT_DEPLOYED_RESPONSE: "air_is_smart_account_deployed_response",
156
+ LOGOUT_REQUEST: "air_logout_request",
157
+ LOGOUT_RESPONSE: "air_logout_response"
158
+ };
159
+ let BaseError$2 = class BaseError extends Error {
160
+ constructor(name, message, options = {}) {
161
+ const {
162
+ cause,
163
+ context
164
+ } = options;
165
+ super(message || name);
166
+ this.name = name;
167
+ this.stack = cause?.stack;
168
+ this.cause = cause;
169
+ this.context = context;
170
+ }
171
+ toJSON() {
172
+ return {
173
+ name: this.name,
174
+ message: this.message,
175
+ context: this.context,
176
+ cause: this.cause
177
+ };
178
+ }
179
+ };
180
+ function ensureError(value) {
181
+ if (value instanceof Error) return value;
182
+ let stringified = "[Unable to stringify the thrown value]";
183
+ try {
184
+ stringified = JSON.stringify(value);
185
+ } catch {
186
+ // ignoring failed stringify
187
+ }
188
+ return new Error(`This value was not thrown as type Error: ${stringified}`);
189
+ }
190
+ const BUILD_ENV = {
191
+ PRODUCTION: "production",
192
+ UAT: "uat",
193
+ STAGING: "staging",
194
+ DEVELOPMENT: "development"
195
+ };
196
+ const AIR_URLS = {
197
+ [BUILD_ENV.DEVELOPMENT]: {
198
+ authUrl: "http://localhost:8100",
199
+ walletUrl: "http://localhost:8200"
200
+ },
201
+ [BUILD_ENV.UAT]: {
202
+ authUrl: "https://auth.uat.air3.com",
203
+ walletUrl: "https://account.uat.air3.com"
204
+ },
205
+ [BUILD_ENV.STAGING]: {
206
+ authUrl: "https://auth.staging.air3.com",
207
+ walletUrl: "https://account.staging.air3.com"
208
+ },
209
+ [BUILD_ENV.PRODUCTION]: {
210
+ authUrl: "https://auth.air3.com",
211
+ walletUrl: "https://account.air3.com"
212
+ }
213
+ };
214
+ const isElement = element => element instanceof Element || element instanceof Document;
215
+ const randomId = () => Math.random().toString(36).slice(2);
216
+ const extractErrorHash = message => {
217
+ if (!message) return "";
218
+ // Format: "reason: 0x..."
219
+ if (message.includes("reason:")) {
220
+ return message.split("reason:")[1].trim();
221
+ }
222
+ // Format: "UserOperation reverted during simulation with reason: 0x..."
223
+ if (message.includes("with reason:")) {
224
+ const match = message.match(/with reason: (0x[a-fA-F0-9]+)/);
225
+ return match ? match[1].trim() : "";
226
+ }
227
+ // Look for any 0x pattern that could be a hash
228
+ const hexMatch = message.match(/(0x[a-fA-F0-9]{8,})/);
229
+ return hexMatch ? hexMatch[1].trim() : "";
230
+ };
231
+ class AirServiceError extends BaseError$2 {
232
+ static from(error) {
233
+ if (error instanceof AirServiceError) {
234
+ return error;
235
+ } else if (error instanceof Object && "message" in error) {
236
+ if (error.message === "User cancelled login") {
237
+ return new AirServiceError("USER_CANCELLED", error.message);
238
+ }
239
+ return new AirServiceError("UNKNOWN_ERROR", error.message.toString());
240
+ }
241
+ return new AirServiceError("UNKNOWN_ERROR");
242
+ }
243
+ }
244
+ let ProviderRpcError$1 = class ProviderRpcError extends Error {
245
+ constructor(message) {
246
+ super(message);
247
+ this.metaMessages = [];
248
+ }
249
+ };
250
+ let UserRejectedRequestError$1 = class UserRejectedRequestError extends ProviderRpcError$1 {
251
+ constructor() {
252
+ super(...arguments);
253
+ this.code = 4001;
254
+ this.name = "UserRejectedRequestError";
255
+ }
256
+ };
257
+ class UnauthorizedProviderError extends ProviderRpcError$1 {
258
+ constructor() {
259
+ super(...arguments);
260
+ this.code = 4100;
261
+ this.name = "UnauthorizedProviderError";
262
+ }
263
+ }
264
+ class UnsupportedProviderMethodError extends ProviderRpcError$1 {
265
+ constructor() {
266
+ super(...arguments);
267
+ this.code = 4200;
268
+ this.name = "UnsupportedProviderMethodError";
269
+ }
270
+ }
271
+ class ProviderDisconnectedError extends ProviderRpcError$1 {
272
+ constructor() {
273
+ super(...arguments);
274
+ this.code = 4900;
275
+ this.name = "ProviderDisconnectedError";
276
+ }
277
+ }
278
+ class ChainDisconnectedError extends ProviderRpcError$1 {
279
+ constructor() {
280
+ super(...arguments);
281
+ this.code = 4901;
282
+ this.name = "ChainDisconnectedError";
283
+ }
284
+ }
285
+ let SwitchChainError$1 = class SwitchChainError extends ProviderRpcError$1 {
286
+ constructor() {
287
+ super(...arguments);
288
+ this.code = 4902;
289
+ this.name = "SwitchChainError";
290
+ }
291
+ };
292
+ class TransactionRejectedRpcError extends ProviderRpcError$1 {
293
+ constructor(message) {
294
+ // Remove the "Version: viem@x.x.x" suffix if present
295
+ const cleanMessage = message.replace(/\nVersion:.*$/, '');
296
+ super(cleanMessage);
297
+ this.code = -32003;
298
+ this.name = "TransactionRejectedRpcError";
299
+ // Parse the error hash from the message
300
+ this.metaMessages.push(extractErrorHash(cleanMessage));
301
+ }
302
+ }
303
+ class InvalidRequestRpcError extends ProviderRpcError$1 {
304
+ constructor() {
305
+ super(...arguments);
306
+ this.code = -32600;
307
+ this.name = "InvalidRequestRpcError";
308
+ }
309
+ }
310
+ class MethodNotFoundRpcError extends ProviderRpcError$1 {
311
+ constructor() {
312
+ super(...arguments);
313
+ this.code = -32601;
314
+ this.name = "MethodNotFoundRpcError";
315
+ }
316
+ }
317
+ class InvalidParamsRpcError extends ProviderRpcError$1 {
318
+ constructor() {
319
+ super(...arguments);
320
+ this.code = -32602;
321
+ this.name = "InvalidParamsRpcError";
322
+ }
323
+ }
324
+ class InternalRpcError extends ProviderRpcError$1 {
325
+ constructor() {
326
+ super(...arguments);
327
+ this.code = -32603;
328
+ this.name = "InternalRpcError";
329
+ }
330
+ }
331
+ function ensureProviderRpcError(value) {
332
+ if (value instanceof ProviderRpcError$1) {
333
+ return value;
334
+ }
335
+ if (typeof value === "object" && value !== null && "errorCode" in value && "errorMessage" in value) {
336
+ if (typeof value.errorCode === "number" && typeof value.errorMessage === "string") {
337
+ switch (value.errorCode) {
338
+ case 4001:
339
+ return new UserRejectedRequestError$1(value.errorMessage);
340
+ case 4100:
341
+ return new UnauthorizedProviderError(value.errorMessage);
342
+ case 4200:
343
+ return new UnsupportedProviderMethodError(value.errorMessage);
344
+ case 4900:
345
+ return new ProviderDisconnectedError(value.errorMessage);
346
+ case 4901:
347
+ return new ChainDisconnectedError(value.errorMessage);
348
+ case 4902:
349
+ return new SwitchChainError$1(value.errorMessage);
350
+ case -32003:
351
+ return new TransactionRejectedRpcError(value.errorMessage);
352
+ }
353
+ }
354
+ }
355
+ let stringified = "[Unable to stringify the thrown value]";
356
+ try {
357
+ stringified = JSON.stringify(value);
358
+ } catch {
359
+ // ignoring failed stringify
360
+ }
361
+ return new InternalRpcError(`Invalid value for ProviderRpcError: ${stringified}`);
362
+ }
363
+ function getDefaultExportFromCjs$1(x) {
364
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
365
+ }
366
+ var loglevel$1$1 = {
367
+ exports: {}
368
+ };
369
+
370
+ /*
371
+ * loglevel - https://github.com/pimterry/loglevel
372
+ *
373
+ * Copyright (c) 2013 Tim Perry
374
+ * Licensed under the MIT license.
375
+ */
376
+ var loglevel$2 = loglevel$1$1.exports;
377
+ var hasRequiredLoglevel$1;
378
+ function requireLoglevel$1() {
379
+ if (hasRequiredLoglevel$1) return loglevel$1$1.exports;
380
+ hasRequiredLoglevel$1 = 1;
381
+ (function (module) {
382
+ (function (root, definition) {
383
+ if (module.exports) {
384
+ module.exports = definition();
385
+ } else {
386
+ root.log = definition();
387
+ }
388
+ })(loglevel$2, function () {
389
+ // Slightly dubious tricks to cut down minimized file size
390
+ var noop = function () {};
391
+ var undefinedType = "undefined";
392
+ var isIE = typeof window !== undefinedType && typeof window.navigator !== undefinedType && /Trident\/|MSIE /.test(window.navigator.userAgent);
393
+ var logMethods = ["trace", "debug", "info", "warn", "error"];
394
+ var _loggersByName = {};
395
+ var defaultLogger = null;
396
+
397
+ // Cross-browser bind equivalent that works at least back to IE6
398
+ function bindMethod(obj, methodName) {
399
+ var method = obj[methodName];
400
+ if (typeof method.bind === 'function') {
401
+ return method.bind(obj);
402
+ } else {
403
+ try {
404
+ return Function.prototype.bind.call(method, obj);
405
+ } catch (e) {
406
+ // Missing bind shim or IE8 + Modernizr, fallback to wrapping
407
+ return function () {
408
+ return Function.prototype.apply.apply(method, [obj, arguments]);
409
+ };
410
+ }
411
+ }
412
+ }
413
+
414
+ // Trace() doesn't print the message in IE, so for that case we need to wrap it
415
+ function traceForIE() {
416
+ if (console.log) {
417
+ if (console.log.apply) {
418
+ console.log.apply(console, arguments);
419
+ } else {
420
+ // In old IE, native console methods themselves don't have apply().
421
+ Function.prototype.apply.apply(console.log, [console, arguments]);
422
+ }
423
+ }
424
+ if (console.trace) console.trace();
425
+ }
426
+
427
+ // Build the best logging method possible for this env
428
+ // Wherever possible we want to bind, not wrap, to preserve stack traces
429
+ function realMethod(methodName) {
430
+ if (methodName === 'debug') {
431
+ methodName = 'log';
432
+ }
433
+ if (typeof console === undefinedType) {
434
+ return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
435
+ } else if (methodName === 'trace' && isIE) {
436
+ return traceForIE;
437
+ } else if (console[methodName] !== undefined) {
438
+ return bindMethod(console, methodName);
439
+ } else if (console.log !== undefined) {
440
+ return bindMethod(console, 'log');
441
+ } else {
442
+ return noop;
443
+ }
444
+ }
445
+
446
+ // These private functions always need `this` to be set properly
447
+
448
+ function replaceLoggingMethods() {
449
+ /*jshint validthis:true */
450
+ var level = this.getLevel();
451
+
452
+ // Replace the actual methods.
453
+ for (var i = 0; i < logMethods.length; i++) {
454
+ var methodName = logMethods[i];
455
+ this[methodName] = i < level ? noop : this.methodFactory(methodName, level, this.name);
456
+ }
457
+
458
+ // Define log.log as an alias for log.debug
459
+ this.log = this.debug;
460
+
461
+ // Return any important warnings.
462
+ if (typeof console === undefinedType && level < this.levels.SILENT) {
463
+ return "No console available for logging";
464
+ }
465
+ }
466
+
467
+ // In old IE versions, the console isn't present until you first open it.
468
+ // We build realMethod() replacements here that regenerate logging methods
469
+ function enableLoggingWhenConsoleArrives(methodName) {
470
+ return function () {
471
+ if (typeof console !== undefinedType) {
472
+ replaceLoggingMethods.call(this);
473
+ this[methodName].apply(this, arguments);
474
+ }
475
+ };
476
+ }
477
+
478
+ // By default, we use closely bound real methods wherever possible, and
479
+ // otherwise we wait for a console to appear, and then try again.
480
+ function defaultMethodFactory(methodName, _level, _loggerName) {
481
+ /*jshint validthis:true */
482
+ return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments);
483
+ }
484
+ function Logger(name, factory) {
485
+ // Private instance variables.
486
+ var self = this;
487
+ /**
488
+ * The level inherited from a parent logger (or a global default). We
489
+ * cache this here rather than delegating to the parent so that it stays
490
+ * in sync with the actual logging methods that we have installed (the
491
+ * parent could change levels but we might not have rebuilt the loggers
492
+ * in this child yet).
493
+ * @type {number}
494
+ */
495
+ var inheritedLevel;
496
+ /**
497
+ * The default level for this logger, if any. If set, this overrides
498
+ * `inheritedLevel`.
499
+ * @type {number|null}
500
+ */
501
+ var defaultLevel;
502
+ /**
503
+ * A user-specific level for this logger. If set, this overrides
504
+ * `defaultLevel`.
505
+ * @type {number|null}
506
+ */
507
+ var userLevel;
508
+ var storageKey = "loglevel";
509
+ if (typeof name === "string") {
510
+ storageKey += ":" + name;
511
+ } else if (typeof name === "symbol") {
512
+ storageKey = undefined;
513
+ }
514
+ function persistLevelIfPossible(levelNum) {
515
+ var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
516
+ if (typeof window === undefinedType || !storageKey) return;
517
+
518
+ // Use localStorage if available
519
+ try {
520
+ window.localStorage[storageKey] = levelName;
521
+ return;
522
+ } catch (ignore) {}
523
+
524
+ // Use session cookie as fallback
525
+ try {
526
+ window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";";
527
+ } catch (ignore) {}
528
+ }
529
+ function getPersistedLevel() {
530
+ var storedLevel;
531
+ if (typeof window === undefinedType || !storageKey) return;
532
+ try {
533
+ storedLevel = window.localStorage[storageKey];
534
+ } catch (ignore) {}
535
+
536
+ // Fallback to cookies if local storage gives us nothing
537
+ if (typeof storedLevel === undefinedType) {
538
+ try {
539
+ var cookie = window.document.cookie;
540
+ var cookieName = encodeURIComponent(storageKey);
541
+ var location = cookie.indexOf(cookieName + "=");
542
+ if (location !== -1) {
543
+ storedLevel = /^([^;]+)/.exec(cookie.slice(location + cookieName.length + 1))[1];
544
+ }
545
+ } catch (ignore) {}
546
+ }
547
+
548
+ // If the stored level is not valid, treat it as if nothing was stored.
549
+ if (self.levels[storedLevel] === undefined) {
550
+ storedLevel = undefined;
551
+ }
552
+ return storedLevel;
553
+ }
554
+ function clearPersistedLevel() {
555
+ if (typeof window === undefinedType || !storageKey) return;
556
+
557
+ // Use localStorage if available
558
+ try {
559
+ window.localStorage.removeItem(storageKey);
560
+ } catch (ignore) {}
561
+
562
+ // Use session cookie as fallback
563
+ try {
564
+ window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
565
+ } catch (ignore) {}
566
+ }
567
+ function normalizeLevel(input) {
568
+ var level = input;
569
+ if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
570
+ level = self.levels[level.toUpperCase()];
571
+ }
572
+ if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
573
+ return level;
574
+ } else {
575
+ throw new TypeError("log.setLevel() called with invalid level: " + input);
576
+ }
577
+ }
578
+
579
+ /*
580
+ *
581
+ * Public logger API - see https://github.com/pimterry/loglevel for details
582
+ *
583
+ */
584
+
585
+ self.name = name;
586
+ self.levels = {
587
+ "TRACE": 0,
588
+ "DEBUG": 1,
589
+ "INFO": 2,
590
+ "WARN": 3,
591
+ "ERROR": 4,
592
+ "SILENT": 5
593
+ };
594
+ self.methodFactory = factory || defaultMethodFactory;
595
+ self.getLevel = function () {
596
+ if (userLevel != null) {
597
+ return userLevel;
598
+ } else if (defaultLevel != null) {
599
+ return defaultLevel;
600
+ } else {
601
+ return inheritedLevel;
602
+ }
603
+ };
604
+ self.setLevel = function (level, persist) {
605
+ userLevel = normalizeLevel(level);
606
+ if (persist !== false) {
607
+ // defaults to true
608
+ persistLevelIfPossible(userLevel);
609
+ }
610
+
611
+ // NOTE: in v2, this should call rebuild(), which updates children.
612
+ return replaceLoggingMethods.call(self);
613
+ };
614
+ self.setDefaultLevel = function (level) {
615
+ defaultLevel = normalizeLevel(level);
616
+ if (!getPersistedLevel()) {
617
+ self.setLevel(level, false);
618
+ }
619
+ };
620
+ self.resetLevel = function () {
621
+ userLevel = null;
622
+ clearPersistedLevel();
623
+ replaceLoggingMethods.call(self);
624
+ };
625
+ self.enableAll = function (persist) {
626
+ self.setLevel(self.levels.TRACE, persist);
627
+ };
628
+ self.disableAll = function (persist) {
629
+ self.setLevel(self.levels.SILENT, persist);
630
+ };
631
+ self.rebuild = function () {
632
+ if (defaultLogger !== self) {
633
+ inheritedLevel = normalizeLevel(defaultLogger.getLevel());
634
+ }
635
+ replaceLoggingMethods.call(self);
636
+ if (defaultLogger === self) {
637
+ for (var childName in _loggersByName) {
638
+ _loggersByName[childName].rebuild();
639
+ }
640
+ }
641
+ };
642
+
643
+ // Initialize all the internal levels.
644
+ inheritedLevel = normalizeLevel(defaultLogger ? defaultLogger.getLevel() : "WARN");
645
+ var initialLevel = getPersistedLevel();
646
+ if (initialLevel != null) {
647
+ userLevel = normalizeLevel(initialLevel);
648
+ }
649
+ replaceLoggingMethods.call(self);
650
+ }
651
+
652
+ /*
653
+ *
654
+ * Top-level API
655
+ *
656
+ */
657
+
658
+ defaultLogger = new Logger();
659
+ defaultLogger.getLogger = function getLogger(name) {
660
+ if (typeof name !== "symbol" && typeof name !== "string" || name === "") {
661
+ throw new TypeError("You must supply a name when creating a logger.");
662
+ }
663
+ var logger = _loggersByName[name];
664
+ if (!logger) {
665
+ logger = _loggersByName[name] = new Logger(name, defaultLogger.methodFactory);
666
+ }
667
+ return logger;
668
+ };
669
+
670
+ // Grab the current global log variable in case of overwrite
671
+ var _log = typeof window !== undefinedType ? window.log : undefined;
672
+ defaultLogger.noConflict = function () {
673
+ if (typeof window !== undefinedType && window.log === defaultLogger) {
674
+ window.log = _log;
675
+ }
676
+ return defaultLogger;
677
+ };
678
+ defaultLogger.getLoggers = function getLoggers() {
679
+ return _loggersByName;
680
+ };
681
+
682
+ // ES6 default export, for compatibility
683
+ defaultLogger['default'] = defaultLogger;
684
+ return defaultLogger;
685
+ });
686
+ })(loglevel$1$1);
687
+ return loglevel$1$1.exports;
688
+ }
689
+ var loglevelExports$1 = requireLoglevel$1();
690
+ var log$1 = /*@__PURE__*/getDefaultExportFromCjs$1(loglevelExports$1);
691
+ function isFunction(value) {
692
+ return typeof value === 'function';
693
+ }
694
+ function createErrorClass(createImpl) {
695
+ var _super = function (instance) {
696
+ Error.call(instance);
697
+ instance.stack = new Error().stack;
698
+ };
699
+ var ctorFunc = createImpl(_super);
700
+ ctorFunc.prototype = Object.create(Error.prototype);
701
+ ctorFunc.prototype.constructor = ctorFunc;
702
+ return ctorFunc;
703
+ }
704
+ var UnsubscriptionError = createErrorClass(function (_super) {
705
+ return function UnsubscriptionErrorImpl(errors) {
706
+ _super(this);
707
+ this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) {
708
+ return i + 1 + ") " + err.toString();
709
+ }).join('\n ') : '';
710
+ this.name = 'UnsubscriptionError';
711
+ this.errors = errors;
712
+ };
713
+ });
714
+ function arrRemove(arr, item) {
715
+ if (arr) {
716
+ var index = arr.indexOf(item);
717
+ 0 <= index && arr.splice(index, 1);
718
+ }
719
+ }
720
+ var Subscription = function () {
721
+ function Subscription(initialTeardown) {
722
+ this.initialTeardown = initialTeardown;
723
+ this.closed = false;
724
+ this._parentage = null;
725
+ this._finalizers = null;
726
+ }
727
+ Subscription.prototype.unsubscribe = function () {
728
+ var e_1, _a, e_2, _b;
729
+ var errors;
730
+ if (!this.closed) {
731
+ this.closed = true;
732
+ var _parentage = this._parentage;
733
+ if (_parentage) {
734
+ this._parentage = null;
735
+ if (Array.isArray(_parentage)) {
736
+ try {
737
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
738
+ var parent_1 = _parentage_1_1.value;
739
+ parent_1.remove(this);
740
+ }
741
+ } catch (e_1_1) {
742
+ e_1 = {
743
+ error: e_1_1
744
+ };
745
+ } finally {
746
+ try {
747
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
748
+ } finally {
749
+ if (e_1) throw e_1.error;
750
+ }
751
+ }
752
+ } else {
753
+ _parentage.remove(this);
754
+ }
755
+ }
756
+ var initialFinalizer = this.initialTeardown;
757
+ if (isFunction(initialFinalizer)) {
758
+ try {
759
+ initialFinalizer();
760
+ } catch (e) {
761
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
762
+ }
763
+ }
764
+ var _finalizers = this._finalizers;
765
+ if (_finalizers) {
766
+ this._finalizers = null;
767
+ try {
768
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
769
+ var finalizer = _finalizers_1_1.value;
770
+ try {
771
+ execFinalizer(finalizer);
772
+ } catch (err) {
773
+ errors = errors !== null && errors !== void 0 ? errors : [];
774
+ if (err instanceof UnsubscriptionError) {
775
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
776
+ } else {
777
+ errors.push(err);
778
+ }
779
+ }
780
+ }
781
+ } catch (e_2_1) {
782
+ e_2 = {
783
+ error: e_2_1
784
+ };
785
+ } finally {
786
+ try {
787
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
788
+ } finally {
789
+ if (e_2) throw e_2.error;
790
+ }
791
+ }
792
+ }
793
+ if (errors) {
794
+ throw new UnsubscriptionError(errors);
795
+ }
796
+ }
797
+ };
798
+ Subscription.prototype.add = function (teardown) {
799
+ var _a;
800
+ if (teardown && teardown !== this) {
801
+ if (this.closed) {
802
+ execFinalizer(teardown);
803
+ } else {
804
+ if (teardown instanceof Subscription) {
805
+ if (teardown.closed || teardown._hasParent(this)) {
806
+ return;
807
+ }
808
+ teardown._addParent(this);
809
+ }
810
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== undefined ? _a : []).push(teardown);
811
+ }
812
+ }
813
+ };
814
+ Subscription.prototype._hasParent = function (parent) {
815
+ var _parentage = this._parentage;
816
+ return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
817
+ };
818
+ Subscription.prototype._addParent = function (parent) {
819
+ var _parentage = this._parentage;
820
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
821
+ };
822
+ Subscription.prototype._removeParent = function (parent) {
823
+ var _parentage = this._parentage;
824
+ if (_parentage === parent) {
825
+ this._parentage = null;
826
+ } else if (Array.isArray(_parentage)) {
827
+ arrRemove(_parentage, parent);
828
+ }
829
+ };
830
+ Subscription.prototype.remove = function (teardown) {
831
+ var _finalizers = this._finalizers;
832
+ _finalizers && arrRemove(_finalizers, teardown);
833
+ if (teardown instanceof Subscription) {
834
+ teardown._removeParent(this);
835
+ }
836
+ };
837
+ Subscription.EMPTY = function () {
838
+ var empty = new Subscription();
839
+ empty.closed = true;
840
+ return empty;
841
+ }();
842
+ return Subscription;
843
+ }();
844
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
845
+ function isSubscription(value) {
846
+ return value instanceof Subscription || value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
847
+ }
848
+ function execFinalizer(finalizer) {
849
+ if (isFunction(finalizer)) {
850
+ finalizer();
851
+ } else {
852
+ finalizer.unsubscribe();
853
+ }
854
+ }
855
+ var config = {
856
+ onUnhandledError: null,
857
+ onStoppedNotification: null,
858
+ Promise: undefined,
859
+ useDeprecatedSynchronousErrorHandling: false,
860
+ useDeprecatedNextContext: false
861
+ };
862
+ var timeoutProvider = {
863
+ setTimeout: function (handler, timeout) {
864
+ var args = [];
865
+ for (var _i = 2; _i < arguments.length; _i++) {
866
+ args[_i - 2] = arguments[_i];
867
+ }
868
+ return setTimeout.apply(undefined, __spreadArray([handler, timeout], __read(args)));
869
+ },
870
+ clearTimeout: function (handle) {
871
+ return clearTimeout(handle);
872
+ },
873
+ delegate: undefined
874
+ };
875
+ function reportUnhandledError(err) {
876
+ timeoutProvider.setTimeout(function () {
877
+ {
878
+ throw err;
879
+ }
880
+ });
881
+ }
882
+ function noop() {}
883
+ function errorContext(cb) {
884
+ {
885
+ cb();
886
+ }
887
+ }
888
+ var Subscriber = function (_super) {
889
+ __extends(Subscriber, _super);
890
+ function Subscriber(destination) {
891
+ var _this = _super.call(this) || this;
892
+ _this.isStopped = false;
893
+ if (destination) {
894
+ _this.destination = destination;
895
+ if (isSubscription(destination)) {
896
+ destination.add(_this);
897
+ }
898
+ } else {
899
+ _this.destination = EMPTY_OBSERVER;
900
+ }
901
+ return _this;
902
+ }
903
+ Subscriber.create = function (next, error, complete) {
904
+ return new SafeSubscriber(next, error, complete);
905
+ };
906
+ Subscriber.prototype.next = function (value) {
907
+ if (this.isStopped) ;else {
908
+ this._next(value);
909
+ }
910
+ };
911
+ Subscriber.prototype.error = function (err) {
912
+ if (this.isStopped) ;else {
913
+ this.isStopped = true;
914
+ this._error(err);
915
+ }
916
+ };
917
+ Subscriber.prototype.complete = function () {
918
+ if (this.isStopped) ;else {
919
+ this.isStopped = true;
920
+ this._complete();
921
+ }
922
+ };
923
+ Subscriber.prototype.unsubscribe = function () {
924
+ if (!this.closed) {
925
+ this.isStopped = true;
926
+ _super.prototype.unsubscribe.call(this);
927
+ this.destination = null;
928
+ }
929
+ };
930
+ Subscriber.prototype._next = function (value) {
931
+ this.destination.next(value);
932
+ };
933
+ Subscriber.prototype._error = function (err) {
934
+ try {
935
+ this.destination.error(err);
936
+ } finally {
937
+ this.unsubscribe();
938
+ }
939
+ };
940
+ Subscriber.prototype._complete = function () {
941
+ try {
942
+ this.destination.complete();
943
+ } finally {
944
+ this.unsubscribe();
945
+ }
946
+ };
947
+ return Subscriber;
948
+ }(Subscription);
949
+ var ConsumerObserver = function () {
950
+ function ConsumerObserver(partialObserver) {
951
+ this.partialObserver = partialObserver;
952
+ }
953
+ ConsumerObserver.prototype.next = function (value) {
954
+ var partialObserver = this.partialObserver;
955
+ if (partialObserver.next) {
956
+ try {
957
+ partialObserver.next(value);
958
+ } catch (error) {
959
+ handleUnhandledError(error);
960
+ }
961
+ }
962
+ };
963
+ ConsumerObserver.prototype.error = function (err) {
964
+ var partialObserver = this.partialObserver;
965
+ if (partialObserver.error) {
966
+ try {
967
+ partialObserver.error(err);
968
+ } catch (error) {
969
+ handleUnhandledError(error);
970
+ }
971
+ } else {
972
+ handleUnhandledError(err);
973
+ }
974
+ };
975
+ ConsumerObserver.prototype.complete = function () {
976
+ var partialObserver = this.partialObserver;
977
+ if (partialObserver.complete) {
978
+ try {
979
+ partialObserver.complete();
980
+ } catch (error) {
981
+ handleUnhandledError(error);
982
+ }
983
+ }
984
+ };
985
+ return ConsumerObserver;
986
+ }();
987
+ var SafeSubscriber = function (_super) {
988
+ __extends(SafeSubscriber, _super);
989
+ function SafeSubscriber(observerOrNext, error, complete) {
990
+ var _this = _super.call(this) || this;
991
+ var partialObserver;
992
+ if (isFunction(observerOrNext) || !observerOrNext) {
993
+ partialObserver = {
994
+ next: observerOrNext !== null && observerOrNext !== undefined ? observerOrNext : undefined,
995
+ error: error !== null && error !== undefined ? error : undefined,
996
+ complete: complete !== null && complete !== undefined ? complete : undefined
997
+ };
998
+ } else {
999
+ {
1000
+ partialObserver = observerOrNext;
1001
+ }
1002
+ }
1003
+ _this.destination = new ConsumerObserver(partialObserver);
1004
+ return _this;
1005
+ }
1006
+ return SafeSubscriber;
1007
+ }(Subscriber);
1008
+ function handleUnhandledError(error) {
1009
+ {
1010
+ reportUnhandledError(error);
1011
+ }
1012
+ }
1013
+ function defaultErrorHandler(err) {
1014
+ throw err;
1015
+ }
1016
+ var EMPTY_OBSERVER = {
1017
+ closed: true,
1018
+ next: noop,
1019
+ error: defaultErrorHandler,
1020
+ complete: noop
1021
+ };
1022
+ var observable = function () {
1023
+ return typeof Symbol === 'function' && Symbol.observable || '@@observable';
1024
+ }();
1025
+ function identity(x) {
1026
+ return x;
1027
+ }
1028
+ function pipeFromArray(fns) {
1029
+ if (fns.length === 0) {
1030
+ return identity;
1031
+ }
1032
+ if (fns.length === 1) {
1033
+ return fns[0];
1034
+ }
1035
+ return function piped(input) {
1036
+ return fns.reduce(function (prev, fn) {
1037
+ return fn(prev);
1038
+ }, input);
1039
+ };
1040
+ }
1041
+ var Observable = function () {
1042
+ function Observable(subscribe) {
1043
+ if (subscribe) {
1044
+ this._subscribe = subscribe;
1045
+ }
1046
+ }
1047
+ Observable.prototype.lift = function (operator) {
1048
+ var observable = new Observable();
1049
+ observable.source = this;
1050
+ observable.operator = operator;
1051
+ return observable;
1052
+ };
1053
+ Observable.prototype.subscribe = function (observerOrNext, error, complete) {
1054
+ var _this = this;
1055
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
1056
+ errorContext(function () {
1057
+ var _a = _this,
1058
+ operator = _a.operator,
1059
+ source = _a.source;
1060
+ subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
1061
+ });
1062
+ return subscriber;
1063
+ };
1064
+ Observable.prototype._trySubscribe = function (sink) {
1065
+ try {
1066
+ return this._subscribe(sink);
1067
+ } catch (err) {
1068
+ sink.error(err);
1069
+ }
1070
+ };
1071
+ Observable.prototype.forEach = function (next, promiseCtor) {
1072
+ var _this = this;
1073
+ promiseCtor = getPromiseCtor(promiseCtor);
1074
+ return new promiseCtor(function (resolve, reject) {
1075
+ var subscriber = new SafeSubscriber({
1076
+ next: function (value) {
1077
+ try {
1078
+ next(value);
1079
+ } catch (err) {
1080
+ reject(err);
1081
+ subscriber.unsubscribe();
1082
+ }
1083
+ },
1084
+ error: reject,
1085
+ complete: resolve
1086
+ });
1087
+ _this.subscribe(subscriber);
1088
+ });
1089
+ };
1090
+ Observable.prototype._subscribe = function (subscriber) {
1091
+ var _a;
1092
+ return (_a = this.source) === null || _a === undefined ? undefined : _a.subscribe(subscriber);
1093
+ };
1094
+ Observable.prototype[observable] = function () {
1095
+ return this;
1096
+ };
1097
+ Observable.prototype.pipe = function () {
1098
+ var operations = [];
1099
+ for (var _i = 0; _i < arguments.length; _i++) {
1100
+ operations[_i] = arguments[_i];
1101
+ }
1102
+ return pipeFromArray(operations)(this);
1103
+ };
1104
+ Observable.prototype.toPromise = function (promiseCtor) {
1105
+ var _this = this;
1106
+ promiseCtor = getPromiseCtor(promiseCtor);
1107
+ return new promiseCtor(function (resolve, reject) {
1108
+ var value;
1109
+ _this.subscribe(function (x) {
1110
+ return value = x;
1111
+ }, function (err) {
1112
+ return reject(err);
1113
+ }, function () {
1114
+ return resolve(value);
1115
+ });
1116
+ });
1117
+ };
1118
+ Observable.create = function (subscribe) {
1119
+ return new Observable(subscribe);
1120
+ };
1121
+ return Observable;
1122
+ }();
1123
+ function getPromiseCtor(promiseCtor) {
1124
+ var _a;
1125
+ return (_a = promiseCtor !== null && promiseCtor !== undefined ? promiseCtor : config.Promise) !== null && _a !== undefined ? _a : Promise;
1126
+ }
1127
+ function isObserver(value) {
1128
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
1129
+ }
1130
+ function isSubscriber(value) {
1131
+ return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
1132
+ }
1133
+ function hasLift(source) {
1134
+ return isFunction(source === null || source === undefined ? undefined : source.lift);
1135
+ }
1136
+ function operate(init) {
1137
+ return function (source) {
1138
+ if (hasLift(source)) {
1139
+ return source.lift(function (liftedSource) {
1140
+ try {
1141
+ return init(liftedSource, this);
1142
+ } catch (err) {
1143
+ this.error(err);
1144
+ }
1145
+ });
1146
+ }
1147
+ throw new TypeError('Unable to lift unknown Observable type');
1148
+ };
1149
+ }
1150
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
1151
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
1152
+ }
1153
+ var OperatorSubscriber = function (_super) {
1154
+ __extends(OperatorSubscriber, _super);
1155
+ function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
1156
+ var _this = _super.call(this, destination) || this;
1157
+ _this.onFinalize = onFinalize;
1158
+ _this.shouldUnsubscribe = shouldUnsubscribe;
1159
+ _this._next = onNext ? function (value) {
1160
+ try {
1161
+ onNext(value);
1162
+ } catch (err) {
1163
+ destination.error(err);
1164
+ }
1165
+ } : _super.prototype._next;
1166
+ _this._error = onError ? function (err) {
1167
+ try {
1168
+ onError(err);
1169
+ } catch (err) {
1170
+ destination.error(err);
1171
+ } finally {
1172
+ this.unsubscribe();
1173
+ }
1174
+ } : _super.prototype._error;
1175
+ _this._complete = onComplete ? function () {
1176
+ try {
1177
+ onComplete();
1178
+ } catch (err) {
1179
+ destination.error(err);
1180
+ } finally {
1181
+ this.unsubscribe();
1182
+ }
1183
+ } : _super.prototype._complete;
1184
+ return _this;
1185
+ }
1186
+ OperatorSubscriber.prototype.unsubscribe = function () {
1187
+ var _a;
1188
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
1189
+ var closed_1 = this.closed;
1190
+ _super.prototype.unsubscribe.call(this);
1191
+ !closed_1 && ((_a = this.onFinalize) === null || _a === undefined ? undefined : _a.call(this));
1192
+ }
1193
+ };
1194
+ return OperatorSubscriber;
1195
+ }(Subscriber);
1196
+ var ObjectUnsubscribedError = createErrorClass(function (_super) {
1197
+ return function ObjectUnsubscribedErrorImpl() {
1198
+ _super(this);
1199
+ this.name = 'ObjectUnsubscribedError';
1200
+ this.message = 'object unsubscribed';
1201
+ };
1202
+ });
1203
+ var Subject = function (_super) {
1204
+ __extends(Subject, _super);
1205
+ function Subject() {
1206
+ var _this = _super.call(this) || this;
1207
+ _this.closed = false;
1208
+ _this.currentObservers = null;
1209
+ _this.observers = [];
1210
+ _this.isStopped = false;
1211
+ _this.hasError = false;
1212
+ _this.thrownError = null;
1213
+ return _this;
1214
+ }
1215
+ Subject.prototype.lift = function (operator) {
1216
+ var subject = new AnonymousSubject(this, this);
1217
+ subject.operator = operator;
1218
+ return subject;
1219
+ };
1220
+ Subject.prototype._throwIfClosed = function () {
1221
+ if (this.closed) {
1222
+ throw new ObjectUnsubscribedError();
1223
+ }
1224
+ };
1225
+ Subject.prototype.next = function (value) {
1226
+ var _this = this;
1227
+ errorContext(function () {
1228
+ var e_1, _a;
1229
+ _this._throwIfClosed();
1230
+ if (!_this.isStopped) {
1231
+ if (!_this.currentObservers) {
1232
+ _this.currentObservers = Array.from(_this.observers);
1233
+ }
1234
+ try {
1235
+ for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
1236
+ var observer = _c.value;
1237
+ observer.next(value);
1238
+ }
1239
+ } catch (e_1_1) {
1240
+ e_1 = {
1241
+ error: e_1_1
1242
+ };
1243
+ } finally {
1244
+ try {
1245
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1246
+ } finally {
1247
+ if (e_1) throw e_1.error;
1248
+ }
1249
+ }
1250
+ }
1251
+ });
1252
+ };
1253
+ Subject.prototype.error = function (err) {
1254
+ var _this = this;
1255
+ errorContext(function () {
1256
+ _this._throwIfClosed();
1257
+ if (!_this.isStopped) {
1258
+ _this.hasError = _this.isStopped = true;
1259
+ _this.thrownError = err;
1260
+ var observers = _this.observers;
1261
+ while (observers.length) {
1262
+ observers.shift().error(err);
1263
+ }
1264
+ }
1265
+ });
1266
+ };
1267
+ Subject.prototype.complete = function () {
1268
+ var _this = this;
1269
+ errorContext(function () {
1270
+ _this._throwIfClosed();
1271
+ if (!_this.isStopped) {
1272
+ _this.isStopped = true;
1273
+ var observers = _this.observers;
1274
+ while (observers.length) {
1275
+ observers.shift().complete();
1276
+ }
1277
+ }
1278
+ });
1279
+ };
1280
+ Subject.prototype.unsubscribe = function () {
1281
+ this.isStopped = this.closed = true;
1282
+ this.observers = this.currentObservers = null;
1283
+ };
1284
+ Object.defineProperty(Subject.prototype, "observed", {
1285
+ get: function () {
1286
+ var _a;
1287
+ return ((_a = this.observers) === null || _a === undefined ? undefined : _a.length) > 0;
1288
+ },
1289
+ enumerable: false,
1290
+ configurable: true
1291
+ });
1292
+ Subject.prototype._trySubscribe = function (subscriber) {
1293
+ this._throwIfClosed();
1294
+ return _super.prototype._trySubscribe.call(this, subscriber);
1295
+ };
1296
+ Subject.prototype._subscribe = function (subscriber) {
1297
+ this._throwIfClosed();
1298
+ this._checkFinalizedStatuses(subscriber);
1299
+ return this._innerSubscribe(subscriber);
1300
+ };
1301
+ Subject.prototype._innerSubscribe = function (subscriber) {
1302
+ var _this = this;
1303
+ var _a = this,
1304
+ hasError = _a.hasError,
1305
+ isStopped = _a.isStopped,
1306
+ observers = _a.observers;
1307
+ if (hasError || isStopped) {
1308
+ return EMPTY_SUBSCRIPTION;
1309
+ }
1310
+ this.currentObservers = null;
1311
+ observers.push(subscriber);
1312
+ return new Subscription(function () {
1313
+ _this.currentObservers = null;
1314
+ arrRemove(observers, subscriber);
1315
+ });
1316
+ };
1317
+ Subject.prototype._checkFinalizedStatuses = function (subscriber) {
1318
+ var _a = this,
1319
+ hasError = _a.hasError,
1320
+ thrownError = _a.thrownError,
1321
+ isStopped = _a.isStopped;
1322
+ if (hasError) {
1323
+ subscriber.error(thrownError);
1324
+ } else if (isStopped) {
1325
+ subscriber.complete();
1326
+ }
1327
+ };
1328
+ Subject.prototype.asObservable = function () {
1329
+ var observable = new Observable();
1330
+ observable.source = this;
1331
+ return observable;
1332
+ };
1333
+ Subject.create = function (destination, source) {
1334
+ return new AnonymousSubject(destination, source);
1335
+ };
1336
+ return Subject;
1337
+ }(Observable);
1338
+ var AnonymousSubject = function (_super) {
1339
+ __extends(AnonymousSubject, _super);
1340
+ function AnonymousSubject(destination, source) {
1341
+ var _this = _super.call(this) || this;
1342
+ _this.destination = destination;
1343
+ _this.source = source;
1344
+ return _this;
1345
+ }
1346
+ AnonymousSubject.prototype.next = function (value) {
1347
+ var _a, _b;
1348
+ (_b = (_a = this.destination) === null || _a === undefined ? undefined : _a.next) === null || _b === undefined ? undefined : _b.call(_a, value);
1349
+ };
1350
+ AnonymousSubject.prototype.error = function (err) {
1351
+ var _a, _b;
1352
+ (_b = (_a = this.destination) === null || _a === undefined ? undefined : _a.error) === null || _b === undefined ? undefined : _b.call(_a, err);
1353
+ };
1354
+ AnonymousSubject.prototype.complete = function () {
1355
+ var _a, _b;
1356
+ (_b = (_a = this.destination) === null || _a === undefined ? undefined : _a.complete) === null || _b === undefined ? undefined : _b.call(_a);
1357
+ };
1358
+ AnonymousSubject.prototype._subscribe = function (subscriber) {
1359
+ var _a, _b;
1360
+ return (_b = (_a = this.source) === null || _a === undefined ? undefined : _a.subscribe(subscriber)) !== null && _b !== undefined ? _b : EMPTY_SUBSCRIPTION;
1361
+ };
1362
+ return AnonymousSubject;
1363
+ }(Subject);
1364
+ var EmptyError = createErrorClass(function (_super) {
1365
+ return function EmptyErrorImpl() {
1366
+ _super(this);
1367
+ this.name = 'EmptyError';
1368
+ this.message = 'no elements in sequence';
1369
+ };
1370
+ });
1371
+ function firstValueFrom(source, config) {
1372
+ return new Promise(function (resolve, reject) {
1373
+ var subscriber = new SafeSubscriber({
1374
+ next: function (value) {
1375
+ resolve(value);
1376
+ subscriber.unsubscribe();
1377
+ },
1378
+ error: reject,
1379
+ complete: function () {
1380
+ {
1381
+ reject(new EmptyError());
1382
+ }
1383
+ }
1384
+ });
1385
+ source.subscribe(subscriber);
1386
+ });
1387
+ }
1388
+ function map(project, thisArg) {
1389
+ return operate(function (source, subscriber) {
1390
+ var index = 0;
1391
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1392
+ subscriber.next(project.call(thisArg, value, index++));
1393
+ }));
1394
+ });
1395
+ }
1396
+ function filter(predicate, thisArg) {
1397
+ return operate(function (source, subscriber) {
1398
+ var index = 0;
1399
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1400
+ return predicate.call(thisArg, value, index++) && subscriber.next(value);
1401
+ }));
1402
+ });
1403
+ }
1404
+
1405
+ // refer to realm-network-api/src/common/enums/error-codes.enum.ts
1406
+ /*** Authentication Errors ***/
1407
+ var AuthErrorName;
1408
+ (function (AuthErrorName) {
1409
+ AuthErrorName["UNAUTHORIZED"] = "UNAUTHORIZED";
1410
+ AuthErrorName["INVALID_TOKEN"] = "INVALID_TOKEN";
1411
+ AuthErrorName["TOKEN_EXPIRED"] = "TOKEN_EXPIRED";
1412
+ AuthErrorName["INVALID_CREDENTIALS"] = "INVALID_CREDENTIALS";
1413
+ })(AuthErrorName || (AuthErrorName = {}));
1414
+ /*** Partner Access Token Errors ***/
1415
+ var PartnerAccessTokenErrorName;
1416
+ (function (PartnerAccessTokenErrorName) {
1417
+ PartnerAccessTokenErrorName["PARTNER_ACCESS_TOKEN_INVALID"] = "PARTNER_ACCESS_TOKEN_INVALID";
1418
+ PartnerAccessTokenErrorName["USER_MISMATCH"] = "USER_MISMATCH";
1419
+ })(PartnerAccessTokenErrorName || (PartnerAccessTokenErrorName = {}));
1420
+ /*** Realm ID Errors ***/
1421
+ var RealmIDErrorName;
1422
+ (function (RealmIDErrorName) {
1423
+ RealmIDErrorName["REALM_ID_NOT_FOUND"] = "REALM_ID_NOT_FOUND";
1424
+ RealmIDErrorName["REALM_ID_INVALID_NAME"] = "REALM_ID_INVALID_NAME";
1425
+ RealmIDErrorName["REALM_ID_ALREADY_EXISTS"] = "REALM_ID_ALREADY_EXISTS";
1426
+ RealmIDErrorName["REALM_ID_DUPLICATE_PARTNER_USER"] = "REALM_ID_DUPLICATE_PARTNER_USER";
1427
+ })(RealmIDErrorName || (RealmIDErrorName = {}));
1428
+ /*** Parameter Errors ***/
1429
+ var ParameterErrorName;
1430
+ (function (ParameterErrorName) {
1431
+ ParameterErrorName["INVALID_PARAMETER"] = "INVALID_PARAMETER";
1432
+ })(ParameterErrorName || (ParameterErrorName = {}));
1433
+ /*** Server Errors ***/
1434
+ var ServerErrorName;
1435
+ (function (ServerErrorName) {
1436
+ ServerErrorName["INTERNAL_SERVER_ERROR"] = "INTERNAL_SERVER_ERROR";
1437
+ })(ServerErrorName || (ServerErrorName = {}));
1438
+ /*** Passkey Errors ***/
1439
+ var PasskeyErrorName;
1440
+ (function (PasskeyErrorName) {
1441
+ PasskeyErrorName["PASSKEY_REGISTRATION_FAILED"] = "PASSKEY_REGISTRATION_FAILED";
1442
+ PasskeyErrorName["PASSKEY_AUTHENTICATION_FAILED"] = "PASSKEY_AUTHENTICATION_FAILED";
1443
+ PasskeyErrorName["PASSKEY_LIMIT_EXCEEDED"] = "PASSKEY_LIMIT_EXCEEDED";
1444
+ PasskeyErrorName["PASSKEY_NOT_FOUND"] = "PASSKEY_NOT_FOUND";
1445
+ PasskeyErrorName["PASSKEY_UNAUTHORIZED"] = "PASSKEY_UNAUTHORIZED";
1446
+ PasskeyErrorName["PASSKEY_CHALLENGE_INVALID"] = "PASSKEY_CHALLENGE_INVALID";
1447
+ })(PasskeyErrorName || (PasskeyErrorName = {}));
1448
+ /*** Passwordless Authentication Errors ***/
1449
+ var PasswordlessErrorName;
1450
+ (function (PasswordlessErrorName) {
1451
+ PasswordlessErrorName["PASSWORDLESS_CODE_EXPIRED"] = "PASSWORDLESS_CODE_EXPIRED";
1452
+ PasswordlessErrorName["PASSWORDLESS_INVALID_CODE"] = "PASSWORDLESS_INVALID_CODE";
1453
+ PasswordlessErrorName["PASSWORDLESS_MAX_ATTEMPTS"] = "PASSWORDLESS_MAX_ATTEMPTS";
1454
+ PasswordlessErrorName["PASSWORDLESS_HOURLY_LIMIT"] = "PASSWORDLESS_HOURLY_LIMIT";
1455
+ PasswordlessErrorName["PASSWORDLESS_LOCK_EXCEEDED"] = "PASSWORDLESS_LOCK_EXCEEDED";
1456
+ PasswordlessErrorName["CAPTCHA_TOKEN_VERIFICATION_FAILED"] = "CAPTCHA_TOKEN_VERIFICATION_FAILED";
1457
+ PasswordlessErrorName["CAPTCHA_TOKEN_INVALID"] = "CAPTCHA_TOKEN_INVALID";
1458
+ PasswordlessErrorName["CAPTCHA_SECRET_MISSING"] = "CAPTCHA_SECRET_MISSING";
1459
+ PasswordlessErrorName["CAPTCHA_TOKEN_MISSING"] = "CAPTCHA_TOKEN_MISSING";
1460
+ })(PasswordlessErrorName || (PasswordlessErrorName = {}));
1461
+ /*** Authentication Wallet Errors ***/
1462
+ var AuthWalletErrorName;
1463
+ (function (AuthWalletErrorName) {
1464
+ AuthWalletErrorName["AUTH_WALLET_LOCK_EXCEEDED"] = "AUTH_WALLET_LOCK_EXCEEDED";
1465
+ AuthWalletErrorName["AUTH_WALLET_NONCE_EXPIRED_OR_INVALID"] = "AUTH_WALLET_NONCE_EXPIRED_OR_INVALID";
1466
+ AuthWalletErrorName["AUTH_WALLET_ADDRESS_MISMATCH"] = "AUTH_WALLET_ADDRESS_MISMATCH";
1467
+ AuthWalletErrorName["AUTH_WALLET_SIGNATURE_VERIFICATION_FAILED"] = "AUTH_WALLET_SIGNATURE_VERIFICATION_FAILED";
1468
+ })(AuthWalletErrorName || (AuthWalletErrorName = {}));
1469
+ /*** Wallet Linking Errors ***/
1470
+ var WalletLinkErrorName;
1471
+ (function (WalletLinkErrorName) {
1472
+ WalletLinkErrorName["LINK_WALLET_ALREADY_LINKED"] = "LINK_WALLET_ALREADY_LINKED";
1473
+ WalletLinkErrorName["LINK_WALLET_LINKED_OTHER_ACCOUNT"] = "LINK_WALLET_LINKED_OTHER_ACCOUNT";
1474
+ WalletLinkErrorName["LINK_EMAIL_LINKED_OTHER_ACCOUNT"] = "LINK_EMAIL_LINKED_OTHER_ACCOUNT";
1475
+ })(WalletLinkErrorName || (WalletLinkErrorName = {}));
1476
+ /*** Intent Errors ***/
1477
+ var IntentErrorName;
1478
+ (function (IntentErrorName) {
1479
+ IntentErrorName["INTENT_INVALID"] = "INTENT_INVALID";
1480
+ IntentErrorName["INTENT_LOCK_EXCEEDED"] = "INTENT_LOCK_EXCEEDED";
1481
+ IntentErrorName["INTENT_REQUIRED"] = "INTENT_REQUIRED";
1482
+ IntentErrorName["INTENT_UNSUPPORTED_TYPE"] = "INTENT_UNSUPPORTED_TYPE";
1483
+ })(IntentErrorName || (IntentErrorName = {}));
1484
+ /*** Privy Errors ***/
1485
+ var PrivyErrorName;
1486
+ (function (PrivyErrorName) {
1487
+ PrivyErrorName["WALLET_PROVIDER_ERROR"] = "WALLET_PROVIDER_ERROR";
1488
+ })(PrivyErrorName || (PrivyErrorName = {}));
1489
+ /*** Air ID Errors ***/
1490
+ var AirIDErrorName;
1491
+ (function (AirIDErrorName) {
1492
+ AirIDErrorName["AIR_ID_MINT_TRANSACTION_NOT_FOUND"] = "AIR_ID_MINT_TRANSACTION_NOT_FOUND";
1493
+ AirIDErrorName["AIR_ID_ON_CHAIN_TRANSACTION_NOT_FOUND"] = "AIR_ID_ON_CHAIN_TRANSACTION_NOT_FOUND";
1494
+ AirIDErrorName["AIR_ID_NOT_FOUND"] = "AIR_ID_NOT_FOUND";
1495
+ AirIDErrorName["AIR_ID_INVALID_OR_DISABLED_CONFIGURATION"] = "AIR_ID_INVALID_OR_DISABLED_CONFIGURATION";
1496
+ AirIDErrorName["AIR_ID_RPC_URL_NOT_CONFIGURED"] = "AIR_ID_RPC_URL_NOT_CONFIGURED";
1497
+ AirIDErrorName["AIR_ID_INVALID_STATUS"] = "AIR_ID_INVALID_STATUS";
1498
+ AirIDErrorName["AIR_ID_PARTNER_ELIGIBILITY_CHECK_FAILED"] = "AIR_ID_PARTNER_ELIGIBILITY_CHECK_FAILED";
1499
+ AirIDErrorName["AIR_ID_PARTNER_ELIGIBILITY_CHECK_TIMEOUT"] = "AIR_ID_PARTNER_ELIGIBILITY_CHECK_TIMEOUT";
1500
+ AirIDErrorName["AIR_ID_MULTIPLE_AIR_IDS_FOUND"] = "AIR_ID_MULTIPLE_AIR_IDS_FOUND";
1501
+ AirIDErrorName["AIR_ID_NAME_RESERVED"] = "AIR_ID_NAME_RESERVED";
1502
+ AirIDErrorName["AIR_ID_NAME_PROFANITY"] = "AIR_ID_NAME_PROFANITY";
1503
+ AirIDErrorName["AIR_ID_USER_ALREADY_HAS_AIR_ID"] = "AIR_ID_USER_ALREADY_HAS_AIR_ID";
1504
+ AirIDErrorName["AIR_ID_NAME_ALREADY_EXISTS"] = "AIR_ID_NAME_ALREADY_EXISTS";
1505
+ AirIDErrorName["AIR_ID_INVALID_MINT_NAME"] = "AIR_ID_INVALID_MINT_NAME";
1506
+ AirIDErrorName["AIR_ID_MINT_TRANSACTION_HASH_MISMATCH"] = "AIR_ID_MINT_TRANSACTION_HASH_MISMATCH";
1507
+ })(AirIDErrorName || (AirIDErrorName = {}));
1508
+ /*** Window Errors ***/
1509
+ var WindowErrorName;
1510
+ (function (WindowErrorName) {
1511
+ WindowErrorName["WINDOW_BLOCKED"] = "WINDOW_BLOCKED";
1512
+ WindowErrorName["WINDOW_CLOSED"] = "WINDOW_CLOSED";
1513
+ })(WindowErrorName || (WindowErrorName = {}));
1514
+ const Codes = {
1515
+ ...AuthErrorName,
1516
+ ...PartnerAccessTokenErrorName,
1517
+ ...RealmIDErrorName,
1518
+ ...ParameterErrorName,
1519
+ ...ServerErrorName,
1520
+ ...PasskeyErrorName,
1521
+ ...PasswordlessErrorName,
1522
+ ...AuthWalletErrorName,
1523
+ ...WalletLinkErrorName,
1524
+ ...IntentErrorName,
1525
+ ...PrivyErrorName,
1526
+ ...AirIDErrorName,
1527
+ ...WindowErrorName
1528
+ };
1529
+ const AirClientUserErrors = ["USER_CANCELLED", "CONFIG_ERROR", "CLIENT_ERROR", "UNKNOWN_ERROR", "PERMISSION_NOT_ENABLED", "SMART_ACCOUNT_NOT_DEPLOYED"];
1530
+ class AirError extends BaseError$2 {}
1531
+ new Set(AirClientUserErrors);
1532
+ new Set(Object.values(Codes));
1533
+ class MessageServiceBase {
1534
+ get events$() {
1535
+ return this._events$;
1536
+ }
1537
+ get messages$() {
1538
+ return this._messages$;
1539
+ }
1540
+ get isOpen() {
1541
+ return !!this.closeListener;
1542
+ }
1543
+ constructor(name, allowedMessageTypes) {
1544
+ this.name = name;
1545
+ this.allowedMessageTypes = allowedMessageTypes;
1546
+ this.closeListener = null;
1547
+ }
1548
+ async _open(target) {
1549
+ await this.close();
1550
+ this.eventSubject = new Subject();
1551
+ this._events$ = this.eventSubject.asObservable();
1552
+ this._messages$ = this.eventSubject.pipe(map(ev => ev.data));
1553
+ this._events$.subscribe(event => {
1554
+ const sentOrReceived = event.origin === window.origin ? "sent" : "received";
1555
+ log$1.debug(`[${this.name}] Message ${sentOrReceived}:`, event.data);
1556
+ });
1557
+ const handleMessage = async ev => {
1558
+ if (this.targetOrigin && ev.origin !== this.targetOrigin || !ev.data || !(ev.data instanceof Object)) return;
1559
+ if (this.isMessageAllowed(ev.data)) {
1560
+ await this.onBeforeEvent(ev);
1561
+ this.eventSubject.next(ev);
1562
+ }
1563
+ };
1564
+ if (target instanceof MessagePort) {
1565
+ this.messagePort = target;
1566
+ target.onmessage = handleMessage;
1567
+ this.closeListener = async () => {
1568
+ target.close();
1569
+ };
1570
+ } else {
1571
+ this.targetWindow = target.window;
1572
+ this.targetOrigin = target.origin;
1573
+ window.addEventListener("message", handleMessage);
1574
+ this.closeListener = async () => {
1575
+ window.removeEventListener("message", handleMessage);
1576
+ };
1577
+ }
1578
+ }
1579
+ isMessageAllowed(message) {
1580
+ return this.allowedMessageTypes.includes(message.type);
1581
+ }
1582
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1583
+ async onBeforeEvent(_event) {
1584
+ // by default not used
1585
+ }
1586
+ async close() {
1587
+ if (this.closeListener) {
1588
+ await this.closeListener();
1589
+ this.closeListener = null;
1590
+ }
1591
+ if (this.eventSubject && !this.eventSubject.closed) {
1592
+ this.eventSubject.complete();
1593
+ }
1594
+ }
1595
+ createErrorResponseMessage(type, error) {
1596
+ return {
1597
+ type,
1598
+ payload: {
1599
+ success: false,
1600
+ errorName: error instanceof AirError ? error.name : "UNKNOWN_ERROR",
1601
+ errorMessage: error.message
1602
+ }
1603
+ };
1604
+ }
1605
+ async sendMessage(message, transfer) {
1606
+ // To prevent any non-cloneable objects causing errors in postMessage
1607
+ const clonedMessage = this.deepClone(message);
1608
+ if (this.messagePort) {
1609
+ this.messagePort.postMessage(clonedMessage);
1610
+ this.eventSubject.next(new MessageEvent("message", {
1611
+ data: clonedMessage,
1612
+ origin: window.origin
1613
+ }));
1614
+ } else if (this.targetWindow && this.targetOrigin) {
1615
+ this.targetWindow.postMessage(clonedMessage, this.targetOrigin, transfer);
1616
+ this.eventSubject.next(new MessageEvent("message", {
1617
+ data: clonedMessage,
1618
+ origin: window.origin
1619
+ }));
1620
+ } else {
1621
+ log$1.debug(`[${this.name}] Not opened yet`);
1622
+ }
1623
+ }
1624
+ deepClone(message) {
1625
+ try {
1626
+ return JSON.parse(JSON.stringify(message));
1627
+ } catch (e) {
1628
+ log$1.warn("Error generating cloneable message", e);
1629
+ return message;
1630
+ }
1631
+ }
1632
+ }
1633
+ var AirWalletProviderMessageTypes;
1634
+ (function (AirWalletProviderMessageTypes) {
1635
+ AirWalletProviderMessageTypes["REQUEST"] = "JRPC_REQUEST";
1636
+ AirWalletProviderMessageTypes["RESPONSE"] = "JRPC_RESPONSE";
1637
+ AirWalletProviderMessageTypes["EVENT"] = "JRPC_EVENT";
1638
+ })(AirWalletProviderMessageTypes || (AirWalletProviderMessageTypes = {}));
1639
+ var _a$2, _ProviderMessageService_instance;
1640
+ const ALLOWED_PROVIDER_MESSAGES = [AirWalletProviderMessageTypes.RESPONSE, AirWalletProviderMessageTypes.EVENT];
1641
+ class ProviderMessageService extends MessageServiceBase {
1642
+ static create() {
1643
+ if (__classPrivateFieldGet$1(this, _a$2, "f", _ProviderMessageService_instance)) throw new Error("ProviderMessageService already created");
1644
+ __classPrivateFieldSet(this, _a$2, new _a$2("Embed Service: Provider Channel", ALLOWED_PROVIDER_MESSAGES), "f", _ProviderMessageService_instance);
1645
+ return __classPrivateFieldGet$1(this, _a$2, "f", _ProviderMessageService_instance);
1646
+ }
1647
+ async open(walletIframe) {
1648
+ const origin = new URL(walletIframe.src).origin;
1649
+ const window = walletIframe.contentWindow;
1650
+ await super._open({
1651
+ window,
1652
+ origin
1653
+ });
1654
+ }
1655
+ async sendWalletProviderRequest(payload) {
1656
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletProviderMessageTypes.RESPONSE), filter(msg => msg.payload.method === payload.method)));
1657
+ await this.sendMessage({
1658
+ type: AirWalletProviderMessageTypes.REQUEST,
1659
+ payload
1660
+ });
1661
+ return response;
1662
+ }
1663
+ }
1664
+ _a$2 = ProviderMessageService;
1665
+ _ProviderMessageService_instance = {
1666
+ value: undefined
1667
+ };
1668
+ var _AirWalletProvider_instances, _AirWalletProvider_providerMessageService, _AirWalletProvider_isLoggedIn, _AirWalletProvider_ensureWallet, _AirWalletProvider_eventListeners, _AirWalletProvider_emit;
1669
+ class AirWalletProvider {
1670
+ constructor({
1671
+ isLoggedIn,
1672
+ ensureWallet
1673
+ }) {
1674
+ _AirWalletProvider_instances.add(this);
1675
+ _AirWalletProvider_providerMessageService.set(this, undefined);
1676
+ _AirWalletProvider_isLoggedIn.set(this, undefined);
1677
+ _AirWalletProvider_ensureWallet.set(this, undefined);
1678
+ _AirWalletProvider_eventListeners.set(this, undefined);
1679
+ this.startEventMessageListening = async walletIframe => {
1680
+ await __classPrivateFieldGet$1(this, _AirWalletProvider_providerMessageService, "f").open(walletIframe);
1681
+ __classPrivateFieldGet$1(this, _AirWalletProvider_providerMessageService, "f").messages$.pipe(filter(msg => msg.type === AirWalletProviderMessageTypes.EVENT)).subscribe(message => {
1682
+ __classPrivateFieldGet$1(this, _AirWalletProvider_instances, "m", _AirWalletProvider_emit).call(this, message.payload.event, ...[message.payload.data]);
1683
+ });
1684
+ };
1685
+ __classPrivateFieldSet(this, _AirWalletProvider_providerMessageService, ProviderMessageService.create());
1686
+ __classPrivateFieldSet(this, _AirWalletProvider_isLoggedIn, isLoggedIn);
1687
+ __classPrivateFieldSet(this, _AirWalletProvider_ensureWallet, ensureWallet);
1688
+ __classPrivateFieldSet(this, _AirWalletProvider_eventListeners, {
1689
+ connect: [],
1690
+ disconnect: [],
1691
+ accountsChanged: [],
1692
+ chainChanged: [],
1693
+ message: []
1694
+ });
1695
+ }
1696
+ async request(request) {
1697
+ // Check if the request is valid
1698
+ if (!request || typeof request !== "object" || Array.isArray(request)) {
1699
+ throw new InvalidRequestRpcError("Invalid request");
1700
+ }
1701
+ const {
1702
+ method,
1703
+ params
1704
+ } = request;
1705
+ // Check if the method is valid
1706
+ if (typeof method !== "string" || method.length === 0) {
1707
+ throw new MethodNotFoundRpcError("Invalid method");
1708
+ }
1709
+ // Check if the params are valid
1710
+ if (params !== undefined && !Array.isArray(params) && (typeof params !== "object" || params === null)) {
1711
+ throw new InvalidParamsRpcError("Invalid params");
1712
+ }
1713
+ // Check if the user is logged in
1714
+ if (!__classPrivateFieldGet$1(this, _AirWalletProvider_isLoggedIn, "f").call(this)) {
1715
+ throw new UnauthorizedProviderError("User is not logged in");
1716
+ }
1717
+ try {
1718
+ await __classPrivateFieldGet$1(this, _AirWalletProvider_ensureWallet, "f").call(this);
1719
+ } catch (error) {
1720
+ throw ensureProviderRpcError(error);
1721
+ }
1722
+ const requestId = randomId();
1723
+ const response = await __classPrivateFieldGet$1(this, _AirWalletProvider_providerMessageService, "f").sendWalletProviderRequest({
1724
+ requestId,
1725
+ ...request
1726
+ });
1727
+ if (!response.success) {
1728
+ throw ensureProviderRpcError(response.payload);
1729
+ }
1730
+ return response.payload.response;
1731
+ }
1732
+ on(eventName, listener) {
1733
+ __classPrivateFieldGet$1(this, _AirWalletProvider_eventListeners, "f")[eventName] = __classPrivateFieldGet$1(this, _AirWalletProvider_eventListeners, "f")[eventName] || [];
1734
+ __classPrivateFieldGet$1(this, _AirWalletProvider_eventListeners, "f")[eventName].push(listener);
1735
+ }
1736
+ removeListener(eventName, listener) {
1737
+ __classPrivateFieldGet$1(this, _AirWalletProvider_eventListeners, "f")[eventName] = __classPrivateFieldGet$1(this, _AirWalletProvider_eventListeners, "f")[eventName] || [];
1738
+ const index = __classPrivateFieldGet$1(this, _AirWalletProvider_eventListeners, "f")[eventName].indexOf(listener);
1739
+ if (index >= 0) {
1740
+ __classPrivateFieldGet$1(this, _AirWalletProvider_eventListeners, "f")[eventName].splice(index, 1);
1741
+ }
1742
+ }
1743
+ removeAllListeners() {
1744
+ __classPrivateFieldSet(this, _AirWalletProvider_eventListeners, {
1745
+ connect: [],
1746
+ disconnect: [],
1747
+ accountsChanged: [],
1748
+ chainChanged: [],
1749
+ message: []
1750
+ });
1751
+ }
1752
+ }
1753
+ _AirWalletProvider_providerMessageService = new WeakMap(), _AirWalletProvider_isLoggedIn = new WeakMap(), _AirWalletProvider_ensureWallet = new WeakMap(), _AirWalletProvider_eventListeners = new WeakMap(), _AirWalletProvider_instances = new WeakSet(), _AirWalletProvider_emit = function _AirWalletProvider_emit(eventName, ...args) {
1754
+ (__classPrivateFieldGet$1(this, _AirWalletProvider_eventListeners, "f")[eventName] || []).forEach(listener => {
1755
+ try {
1756
+ return listener(...args);
1757
+ } catch (error) {
1758
+ log$1.warn(error);
1759
+ }
1760
+ });
1761
+ };
1762
+ class IframeController {
1763
+ constructor(iframeUrl, iframeId, state) {
1764
+ this._iframeElement = null;
1765
+ this.state = {
1766
+ ...IframeController.defaultState,
1767
+ ...state
1768
+ };
1769
+ this.iframeUrl = iframeUrl;
1770
+ this.iframeId = iframeId;
1771
+ }
1772
+ get iframeElement() {
1773
+ return this._iframeElement;
1774
+ }
1775
+ createIframe() {
1776
+ if (this._iframeElement) return this._iframeElement;
1777
+ const iframe = document.createElement("iframe");
1778
+ iframe.id = this.iframeId;
1779
+ iframe.allow = "publickey-credentials-get *; publickey-credentials-create *";
1780
+ iframe.src = this.iframeUrl;
1781
+ iframe.style.position = "fixed";
1782
+ iframe.style.zIndex = "999999";
1783
+ iframe.style.border = "none";
1784
+ iframe.style.margin = "0";
1785
+ iframe.style.padding = "0";
1786
+ iframe.style.display = "none";
1787
+ iframe.style.colorScheme = "auto";
1788
+ document.body.appendChild(iframe);
1789
+ this._iframeElement = iframe;
1790
+ return iframe;
1791
+ }
1792
+ setIframeVisibility(isVisible) {
1793
+ this.state.isVisible = isVisible;
1794
+ }
1795
+ updateIframeState() {
1796
+ if (!this.iframeElement) return;
1797
+ const style = {};
1798
+ style.display = this.state.isVisible ? "block" : "none";
1799
+ style.width = "100%";
1800
+ style.height = "100%";
1801
+ style.top = "0px";
1802
+ style.right = "0px";
1803
+ style.left = "0px";
1804
+ style.bottom = "0px";
1805
+ Object.assign(this.iframeElement.style, style);
1806
+ }
1807
+ destroy() {
1808
+ if (this.iframeElement) {
1809
+ this.iframeElement.remove();
1810
+ this._iframeElement = null;
1811
+ }
1812
+ }
1813
+ postMessage(message) {
1814
+ if (!this.iframeElement) return;
1815
+ const {
1816
+ origin
1817
+ } = new URL(this.iframeElement.src);
1818
+ this.iframeElement.contentWindow.postMessage(message, origin);
1819
+ }
1820
+ }
1821
+ IframeController.defaultState = {
1822
+ isVisible: false
1823
+ };
1824
+
1825
+ /**
1826
+ * Creates a window features string for `window.open`, based on the current screen size.
1827
+ * It tries to center the window and limits the size to the given max width and height.
1828
+ * Slightly reduces the size to avoid browser auto-resizing.
1829
+ */
1830
+ const getWindowFeatures = (maxWidth, maxHeight) => {
1831
+ const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
1832
+ const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;
1833
+ const w = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : window.screen.width;
1834
+ const h = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : window.screen.height;
1835
+ // 95% adjustment for mobile devices, some browser might resize the window
1836
+ const finalWidth = Math.min(w, maxWidth) * 0.95;
1837
+ const finalHeight = Math.min(h, maxHeight) * 0.95;
1838
+ const systemZoom = 1; // No reliable estimate
1839
+ const left = Math.abs((w - finalWidth) / 2 / systemZoom + dualScreenLeft);
1840
+ const top = Math.abs((h - finalHeight) / 2 / systemZoom + dualScreenTop);
1841
+ return `titlebar=0,toolbar=0,status=0,location=0,menubar=0,height=${finalHeight / systemZoom},width=${finalWidth / systemZoom},top=${top},left=${left}`;
1842
+ };
1843
+ class WindowController {
1844
+ get messages$() {
1845
+ return this._messages$.asObservable();
1846
+ }
1847
+ constructor(windowId, windowUrl) {
1848
+ this._windowInstance = null;
1849
+ this._messageHandler = null;
1850
+ this._messages$ = new Subject();
1851
+ this.windowId = windowId;
1852
+ this.windowUrl = windowUrl;
1853
+ this.windowOrigin = new URL(windowUrl).origin;
1854
+ this._messageHandler = ev => {
1855
+ if (ev.source !== this._windowInstance || ev.origin !== this.windowOrigin || !ev.data || !(ev.data instanceof Object)) {
1856
+ return;
1857
+ }
1858
+ this._messages$.next(ev);
1859
+ };
1860
+ window.addEventListener("message", this._messageHandler);
1861
+ }
1862
+ get windowInstance() {
1863
+ return this._windowInstance;
1864
+ }
1865
+ async openWindow(onRetry) {
1866
+ let windowInstance = this.tryOpenWindow();
1867
+ if (!windowInstance) {
1868
+ await onRetry();
1869
+ windowInstance = this.tryOpenWindow();
1870
+ if (!windowInstance) {
1871
+ throw new AirError(WindowErrorName.WINDOW_BLOCKED);
1872
+ }
1873
+ }
1874
+ const pendingWindowOpenCheck = new Promise((resolve, reject) => {
1875
+ setTimeout(() => {
1876
+ if (this.isWindowOpen(windowInstance)) {
1877
+ // only now are we scheduling the close event check since we're sure the window is open
1878
+ this.scheduleWindowClosedChecks(windowInstance);
1879
+ resolve("opened");
1880
+ } else {
1881
+ onRetry().then(() => {
1882
+ windowInstance = this.tryOpenWindow();
1883
+ if (windowInstance) {
1884
+ this._windowInstance = windowInstance;
1885
+ windowInstance.focus();
1886
+ this.scheduleWindowClosedChecks(windowInstance);
1887
+ resolve("retry");
1888
+ } else {
1889
+ reject(new AirError(WindowErrorName.WINDOW_BLOCKED));
1890
+ }
1891
+ }).catch(reject);
1892
+ }
1893
+ }, 1000);
1894
+ });
1895
+ this._windowInstance = windowInstance;
1896
+ windowInstance.focus();
1897
+ return {
1898
+ pendingWindowOpenCheck
1899
+ };
1900
+ }
1901
+ postMessage(message, transfer) {
1902
+ if (!this._windowInstance) return;
1903
+ this._windowInstance.postMessage(message, this.windowOrigin, transfer);
1904
+ }
1905
+ onMessage(callback) {
1906
+ const listener = ev => {
1907
+ if (ev.source !== this._windowInstance || ev.origin !== this.windowOrigin) return;
1908
+ callback(ev);
1909
+ };
1910
+ window.addEventListener("message", listener);
1911
+ const close = () => window.removeEventListener("message", listener);
1912
+ this.onClose(close);
1913
+ return {
1914
+ close
1915
+ };
1916
+ }
1917
+ cleanup() {
1918
+ if (this._windowInstance && !this._windowInstance.closed) {
1919
+ this._windowInstance.close();
1920
+ }
1921
+ this._windowInstance = null;
1922
+ if (this._messageHandler) {
1923
+ window.removeEventListener("message", this._messageHandler);
1924
+ this._messageHandler = null;
1925
+ }
1926
+ if (this._messages$ && !this._messages$.closed) {
1927
+ this._messages$.complete();
1928
+ }
1929
+ }
1930
+ onClose(callback) {
1931
+ return this._messages$.subscribe({
1932
+ complete: callback
1933
+ });
1934
+ }
1935
+ isWindowOpen(windowInstance) {
1936
+ return !(!windowInstance || windowInstance.closed || typeof windowInstance.closed == "undefined");
1937
+ }
1938
+ tryOpenWindow() {
1939
+ const windowInstance = window.open(this.windowUrl, this.windowId, getWindowFeatures(425, 680));
1940
+ if (this.isWindowOpen(windowInstance)) {
1941
+ return windowInstance;
1942
+ }
1943
+ return null;
1944
+ }
1945
+ scheduleWindowClosedChecks(windowInstance) {
1946
+ const checkWindow = setInterval(() => {
1947
+ if (!windowInstance || windowInstance.closed) {
1948
+ clearInterval(checkWindow);
1949
+ if (windowInstance === this._windowInstance) {
1950
+ this.cleanup();
1951
+ }
1952
+ }
1953
+ }, 500);
1954
+ }
1955
+ }
1956
+ class WindowService {
1957
+ constructor() {
1958
+ this.windowControllers = new Map();
1959
+ }
1960
+ static get instance() {
1961
+ return this._instance || (this._instance = new this());
1962
+ }
1963
+ async sendWindowInitializationRequest(windowId, payload, port) {
1964
+ const windowController = this.windowControllers.get(windowId);
1965
+ if (!windowController) {
1966
+ throw new Error("Window controller not found");
1967
+ }
1968
+ const windowInstance = windowController.windowInstance;
1969
+ if (!windowInstance) {
1970
+ throw new Error("Window instance not found");
1971
+ }
1972
+ const response = firstValueFrom(windowController.messages$.pipe(filter(event => event.data.type === AirWalletMessageTypes.INITIALIZATION_RESPONSE)));
1973
+ windowController.postMessage({
1974
+ type: AirWalletMessageTypes.INITIALIZATION_REQUEST,
1975
+ payload
1976
+ }, [port]);
1977
+ return (await response).data;
1978
+ }
1979
+ async openAndInitializeWalletServiceWindow({
1980
+ url,
1981
+ windowId,
1982
+ partnerId,
1983
+ enableLogging,
1984
+ onRetry,
1985
+ sdkVersion
1986
+ }) {
1987
+ if (this.windowControllers.has(windowId)) {
1988
+ throw new Error("Window controller already exists");
1989
+ }
1990
+ const windowController = new WindowController(windowId, url);
1991
+ const {
1992
+ pendingWindowOpenCheck
1993
+ } = await windowController.openWindow(onRetry);
1994
+ windowController.onClose(() => {
1995
+ this.removeWindowController(windowId);
1996
+ });
1997
+ this.windowControllers.set(windowId, windowController);
1998
+ let channel = null;
1999
+ const initializeWindow = () => {
2000
+ return new Promise((resolve, reject) => {
2001
+ windowController.onMessage(async ev => {
2002
+ if (ev.data === AirWalletMessageTypes.SERVICE_STARTED) {
2003
+ try {
2004
+ channel = new MessageChannel();
2005
+ const {
2006
+ payload
2007
+ } = await this.sendWindowInitializationRequest(windowId, {
2008
+ partnerId,
2009
+ enableLogging,
2010
+ sdkVersion
2011
+ }, channel.port1);
2012
+ if (payload.success === false) {
2013
+ reject(new AirServiceError(payload.errorName, payload.errorMessage));
2014
+ } else {
2015
+ resolve();
2016
+ }
2017
+ } catch (e) {
2018
+ reject(e);
2019
+ }
2020
+ }
2021
+ });
2022
+ });
2023
+ };
2024
+ const initializeWindowPromise = initializeWindow();
2025
+ const result = await pendingWindowOpenCheck;
2026
+ if (result === "retry") {
2027
+ // we can ignore previous initialization attempt since a new window was opened
2028
+ await initializeWindow();
2029
+ } else {
2030
+ await initializeWindowPromise;
2031
+ }
2032
+ return {
2033
+ windowController,
2034
+ port: channel.port2
2035
+ };
2036
+ }
2037
+ getWindowController(windowId) {
2038
+ return this.windowControllers.get(windowId);
2039
+ }
2040
+ removeWindowController(windowId) {
2041
+ this.windowControllers.delete(windowId);
2042
+ }
2043
+ }
2044
+ var WindowService$1 = WindowService.instance;
2045
+ var _a$1, _AuthMessageService_instance;
2046
+ const ALLOWED_AUTH_MESSAGES = [AirAuthMessageTypes.INITIALIZATION_RESPONSE, AirAuthMessageTypes.LOGIN_RESPONSE, AirAuthMessageTypes.SETUP_WALLET_REQUEST, AirAuthMessageTypes.LOGOUT_RESPONSE, AirAuthMessageTypes.PARTNER_USER_INFO_RESPONSE, AirAuthMessageTypes.CROSS_PARTNER_TOKEN_RESPONSE, AirAuthMessageTypes.PARTNER_ACCESS_TOKEN_RESPONSE, AirAuthMessageTypes.IFRAME_VISIBILITY_REQUEST];
2047
+ class AuthMessageService extends MessageServiceBase {
2048
+ static create() {
2049
+ if (__classPrivateFieldGet$1(this, _a$1, "f", _AuthMessageService_instance)) throw new Error("AuthMessageService already created");
2050
+ __classPrivateFieldSet(this, _a$1, new _a$1("Embed Service: Auth Channel", ALLOWED_AUTH_MESSAGES), "f", _AuthMessageService_instance);
2051
+ return __classPrivateFieldGet$1(this, _a$1, "f", _AuthMessageService_instance);
2052
+ }
2053
+ async open(authIframe) {
2054
+ const origin = new URL(authIframe.src).origin;
2055
+ const window = authIframe.contentWindow;
2056
+ await super._open({
2057
+ window,
2058
+ origin
2059
+ });
2060
+ }
2061
+ async initWalletCommunication(port) {
2062
+ await this.sendMessage({
2063
+ type: AirAuthMessageTypes.INIT_WALLET_COMMUNICATION
2064
+ }, [port]);
2065
+ }
2066
+ async sendPartnerUserInfoRequest() {
2067
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirAuthMessageTypes.PARTNER_USER_INFO_RESPONSE)));
2068
+ await this.sendMessage({
2069
+ type: AirAuthMessageTypes.PARTNER_USER_INFO_REQUEST,
2070
+ payload: {
2071
+ allowCache: false
2072
+ }
2073
+ });
2074
+ return response;
2075
+ }
2076
+ async sendLoginRequest(payload) {
2077
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirAuthMessageTypes.LOGIN_RESPONSE)));
2078
+ await this.sendMessage({
2079
+ type: AirAuthMessageTypes.LOGIN_REQUEST,
2080
+ payload
2081
+ });
2082
+ return response;
2083
+ }
2084
+ async logout() {
2085
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirAuthMessageTypes.LOGOUT_RESPONSE)));
2086
+ await this.sendMessage({
2087
+ type: AirAuthMessageTypes.LOGOUT_REQUEST
2088
+ });
2089
+ return response;
2090
+ }
2091
+ async resetWalletCommunication() {
2092
+ await this.sendMessage({
2093
+ type: AirAuthMessageTypes.RESET_WALLET_COMMUNICATION
2094
+ });
2095
+ }
2096
+ async sendInitializationRequest(payload) {
2097
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirAuthMessageTypes.INITIALIZATION_RESPONSE)));
2098
+ await this.sendMessage({
2099
+ type: AirAuthMessageTypes.INITIALIZATION_REQUEST,
2100
+ payload
2101
+ });
2102
+ return response;
2103
+ }
2104
+ async sendSetupWalletSuccessResponse() {
2105
+ await this.sendMessage({
2106
+ type: AirAuthMessageTypes.SETUP_WALLET_RESPONSE,
2107
+ payload: {
2108
+ success: true
2109
+ }
2110
+ });
2111
+ }
2112
+ async sendSetupWalletErrorResponse(error) {
2113
+ await this.sendMessage(this.createErrorResponseMessage(AirAuthMessageTypes.SETUP_WALLET_RESPONSE, error));
2114
+ }
2115
+ async sendCrossPartnerTokenRequest(targetPartnerUrl) {
2116
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirAuthMessageTypes.CROSS_PARTNER_TOKEN_RESPONSE)));
2117
+ await this.sendMessage({
2118
+ type: AirAuthMessageTypes.CROSS_PARTNER_TOKEN_REQUEST,
2119
+ payload: {
2120
+ targetPartnerUrl
2121
+ }
2122
+ });
2123
+ return response;
2124
+ }
2125
+ async sendPartnerAccessTokenRequest() {
2126
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirAuthMessageTypes.PARTNER_ACCESS_TOKEN_RESPONSE)));
2127
+ await this.sendMessage({
2128
+ type: AirAuthMessageTypes.PARTNER_ACCESS_TOKEN_REQUEST
2129
+ });
2130
+ return response;
2131
+ }
2132
+ }
2133
+ _a$1 = AuthMessageService;
2134
+ _AuthMessageService_instance = {
2135
+ value: undefined
2136
+ };
2137
+ var _a, _WalletMessageService_instance;
2138
+ const ALLOWED_WALLET_MESSAGES = [AirWalletMessageTypes.INITIALIZATION_RESPONSE, AirWalletMessageTypes.WALLET_INITIALIZED, AirWalletMessageTypes.WALLET_LOGIN_RESPONSE, AirWalletMessageTypes.SETUP_OR_UPDATE_MFA_RESPONSE, AirWalletMessageTypes.CLAIM_ID_RESPONSE, AirWalletMessageTypes.IS_SMART_ACCOUNT_DEPLOYED_RESPONSE, AirWalletMessageTypes.DEPLOY_SMART_ACCOUNT_RESPONSE, AirWalletMessageTypes.EXECUTE_ACTION_RESPONSE, AirWalletMessageTypes.REVOKE_PERMISSIONS_RESPONSE, AirWalletMessageTypes.GRANT_PERMISSIONS_RESPONSE, AirWalletMessageTypes.LIST_ALL_SESSION_KEY_SCOPES_RESPONSE, AirWalletMessageTypes.WALLET_INITIALIZED, AirWalletMessageTypes.WALLET_IFRAME_VISIBILITY_REQUEST, AirWalletMessageTypes.LOGOUT_RESPONSE, AirWalletMessageTypes.OPEN_WINDOW_REQUEST, AirWalletMessageTypes.OPEN_WINDOW_RETRY_RESPONSE];
2139
+ class WalletMessageService extends MessageServiceBase {
2140
+ static create() {
2141
+ if (__classPrivateFieldGet$1(this, _a, "f", _WalletMessageService_instance)) throw new Error("WalletMessageService already created");
2142
+ __classPrivateFieldSet(this, _a, new _a("Embed Service: Wallet Channel", ALLOWED_WALLET_MESSAGES), "f", _WalletMessageService_instance);
2143
+ return __classPrivateFieldGet$1(this, _a, "f", _WalletMessageService_instance);
2144
+ }
2145
+ async open(walletIframe) {
2146
+ const origin = new URL(walletIframe.src).origin;
2147
+ const window = walletIframe.contentWindow;
2148
+ await super._open({
2149
+ window,
2150
+ origin
2151
+ });
2152
+ }
2153
+ async initAuthCommunication(skipWalletLogin, port) {
2154
+ await this.sendMessage({
2155
+ type: AirWalletMessageTypes.INIT_AUTH_COMMUNICATION,
2156
+ payload: {
2157
+ skipWalletLogin
2158
+ }
2159
+ }, [port]);
2160
+ }
2161
+ async sendGrantPermissionRequest(policies) {
2162
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.GRANT_PERMISSIONS_RESPONSE)));
2163
+ await this.sendMessage({
2164
+ type: AirWalletMessageTypes.GRANT_PERMISSIONS_REQUEST,
2165
+ payload: {
2166
+ policies
2167
+ }
2168
+ });
2169
+ const result = await response;
2170
+ if (result.payload.success === false) {
2171
+ throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2172
+ }
2173
+ return result.payload.sessionData;
2174
+ }
2175
+ async sendExecuteActionRequest(params) {
2176
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.EXECUTE_ACTION_RESPONSE)));
2177
+ await this.sendMessage({
2178
+ type: AirWalletMessageTypes.EXECUTE_ACTION_REQUEST,
2179
+ payload: {
2180
+ sessionData: params.sessionData,
2181
+ call: {
2182
+ to: params.call.to,
2183
+ value: params.call.value,
2184
+ data: params.call.data
2185
+ },
2186
+ sessionOwnerPrivateKey: params.sessionOwnerPrivateKey
2187
+ }
2188
+ });
2189
+ const result = await response;
2190
+ if (result.payload.success === false) {
2191
+ throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2192
+ }
2193
+ return result.payload.txHash;
2194
+ }
2195
+ async sendRevokePermissionsRequest(permissionId) {
2196
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.REVOKE_PERMISSIONS_RESPONSE)));
2197
+ await this.sendMessage({
2198
+ type: AirWalletMessageTypes.REVOKE_PERMISSIONS_REQUEST,
2199
+ payload: {
2200
+ permissionId
2201
+ }
2202
+ });
2203
+ const result = await response;
2204
+ if (result.payload.success === false) {
2205
+ throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2206
+ }
2207
+ return result.payload.txHash;
2208
+ }
2209
+ async sendDeploySmartAccountRequest() {
2210
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.DEPLOY_SMART_ACCOUNT_RESPONSE)));
2211
+ await this.sendMessage({
2212
+ type: AirWalletMessageTypes.DEPLOY_SMART_ACCOUNT_REQUEST
2213
+ });
2214
+ return response;
2215
+ }
2216
+ async sendIsSmartAccountDeployedRequest() {
2217
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.IS_SMART_ACCOUNT_DEPLOYED_RESPONSE)));
2218
+ await this.sendMessage({
2219
+ type: AirWalletMessageTypes.IS_SMART_ACCOUNT_DEPLOYED_REQUEST
2220
+ });
2221
+ return response;
2222
+ }
2223
+ async logout() {
2224
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.LOGOUT_RESPONSE)));
2225
+ await this.sendMessage({
2226
+ type: AirWalletMessageTypes.LOGOUT_REQUEST
2227
+ });
2228
+ return response;
2229
+ }
2230
+ async sendInitializationRequest(payload) {
2231
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.INITIALIZATION_RESPONSE)));
2232
+ await this.sendMessage({
2233
+ type: AirWalletMessageTypes.INITIALIZATION_REQUEST,
2234
+ payload
2235
+ });
2236
+ return response;
2237
+ }
2238
+ async sendGrantPermissionsRequest(payload) {
2239
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.GRANT_PERMISSIONS_RESPONSE)));
2240
+ await this.sendMessage({
2241
+ type: AirWalletMessageTypes.GRANT_PERMISSIONS_REQUEST,
2242
+ payload
2243
+ });
2244
+ return response;
2245
+ }
2246
+ async sendListAllSessionKeyScopesRequest() {
2247
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.LIST_ALL_SESSION_KEY_SCOPES_RESPONSE)));
2248
+ await this.sendMessage({
2249
+ type: AirWalletMessageTypes.LIST_ALL_SESSION_KEY_SCOPES_REQUEST
2250
+ });
2251
+ return response;
2252
+ }
2253
+ onInitialized() {
2254
+ return firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.WALLET_INITIALIZED)));
2255
+ }
2256
+ async sendLoginRequest() {
2257
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.WALLET_LOGIN_RESPONSE)));
2258
+ await this.sendMessage({
2259
+ type: AirWalletMessageTypes.WALLET_LOGIN_REQUEST
2260
+ });
2261
+ return response;
2262
+ }
2263
+ async sendSetupMfaRequest() {
2264
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.SETUP_OR_UPDATE_MFA_RESPONSE)));
2265
+ await this.sendMessage({
2266
+ type: AirWalletMessageTypes.SETUP_OR_UPDATE_MFA_REQUEST
2267
+ });
2268
+ return response;
2269
+ }
2270
+ async sendOpenWindowSuccessResponse(windowId, port) {
2271
+ await this.sendMessage({
2272
+ type: AirWalletMessageTypes.OPEN_WINDOW_RESPONSE,
2273
+ payload: {
2274
+ success: true,
2275
+ windowId
2276
+ }
2277
+ }, [port]);
2278
+ }
2279
+ async sendOpenWindowErrorResponse(windowId, error) {
2280
+ const errorResponse = this.createErrorResponseMessage(AirWalletMessageTypes.OPEN_WINDOW_RESPONSE, error);
2281
+ await this.sendMessage({
2282
+ ...errorResponse,
2283
+ payload: {
2284
+ ...errorResponse.payload,
2285
+ windowId
2286
+ }
2287
+ });
2288
+ }
2289
+ async sendOpenWindowRetryRequest(windowId) {
2290
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.OPEN_WINDOW_RETRY_RESPONSE), filter(msg => msg.payload.windowId === windowId)));
2291
+ await this.sendMessage({
2292
+ type: AirWalletMessageTypes.OPEN_WINDOW_RETRY_REQUEST,
2293
+ payload: {
2294
+ windowId
2295
+ }
2296
+ });
2297
+ return response;
2298
+ }
2299
+ async sendWindowClosed(windowId) {
2300
+ await this.sendMessage({
2301
+ type: AirWalletMessageTypes.WINDOW_CLOSED,
2302
+ payload: {
2303
+ windowId
2304
+ }
2305
+ });
2306
+ }
2307
+ async sendClaimIdRequest(payload) {
2308
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirWalletMessageTypes.CLAIM_ID_RESPONSE)));
2309
+ await this.sendMessage({
2310
+ type: AirWalletMessageTypes.CLAIM_ID_REQUEST,
2311
+ payload
2312
+ });
2313
+ return response;
2314
+ }
2315
+ }
2316
+ _a = WalletMessageService;
2317
+ _WalletMessageService_instance = {
2318
+ value: undefined
2319
+ };
2320
+ const getLevelName = levelNum => {
2321
+ const levelNames = Object.keys(log$1.levels);
2322
+ if (levelNum >= 0 && levelNum < levelNames.length) {
2323
+ return levelNames[levelNum];
2324
+ }
2325
+ return "UNKNOWN";
2326
+ };
2327
+ const configureLogLevel = (environment, enableLogging) => {
2328
+ let level = log$1.levels.ERROR;
2329
+ if (environment === "development") {
2330
+ level = enableLogging ? log$1.levels.TRACE : log$1.levels.INFO;
2331
+ } else if (environment === "staging") {
2332
+ level = enableLogging ? log$1.levels.DEBUG : log$1.levels.INFO;
2333
+ } else if (environment === "uat") {
2334
+ level = enableLogging ? log$1.levels.INFO : log$1.levels.WARN;
2335
+ } else if (environment === "production") {
2336
+ // Be cautious with enabling more than WARN in prod
2337
+ level = enableLogging ? log$1.levels.WARN : log$1.levels.ERROR;
2338
+ }
2339
+ log$1.setLevel(level);
2340
+ log$1.info(`[${window?.location?.origin}] LogLevel: ${getLevelName(log$1.getLevel())}`);
2341
+ };
2342
+ var name = "@mocanetwork/airkit";
2343
+ var version$2 = "1.2.0";
2344
+ var description = "Air kit to interact with the Moca Network";
2345
+ var main = "dist/airkit.cjs.js";
2346
+ var module$1 = "dist/airkit.esm.js";
2347
+ var unpkg = "dist/airkit.umd.min.js";
2348
+ var jsdelivr = "dist/airkit.umd.min.js";
2349
+ var types = "dist/types/index.d.ts";
2350
+ var files = ["dist"];
2351
+ var scripts = {
2352
+ build: "rollup --config",
2353
+ prepack: "npm run build && npm run postbuild",
2354
+ lint: "eslint --fix 'src/**/*.ts'",
2355
+ format: "prettier --write 'src/**/*.ts'",
2356
+ postbuild: "node scripts/copyAndAdjustDtsFiles.js '../common/src' 'common'"
2357
+ };
2358
+ var dependencies = {
2359
+ "@mocanetwork/airkit-connector": "^1.2.0",
2360
+ "fast-deep-equal": "^3.1.3",
2361
+ loglevel: "^1.9.2",
2362
+ pump: "^3.0.0",
2363
+ "readable-stream": "^4.5.2",
2364
+ rxjs: "^7.8.1"
2365
+ };
2366
+ var devDependencies = {
2367
+ "@babel/runtime": "^7.25.6",
2368
+ "@rushstack/eslint-patch": "^1.10.2",
2369
+ "@types/pump": "^1.1.3",
2370
+ "@types/readable-stream": "^4.0.15",
2371
+ "fs-extra": "^11.2.0",
2372
+ glob: "^11.0.0",
2373
+ process: "^0.11.10",
2374
+ "typescript-eslint": "^8.21.0"
2375
+ };
2376
+ var mocha = {
2377
+ timeout: 0
2378
+ };
2379
+ var keywords = ["airkit", "mocaverse", "wallet", "embed", "login", "OAuth", "crypto"];
2380
+ var author = "Mocaverse";
2381
+ var license = "ISC";
2382
+ var engines = {
2383
+ node: ">=18.x",
2384
+ npm: ">=9.x"
2385
+ };
2386
+ var publishConfig = {
2387
+ access: "restricted"
2388
+ };
2389
+ var airkitPackage = {
2390
+ name: name,
2391
+ version: version$2,
2392
+ description: description,
2393
+ main: main,
2394
+ module: module$1,
2395
+ unpkg: unpkg,
2396
+ jsdelivr: jsdelivr,
2397
+ types: types,
2398
+ files: files,
2399
+ scripts: scripts,
2400
+ dependencies: dependencies,
2401
+ devDependencies: devDependencies,
2402
+ mocha: mocha,
2403
+ keywords: keywords,
2404
+ author: author,
2405
+ license: license,
2406
+ "lint-staged": {
2407
+ "!(*d).{js,ts}": ["eslint --cache --fix", "prettier --write"],
2408
+ "*.{json, md}": ["prettier --write"]
2409
+ },
2410
+ engines: engines,
2411
+ publishConfig: publishConfig
2412
+ };
2413
+ var _AirService_instances, _AirService_loginResult, _AirService_buildEnv, _AirService_enableLogging, _AirService_partnerId, _AirService_authMessagingService, _AirService_authIframeController, _AirService_isAuthInitialized, _AirService_airAuthListener, _AirService_walletMessagingService, _AirService_walletIframeController, _AirService_walletInitialization, _AirService_walletLoggedInResult, _AirService_airWalletProvider, _AirService_ensureWallet, _AirService_initializeWallet, _AirService_subscribeToWalletEvents, _AirService_triggerEventListeners, _AirService_triggerAirAuthInitialized, _AirService_triggerAirAuthLoggedIn, _AirService_triggerAirAuthLoggedOut, _AirService_triggerWalletInitialized, _AirService_createLoginResult, _AirService_createWalletInitializedResult, _AirService_cleanUpAuth, _AirService_cleanUpWallet;
2414
+ const airKitVersion = airkitPackage.version;
2415
+ class AirService {
2416
+ constructor({
2417
+ partnerId
2418
+ }) {
2419
+ _AirService_instances.add(this);
2420
+ _AirService_loginResult.set(this, undefined);
2421
+ _AirService_buildEnv.set(this, undefined);
2422
+ _AirService_enableLogging.set(this, false);
2423
+ _AirService_partnerId.set(this, undefined);
2424
+ //#modalZIndex: number; TODO implement z index overwrite
2425
+ _AirService_authMessagingService.set(this, undefined);
2426
+ _AirService_authIframeController.set(this, undefined);
2427
+ _AirService_isAuthInitialized.set(this, false);
2428
+ _AirService_airAuthListener.set(this, []);
2429
+ _AirService_walletMessagingService.set(this, undefined);
2430
+ _AirService_walletIframeController.set(this, undefined);
2431
+ _AirService_walletInitialization.set(this, undefined);
2432
+ _AirService_walletLoggedInResult.set(this, undefined);
2433
+ _AirService_airWalletProvider.set(this, undefined);
2434
+ __classPrivateFieldSet(this, _AirService_partnerId, partnerId);
2435
+ __classPrivateFieldSet(this, _AirService_authMessagingService, AuthMessageService.create());
2436
+ __classPrivateFieldSet(this, _AirService_walletMessagingService, WalletMessageService.create());
2437
+ __classPrivateFieldSet(this, _AirService_airWalletProvider, new AirWalletProvider({
2438
+ isLoggedIn: () => this.isLoggedIn,
2439
+ ensureWallet: __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_ensureWallet).bind(this)
2440
+ }));
2441
+ // this.#modalZIndex = modalZIndex ?? 99999;
2442
+ }
2443
+ get buildEnv() {
2444
+ return __classPrivateFieldGet$1(this, _AirService_buildEnv, "f");
2445
+ }
2446
+ get isInitialized() {
2447
+ return __classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f");
2448
+ }
2449
+ get isLoggedIn() {
2450
+ return !!__classPrivateFieldGet$1(this, _AirService_loginResult, "f");
2451
+ }
2452
+ get isWalletInitialized() {
2453
+ return !!__classPrivateFieldGet$1(this, _AirService_walletLoggedInResult, "f");
2454
+ }
2455
+ get provider() {
2456
+ const provider = __classPrivateFieldGet$1(this, _AirService_airWalletProvider, "f");
2457
+ return {
2458
+ request: provider.request.bind(provider),
2459
+ on: provider.on.bind(provider),
2460
+ removeListener: provider.removeListener.bind(provider)
2461
+ };
2462
+ }
2463
+ async init({
2464
+ buildEnv = BUILD_ENV.PRODUCTION,
2465
+ enableLogging = false,
2466
+ skipRehydration = false
2467
+ }) {
2468
+ if (!__classPrivateFieldGet$1(this, _AirService_partnerId, "f")) throw new Error("Partner ID is required to initialize auth service");
2469
+ if (__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) return;
2470
+ __classPrivateFieldSet(this, _AirService_buildEnv, buildEnv);
2471
+ __classPrivateFieldSet(this, _AirService_enableLogging, enableLogging);
2472
+ const {
2473
+ authUrl
2474
+ } = AIR_URLS[buildEnv];
2475
+ configureLogLevel(buildEnv, enableLogging);
2476
+ const authIframeOrigin = new URL(authUrl).origin;
2477
+ __classPrivateFieldSet(this, _AirService_authIframeController, new IframeController(authUrl, `air-auth-${randomId()}`));
2478
+ try {
2479
+ __classPrivateFieldGet$1(this, _AirService_authIframeController, "f").createIframe();
2480
+ await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").open(__classPrivateFieldGet$1(this, _AirService_authIframeController, "f").iframeElement);
2481
+ __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").messages$.subscribe(async msg => {
2482
+ switch (msg.type) {
2483
+ case AirAuthMessageTypes.IFRAME_VISIBILITY_REQUEST:
2484
+ {
2485
+ const authIframeController = __classPrivateFieldGet$1(this, _AirService_authIframeController, "f");
2486
+ authIframeController.setIframeVisibility(msg.payload.visible);
2487
+ authIframeController.updateIframeState();
2488
+ break;
2489
+ }
2490
+ case AirAuthMessageTypes.SETUP_WALLET_REQUEST:
2491
+ {
2492
+ try {
2493
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_ensureWallet).call(this, {
2494
+ skipWalletLogin: true
2495
+ });
2496
+ await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").sendSetupWalletSuccessResponse();
2497
+ } catch (err) {
2498
+ const error = ensureError(err);
2499
+ await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").sendSetupWalletErrorResponse(error);
2500
+ }
2501
+ break;
2502
+ }
2503
+ }
2504
+ });
2505
+ const result = await new Promise((resolve, reject) => {
2506
+ const handleAuthMessage = async ev => {
2507
+ if (ev.origin !== authIframeOrigin) return;
2508
+ if (ev.data === AirAuthMessageTypes.AUTH_SETUP_COMPLETED) {
2509
+ window.removeEventListener("message", handleAuthMessage);
2510
+ const {
2511
+ payload
2512
+ } = await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").sendInitializationRequest({
2513
+ partnerId: __classPrivateFieldGet$1(this, _AirService_partnerId, "f"),
2514
+ skipRehydration,
2515
+ partnerDAppUrl: window.location.href,
2516
+ sdkVersion: airKitVersion,
2517
+ enableLogging: __classPrivateFieldGet$1(this, _AirService_enableLogging, "f")
2518
+ });
2519
+ if (payload.success === true) {
2520
+ resolve(payload);
2521
+ } else {
2522
+ reject(new AirServiceError(payload.errorName, payload.errorMessage));
2523
+ }
2524
+ }
2525
+ };
2526
+ window.addEventListener("message", handleAuthMessage);
2527
+ });
2528
+ __classPrivateFieldSet(this, _AirService_isAuthInitialized, true, "f");
2529
+ __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_triggerAirAuthInitialized).call(this, {
2530
+ rehydrated: result.rehydrated
2531
+ });
2532
+ // rehydrated auth session
2533
+ if (result.rehydrated) {
2534
+ __classPrivateFieldSet(this, _AirService_loginResult, __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_createLoginResult).call(this, result), "f");
2535
+ __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_triggerAirAuthLoggedIn).call(this);
2536
+ return __classPrivateFieldGet$1(this, _AirService_loginResult, "f");
2537
+ }
2538
+ } catch (error) {
2539
+ log$1.debug("Error initializing auth service", error);
2540
+ await this.cleanUp();
2541
+ throw error;
2542
+ }
2543
+ return null;
2544
+ }
2545
+ async login(options) {
2546
+ if (!__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) throw new Error("Service is not initialized");
2547
+ if (__classPrivateFieldGet$1(this, _AirService_loginResult, "f")) return __classPrivateFieldGet$1(this, _AirService_loginResult, "f");
2548
+ const {
2549
+ payload
2550
+ } = await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").sendLoginRequest({
2551
+ partnerLoginToken: options?.authToken
2552
+ });
2553
+ if (payload.success === true) {
2554
+ __classPrivateFieldSet(this, _AirService_loginResult, __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_createLoginResult).call(this, payload));
2555
+ __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_triggerAirAuthLoggedIn).call(this);
2556
+ return __classPrivateFieldGet$1(this, _AirService_loginResult, "f");
2557
+ }
2558
+ throw new AirServiceError(payload.errorName, payload.errorMessage);
2559
+ }
2560
+ /**
2561
+ * @experimental This method is experimental and will change in the future.
2562
+ */
2563
+ async deploySmartAccount() {
2564
+ if (!__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) throw new Error("Service is not initialized");
2565
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2566
+ try {
2567
+ log$1.info("deploySmartAccount");
2568
+ const {
2569
+ payload
2570
+ } = await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendDeploySmartAccountRequest();
2571
+ if (payload.success === false) {
2572
+ throw new AirServiceError(payload.errorName, payload.errorMessage);
2573
+ }
2574
+ return {
2575
+ txHash: payload.txHash
2576
+ };
2577
+ } catch (error) {
2578
+ throw AirServiceError.from(error);
2579
+ }
2580
+ }
2581
+ /**
2582
+ * @experimental This method is experimental and will change in the future.
2583
+ */
2584
+ async grantPermission(policies) {
2585
+ if (!__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) throw new Error("AirAuth is not initialized");
2586
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2587
+ try {
2588
+ log$1.info("grantPermission", policies);
2589
+ const {
2590
+ payload
2591
+ } = await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendGrantPermissionsRequest({
2592
+ policies
2593
+ });
2594
+ if (payload.success === false) {
2595
+ throw new AirServiceError(payload.errorName, payload.errorMessage);
2596
+ }
2597
+ return payload.sessionData;
2598
+ } catch (error) {
2599
+ throw AirServiceError.from(error);
2600
+ }
2601
+ }
2602
+ /**
2603
+ * @experimental This method is experimental and will change in the future.
2604
+ */
2605
+ async listAllSessionKeyScopes() {
2606
+ if (!__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) throw new Error("Service is not initialized");
2607
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2608
+ try {
2609
+ const {
2610
+ payload
2611
+ } = await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendListAllSessionKeyScopesRequest();
2612
+ if (payload.success === false) {
2613
+ throw new AirServiceError(payload.errorName, payload.errorMessage);
2614
+ }
2615
+ return payload.sessionKeyScopes;
2616
+ } catch (error) {
2617
+ throw AirServiceError.from(error);
2618
+ }
2619
+ }
2620
+ /**
2621
+ * @experimental This method is experimental and will change in the future.
2622
+ */
2623
+ async executeAction(params) {
2624
+ if (!__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) throw new Error("Service is not initialized");
2625
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2626
+ try {
2627
+ log$1.info("executeAction", params);
2628
+ const txHash = await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendExecuteActionRequest(params);
2629
+ return txHash;
2630
+ } catch (error) {
2631
+ throw AirServiceError.from(error);
2632
+ }
2633
+ }
2634
+ /**
2635
+ * @experimental This method is experimental and will change in the future.
2636
+ */
2637
+ async revokePermission(permissionId) {
2638
+ if (!__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) throw new Error("Service is not initialized");
2639
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2640
+ try {
2641
+ log$1.info("revokePermission", permissionId);
2642
+ const txHash = await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendRevokePermissionsRequest(permissionId);
2643
+ return txHash;
2644
+ } catch (error) {
2645
+ throw AirServiceError.from(error);
2646
+ }
2647
+ }
2648
+ /**
2649
+ * @experimental This method is experimental and will change in the future.
2650
+ */
2651
+ async isSmartAccountDeployed() {
2652
+ if (!__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) throw new Error("Service is not initialized");
2653
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2654
+ try {
2655
+ const {
2656
+ payload
2657
+ } = await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendIsSmartAccountDeployedRequest();
2658
+ if (payload.success === false) {
2659
+ throw new AirServiceError(payload.errorName, payload.errorMessage);
2660
+ }
2661
+ return payload.isDeployed;
2662
+ } catch (error) {
2663
+ throw AirServiceError.from(error);
2664
+ }
2665
+ }
2666
+ getProvider() {
2667
+ return this.provider;
2668
+ }
2669
+ async preloadWallet() {
2670
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_ensureWallet).call(this, {
2671
+ skipWalletLogin: true
2672
+ });
2673
+ }
2674
+ async setupOrUpdateMfa() {
2675
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_ensureWallet).call(this, {
2676
+ skipWalletLogin: true
2677
+ });
2678
+ const result = await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendSetupMfaRequest();
2679
+ if (result.payload.success === false) {
2680
+ throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2681
+ }
2682
+ __classPrivateFieldSet(this, _AirService_loginResult, {
2683
+ ...__classPrivateFieldGet$1(this, _AirService_loginResult, "f"),
2684
+ isMFASetup: true
2685
+ });
2686
+ }
2687
+ async claimAirId(options) {
2688
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2689
+ const result = await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendClaimIdRequest(options ?? {});
2690
+ if (result.payload.success === true) {
2691
+ return {
2692
+ airId: result.payload.airId
2693
+ };
2694
+ }
2695
+ throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2696
+ }
2697
+ async getUserInfo() {
2698
+ if (!this.isLoggedIn) throw new Error("User not logged in");
2699
+ const info = await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").sendPartnerUserInfoRequest();
2700
+ if (info.payload.success === false) {
2701
+ throw new AirServiceError(info.payload.errorName, info.payload.errorMessage);
2702
+ }
2703
+ return {
2704
+ partnerId: info.payload.partnerId,
2705
+ partnerUserId: info.payload.partnerUserId,
2706
+ airId: info.payload.airId,
2707
+ user: {
2708
+ id: info.payload.user.id,
2709
+ abstractAccountAddress: info.payload.user.abstractAccountAddress,
2710
+ email: info.payload.user.email,
2711
+ isMFASetup: info.payload.user.isMFASetup
2712
+ }
2713
+ };
2714
+ }
2715
+ async goToPartner(partnerUrl) {
2716
+ if (!__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) throw new Error("Service is not initialized");
2717
+ if (!this.isLoggedIn) throw new Error("No active session to generate token");
2718
+ const result = await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").sendCrossPartnerTokenRequest(partnerUrl);
2719
+ if (result.payload.success === false) {
2720
+ throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2721
+ }
2722
+ return {
2723
+ urlWithToken: result.payload.urlWithToken
2724
+ };
2725
+ }
2726
+ async getAccessToken() {
2727
+ if (!__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) throw new Error("Service is not initialized");
2728
+ if (!this.isLoggedIn) throw new Error("No active session to get partner access token");
2729
+ const result = await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").sendPartnerAccessTokenRequest();
2730
+ if (result.payload.success !== true) {
2731
+ throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2732
+ }
2733
+ if (!result.payload.partnerAccessToken) {
2734
+ throw new Error("Partner access token not found in response");
2735
+ }
2736
+ return {
2737
+ token: result.payload.partnerAccessToken
2738
+ };
2739
+ }
2740
+ async logout() {
2741
+ if (!__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) throw new Error("Service is not initialized");
2742
+ if (!this.isLoggedIn) throw new Error("No active session to logout");
2743
+ // Clear up wallet
2744
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_cleanUpWallet).call(this);
2745
+ await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").logout();
2746
+ __classPrivateFieldSet(this, _AirService_loginResult, undefined);
2747
+ __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_triggerAirAuthLoggedOut).call(this);
2748
+ }
2749
+ async cleanUp() {
2750
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_cleanUpWallet).call(this);
2751
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_cleanUpAuth).call(this);
2752
+ this.clearEventListeners();
2753
+ }
2754
+ on(listener) {
2755
+ if (__classPrivateFieldGet$1(this, _AirService_airAuthListener, "f").indexOf(listener) < 0) __classPrivateFieldGet$1(this, _AirService_airAuthListener, "f").push(listener);
2756
+ }
2757
+ off(listener) {
2758
+ if (__classPrivateFieldGet$1(this, _AirService_airAuthListener, "f").indexOf(listener) >= 0) __classPrivateFieldGet$1(this, _AirService_airAuthListener, "f").splice(__classPrivateFieldGet$1(this, _AirService_airAuthListener, "f").indexOf(listener), 1);
2759
+ }
2760
+ clearEventListeners() {
2761
+ __classPrivateFieldSet(this, _AirService_airAuthListener, []);
2762
+ }
2763
+ }
2764
+ _AirService_loginResult = new WeakMap(), _AirService_buildEnv = new WeakMap(), _AirService_enableLogging = new WeakMap(), _AirService_partnerId = new WeakMap(), _AirService_authMessagingService = new WeakMap(), _AirService_authIframeController = new WeakMap(), _AirService_isAuthInitialized = new WeakMap(), _AirService_airAuthListener = new WeakMap(), _AirService_walletMessagingService = new WeakMap(), _AirService_walletIframeController = new WeakMap(), _AirService_walletInitialization = new WeakMap(), _AirService_walletLoggedInResult = new WeakMap(), _AirService_airWalletProvider = new WeakMap(), _AirService_instances = new WeakSet(), _AirService_ensureWallet = async function _AirService_ensureWallet(option) {
2765
+ if (!this.isInitialized) throw new Error("Service not initialized");
2766
+ if (!this.isLoggedIn && !option?.skipWalletLogin) throw new Error("User not logged in");
2767
+ if (!__classPrivateFieldGet$1(this, _AirService_walletInitialization, "f")) __classPrivateFieldSet(this, _AirService_walletInitialization, __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_initializeWallet).call(this, option));
2768
+ if (__classPrivateFieldGet$1(this, _AirService_walletLoggedInResult, "f")) return __classPrivateFieldGet$1(this, _AirService_walletLoggedInResult, "f");
2769
+ try {
2770
+ const result = await __classPrivateFieldGet$1(this, _AirService_walletInitialization, "f");
2771
+ if (option?.skipWalletLogin || result.isWalletLoggedIn) {
2772
+ return __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_createWalletInitializedResult).call(this, result);
2773
+ }
2774
+ } catch (error) {
2775
+ __classPrivateFieldSet(this, _AirService_walletInitialization, null);
2776
+ log$1.error("Error initializing wallet", error);
2777
+ throw error;
2778
+ }
2779
+ if (__classPrivateFieldGet$1(this, _AirService_walletLoggedInResult, "f")) return __classPrivateFieldGet$1(this, _AirService_walletLoggedInResult, "f");
2780
+ const walletLoginResult = await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendLoginRequest();
2781
+ if (walletLoginResult.payload.success !== true) {
2782
+ throw new AirServiceError(walletLoginResult.payload.errorName, walletLoginResult.payload.errorMessage);
2783
+ }
2784
+ return __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_createWalletInitializedResult).call(this, walletLoginResult.payload);
2785
+ }, _AirService_initializeWallet = async function _AirService_initializeWallet(option) {
2786
+ if (__classPrivateFieldGet$1(this, _AirService_walletInitialization, "f")) throw new Error("Already initializing");
2787
+ const {
2788
+ walletUrl
2789
+ } = AIR_URLS[__classPrivateFieldGet$1(this, _AirService_buildEnv, "f")];
2790
+ log$1.info(walletUrl, "url loaded");
2791
+ const walletIframeOrigin = new URL(walletUrl).origin;
2792
+ try {
2793
+ const walletInitRequestPromise = new Promise((resolve, reject) => {
2794
+ const handleWalletMessage = async ev => {
2795
+ if (ev.origin !== walletIframeOrigin) return;
2796
+ if (ev.data === AirWalletMessageTypes.SERVICE_STARTED) {
2797
+ window.removeEventListener("message", handleWalletMessage);
2798
+ const {
2799
+ payload
2800
+ } = await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendInitializationRequest({
2801
+ partnerId: __classPrivateFieldGet$1(this, _AirService_partnerId, "f"),
2802
+ enableLogging: __classPrivateFieldGet$1(this, _AirService_enableLogging, "f"),
2803
+ sdkVersion: airKitVersion
2804
+ });
2805
+ if (payload.success === true) {
2806
+ resolve();
2807
+ } else {
2808
+ reject(new AirServiceError(payload.errorName, payload.errorMessage));
2809
+ }
2810
+ }
2811
+ };
2812
+ window.addEventListener("message", handleWalletMessage);
2813
+ });
2814
+ __classPrivateFieldSet(this, _AirService_walletIframeController, new IframeController(walletUrl, `air-wallet-${randomId()}`), "f");
2815
+ __classPrivateFieldGet$1(this, _AirService_walletIframeController, "f").createIframe();
2816
+ await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").open(__classPrivateFieldGet$1(this, _AirService_walletIframeController, "f").iframeElement);
2817
+ __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_subscribeToWalletEvents).call(this);
2818
+ await __classPrivateFieldGet$1(this, _AirService_airWalletProvider, "f").startEventMessageListening(__classPrivateFieldGet$1(this, _AirService_walletIframeController, "f").iframeElement);
2819
+ const walletInitPromise = __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").onInitialized();
2820
+ await walletInitRequestPromise;
2821
+ const channel = new MessageChannel();
2822
+ await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").initWalletCommunication(channel.port1);
2823
+ await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").initAuthCommunication(option?.skipWalletLogin ?? false, channel.port2);
2824
+ const walletInitResult = await walletInitPromise;
2825
+ if (walletInitResult.payload.success !== true) {
2826
+ throw new AirServiceError(walletInitResult.payload.errorName, walletInitResult.payload.errorMessage);
2827
+ }
2828
+ if (!__classPrivateFieldGet$1(this, _AirService_walletLoggedInResult, "f") && walletInitResult.payload.isWalletLoggedIn) {
2829
+ __classPrivateFieldSet(this, _AirService_walletLoggedInResult, __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_createWalletInitializedResult).call(this, walletInitResult.payload), "f");
2830
+ __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_triggerWalletInitialized).call(this, __classPrivateFieldGet$1(this, _AirService_walletLoggedInResult, "f"));
2831
+ }
2832
+ return walletInitResult.payload;
2833
+ } catch (error) {
2834
+ log$1.error("Error initializing wallet", error);
2835
+ await __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_cleanUpWallet).call(this);
2836
+ throw error;
2837
+ }
2838
+ }, _AirService_subscribeToWalletEvents = function _AirService_subscribeToWalletEvents() {
2839
+ __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").messages$.subscribe(async msg => {
2840
+ switch (msg.type) {
2841
+ case AirWalletMessageTypes.WALLET_IFRAME_VISIBILITY_REQUEST:
2842
+ {
2843
+ const walletIframeController = __classPrivateFieldGet$1(this, _AirService_walletIframeController, "f");
2844
+ walletIframeController.setIframeVisibility(msg.payload.visible);
2845
+ walletIframeController.updateIframeState();
2846
+ break;
2847
+ }
2848
+ case AirWalletMessageTypes.WALLET_LOGIN_RESPONSE:
2849
+ {
2850
+ if (msg.payload.success === true && !__classPrivateFieldGet$1(this, _AirService_walletLoggedInResult, "f")) {
2851
+ __classPrivateFieldSet(this, _AirService_walletLoggedInResult, __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_createWalletInitializedResult).call(this, msg.payload));
2852
+ __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_triggerWalletInitialized).call(this, __classPrivateFieldGet$1(this, _AirService_walletLoggedInResult, "f"));
2853
+ }
2854
+ break;
2855
+ }
2856
+ case AirWalletMessageTypes.OPEN_WINDOW_REQUEST:
2857
+ {
2858
+ try {
2859
+ const onRetry = async () => {
2860
+ const {
2861
+ payload
2862
+ } = await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendOpenWindowRetryRequest(msg.payload.windowId);
2863
+ if (payload.success === false) {
2864
+ throw new AirServiceError(payload.errorName, payload.errorMessage);
2865
+ }
2866
+ };
2867
+ const {
2868
+ windowController,
2869
+ port
2870
+ } = await WindowService$1.openAndInitializeWalletServiceWindow({
2871
+ url: msg.payload.url,
2872
+ windowId: msg.payload.windowId,
2873
+ partnerId: __classPrivateFieldGet$1(this, _AirService_partnerId, "f"),
2874
+ enableLogging: __classPrivateFieldGet$1(this, _AirService_enableLogging, "f"),
2875
+ sdkVersion: airKitVersion,
2876
+ onRetry
2877
+ });
2878
+ windowController.onClose(async () => await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendWindowClosed(msg.payload.windowId));
2879
+ await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendOpenWindowSuccessResponse(msg.payload.windowId, port);
2880
+ } catch (err) {
2881
+ const error = ensureError(err);
2882
+ await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").sendOpenWindowErrorResponse(msg.payload.windowId, error);
2883
+ }
2884
+ break;
2885
+ }
2886
+ }
2887
+ });
2888
+ }, _AirService_triggerEventListeners = function _AirService_triggerEventListeners(data) {
2889
+ __classPrivateFieldGet$1(this, _AirService_airAuthListener, "f").forEach(listener => {
2890
+ listener(data);
2891
+ });
2892
+ }, _AirService_triggerAirAuthInitialized = function _AirService_triggerAirAuthInitialized(result) {
2893
+ __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_triggerEventListeners).call(this, {
2894
+ event: "initialized",
2895
+ result
2896
+ });
2897
+ }, _AirService_triggerAirAuthLoggedIn = function _AirService_triggerAirAuthLoggedIn() {
2898
+ __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_triggerEventListeners).call(this, {
2899
+ event: "logged_in",
2900
+ result: __classPrivateFieldGet$1(this, _AirService_loginResult, "f")
2901
+ });
2902
+ }, _AirService_triggerAirAuthLoggedOut = function _AirService_triggerAirAuthLoggedOut() {
2903
+ __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_triggerEventListeners).call(this, {
2904
+ event: "logged_out"
2905
+ });
2906
+ }, _AirService_triggerWalletInitialized = function _AirService_triggerWalletInitialized(result) {
2907
+ __classPrivateFieldGet$1(this, _AirService_instances, "m", _AirService_triggerEventListeners).call(this, {
2908
+ event: "wallet_initialized",
2909
+ result
2910
+ });
2911
+ }, _AirService_createLoginResult = function _AirService_createLoginResult(payload) {
2912
+ return {
2913
+ isLoggedIn: true,
2914
+ id: payload.id,
2915
+ abstractAccountAddress: payload.abstractAccountAddress,
2916
+ token: payload.partnerAccessToken,
2917
+ isMFASetup: payload.isMFASetup
2918
+ };
2919
+ }, _AirService_createWalletInitializedResult = function _AirService_createWalletInitializedResult(payload) {
2920
+ if ("isWalletLoggedIn" in payload && !payload.isWalletLoggedIn) {
2921
+ return {
2922
+ abstractAccountAddress: null,
2923
+ isMFASetup: __classPrivateFieldGet$1(this, _AirService_loginResult, "f")?.isMFASetup ?? false
2924
+ };
2925
+ }
2926
+ return {
2927
+ abstractAccountAddress: payload.addresses.aa,
2928
+ isMFASetup: payload.isMFASetup
2929
+ };
2930
+ }, _AirService_cleanUpAuth = async function _AirService_cleanUpAuth() {
2931
+ // Logout auth session
2932
+ await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").logout();
2933
+ // Destroy the auth iframe
2934
+ const authIframeElement = __classPrivateFieldGet$1(this, _AirService_authIframeController, "f")?.iframeElement;
2935
+ if (isElement(authIframeElement) && window.document.body.contains(authIframeElement)) {
2936
+ __classPrivateFieldGet$1(this, _AirService_authIframeController, "f").destroy();
2937
+ __classPrivateFieldSet(this, _AirService_authIframeController, undefined);
2938
+ }
2939
+ // Close the message service
2940
+ await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").close();
2941
+ __classPrivateFieldSet(this, _AirService_isAuthInitialized, false);
2942
+ }, _AirService_cleanUpWallet = async function _AirService_cleanUpWallet() {
2943
+ if (!__classPrivateFieldGet$1(this, _AirService_isAuthInitialized, "f")) return;
2944
+ // Logout wallet and destroy the wallet iframe
2945
+ const walletIframeElement = __classPrivateFieldGet$1(this, _AirService_walletIframeController, "f")?.iframeElement;
2946
+ if (isElement(walletIframeElement) && window.document.body.contains(walletIframeElement)) {
2947
+ await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").logout();
2948
+ __classPrivateFieldGet$1(this, _AirService_walletIframeController, "f").destroy();
2949
+ __classPrivateFieldSet(this, _AirService_walletIframeController, undefined);
2950
+ }
2951
+ const authIframeElement = __classPrivateFieldGet$1(this, _AirService_authIframeController, "f")?.iframeElement;
2952
+ if (isElement(authIframeElement) && window.document.body.contains(authIframeElement)) {
2953
+ await __classPrivateFieldGet$1(this, _AirService_authMessagingService, "f").resetWalletCommunication();
2954
+ }
2955
+ // Close the message service
2956
+ await __classPrivateFieldGet$1(this, _AirService_walletMessagingService, "f").close();
2957
+ __classPrivateFieldSet(this, _AirService_walletLoggedInResult, undefined);
2958
+ __classPrivateFieldSet(this, _AirService_walletInitialization, undefined);
2959
+ };
4
2960
 
5
2961
  const version$1 = '2.26.5';
6
2962
 
@@ -1405,7 +4361,7 @@ const DEFAULT_CHAIN = {
1405
4361
  };
1406
4362
  function airConnector(parameters) {
1407
4363
  let providerInitialPromise = null;
1408
- const service = new airkit.AirService({ partnerId: parameters.partnerId });
4364
+ const service = new AirService({ partnerId: parameters.partnerId });
1409
4365
  let loginResult = null;
1410
4366
  return createConnector((config) => ({
1411
4367
  id: MOCA_NETWORK_CONNECTOR_ID,
@@ -1418,13 +4374,13 @@ function airConnector(parameters) {
1418
4374
  async connect({ chainId } = {}) {
1419
4375
  try {
1420
4376
  config.emitter.emit("message", { type: "connecting" });
1421
- loginResult = await service.login({
1422
- authToken: parameters.loginOptions?.authToken,
1423
- });
1424
4377
  const provider = await this.getProvider();
1425
4378
  provider.on("accountsChanged", (payload) => this.onAccountsChanged(payload));
1426
4379
  provider.on("chainChanged", this.onChainChanged);
1427
4380
  provider.on("disconnect", this.onDisconnect.bind(this));
4381
+ loginResult = await service.login({
4382
+ authToken: parameters.loginOptions?.authToken,
4383
+ });
1428
4384
  let currentChainId = await this.getChainId();
1429
4385
  if (chainId && currentChainId !== chainId) {
1430
4386
  const chain = await this.switchChain({ chainId }).catch((error) => {