@jetthai/cuora 1.1.441-dev.1 → 1.1.441

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 (166) hide show
  1. package/.claude/commands/auto-git-flow.md +12 -5
  2. package/.claude/commands/commit-push.md +4 -15
  3. package/.claude/commands/sync-ai-prompts.md +1 -88
  4. package/.claude/settings.local.json +1 -3
  5. package/.claude/worktrees/geemee-sendpixel/.claude/commands/auto-git-flow.md +52 -0
  6. package/.claude/worktrees/geemee-sendpixel/.claude/commands/commit-push.md +174 -0
  7. package/.claude/worktrees/geemee-sendpixel/.claude/commands/create-branch.md +142 -0
  8. package/.claude/worktrees/geemee-sendpixel/.claude/commands/sync-ai-prompts.md +93 -0
  9. package/.claude/worktrees/geemee-sendpixel/.claude/settings.local.json +23 -0
  10. package/.claude/worktrees/geemee-sendpixel/.github/copilot-instructions.md +696 -0
  11. package/.claude/worktrees/geemee-sendpixel/.husky/post-checkout +32 -0
  12. package/.claude/worktrees/geemee-sendpixel/.husky/pre-commit +2 -0
  13. package/.claude/worktrees/geemee-sendpixel/.husky/pre-push +36 -0
  14. package/.claude/worktrees/geemee-sendpixel/.prettierignore +1 -0
  15. package/.claude/worktrees/geemee-sendpixel/.prettierrc +7 -0
  16. package/.claude/worktrees/geemee-sendpixel/AGENTS.md +696 -0
  17. package/.claude/worktrees/geemee-sendpixel/AI_PROMPT_SOURCE.md +758 -0
  18. package/.claude/worktrees/geemee-sendpixel/CHANGELOG.md +1779 -0
  19. package/.claude/worktrees/geemee-sendpixel/CLAUDE.md +696 -0
  20. package/.claude/worktrees/geemee-sendpixel/GEMINI.md +696 -0
  21. package/.claude/worktrees/geemee-sendpixel/README.md +308 -0
  22. package/.claude/worktrees/geemee-sendpixel/docs/kibana/crypto-way-deposit-amount-bug-analysis.md +1003 -0
  23. package/.claude/worktrees/geemee-sendpixel/docs/kibana/play-providerId-error.md +202 -0
  24. package/.claude/worktrees/geemee-sendpixel/docs/kibana/play-selectedWalletType.md +1 -0
  25. package/.claude/worktrees/geemee-sendpixel/docs/kibana/play-selectedWalletType_2.md +1 -0
  26. package/.claude/worktrees/geemee-sendpixel/docs/kibana/play-selectedWalletType_analysis.md +565 -0
  27. package/.claude/worktrees/geemee-sendpixel/package-lock.json +2455 -0
  28. package/.claude/worktrees/geemee-sendpixel/package.json +34 -0
  29. package/.claude/worktrees/geemee-sendpixel/scripts/auto-version.js +68 -0
  30. package/.claude/worktrees/geemee-sendpixel/scripts/auto-version.sh +33 -0
  31. package/.claude/worktrees/geemee-sendpixel/scripts/branch-auto-npm-publish.js +29 -0
  32. package/.claude/worktrees/geemee-sendpixel/scripts/check-version.sh +36 -0
  33. package/.claude/worktrees/geemee-sendpixel/scripts/clean-tags.sh +59 -0
  34. package/.claude/worktrees/geemee-sendpixel/src/api/account.js +8 -0
  35. package/.claude/worktrees/geemee-sendpixel/src/api/activity.js +128 -0
  36. package/.claude/worktrees/geemee-sendpixel/src/api/auth.js +63 -0
  37. package/.claude/worktrees/geemee-sendpixel/src/api/common.js +17 -0
  38. package/.claude/worktrees/geemee-sendpixel/src/api/form.js +3 -0
  39. package/.claude/worktrees/geemee-sendpixel/src/api/game.js +114 -0
  40. package/.claude/worktrees/geemee-sendpixel/src/api/index.js +13 -0
  41. package/.claude/worktrees/geemee-sendpixel/src/api/mailbox.js +24 -0
  42. package/.claude/worktrees/geemee-sendpixel/src/api/otp.js +5 -0
  43. package/.claude/worktrees/geemee-sendpixel/src/api/payment.js +262 -0
  44. package/.claude/worktrees/geemee-sendpixel/src/api/ranking.js +27 -0
  45. package/.claude/worktrees/geemee-sendpixel/src/api/user.js +69 -0
  46. package/.claude/worktrees/geemee-sendpixel/src/index.js +7 -0
  47. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/activity.js +209 -0
  48. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/activity_cash.js +181 -0
  49. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/cash_rain_activity.js +153 -0
  50. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/continue_deposit_activity.js +146 -0
  51. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/deposit_activity.js +95 -0
  52. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/diamond_shop_activity_cash.js +179 -0
  53. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/diamond_shop_activity_fc.js +196 -0
  54. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/diamond_shop_activity_vn.js +178 -0
  55. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/fafafa_activity.js +208 -0
  56. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/friend_invite_friends_activity.js +287 -0
  57. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/index.js +51 -0
  58. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/instant_rebate_activity.js +209 -0
  59. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/invite_friends_activity.js +114 -0
  60. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/jackpot.js +74 -0
  61. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/mini_game_activity.js +68 -0
  62. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/otp_verified_activity.js +74 -0
  63. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/ranking_activity.js +105 -0
  64. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/return_bonus_activity.js +153 -0
  65. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/roulette_activity_v2.js +95 -0
  66. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/sign_in_activity.js +157 -0
  67. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/sign_in_monthly_activity.js +65 -0
  68. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/specify_bets_activity.js +157 -0
  69. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/specify_turnover_activity.js +136 -0
  70. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/time_bomb_activity.js +89 -0
  71. package/.claude/worktrees/geemee-sendpixel/src/machine/activity/vip_card_activity.js +187 -0
  72. package/.claude/worktrees/geemee-sendpixel/src/machine/auth.js +592 -0
  73. package/.claude/worktrees/geemee-sendpixel/src/machine/auth_otp_v2.js +177 -0
  74. package/.claude/worktrees/geemee-sendpixel/src/machine/auth_otp_v3.js +300 -0
  75. package/.claude/worktrees/geemee-sendpixel/src/machine/bank_binding.js +277 -0
  76. package/.claude/worktrees/geemee-sendpixel/src/machine/bank_binding_amb.js +146 -0
  77. package/.claude/worktrees/geemee-sendpixel/src/machine/bonus.js +76 -0
  78. package/.claude/worktrees/geemee-sendpixel/src/machine/common.js +418 -0
  79. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/amb.js +93 -0
  80. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/crypto_bank.js +330 -0
  81. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/crypto_bank_cash.js +307 -0
  82. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/crypto_qrcode.js +148 -0
  83. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/crypto_qrcode_cash.js +131 -0
  84. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/crypto_way.js +252 -0
  85. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/crypto_way_cash.js +296 -0
  86. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/deposit_fc.js +272 -0
  87. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/direct.js +310 -0
  88. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/direct_cash.js +225 -0
  89. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/float.js +375 -0
  90. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/index.js +49 -0
  91. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/krway.js +151 -0
  92. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/loadcard_cash.js +215 -0
  93. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/loadcard_vn.js +351 -0
  94. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/manual_cash.js +364 -0
  95. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/manual_vn.js +458 -0
  96. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/qrcode_cash.js +225 -0
  97. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/qrcode_v2.js +338 -0
  98. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/usdt.js +144 -0
  99. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/usdt_cash.js +138 -0
  100. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/virtual_bank_cash.js +209 -0
  101. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/virtual_bank_vn.js +269 -0
  102. package/.claude/worktrees/geemee-sendpixel/src/machine/deposit/vpay.js +368 -0
  103. package/.claude/worktrees/geemee-sendpixel/src/machine/error.js +112 -0
  104. package/.claude/worktrees/geemee-sendpixel/src/machine/game_betslip.js +46 -0
  105. package/.claude/worktrees/geemee-sendpixel/src/machine/game_favorite_v2.js +160 -0
  106. package/.claude/worktrees/geemee-sendpixel/src/machine/game_hot_new.js +79 -0
  107. package/.claude/worktrees/geemee-sendpixel/src/machine/game_info.js +61 -0
  108. package/.claude/worktrees/geemee-sendpixel/src/machine/game_replay.js +46 -0
  109. package/.claude/worktrees/geemee-sendpixel/src/machine/game_search_cash.js +401 -0
  110. package/.claude/worktrees/geemee-sendpixel/src/machine/game_search_v2.js +401 -0
  111. package/.claude/worktrees/geemee-sendpixel/src/machine/game_v2_1.js +699 -0
  112. package/.claude/worktrees/geemee-sendpixel/src/machine/honor_board.js +132 -0
  113. package/.claude/worktrees/geemee-sendpixel/src/machine/honor_board_cash.js +89 -0
  114. package/.claude/worktrees/geemee-sendpixel/src/machine/inbox.js +489 -0
  115. package/.claude/worktrees/geemee-sendpixel/src/machine/index.js +89 -0
  116. package/.claude/worktrees/geemee-sendpixel/src/machine/leaderboard.js +130 -0
  117. package/.claude/worktrees/geemee-sendpixel/src/machine/merge.js +57 -0
  118. package/.claude/worktrees/geemee-sendpixel/src/machine/navbar.js +126 -0
  119. package/.claude/worktrees/geemee-sendpixel/src/machine/payment_data.js +86 -0
  120. package/.claude/worktrees/geemee-sendpixel/src/machine/promotions.js +170 -0
  121. package/.claude/worktrees/geemee-sendpixel/src/machine/ranking.js +219 -0
  122. package/.claude/worktrees/geemee-sendpixel/src/machine/reward.js +255 -0
  123. package/.claude/worktrees/geemee-sendpixel/src/machine/reward_cash.js +276 -0
  124. package/.claude/worktrees/geemee-sendpixel/src/machine/reward_fc.js +98 -0
  125. package/.claude/worktrees/geemee-sendpixel/src/machine/roulette_v2.js +280 -0
  126. package/.claude/worktrees/geemee-sendpixel/src/machine/setting.js +47 -0
  127. package/.claude/worktrees/geemee-sendpixel/src/machine/side.js +154 -0
  128. package/.claude/worktrees/geemee-sendpixel/src/machine/side_cash.js +111 -0
  129. package/.claude/worktrees/geemee-sendpixel/src/machine/side_v2.js +209 -0
  130. package/.claude/worktrees/geemee-sendpixel/src/machine/user_info.js +64 -0
  131. package/.claude/worktrees/geemee-sendpixel/src/machine/user_photo.js +65 -0
  132. package/.claude/worktrees/geemee-sendpixel/src/machine/user_reset_password.js +231 -0
  133. package/.claude/worktrees/geemee-sendpixel/src/machine/user_sign_up.js +244 -0
  134. package/.claude/worktrees/geemee-sendpixel/src/machine/vip_table.js +57 -0
  135. package/.claude/worktrees/geemee-sendpixel/src/machine/websocket.js +361 -0
  136. package/.claude/worktrees/geemee-sendpixel/src/machine/welcome.js +110 -0
  137. package/.claude/worktrees/geemee-sendpixel/src/machine/withdraw/index.js +11 -0
  138. package/.claude/worktrees/geemee-sendpixel/src/machine/withdraw/withdraw_crypto_cash.js +327 -0
  139. package/.claude/worktrees/geemee-sendpixel/src/machine/withdraw/withdraw_krway.js +223 -0
  140. package/.claude/worktrees/geemee-sendpixel/src/machine/withdraw/withdraw_manual.js +536 -0
  141. package/.claude/worktrees/geemee-sendpixel/src/machine/withdraw/withdraw_manual_cash.js +324 -0
  142. package/.claude/worktrees/geemee-sendpixel/src/request/config.js +41 -0
  143. package/.claude/worktrees/geemee-sendpixel/src/request/request.js +365 -0
  144. package/.claude/worktrees/geemee-sendpixel/src/util/constant.js +20 -0
  145. package/.claude/worktrees/geemee-sendpixel/src/util/index.js +6 -0
  146. package/.claude/worktrees/geemee-sendpixel/src/util/math.js +4 -0
  147. package/.claude/worktrees/geemee-sendpixel/src/util/storage.js +42 -0
  148. package/.github/copilot-instructions.md +399 -551
  149. package/.husky/post-checkout +3 -3
  150. package/.husky/pre-push +1 -1
  151. package/.prettierignore +1 -2
  152. package/AGENTS.md +399 -551
  153. package/AI_PROMPT_SOURCE.md +130 -662
  154. package/CHANGELOG.md +22 -229
  155. package/CLAUDE.md +399 -551
  156. package/GEMINI.md +399 -551
  157. package/README.md +137 -40
  158. package/package.json +1 -1
  159. package/scripts/auto-version.js +0 -1
  160. package/src/api/activity.js +0 -10
  161. package/src/api/auth.js +2 -2
  162. package/src/machine/activity/activity_cash.js +3 -18
  163. package/src/machine/auth.js +10 -2
  164. package/src/machine/common.js +15 -1
  165. package/src/machine/ranking.js +25 -43
  166. package/src/machine/user_sign_up.js +67 -7
