@metamask/profile-sync-controller 0.2.0 → 0.3.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.
Files changed (172) hide show
  1. package/CHANGELOG.md +46 -1
  2. package/auth/mocks/package.json +9 -0
  3. package/auth/package.json +9 -0
  4. package/dist/{chunk-BDO3VJEU.mjs → chunk-2CWF7ZTL.mjs} +2 -2
  5. package/dist/{chunk-7KMONAQI.mjs → chunk-4WXZXVLI.mjs} +7 -9
  6. package/dist/{chunk-7KMONAQI.mjs.map → chunk-4WXZXVLI.mjs.map} +1 -1
  7. package/dist/{chunk-VD2IGTS3.js → chunk-4ZGRRVMI.js} +5 -5
  8. package/dist/{chunk-Y7P3UH26.mjs → chunk-D4SNJOID.mjs} +31 -3
  9. package/dist/chunk-D4SNJOID.mjs.map +1 -0
  10. package/dist/{chunk-SMKTWM6I.js → chunk-DF24ZX4H.js} +2 -3
  11. package/dist/chunk-DF24ZX4H.js.map +1 -0
  12. package/dist/{chunk-NPH5AHLH.mjs → chunk-E7Z5TCQT.mjs} +54 -6
  13. package/dist/chunk-E7Z5TCQT.mjs.map +1 -0
  14. package/dist/chunk-EHZFPUJH.mjs +53 -0
  15. package/dist/chunk-EHZFPUJH.mjs.map +1 -0
  16. package/dist/{chunk-SLHAVOTE.js → chunk-EYZFHZR2.js} +11 -4
  17. package/dist/chunk-EYZFHZR2.js.map +1 -0
  18. package/dist/{chunk-DHKZ2NEF.js → chunk-F6BAOSH2.js} +35 -7
  19. package/dist/chunk-F6BAOSH2.js.map +1 -0
  20. package/dist/chunk-GQXYWBFK.js +28 -0
  21. package/dist/chunk-GQXYWBFK.js.map +1 -0
  22. package/dist/{chunk-3TE6M5TV.js → chunk-HMRRB4EX.js} +40 -7
  23. package/dist/chunk-HMRRB4EX.js.map +1 -0
  24. package/dist/{chunk-DRD22DR5.mjs → chunk-J7NSK6BO.mjs} +2 -2
  25. package/dist/chunk-JAQ5TPSZ.js +53 -0
  26. package/dist/chunk-JAQ5TPSZ.js.map +1 -0
  27. package/dist/{chunk-PSR2V3R4.js → chunk-JJ5BDCKD.js} +17 -19
  28. package/dist/chunk-JJ5BDCKD.js.map +1 -0
  29. package/dist/{chunk-G4NU4KP7.js → chunk-KIVBL6OM.js} +6 -6
  30. package/dist/{chunk-FQ5SDMRE.mjs → chunk-KTCSRECK.mjs} +2 -3
  31. package/dist/{chunk-FQ5SDMRE.mjs.map → chunk-KTCSRECK.mjs.map} +1 -1
  32. package/dist/chunk-LDYHGAP4.js +11 -0
  33. package/dist/chunk-LDYHGAP4.js.map +1 -0
  34. package/dist/{chunk-7SW3CC66.mjs → chunk-LGXQBALM.mjs} +2 -2
  35. package/dist/{chunk-5C53GKTU.js.map → chunk-LGXQBALM.mjs.map} +1 -1
  36. package/dist/{chunk-BOET676P.js → chunk-LLG4D2SC.js} +8 -8
  37. package/dist/{chunk-R2S3HIDN.js → chunk-LNECIW4K.js} +236 -6
  38. package/dist/chunk-LNECIW4K.js.map +1 -0
  39. package/dist/{chunk-FU7PSGFP.mjs → chunk-LYDHYB6I.mjs} +36 -3
  40. package/dist/chunk-LYDHYB6I.mjs.map +1 -0
  41. package/dist/{chunk-LNSB4L7K.mjs → chunk-M23ZCTKE.mjs} +235 -5
  42. package/dist/chunk-M23ZCTKE.mjs.map +1 -0
  43. package/dist/{chunk-ILIZJQ6X.mjs → chunk-NSSHFDIS.mjs} +10 -3
  44. package/dist/chunk-NSSHFDIS.mjs.map +1 -0
  45. package/dist/{chunk-BXPL7ZFX.js → chunk-PRYLTXW4.js} +15 -9
  46. package/dist/chunk-PRYLTXW4.js.map +1 -0
  47. package/dist/{chunk-XSSIP3PJ.js → chunk-Q5KTSMRE.js} +8 -8
  48. package/dist/chunk-QU4EXKJO.mjs +11 -0
  49. package/dist/chunk-QU4EXKJO.mjs.map +1 -0
  50. package/dist/{chunk-LDEIUP6J.mjs → chunk-UHP2Y32K.mjs} +9 -3
  51. package/dist/chunk-UHP2Y32K.mjs.map +1 -0
  52. package/dist/chunk-WAFY3R2F.js +103 -0
  53. package/dist/chunk-WAFY3R2F.js.map +1 -0
  54. package/dist/{chunk-VYZPOR47.mjs → chunk-YKOMKXG4.mjs} +4 -4
  55. package/dist/{chunk-WB6MUIML.mjs → chunk-YLURF2PF.mjs} +2 -2
  56. package/dist/{chunk-FUPEFLXB.js → chunk-ZMQRPWJN.js} +60 -12
  57. package/dist/chunk-ZMQRPWJN.js.map +1 -0
  58. package/dist/chunk-ZUPTMFEA.mjs +28 -0
  59. package/dist/chunk-ZUPTMFEA.mjs.map +1 -0
  60. package/dist/{chunk-5C53GKTU.js → chunk-ZX2KHPXG.js} +5 -5
  61. package/dist/chunk-ZX2KHPXG.js.map +1 -0
  62. package/dist/chunk-ZYYAQJ56.mjs +103 -0
  63. package/dist/chunk-ZYYAQJ56.mjs.map +1 -0
  64. package/dist/controllers/authentication/AuthenticationController.js +4 -21
  65. package/dist/controllers/authentication/AuthenticationController.mjs +3 -20
  66. package/dist/controllers/authentication/index.js +7 -22
  67. package/dist/controllers/authentication/index.mjs +6 -21
  68. package/dist/controllers/authentication/services.js +3 -20
  69. package/dist/controllers/authentication/services.mjs +2 -19
  70. package/dist/controllers/index.js +11 -21
  71. package/dist/controllers/index.mjs +10 -20
  72. package/dist/controllers/user-storage/UserStorageController.js +7 -17
  73. package/dist/controllers/user-storage/UserStorageController.mjs +6 -16
  74. package/dist/controllers/user-storage/accounts/constants.js +12 -0
  75. package/dist/controllers/user-storage/accounts/constants.js.map +1 -0
  76. package/dist/controllers/user-storage/accounts/constants.mjs +12 -0
  77. package/dist/controllers/user-storage/accounts/constants.mjs.map +1 -0
  78. package/dist/controllers/user-storage/accounts/user-storage.js +11 -0
  79. package/dist/controllers/user-storage/accounts/user-storage.js.map +1 -0
  80. package/dist/controllers/user-storage/accounts/user-storage.mjs +11 -0
  81. package/dist/controllers/user-storage/accounts/user-storage.mjs.map +1 -0
  82. package/dist/controllers/user-storage/index.js +10 -18
  83. package/dist/controllers/user-storage/index.mjs +10 -18
  84. package/dist/controllers/user-storage/schema.js +4 -2
  85. package/dist/controllers/user-storage/schema.mjs +5 -3
  86. package/dist/controllers/user-storage/services.js +6 -16
  87. package/dist/controllers/user-storage/services.mjs +5 -15
  88. package/dist/index.js +18 -16
  89. package/dist/index.mjs +17 -15
  90. package/dist/sdk/authentication-jwt-bearer/flow-siwe.js +4 -4
  91. package/dist/sdk/authentication-jwt-bearer/flow-siwe.mjs +3 -3
  92. package/dist/sdk/authentication-jwt-bearer/flow-srp.js +4 -4
  93. package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs +3 -3
  94. package/dist/sdk/authentication-jwt-bearer/services.js +3 -3
  95. package/dist/sdk/authentication-jwt-bearer/services.mjs +2 -2
  96. package/dist/sdk/authentication.js +6 -6
  97. package/dist/sdk/authentication.mjs +5 -5
  98. package/dist/sdk/encryption.js +5 -3
  99. package/dist/sdk/encryption.mjs +6 -4
  100. package/dist/sdk/env.js +2 -2
  101. package/dist/sdk/env.mjs +1 -1
  102. package/dist/sdk/index.js +13 -15
  103. package/dist/sdk/index.mjs +12 -14
  104. package/dist/sdk/user-storage.js +5 -5
  105. package/dist/sdk/user-storage.mjs +4 -4
  106. package/dist/tsconfig.build.tsbuildinfo +1 -1
  107. package/dist/types/controllers/authentication/AuthenticationController.d.ts +9 -4
  108. package/dist/types/controllers/authentication/AuthenticationController.d.ts.map +1 -1
  109. package/dist/types/controllers/authentication/__fixtures__/mockResponses.d.ts +1 -1
  110. package/dist/types/controllers/authentication/__fixtures__/mockResponses.d.ts.map +1 -1
  111. package/dist/types/controllers/authentication/index.d.ts +2 -0
  112. package/dist/types/controllers/authentication/index.d.ts.map +1 -1
  113. package/dist/types/controllers/user-storage/UserStorageController.d.ts +48 -8
  114. package/dist/types/controllers/user-storage/UserStorageController.d.ts.map +1 -1
  115. package/dist/types/controllers/user-storage/__fixtures__/mockAccounts.d.ts +63 -0
  116. package/dist/types/controllers/user-storage/__fixtures__/mockAccounts.d.ts.map +1 -0
  117. package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts +10 -4
  118. package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts.map +1 -1
  119. package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts +4 -2
  120. package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts.map +1 -1
  121. package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts +1 -1
  122. package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts.map +1 -1
  123. package/dist/types/controllers/user-storage/accounts/constants.d.ts +4 -0
  124. package/dist/types/controllers/user-storage/accounts/constants.d.ts.map +1 -0
  125. package/dist/types/controllers/user-storage/accounts/user-storage.d.ts +32 -0
  126. package/dist/types/controllers/user-storage/accounts/user-storage.d.ts.map +1 -0
  127. package/dist/types/controllers/user-storage/index.d.ts +2 -0
  128. package/dist/types/controllers/user-storage/index.d.ts.map +1 -1
  129. package/dist/types/controllers/user-storage/schema.d.ts +13 -6
  130. package/dist/types/controllers/user-storage/schema.d.ts.map +1 -1
  131. package/dist/types/controllers/user-storage/services.d.ts +20 -4
  132. package/dist/types/controllers/user-storage/services.d.ts.map +1 -1
  133. package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts +1 -0
  134. package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts.map +1 -1
  135. package/dist/types/sdk/encryption.d.ts +3 -19
  136. package/dist/types/sdk/encryption.d.ts.map +1 -1
  137. package/dist/types/sdk/user-storage.d.ts +4 -3
  138. package/dist/types/sdk/user-storage.d.ts.map +1 -1
  139. package/package.json +37 -4
  140. package/user-storage/mocks/package.json +9 -0
  141. package/user-storage/package.json +9 -0
  142. package/dist/chunk-3TE6M5TV.js.map +0 -1
  143. package/dist/chunk-77LSWSGB.js +0 -81
  144. package/dist/chunk-77LSWSGB.js.map +0 -1
  145. package/dist/chunk-7SW3CC66.mjs.map +0 -1
  146. package/dist/chunk-B5DBQDB3.mjs +0 -140
  147. package/dist/chunk-B5DBQDB3.mjs.map +0 -1
  148. package/dist/chunk-BXPL7ZFX.js.map +0 -1
  149. package/dist/chunk-DHKZ2NEF.js.map +0 -1
  150. package/dist/chunk-FU7PSGFP.mjs.map +0 -1
  151. package/dist/chunk-FUPEFLXB.js.map +0 -1
  152. package/dist/chunk-ILIZJQ6X.mjs.map +0 -1
  153. package/dist/chunk-IQECLCH4.mjs +0 -81
  154. package/dist/chunk-IQECLCH4.mjs.map +0 -1
  155. package/dist/chunk-LDEIUP6J.mjs.map +0 -1
  156. package/dist/chunk-LNSB4L7K.mjs.map +0 -1
  157. package/dist/chunk-NPH5AHLH.mjs.map +0 -1
  158. package/dist/chunk-P4DUDLMY.js +0 -140
  159. package/dist/chunk-P4DUDLMY.js.map +0 -1
  160. package/dist/chunk-PSR2V3R4.js.map +0 -1
  161. package/dist/chunk-R2S3HIDN.js.map +0 -1
  162. package/dist/chunk-SLHAVOTE.js.map +0 -1
  163. package/dist/chunk-SMKTWM6I.js.map +0 -1
  164. package/dist/chunk-Y7P3UH26.mjs.map +0 -1
  165. /package/dist/{chunk-BDO3VJEU.mjs.map → chunk-2CWF7ZTL.mjs.map} +0 -0
  166. /package/dist/{chunk-VD2IGTS3.js.map → chunk-4ZGRRVMI.js.map} +0 -0
  167. /package/dist/{chunk-DRD22DR5.mjs.map → chunk-J7NSK6BO.mjs.map} +0 -0
  168. /package/dist/{chunk-G4NU4KP7.js.map → chunk-KIVBL6OM.js.map} +0 -0
  169. /package/dist/{chunk-BOET676P.js.map → chunk-LLG4D2SC.js.map} +0 -0
  170. /package/dist/{chunk-XSSIP3PJ.js.map → chunk-Q5KTSMRE.js.map} +0 -0
  171. /package/dist/{chunk-VYZPOR47.mjs.map → chunk-YKOMKXG4.mjs.map} +0 -0
  172. /package/dist/{chunk-WB6MUIML.mjs.map → chunk-YLURF2PF.mjs.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
 
4
- var _chunkSMKTWM6Ijs = require('./chunk-SMKTWM6I.js');
4
+ var _chunkDF24ZX4Hjs = require('./chunk-DF24ZX4H.js');
5
5
 
6
6
 
7
7
 
@@ -10,11 +10,11 @@ var _chunkSMKTWM6Ijs = require('./chunk-SMKTWM6I.js');
10
10
  var _chunkMBTBE4P5js = require('./chunk-MBTBE4P5.js');
11
11
 
12
12
  // src/sdk/authentication-jwt-bearer/services.ts
13
- var NONCE_URL = (env) => `${_chunkSMKTWM6Ijs.getEnvUrls.call(void 0, env).authApiUrl}/api/v2/nonce`;
14
- var PAIR_IDENTIFIERS = (env) => `${_chunkSMKTWM6Ijs.getEnvUrls.call(void 0, env).authApiUrl}/api/v2/identifiers/pair`;
15
- var OIDC_TOKEN_URL = (env) => `${_chunkSMKTWM6Ijs.getEnvUrls.call(void 0, env).oidcApiUrl}/oauth2/token`;
16
- var SRP_LOGIN_URL = (env) => `${_chunkSMKTWM6Ijs.getEnvUrls.call(void 0, env).authApiUrl}/api/v2/srp/login`;
17
- var SIWE_LOGIN_URL = (env) => `${_chunkSMKTWM6Ijs.getEnvUrls.call(void 0, env).authApiUrl}/api/v2/siwe/login`;
13
+ var NONCE_URL = (env) => `${_chunkDF24ZX4Hjs.getEnvUrls.call(void 0, env).authApiUrl}/api/v2/nonce`;
14
+ var PAIR_IDENTIFIERS = (env) => `${_chunkDF24ZX4Hjs.getEnvUrls.call(void 0, env).authApiUrl}/api/v2/identifiers/pair`;
15
+ var OIDC_TOKEN_URL = (env) => `${_chunkDF24ZX4Hjs.getEnvUrls.call(void 0, env).oidcApiUrl}/oauth2/token`;
16
+ var SRP_LOGIN_URL = (env) => `${_chunkDF24ZX4Hjs.getEnvUrls.call(void 0, env).authApiUrl}/api/v2/srp/login`;
17
+ var SIWE_LOGIN_URL = (env) => `${_chunkDF24ZX4Hjs.getEnvUrls.call(void 0, env).authApiUrl}/api/v2/siwe/login`;
18
18
  var getAuthenticationUrl = (authType, env) => {
19
19
  switch (authType) {
20
20
  case "SRP" /* SRP */:
@@ -81,7 +81,7 @@ async function authorizeOIDC(jwtToken, env, platform) {
81
81
  });
82
82
  const urlEncodedBody = new URLSearchParams();
83
83
  urlEncodedBody.append("grant_type", grantType);
84
- urlEncodedBody.append("client_id", _chunkSMKTWM6Ijs.getOidcClientId.call(void 0, env, platform));
84
+ urlEncodedBody.append("client_id", _chunkDF24ZX4Hjs.getOidcClientId.call(void 0, env, platform));
85
85
  urlEncodedBody.append("assertion", jwtToken);
86
86
  try {
87
87
  const response = await fetch(OIDC_TOKEN_URL(env), {
@@ -154,4 +154,4 @@ async function authenticate(rawMessage, signature, authType, env) {
154
154
 
155
155
 
156
156
  exports.NONCE_URL = NONCE_URL; exports.PAIR_IDENTIFIERS = PAIR_IDENTIFIERS; exports.OIDC_TOKEN_URL = OIDC_TOKEN_URL; exports.SRP_LOGIN_URL = SRP_LOGIN_URL; exports.SIWE_LOGIN_URL = SIWE_LOGIN_URL; exports.pairIdentifiers = pairIdentifiers; exports.getNonce = getNonce; exports.authorizeOIDC = authorizeOIDC; exports.authenticate = authenticate;
157
- //# sourceMappingURL=chunk-BOET676P.js.map
157
+ //# sourceMappingURL=chunk-LLG4D2SC.js.map
@@ -1,10 +1,15 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
+
4
+ var _chunkGQXYWBFKjs = require('./chunk-GQXYWBFK.js');
5
+
6
+
3
7
  var _chunkYHGWG3EQjs = require('./chunk-YHGWG3EQ.js');
4
8
 
5
9
 
6
10
 
7
- var _chunk3TE6M5TVjs = require('./chunk-3TE6M5TV.js');
11
+
12
+ var _chunkHMRRB4EXjs = require('./chunk-HMRRB4EX.js');
8
13
 
9
14
 
10
15
  var _chunkT3FNDVE3js = require('./chunk-T3FNDVE3.js');
@@ -12,6 +17,7 @@ var _chunkT3FNDVE3js = require('./chunk-T3FNDVE3.js');
12
17
 
13
18
 
14
19
 
20
+
15
21
  var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
16
22
 
17
23
  // src/controllers/user-storage/UserStorageController.ts
@@ -31,7 +37,7 @@ var metadata = {
31
37
  anonymous: false
32
38
  }
33
39
  };
34
- var _auth, _notificationServices, _registerMessageHandlers, registerMessageHandlers_fn, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn, _createStorageKey, createStorageKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn;
40
+ var _auth, _accounts, _notificationServices, _isUnlocked, _keyringController, _registerMessageHandlers, registerMessageHandlers_fn, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn, _createStorageKey, createStorageKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn;
35
41
  var UserStorageController = class extends _basecontroller.BaseController {
36
42
  constructor(params) {
37
43
  super({
@@ -90,6 +96,54 @@ var UserStorageController = class extends _basecontroller.BaseController {
90
96
  );
91
97
  }
92
98
  });
99
+ _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _accounts, {
100
+ // This is replaced with the actual value in the constructor
101
+ // We will remove this once the feature will be released
102
+ isAccountSyncingEnabled: false,
103
+ getInternalAccountByAddress: async (address) => {
104
+ return this.messagingSystem.call(
105
+ "AccountsController:getAccountByAddress",
106
+ address
107
+ );
108
+ },
109
+ getInternalAccountsList: async () => {
110
+ return this.messagingSystem.call("AccountsController:listAccounts");
111
+ },
112
+ getUserStorageAccountsList: async () => {
113
+ const rawAccountsListResponse = await this.performGetStorageAllFeatureEntries("accounts");
114
+ return rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ?? null;
115
+ },
116
+ saveInternalAccountToUserStorage: async (address) => {
117
+ const internalAccount = await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).getInternalAccountByAddress(
118
+ address
119
+ );
120
+ if (!internalAccount) {
121
+ return;
122
+ }
123
+ const mappedAccount = _chunkGQXYWBFKjs.mapInternalAccountToUserStorageAccount.call(void 0, internalAccount);
124
+ await this.performSetStorage(
125
+ `accounts.${address}`,
126
+ JSON.stringify(mappedAccount)
127
+ );
128
+ },
129
+ saveInternalAccountsListToUserStorage: async () => {
130
+ const internalAccountsList = await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).getInternalAccountsList();
131
+ if (!internalAccountsList) {
132
+ return;
133
+ }
134
+ const userStorageAccountsList = internalAccountsList.map(
135
+ _chunkGQXYWBFKjs.mapInternalAccountToUserStorageAccount
136
+ );
137
+ await Promise.all(
138
+ userStorageAccountsList.map(async (userStorageAccount) => {
139
+ await this.performSetStorage(
140
+ `accounts.${userStorageAccount.a}`,
141
+ JSON.stringify(userStorageAccount)
142
+ );
143
+ })
144
+ );
145
+ }
146
+ });
93
147
  _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _notificationServices, {
94
148
  disableNotificationServices: async () => {
95
149
  return await this.messagingSystem.call(
@@ -102,8 +156,32 @@ var UserStorageController = class extends _basecontroller.BaseController {
102
156
  );
103
157
  }
104
158
  });
159
+ _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _isUnlocked, false);
160
+ _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _keyringController, {
161
+ setupLockedStateSubscriptions: () => {
162
+ const { isUnlocked } = this.messagingSystem.call(
163
+ "KeyringController:getState"
164
+ );
165
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, isUnlocked);
166
+ this.messagingSystem.subscribe(
167
+ "KeyringController:unlock",
168
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
169
+ async () => {
170
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, true);
171
+ await this.syncInternalAccountsWithUserStorage();
172
+ }
173
+ );
174
+ this.messagingSystem.subscribe("KeyringController:lock", () => {
175
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, false);
176
+ });
177
+ }
178
+ });
105
179
  _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, __snapSignMessageCache, {});
