@arcblock/did-connect-react 3.1.40 → 3.1.42

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 (81) hide show
  1. package/.aigne/doc-smith/config.yaml +83 -0
  2. package/.aigne/doc-smith/output/structure-plan.json +197 -0
  3. package/.aigne/doc-smith/upload-cache.yaml +168 -0
  4. package/docs/_sidebar.md +18 -0
  5. package/docs/advanced-authentication-methods.ja.md +261 -0
  6. package/docs/advanced-authentication-methods.md +261 -0
  7. package/docs/advanced-authentication-methods.zh-TW.md +261 -0
  8. package/docs/advanced-authentication-methods.zh.md +261 -0
  9. package/docs/advanced-utilities.ja.md +132 -0
  10. package/docs/advanced-utilities.md +132 -0
  11. package/docs/advanced-utilities.zh-TW.md +132 -0
  12. package/docs/advanced-utilities.zh.md +132 -0
  13. package/docs/advanced.ja.md +95 -0
  14. package/docs/advanced.md +95 -0
  15. package/docs/advanced.zh-TW.md +95 -0
  16. package/docs/advanced.zh.md +95 -0
  17. package/docs/api-reference.ja.md +178 -0
  18. package/docs/api-reference.md +178 -0
  19. package/docs/api-reference.zh-TW.md +178 -0
  20. package/docs/api-reference.zh.md +178 -0
  21. package/docs/core-components-did-connect.ja.md +214 -0
  22. package/docs/core-components-did-connect.md +213 -0
  23. package/docs/core-components-did-connect.zh-TW.md +214 -0
  24. package/docs/core-components-did-connect.zh.md +213 -0
  25. package/docs/core-components-session-provider.ja.md +239 -0
  26. package/docs/core-components-session-provider.md +239 -0
  27. package/docs/core-components-session-provider.zh-TW.md +239 -0
  28. package/docs/core-components-session-provider.zh.md +239 -0
  29. package/docs/core-components.ja.md +16 -0
  30. package/docs/core-components.md +16 -0
  31. package/docs/core-components.zh-TW.md +16 -0
  32. package/docs/core-components.zh.md +16 -0
  33. package/docs/getting-started.ja.md +138 -0
  34. package/docs/getting-started.md +138 -0
  35. package/docs/getting-started.zh-TW.md +138 -0
  36. package/docs/getting-started.zh.md +138 -0
  37. package/docs/hooks-use-connect.ja.md +214 -0
  38. package/docs/hooks-use-connect.md +214 -0
  39. package/docs/hooks-use-connect.zh-TW.md +214 -0
  40. package/docs/hooks-use-connect.zh.md +214 -0
  41. package/docs/hooks-use-did.ja.md +107 -0
  42. package/docs/hooks-use-did.md +107 -0
  43. package/docs/hooks-use-did.zh-TW.md +107 -0
  44. package/docs/hooks-use-did.zh.md +107 -0
  45. package/docs/hooks-use-oauth-passkey.ja.md +188 -0
  46. package/docs/hooks-use-oauth-passkey.md +188 -0
  47. package/docs/hooks-use-oauth-passkey.zh-TW.md +188 -0
  48. package/docs/hooks-use-oauth-passkey.zh.md +188 -0
  49. package/docs/hooks.ja.md +23 -0
  50. package/docs/hooks.md +23 -0
  51. package/docs/hooks.zh-TW.md +23 -0
  52. package/docs/hooks.zh.md +23 -0
  53. package/docs/overview.ja.md +159 -0
  54. package/docs/overview.md +159 -0
  55. package/docs/overview.zh-TW.md +159 -0
  56. package/docs/overview.zh.md +160 -0
  57. package/docs/ui-components-address.ja.md +121 -0
  58. package/docs/ui-components-address.md +121 -0
  59. package/docs/ui-components-address.zh-TW.md +121 -0
  60. package/docs/ui-components-address.zh.md +121 -0
  61. package/docs/ui-components-avatar.ja.md +65 -0
  62. package/docs/ui-components-avatar.md +65 -0
  63. package/docs/ui-components-avatar.zh-TW.md +65 -0
  64. package/docs/ui-components-avatar.zh.md +65 -0
  65. package/docs/ui-components-button.ja.md +99 -0
  66. package/docs/ui-components-button.md +99 -0
  67. package/docs/ui-components-button.zh-TW.md +99 -0
  68. package/docs/ui-components-button.zh.md +99 -0
  69. package/docs/ui-components-logo.ja.md +52 -0
  70. package/docs/ui-components-logo.md +52 -0
  71. package/docs/ui-components-logo.zh-TW.md +52 -0
  72. package/docs/ui-components-logo.zh.md +52 -0
  73. package/docs/ui-components.ja.md +57 -0
  74. package/docs/ui-components.md +57 -0
  75. package/docs/ui-components.zh-TW.md +57 -0
  76. package/docs/ui-components.zh.md +57 -0
  77. package/glossary.md +1 -0
  78. package/lib/package.json.js +1 -1
  79. package/package.json +5 -5
  80. package/src/Session/hooks/use-federated.js +3 -0
  81. package/src/Session/libs/federated.js +3 -0