@@ -2,76 +2,44 @@
2
2
 
3
3
  <!-- AUTO-SYNCED FROM AI_PROMPT_SOURCE.md — DO NOT EDIT DIRECTLY -->
4
4
 
5
- > This file provides guidance for GitHub Copilot when working on this project.
5
+ > This file provides guidance for GitHub Copilot when working on this project. It focuses on design context and conventions that "cannot be derived from the code", avoiding duplication of usage instructions already in the README.
6
+ >
7
+ > **Companion file**: [README.md](./README.md) covers user-facing content such as project overview, tech stack, module exports, dependencies, and Git branch versioning/release workflow.
6
8
 
7
9
  ---
8
10
 
9
11
  ## 1. Project Architecture
10
12
 
11
- ### 1.1 Project Overview & Tech Stack
13
+ ### 1.1 Four-Layer Architecture
12
14
 
13
- `@jetthai/cuora` (v1.1.413) is a pure ESM JavaScript library with no build step — raw `.js` files are published directly to npm. It integrates API calls and business logic through XState v4 state machines, serving an online gaming platform. It handles authentication, payments (deposits/withdrawals), game management, activities, and real-time WebSocket communication. Designed for Nuxt.js client-side applications (`ssr: false`).
15
+ #### 1.1.1 Request Layer
14
16
 
15
- - **Module format**: `"type": "module"` (`package.json:6`)
16
- - **Entry point**: `"main": "./src/index.js"` (`package.json:5`)
17
- - **No build step**: No Webpack/Rollup/TypeScript, no test framework, no linter
18
- - **Code formatting**: Prettier (`.prettierrc`: no semicolons, single quotes, 2-space indent, 150-char line width, ES5 trailing commas)
19
- - **Pre-commit Hook**: Husky runs `npm run format && git add .`
17
+ **Files**: `src/request/request.js`, `src/request/config.js`
20
18
 
21
- ### 1.2 Entry Point & Module Exports
19
+ **Request class**:
22
20
 
23
- **File**: `src/index.js`
21
+ - **Token injection**: Request interceptor auto-injects `Bearer {token}`
22
+ - **API versioning**: `supportVersion2List` array defines endpoints requiring conversion, auto-converts V1 camelCase paths to V2 kebab-case
23
+ - **Maintenance detection**: `ERR_F108` error triggers `isBlocked` flag, blocking subsequent non-config requests
24
+ - **Custom serialization**: Avoids double-encoding for `q` parameter
25
+ - **Request cancellation**: Batch cancellation supported via Axios CancelToken
24
26
 
25
- ```js
26
- import api from './api/index.js'
27
- import machine from './machine/index.js'
28
- import Request from './request/request.js'
29
- import Config from './request/config.js'
30
- import util, { constant, storage } from './util/index.js'
31
-
32
- export { api, machine, Request, Config, util, constant, storage }
33
- ```
34
-
35
- | Export Name | Description |
36
- | ----------- | --------------------------------------------------------------- |
37
- | `api` | Aggregated object of 11 API modules |
38
- | `machine` | Aggregated object of 89+ XState state machine factory functions |
39
- | `Request` | Axios wrapper class (interceptors, token, version control) |
40
- | `Config` | Configuration class (apiURL, clientId, appSecret, etc.) |
41
- | `util` | Utility functions (`getDeviceToken`, `getDeviceTokenWithRetry`) |
42
- | `constant` | Game type constants (16 game types) |
43
- | `storage` | localStorage wrapper (supports TTL/expiration) |
44
-
45
- ### 1.3 Four-Layer Architecture
46
-
47
- #### 1.3.1 Request Layer
48
-
49
- **Files**: `src/request/request.js` (363 lines), `src/request/config.js` (39 lines)
50
-
51
- **Request class** (`request.js`):
27
+ **Config class**:
52
28
 
53
- - **Token injection**: Request interceptor auto-injects `Bearer {token}` (`request.js:207`)
54
- - **API versioning**: `supportVersion2List` array defines 158 endpoints (`request.js:5-158`), auto-converts V1 camelCase paths to V2 kebab-case
55
- - **Maintenance detection**: `ERR_F108` error triggers `isBlocked` flag, blocking subsequent non-config requests (`request.js:254-258`)
56
- - **Custom serialization**: Avoids double-encoding for `q` parameter (`request.js:187-195`)
57
- - **Request cancellation**: Batch cancellation via Axios CancelToken (`request.js:269-272`)
58
-
59
- **Config class** (`config.js`):
60
-
61
- - Composes `fullURL = urljoin(apiURL, apiVersion, clientId)` (`config.js:26`)
29
+ - Composes `fullURL = urljoin(apiURL, apiVersion, clientId)`
62
30
  - `setApiURL(url)` dynamically updates the API base URL
63
31
 
64
32
  **Core methods**:
65
33
 
66
- - `send(req, customToken)` — Main request dispatcher (`request.js:240-267`)
67
- - `_createConfig(req, cancelToken)` — Builds Axios request config (`request.js:278-320`)
68
- - `_convertUrlToKebabCase(url)` — V1→V2 path conversion with 19 special mappings (`request.js:323-352`)
69
- - `_checkToken(req)` — Token check for non-public endpoints (`request.js:354-358`)
70
- - `getToken()` — Retrieves token from localStorage (`request.js:360-362`)
34
+ - `send(req, customToken)` — Main request dispatcher
35
+ - `_createConfig(req, cancelToken)` — Builds Axios request config
36
+ - `_convertUrlToKebabCase(url)` — V1→V2 path conversion with special mappings
37
+ - `_checkToken(req)` — Token check for non-public endpoints
38
+ - `getToken()` — Retrieves token from localStorage
71
39
 
72
- #### 1.3.2 API Layer
40
+ #### 1.1.2 API Layer
73
41
 
74
- **Directory**: `src/api/` (12 files: 11 modules + `index.js`)
42
+ **Directory**: `src/api/` (11 modules + `index.js`)
75
43
 
76
44
  Each API module exports an object with functions returning request descriptor objects:
77
45
 
@@ -86,36 +54,24 @@ Each API module exports an object with functions returning request descriptor ob
86
54
  }
