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