@arcblock/did-connect-react 3.4.15 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/dist/standalone/did-connect-react.css +1 -0
  2. package/dist/standalone/index.js +133700 -0
  3. package/lib/package.json.js +1 -1
  4. package/package.json +11 -6
  5. package/.aigne/doc-smith/config.yaml +0 -85
  6. package/.aigne/doc-smith/history.yaml +0 -6
  7. package/.aigne/doc-smith/output/structure-plan.json +0 -204
  8. package/.aigne/doc-smith/translation-cache.yaml +0 -11
  9. package/.aigne/doc-smith/upload-cache.yaml +0 -213
  10. package/docs/_sidebar.md +0 -18
  11. package/docs/advanced-authentication-methods.ja.md +0 -261
  12. package/docs/advanced-authentication-methods.md +0 -261
  13. package/docs/advanced-authentication-methods.zh-TW.md +0 -261
  14. package/docs/advanced-authentication-methods.zh.md +0 -261
  15. package/docs/advanced-utilities.ja.md +0 -132
  16. package/docs/advanced-utilities.md +0 -132
  17. package/docs/advanced-utilities.zh-TW.md +0 -132
  18. package/docs/advanced-utilities.zh.md +0 -132
  19. package/docs/advanced.ja.md +0 -95
  20. package/docs/advanced.md +0 -95
  21. package/docs/advanced.zh-TW.md +0 -95
  22. package/docs/advanced.zh.md +0 -95
  23. package/docs/api-reference.ja.md +0 -178
  24. package/docs/api-reference.md +0 -178
  25. package/docs/api-reference.zh-TW.md +0 -178
  26. package/docs/api-reference.zh.md +0 -178
  27. package/docs/assets/diagram/core-components-session-provider-01.ja.jpg +0 -0
  28. package/docs/assets/diagram/core-components-session-provider-01.jpg +0 -0
  29. package/docs/assets/diagram/core-components-session-provider-01.zh-TW.jpg +0 -0
  30. package/docs/assets/diagram/core-components-session-provider-01.zh.jpg +0 -0
  31. package/docs/assets/diagram/did-connect-diagram-0.ja.jpg +0 -0
  32. package/docs/assets/diagram/did-connect-diagram-0.jpg +0 -0
  33. package/docs/assets/diagram/did-connect-diagram-0.zh-TW.jpg +0 -0
  34. package/docs/assets/diagram/did-connect-diagram-0.zh.jpg +0 -0
  35. package/docs/assets/diagram/overview-01.ja.jpg +0 -0
  36. package/docs/assets/diagram/overview-01.jpg +0 -0
  37. package/docs/assets/diagram/overview-01.zh-TW.jpg +0 -0
  38. package/docs/assets/diagram/overview-01.zh.jpg +0 -0
  39. package/docs/assets/diagram/use-connect-diagram-0.ja.jpg +0 -0
  40. package/docs/assets/diagram/use-connect-diagram-0.jpg +0 -0
  41. package/docs/assets/diagram/use-connect-diagram-0.zh-TW.jpg +0 -0
  42. package/docs/assets/diagram/use-connect-diagram-0.zh.jpg +0 -0
  43. package/docs/core-components-did-connect.ja.md +0 -166
  44. package/docs/core-components-did-connect.md +0 -166
  45. package/docs/core-components-did-connect.zh-TW.md +0 -166
  46. package/docs/core-components-did-connect.zh.md +0 -166
  47. package/docs/core-components-session-provider.ja.md +0 -197
  48. package/docs/core-components-session-provider.md +0 -197
  49. package/docs/core-components-session-provider.zh-TW.md +0 -197
  50. package/docs/core-components-session-provider.zh.md +0 -197
  51. package/docs/core-components.ja.md +0 -16
  52. package/docs/core-components.md +0 -16
  53. package/docs/core-components.zh-TW.md +0 -16
  54. package/docs/core-components.zh.md +0 -16
  55. package/docs/getting-started.ja.md +0 -138
  56. package/docs/getting-started.md +0 -138
  57. package/docs/getting-started.zh-TW.md +0 -138
  58. package/docs/getting-started.zh.md +0 -138
  59. package/docs/hooks-use-connect.ja.md +0 -178
  60. package/docs/hooks-use-connect.md +0 -178
  61. package/docs/hooks-use-connect.zh-TW.md +0 -178
  62. package/docs/hooks-use-connect.zh.md +0 -178
  63. package/docs/hooks-use-did.ja.md +0 -107
  64. package/docs/hooks-use-did.md +0 -107
  65. package/docs/hooks-use-did.zh-TW.md +0 -107
  66. package/docs/hooks-use-did.zh.md +0 -107
  67. package/docs/hooks-use-oauth-passkey.ja.md +0 -188
  68. package/docs/hooks-use-oauth-passkey.md +0 -188
  69. package/docs/hooks-use-oauth-passkey.zh-TW.md +0 -188
  70. package/docs/hooks-use-oauth-passkey.zh.md +0 -188
  71. package/docs/hooks.ja.md +0 -23
  72. package/docs/hooks.md +0 -23
  73. package/docs/hooks.zh-TW.md +0 -23
  74. package/docs/hooks.zh.md +0 -23
  75. package/docs/overview.ja.md +0 -119
  76. package/docs/overview.md +0 -119
  77. package/docs/overview.zh-TW.md +0 -119
  78. package/docs/overview.zh.md +0 -119
  79. package/docs/ui-components-address.ja.md +0 -121
  80. package/docs/ui-components-address.md +0 -121
  81. package/docs/ui-components-address.zh-TW.md +0 -121
  82. package/docs/ui-components-address.zh.md +0 -121
  83. package/docs/ui-components-avatar.ja.md +0 -65
  84. package/docs/ui-components-avatar.md +0 -65
  85. package/docs/ui-components-avatar.zh-TW.md +0 -65
  86. package/docs/ui-components-avatar.zh.md +0 -65
  87. package/docs/ui-components-button.ja.md +0 -99
  88. package/docs/ui-components-button.md +0 -99
  89. package/docs/ui-components-button.zh-TW.md +0 -99
  90. package/docs/ui-components-button.zh.md +0 -99
  91. package/docs/ui-components-logo.ja.md +0 -52
  92. package/docs/ui-components-logo.md +0 -52
  93. package/docs/ui-components-logo.zh-TW.md +0 -52
  94. package/docs/ui-components-logo.zh.md +0 -52
  95. package/docs/ui-components.ja.md +0 -57
  96. package/docs/ui-components.md +0 -57
  97. package/docs/ui-components.zh-TW.md +0 -57
  98. package/docs/ui-components.zh.md +0 -57
  99. package/glossary.md +0 -1
  100. package/src/Address/index.jsx +0 -2
  101. package/src/Avatar/index.jsx +0 -2
  102. package/src/Button/Button.stories.jsx +0 -7
  103. package/src/Button/index.jsx +0 -21
  104. package/src/Connect/Connect.stories.jsx +0 -34
  105. package/src/Connect/assets/locale.js +0 -149
  106. package/src/Connect/assets/login-bg.png +0 -0
  107. package/src/Connect/assets/login-slogan.js +0 -7
  108. package/src/Connect/components/action-button.jsx +0 -22
  109. package/src/Connect/components/app-tips.jsx +0 -156
  110. package/src/Connect/components/auto-height.jsx +0 -38
  111. package/src/Connect/components/back-button.jsx +0 -24
  112. package/src/Connect/components/connect-status.jsx +0 -259
  113. package/src/Connect/components/did-connect-title.jsx +0 -107
  114. package/src/Connect/components/download-tips.jsx +0 -55
  115. package/src/Connect/components/loading.jsx +0 -25
  116. package/src/Connect/components/login-item/connect-choose-list.jsx +0 -328
  117. package/src/Connect/components/login-item/connect-provider-list.jsx +0 -473
  118. package/src/Connect/components/login-item/login-method-item.jsx +0 -139
  119. package/src/Connect/components/login-item/mobile-login-item.jsx +0 -184
  120. package/src/Connect/components/login-item/passkey-login-item.jsx +0 -56
  121. package/src/Connect/components/login-item/wallet-login-options.jsx +0 -129
  122. package/src/Connect/components/login-item/web-login-item.jsx +0 -159
  123. package/src/Connect/components/mask-overlay.jsx +0 -32
  124. package/src/Connect/components/refresh-overlay.jsx +0 -52
  125. package/src/Connect/components/switch-app.jsx +0 -69
  126. package/src/Connect/connect.jsx +0 -635
  127. package/src/Connect/contexts/state.jsx +0 -235
  128. package/src/Connect/fallback-connect.jsx +0 -47
  129. package/src/Connect/fullpage.jsx +0 -3
  130. package/src/Connect/hooks/auth-url.js +0 -31
  131. package/src/Connect/hooks/method-list.js +0 -121
  132. package/src/Connect/hooks/page-show.js +0 -24
  133. package/src/Connect/hooks/provider-list.js +0 -168
  134. package/src/Connect/hooks/security.js +0 -40
  135. package/src/Connect/hooks/token.js +0 -627
  136. package/src/Connect/hooks/use-apps.js +0 -69
  137. package/src/Connect/hooks/use-quick-connect.js +0 -119
  138. package/src/Connect/index.jsx +0 -21
  139. package/src/Connect/landing-page.jsx +0 -3
  140. package/src/Connect/plugins/email/index.jsx +0 -85
  141. package/src/Connect/plugins/email/list-item.jsx +0 -35
  142. package/src/Connect/plugins/email/placeholder.jsx +0 -372
  143. package/src/Connect/plugins/index.js +0 -2
  144. package/src/Connect/use-connect.jsx +0 -321
  145. package/src/Connect/with-blocklet.jsx +0 -26
  146. package/src/Connect/with-bridge-call.jsx +0 -138
  147. package/src/Federated/context.jsx +0 -93
  148. package/src/Federated/index.jsx +0 -1
  149. package/src/Logo/index.jsx +0 -2
  150. package/src/OAuth/bind-conflict-alert.jsx +0 -37
  151. package/src/OAuth/context.jsx +0 -407
  152. package/src/OAuth/guest.svg +0 -20
  153. package/src/OAuth/index.jsx +0 -1
  154. package/src/OAuth/passport-switcher.jsx +0 -2
  155. package/src/Passkey/actions.jsx +0 -217
  156. package/src/Passkey/constants.js +0 -2
  157. package/src/Passkey/context.jsx +0 -395
  158. package/src/Passkey/dialog.jsx +0 -401
  159. package/src/Passkey/icon.jsx +0 -10
  160. package/src/Passkey/index.jsx +0 -2
  161. package/src/Service/index.jsx +0 -96
  162. package/src/Session/assets/did-spaces-guide-cover.svg +0 -1
  163. package/src/Session/assets/did-spaces-guide-icon.svg +0 -7
  164. package/src/Session/context.jsx +0 -7
  165. package/src/Session/did-spaces-guide.jsx +0 -173
  166. package/src/Session/handler.jsx +0 -98
  167. package/src/Session/hooks/use-federated.js +0 -91
  168. package/src/Session/hooks/use-mobile.jsx +0 -6
  169. package/src/Session/hooks/use-protected-routes.js +0 -16
  170. package/src/Session/hooks/use-session-token.js +0 -400
  171. package/src/Session/hooks/use-verify.jsx +0 -76
  172. package/src/Session/index.jsx +0 -1789
  173. package/src/Session/libs/constants.js +0 -17
  174. package/src/Session/libs/did-spaces.js +0 -38
  175. package/src/Session/libs/federated.js +0 -82
  176. package/src/Session/libs/index.js +0 -5
  177. package/src/Session/libs/locales.js +0 -160
  178. package/src/Session/libs/login-mobile.js +0 -80
  179. package/src/Session/window-focus-aware.jsx +0 -28
  180. package/src/SessionManager/index.jsx +0 -2
  181. package/src/Storage/engine/cookie.js +0 -25
  182. package/src/Storage/engine/local-storage.js +0 -57
  183. package/src/Storage/index.js +0 -25
  184. package/src/User/index.js +0 -4
  185. package/src/User/use-did.js +0 -80
  186. package/src/User/wrap-did.jsx +0 -18
  187. package/src/WebWalletSWKeeper/index.jsx +0 -3
  188. package/src/components/PassportSwitcher.jsx +0 -160
  189. package/src/constant.js +0 -27
  190. package/src/error.js +0 -6
  191. package/src/hooks/use-locale.jsx +0 -6
  192. package/src/index.js +0 -32
  193. package/src/locales/en.jsx +0 -15
  194. package/src/locales/index.jsx +0 -13
  195. package/src/locales/zh.jsx +0 -15
  196. package/src/types.d.ts +0 -355
  197. package/src/utils.js +0 -413
  198. package/vite.config.mjs +0 -29