87
55
  ```
88
56
 
89
- | Module | File | Function Count | Description |
90
- | ---------- | ----------------- | -------------- | ---------------------------------------------------- |
91
- | `auth` | `api/auth.js` | 7 | Login, register, logout, OAuth, account check |
92
- | `account` | `api/account.js` | 6 | Account binding, password management |
93
- | `activity` | `api/activity.js` | 25 | Activity list, rewards, ranking, diamond exchange |
94
- | `common` | `api/common.js` | 8 | Site config, announcements, navbar, pixel tracking |
95
- | `form` | `api/form.js` | 1 | File upload |
96
- | `game` | `api/game.js` | 27 | Game list, search, history, favorites |
97
- | `mailbox` | `api/mailbox.js` | 6 | Message list, send, update, delete |
98
- | `otp` | `api/otp.js` | 3 | OTP verification, confirmation, reset |
99
- | `payment` | `api/payment.js` | 40+ | Payment info, deposit/withdrawal transactions, rules |
100
- | `ranking` | `api/ranking.js` | 4 | Tournament, ranking options, details |
101
- | `user` | `api/user.js` | 27 | User info, password, avatar, friends |
57
+ Module categories: `auth`, `account`, `activity`, `common`, `form`, `game`, `mailbox`, `otp`, `payment`, `ranking`, `user`.
102
58
 
103
- #### 1.3.3 Machine Layer (State Machines)
59
+ #### 1.1.3 Machine Layer (State Machines)
104
60
 
105
- **Directory**: `src/machine/` (91 files including index, 89 state machines)
61
+ **Directory**: `src/machine/` (91 state machines)
106
62
 
107
63
  All state machines follow the factory pattern — default export function receives a `request` object and returns a `createMachine()` definition.
108
64
 
109
- | Category | Directory/File | Count | Representative Files |
110
- | ---------- | ------------------- | ----- | -------------------------------------------------------------------------------------- |
111
- | Core | `machine/` root | 4 | `auth.js` (555 lines), `common.js` (415 lines), `error.js`, `websocket.js` (369 lines) |
112
- | Deposit | `machine/deposit/` | 23 | `direct.js`, `usdt.js`, `crypto_bank.js`, `qrcode_v2.js` |
113
- | Withdrawal | `machine/withdraw/` | 4 | `withdraw_manual.js` (533 lines), `withdraw_krway.js` |
114
- | Activity | `machine/activity/` | 24 | `sign_in_activity.js`, `time_bomb_activity.js`, `diamond_shop_activity_*.js` |
115
- | Game | `machine/` root | 8 | `game_v2_1.js` (691 lines, largest file), `game_search_v2.js` |
116
- | User | `machine/` root | 6 | `user_info.js`, `user_sign_up.js`, `bank_binding.js` |
117
- | OTP | `machine/` root | 2 | `auth_otp_v2.js`, `auth_otp_v3.js` |
118
- | UI/Other | `machine/` root | 18 | `navbar.js`, `side.js`, `inbox.js`, `setting.js` |
65
+ | Category | Directory/File | Representative Files |
66
+ | ---------- | ------------------- | ---------------------------------------------------------------------------- |
67
+ | Core | `machine/` root | `auth.js`, `common.js`, `error.js`, `websocket.js` |
68
+ | Deposit | `machine/deposit/` | `direct.js`, `usdt.js`, `crypto_bank.js`, `qrcode_v2.js` |
69
+ | Withdrawal | `machine/withdraw/` | `withdraw_manual.js`, `withdraw_krway.js` |
70
+ | Activity | `machine/activity/` | `sign_in_activity.js`, `time_bomb_activity.js`, `diamond_shop_activity_*.js` |
71
+ | Game | `machine/` root | `game_v2_1.js` (largest file), `game_search_v2.js` |
72
+ | User | `machine/` root | `user_info.js`, `user_sign_up.js`, `user_photo.js`, `bank_binding.js` |
73
+ | OTP | `machine/` root | `auth_otp_v2.js`, `auth_otp_v3.js` |
74
+ | UI/Other | `machine/` root | `navbar.js`, `side.js`, `side_v2.js`, `inbox.js`, `setting.js`, `welcome.js` |
119
75
 
120
76
  **Common state flows**:
121
77
 
@@ -123,60 +79,22 @@ All state machines follow the factory pattern — default export function receiv
123
79
  - **Withdrawal**: `loading` → `pending` → `cash` (checking → withdrawable → submitting → submitted) → optional OTP verification
124
80
  - **Activity**: `idle/init` → `loading/fetching` → `loaded` → reward state (received/receiveable/progress)
125
81
 
126
- #### 1.3.4 Util Layer
82
+ #### 1.1.4 Util Layer
127
83
 
128
- **Directory**: `src/util/` (5 files)
84
+ **Directory**: `src/util/`
129
85
 
130
- | File | Lines | Description |
131
- | ---------------- | ----- | -------------------------------------------------------------------------------------------- |
132
- | `storage.js` | 42 | localStorage wrapper, `get()`/`set()`/`remove()`, supports `maxAge` option (seconds) for TTL |
133
- | `deviceToken.js` | 59 | FingerprintJS integration, `getDeviceTokenWithRetry()`: max 3 retries, 1000ms interval |
134
- | `constant.js` | 20 | `GAME_TYPE_LIST` (16 game types), `MY_FAVORITE`, `GAME_SEARCH` |
135
- | `math.js` | 4 | `max()` — converts falsy values to 0 then takes maximum |
136
- | `index.js` | 7 | Aggregated exports |
86
+ | File | Description |
87
+ | ---------------- | -------------------------------------------------------------------------------------------- |
88
+ | `storage.js` | localStorage wrapper, `get()`/`set()`/`remove()`, supports `maxAge` option (seconds) for TTL |
89
+ | `deviceToken.js` | FingerprintJS integration, `getDeviceTokenWithRetry()`: max 3 retries, 1000ms interval |
90
+ | `constant.js` | `GAME_TYPE_LIST` (16 game types), `MY_FAVORITE`, `GAME_SEARCH` |
91
+ | `math.js` | `max()` — converts falsy values to 0 then takes maximum |
137
92
 
138
93
  **Additional**: `src/lib/fingerprint_v3_11_12.js` (292 KB) — embedded FingerprintJS v3.11.12 library.
139
94
 
140
- ### 1.4 Directory Structure & File Statistics
95
+ ### 1.2 Key Design Patterns
141
96
 
142
- ```
143
- src/ (115 .js files)
144
- ├── index.js (entry point, 7 exports)
145
- ├── api/ (12 files: 11 modules + index.js)
146
- │ ├── auth.js (7 functions)
147
- │ ├── account.js (6 functions)
148
- │ ├── activity.js (25 functions)
149
- │ ├── common.js (8 functions)
150
- │ ├── form.js (1 function)
151
- │ ├── game.js (27 functions)
152
- │ ├── mailbox.js (6 functions)
153
- │ ├── otp.js (3 functions)
154
- │ ├── payment.js (40+ functions)
155
- │ ├── ranking.js (4 functions)
156
- │ ├── user.js (27 functions)
157
- │ └── index.js
158
- ├── machine/ (91 files: 89 state machines + 3 index)
159
- │ ├── activity/ (25 files: 24 state machines + index)
160
- │ ├── deposit/ (24 files: 23 state machines + index)
161
- │ ├── withdraw/ (5 files: 4 state machines + index)
162
- │ ├── auth.js, common.js, error.js, websocket.js (core)
163
- │ ├── game_v2_1.js, game_*.js (game)
164
- │ ├── user_*.js, bank_binding*.js (user)
165
- │ ├── auth_otp_v2.js, auth_otp_v3.js (OTP)
166
- │ └── navbar.js, side*.js, inbox.js, setting.js ... (UI/other)
167
- ├── request/ (2 files)
168
- │ ├── request.js (363 lines, Axios wrapper)
169
- │ └── config.js (39 lines, config class)
170
- ├── util/ (5 files)
171
- │ ├── storage.js, deviceToken.js, constant.js, math.js
172
- │ └── index.js
173
- └── lib/ (1 file)
174
- └── fingerprint_v3_11_12.js (292 KB, FingerprintJS)
175
- ```
176
-
177
- ### 1.5 Key Design Patterns
178
-
179
- #### 1.5.1 Factory Pattern
97
+ #### 1.2.1 Factory Pattern
180
98
 
181
99
  All state machines follow a unified pattern:
182
100
 
@@ -215,29 +133,29 @@ export default function (request) {
215
133
 
216
134
  Some state machines accept additional context: `export default function (request, context)`
217
135
 
218
- #### 1.5.2 Token Management
136
+ #### 1.2.2 Token Management
219
137
 
220
138
  - **Storage location**: localStorage, key is `cuora_{clientId}`
221
139
  - **TTL**: Token 300 seconds (5 minutes), account info 31 days, cookie data 7 days
222
- - **Injection method**: Request interceptor auto-adds `Authorization: Bearer {token}` (`request.js:207`)
140
+ - **Injection method**: Request interceptor auto-adds `Authorization: Bearer {token}`
223
141
  - **Extension mechanism**: After each successful `fetchUserInfo`, the `extendToken` action updates TTL (`auth.js`)
224
142
 
225
- #### 1.5.3 API Versioning (V1 → V2)
143
+ #### 1.2.3 API Versioning (V1 → V2)
226
144
 
227
- `supportVersion2List` (`request.js:5-158`) defines 158 endpoints requiring conversion. Conversion logic:
145
+ `supportVersion2List` (`request.js`) defines endpoints requiring conversion. Conversion logic:
228
146
 
229
147
  1. Strip query parameters from URL (`url.split('?')[0]`)
230
148
  2. Check if URL is in the V2 support list (supports `:parameter` dynamic path matching)
231
149
  3. If matched, convert path via `_convertUrlToKebabCase()`
232
- 4. `specifyingPath` mapping handles 19 non-standard conversions (`request.js:324-344`)
150
+ 4. `specifyingPath` mapping handles non-standard conversions
233
151
  5. Remaining paths use regex `/([a-z])([A-Z])/g` to convert camelCase to kebab-case
234
152
 
235
- #### 1.5.4 Error Code System
153
+ #### 1.2.4 Error Code System
236
154
 
237
- | Code | Meaning | Source |
155
+ | Code | Meaning | Primary Source |
238
156
  | ---------- | ------------------------------------ | ------------------------------------------------------ |
239
- | `ERR_F108` | System under maintenance | `request.js:254`, `error.js` |
240
- | `ERR_A103` | Missing auth token | `request.js:356`, `error.js` |
157
+ | `ERR_F108` | System under maintenance | `request.js`, `error.js` |
158
+ | `ERR_A103` | Missing auth token | `request.js`, `error.js` |
241
159
  | `ERR_A104` | Auth-related error | `error.js` |
242
160
  | `ERR_A108` | OTP auth-related | `error.js`, `auth_otp_v2.js`, `user_reset_password.js` |
243
161
  | `ERR_A113` | Auth-related error | `error.js` |
@@ -247,45 +165,298 @@ Some state machines accept additional context: `export default function (request
247
165
  | `ERR_G106` | Insufficient balance | `error.js` |
248
166
  | `ERR_G124` | Free game settlement | `error.js` |
249
167
  | `ERR_G125` | Free game forfeit | `error.js` |
250
- | `ERR_800` | Cancelled request (silently handled) | `request.js:260` |
251
- | `ERR_998` | Network error/404 | `request.js:228-229` |
168
+ | `ERR_800` | Cancelled request (silently handled) | `request.js` |
169
+ | `ERR_998` | Network error/404 | `request.js` |
252
170
 
253
- ### 1.6 Dependencies & Their Roles
171
+ ### 1.3 Core Business Flows & Critical Know-How
254
172
 
255
- | Package | Version | Role | Used In |
256
- | ------------------ | ---------- | ------------------------------------------------------------------------------------------ | ---------------------- |
257
- | `xstate` | `^4.25.0` | State machine core framework | All `machine/` files |
258
- | `socket.io-client` | `^4.8.3` | WebSocket real-time communication | `machine/websocket.js` |
259
- | `lodash` | `^4.17.21` | Utility functions (`pickBy`, `uniqBy`, `findLastIndex`, `padStart`, `toNumber`, `isEqual`) | Spread across 12 files |
260
- | `ua-parser-js` | `^0.7.34` | User-agent parsing (mobile detection) | `machine/common.js` |
261
- | `url-join` | `^4.0.1` | Safe URL path joining | `request/config.js` |
262
- | `universal-cookie` | `^4.0.4` | Cookie operations | `machine/common.js` |
173
+ This section explains how each module actually operates, non-obvious behaviors, and design decisions that must be understood when adding or modifying code.
263
174
 
264
- ---
175
+ #### 1.3.1 Inter-Machine Communication Patterns
265
176
 
266
- ## 2. Code Quality Standards (Clean Code Guidelines)
177
+ State machines **do not directly reference each other**, but communicate indirectly through the following four patterns:
267
178
 
268
- ### 2.1 Naming Consistency
179
+ **Pattern 1 — Request Bus**: All state machines share the same `request` object (passed in as a factory parameter), sending API requests via `request.send(api.xxx())`. `request.errorHandler` can forward errors to the error machine.
269
180
 
270
- #### 2.1.1 Inconsistent HTTP Method Casing
181
+ **Pattern 2 — WebSocket Event Injection**: The callback service in `websocket.js` converts socket events into internal state-machine events (e.g. `ACTIVITY_INFO`, `PUSH_ANALYTICS`); other machines or the UI layer can watch for changes to `context.socketData`.
182
+
183
+ **Pattern 3 — Parallel-State Shared Context**: `common.js` uses `type: 'parallel'` so that 4 sub-machines share context (e.g. the `feed` sub-machine reads the `isPlaying` flag to decide whether to pause polling).
184
+
185
+ **Pattern 4 — External Event Dispatch**: The UI layer or a scheduler dispatches events to each state machine (e.g. auth's `LOGIN_ID`, `SET_PLAY`); each machine handles events independently.
186
+
187
+ ```
188
+ User action → UI layer dispatches event → state machine handles
189
+ ↓
190
+ request.send(api.xxx()) → Request class → API server
191
+ ↓
192
+ Error → request.errorHandler → error machine → routing
193
+ ```
194
+
195
+ #### 1.3.2 Authentication & Token Lifecycle
196
+
197
+ **Token survival strategy**: Token TTL is only 5 minutes (`maxAge: 300`), kept alive by repeated `fetchUserInfo` polling. On each successful poll, `extendToken` rewrites storage and resets TTL. If `fetchUserInfo` fails, the token expires naturally and the session terminates.
198
+
199
+ ```
200
+ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll again
201
+ fetchUserInfo failure → leaving state → logout
202
+ ```
203
+
204
+ **inline vs login states** (the most central concept in auth.js):
271
205
 
272
- `account.js` and `otp.js` use uppercase `'GET'`/`'POST'`, while the other 9 API modules use lowercase `'get'`/`'post'`.
206
+ - `inline`: User is authenticated but `rank < 0` (account not yet ranked/activated); polling continues until rank takes effect
207
+ - `login`: User authenticated with `rank >= 0` (full user); enters device-token check then begins normal polling
208
+ - Flow: `loginSuccess → inline → (when rank >= 0) → inlineFinish → login`
209
+ - `tokenAuthenticated` path (token recovery): reads token directly from storage; on `fetchUserInfo` success, skips inline and goes straight to login
210
+
211
+ **Polling interval**: base `tick: 2000ms`, multiplied by 5 in-game (becomes 10 seconds) to reduce server load while playing.
212
+
213
+ **Login method routing** (7 types):
214
+
215
+ | Event | Method | Special Handling |
216
+ | ---------------- | -------------------- | -------------------------------------------------- |
217
+ | `LOGIN_ID` | Account + password | reCAPTCHA header |
218
+ | `LOGIN_PHONE` | Phone number | reCAPTCHA header + country code |
219
+ | `LOGIN_EMAIL` | Email | reCAPTCHA header |
220
+ | `LOGIN_LOCAL` | Local account | Additionally stores `cuora_tempuser` (24h TTL) |
221
+ | `LOGIN_GUEST` | Guest | No auth credentials |
222
+ | `LOGIN_APP` | OAuth App | provider + accessToken |
223
+ | `LOGIN_TELEGRAM` | Telegram | additionalUserInfo |
224
+ | `LOGIN_3PARTY` | Third-party redirect | Does not switch state; uses `window.location.href` |
225
+
226
+ **OTP flow**: After successful login, enter `otpChecking` state, and only proceed to `loginSuccess` after `OTP_VERIFIED` or `OTP_SKIP` event.
227
+
228
+ **Account persistence**: The most recently used login account is saved in localStorage (31-day TTL) for auto-fill on the login form. Token expiration does not affect the account record.
229
+
230
+ #### 1.3.3 Canonical Deposit Pattern
231
+
232
+ All deposit state machines follow a unified core flow, with variants per payment method:
233
+
234
+ ```
235
+ loading (parallel: fetch siteConfig + bankList)
236
+ → promotion (route: has minimum deposit → calculating, no minimum → loaded)
237
+ → loaded (user selects bank/amount)
238
+ → debouncing (CALCULATE event, 1000ms debounce)
239
+ → calculating (call getDepositExpectedResult)
240
+ → loaded/calculated (show calculation result)
241
+ → submitting (submit deposit)
242
+ → submitted
243
+ ```
244
+
245
+ **Cash vs Non-Cash variants**:
246
+
247
+ | Aspect | Non-Cash (e.g. `direct.js`) | Cash (e.g. `direct_cash.js`) |
248
+ | ------------- | -------------------------------- | ----------------------------------------------- |
249
+ | Constructor | `(request) => createMachine()` | `(request, context) => createMachine()` |
250
+ | Initial data | Fetched async (init → fetching) | Preloaded via context parameter |
251
+ | loading phase | Two sub-states (init + fetching) | `always` jumps directly to checking |
252
+ | Global events | `internal: true` (default) | `internal: false` (forces external transitions) |
253
+ | Bank list | Fetched fresh each time | `bankMap` cache (keyed by method) |
254
+
255
+ **Promotion & Bonus preview**:
256
+
257
+ - `SET_PROMOTION` global event sets the promotion context
258
+ - If `siteConfig.bonusPreviewEnable === true` and `promotion.activityNo !== 'none'`, additionally call `getBonusPreview` to display the expected reward
259
+ - **Naming inconsistency**: Non-Cash uses `promotion?.activityNo`, Cash uses `promotion?.promotionsNo`
260
+
261
+ **resultMap cache** (usdt.js, usdt_cash.js): caches results keyed by `selectedNetwork.value` to avoid re-fetching the same network address.
262
+
263
+ **V2 API response format inconsistency**: the same endpoint may return either `{ data: {...} }` or just `{...}`; all machines must handle both defensively:
273
264
 
274
265
  ```js
275
- // Bad — api/account.js:2, api/otp.js:2-4
276
- bindingStatus: () => ({ url: 'account-binding/status', method: 'GET' })
277
- verification: (data) => ({ url: 'otp-verification-point/verify', method: 'POST', params: data })
266
+ setCalculation: assign((context, event) => {
267
+ const { data } = event.data
268
+ return { calculation: data || event.data }
269
+ })
270
+ ```
271
+
272
+ **processing state check**: `crypto_bank.js`, `manual_cash.js` check at initialization whether there is an in-progress deposit order; if so, jump directly to `submitted` to prevent duplicate submission.
278
273
 
279
- // Good — use lowercase consistently (matching the other 9 modules)
280
- bindingStatus: () => ({ url: 'account-binding/status', method: 'get' })
281
- verification: (data) => ({ url: 'otp-verification-point/verify', method: 'post', params: data })
274
+ #### 1.3.4 Withdrawal Flow & OTP
275
+
276
+ **Five-step eligibility validation chain** (withdraw_manual.js):
277
+
278
+ ```
279
+ 1. haveProcessing → in-progress withdrawal? (yes → inProcessing)
280
+ 2. isBankNotBound → bank account bound? (no → unbound)
281
+ 3. isNotWithdrawMinDepositAmount → minimum deposit threshold met?
282
+ 4. isPassWithdrawCooldownTime → still in cooldown?
283
+ 5. isNotWIthdrawServiceTime → within service window?
284
+ All passed → withdrawable
282
285
  ```
283
286
 
284
- > Note: `request.js:317` uses `method.toUpperCase()` so functionality is unaffected, but it creates style inconsistency.
287
+ **OTP parallel states**: After withdrawal submission, if the response contains `request_id` and `number`/`email`, enter OTP verification:
288
+
289
+ - `countdown` sub-state: decrement TTL each second (`Math.max(second - 1000, 0)`)
290
+ - `verification` sub-state: `idle → acknowledging → submitted` or `idle → reset → idle`
291
+ - The two run in parallel (countdown does not block verification actions)
292
+
293
+ **Withdrawal rules system**: the `withdrawRules` array is matched against the balance; `findLastIndex` finds the last rule that satisfies the condition (the highest-amount tier), determining `maxWithdrawAmount`.
294
+
295
+ **Attachment types**: `withdraw` (normal withdrawal) vs `pool` (bonus / free-credit redemption, which calls the `restore` API).
296
+
297
+ #### 1.3.5 Game Management
298
+
299
+ **Parallel architecture** (game_v2_1.js): `flow` (UI interaction and game launch) and `timer` (auto-update every 20 seconds) run in parallel.
300
+
301
+ **Static-data fallback**: When not logged in, static data (`staticData`) is used; each page slices 20 entries from cache with no API call.
302
+
303
+ **Game-switch mechanism**: When switching to another game while in-game, first go through `connectSwitching` to disconnect the old game, then `connecting` to connect to the new one.
304
+
305
+ **Provider-specific behavior**: Some providers (`RSG`, `PG`, `NPG`, etc., 8 in total) use `${origin}${base}return` as the returnURL; others use `window.location.href` (with query string stripped).
306
+
307
+ **Response mapping**: backend returns `redirect_url` → `gameURL`, `wallet_type` → `gameWalletType`, `gameHtml` (some games return embedded HTML rather than a URL).
308
+
309
+ #### 1.3.6 Activity System
310
+
311
+ **Three classes of activity state machines**:
312
+
313
+ | Type | Representative | Behavior |
314
+ | ----------------- | --------------------------- | ------------------------------------------- |
315
+ | Display-only | `ranking_activity` | Fetch details, display, watch expiration |
316
+ | Reward-claim | `sign_in_activity` | Determine claim status from `receiveStatus` |
317
+ | Progress-tracking | `specify_turnover_activity` | Show completion percentage + claim |
318
+
319
+ **receiveStatus enum**:
320
+
321
+ - `0`: in progress / not yet eligible (→ `progress_status`)
322
+ - `1`: claimed (→ `received`, terminal state)
323
+ - `2`: claimable (→ `receiveable`, shows claim button)
324
+
325
+ **Red-dot unread state**:
326
+
327
+ - `noRedActivity = [2, 4, 13, 20, 90, 91, 92]`: these activity types never show a red dot
328
+ - For other activities, the read state is stored in localStorage under the key `unread_${activityNo}_${uidSite}`
329
+ - When updating `activityList`, clone the entire array to avoid direct mutation
330
+
331
+ **Activity polling**: base interval `tick * 10 = 20 seconds`; polling pauses while in-game (`isPlaying === true`). Promotion fetch additionally requires `hasToken`.
332
+
333
+ #### 1.3.7 Real-Time Communication (WebSocket)
334
+
335
+ **SocketTester race mechanism**: the `fetchSocket` service fetches multiple socket URLs from `/target/target.json` and uses `Promise.any()` to ping them all simultaneously — fastest responder wins.
336
+
337
+ **Connection parameters**:
338
+
339
+ ```js
340
+ io(`${socketURL}/frontend`, {
341
+ withCredentials: true,
342
+ forceNew: true,
343
+ transports: ['websocket', 'polling'], // WebSocket preferred, polling as fallback
344
+ auth: { Authorization: authToken },
345
+ })
346
+ ```
347
+
348
+ **Reconnection strategy**: reconnect only when `connectError === 'io server disconnect'` (server actively disconnected); max 3 attempts, 2-second interval. Client-side network errors do not trigger reconnect (Socket.IO's built-in auto-reconnect handles those).
349
+
350
+ **Event forwarding map**:
351
+
352
+ | Socket event | State-machine event | Notes |
353
+ | ---------------------- | ----------------------------------------------- | --------------------------------- |
354
+ | `activity-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` | Activity notification + analytics |
355
+ | `activity-reward-info` | `ACTIVITY_INFO` | Activity reward notification |
356
+ | `message-notice-info` | `ACTIVITY_INFO` | Message notification |
357
+ | `payment-info` | conditional: `ACTIVITY_INFO` + `PUSH_ANALYTICS` | fires when windowType === 'toast' |
358
+ | `connect` | `SET_CONNECTED` | Update socket instance |
359
+ | `connect_error` | `CONNECT_ERROR` | Record error |
360
+ | `disconnect` | `DISCONNECT` | Record disconnect reason |
361
+
362
+ **First-deposit detection**: while handling `PUSH_ANALYTICS`, if `event === 'purchase'` and `data.isFirst === true`, additionally push a `first_deposit` event automatically (Facebook Pixel / conversion tracking).
363
+
364
+ #### 1.3.8 Configuration & Live Info (Common Machine)
365
+
366
+ **4 parallel sub-machines**:
367
+
368
+ | Sub-machine | Responsibility | Polling/Trigger |
369
+ | ------------------ | ---------------------------------- | ---------------------- |
370
+ | `config` | Fetch siteConfig + layoutConfig | Event-triggered |
371
+ | `feed` | Fetch feeds + mailbox + promotions | 20-second polling |
372
+ | `getAnnouncements` | Fetch system announcements | Event-triggered |
373
+ | `broadcast` | Rotate broadcast messages | Switch every 5 seconds |
374
+
375
+ **siteConfig decoding**: the response is JWT-encoded; the `setConfig` action base64-decodes it to obtain the actual configuration (`loginMethods`, `paymentMethods`, `csChat`, etc.).
376
+
377
+ **Broadcast rotation mechanism**: `picking` (5s) → `display` (5s) → `picking`; selects broadcasts with `type === '0'` from `broadcastList`; already-shown broadcasts go into `sentNormalBroadcastList` and are not repeated.
378
+
379
+ **Cocos native-app detection**: when `window.CC_JSB === true`, skip all agent/channel/cookie setup (native apps don't need browser tracking).
380
+
381
+ **Mobile detection**: `isMobile` stores a device-type string (e.g. `'mobile'`, `'tablet'`), **not a boolean**.
382
+
383
+ **Mailbox filtering**: if `customerMessageEnable === false`, deduct CUSTOMER-type message counts from the mailbox total.
384
+
385
+ #### 1.3.9 Error-Handling Routing (Error Machine)
386
+
387
+ **Error classification & routing**:
388
+
389
+ | Error code | Category | Handling |
390
+ | ---------------------------------------------------- | -------------------- | -------------------------------------------------- |
391
+ | `ERR_A201`/`A204`/`A103`/`A104`/`A108`/`A113`/`F108` | Logout-class | → logout state |
392
+ | `ERR_G106` | Insufficient balance | → deposit state |
393
+ | `error.extend` containing `unfinished_` | Unfinished game | → unfinishedGame (resume after fetching game info) |
394
+ | `ERR_G124` | Free game settlement | → freeGameSettle |
395
+ | `ERR_G125` | Free game forfeit | → freeGameGiveUp |
396
+
397
+ **gameCode parsing for unfinished game**: `error.extend.split(/_(.+)/)[1]` — uses regex to take everything after the first underscore as the gameCode (e.g. `unfinished_ABC123` → `ABC123`).
398
+
399
+ **Maintenance mode dual-interception**:
400
+
401
+ 1. `request.js`: `ERR_F108` sets `isBlocked = true`, blocking all subsequent non-config requests
402
+ 2. `error.js`: `ERR_F108` routes to logout state
403
+
404
+ #### 1.3.10 API Request Lifecycle
405
+
406
+ The complete path of an API request from descriptor object to response:
407
+
408
+ ```
409
+ 1. State machine service calls request.send(api.xxx(params))
410
+ 2. api.xxx(params) returns descriptor { url, method, params, isPublic, ... }
411
+ 3. _checkToken(req): non-public endpoints check token; if missing throw ERR_A103
412
+ 4. isBlocked check: in maintenance and not a config request → silently blocked
413
+ 5. _createConfig(req):
414
+ a. Strip query string from URL
415
+ b. Match against supportVersion2List (supports :param dynamic-path regex matching)
416
+ c. If matched → _convertUrlToKebabCase() (look up specifyingPath first, otherwise auto-convert)
417
+ d. GET → params goes into params field; POST → params goes into data field
418
+ e. pickBy filters out null/undefined values
419
+ 6. Request interceptor: inject X-TH1GAMES-VERSION, X-TH1GAMES-PLATFORM, Authorization
420
+ 7. Custom paramsSerializer: special encoding for q parameter (avoid double-encoding)
421
+ 8. axios.request(config)
422
+ 9. Response interceptor:
423
+ a. response.data.error present → reject
424
+ b. Network Error / 404 → ERR_998 + Sentry report
425
+ 10. Error handling: ERR_F108 → isBlocked; ERR_800 (cancelled) → silent; otherwise → errorHandler
426
+ ```
427
+
428
+ **V2 URL conversion details**: `supportVersion2List` supports dynamic path matching (e.g. `payment/v2/:paymentType/transaction`), replacing `:param` with the regex `[^/]+`. Special paths are hard-coded in the `specifyingPath` map; the rest are auto-converted via `/([a-z])([A-Z])/g`.
429
+
430
+ **When adding a new API endpoint**: if it requires V2 conversion, it must be added to `supportVersion2List` manually.
431
+
432
+ #### 1.3.11 Critical Design Constraints & Gotchas
433
+
434
+ 1. **Token extension only happens when fetchUserInfo succeeds**: tokens are not auto-renewed; they depend on successful polling. If the API fails → the session terminates.
435
+ 2. **Leading slashes affect routing**: `/payment/v2/...` (withdrawal OTP endpoints) bypasses `url-join`'s baseURL composition and starts from the API root. Regular endpoints should not have a leading slash.
436
+ 3. **Mixed parameter passing for register**: `channel`/`subchannel`/`ac`/`fc` are appended to the URL query string while the rest go in the body. This is the only endpoint using this pattern.
437
+ 4. **OTP endpoints flagged isPublic**: the withdrawal OTP `acknowledge`/`reset` endpoints are `isPublic: true` despite handling sensitive operations. This is because the token may have expired during the OTP flow.
438
+ 5. **reCAPTCHA token is passed via header**: uses `headers['x-access-captcha']`, not in params. Only LOGIN_ID/PHONE/EMAIL use it.
439
+ 6. **Context modifications must use assign()**: XState v4 forbids direct context mutation. Deep objects should be cloned with `JSON.parse(JSON.stringify())`.
440
+ 7. **after: { 0 } (immediate transition) pattern**: `loginSuccess → inline → inlineFinish → login` chains together with 0ms delays; XState properly executes each state's entry/exit effects.
441
+ 8. **appSecret as a public-endpoint marker**: nearly all `isPublic: true` endpoints require an `appSecret` parameter, but auth endpoints do not.
442
+ 9. **Unfinished-game infinite retry**: the `unfinishedGame` state in `error.js` re-enters itself on `onError` with no backoff or retry cap.
443
+ 10. **isMobile is a string, not a boolean**: in `common.js`, `isMobile = userAgent?.device?.type` returns `'mobile'`/`'tablet'`/`undefined`; comparisons must be string-based (e.g. `isMobile === 'mobile' ? 'y' : null`).
444
+
445
+ ---
446
+
447
+ ## 2. Code Quality Standards (Clean Code Guidelines)
448
+
449
+ ### 2.1 Naming Consistency
450
+
451
+ #### 2.1.1 Inconsistent HTTP Method Casing
452
+
453
+ `account.js` and `otp.js` use uppercase `'GET'`/`'POST'`, while the other 9 API modules use lowercase `'get'`/`'post'`. `request.js` internally calls `method.toUpperCase()` so functionality is unaffected, but it creates style inconsistency.
454
+
455
+ **Convention**: use lowercase `'get'`/`'post'`/`'put'`/`'delete'` consistently.
285
456
 
286
457
  #### 2.1.2 Inconsistent State Names
287
458
 
288
- Different state machines use different initial state naming:
459
+ Different state machines use different initial state names:
289
460
 
290
461
  | Name | Usage Frequency | Representative Files |
291
462
  | ----------- | --------------- | ---------------------------------------------------------------------- |
@@ -298,64 +469,30 @@ Different state machines use different initial state naming:
298
469
 
299
470
  **Recommended conventions**:
300
471
 
301
- - `idle`: Resting state awaiting user action
302
- - `loading`: Initial data loading
303
- - `fetching`: Subsequent data re-fetching
304
- - `submitting`: Submission in progress
305
- - `submitted`: Submission complete
472
+ - `idle`: idle state awaiting user action
473
+ - `loading`: initial data load
474
+ - `fetching`: subsequent data re-fetch
475
+ - `submitting`: submission in progress
476
+ - `submitted`: submission complete
306
477
 
307
478
  #### 2.1.3 Ambiguous Parameter Names
308
479
 
309
- ```js
310
- // Bad — api/game.js:3
311
- addFavoriteGame(code) // What is code? gameCode? providerCode?
312
-
313
- // Good
314
- addFavoriteGame(gameCode)
315
- ```
480
+ Example: `addFavoriteGame(code)` — the meaning of `code` is unclear (gameCode? providerCode?); should be renamed to `addFavoriteGame(gameCode)`.
316
481
 
317
482
  ### 2.2 Magic Numbers & Hardcoded Strings
318
483
 
319
- #### 2.2.1 Activity Type IDs
484
+ These should be centralized in `util/constant.js`. Currently scattered across files:
320
485
 
321
- ```js
322
- // Bad — machine/activity/activity.js:13
323
- context: {
324
- specifyActivities: [4, 29, 34], // Unexplained numbers
325
- }
486
+ #### 2.2.1 Activity Type IDs
326
487
 
327
- // Bad — machine/activity/activity.js (deep inside)
328
- const noRedActivity = [2, 4, 13, 20, 90, 91, 92] // Unexplained numbers
488
+ - `specifyActivities: [4, 29, 34]` (`machine/activity/activity.js`)
489
+ - `noRedActivity = [2, 4, 13, 20, 90, 91, 92]` (deeper in the same file)
329
490
 
330
- // Good — should be defined in util/constant.js
331
- export const SPECIFY_ACTIVITIES = [4, 29, 34]
332
- export const NO_RED_DOT_ACTIVITIES = [2, 4, 13, 20, 90, 91, 92]
333
- ```
491
+ #### 2.2.2 Error Codes
334
492
 
335
- #### 2.2.2 Scattered Error Codes
493
+ `ERR_F108`, `ERR_A103`, `ERR_800`, `ERR_998`, etc. appear as string literals across `request.js`, `error.js`, `auth_otp_v2.js`, and others. Should be centralized as an `ERROR_CODES` constants object.
336
494
 
337
- Error codes are scattered as string literals across multiple files.
338
-
339
- ```js
340
- // Bad — scattered across request.js, error.js, auth_otp_v2.js, etc.
341
- if (error.code === 'ERR_F108') { ... }
342
- if (error.code !== 'ERR_800') { ... }
343
- throw { code: 'ERR_A103', url: req.url }
344
-
345
- // Good — centralized definition
346
- export const ERROR_CODES = {
347
- MAINTENANCE: 'ERR_F108',
348
- AUTH_MISSING: 'ERR_A103',
349
- CANCELLED: 'ERR_800',
350
- NETWORK_ERROR: 'ERR_998',
351
- OTP_FAILED: 'ERR_F106',
352
- BALANCE_INSUFFICIENT: 'ERR_G106',
353
- }
354
- ```
355
-
356
- #### 2.2.3 Hardcoded Time Constants
357
-
358
- Time values scattered across multiple files:
495
+ #### 2.2.3 Time Constants
359
496
 
360
497
  | Value | Purpose | Occurrences |
361
498
  | ------------------- | ------------------------ | ------------------------------------- |
@@ -365,109 +502,39 @@ Time values scattered across multiple files:
365
502
  | `1000` | Debounce delay | 44 places (across machine/) |
366
503
  | `2000` | Polling tick | `auth.js`, `common.js`, `activity.js` |
367
504
  | `6000` | Honor board/Jackpot tick | `honor_board.js`, `jackpot.js` |
368
- | `30000` | FingerprintJS timeout | `deviceToken.js:19` |
505
+ | `30000` | FingerprintJS timeout | `deviceToken.js` |
369
506
 
370
- ```js
371
- // Good — centralized definition
372
- export const TTL = {
373
- TOKEN: 300,
374
- SESSION: 60 * 60 * 24,
375
- ACCOUNT: 60 * 60 * 24 * 31,
376
- COOKIE: 60 * 60 * 24 * 7,
377
- }
378
- export const INTERVAL = {
379
- DEBOUNCE: 1000,
380
- POLLING_DEFAULT: 2000,
381
- POLLING_HONOR: 6000,
382
- BROADCAST: 5000,
383
- }
384
- ```
507
+ Should be centralized as `TTL` and `INTERVAL` constants objects.
385
508
 
386
- #### 2.2.4 Hardcoded Transaction Type Strings
509
+ #### 2.2.4 Transaction Type Strings
387
510
 
388
- ```js
389
- // Bad — api/payment.js (38 places, across 22 files)
390
- params: {
391
- transferType: 'DEPOSIT', amount, cryptoCurrency, promotionsNo
392
- }
393
- params: {
394
- transferType: 'WITHDRAW', amount, cryptoCurrency
395
- }
396
-
397
- // Good
398
- export const TRANSFER_TYPE = { DEPOSIT: 'DEPOSIT', WITHDRAW: 'WITHDRAW' }
399
- ```
400
-
401
- #### 2.2.5 WebSocket Connection Status Magic Numbers
402
-
403
- ```js
404
- // Bad — machine/websocket.js:14
405
- connectStatus: 0, // 0: disconnected, 1: connecting, 2: connected
511
+ `'DEPOSIT'`, `'WITHDRAW'` are scattered across 38 places (`api/payment.js` and 22 state machines). Should be centralized as `TRANSFER_TYPE` constants.
406
512
 
407
- // Good
408
- export const SOCKET_STATUS = { DISCONNECTED: 0, CONNECTING: 1, CONNECTED: 2 }
409
- ```
513
+ #### 2.2.5 WebSocket Connection Status
410
514
 
411
- #### 2.2.6 Activity Receive Status Magic Numbers
515
+ `machine/websocket.js`'s `connectStatus: 0/1/2` (disconnected/connecting/connected) should be replaced with named constants.
412
516
 
413
- ```js
414
- // Bad — machine/activity/sign_in_activity.js
415
- isReceived: (context) => context.receiveStatus === 1
416
- isReceiveable: (context) => context.receiveStatus === 2
517
+ #### 2.2.6 Activity Receive Status
417
518
 
418
- // Good
419
- export const RECEIVE_STATUS = { UNCLAIMED: 0, RECEIVED: 1, CLAIMABLE: 2 }
420
- ```
519
+ Magic numbers like `receiveStatus === 1` (received), `=== 2` (claimable) should be replaced with `RECEIVE_STATUS` constants.
421
520
 
422
521
  ### 2.3 Missing Parameter Validation
423
522
 
424
- All API functions accept parameters without any validation:
425
-
426
- ```js
427
- // Bad — api/payment.js
428
- makeTransaction: ({ type, payload, paymentMethod }) => ({
429
- url: `payment/v2/${paymentMethod}/transaction`, // paymentMethod injected directly into URL, no validation
430
- method: 'post',
431
- params: { transferType: type, ...payload },
432
- })
433
- ```
523
+ All API functions accept parameters with no validation. For example, `makeTransaction({ paymentMethod })` injects `paymentMethod` directly into the URL with no checks.
434
524
 
435
525
  **Recommended guidelines**:
436
526
 
437
527
  - Validate critical parameters at system boundaries (API layer)
438
- - URL path parameters should be checked for non-undefined and no path traversal characters
528
+ - URL path parameters should be checked for non-undefined and absence of path-traversal characters
439
529
  - Amount parameters should be confirmed as positive numbers
440
530
 
441
531
  ### 2.4 Inconsistent Error Handling
442
532
 
443
- Three error handling patterns exist but lack a unified strategy:
444
-
445
- **Pattern 1 — Silent transition to idle** (~60% of state machines):
446
-
447
- ```js
448
- // machine/deposit/usdt.js
449
- onError: {
450
- target: 'idle'
451
- } // Error information lost
452
- ```
533
+ Three error-handling patterns currently exist but no unified strategy:
453
534
 
454
- **Pattern 2 — Transition to fail state** (some state machines):
455
-
456
- ```js
457
- // machine/withdraw/withdraw_manual.js
458
- onError: {
459
- target: 'fail'
460
- }
461
- ```
462
-
463
- **Pattern 3 — Infinite retry** (few state machines):
464
-
465
- ```js
466
- // machine/error.js
467
- onError: {
468
- target: 'unfinishedGame'
469
- } // Re-enters same state, potential infinite loop
470
- ```
535
+ - **Silent transition to idle** (~60% of state machines): `onError: { target: 'idle' }`, error info lost
536
+ - **Transition to fail state** (some): `onError: { target: 'fail' }`
537
+ - **Infinite retry** (a few): `onError: { target: 'unfinishedGame' }`, potential infinite loop
471
538
 
472
539
  **Recommended guidelines**:
473
540
 
@@ -481,112 +548,44 @@ onError: {
481
548
 
482
549
  10 files use the `@jetthai/cuora` package name instead of relative paths:
483
550
 
484
- ```js
485
- // Bad — machine/deposit/usdt.js:2
486
- import payment from '@jetthai/cuora/src/api/payment.js'
487
-
488
- // Good — machine/deposit/direct.js:2 (approach used by most files)
489
- import payment from '../../api/payment.js'
490
- ```
491
-
492
- **Affected files**:
493
-
494
- - `machine/deposit/usdt.js`
495
- - `machine/deposit/usdt_cash.js`
496
- - `machine/deposit/crypto_way.js`
497
- - `machine/deposit/crypto_bank.js`
498
- - `machine/deposit/crypto_qrcode.js`
499
- - `machine/deposit/crypto_qrcode_cash.js`
500
- - `machine/deposit/crypto_bank_cash.js`
501
- - `machine/deposit/crypto_way_cash.js`
551
+ - `machine/deposit/usdt.js`, `usdt_cash.js`
552
+ - `machine/deposit/crypto_way.js`, `crypto_way_cash.js`
553
+ - `machine/deposit/crypto_bank.js`, `crypto_bank_cash.js`
554
+ - `machine/deposit/crypto_qrcode.js`, `crypto_qrcode_cash.js`
502
555
  - `machine/deposit/virtual_bank_cash.js`
503
556
  - `machine/activity/sign_in_monthly_activity.js`
504
557
 
558
+ **Convention**: use relative paths consistently (e.g. `'../../api/payment.js'`).
559
+
505
560
  #### 2.5.2 Inconsistent lodash Import Extensions
506
561
 
507
562
  ```js
508
- // With .js extension — request.js, machine/auth.js, machine/common.js
563
+ // request.js, machine/auth.js, machine/common.js — with .js
509
564
  import pickBy from 'lodash/pickBy.js'
510
565
 
511
- // Without .js extension — api/auth.js, util/deviceToken.js
566
+ // api/auth.js, util/deviceToken.js — without .js
512
567
  import pickBy from 'lodash/pickBy'
513
- import uniqBy from 'lodash/uniqBy'
514
568
  ```
515
569
 
516
- **Recommendation**: Use the form without extension (`'lodash/pickBy'`) consistently, matching lodash official documentation.
570
+ **Convention**: use the form without extension (matches lodash official docs).
517
571
 
518
572
  ### 2.6 V1/V2 Legacy Duplication
519
573
 
520
- V1 and V2 password recovery functions coexist in `api/user.js`:
521
-
522
- ```js
523
- // V1 — api/user.js:23 (legacy)
524
- passwordRecovery: (recoveryData) => ({ url: 'recovery', method: 'post', ... })
525
-
526
- // V2 — api/user.js:28-52 (new)
527
- passwordV2RecoveryInit: ({ ... }) => ({ url: 'recovery/v2/initiate', method: 'post', ... })
528
- passwordV2Acknowledge: ({ ... }) => ({ url: 'recovery/v2/acknowledge', method: 'post', ... })
529
- passwordV2ResetOtp: ({ ... }) => ({ url: 'recovery/v2/reset', method: 'post', ... })
530
- passwordV2Change: ({ ... }) => ({ url: 'recovery/v2/changePassword', method: 'post', ... })
531
- ```
532
-
533
- The V1 version has no deprecation marker and is noted as "not used by platform or cash site".
574
+ In `api/user.js`, V1 `passwordRecovery` coexists with the V2 `passwordV2*` family; V1 is annotated "not used by platform or cash site" but lacks an `@deprecated` marker.
534
575
 
535
- **Recommendation**: Add `@deprecated` markers to deprecated functions and remove them after confirming no references.
576
+ **Recommended guidelines**: add `@deprecated` markers to deprecated functions and remove them after confirming no references.
536
577
 
537
578
  ### 2.7 Parameter Explosion
538
579
 
539
- `api/payment.js` has multiple functions receiving too many destructured parameters:
540
-
541
- ```js
542
- // Bad — api/payment.js:12-33 (18 parameters)
543
- updatePaymentInfo: ({
544
- bankCode, branch, branchCode, holderName, bankAccount,
545
- firstNameTh, lastNameTh, firstNameEn, lastNameEn,
546
- firstNameLocale, lastNameLocale, bonus, paymentProvider,
547
- pixType, bindingType, cryptoCurrency, cryptoNetwork, cryptoAddress,
548
- walletCode, ifscCode,
549
- }) => ({ ... })
550
-
551
- // Good — group related parameters
552
- updatePaymentInfo: ({ bank, name, crypto, options }) => ({ ... })
553
- // bank = { bankCode, branch, branchCode, holderName, bankAccount, ifscCode }
554
- // name = { firstNameTh, lastNameTh, firstNameEn, lastNameEn, firstNameLocale, lastNameLocale }
555
- // crypto = { cryptoCurrency, cryptoNetwork, cryptoAddress }
556
- // options = { bonus, paymentProvider, pixType, bindingType, walletCode }
557
- ```
580
+ `api/payment.js`'s `updatePaymentInfo` receives 18 destructured parameters (`bankCode`, `branch`, `firstNameTh`, ...). Should be grouped as `{ bank, name, crypto, options }`.
558
581
 
559
582
  ### 2.8 Inconsistent Leading Slashes
560
583
 
561
- 3 URLs in `api/user.js` have leading slashes, while all other API modules do not:
562
-
563
- ```js
564
- // Bad — api/user.js:55, 60, 65
565
- url: '/verify/v2/initiate' // leading slash
566
- url: '/otpsso/acknowledge' // leading slash
567
- url: '/otpsso/reset' // leading slash
568
-
569
- // Good — consistent with other modules
570
- url: 'verify/v2/initiate'
571
- url: 'otpsso/acknowledge'
572
- url: 'otpsso/reset'
573
- ```
574
-
575
- > Note: Leading slashes may affect `url-join` path composition behavior, causing it to skip the `baseURL` path.
584
+ In `api/user.js`, `'/verify/v2/initiate'`, `'/otpsso/acknowledge'`, `'/otpsso/reset'` have leading slashes, while all other API modules do not. Leading slashes may affect `url-join`'s path composition, causing the `baseURL` path to be skipped.
576
585
 
577
586
  ### 2.9 Hardcoded URL Query Parameters
578
587
 
579
- Some functions write query parameters directly into the URL instead of using `params`:
580
-
581
- ```js
582
- // Bad — api/auth.js:42
583
- url: `register?${qs}` // manually concatenated query string
584
-
585
- // Bad — api/mailbox.js
586
- url: 'mail?include=cl' // hardcoded query parameter
587
- ```
588
-
589
- This bypasses the parameter serialization mechanism in `request.js`.
588
+ `api/auth.js`'s `register?${qs}` and `api/mailbox.js`'s `mail?include=cl` write query parameters directly into the URL, bypassing the parameter serialization mechanism in `request.js`. Should use the `params` field instead.
590
589
 
591
590
  ---
592
591
 
@@ -603,136 +602,59 @@ Every API call hits the server directly with no client-side caching. High-freque
603
602
  | `getPaymentDetail` | Every deposit/withdrawal page entry | 15+ deposit/withdraw state machines |
604
603
  | `getActivityList` | Every 20 seconds | `activity.js` (`tick * 10`) |
605
604
 
606
- **Impact**: Increases server load, degrades user experience (especially on slow networks).
607
-
608
- **Recommendations**:
609
-
610
- - Introduce TTL caching for infrequently changing data (`getConfig`, `getPaymentDetail`)
611
- - Use `stale-while-revalidate` strategy: return cache first, update in background
605
+ **Recommendations**: introduce TTL caching for infrequently changing data, or use a `stale-while-revalidate` strategy.
612
606
 
613
607
  ### 3.2 Memory Leak — WebSocket Listeners
614
608
 
615
609
  **Severity**: High
616
610
 
617
- `machine/websocket.js:266-320`'s `listenToSocketEvents` callback service registers 7 `.on()` listeners but **never returns a cleanup function**:
611
+ The `listenToSocketEvents` callback service in `machine/websocket.js` registers 7 `.on()` listeners (`activity-info`, `activity-reward-info`, `message-notice-info`, `payment-info`, `connect`, `connect_error`, `disconnect`) but **never returns a cleanup function**.
618
612
 
619
- ```js
620
- // Current code — machine/websocket.js:266-320
621
- listenToSocketEvents: (context) => (callback) => {
622
- const { clientSocket } = context
623
- clientSocket.on('activity-info', (data) => { ... })
624
- clientSocket.on('activity-reward-info', (data) => { ... })
625
- clientSocket.on('message-notice-info', (data) => { ... })
626
- clientSocket.on('payment-info', (data) => { ... })
627
- clientSocket.on('connect', () => { ... })
628
- clientSocket.on('connect_error', (error) => { ... })
629
- clientSocket.on('disconnect', (data) => { ... })
630
- // Missing cleanup return!
631
- }
632
- ```
613
+ In XState v4 callback services, the returned function is the cleanup/teardown function. Missing it causes listeners to accumulate on each reconnection. Fix: extract the handlers into named variables and return a `() => clientSocket.off(event, handler)` cleanup function.
633
614
 
634
- In XState v4 callback services, the returned function is the cleanup/teardown function. Missing it causes listeners to accumulate on each reconnection.
635
-
636
- ```js
637
- // Fixed version
638
- listenToSocketEvents: (context) => (callback) => {
639
- const { clientSocket } = context
640
- const handlers = {
641
- 'activity-info': (data) => {
642
- callback({ type: 'ACTIVITY_INFO', data })
643
- },
644
- 'activity-reward-info': (data) => {
645
- callback({ type: 'ACTIVITY_INFO', data })
646
- },
647
- // ... other handlers
648
- }
649
- Object.entries(handlers).forEach(([event, handler]) => clientSocket.on(event, handler))
650
-
651
- // Cleanup function — remove all listeners
652
- return () => {
653
- Object.entries(handlers).forEach(([event, handler]) => clientSocket.off(event, handler))
654
- }
655
- }
656
- ```
657
-
658
- Additionally, `connectSocket` (`websocket.js:241-264`) registers `connect` and `connect_error` listeners in a Promise that are not cleaned up after Promise resolve/reject.
615
+ Additionally, `connectSocket`'s Promise registers `connect` and `connect_error` listeners that are not cleaned up after Promise resolve/reject either.
659
616
 
660
617
  ### 3.3 No Rate Limiting
661
618
 
662
619
  API calls have no client-side throttling or debouncing:
663
620
 
664
621
  - Some deposit state machines use a `debouncing` state (1000ms delay), but only for calculation requests
665
- - `fetchUserInfo` polling (`auth.js`) and `fetchFeeds` polling (`common.js`) have no backoff strategy — fixed-interval polling, unchanged even on errors
622
+ - `fetchUserInfo` polling and `fetchFeeds` polling have no backoff strategy — fixed-interval polling, unchanged even on errors
666
623
 
667
- **Recommendations**:
668
-
669
- - Use exponential backoff on errors
670
- - Add throttle decorators to critical API calls
624
+ **Recommendations**: use exponential backoff on errors and add throttling to critical API calls.
671
625
 
672
626
  ### 3.4 No Automatic Token Refresh
673
627
 
674
- The response interceptor in `request.js` (`request.js:212-233`) does not handle 401 status codes. When the token expires, requests fail directly and state machines transition to error/exit states.
675
-
676
- **Recommendations**:
628
+ The response interceptor in `request.js` does not handle 401 status codes. When the token expires, requests fail directly and state machines transition to error/exit states.
677
629
 
678
- - Intercept 401 responses and automatically attempt token refresh
679
- - Replay the original request on successful refresh
680
- - Trigger logout flow on refresh failure
630
+ **Recommendations**: intercept 401, attempt automatic token refresh, replay the original request on success; trigger logout on failure.
681
631
 
682
632
  ### 3.5 Unused Context Variables
683
633
 
684
- Multiple state machines declare context fields that are never assigned or read:
685
-
686
- ```js
687
- // machine/activity/activity.js:19
688
- context: {
689
- refs: {}, // Never assigned or read
690
- uidSite: '', // Only written in setUnread action, never initialized
691
- siteConfig: {}, // Set via SET_CONFIG event but never read in guards/services
692
- }
693
-
694
- // machine/websocket.js:16
695
- context: {
696
- analytics: null, // Set externally but not used by the state machine for transitions
697
- }
698
- ```
634
+ Several state machines declare context fields that are never assigned or read, for example:
699
635
 
700
- **Impact**: Increases memory usage, reduces code readability.
636
+ - `machine/activity/activity.js`: `refs: {}` (never used), `uidSite: ''` (never initialized), `siteConfig: {}` (never read)
637
+ - `machine/websocket.js`: `analytics: null` (set externally but not used by the state machine for transitions)
701
638
 
702
- **Recommendation**: Audit all state machine context fields and remove unused definitions.
639
+ **Recommendation**: audit all state-machine context fields and remove unused definitions.
703
640
 
704
641
  ### 3.6 Large State Machine Files
705
642
 
706
643
  Files exceeding 300 lines should be considered for splitting into smaller, composable state machines:
707
644
 
708
- | File | Lines | Suggestion |
709
- | -------------------- | ----- | ------------------------------------------------------------------------- |
710
- | `game_v2_1.js` | 691 | Split game list, categories, pagination into separate state machines |
711
- | `auth.js` | 555 | Extract login flow, token management, user info polling |
712
- | `withdraw_manual.js` | 533 | Extract OTP verification as a reusable child state machine |
713
- | `inbox.js` | 489 | Split notification and message management |
714
- | `manual_vn.js` | 458 | Extract calculation and submission as shared deposit utilities |
715
- | `common.js` | 415 | Already uses parallel states, can further decompose config/feed/broadcast |
716
- | `game_search_v2.js` | 401 | Extract search logic as a reusable state machine |
645
+ | File | Suggestion |
646
+ | -------------------- | ------------------------------------------------------------------------- |
647
+ | `game_v2_1.js` | Split game list, categories, pagination into separate state machines |
648
+ | `auth.js` | Extract login flow, token management, user info polling |
649
+ | `withdraw_manual.js` | Extract OTP verification as a reusable child state machine |
650
+ | `inbox.js` | Split notification and message management |
651
+ | `manual_vn.js` | Extract calculation and submission as shared deposit utilities |
652
+ | `common.js` | Already uses parallel states; can further decompose config/feed/broadcast |
653
+ | `game_search_v2.js` | Extract search logic as a reusable state machine |
717
654
 
718
655
  ### 3.7 Timer Management
719
656
 
720
- 44 instances of self-referencing state transitions with `1000` millisecond timers:
721
-
722
- ```js
723
- // Common pattern — auth_otp_v2.js, withdraw_manual.js, etc.
724
- countdown: {
725
- after: {
726
- 1000: {
727
- target: 'countdown', // self-reference
728
- actions: 'decreaseTtl',
729
- cond: (context) => context.ttl > 0,
730
- },
731
- },
732
- }
733
- ```
734
-
735
- **Impact**: Produces one state transition per second (including context clone + event dispatch).
657
+ 44 places use 1000-millisecond timers with self-referencing state transitions (e.g. countdown `after: { 1000: { target: 'countdown', actions: 'decreaseTtl' } }`), producing one state transition per second (including context clone + event dispatch).
736
658
 
737
659
  **Recommendations**:
738
660
 
@@ -741,68 +663,22 @@ countdown: {
741
663
 
742
664
  ### 3.8 FingerprintJS Bundling Issue
743
665
 
744
- `src/lib/fingerprint_v3_11_12.js` is a **292 KB** embedded FingerprintJS v3.11.12 library.
745
-
746
- ```js
747
- // util/deviceToken.js:2
748
- import { load, defaultEndpoint } from '../lib/fingerprint_v3_11_12.js'
749
- ```
750
-
751
- Even when `enable = false` (device token not used), this 292KB is still loaded at module initialization.
666
+ `src/lib/fingerprint_v3_11_12.js` is a **292 KB** embedded FingerprintJS v3.11.12 library. Even when `enable = false` (device token not used), this 292KB is still loaded at module initialization.
752
667
 
753
668
  **Recommendations**:
754
669
 
755
670
  - Use `@fingerprintjs/fingerprintjs` as an npm dependency
756
- - Use dynamic `import()` for lazy loading:
757
-
758
- ```js
759
- const getDeviceToken = async ({ fpToken, sentry, hosts, enable = true }) => {
760
- if (!enable) return
761
- const { load, defaultEndpoint } = await import('@fingerprintjs/fingerprintjs')
762
- // ...
763
- }
764
- ```
671
+ - Use dynamic `import()` for lazy loading: `await import()` inside `getDeviceToken` before using it
765
672
 
766
673
  ### 3.9 No Code Splitting
767
674
 
768
- `machine/index.js` eagerly imports all 89 state machines:
675
+ `machine/index.js` eagerly imports all 91 state machines + all API modules + FingerprintJS (292KB) + Socket.IO + lodash functions. Importing `machine` loads the entire bundle, even if the consumer only needs 1-2 state machines.
769
676
 
770
- ```js
771
- // machine/index.js (full import chain)
772
- import activity from './activity/index.js' // 24 state machines
773
- import auth from './auth.js'
774
- import deposit from './deposit/index.js' // 23 state machines
775
- import withdraw from './withdraw/index.js' // 4 state machines
776
- // ... 42 import statements total
777
-
778
- export default { ...activity, auth, ...deposit, ...withdraw, ... }
779
- ```
780
-
781
- Importing `machine` loads: all 89 state machine definitions + all API modules + FingerprintJS (292KB) + Socket.IO + lodash functions.
782
-
783
- **Impact**: Large initial load size, even if the user only needs 1-2 state machines.
784
-
785
- **Recommendations**:
786
-
787
- - Support individual imports to enable tree-shaking:
788
-
789
- ```js
790
- // Current (loads everything)
791
- import { machine } from '@jetthai/cuora'
792
- const auth = machine.auth(request)
793
-
794
- // Recommended (on-demand loading)
795
- export { default as auth } from './auth.js'
796
- export { default as websocket } from './websocket.js'
797
- // Consumer:
798
- import { auth } from '@jetthai/cuora/src/machine/index.js'
799
- ```
677
+ **Recommendations**: support individual imports to enable tree-shaking, e.g. `export { default as auth } from './auth.js'`; consumer side: `import { auth } from '@jetthai/cuora/src/machine/index.js'`.
800
678
 
801
679
  ### 3.10 Lodash Usage Optimization
802
680
 
803
- Currently uses individual imports (e.g., `import pickBy from 'lodash/pickBy'`), but can be further optimized:
804
-
805
- **6 functions actually used**:
681
+ The 6 functions actually used:
806
682
 
807
683
  | Function | Files Using It | Native Alternative |
808
684
  | --------------- | -------------- | ------------------------------------------------------------- |
@@ -817,32 +693,4 @@ Currently uses individual imports (e.g., `import pickBy from 'lodash/pickBy'`),
817
693
 
818
694
  - `padStart`, `toNumber` can be directly replaced with native methods
819
695
  - `findLastIndex` is natively supported in modern browsers (Chrome 97+)
820
- - Consider replacing `lodash` with `lodash-es` to support ESM tree-shaking
821
- - Or remove the lodash dependency entirely and use native alternatives
822
-
823
- ---
824
-
825
- ## Appendix: Review Checklist
826
-
827
- ### Clean Code Checks for New/Modified Code
828
-
829
- - [ ] HTTP methods use lowercase (`'get'`, `'post'`)
830
- - [ ] State names follow unified naming (`idle`, `loading`, `fetching`, `submitting`)
831
- - [ ] No magic numbers — use constants defined in `constant.js`
832
- - [ ] No hardcoded strings — error codes and transaction types use constants
833
- - [ ] Imports use relative paths (not package names)
834
- - [ ] lodash imports without `.js` extension
835
- - [ ] URL paths without leading slashes
836
- - [ ] Query parameters use `params` object instead of hardcoding in URL
837
- - [ ] Function parameters do not exceed 5 (group if more)
838
- - [ ] `onError` paired with `actions: 'setError'` to save error info
839
- - [ ] Callback services return cleanup functions
840
- - [ ] Context fields only declare what is actually used
841
-
842
- ### Performance Checks
843
-
844
- - [ ] High-frequency API calls consider caching strategies
845
- - [ ] WebSocket listeners include cleanup functions
846
- - [ ] Timers use reasonable intervals (avoid unnecessary 1-second ticks)
847
- - [ ] New dependencies evaluated for bundle size impact
848
- - [ ] Avoid heavy initialization at module top level
696
+ - Consider replacing `lodash` with `lodash-es` to support ESM tree-shaking, or remove the lodash dependency entirely