@@ -0,0 +1,132 @@
1
+ # Utilities
2
+
3
+ The `@arcblock/did-connect-react` library exports a collection of utility functions designed to simplify common tasks related to authentication flows, data handling, and API communication. While the core components and hooks handle most use cases, these utilities offer granular control for advanced integrations or custom implementations.
4
+
5
+ ## API Client
6
+
7
+ ### createAxios
8
+
9
+ This function is a factory for creating a pre-configured `axios` instance. It automatically includes essential headers like `x-did-connect-version` and `x-blocklet-visitor-id`, ensuring proper communication with Blocklet-based services. It's the recommended way to create API clients in your application.
10
+
11
+ **Parameters**
12
+
13
+ <x-field-group>
14
+ <x-field data-name="options" data-type="object" data-required="false" data-desc="Standard Axios configuration object."></x-field>
15
+ <x-field data-name="lazyOptions" data-type="object" data-required="false" data-desc="Configuration for lazy sending.">
16
+ <x-field data-name="lazy" data-type="boolean" data-default="false" data-desc="Whether to enable lazy sending."></x-field>
17
+ <x-field data-name="lazyTime" data-type="number" data-default="300" data-desc="The debounce time in milliseconds for lazy sending."></x-field>
18
+ </x-field>
19
+ </x-field-group>
20
+
21
+ **Returns**
22
+
23
+ <x-field data-name="axiosInstance" data-type="AxiosInstance" data-desc="A configured instance of Axios."></x-field>
24
+
25
+ **Example**
26
+
27
+ ```javascript apiClient.js icon=logos:javascript
28
+ import { createAxios } from '@arcblock/did-connect-react/lib/utils';
29
+
30
+ const apiClient = createAxios({
31
+ baseURL: '/api',
32
+ });
33
+
34
+ export default apiClient;
35
+ ```
36
+
37
+ ## URL and Popup Handling
38
+
39
+ These functions help manage the URLs and popup windows used during the DID Connect authentication process.
40
+
41
+ | Function | Description |
42
+ | :--- | :--- |
43
+ | `encodeConnectUrl(url)` | Encodes a URL to be safely passed as a `__connect_url__` query parameter. |
44
+ | `decodeConnectUrl(encoded)` | Decodes a URL that was encoded with `encodeConnectUrl`. |
45
+ | `parseTokenFromConnectUrl(connectUrl)` | Extracts the session token (`_t_`) from a DID Connect URL. |
46
+ | `openPopup(url, options)` | Opens a new, centered popup window. It's used internally by the `DidConnect` component to display the wallet connection interface. Throws a `NotOpenError` if the popup is blocked. |
47
+ | `runPopup(config)` | A promise-based wrapper that manages the lifecycle of a popup created with `openPopup`. It listens for `message` events from the popup, handles timeouts, and resolves when the authentication flow is complete. |
48
+ | `decodeUrlParams()` | Parses custom `__did-connect__` parameters from the current window's URL. |
49
+
50
+ **Example: Custom Popup Flow**
51
+
52
+ ```javascript customAuthButton.js icon=logos:javascript
53
+ import { openPopup, runPopup } from '@arcblock/did-connect-react/lib/utils';
54
+
55
+ const handleCustomLogin = async () => {
56
+ const authUrl = 'https://your-auth-service.com/connect';
57
+ try {
58
+ const popup = openPopup(authUrl);
59
+ const result = await runPopup({ popup, timeoutInSeconds: 600 });
60
+ console.log('Authentication successful:', result);
61
+ // Handle successful login
62
+ } catch (error) {
63
+ console.error('Authentication failed:', error.message);
64
+ // Handle popup closed or timeout
65
+ }
66
+ };
67
+ ```
68
+
69
+ ## Session and Cookie Management
70
+
71
+ These helpers are used to read and write user connection information to cookies, enabling session persistence across page loads.
72
+
73
+ | Function | Description |
74
+ | :--- | :--- |
75
+ | `getConnectedInfo(data)` | Formats the raw response data from a connection request into a standardized object suitable for cookie storage. |
76
+ | `updateConnectedInfo(info, parsed)` | Sets the necessary cookies (`connected_did`, `connected_pk`, `connected_app`) after a successful connection. This allows the library to optimize subsequent authentication checks. |
77
+ | `getVisitorId()` | Retrieves the unique visitor ID from cookies. |
78
+ | `setVisitorId(id)` | Sets the unique visitor ID in cookies. |
79
+
80
+ **Example**
81
+
82
+ ```javascript sessionManager.js icon=logos:javascript
83
+ import { getConnectedInfo, updateConnectedInfo } from '@arcblock/did-connect-react/lib/utils';
84
+
85
+ // Assuming 'authResponse' is the object returned from your login API
86
+ function persistSession(authResponse) {
87
+ const connectedInfo = getConnectedInfo(authResponse);
88
+ updateConnectedInfo(connectedInfo, true);
89
+ console.log('Session info saved to cookies.');
90
+ }
91
+ ```
92
+
93
+ ## Encryption Utilities
94
+
95
+ For advanced scenarios requiring client-side encryption or decryption, the library exposes helpers that wrap the `tweetnacl-sealedbox-js` library.
96
+
97
+ | Function | Description |
98
+ | :--- | :--- |
99
+ | `encodeKey(key)` | Base64URL encodes a key for transmission. |
100
+ | `decodeKey(str)` | Decodes a Base64URL string into a `Uint8Array` key. |
101
+ | `encrypt(value, encryptKey)` | Encrypts a string value using a public key. |
102
+ | `decrypt(value, encryptKey, decryptKey)` | Decrypts a base64 string using the corresponding public and private keys. |
103
+
104
+ ## Error Handling
105
+
106
+ To provide better feedback to users, you can use these functions to parse technical error objects into human-readable messages.
107
+
108
+ | Function | Description |
109
+ | :--- | :--- |
110
+ | `getApiErrorMessage(err, defaultMessage)` | Extracts a user-friendly error message from an `axios` error object. |
111
+ | `getWebAuthnErrorMessage(err, defaultMessage, t)` | Handles WebAuthn/Passkey specific errors (e.g., user cancellation, browser not supported) and returns localized, user-friendly messages. |
112
+
113
+ **Example**
114
+
115
+ ```javascript errorHandling.js icon=logos:javascript
116
+ import { getApiErrorMessage } from '@arcblock/did-connect-react/lib/utils';
117
+ import apiClient from './apiClient';
118
+
119
+ async function fetchData() {
120
+ try {
121
+ const response = await apiClient.get('/data');
122
+ return response.data;
123
+ } catch (error) {
124
+ const message = getApiErrorMessage(error, 'Failed to fetch data.');
125
+ alert(message);
126
+ }
127
+ }
128
+ ```
129
+
130
+ ---
131
+
132
+ By leveraging these utilities, you can build more complex and customized authentication experiences. For a complete list of all exported members and their types, please refer to the [API Reference](./api-reference.md).
@@ -0,0 +1,132 @@
1
+ # 工具程式
2
+
3
+ `@arcblock/did-connect-react` 函式庫匯出了一系列工具函式,旨在簡化與身份驗證流程、資料處理和 API 通訊相關的常見任務。雖然核心元件和掛鉤(hooks)處理了大多數使用情境,但這些工具程式為進階整合或自訂實作提供了精細的控制。
4
+
5
+ ## API 客戶端
6
+
7
+ ### createAxios
8
+
9
+ 此函式是一個用於建立預先設定的 `axios` 實例的工廠。它會自動包含必要的標頭,如 `x-did-connect-version` 和 `x-blocklet-visitor-id`,以確保與基於 Blocklet 的服務正常通訊。這是您應用程式中建立 API 客戶端的建議方法。
10
+
11
+ **參數**
12
+
13
+ <x-field-group>
14
+ <x-field data-name="options" data-type="object" data-required="false" data-desc="標準的 Axios 設定物件。"></x-field>
15
+ <x-field data-name="lazyOptions" data-type="object" data-required="false" data-desc="延遲發送的設定。">
16
+ <x-field data-name="lazy" data-type="boolean" data-default="false" data-desc="是否啟用延遲發送。"></x-field>
17
+ <x-field data-name="lazyTime" data-type="number" data-default="300" data-desc="延遲發送的去抖動時間(毫秒)。"></x-field>
18
+ </x-field>
19
+ </x-field-group>
20
+
21
+ **回傳值**
22
+
23
+ <x-field data-name="axiosInstance" data-type="AxiosInstance" data-desc="一個已設定的 Axios 實例。"></x-field>
24
+
25
+ **範例**
26
+
27
+ ```javascript apiClient.js icon=logos:javascript
28
+ import { createAxios } from '@arcblock/did-connect-react/lib/utils';
29
+
30
+ const apiClient = createAxios({
31
+ baseURL: '/api',
32
+ });
33
+
34
+ export default apiClient;
35
+ ```
36
+
37
+ ## URL 和彈出視窗處理
38
+
39
+ 這些函式有助於管理在 DID Connect 身份驗證過程中使用的 URL 和彈出視窗。
40
+
41
+ | 函式 | 說明 |
42
+ | :--- | :--- |
43
+ | `encodeConnectUrl(url)` | 將 URL 編碼,以便安全地作為 `__connect_url__` 查詢參數傳遞。 |
44
+ | `decodeConnectUrl(encoded)` | 解碼由 `encodeConnectUrl` 編碼的 URL。 |
45
+ | `parseTokenFromConnectUrl(connectUrl)` | 從 DID Connect URL 中提取會話權杖 (`_t_`)。 |
46
+ | `openPopup(url, options)` | 開啟一個新的、置中的彈出視窗。`DidConnect` 元件內部使用它來顯示錢包連接介面。如果彈出視窗被阻擋,則會拋出 `NotOpenError`。 |
47
+ | `runPopup(config)` | 一個基於 promise 的包裝器,用於管理由 `openPopup` 建立的彈出視窗的生命週期。它監聽來自彈出視窗的 `message` 事件,處理超時,並在身份驗證流程完成時解析。 |
48
+ | `decodeUrlParams()` | 從當前視窗的 URL 中解析自訂的 `__did-connect__` 參數。 |
49
+
50
+ **範例:自訂彈出視窗流程**
51
+
52
+ ```javascript customAuthButton.js icon=logos:javascript
53
+ import { openPopup, runPopup } from '@arcblock/did-connect-react/lib/utils';
54
+
55
+ const handleCustomLogin = async () => {
56
+ const authUrl = 'https://your-auth-service.com/connect';
57
+ try {
58
+ const popup = openPopup(authUrl);
59
+ const result = await runPopup({ popup, timeoutInSeconds: 600 });
60
+ console.log('Authentication successful:', result);
61
+ // Handle successful login
62
+ } catch (error) {
63
+ console.error('Authentication failed:', error.message);
64
+ // Handle popup closed or timeout
65
+ }
66
+ };
67
+ ```
68
+
69
+ ## 會話和 Cookie 管理
70
+
71
+ 這些輔助函式用於將使用者連接資訊讀寫到 Cookie,從而實現跨頁面載入的會話持久性。
72
+
73
+ | 函式 | 說明 |
74
+ | :--- | :--- |
75
+ | `getConnectedInfo(data)` | 將來自連接請求的原始回應資料格式化為適合 Cookie 儲存的標準化物件。 |
76
+ | `updateConnectedInfo(info, parsed)` | 在成功連接後設定必要的 Cookie (`connected_did`, `connected_pk`, `connected_app`)。這讓函式庫可以優化後續的身份驗證檢查。 |
77
+ | `getVisitorId()` | 從 Cookie 中檢索唯一訪客 ID。 |
78
+ | `setVisitorId(id)` | 在 Cookie 中設定唯一訪客 ID。 |
79
+
80
+ **範例**
81
+
82
+ ```javascript sessionManager.js icon=logos:javascript
83
+ import { getConnectedInfo, updateConnectedInfo } from '@arcblock/did-connect-react/lib/utils';
84
+
85
+ // Assuming 'authResponse' is the object returned from your login API
86
+ function persistSession(authResponse) {
87
+ const connectedInfo = getConnectedInfo(authResponse);
88
+ updateConnectedInfo(connectedInfo, true);
89
+ console.log('Session info saved to cookies.');
90
+ }
91
+ ```
92
+
93
+ ## 加密工具
94
+
95
+ 對於需要客戶端加密或解密的進階情境,該函式庫公開了包裝 `tweetnacl-sealedbox-js` 函式庫的輔助函式。
96
+
97
+ | 函式 | 說明 |
98
+ | :--- | :--- |
99
+ | `encodeKey(key)` | 將金鑰進行 Base64URL 編碼以便傳輸。 |
100
+ | `decodeKey(str)` | 將 Base64URL 字串解碼為 `Uint8Array` 金鑰。 |
101
+ | `encrypt(value, encryptKey)` | 使用公鑰加密字串值。 |
102
+ | `decrypt(value, encryptKey, decryptKey)` | 使用對應的公鑰和私鑰解密 base64 字串。 |
103
+
104
+ ## 錯誤處理
105
+
106
+ 為了向使用者提供更好的回饋,您可以使用這些函式將技術性錯誤物件解析為人類可讀的訊息。
107
+
108
+ | 函式 | 說明 |
109
+ | :--- | :--- |
110
+ | `getApiErrorMessage(err, defaultMessage)` | 從 `axios` 錯誤物件中提取使用者友善的錯誤訊息。 |
111
+ | `getWebAuthnErrorMessage(err, defaultMessage, t)` | 處理 WebAuthn/Passkey 特定錯誤(例如,使用者取消、瀏覽器不支援),並回傳本地化的、使用者友善的訊息。 |
112
+
113
+ **範例**
114
+
115
+ ```javascript errorHandling.js icon=logos:javascript
116
+ import { getApiErrorMessage } from '@arcblock/did-connect-react/lib/utils';
117
+ import apiClient from './apiClient';
118
+
119
+ async function fetchData() {
120
+ try {
121
+ const response = await apiClient.get('/data');
122
+ return response.data;
123
+ } catch (error) {
124
+ const message = getApiErrorMessage(error, 'Failed to fetch data.');
125
+ alert(message);
126
+ }
127
+ }
128
+ ```
129
+
130
+ ---
131
+
132
+ 透過利用這些工具程式,您可以建立更複雜和自訂的身份驗證體驗。有關所有匯出成員及其類型的完整列表,請參閱 [API 參考](./api-reference.md)。
@@ -0,0 +1,132 @@
1
+ # 工具函数
2
+
3
+ `@arcblock/did-connect-react` 库导出了一系列工具函数,旨在简化与身份验证流程、数据处理和 API 通信相关的常见任务。虽然核心组件和钩子处理了大多数用例,但这些工具为高级集成或自定义实现提供了精细的控制。
4
+
5
+ ## API 客户端
6
+
7
+ ### createAxios
8
+
9
+ 该函数是一个用于创建预配置 `axios` 实例的工厂。它会自动包含必要的头信息,如 `x-did-connect-version` 和 `x-blocklet-visitor-id`,以确保与基于 Blocklet 的服务正常通信。这是在你的应用程序中创建 API 客户端的推荐方法。
10
+
11
+ **参数**
12
+
13
+ <x-field-group>
14
+ <x-field data-name="options" data-type="object" data-required="false" data-desc="标准的 Axios 配置对象。"></x-field>
15
+ <x-field data-name="lazyOptions" data-type="object" data-required="false" data-desc="懒发送的配置。">
16
+ <x-field data-name="lazy" data-type="boolean" data-default="false" data-desc="是否启用懒发送。"></x-field>
17
+ <x-field data-name="lazyTime" data-type="number" data-default="300" data-desc="懒发送的防抖时间(毫秒)。"></x-field>
18
+ </x-field>
19
+ </x-field-group>
20
+
21
+ **返回值**
22
+
23
+ <x-field data-name="axiosInstance" data-type="AxiosInstance" data-desc="一个已配置的 Axios 实例。"></x-field>
24
+
25
+ **示例**
26
+
27
+ ```javascript apiClient.js icon=logos:javascript
28
+ import { createAxios } from '@arcblock/did-connect-react/lib/utils';
29
+
30
+ const apiClient = createAxios({
31
+ baseURL: '/api',
32
+ });
33
+
34
+ export default apiClient;
35
+ ```
36
+
37
+ ## URL 和弹窗处理
38
+
39
+ 这些函数帮助管理在 DID Connect 身份验证过程中使用的 URL 和弹窗。
40
+
41
+ | 函数 | 描述 |
42
+ | :--- | :--- |
43
+ | `encodeConnectUrl(url)` | 对 URL 进行编码,以便安全地作为 `__connect_url__` 查询参数传递。 |
44
+ | `decodeConnectUrl(encoded)` | 解码由 `encodeConnectUrl` 编码的 URL。 |
45
+ | `parseTokenFromConnectUrl(connectUrl)` | 从 DID Connect URL 中提取会话令牌 (`_t_`)。 |
46
+ | `openPopup(url, options)` | 打开一个新的、居中的弹窗。它由 `DidConnect` 组件内部使用,以显示钱包连接界面。如果弹窗被阻止,则会抛出 `NotOpenError`。 |
47
+ | `runPopup(config)` | 一个基于 Promise 的包装器,用于管理由 `openPopup` 创建的弹窗的生命周期。它监听来自弹窗的 `message` 事件,处理超时,并在身份验证流程完成时解析。 |
48
+ | `decodeUrlParams()` | 从当前窗口的 URL 中解析自定义的 `__did-connect__` 参数。 |
49
+
50
+ **示例:自定义弹窗流程**
51
+
52
+ ```javascript customAuthButton.js icon=logos:javascript
53
+ import { openPopup, runPopup } from '@arcblock/did-connect-react/lib/utils';
54
+
55
+ const handleCustomLogin = async () => {
56
+ const authUrl = 'https://your-auth-service.com/connect';
57
+ try {
58
+ const popup = openPopup(authUrl);
59
+ const result = await runPopup({ popup, timeoutInSeconds: 600 });
60
+ console.log('Authentication successful:', result);
61
+ // Handle successful login
62
+ } catch (error) {
63
+ console.error('Authentication failed:', error.message);
64
+ // Handle popup closed or timeout
65
+ }
66
+ };
67
+ ```
68
+
69
+ ## 会话和 Cookie 管理
70
+
71
+ 这些辅助函数用于向 Cookie 读写用户连接信息,从而实现跨页面加载的会话持久性。
72
+
73
+ | 函数 | 描述 |
74
+ | :--- | :--- |
75
+ | `getConnectedInfo(data)` | 将连接请求的原始响应数据格式化为适合 Cookie 存储的标准化对象。 |
76
+ | `updateConnectedInfo(info, parsed)` | 在成功连接后设置必要的 Cookie (`connected_did`, `connected_pk`, `connected_app`)。这使得库可以优化后续的身份验证检查。 |
77
+ | `getVisitorId()` | 从 Cookie 中检索唯一访客 ID。 |
78
+ | `setVisitorId(id)` | 在 Cookie 中设置唯一访客 ID。 |
79
+
80
+ **示例**
81
+
82
+ ```javascript sessionManager.js icon=logos:javascript
83
+ import { getConnectedInfo, updateConnectedInfo } from '@arcblock/did-connect-react/lib/utils';
84
+
85
+ // Assuming 'authResponse' is the object returned from your login API
86
+ function persistSession(authResponse) {
87
+ const connectedInfo = getConnectedInfo(authResponse);
88
+ updateConnectedInfo(connectedInfo, true);
89
+ console.log('Session info saved to cookies.');
90
+ }
91
+ ```
92
+
93
+ ## 加密工具
94
+
95
+ 对于需要客户端加密或解密的高级场景,该库公开了包装 `tweetnacl-sealedbox-js` 库的辅助函数。
96
+
97
+ | 函数 | 描述 |
98
+ | :--- | :--- |
99
+ | `encodeKey(key)` | 对密钥进行 Base64URL 编码以便传输。 |
100
+ | `decodeKey(str)` | 将 Base64URL 字符串解码为 `Uint8Array` 密钥。 |
101
+ | `encrypt(value, encryptKey)` | 使用公钥加密字符串值。 |
102
+ | `decrypt(value, encryptKey, decryptKey)` | 使用相应的公钥和私钥解密 base64 字符串。 |
103
+
104
+ ## 错误处理
105
+
106
+ 为了向用户提供更好的反馈,你可以使用这些函数将技术性错误对象解析为人类可读的消息。
107
+
108
+ | 函数 | 描述 |
109
+ | :--- | :--- |
110
+ | `getApiErrorMessage(err, defaultMessage)` | 从 `axios` 错误对象中提取用户友好的错误消息。 |
111
+ | `getWebAuthnErrorMessage(err, defaultMessage, t)` | 处理 WebAuthn/Passkey 特定错误(例如,用户取消、浏览器不支持),并返回本地化的、用户友好的消息。 |
112
+
113
+ **示例**
114
+
115
+ ```javascript errorHandling.js icon=logos:javascript
116
+ import { getApiErrorMessage } from '@arcblock/did-connect-react/lib/utils';
117
+ import apiClient from './apiClient';
118
+
119
+ async function fetchData() {
120
+ try {
121
+ const response = await apiClient.get('/data');
122
+ return response.data;
123
+ } catch (error) {
124
+ const message = getApiErrorMessage(error, 'Failed to fetch data.');
125
+ alert(message);
126
+ }
127
+ }
128
+ ```
129
+
130
+ ---
131
+
132
+ 通过利用这些工具,你可以构建更复杂和定制化的身份验证体验。有关所有导出成员及其类型的完整列表,请参阅 [API 参考](./api-reference.md)。
@@ -0,0 +1,95 @@
1
+ # 高度なトピック
2
+
3
+ `SessionProvider`や`DidConnect`のようなコアコンポーネントに慣れたら、`@arcblock/did-connect-react`ライブラリのより強力で柔軟な機能を探索する準備が整います。このセクションでは、より洗練され、堅牢で、ユーザーフレンドリーな分散型アイデンティティアプリケーションを構築するための高度なトピックを扱います。
4
+
5
+ 3つの主要な分野を探求します:
6
+
7
+ 1. **代替認証方法**:デフォルトのQRコードスキャンを超えて、OAuth(ソーシャルログイン)、パスキー(パスワードレス)、およびフェデレーションログインなどの一般的なログイン方法を統合します。
8
+ 2. **ユーティリティ関数**:URLエンコーディング、APIクライアントの作成、ポップアップの管理などの一般的なタスクを処理するための一連のヘルパー関数を活用します。
9
+ 3. **エラーハンドリング**:ブロックされたポップアップからWebAuthn APIの失敗まで、一般的なエラーを適切に処理する方法を学び、スムーズなユーザーエクスペリエンスを確保します。
10
+
11
+ ---
12
+
13
+ ## 認証方法
14
+
15
+ DID Connectが主要な認証方法ですが、このライブラリは他の一般的なログインフローとのシームレスな統合を提供します。これにより、ユーザーに複数のサインイン方法を提供し、さまざまな好みやセキュリティレベルに対応できます。
16
+
17
+ <x-card data-title="認証方法を探る" data-icon="lucide:key-round" data-href="/advanced/authentication-methods" data-cta="詳しく見る">
18
+ アプリケーション内でOAuth(ソーシャルログイン)、パスキー(パスワードレス)、およびフェデレーションログインを実装するための詳細なガイドに飛び込みます。
19
+ </x-card>
20
+
21
+ ## ユーティリティ
22
+
23
+ このライブラリは、一般的なタスクを簡素化し、アプリケーションの定型コードを削減するために設計されたユーティリティ関数のコレクションをエクスポートします。これらのヘルパーは、データエンコーディングや暗号化操作から、認証フローのためのブラウザポップアップの管理まで、すべてをカバーします。
24
+
25
+ <x-card data-title="ユーティリティ関数を閲覧する" data-icon="lucide:wrench" data-href="/advanced/utilities" data-cta="リファレンスを見る">
26
+ URL操作、APIクライアント作成、データ暗号化などの例を含む、すべてのヘルパー関数の包括的なリファレンスをご覧ください。
27
+ </x-card>
28
+
29
+ ## エラーハンドリング
30
+
31
+ 堅牢なアプリケーションを構築するには、適切なエラーハンドリングが必要です。`@arcblock/did-connect-react`ライブラリは、このプロセスを容易にするために、特定のエラータイプとヘルパー関数を提供します。
32
+
33
+ ### ポップアップエラー
34
+
35
+ OAuthのようなポップアップウィンドウを必要とする認証方法を使用する場合、ブラウザのポップアップブロッカーが干渉する可能性があります。`openPopup`関数は、ウィンドウを開くのに失敗した場合に`NotOpenError`をスローします。このエラーをキャッチし、ユーザーに適切なフィードバックを提供する必要があります。
36
+
37
+ ```javascript ポップアップエラーの処理 icon=logos:javascript
38
+ import { openPopup, runPopup } from '@arcblock/did-connect-react/lib/utils';
39
+ import { NotOpenError } from '@arcblock/did-connect-react/lib/error';
40
+
41
+ async function startOAuthFlow(url) {
42
+ try {
43
+ const popup = openPopup(url);
44
+ const result = await runPopup({ popup });
45
+ console.log('OAuth成功:', result);
46
+ } catch (err) {
47
+ if (err instanceof NotOpenError) {
48
+ alert('ポップアップがブロックされました。このサイトのポップアップを許可して、もう一度お試しください。');
49
+ } else {
50
+ alert(`エラーが発生しました: ${err.message}`);
51
+ }
52
+ }
53
+ }
54
+ ```
55
+
56
+ ### APIおよびWebAuthnエラー
57
+
58
+ バックエンドサービスやWebAuthn API(パスキーで使用)とのやり取りのために、このライブラリは複雑なエラーオブジェクトをユーザーフレンドリーなメッセージに解析するためのヘルパー関数を提供します。
59
+
60
+ - `getApiErrorMessage(err, defaultMessage)`:Axiosエラーレスポンスからエラーメッセージを抽出します。
61
+ - `getWebAuthnErrorMessage(err, defaultMessage, t)`:WebAuthn固有のエラー(例:ユーザーによるキャンセル、サポートされていないブラウザ)を処理し、翻訳可能でユーザーフレンドリーなメッセージを提供します。
62
+
63
+ ```javascript WebAuthnエラーの処理 icon=logos:javascript
64
+ import { usePasskey } from '@arcblock/did-connect-react';
65
+ import { getWebAuthnErrorMessage } from '@arcblock/did-connect-react/lib/utils';
66
+
67
+ function PasskeyLoginButton() {
68
+ const { loginWithPasskey } = usePasskey();
69
+
70
+ const handleLogin = async () => {
71
+ try {
72
+ await loginWithPasskey();
73
+ // ログイン成功時の処理
74
+ } catch (err) {
75
+ // ユーティリティを使用してユーザーフレンドリーなメッセージを取得
76
+ const friendlyMessage = getWebAuthnErrorMessage(err, '不明なエラーが発生しました。');
77
+ alert(friendlyMessage);
78
+ }
79
+ };
80
+
81
+ return <button onClick={handleLogin}>パスキーでログイン</button>;
82
+ }
83
+ ```
84
+
85
+ 適切なエラーハンドリングを実装することで、計画通りに進まなかった場合のユーザーエクスペリエンスを大幅に向上させることができます。
86
+
87
+ ---
88
+
89
+ ## 次のステップ
90
+
91
+ 高度な機能の概要を理解したところで、あなたのプロジェクトに最も関連のあるトピックをさらに深く掘り下げることができます。
92
+
93
+ - **[認証方法](./advanced-authentication-methods.md)**:ユーザーがログインするための新しい方法を実装します。
94
+ - **[ユーティリティ](./advanced-utilities.md)**:ヘルパー関数でコードを効率化します。
95
+ - **[APIリファレンス](./api-reference.md)**:すべてのコンポーネント、フック、関数の完全で詳細な情報を取得します。
@@ -0,0 +1,95 @@
1
+ # Advanced Topics
2
+
3
+ Once you are comfortable with the core components like `SessionProvider` and `DidConnect`, you're ready to explore the more powerful and flexible features of the `@arcblock/did-connect-react` library. This section covers advanced subjects that allow you to build more sophisticated, robust, and user-friendly decentralized identity applications.
4
+
5
+ We will explore three main areas:
6
+
7
+ 1. **Alternative Authentication Methods**: Go beyond the default QR code scan and integrate popular login methods like OAuth (social login), Passkeys (passwordless), and Federated Login.
8
+ 2. **Utility Functions**: Leverage a suite of helper functions to handle common tasks such as URL encoding, creating API clients, and managing popups.
9
+ 3. **Error Handling**: Learn how to gracefully handle common errors, from blocked popups to WebAuthn API failures, ensuring a smooth user experience.
10
+
11
+ ---
12
+
13
+ ## Authentication Methods
14
+
15
+ While DID Connect is the primary authentication method, the library provides seamless integration with other popular login flows. This allows you to offer users multiple ways to sign in, catering to different preferences and security levels.
16
+
17
+ <x-card data-title="Explore Authentication Methods" data-icon="lucide:key-round" data-href="/advanced/authentication-methods" data-cta="Learn More">
18
+ Dive into detailed guides for implementing OAuth (social login), Passkeys (passwordless), and Federated Login within your application.
19
+ </x-card>
20
+
21
+ ## Utilities
22
+
23
+ The library exports a collection of utility functions designed to simplify common tasks and reduce boilerplate code in your application. These helpers cover everything from data encoding and cryptographic operations to managing browser popups for authentication flows.
24
+
25
+ <x-card data-title="Browse Utility Functions" data-icon="lucide:wrench" data-href="/advanced/utilities" data-cta="View Reference">
26
+ Discover a comprehensive reference for all helper functions, including examples for URL manipulation, API client creation, data encryption, and more.
27
+ </x-card>
28
+
29
+ ## Error Handling
30
+
31
+ Building a robust application requires graceful error handling. The `@arcblock/did-connect-react` library provides specific error types and helper functions to make this process easier.
32
+
33
+ ### Popup Errors
34
+
35
+ When using authentication methods that require a popup window (like OAuth), the browser's popup blocker might interfere. The `openPopup` function will throw a `NotOpenError` if it fails to open the window. You should catch this error and provide appropriate feedback to the user.
36
+
37
+ ```javascript Handling Popup Errors icon=logos:javascript
38
+ import { openPopup, runPopup } from '@arcblock/did-connect-react/lib/utils';
39
+ import { NotOpenError } from '@arcblock/did-connect-react/lib/error';
40
+
41
+ async function startOAuthFlow(url) {
42
+ try {
43
+ const popup = openPopup(url);
44
+ const result = await runPopup({ popup });
45
+ console.log('OAuth successful:', result);
46
+ } catch (err) {
47
+ if (err instanceof NotOpenError) {
48
+ alert('Popup was blocked. Please allow popups for this site and try again.');
49
+ } else {
50
+ alert(`An error occurred: ${err.message}`);
51
+ }
52
+ }
53
+ }
54
+ ```
55
+
56
+ ### API and WebAuthn Errors
57
+
58
+ For interactions with backend services or WebAuthn APIs (used by Passkeys), the library provides helper functions to parse complex error objects into user-friendly messages.
59
+
60
+ - `getApiErrorMessage(err, defaultMessage)`: Extracts an error message from an Axios error response.
61
+ - `getWebAuthnErrorMessage(err, defaultMessage, t)`: Handles WebAuthn-specific errors (e.g., user cancellation, unsupported browser) and provides translatable, user-friendly messages.
62
+
63
+ ```javascript Handling WebAuthn Errors icon=logos:javascript
64
+ import { usePasskey } from '@arcblock/did-connect-react';
65
+ import { getWebAuthnErrorMessage } from '@arcblock/did-connect-react/lib/utils';
66
+
67
+ function PasskeyLoginButton() {
68
+ const { loginWithPasskey } = usePasskey();
69
+
70
+ const handleLogin = async () => {
71
+ try {
72
+ await loginWithPasskey();
73
+ // Handle successful login
74
+ } catch (err) {
75
+ // Use the utility to get a user-friendly message
76
+ const friendlyMessage = getWebAuthnErrorMessage(err, 'An unknown error occurred.');
77
+ alert(friendlyMessage);
78
+ }
79
+ };
80
+
81
+ return <button onClick={handleLogin}>Login with Passkey</button>;
82
+ }
83
+ ```
84
+
85
+ By implementing proper error handling, you can significantly improve the user experience when things don't go as planned.
86
+
87
+ ---
88
+
89
+ ## Next Steps
90
+
91
+ Now that you have an overview of the advanced capabilities, you can dive deeper into the topics that are most relevant to your project.
92
+
93
+ - **[Authentication Methods](./advanced-authentication-methods.md)**: Implement new ways for your users to log in.
94
+ - **[Utilities](./advanced-utilities.md)**: Streamline your code with our helper functions.
95
+ - **[API Reference](./api-reference.md)**: Get a complete, detailed look at all components, hooks, and functions.