180
+ _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).isAccountSyncingEnabled = Boolean(
181
+ params.env?.isAccountSyncingEnabled
182
+ );
106
183
  this.getMetaMetricsState = params.getMetaMetricsState;
184
+ _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _keyringController).setupLockedStateSubscriptions();
107
185
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
108
186
  }
109
187
  async enableProfileSyncing() {
@@ -143,7 +221,7 @@ var UserStorageController = class extends _basecontroller.BaseController {
143
221
  }
144
222
  const isMetaMetricsParticipation = this.getMetaMetricsState();
145
223
  if (!isMetaMetricsParticipation) {
146
- this.messagingSystem.call("AuthenticationController:performSignOut");
224
+ await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _auth).signOut();
147
225
  }
148
226
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn).call(this, false);
149
227
  this.update((state) => {
@@ -167,7 +245,24 @@ var UserStorageController = class extends _basecontroller.BaseController {
167
245
  async performGetStorage(path) {
168
246
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
169
247
  const { bearerToken, storageKey } = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
170
- const result = await _chunk3TE6M5TVjs.getUserStorage.call(void 0, {
248
+ const result = await _chunkHMRRB4EXjs.getUserStorage.call(void 0, {
249
+ path,
250
+ bearerToken,
251
+ storageKey
252
+ });
253
+ return result;
254
+ }
255
+ /**
256
+ * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.
257
+ * Developers can extend the entry path through the `schema.ts` file.
258
+ *
259
+ * @param path - string in the form of `${feature}` that matches schema
260
+ * @returns the array of decrypted string contents found from user storage (or null if not found)
261
+ */
262
+ async performGetStorageAllFeatureEntries(path) {
263
+ _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
264
+ const { bearerToken, storageKey } = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
265
+ const result = await _chunkHMRRB4EXjs.getUserStorageAllFeatureEntries.call(void 0, {
171
266
  path,
172
267
  bearerToken,
173
268
  storageKey
@@ -185,7 +280,7 @@ var UserStorageController = class extends _basecontroller.BaseController {
185
280
  async performSetStorage(path, value) {
186
281
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
187
282
  const { bearerToken, storageKey } = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
188
- await _chunk3TE6M5TVjs.upsertUserStorage.call(void 0, value, {
283
+ await _chunkHMRRB4EXjs.upsertUserStorage.call(void 0, value, {
189
284
  path,
190
285
  bearerToken,
191
286
  storageKey
@@ -201,15 +296,137 @@ var UserStorageController = class extends _basecontroller.BaseController {
201
296
  const storageKey = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _createStorageKey, createStorageKey_fn).call(this);
202
297
  return storageKey;
203
298
  }
299
+ /**
300
+ * Syncs the internal accounts list with the user storage accounts list.
301
+ * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.
302
+ * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.
303
+ */
304
+ async syncInternalAccountsWithUserStorage() {
305
+ if (!_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).isAccountSyncingEnabled) {
306
+ return;
307
+ }
308
+ try {
309
+ _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
310
+ const userStorageAccountsList = await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).getUserStorageAccountsList();
311
+ if (!userStorageAccountsList || !userStorageAccountsList.length) {
312
+ await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).saveInternalAccountsListToUserStorage();
313
+ return;
314
+ }
315
+ let internalAccountsList = await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).getInternalAccountsList();
316
+ if (!internalAccountsList || !internalAccountsList.length) {
317
+ throw new Error(`Failed to get internal accounts list`);
318
+ }
319
+ const hasMoreInternalAccountsThanUserStorageAccounts = internalAccountsList.length > userStorageAccountsList.length;
320
+ if (!hasMoreInternalAccountsThanUserStorageAccounts) {
321
+ const numberOfAccountsToAdd = userStorageAccountsList.length - internalAccountsList.length;
322
+ const addNewAccountsPromises = Array.from({
323
+ length: numberOfAccountsToAdd
324
+ }).map(async () => {
325
+ await this.messagingSystem.call("KeyringController:addNewAccount");
326
+ });
327
+ await Promise.all(addNewAccountsPromises);
328
+ }
329
+ internalAccountsList = await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).getInternalAccountsList();
330
+ for await (const internalAccount of internalAccountsList) {
331
+ const userStorageAccount = userStorageAccountsList.find(
332
+ (account) => account.a === internalAccount.address
333
+ );
334
+ if (!userStorageAccount) {
335
+ await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).saveInternalAccountToUserStorage(
336
+ internalAccount.address
337
+ );
338
+ continue;
339
+ }
340
+ const isInternalAccountNameDefault = _chunkGQXYWBFKjs.isNameDefaultAccountName.call(void 0,
341
+ internalAccount.metadata.name
342
+ );
343
+ const isUserStorageAccountNameDefault = _chunkGQXYWBFKjs.isNameDefaultAccountName.call(void 0,
344
+ userStorageAccount.n
345
+ );
346
+ if (isInternalAccountNameDefault) {
347
+ if (!isUserStorageAccountNameDefault) {
348
+ this.messagingSystem.call(
349
+ "AccountsController:updateAccountMetadata",
350
+ internalAccount.id,
351
+ {
352
+ name: userStorageAccount.n
353
+ }
354
+ );
355
+ }
356
+ continue;
357
+ }
358
+ if (isUserStorageAccountNameDefault) {
359
+ await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).saveInternalAccountToUserStorage(
360
+ internalAccount.address
361
+ );
362
+ continue;
363
+ }
364
+ if (userStorageAccount.nlu !== void 0) {
365
+ if (internalAccount.metadata.nameLastUpdatedAt !== void 0) {
366
+ const isInternalAccountNameNewer = internalAccount.metadata.nameLastUpdatedAt > userStorageAccount.nlu;
367
+ if (isInternalAccountNameNewer) {
368
+ await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).saveInternalAccountToUserStorage(
369
+ internalAccount.address
370
+ );
371
+ continue;
372
+ }
373
+ }
374
+ this.messagingSystem.call(
375
+ "AccountsController:updateAccountMetadata",
376
+ internalAccount.id,
377
+ {
378
+ name: userStorageAccount.n,
379
+ nameLastUpdatedAt: userStorageAccount.nlu
380
+ }
381
+ );
382
+ continue;
383
+ } else if (internalAccount.metadata.nameLastUpdatedAt !== void 0) {
384
+ await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).saveInternalAccountToUserStorage(
385
+ internalAccount.address
386
+ );
387
+ continue;
388
+ }
389
+ }
390
+ } catch (e) {
391
+ const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
392
+ throw new Error(
393
+ `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`
394
+ );
395
+ }
396
+ }
397
+ /**
398
+ * Saves an individual internal account to the user storage.
399
+ * @param address - The address of the internal account to save
400
+ */
401
+ async saveInternalAccountToUserStorage(address) {
402
+ if (!_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).isAccountSyncingEnabled) {
403
+ return;
404
+ }
405
+ try {
406
+ await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).saveInternalAccountToUserStorage(address);
407
+ } catch (e) {
408
+ const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
409
+ throw new Error(
410
+ `${controllerName} - failed to save account to user storage - ${errorMessage}`
411
+ );
412
+ }
413
+ }
204
414
  };
205
415
  _auth = new WeakMap();
416
+ _accounts = new WeakMap();
206
417
  _notificationServices = new WeakMap();
418
+ _isUnlocked = new WeakMap();
419
+ _keyringController = new WeakMap();
207
420
  _registerMessageHandlers = new WeakSet();
208
421
  registerMessageHandlers_fn = function() {
209
422
  this.messagingSystem.registerActionHandler(
210
423
  "UserStorageController:performGetStorage",
211
424
  this.performGetStorage.bind(this)
212
425
  );
426
+ this.messagingSystem.registerActionHandler(
427
+ "UserStorageController:performGetStorageAllFeatureEntries",
428
+ this.performGetStorageAllFeatureEntries.bind(this)
429
+ );
213
430
  this.messagingSystem.registerActionHandler(
214
431
  "UserStorageController:performSetStorage",
215
432
  this.performSetStorage.bind(this)
@@ -226,6 +443,14 @@ registerMessageHandlers_fn = function() {
226
443
  "UserStorageController:disableProfileSyncing",
227
444
  this.disableProfileSyncing.bind(this)
228
445
  );
446
+ this.messagingSystem.registerActionHandler(
447
+ "UserStorageController:syncInternalAccountsWithUserStorage",
448
+ this.syncInternalAccountsWithUserStorage.bind(this)
449
+ );
450
+ this.messagingSystem.registerActionHandler(
451
+ "UserStorageController:saveInternalAccountToUserStorage",
452
+ this.saveInternalAccountToUserStorage.bind(this)
453
+ );
229
454
  };
230
455
  _assertProfileSyncingEnabled = new WeakSet();
231
456
  assertProfileSyncingEnabled_fn = function() {
@@ -260,6 +485,11 @@ snapSignMessage_fn = async function(message) {
260
485
  if (_chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapSignMessageCache)[message]) {
261
486
  return _chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapSignMessageCache)[message];
262
487
  }
488
+ if (!_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _isUnlocked)) {
489
+ throw new Error(
490
+ "#snapSignMessage - unable to call snap, wallet is locked"
491
+ );
492
+ }
263
493
  const result = await this.messagingSystem.call(
264
494
  "SnapController:handleRequest",
265
495
  _chunkYHGWG3EQjs.createSnapSignMessageRequest.call(void 0, message)
@@ -278,4 +508,4 @@ setIsProfileSyncingUpdateLoading_fn = function(isProfileSyncingUpdateLoading) {
278
508
 
279
509
 
280
510
  exports.defaultState = defaultState; exports.UserStorageController = UserStorageController;
281
- //# sourceMappingURL=chunk-R2S3HIDN.js.map
511
+ //# sourceMappingURL=chunk-LNECIW4K.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,sBAAsB;AA+C/B,IAAM,iBAAiB;AAchB,IAAM,eAA2C;AAAA,EACtD,yBAAyB;AAAA,EACzB,+BAA+B;AACjC;AAEA,IAAM,WAAsD;AAAA,EAC1D,yBAAyB;AAAA,IACvB,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AAAA,EACA,+BAA+B;AAAA,IAC7B,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AACF;AAtFA;AAiMA,IAAqB,wBAArB,cAAmD,eAIjD;AAAA,EAqIA,YAAY,QAOT;AACD,UAAM;AAAA,MACJ,WAAW,OAAO;AAAA,MAClB;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,OAAO,MAAM;AAAA,IAC5C,CAAC;AAeH;AAAA;AAAA;AAAA;AAAA;AAgMA;AAWA;AAAA;AAAA;AAAA,uBAAM;AAkBN;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AAmBN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AAqBN;AAraA,8BAAQ;AAAA,MACN,gBAAgB,YAAY;AAC1B,eAAO,MAAM,KAAK,gBAAgB;AAAA,UAChC;AAAA,QACF;AAAA,MACF;AAAA,MACA,cAAc,YAAY;AACxB,cAAM,iBAAiB,MAAM,K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AACF;AAwJA;AAAA,iCAA4B,WAAS;AACnC,MAAI,CAAC,KAAK,MAAM,yBAAyB;AACvC,UAAM,IAAI;AAAA,MACR,GAAG,cAAc;AAAA,IACnB;AAAA,EACF;AACF;AAKM;AAAA,iCAA4B,iBAG/B;AACD,QAAM,cAAc,MAAM,mBAAK,OAAM,eAAe;AACpD,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI,MAAM,oDAAoD;AAAA,EACtE;AACA,QAAM,aAAa,MAAM,sBAAK,wCAAL;AAEzB,SAAO,EAAE,aAAa,WAAW;AACnC;AAOM;AAAA,sBAAiB,iBAAoB;AACzC,QAAM,KAAa,MAAM,mBAAK,OAAM,aAAa;AACjD,MAAI,CAAC,IAAI;AACP,UAAM,IAAI,MAAM,sDAAsD;AAAA,EACxE;AAEA,QAAM,sBAAsB,MAAM,sBAAK,sCAAL,WAAsB,YAAY,EAAE;AACtE,QAAM,aAAa,iBAAiB,mBAAmB;AACvD,SAAO;AACT;AAEA;AAQM;AAAA,qBAAgB,eAAC,SAAgD;AACrE,MAAI,mBAAK,wBAAuB,OAAO,GAAG;AACxC,WAAO,mBAAK,wBAAuB,OAAO;AAAA,EAC5C;AAEA,MAAI,CAAC,mBAAK,cAAa;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAU,MAAM,KAAK,gBAAgB;AAAA,IACzC;AAAA,IACA,6BAA6B,OAAO;AAAA,EACtC;AAEA,qBAAK,wBAAuB,OAAO,IAAI;AAEvC,SAAO;AACT;AAEA;AAAA,sCAAiC,SAC/B,+BACM;AACN,OAAK,OAAO,CAAC,UAAU;AACrB,UAAM,gCAAgC;AAAA,EACxC,CAAC;AACH","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerGetAccountByAddressAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { InternalAccount } from '@metamask/keyring-api';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerAddNewAccountAction,\n} from '@metamask/keyring-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport type { UserStorageAccount } from './accounts/user-storage';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './accounts/user-storage';\nimport { createSHA256Hash } from './encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from './schema';\nimport {\n getUserStorage,\n getUserStorageAllFeatureEntries,\n upsertUserStorage,\n} from './services';\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n | 'syncInternalAccountsWithUserStorage'\n | 'saveInternalAccountToUserStorage'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\nexport type UserStorageControllerSyncInternalAccountsWithUserStorage =\n ActionsObj['syncInternalAccountsWithUserStorage'];\nexport type UserStorageControllerSaveInternalAccountToUserStorage =\n ActionsObj['saveInternalAccountToUserStorage'];\n\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Events = UserStorageControllerStateChangeEvent;\n\n// Allowed Actions\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n // Account syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerGetAccountByAddressAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerAddNewAccountAction;\n\n// Messenger events\nexport type UserStorageControllerChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type UserStorageControllerAccountSyncingInProgress = {\n type: `${typeof controllerName}:accountSyncingInProgress`;\n payload: [boolean];\n};\nexport type UserStorageControllerAccountSyncingComplete = {\n type: `${typeof controllerName}:accountSyncingComplete`;\n payload: [boolean];\n};\n\nexport type AllowedEvents =\n | UserStorageControllerChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #accounts = {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n isAccountSyncingEnabled: false,\n getInternalAccountByAddress: async (address: string) => {\n return this.messagingSystem.call(\n 'AccountsController:getAccountByAddress',\n address,\n );\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n return this.messagingSystem.call('AccountsController:listAccounts');\n },\n getUserStorageAccountsList: async (): Promise<\n UserStorageAccount[] | null\n > => {\n const rawAccountsListResponse =\n await this.performGetStorageAllFeatureEntries('accounts');\n\n return (\n rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??\n null\n );\n },\n saveInternalAccountToUserStorage: async (address: string) => {\n const internalAccount = await this.#accounts.getInternalAccountByAddress(\n address,\n );\n\n if (!internalAccount) {\n return;\n }\n\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await this.performSetStorage(\n `accounts.${address}`,\n JSON.stringify(mappedAccount),\n );\n },\n saveInternalAccountsListToUserStorage: async () => {\n const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList) {\n return;\n }\n\n const userStorageAccountsList = internalAccountsList.map(\n mapInternalAccountToUserStorageAccount,\n );\n\n await Promise.all(\n userStorageAccountsList.map(async (userStorageAccount) => {\n await this.performSetStorage(\n `accounts.${userStorageAccount.a}`,\n JSON.stringify(userStorageAccount),\n );\n }),\n );\n },\n };\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe(\n 'KeyringController:unlock',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async () => {\n this.#isUnlocked = true;\n\n await this.syncInternalAccountsWithUserStorage();\n },\n );\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n getMetaMetricsState: () => boolean;\n\n constructor(params: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n env?: {\n isAccountSyncingEnabled?: boolean;\n };\n getMetaMetricsState: () => boolean;\n }) {\n super({\n messenger: params.messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...params.state },\n });\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n params.env?.isAccountSyncingEnabled,\n );\n\n this.getMetaMetricsState = params.getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:syncInternalAccountsWithUserStorage',\n this.syncInternalAccountsWithUserStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:saveInternalAccountToUserStorage',\n this.saveInternalAccountToUserStorage.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n });\n\n return result;\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n\n /**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n */\n async syncInternalAccountsWithUserStorage(): Promise<void> {\n if (!this.#accounts.isAccountSyncingEnabled) {\n return;\n }\n\n try {\n this.#assertProfileSyncingEnabled();\n\n const userStorageAccountsList =\n await this.#accounts.getUserStorageAccountsList();\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await this.#accounts.saveInternalAccountsListToUserStorage();\n return;\n }\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n let internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreInternalAccountsThanUserStorageAccounts =\n internalAccountsList.length > userStorageAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts than the internal accounts list\n if (!hasMoreInternalAccountsThanUserStorageAccounts) {\n const numberOfAccountsToAdd =\n userStorageAccountsList.length - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n const addNewAccountsPromises = Array.from({\n length: numberOfAccountsToAdd,\n }).map(async () => {\n await this.messagingSystem.call('KeyringController:addNewAccount');\n });\n\n await Promise.all(addNewAccountsPromises);\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n for await (const internalAccount of internalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n if (!userStorageAccount) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n }\n\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n }\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Saves an individual internal account to the user storage.\n * @param address - The address of the internal account to save\n */\n async saveInternalAccountToUserStorage(address: string): Promise<void> {\n if (!this.#accounts.isAccountSyncingEnabled) {\n return;\n }\n\n try {\n await this.#accounts.saveInternalAccountToUserStorage(address);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to save account to user storage - ${errorMessage}`,\n );\n }\n }\n}\n"]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  createEntryPath
3
- } from "./chunk-ILIZJQ6X.mjs";
3
+ } from "./chunk-NSSHFDIS.mjs";
4
4
  import {
5
5
  encryption_default
6
6
  } from "./chunk-5TOWF6UW.mjs";
7
7
  import {
8
8
  getEnvUrls
9
- } from "./chunk-FQ5SDMRE.mjs";
9
+ } from "./chunk-KTCSRECK.mjs";
10
10
 