package/src/utils.js DELETED
@@ -1,413 +0,0 @@
1
- import { Buffer } from 'buffer';
2
- import SealedBox from 'tweetnacl-sealedbox-js';
3
- import { getCookieOptions, setVisitorId, getVisitorId, isUrl } from '@arcblock/ux/lib/Util';
4
- import Cookie from 'js-cookie';
5
- import isNil from 'lodash/isNil';
6
- import isString from 'lodash/isString';
7
- import isUndefined from 'lodash/isUndefined';
8
- import { createAxios as _createAxios, getBlockletSDK } from '@blocklet/js-sdk';
9
- import { withQuery } from 'ufo';
10
- import { isFromPublicKey, isValid as isValidDid } from '@arcblock/did';
11
- import { getSafeUrl } from '@arcblock/ux/lib/Util/security';
12
- import { createDebug, createLogger } from '@arcblock/ux/lib/Util/logger';
13
-
14
- import pkg from '../package.json';
15
- import { DID_CONNECT_URL_PARAMS_NAME, DEFAULT_WINDOW_TIMEOUT } from './constant';
16
- import { NotOpenError } from './error';
17
-
18
- const { version } = pkg;
19
-
20
- export const debug = createDebug('did-connect');
21
- export const debugTmp = createDebug('did-connect:tmp');
22
- export const debugTmpInterval = createDebug('did-connect:tmp-interval');
23
- export const logger = createLogger('did-connect');
24
-
25
- export * from '@arcblock/ux/lib/Util/wallet';
26
-
27
- export { setVisitorId, getVisitorId, version };
28
-
29
- // https://github.com/joaquimserafim/base64-url/blob/54d9c9ede66a8724f280cf24fd18c38b9a53915f/index.js#L10
30
- function unescape(str) {
31
- return (str + '==='.slice((str.length + 3) % 4)).replace(/-/g, '+').replace(/_/g, '/');
32
- }
33
- function escape(str) {
34
- return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
35
- }
36
-
37
- // 如果需要 did-connect 加入一个已经存在的 session, 可以通过 url 传递一个 "__connect_url__" 查询参数, did-connect 会解析参数值中的 token 和 connect url 并加入该 session
38
- // "__connect_url__" 需要编码/解码才可以正常使用
39
- // 该方法只针对 browser 环境, nodejs 环境可以使用 escape(Buffer.from(url).toString('base64')) 进行编码
40
- export const encodeConnectUrl = (url) => {
41
- return escape(window.btoa(url));
42
- };
43
-
44
- export const decodeConnectUrl = (encoded) => {
45
- return window.atob(unescape(encoded));
46
- };
47
-
48
- // connectUrl 对应 create token 响应数据中的 url 字段值
49
- export const parseTokenFromConnectUrl = (connectUrl) => {
50
- const connectUrlObj = new URL(connectUrl);
51
- const url = decodeURIComponent(connectUrlObj.searchParams.get('url'));
52
- const token = new URL(url).searchParams.get('_t_');
53
- return token;
54
- };
55
-
56
- /**
57
- * 获取 appInfo 的 appId
58
- * @param {{agentDid: string; publisher: string}} appInfo
59
- * @returns {string} appId
60
- */
61
- export const getAppId = (appInfo, memberAppInfo) => {
62
- // 优先读取 agentDid,在 federated 登录模式下,当前应用会被存在 agentDid 中,而 publisher 中存储的是 federated master 的 appPid
63
- let publisher = memberAppInfo?.publisher;
64
- if (!publisher) {
65
- // @deprecated 兼容原来的 agentDid 字段,新版中,将使用 memberAppInfo 来代替
66
- if (appInfo?.agentDid) {
67
- return appInfo.agentDid;
68
- }
69
- publisher = appInfo?.publisher;
70
- }
71
- if (publisher) {
72
- return publisher.replace('did:abt:', '');
73
- }
74
- return globalThis.blocklet?.appPid || globalThis.blocklet?.appId || globalThis.env?.appId || '';
75
- };
76
-
77
- export const getConnectedInfo = (data) => {
78
- const result = {
79
- connected_did: data.did || '',
80
- connected_pk: data.pk || '',
81
- connected_app: getAppId(data.appInfo, data.memberAppInfo),
82
- };
83
- if (data?.connectedWallet?.os) {
84
- result.connected_wallet_os = data.connectedWallet.os;
85
- }
86
- return result;
87
- };
88
-
89
- /**
90
- *
91
- * @param {object} connectedInfo 服务端返回的 did-connect 连接信息,可通过格式化解析后成为可以写入 cookie 的值(也可以直接传入解析后的值,但第二个参数要求填写为 true)
92
- * @param {boolean} parsed connectedInfo 是否被格式化解析过
93
- * @returns
94
- */
95
- export const updateConnectedInfo = (connectedInfo, parsed = false) => {
96
- if (!connectedInfo) return;
97
- // 如果输入的是原始数据,需要通过 getConnectedInfo 处理一下(兼容之前的调用方式)
98
- if (!parsed) {
99
- // eslint-disable-next-line no-param-reassign
100
- connectedInfo = getConnectedInfo(connectedInfo);
101
- }
102
- const cookieOptions = getCookieOptions({
103
- expireInDays: 7,
104
- returnDomain: false,
105
- });
106
- // connected_did and connected_pk are used to skip authPrincipal
107
- if (!isNil(connectedInfo.connected_did) && !isNil(connectedInfo.connected_pk)) {
108
- // NOTICE: 需要严格校验 connected_did 和 connected_pk 是否合法
109
- if (
110
- isValidDid(connectedInfo.connected_did) &&
111
- isFromPublicKey(connectedInfo.connected_did, connectedInfo.connected_pk)
112
- ) {
113
- Cookie.set('connected_did', connectedInfo.connected_did, cookieOptions);
114
- Cookie.set('connected_pk', connectedInfo.connected_pk, cookieOptions);
115
- }
116
- }
117
- // connected_app is used to check session validity
118
- if (!isNil(connectedInfo.connected_app) && isValidDid(connectedInfo.connected_app))
119
- Cookie.set('connected_app', connectedInfo.connected_app, cookieOptions);
120
- if (connectedInfo.connected_wallet_os) {
121
- Cookie.set('connected_wallet_os', connectedInfo.connected_wallet_os, cookieOptions);
122
- }
123
- };
124
-
125
- export const encodeKey = (key) => escape(Buffer.from(key).toString('base64'));
126
- export const decodeKey = (str) => Uint8Array.from(Buffer.from(unescape(str), 'base64'));
127
-
128
- export const decrypt = (value, encryptKey, decryptKey) => {
129
- const decrypted = SealedBox.open(
130
- Uint8Array.from(Buffer.from(value, 'base64')),
131
- decodeKey(encryptKey),
132
- decodeKey(decryptKey)
133
- );
134
-
135
- return JSON.parse(Buffer.from(decrypted).toString('utf8'));
136
- };
137
-
138
- export const encrypt = (value, encryptKey) => {
139
- return Buffer.from(SealedBox.seal(Uint8Array.from(Buffer.from(value)), decodeKey(encryptKey))).toString('base64');
140
- };
141
-
142
- export const parseNextWorkflow = (url, tokenKey = '_t_') => {
143
- const tmp = new URL(url);
144
- const nw = {
145
- baseUrl: tmp.origin,
146
- prefix: tmp.pathname.replace(/\/auth$/, ''),
147
- token: tmp.searchParams.get(tokenKey) || '',
148
- };
149
-
150
- if (!nw.baseUrl) {
151
- throw new Error('Invalid next workflow: origin empty');
152
- }
153
-
154
- if (!nw.token) {
155
- throw new Error('Invalid next workflow: token not found');
156
- }
157
-
158
- return nw;
159
- };
160
-
161
- export const getApiErrorMessage = (err, defaultMessage) => {
162
- let errorMessage = err.message;
163
- const { response } = err;
164
- if (response) {
165
- errorMessage = response.data?.error || response.data?.message || response.data || defaultMessage;
166
- errorMessage = typeof errorMessage === 'object' ? defaultMessage : errorMessage;
167
- }
168
- return errorMessage;
169
- };
170
-
171
- /**
172
- * Handle WebAuthn specific errors with user-friendly messages
173
- * @param {Error} err The error object from WebAuthn operations
174
- * @param {string} defaultMessage Default fallback message
175
- * @param {Function} t Translation function
176
- * @returns {string} User-friendly error message
177
- */
178
- export const getWebAuthnErrorMessage = (err, defaultMessage, t) => {
179
- if (!err) {
180
- return err;
181
- }
182
- // If it's not a WebAuthn specific error, use the general API error handler
183
- if (!err.name) {
184
- return getApiErrorMessage(err, defaultMessage);
185
- }
186
-
187
- // Handle specific WebAuthn error types
188
- switch (err.name) {
189
- case 'NotAllowedError':
190
- // User canceled the operation or it timed out
191
- return t ? t('webauthn.error.canceled') : 'Authentication was canceled';
192
- case 'SecurityError':
193
- return t ? t('webauthn.error.security') : 'A security error occurred during authentication';
194
- case 'NotSupportedError':
195
- return t ? t('webauthn.error.notSupported') : 'This browser does not support passkey authentication';
196
- case 'AbortError':
197
- return t ? t('webauthn.error.aborted') : 'Authentication was aborted';
198
- default:
199
- // For unknown error types, log the error name for debugging
200
- console.warn('Unhandled WebAuthn error type:', err.name);
201
- return getApiErrorMessage(err, defaultMessage);
202
- }
203
- };
204
-
205
- export const getExtraHeaders = (baseUrl) => {
206
- const headers = {};
207
- // 如果 baseUrl 是有效的 url,则使用 baseUrl,否则使用当前页面的 url
208
- // 避免传入的 baseUrl 是相对路径,导致 new URL 失败
209
- const authUrl = isUrl(baseUrl) ? baseUrl : window.location.href;
210
-
211
- if (authUrl) {
212
- const { hostname, protocol, port } = new URL(authUrl);
213
- headers['x-real-hostname'] = hostname;
214
- headers['x-real-port'] = port;
215
- headers['x-real-protocol'] = protocol.endsWith(':') ? protocol.substring(0, protocol.length - 1) : protocol;
216
- }
217
- return headers;
218
- };
219
-
220
- export const createAxios = (options = {}, { lazy = false, lazyTime = 300 } = {}) => {
221
- const mergedHeaders = {
222
- ...getExtraHeaders(options.baseURL),
223
- ...options.headers,
224
- 'x-did-connect-version': version,
225
- };
226
-
227
- const instance = _createAxios(
228
- {
229
- ...options,
230
- headers: mergedHeaders,
231
- },
232
- { lazy, lazyTime }
233
- );
234
- instance.interceptors.request.use((config) => {
235
- const visitorId = getVisitorId();
236
- // FIXME: @zhanghan 需要在 js-sdk 改为动态获取 visitorId 后,删除该逻辑
237
- if (visitorId) config.headers['x-blocklet-visitor-id'] = visitorId;
238
- return config;
239
- });
240
- return instance;
241
- };
242
-
243
- export const sleep = (time = 0) => {
244
- return new Promise((resolve) => {
245
- setTimeout(() => {
246
- resolve();
247
- }, time);
248
- });
249
- };
250
-
251
- export function getBrowserLang() {
252
- if (typeof window === 'undefined') {
253
- return null;
254
- }
255
-
256
- const lang =
257
- (window.navigator.languages && window.navigator.languages[0]) ||
258
- window.navigator.language ||
259
- window.navigator.browserLanguage ||
260
- window.navigator.userLanguage ||
261
- window.navigator.systemLanguage ||
262
- null;
263
-
264
- const langMap = {
265
- 'zh-CN': 'zh',
266
- 'zh-TW': 'zh',
267
- zh: 'zh',
268
- en: 'en',
269
- };
270
-
271
- return langMap[lang] || 'en';
272
- }
273
-
274
- export function formatCacheTtl(ttl, defaultVal) {
275
- if ([undefined, null, ''].includes(ttl)) {
276
- return defaultVal;
277
- }
278
- return ttl / 86400;
279
- }
280
-
281
- /**
282
- * @returns {import('./types').DIDConnectUrlOptions}
283
- */
284
- export async function decodeUrlParams() {
285
- const currentUrl = window.location.href;
286
- try {
287
- const urlInstance = new URL(currentUrl);
288
- const encodedParams = urlInstance.searchParams.get(DID_CONNECT_URL_PARAMS_NAME);
289
- if (encodedParams) {
290
- urlInstance.searchParams.delete(DID_CONNECT_URL_PARAMS_NAME);
291
- const params = JSON.parse(Buffer.from(encodedParams, 'base64').toString('utf-8'));
292
- if (isString(params.forceConnected) && isUndefined(params.sourceAppPid)) {
293
- const sdk = getBlockletSDK();
294
- const userInfo = await sdk.user.getUserPublicInfo({ did: params.forceConnected });
295
- if (!isUndefined(userInfo?.sourceAppPid)) {
296
- params.sourceAppPid = userInfo.sourceAppPid;
297
- }
298
- }
299
- return {
300
- params,
301
- url: urlInstance.href,
302
- };
303
- }
304
- } catch {
305
- console.warn('Failed to decode did-connect url params');
306
- }
307
-
308
- return {
309
- params: null,
310
- url: currentUrl,
311
- };
312
- }
313
-
314
- /**
315
- *
316
- * @param {string} url - 打开一个弹窗
317
- * @returns
318
- */
319
- export const openPopup = (
320
- _url,
321
- { width = 680, height = 720, name = 'did-connect:popup', offsetX = 0, offsetY = 0 } = {}
322
- ) => {
323
- // 需要处理为安全的 url
324
- const url = getSafeUrl(_url, { allowDomains: null });
325
-
326
- const left = window.screenX + (window.innerWidth - width) / 2 + offsetX;
327
- const top = window.screenY + (window.innerHeight - height) / 2 + offsetY;
328
-
329
- const windowFeatures = [
330
- `left=${left}`,
331
- `top=${top}`,
332
- `width=${width}`,
333
- `height=${height}`,
334
- 'resizable=no', // not working
335
- 'scrollbars=yes',
336
- 'status=yes',
337
- 'popup=yes',
338
- ];
339
-
340
- // HACK: IOS 必须以这种形式打开,才能被识别为 dialog 模式
341
- const popup = window.open('', name, windowFeatures.join(','));
342
- if (popup === null) {
343
- throw new NotOpenError();
344
- }
345
- popup.location.href = withQuery(url, {
346
- // NOTICE: 携带当前页面的 origin,用于在 popup 中通过该参数判断是否可以发送 postMessage,即使该参数被伪造,最终也只有该域名能接收到消息,所以没有关系
347
- opener: window.location.origin,
348
- });
349
- return popup;
350
- };
351
-
352
- /**
353
- * @typedef {Object} PopupConfig
354
- * @property {number} [timeoutInSeconds] - 等待弹窗响应的超时时间
355
- * @property {number} [closeTimeout] - 弹窗关闭前的等待时间
356
- * @property {any} [popup] - 弹窗的实例
357
- */
358
-
359
- /**
360
- *
361
- * @param {PopupConfig} config
362
- * @returns
363
- */
364
- export const runPopup = (config) => {
365
- return new Promise((resolve, reject) => {
366
- let popupTimer;
367
- let timeoutId;
368
- const popupEventListener = ({ data }) => {
369
- if (!data) {
370
- return;
371
- }
372
-
373
- if (data.type !== 'authorization_response') {
374
- return;
375
- }
376
-
377
- if (data?.error) {
378
- // HACK: 捕获到报错时,如果弹窗未关闭,则不应该 reject,否则调用 runPopup 的地方拿不到成功后的值
379
- console.error(data.error);
380
- return;
381
- }
382
-
383
- setTimeout(() => {
384
- config.popup?.close();
385
- // 弹窗关闭后才取消事件监听
386
- clearTimeout(timeoutId);
387
- clearInterval(popupTimer);
388
- window.removeEventListener('message', popupEventListener, false);
389
- }, config.closeTimeout || 0);
390
- // 不用等弹窗关闭,可以直接返回结果
391
- resolve(data);
392
- };
393
-
394
- timeoutId = setTimeout(
395
- () => {
396
- clearInterval(popupTimer);
397
- reject(new Error('Timeout'));
398
- window.removeEventListener('message', popupEventListener, false);
399
- },
400
- (config.timeoutInSeconds || DEFAULT_WINDOW_TIMEOUT) * 1000
401
- );
402
- popupTimer = setInterval(() => {
403
- if (config.popup?.closed) {
404
- clearInterval(popupTimer);
405
- clearTimeout(timeoutId);
406
- window.removeEventListener('message', popupEventListener, false);
407
- reject(new Error('Popup closed'));
408
- }
409
- }, 1000);
410
-
411
- window.addEventListener('message', popupEventListener);
412
- });
413
- };
package/vite.config.mjs DELETED
@@ -1,29 +0,0 @@
1
- import { defineConfig } from 'vite';
2
- import svgr from 'vite-plugin-svgr';
3
- import react from '@vitejs/plugin-react';
4
- import noBundlePlugin from 'vite-plugin-no-bundle';
5
- import fg from 'fast-glob';
6
-
7
- export default defineConfig({
8
- plugins: [
9
- react({ jsxRuntime: 'automatic' }),
10
- svgr({
11
- include: ['**/*.svg', '**/*.svg?react'],
12
- }),
13
- noBundlePlugin({
14
- root: 'src',
15
- copy: ['**/*.png', '**/*.gif', '**/*.jpg', '**/*.jpeg', '**/*.d.ts'],
16
- }),
17
- ],
18
- build: {
19
- lib: {
20
- entry: fg.sync('src/**/*.{tsx,ts,jsx,js}', {
21
- ignore: ['**/stories/**', '**/demo/**', '**/*.d.ts', '**/*.stories.*'],
22
- }),
23
- formats: ['es'],
24
- fileName: (format, entryName) => `${entryName}.js`,
25
- },
26
- outDir: 'lib',
27
- emptyOutDir: true,
28
- },
29
- });