@blotoutio/providers-blotout-wallet-sdk 0.42.2 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,19 +1,150 @@
1
1
  var ProvidersBlotoutWalletSdk = (function () {
2
2
  'use strict';
3
3
 
4
+ /**
5
+ * Returns whether A contains the entirety of B (A superset of B)
6
+ *
7
+ * A ⊇ B
8
+ */
9
+ const isSuperset = (a, b) => {
10
+ for (const item of b) {
11
+ if (!a.has(item)) {
12
+ return false;
13
+ }
14
+ }
15
+ return true;
16
+ };
17
+ /**
18
+ * Returns whether A is entirely contained within B (A subset of B)
19
+ *
20
+ * A ⊆ B
21
+ */
22
+ const isSubset = (a, b) => {
23
+ for (const item of a) {
24
+ if (!b.has(item)) {
25
+ return false;
26
+ }
27
+ }
28
+ return true;
29
+ };
30
+ /**
31
+ * Returns true when the two ets contain the same set of elements
32
+ *
33
+ * A = B
34
+ */
35
+ const areEquivalent = (a, b) => a.size == b.size && isSuperset(a, b) && isSubset(a, b);
36
+
37
+ const expand = (str) => str.split(',').flatMap((entry) => {
38
+ if (!entry.includes('-')) {
39
+ return entry;
40
+ }
41
+ const result = [];
42
+ const [start, end] = entry.split('-').map(Number);
43
+ for (let i = start; i <= end; i++) {
44
+ result.push(i.toString());
45
+ }
46
+ return result;
47
+ });
48
+ /**
49
+ * Exported from https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes
50
+ *
51
+ * In Dev Tools, select the `tbody` element containing the area codes and run the following code,
52
+ * replacing the emdash character with a simple endash:
53
+ *
54
+ * ```ts
55
+ * [...$0.querySelectorAll('td:first-child')]
56
+ * .filter(cell => cell.firstChild.nodeName != 'A')
57
+ * .map(cell => cell.textContent.trim()).join(',')
58
+ * ```
59
+ */
60
+ new Set([
61
+ ...expand('200,211,221,222,230,232,233,235,237-238,241,243,244,245,247,255,257,258-259,261,265,266,271,273,274,275,277,278,280,282,283,285-287,288,290-299'),
62
+ ...expand('300,311,322,324,327,328,333,335,338,342,344,348-349,353,355,356,357-359,362,366,369,370-379,381,382,383-384,387,388,389,390-399'),
63
+ ...expand('400,411,420,421-422,426-427,428,429,433,439,444,446,449,451-454,455,456,457,459,460,461-462,465,466,467,471,476,477,481-483,485-486,487,488,489,490-499'),
64
+ ...expand('511,532,535,536,537,538,542-543,545-547,549-550,552-554,555,556,558,560,565,568,569,576,578,583,589,590-599'),
65
+ ...expand('611,621,624,625,627,632,633,634-635,637-638,642-643,644,648,652-654,655,663,665,666,668,673-676,677,679,685,686,687,688,690-699'),
66
+ ...expand('711,722,723,729,733,735-736,739,741,744,745-746,748,749-751,752,755,756,759,761,764,766,768,776,777,783,788,789,790-799'),
67
+ ...expand('811,821,822,823-824,827,834,836,841-842,846,851,852-853,871,874-875,879,880-887,889,890-899'),
68
+ ...expand('911,921,922,923,924,926,927,932,933,935,942,944,946,950,953,955,957-958,960-969,974,975,976,977,981-982,987,988,990-999'),
69
+ ]);
70
+
4
71
  const packageName = 'blotoutWallet';
72
+ const customAttributes = {
73
+ '--bw-primary': { type: 'color', defaultValue: '#f25c2b' },
74
+ '--bw-secondary': { type: 'color', defaultValue: '#172a41' },
75
+ '--bw-button': { type: 'color', defaultValue: '#da2e3a' },
76
+ '--bw-foreground': { type: 'color', defaultValue: 'white' },
77
+ '--bw-input-border': { type: 'color', defaultValue: '#dbe2eb' },
78
+ '--bw-input-foreground': { type: 'color', defaultValue: '#172a41' },
79
+ '--bw-input-background': { type: 'color', defaultValue: 'white' },
80
+ '--bw-backdrop': { type: 'color', defaultValue: '#00000077' },
81
+ '--bw-z-index': { type: 'number', defaultValue: '9999' },
82
+ };
5
83
 
84
+ const canLog = () => {
85
+ try {
86
+ return localStorage.getItem('edgeTagDebug') === '1';
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ };
92
+ const logger = {
93
+ log: (...args) => {
94
+ if (canLog()) {
95
+ console.log(...args);
96
+ }
97
+ },
98
+ error: (...args) => {
99
+ if (canLog()) {
100
+ console.error(...args);
101
+ }
102
+ },
103
+ info: (...args) => {
104
+ if (canLog()) {
105
+ console.info(...args);
106
+ }
107
+ },
108
+ trace: (...args) => {
109
+ if (canLog()) {
110
+ console.trace(...args);
111
+ }
112
+ },
113
+ table: (...args) => {
114
+ if (canLog()) {
115
+ console.table(...args);
116
+ }
117
+ },
118
+ dir: (...args) => {
119
+ if (canLog()) {
120
+ console.dir(...args);
121
+ }
122
+ },
123
+ };
124
+
125
+ // eslint-disable-next-line @nx/enforce-module-boundaries
6
126
  class APIError extends Error {
7
127
  constructor(...args) {
8
128
  super(...args);
9
129
  }
10
130
  }
131
+ const getItemKey = (item) => `${item.productId}-${item.variantId}`;
132
+ const postMessageKey = 'blotoutWallet';
11
133
  class WalletAPI {
12
- constructor({ baseUrl, userId }) {
134
+ constructor({ baseUrl, userId, enabled }) {
13
135
  this.listeners = new Set();
14
136
  this._cart = { cartId: null, items: [], email: false };
137
+ this.onWindowMessage = (event) => {
138
+ var _a;
139
+ if (((_a = event.data) === null || _a === void 0 ? void 0 : _a.name) == postMessageKey) {
140
+ this.cart = event.data.cart;
141
+ }
142
+ };
15
143
  this.baseUrl = baseUrl;
16
144
  this.userId = userId;
145
+ this.enabled = enabled;
146
+ logger.info(`[Blotout Wallet] User is ${enabled ? 'enabled' : 'disabled'}`);
147
+ window.addEventListener('message', this.onWindowMessage);
17
148
  }
18
149
  getHeaders(json = false) {
19
150
  const headers = new Headers({
@@ -28,6 +159,7 @@ var ProvidersBlotoutWalletSdk = (function () {
28
159
  return `${this.baseUrl}/providers/blotoutWallet${path}`;
29
160
  }
30
161
  notify() {
162
+ var _a;
31
163
  for (const listener of this.listeners) {
32
164
  try {
33
165
  listener(this.cart);
@@ -36,13 +168,44 @@ var ProvidersBlotoutWalletSdk = (function () {
36
168
  console.error(err);
37
169
  }
38
170
  }
171
+ (_a = window.top) === null || _a === void 0 ? void 0 : _a.postMessage({ name: postMessageKey, cart: this.cart }, '*');
39
172
  }
40
173
  get cart() {
41
174
  return this._cart;
42
175
  }
43
176
  set cart(value) {
44
- this._cart = value;
45
- this.notify();
177
+ if (this.isCartUpdated(value)) {
178
+ this._cart = value;
179
+ this.notify();
180
+ }
181
+ }
182
+ isCartUpdated(value) {
183
+ if (value.cartId != this.cart.cartId ||
184
+ value.email != this.cart.email ||
185
+ value.items.length != this.cart.items.length) {
186
+ return true;
187
+ }
188
+ const newItemsMap = new Map(value.items.map((item) => [item.itemId, item]));
189
+ const newItemsKeys = new Set(newItemsMap.keys());
190
+ const currenItemsMap = new Map(this.cart.items.map((item) => [item.itemId, item]));
191
+ const currentItemsKeys = new Set(currenItemsMap.keys());
192
+ if (!areEquivalent(newItemsKeys, currentItemsKeys)) {
193
+ return true;
194
+ }
195
+ for (const [key, newItem] of newItemsMap) {
196
+ const currentItem = currenItemsMap.get(key);
197
+ if (newItem.amount != currentItem.amount ||
198
+ newItem.value != currentItem.value ||
199
+ newItem.name != currentItem.name ||
200
+ newItem.productId != currentItem.productId ||
201
+ newItem.variantId != currentItem.variantId) {
202
+ return true;
203
+ }
204
+ }
205
+ return false;
206
+ }
207
+ get segmentEnabled() {
208
+ return this.enabled;
46
209
  }
47
210
  subscribe(listener) {
48
211
  this.listeners.add(listener);
@@ -75,6 +238,26 @@ var ProvidersBlotoutWalletSdk = (function () {
75
238
  return (this.cart = await response.json());
76
239
  });
77
240
  }
241
+ removeItems(items) {
242
+ const cartLookup = new Map(this._cart.items.map((item) => [getItemKey(item), item]));
243
+ const itemLookup = new Map(items.map((item) => [getItemKey(item), item]));
244
+ const updatedCartItems = [];
245
+ for (const [itemKey, walletItem] of cartLookup.entries()) {
246
+ const itemToRemove = itemLookup.get(itemKey);
247
+ if (itemToRemove) {
248
+ // if the removed amount is equal or greater, we simply don't push the
249
+ // wallet item into the updated cart contents
250
+ if (walletItem.amount > itemToRemove.amount) {
251
+ walletItem.amount -= itemToRemove.amount;
252
+ updatedCartItems.push(walletItem);
253
+ }
254
+ }
255
+ else {
256
+ updatedCartItems.push(walletItem);
257
+ }
258
+ }
259
+ return this.setItems(updatedCartItems);
260
+ }
78
261
  setItems(items) {
79
262
  return fetch(this.getUrl('/items'), {
80
263
  method: 'PUT',
@@ -88,7 +271,7 @@ var ProvidersBlotoutWalletSdk = (function () {
88
271
  });
89
272
  }
90
273
  updateItem(item) {
91
- fetch(this.getUrl(`/items/${item.itemId}`), {
274
+ return fetch(this.getUrl(`/items/${item.itemId}`), {
92
275
  method: 'PUT',
93
276
  headers: this.getHeaders(true),
94
277
  body: JSON.stringify({
@@ -105,7 +288,7 @@ var ProvidersBlotoutWalletSdk = (function () {
105
288
  });
106
289
  }
107
290
  removeItem(itemId) {
108
- fetch(this.getUrl(`/items/${itemId}`), {
291
+ return fetch(this.getUrl(`/items/${itemId}`), {
109
292
  method: 'DELETE',
110
293
  headers: this.getHeaders(),
111
294
  }).then(async (response) => {
@@ -115,19 +298,6 @@ var ProvidersBlotoutWalletSdk = (function () {
115
298
  return (this.cart = await response.json());
116
299
  });
117
300
  }
118
- purchase(orderId) {
119
- return fetch(this.getUrl('/cart/purchase'), {
120
- method: 'POST',
121
- body: JSON.stringify({ orderId }),
122
- headers: this.getHeaders(true),
123
- }).then((response) => {
124
- if (!response.ok) {
125
- throw new APIError(`Could not mark purchase`, { cause: response });
126
- }
127
- this.cart = { cartId: null, email: this.cart.email, items: [] };
128
- this.notify();
129
- });
130
- }
131
301
  saveEmail(email) {
132
302
  return fetch(this.getUrl('/cart/email'), {
133
303
  method: 'POST',
@@ -274,15 +444,42 @@ var ProvidersBlotoutWalletSdk = (function () {
274
444
 
275
445
  const cssVars = i$4 `
276
446
  :host {
277
- --primary: var(--bw-primary, #f25c2b);
278
- --secondary: var(--bw-secondary, #172a41);
279
- --button: var(--bw-primary, #da2e3a);
280
- --foreground: var(--bw-foreground, white);
281
- --input-border: var(--bw-input-border, #dbe2eb);
282
- --input-foreground: var(--wb-input-foreground, var(--secondary));
283
- --input-background: var(--wb-input-background, white);
284
- --backdrop: var(--wb-backdrop, #00000077);
285
- --z-index: var(--wb-z-index, 9999);
447
+ --primary: var(
448
+ --bw-primary,
449
+ ${r$5(customAttributes['--bw-primary'].defaultValue)}
450
+ );
451
+ --secondary: var(
452
+ --bw-secondary,
453
+ ${r$5(customAttributes['--bw-secondary'].defaultValue)}
454
+ );
455
+ --button: var(
456
+ --bw-button,
457
+ ${r$5(customAttributes['--bw-button'].defaultValue)}
458
+ );
459
+ --foreground: var(
460
+ --bw-foreground,
461
+ ${r$5(customAttributes['--bw-foreground'].defaultValue)}
462
+ );
463
+ --input-border: var(
464
+ --bw-input-border,
465
+ ${r$5(customAttributes['--bw-input-border'].defaultValue)}
466
+ );
467
+ --input-foreground: var(
468
+ --bw-input-foreground,
469
+ ${r$5(customAttributes['--bw-input-foreground'].defaultValue)}
470
+ );
471
+ --input-background: var(
472
+ --bw-input-background,
473
+ ${r$5(customAttributes['--bw-input-background'].defaultValue)}
474
+ );
475
+ --backdrop: var(
476
+ --bw-backdrop,
477
+ ${r$5(customAttributes['--bw-backdrop'].defaultValue)}
478
+ );
479
+ --z-index: var(
480
+ --bw-z-index,
481
+ ${r$5(customAttributes['--bw-z-index'].defaultValue)}
482
+ );
286
483
 
287
484
  --spring-easing: ${r$5(spring)};
288
485
 
@@ -421,22 +618,22 @@ var ProvidersBlotoutWalletSdk = (function () {
421
618
  'top-left',
422
619
  'top-right',
423
620
  ]);
424
- const getItemKey = (item) => `${item.productId}-${item.variantId}`;
425
621
  const wait = (timeout) => new Promise((res) => setTimeout(res, timeout));
426
622
  let BlotoutWallet = class BlotoutWallet extends s {
427
623
  constructor() {
428
624
  super(...arguments);
429
- this._buttonVisible = false;
430
- this._bannerVisible = false;
431
- this._hasItemsInWallet = false;
432
- this._hasEmail = false;
433
- this.onWalletUpdated = () => {
434
- const cart = this._walletApi.cart;
435
- this._hasItemsInWallet = cart.items.length > 0;
436
- if (this._hasItemsInWallet || !this._hasEmail) {
625
+ this.buttonVisible = false;
626
+ this.bannerVisible = false;
627
+ this.hasItemsInWallet = false;
628
+ this.hasEmail = false;
629
+ this.onWalletUpdated = (walletContent) => {
630
+ logger.log('[Blotout Wallet] Cart updated', walletContent);
631
+ this.hasItemsInWallet = walletContent.items.length > 0;
632
+ this.hasEmail = walletContent.email;
633
+ if (this.isSegmentEnabled && (this.hasItemsInWallet || !this.hasEmail)) {
437
634
  this.showButton();
438
635
  }
439
- else if (!this._hasItemsInWallet && this._hasEmail) {
636
+ else if (!this.hasItemsInWallet && this.hasEmail) {
440
637
  this.hideButton();
441
638
  }
442
639
  };
@@ -445,164 +642,152 @@ var ProvidersBlotoutWalletSdk = (function () {
445
642
  ev.preventDefault();
446
643
  ev.stopPropagation();
447
644
  const modalAnimation = this.hideModal();
448
- const email = (_a = this._email) === null || _a === void 0 ? void 0 : _a.value.trim();
645
+ const email = (_a = this.email) === null || _a === void 0 ? void 0 : _a.value.trim();
449
646
  if (email) {
450
- this._walletApi.saveEmail(email)
647
+ this.walletApi.saveEmail(email)
451
648
  .then(() => {
452
- this._email.value = '';
453
- this._hasEmail = true;
649
+ this.email.value = '';
650
+ this.hasEmail = true;
454
651
  this.dispatchEvent(new CustomEvent('blotout-wallet-email-saved', { bubbles: true }));
455
652
  })
456
- .catch((err) => console.error(err));
653
+ .catch((err) => logger.error(err));
457
654
  }
458
- if (this._hasItemsInWallet) {
459
- this._storeApi.clearCart()
460
- .then(() => this._storeApi.addItems(this._walletApi.cart.items))
461
- .then(() => this._walletApi.restore())
655
+ if (this.hasItemsInWallet) {
656
+ this.storeApi.addItems(this.walletApi.cart.items)
657
+ .then(() => this.walletApi.restore())
462
658
  .then(() => {
463
659
  this.dispatchEvent(new CustomEvent('blotout-wallet-restored', { bubbles: true }));
464
660
  return modalAnimation.then(() => this.showRestorationBanner());
465
661
  })
466
- .catch((err) => console.error(err));
662
+ .then(() => wait(1000))
663
+ .then(() => (window.location.href = `${window.Shopify.routes.root}cart`))
664
+ .catch((err) => logger.error(err));
467
665
  }
468
666
  };
469
667
  this.showRestorationBanner = async () => {
470
- this._bannerVisible = true;
668
+ if (this.bannerVisible) {
669
+ return;
670
+ }
671
+ this.bannerVisible = true;
471
672
  await new Promise(requestAnimationFrame);
472
- await springInFromBottom(this._banner, '120%');
473
- await wait(5000);
474
- await springOutToBottom(this._banner, '120%');
475
- this._bannerVisible = false;
673
+ await springInFromBottom(this.banner, '120%');
674
+ };
675
+ this.hideRestorationBanner = async () => {
676
+ if (!this.bannerVisible) {
677
+ return;
678
+ }
679
+ await springOutToBottom(this.banner, '120%');
680
+ this.bannerVisible = false;
476
681
  };
477
682
  }
478
- get _storeApi() {
683
+ get storeApi() {
479
684
  var _a;
480
685
  return (_a = window[registryKey]) === null || _a === void 0 ? void 0 : _a.storeAPI;
481
686
  }
482
- get _walletApi() {
687
+ get walletApi() {
483
688
  var _a;
484
689
  return (_a = window[registryKey]) === null || _a === void 0 ? void 0 : _a.walletAPI;
485
690
  }
691
+ get isSegmentEnabled() {
692
+ var _a;
693
+ return (_a = this.walletApi) === null || _a === void 0 ? void 0 : _a.segmentEnabled;
694
+ }
486
695
  get _position() {
487
696
  return validPositions.has(this.position) ? this.position : 'bottom-left';
488
697
  }
489
698
  connectedCallback() {
490
699
  var _a;
491
700
  super.connectedCallback();
492
- this._unsubscribe = (_a = this._walletApi) === null || _a === void 0 ? void 0 : _a.subscribe(this.onWalletUpdated);
493
- this.syncItems().then((hasItemsSaved) => {
701
+ this.unsubscribe = (_a = this.walletApi) === null || _a === void 0 ? void 0 : _a.subscribe(this.onWalletUpdated);
702
+ this.syncItems().then(() => {
494
703
  this.dispatchEvent(new CustomEvent('blotout-wallet-loaded', { bubbles: true }));
495
- this._hasItemsInWallet = hasItemsSaved;
496
- if (this._hasItemsInWallet) {
497
- this.showButton();
498
- }
499
704
  });
500
705
  }
501
706
  disconnectedCallback() {
502
707
  var _a;
503
708
  super.disconnectedCallback();
504
- (_a = this._unsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
505
- this._unsubscribe = undefined;
709
+ (_a = this.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
710
+ this.unsubscribe = undefined;
506
711
  }
507
712
  async syncItems() {
508
- if (!this._walletApi || !this._storeApi) {
509
- console.error('The required APIs are not available');
713
+ if (!this.walletApi) {
714
+ logger.error('The required APIs are not available');
510
715
  return false;
511
716
  }
512
- const [savedCart, shopItems] = await Promise.all([
513
- this._walletApi.getCart(),
514
- this._storeApi.getCart(),
515
- ]);
516
- this._hasEmail = savedCart.email;
517
- const savedItemsLookup = new Map(savedCart.items.map((item) => [getItemKey(item), item]));
518
- const missingItems = [];
519
- for (const item of shopItems) {
520
- const walletItem = savedItemsLookup.get(getItemKey(item));
521
- if (!walletItem) {
522
- missingItems.push(item);
523
- }
524
- else if (walletItem.amount < item.amount) {
525
- missingItems.push({
526
- ...item,
527
- amount: item.amount - walletItem.amount,
528
- });
529
- }
530
- }
531
- if (missingItems.length > 0) {
532
- await this._walletApi.addItems(missingItems);
533
- }
717
+ const savedCart = await this.walletApi.getCart();
718
+ this.hasEmail = savedCart.email;
534
719
  return savedCart.items.length > 0;
535
720
  }
536
721
  async showButton() {
537
- if (this._buttonVisible) {
722
+ if (this.buttonVisible) {
538
723
  return;
539
724
  }
540
- this._buttonVisible = true;
725
+ this.buttonVisible = true;
541
726
  await new Promise(requestAnimationFrame).then(() => {
542
- switch (this._position) {
727
+ switch (this.position) {
543
728
  case 'top-left':
544
729
  case 'left':
545
730
  case 'bottom-left': {
546
- return springInFromLeft(this._button);
731
+ return springInFromLeft(this.button);
547
732
  }
548
733
  case 'top-right':
549
734
  case 'right':
550
735
  case 'bottom-right': {
551
- return springInFromRight(this._button);
736
+ return springInFromRight(this.button);
552
737
  }
553
738
  case 'bottom': {
554
- return springInFromBottom(this._button);
739
+ return springInFromBottom(this.button);
555
740
  }
556
741
  case 'top': {
557
- return springInFromTop(this._button);
742
+ return springInFromTop(this.button);
558
743
  }
559
744
  default: {
560
- return springInFromLeft(this._button);
745
+ return springInFromLeft(this.button);
561
746
  }
562
747
  }
563
748
  });
564
749
  this.dispatchEvent(new CustomEvent('blotout-wallet-shown', { bubbles: true }));
565
750
  }
566
751
  async hideButton() {
567
- if (!this._buttonVisible) {
752
+ if (!this.buttonVisible) {
568
753
  return;
569
754
  }
570
- switch (this._position) {
755
+ switch (this.position) {
571
756
  case 'top-left':
572
757
  case 'left':
573
758
  case 'bottom-left': {
574
- await springOutToLeft(this._button);
759
+ await springOutToLeft(this.button);
575
760
  break;
576
761
  }
577
762
  case 'top-right':
578
763
  case 'right':
579
764
  case 'bottom-right': {
580
- await springOutToRight(this._button);
765
+ await springOutToRight(this.button);
581
766
  break;
582
767
  }
583
768
  case 'bottom': {
584
- await springOutToBottom(this._button);
769
+ await springOutToBottom(this.button);
585
770
  break;
586
771
  }
587
772
  case 'top': {
588
- await springOutToTop(this._button);
773
+ await springOutToTop(this.button);
589
774
  break;
590
775
  }
591
776
  default: {
592
- await springOutToLeft(this._button);
777
+ await springOutToLeft(this.button);
593
778
  }
594
779
  }
595
- this._buttonVisible = false;
780
+ this.buttonVisible = false;
596
781
  this.dispatchEvent(new CustomEvent('blotout-wallet-hidden', { bubbles: true }));
597
782
  }
598
783
  async showModal() {
599
- this._dialog.showModal();
784
+ this.dialog.showModal();
600
785
  await new Promise(requestAnimationFrame);
601
- await fadeInDialog(this._dialog);
786
+ await fadeInDialog(this.dialog);
602
787
  }
603
788
  async hideModal() {
604
- await fadeOutToBottom(this._dialog);
605
- this._dialog.close();
789
+ await fadeOutToBottom(this.dialog);
790
+ this.dialog.close();
606
791
  }
607
792
  render() {
608
793
  return x `
@@ -610,7 +795,7 @@ var ProvidersBlotoutWalletSdk = (function () {
610
795
  class="${e({
611
796
  cta: true,
612
797
  [this._position]: true,
613
- hidden: !this._buttonVisible,
798
+ hidden: !this.buttonVisible,
614
799
  })}"
615
800
  @click=${this.showModal}
616
801
  >
@@ -621,7 +806,7 @@ var ProvidersBlotoutWalletSdk = (function () {
621
806
  <button class="dismiss" @click=${this.hideModal}>${cross()}</button>
622
807
  ${blotout({ class: 'logo' })}
623
808
  <form method="dialog" @submit=${this.onSubmit}>
624
- ${this._hasItemsInWallet
809
+ ${this.hasItemsInWallet
625
810
  ? x `<p>
626
811
  Hey! Your <strong>cart has expired!</strong><br />But we've got
627
812
  you covered. ${wink({ style: 'vertical-align:middle' })}
@@ -636,15 +821,15 @@ var ProvidersBlotoutWalletSdk = (function () {
636
821
  type="email"
637
822
  name="email"
638
823
  placeholder="Enter your email ID"
639
- ?required=${!this._hasEmail}
824
+ ?required=${!this.hasEmail}
640
825
  style=${o({
641
- display: this._hasEmail ? 'none' : 'block',
826
+ display: this.hasEmail ? 'none' : 'block',
642
827
  })}
643
828
  />
644
829
  </p>
645
830
  <p>
646
831
  <button class="restore" type="submit">
647
- ${this._hasItemsInWallet ? 'Restore Cart' : 'Save Cart'}
832
+ ${this.hasItemsInWallet ? 'Restore Cart' : 'Save Cart'}
648
833
  </button>
649
834
  </p>
650
835
  </form>
@@ -652,7 +837,7 @@ var ProvidersBlotoutWalletSdk = (function () {
652
837
 
653
838
  <div
654
839
  class="banner"
655
- style=${o({ display: this._bannerVisible ? '' : 'none' })}
840
+ style=${o({ display: this.bannerVisible ? '' : 'none' })}
656
841
  >
657
842
  ${blotout({
658
843
  class: 'logo',
@@ -755,7 +940,6 @@ var ProvidersBlotoutWalletSdk = (function () {
755
940
  }
756
941
 
757
942
  dialog {
758
- position: relative;
759
943
  width: 430px;
760
944
  max-width: 100vw;
761
945
  background: var(--secondary);
@@ -839,97 +1023,92 @@ var ProvidersBlotoutWalletSdk = (function () {
839
1023
  __decorate([
840
1024
  e$2('dialog'),
841
1025
  __metadata("design:type", HTMLDialogElement)
842
- ], BlotoutWallet.prototype, "_dialog", void 0);
1026
+ ], BlotoutWallet.prototype, "dialog", void 0);
843
1027
  __decorate([
844
1028
  e$2('button.cta'),
845
1029
  __metadata("design:type", HTMLButtonElement)
846
- ], BlotoutWallet.prototype, "_button", void 0);
1030
+ ], BlotoutWallet.prototype, "button", void 0);
847
1031
  __decorate([
848
1032
  e$2('input[name=email]'),
849
1033
  __metadata("design:type", HTMLInputElement)
850
- ], BlotoutWallet.prototype, "_email", void 0);
1034
+ ], BlotoutWallet.prototype, "email", void 0);
851
1035
  __decorate([
852
1036
  e$2('.banner'),
853
1037
  __metadata("design:type", HTMLDivElement)
854
- ], BlotoutWallet.prototype, "_banner", void 0);
1038
+ ], BlotoutWallet.prototype, "banner", void 0);
855
1039
  __decorate([
856
1040
  r(),
857
1041
  __metadata("design:type", Boolean)
858
- ], BlotoutWallet.prototype, "_buttonVisible", void 0);
1042
+ ], BlotoutWallet.prototype, "buttonVisible", void 0);
859
1043
  __decorate([
860
1044
  r(),
861
1045
  __metadata("design:type", Boolean)
862
- ], BlotoutWallet.prototype, "_bannerVisible", void 0);
1046
+ ], BlotoutWallet.prototype, "bannerVisible", void 0);
863
1047
  __decorate([
864
1048
  r(),
865
1049
  __metadata("design:type", Boolean)
866
- ], BlotoutWallet.prototype, "_hasItemsInWallet", void 0);
1050
+ ], BlotoutWallet.prototype, "hasItemsInWallet", void 0);
867
1051
  __decorate([
868
1052
  r(),
869
1053
  __metadata("design:type", Boolean)
870
- ], BlotoutWallet.prototype, "_hasEmail", void 0);
1054
+ ], BlotoutWallet.prototype, "hasEmail", void 0);
871
1055
  BlotoutWallet = __decorate([
872
1056
  t$1('blotout-wallet')
873
1057
  ], BlotoutWallet);
874
1058
 
875
1059
  const init = (params) => {
876
- var _a, _b;
877
- if (window && document && !window[registryKey].wallet) {
878
- window[registryKey].walletAPI = new WalletAPI({
1060
+ var _a, _b, _c;
1061
+ if (
1062
+ // if loaded in non-browser SDKs
1063
+ !window ||
1064
+ !document) {
1065
+ return;
1066
+ }
1067
+ let walletAPI = window[registryKey].walletAPI;
1068
+ if (!window[registryKey].walletAPI) {
1069
+ walletAPI = window[registryKey].walletAPI = new WalletAPI({
879
1070
  baseUrl: params.baseUrl,
880
1071
  userId: params.userId,
1072
+ enabled: !!((_a = params.manifest.variables) === null || _a === void 0 ? void 0 : _a['enabled']),
881
1073
  });
882
- const store = (window[registryKey].storeAPI =
883
- (_b = (_a = window[registryKey]).storeAPIFactory) === null || _b === void 0 ? void 0 : _b.call(_a));
1074
+ }
1075
+ let store = window[registryKey].storeAPI;
1076
+ if (!store) {
1077
+ store = window[registryKey].storeAPI =
1078
+ (_c = (_b = window[registryKey]).storeAPIFactory) === null || _c === void 0 ? void 0 : _c.call(_b);
884
1079
  if (!store) {
885
1080
  throw new Error('Implementation for store API missing!');
886
1081
  }
1082
+ }
1083
+ const initComponent = () => {
1084
+ var _a, _b;
887
1085
  const element = (window[registryKey].wallet =
888
1086
  document.createElement('blotout-wallet'));
889
- element.setAttribute('tag-name', params.manifest.tagName);
890
- document.body.append(element);
891
- }
892
- };
893
-
894
- const canLog = () => {
895
- try {
896
- return localStorage.getItem('edgeTagDebug') === '1';
897
- }
898
- catch {
899
- return false;
900
- }
901
- };
902
- const logger = {
903
- log: (...args) => {
904
- if (canLog()) {
905
- console.log(...args);
906
- }
907
- },
908
- error: (...args) => {
909
- if (canLog()) {
910
- console.error(...args);
911
- }
912
- },
913
- info: (...args) => {
914
- if (canLog()) {
915
- console.info(...args);
1087
+ const theme = (_a = params.manifest.variables) === null || _a === void 0 ? void 0 : _a['theme'];
1088
+ if (theme) {
1089
+ element.style.cssText = Object.entries(theme)
1090
+ .map(([name, value]) => `${name}:${value}`)
1091
+ .join(';');
916
1092
  }
917
- },
918
- trace: (...args) => {
919
- if (canLog()) {
920
- console.trace(...args);
1093
+ const position = (_b = params.manifest.variables) === null || _b === void 0 ? void 0 : _b['position'];
1094
+ if (position) {
1095
+ element.setAttribute('position', position);
921
1096
  }
922
- },
923
- table: (...args) => {
924
- if (canLog()) {
925
- console.table(...args);
1097
+ document.body.append(element);
1098
+ };
1099
+ if (window.top === window && !window[registryKey].wallet) {
1100
+ if (params.isNewUser) {
1101
+ // sync items from cart to wallet if a new user is detected
1102
+ store
1103
+ .getCart()
1104
+ .then((cartContent) => walletAPI.addItems(cartContent).catch(logger.error))
1105
+ .then(() => initComponent())
1106
+ .catch((err) => logger.error(err));
926
1107
  }
927
- },
928
- dir: (...args) => {
929
- if (canLog()) {
930
- console.dir(...args);
1108
+ else {
1109
+ initComponent();
931
1110
  }
932
- },
1111
+ }
933
1112
  };
934
1113
 
935
1114
  const transformItems = (data) => {
@@ -943,44 +1122,35 @@ var ProvidersBlotoutWalletSdk = (function () {
943
1122
  }));
944
1123
  };
945
1124
  const tag = (params) => {
946
- const wallet = window[registryKey].walletAPI;
947
- if (!wallet) {
1125
+ var _a;
1126
+ if (!((_a = window === null || window === void 0 ? void 0 : window[registryKey]) === null || _a === void 0 ? void 0 : _a.walletAPI)) {
1127
+ logger.error(`[Blotout Wallet] No wallet API available`);
948
1128
  return;
949
1129
  }
1130
+ const wallet = window[registryKey].walletAPI;
950
1131
  switch (params.eventName) {
951
1132
  case 'AddToCart': {
952
1133
  const items = transformItems(params.data);
953
- if (items) {
1134
+ if (items === null || items === void 0 ? void 0 : items.length) {
954
1135
  wallet.addItems(items).catch(logger.error);
955
1136
  }
956
1137
  return;
957
1138
  }
958
- case 'InitiateCheckout': {
1139
+ case 'RemoveFromCart': {
959
1140
  const items = transformItems(params.data);
960
- if (items) {
961
- wallet.setItems(items).catch(logger.error);
1141
+ if (items === null || items === void 0 ? void 0 : items.length) {
1142
+ wallet.removeItems(items).catch(logger.error);
962
1143
  }
963
1144
  return;
964
1145
  }
965
- case 'Purchase': {
966
- const { orderId } = params.data;
967
- wallet.purchase(orderId).catch(logger.error);
968
- return;
969
- }
970
1146
  }
971
1147
  };
972
1148
 
973
- // eslint-disable-next-line @nx/enforce-module-boundaries
974
- const user = (params) => {
975
- console.log(`[${packageName}]: user`, params);
976
- };
977
-
978
1149
  // eslint-disable-next-line @nx/enforce-module-boundaries
979
1150
  const data = {
980
1151
  name: packageName,
981
1152
  init,
982
1153
  tag,
983
- user,
984
1154
  };
985
1155
  try {
986
1156
  if (window) {