11
11
  // src/controllers/user-storage/services.ts
12
12
  import log from "loglevel";
@@ -45,6 +45,38 @@ async function getUserStorage(opts) {
45
45
  return null;
46
46
  }
47
47
  }
48
+ async function getUserStorageAllFeatureEntries(opts) {
49
+ try {
50
+ const { bearerToken, path } = opts;
51
+ const url = new URL(`${USER_STORAGE_ENDPOINT}/${path}`);
52
+ const userStorageResponse = await fetch(url.toString(), {
53
+ headers: {
54
+ "Content-Type": "application/json",
55
+ Authorization: `Bearer ${bearerToken}`
56
+ }
57
+ });
58
+ if (userStorageResponse.status === 404) {
59
+ return null;
60
+ }
61
+ if (userStorageResponse.status !== 200) {
62
+ throw new Error("Unable to get User Storage");
63
+ }
64
+ const userStorage = await userStorageResponse.json();
65
+ if (!Array.isArray(userStorage)) {
66
+ return null;
67
+ }
68
+ const decryptedData = userStorage?.flatMap((entry) => {
69
+ if (!entry.Data) {
70
+ return [];
71
+ }
72
+ return encryption_default.decryptString(entry.Data, opts.storageKey);
73
+ });
74
+ return decryptedData;
75
+ } catch (e) {
76
+ log.error("Failed to get user storage", e);
77
+ return null;
78
+ }
79
+ }
48
80
  async function upsertUserStorage(data, opts) {
49
81
  const { bearerToken, path, storageKey } = opts;
50
82
  const encryptedData = encryption_default.encryptString(data, opts.storageKey);
@@ -67,6 +99,7 @@ export {
67
99
  USER_STORAGE_API,
68
100
  USER_STORAGE_ENDPOINT,
69
101
  getUserStorage,
102
+ getUserStorageAllFeatureEntries,
70
103
  upsertUserStorage
71
104
  };
72
- //# sourceMappingURL=chunk-FU7PSGFP.mjs.map
105
+ //# sourceMappingURL=chunk-LYDHYB6I.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/user-storage/services.ts"],"sourcesContent":["import log from 'loglevel';\n\nimport { Env, getEnvUrls } from '../../sdk/env';\nimport encryption from './encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from './schema';\nimport { createEntryPath } from './schema';\n\nconst ENV_URLS = getEnvUrls(Env.PRD);\n\nexport const USER_STORAGE_API: string = ENV_URLS.userStorageApiUrl;\nexport const USER_STORAGE_ENDPOINT = `${USER_STORAGE_API}/api/v1/userstorage`;\n\n/**\n * This is the Server Response shape for a feature entry.\n */\nexport type GetUserStorageResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n}[];\n\nexport type UserStorageBaseOptions = {\n bearerToken: string;\n storageKey: string;\n};\n\nexport type UserStorageOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureAndKey;\n};\n\nexport type UserStorageAllFeatureEntriesOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureOnly;\n};\n\n/**\n * User Storage Service - Get Storage Entry.\n *\n * @param opts - User Storage Options\n * @returns The storage entry, or null if fails to find entry\n */\nexport async function getUserStorage(\n opts: UserStorageOptions,\n): Promise<string | null> {\n try {\n const { bearerToken, path, storageKey } = opts;\n\n const encryptedPath = createEntryPath(path, storageKey);\n const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);\n\n const userStorageResponse = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n\n // Acceptable error - since indicates entry does not exist.\n if (userStorageResponse.status === 404) {\n return null;\n }\n\n if (userStorageResponse.status !== 200) {\n throw new Error('Unable to get User Storage');\n }\n\n const userStorage: GetUserStorageResponse | null =\n await userStorageResponse.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = encryption.decryptString(\n encryptedData,\n opts.storageKey,\n );\n\n return decryptedData;\n } catch (e) {\n log.error('Failed to get user storage', e);\n return null;\n }\n}\n\n/**\n * User Storage Service - Get all storage entries for a specific feature.\n *\n * @param opts - User Storage Options\n * @returns The storage entry, or null if fails to find entry\n */\nexport async function getUserStorageAllFeatureEntries(\n opts: UserStorageAllFeatureEntriesOptions,\n): Promise<string[] | null> {\n try {\n const { bearerToken, path } = opts;\n const url = new URL(`${USER_STORAGE_ENDPOINT}/${path}`);\n\n const userStorageResponse = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n\n // Acceptable error - since indicates feature does not exist.\n if (userStorageResponse.status === 404) {\n return null;\n }\n\n if (userStorageResponse.status !== 200) {\n throw new Error('Unable to get User Storage');\n }\n\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await userStorageResponse.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData = userStorage?.flatMap((entry) => {\n if (!entry.Data) {\n return [];\n }\n\n return encryption.decryptString(entry.Data, opts.storageKey);\n });\n\n return decryptedData;\n } catch (e) {\n log.error('Failed to get user storage', e);\n return null;\n }\n}\n\n/**\n * User Storage Service - Set Storage Entry.\n *\n * @param data - data to store\n * @param opts - storage options\n */\nexport async function upsertUserStorage(\n data: string,\n opts: UserStorageOptions,\n): Promise<void> {\n const { bearerToken, path, storageKey } = opts;\n\n const encryptedData = encryption.encryptString(data, opts.storageKey);\n const encryptedPath = createEntryPath(path, storageKey);\n const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);\n\n const res = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!res.ok) {\n throw new Error('user-storage - unable to upsert data');\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,OAAO,SAAS;AAUhB,IAAM,WAAW,0BAAkB;AAE5B,IAAM,mBAA2B,SAAS;AAC1C,IAAM,wBAAwB,GAAG,gBAAgB;AAsCxD,eAAsB,eACpB,MACwB;AACxB,MAAI;AACF,UAAM,EAAE,aAAa,MAAM,WAAW,IAAI;AAE1C,UAAM,gBAAgB,gBAAgB,MAAM,UAAU;AACtD,UAAM,MAAM,IAAI,IAAI,GAAG,qBAAqB,GAAG,aAAa,EAAE;AAE9D,UAAM,sBAAsB,MAAM,MAAM,IAAI,SAAS,GAAG;AAAA,MACtD,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,eAAe,UAAU,WAAW;AAAA,MACtC;AAAA,IACF,CAAC;AAGD,QAAI,oBAAoB,WAAW,KAAK;AACtC,aAAO;AAAA,IACT;AAEA,QAA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