@jetthai/cuora 1.1.413-dev-3 → 1.1.413-dev-8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -1,64 +1,848 @@
1
1
  # CLAUDE.md
2
2
 
3
- This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
3
+ <!-- AUTO-SYNCED FROM AI_PROMPT_SOURCE.md — DO NOT EDIT DIRECTLY -->
4
4
 
5
- ## 專案概述
5
+ > This file provides guidance for Claude Code (claude.ai/code) when working in this project.
6
6
 
7
- `@jetthai/cuora` 是一個 ESM JavaScript 函式庫,透過 XState 狀態機整合 API 呼叫與業務邏輯,服務於線上遊戲平台。處理認證、支付(存款/提款)、遊戲管理、活動及即時 WebSocket 通訊。設計用於 Nuxt.js 客戶端應用程式(`ssr: false`)。
7
+ ---
8
8
 
9
- ## 指令
9
+ ## 1. Project Architecture
10
10
 
11
- - **格式化程式碼:** `npm run format`(Prettier)
12
- - **發佈版本:** `npm run release`(standard-version + git push + npm publish)
13
- - **發佈並標記為 latest:** `npm run release:latest`
11
+ ### 1.1 Project Overview & Tech Stack
14
12
 
15
- 沒有建置步驟、測試框架或 linter — 原始 `.js` 檔案直接以 ES modules 形式發佈。
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`).
16
14
 
17
- ## Pre-commit Hook
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 .`
18
20
 
19
- Husky 在每次 commit 時執行 `npm run format && git add .`,所有程式碼在提交前會自動格式化。
21
+ ### 1.2 Entry Point & Module Exports
20
22
 
21
- ## 程式碼風格
23
+ **File**: `src/index.js`
22
24
 
23
- Prettier 設定(`.prettierrc`):不加分號、單引號、尾隨逗號(ES5)、2 空格縮排、150 字元行寬。
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'
24
31
 
25
- ## 架構
32
+ export { api, machine, Request, Config, util, constant, storage }
33
+ ```
26
34
 
27
- ### 進入點(`src/index.js`)
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) |
28
44
 
29
- 匯出六個模組:`api`、`machine`、`Request`、`Config`、`util`(含 `constant`、`storage`)。
45
+ ### 1.3 Four-Layer Architecture
30
46
 
31
- ### 請求層(`src/request/`)
47
+ #### 1.3.1 Request Layer
32
48
 
33
- - **`Request.js`** — Axios 封裝,包含攔截器處理認證 token(Bearer)、API 版本控制(透過 `supportVersion2List` 自動將 158+ 個端點從 V1 轉換為 V2 路徑)、維護模式偵測(`ERR_F108`)及自訂參數序列化。
34
- - **`Config.js`** — 設定類別(apiURL、clientId、appSecret、platform、socketURL 等),透過 `url-join` 組合完整 API URL。
49
+ **Files**: `src/request/request.js` (363 lines), `src/request/config.js` (39 lines)
35
50
 
36
- ### API 層(`src/api/`)
51
+ **Request class** (`request.js`):
37
52
 
38
- 函式模組回傳請求描述物件,格式為 `{ url, method, params, isPublic?, headers?, isFormData? }`。模組包含:`auth`、`account`、`activity`、`common`、`form`、`game`、`mailbox`、`otp`、`payment`、`ranking`、`user`。
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`)
39
58
 
40
- ### 狀態機層(`src/machine/`)
59
+ **Config class** (`config.js`):
41
60
 
42
- 約 40 個 XState(v4)狀態機工廠函式,每個接收 `request` 物件並回傳 `createMachine()` 定義。主要分類:
61
+ - Composes `fullURL = urljoin(apiURL, apiVersion, clientId)` (`config.js:26`)
62
+ - `setApiURL(url)` dynamically updates the API base URL
43
63
 
44
- - **核心:** `auth.js`(登入/註冊流程、token 管理)、`common.js`(平行狀態機處理網站設定、user-agent、聯盟行銷)、`error.js`
45
- - **支付 — deposit/**(22 個狀態機):直接、手動、QR 碼、加密貨幣(USDT)、虛擬銀行、儲值卡 — 每個皆有 載入 → 銀行選擇 → 金額輸入 → 計算 → 提交 流程
46
- - **支付 — withdraw/**(4 個狀態機):手動、加密貨幣、krway 等變體
47
- - **活動 Activity/**(24 個狀態機):簽到、排名、炸彈、小遊戲、鑽石商店等
48
- - **遊戲 Game:** 遊戲列表(v2)、收藏、搜尋、熱門/最新、回放、投注單
49
- - **OTP 認證:** `auth_otp_v2.js`、`auth_otp_v3.js`
50
- - **WebSocket:** `websocket.js` — Socket.IO 連線,支援自動重連(最多 3 次)
51
- - **使用者 User:** 註冊、密碼重設、銀行綁定、使用者資訊、頭像
64
+ **Core methods**:
52
65
 
53
- ### 工具模組(`src/util/`)
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`)
54
71
 
55
- - **`storage.js`** — LocalStorage 封裝,支援 TTL/過期機制
56
- - **`deviceToken.js`** — FingerprintJS 整合,含重試邏輯
57
- - **`constant.js`** — 遊戲類型常數(SLOT、FISH、LIVE、SPORT 等)
72
+ #### 1.3.2 API Layer
58
73
 
59
- ### 關鍵模式
74
+ **Directory**: `src/api/` (12 files: 11 modules + `index.js`)
60
75
 
61
- - **工廠模式:** 所有狀態機皆為預設匯出函式,接收 `request` 並回傳 XState 狀態機設定。
62
- - **Token 管理:** 儲存於 localStorage,key 為 `cuora_{clientId}`,透過請求攔截器自動注入。
63
- - **API 版本控制:** `supportVersion2List` 自動將 V1 camelCase 路徑對應至 V2 kebab-case 路徑。
64
- - **錯誤代碼:** `ERR_F108`(維護中)、`ERR_A103`(缺少認證)、`ERR_800`(已取消)、`ERR_998`(網路/404)。
76
+ Each API module exports an object with functions returning request descriptor objects:
77
+
78
+ ```js
79
+ {
80
+ url: string, // API path (relative to fullURL)
81
+ method: string, // HTTP method ('get'/'post'/'put'/'delete')
82
+ params?: object, // Request parameters
83
+ isPublic?: boolean, // true = no auth token required
84
+ headers?: object, // Custom headers (e.g., reCAPTCHA)
85
+ isFormData?: boolean, // true = multipart/form-data
86
+ }
87
+ ```
88
+
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 |
102
+
103
+ #### 1.3.3 Machine Layer (State Machines)
104
+
105
+ **Directory**: `src/machine/` (91 files including index, 89 state machines)
106
+
107
+ All state machines follow the factory pattern — default export function receives a `request` object and returns a `createMachine()` definition.
108
+
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` |
119
+
120
+ **Common state flows**:
121
+
122
+ - **Deposit**: `loading` → `promotion/bonusStatus` → `loaded` (bank/amount selection) → `debouncing` (1000ms) → `calculating` → `submitting` → `submitted`
123
+ - **Withdrawal**: `loading` → `pending` → `cash` (checking → withdrawable → submitting → submitted) → optional OTP verification
124
+ - **Activity**: `idle/init` → `loading/fetching` → `loaded` → reward state (received/receiveable/progress)
125
+
126
+ #### 1.3.4 Util Layer
127
+
128
+ **Directory**: `src/util/` (5 files)
129
+
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 |
137
+
138
+ **Additional**: `src/lib/fingerprint_v3_11_12.js` (292 KB) — embedded FingerprintJS v3.11.12 library.
139
+
140
+ ### 1.4 Directory Structure & File Statistics
141
+
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
180
+
181
+ All state machines follow a unified pattern:
182
+
183
+ ```js
184
+ // src/machine/[name].js
185
+ import { assign, createMachine } from 'xstate'
186
+ import api from '../api/[module].js' // or '../../api/[module].js'
187
+
188
+ export default function (request) {
189
+ const { appSecret } = request.config
190
+ return createMachine(
191
+ {
192
+ id: 'machineName',
193
+ initial: 'loading',
194
+ context: {
195
+ /* initial data */
196
+ },
197
+ states: {
198
+ /* state definitions */
199
+ },
200
+ },
201
+ {
202
+ actions: {
203
+ /* assign operations */
204
+ },
205
+ guards: {
206
+ /* conditional checks */
207
+ },
208
+ services: {
209
+ /* async services */
210
+ },
211
+ }
212
+ )
213
+ }
214
+ ```
215
+
216
+ Some state machines accept additional context: `export default function (request, context)`
217
+
218
+ #### 1.5.2 Token Management
219
+
220
+ - **Storage location**: localStorage, key is `cuora_{clientId}`
221
+ - **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`)
223
+ - **Extension mechanism**: After each successful `fetchUserInfo`, the `extendToken` action updates TTL (`auth.js`)
224
+
225
+ #### 1.5.3 API Versioning (V1 → V2)
226
+
227
+ `supportVersion2List` (`request.js:5-158`) defines 158 endpoints requiring conversion. Conversion logic:
228
+
229
+ 1. Strip query parameters from URL (`url.split('?')[0]`)
230
+ 2. Check if URL is in the V2 support list (supports `:parameter` dynamic path matching)
231
+ 3. If matched, convert path via `_convertUrlToKebabCase()`
232
+ 4. `specifyingPath` mapping handles 19 non-standard conversions (`request.js:324-344`)
233
+ 5. Remaining paths use regex `/([a-z])([A-Z])/g` to convert camelCase to kebab-case
234
+
235
+ #### 1.5.4 Error Code System
236
+
237
+ | Code | Meaning | Source |
238
+ | ---------- | ------------------------------------ | ------------------------------------------------------ |
239
+ | `ERR_F108` | System under maintenance | `request.js:254`, `error.js` |
240
+ | `ERR_A103` | Missing auth token | `request.js:356`, `error.js` |
241
+ | `ERR_A104` | Auth-related error | `error.js` |
242
+ | `ERR_A108` | OTP auth-related | `error.js`, `auth_otp_v2.js`, `user_reset_password.js` |
243
+ | `ERR_A113` | Auth-related error | `error.js` |
244
+ | `ERR_A201` | Logout-related | `error.js` |
245
+ | `ERR_A204` | Logout-related | `error.js` |
246
+ | `ERR_F106` | OTP verification failed | `auth_otp_v3.js` |
247
+ | `ERR_G106` | Insufficient balance | `error.js` |
248
+ | `ERR_G124` | Free game settlement | `error.js` |
249
+ | `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` |
252
+
253
+ ### 1.6 Dependencies & Their Roles
254
+
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` |
263
+
264
+ ---
265
+
266
+ ## 2. Code Quality Standards (Clean Code Guidelines)
267
+
268
+ ### 2.1 Naming Consistency
269
+
270
+ #### 2.1.1 Inconsistent HTTP Method Casing
271
+
272
+ `account.js` and `otp.js` use uppercase `'GET'`/`'POST'`, while the other 9 API modules use lowercase `'get'`/`'post'`.
273
+
274
+ ```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 })
278
+
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 })
282
+ ```
283
+
284
+ > Note: `request.js:317` uses `method.toUpperCase()` so functionality is unaffected, but it creates style inconsistency.
285
+
286
+ #### 2.1.2 Inconsistent State Names
287
+
288
+ Different state machines use different initial state naming:
289
+
290
+ | Name | Usage Frequency | Representative Files |
291
+ | ----------- | --------------- | ---------------------------------------------------------------------- |
292
+ | `idle` | ~30 machines | Most UI state machines |
293
+ | `loading` | ~20 machines | Deposit/withdrawal state machines |
294
+ | `fetching` | ~10 machines | `bank_binding.js`, `game_favorite_v2.js` |
295
+ | `init` | ~5 machines | `side_v2.js`, `game_search_v2.js`, `activity.js` |
296
+ | `preparing` | ~3 machines | `side.js`, `game_hot_new.js` |
297
+ | Other | Few | `normal` (error.js), `inactive` (side_cash.js), `pending` (jackpot.js) |
298
+
299
+ **Recommended conventions**:
300
+
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
306
+
307
+ #### 2.1.3 Ambiguous Parameter Names
308
+
309
+ ```js
310
+ // Bad — api/game.js:3
311
+ addFavoriteGame(code) // What is code? gameCode? providerCode?
312
+
313
+ // Good
314
+ addFavoriteGame(gameCode)
315
+ ```
316
+
317
+ ### 2.2 Magic Numbers & Hardcoded Strings
318
+
319
+ #### 2.2.1 Activity Type IDs
320
+
321
+ ```js
322
+ // Bad — machine/activity/activity.js:13
323
+ context: {
324
+ specifyActivities: [4, 29, 34], // Unexplained numbers
325
+ }
326
+
327
+ // Bad — machine/activity/activity.js (deep inside)
328
+ const noRedActivity = [2, 4, 13, 20, 90, 91, 92] // Unexplained numbers
329
+
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
+ ```
334
+
335
+ #### 2.2.2 Scattered Error Codes
336
+
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:
359
+
360
+ | Value | Purpose | Occurrences |
361
+ | ------------------- | ------------------------ | ------------------------------------- |
362
+ | `300` | Token TTL (5 minutes) | `auth.js` (3 places) |
363
+ | `60 * 60 * 24 * 31` | Account TTL (31 days) | `auth.js` (4 places) |
364
+ | `60 * 60 * 24 * 7` | Cookie TTL (7 days) | `common.js` (6 places) |
365
+ | `1000` | Debounce delay | 44 places (across machine/) |
366
+ | `2000` | Polling tick | `auth.js`, `common.js`, `activity.js` |
367
+ | `6000` | Honor board/Jackpot tick | `honor_board.js`, `jackpot.js` |
368
+ | `30000` | FingerprintJS timeout | `deviceToken.js:19` |
369
+
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
+ ```
385
+
386
+ #### 2.2.4 Hardcoded Transaction Type Strings
387
+
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
406
+
407
+ // Good
408
+ export const SOCKET_STATUS = { DISCONNECTED: 0, CONNECTING: 1, CONNECTED: 2 }
409
+ ```
410
+
411
+ #### 2.2.6 Activity Receive Status Magic Numbers
412
+
413
+ ```js
414
+ // Bad — machine/activity/sign_in_activity.js
415
+ isReceived: (context) => context.receiveStatus === 1
416
+ isReceiveable: (context) => context.receiveStatus === 2
417
+
418
+ // Good
419
+ export const RECEIVE_STATUS = { UNCLAIMED: 0, RECEIVED: 1, CLAIMABLE: 2 }
420
+ ```
421
+
422
+ ### 2.3 Missing Parameter Validation
423
+
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
+ ```
434
+
435
+ **Recommended guidelines**:
436
+
437
+ - Validate critical parameters at system boundaries (API layer)
438
+ - URL path parameters should be checked for non-undefined and no path traversal characters
439
+ - Amount parameters should be confirmed as positive numbers
440
+
441
+ ### 2.4 Inconsistent Error Handling
442
+
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
+ ```
453
+
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
+ ```
471
+
472
+ **Recommended guidelines**:
473
+
474
+ - Consistently use `onError` with `actions: 'setError'` to save error info to context
475
+ - Distinguish recoverable errors (retry) from unrecoverable errors (transition to fail)
476
+ - Set retry limits (e.g., max 3 attempts)
477
+
478
+ ### 2.5 Inconsistent Import Paths
479
+
480
+ #### 2.5.1 Package Name vs Relative Path
481
+
482
+ 10 files use the `@jetthai/cuora` package name instead of relative paths:
483
+
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`
502
+ - `machine/deposit/virtual_bank_cash.js`
503
+ - `machine/activity/sign_in_monthly_activity.js`
504
+
505
+ #### 2.5.2 Inconsistent lodash Import Extensions
506
+
507
+ ```js
508
+ // With .js extension — request.js, machine/auth.js, machine/common.js
509
+ import pickBy from 'lodash/pickBy.js'
510
+
511
+ // Without .js extension — api/auth.js, util/deviceToken.js
512
+ import pickBy from 'lodash/pickBy'
513
+ import uniqBy from 'lodash/uniqBy'
514
+ ```
515
+
516
+ **Recommendation**: Use the form without extension (`'lodash/pickBy'`) consistently, matching lodash official documentation.
517
+
518
+ ### 2.6 V1/V2 Legacy Duplication
519
+
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".
534
+
535
+ **Recommendation**: Add `@deprecated` markers to deprecated functions and remove them after confirming no references.
536
+
537
+ ### 2.7 Parameter Explosion
538
+
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
+ ```
558
+
559
+ ### 2.8 Inconsistent Leading Slashes
560
+
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.
576
+
577
+ ### 2.9 Hardcoded URL Query Parameters
578
+
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`.
590
+
591
+ ---
592
+
593
+ ## 3. Performance, Memory & Rendering Audit
594
+
595
+ ### 3.1 No Request Caching
596
+
597
+ Every API call hits the server directly with no client-side caching. High-frequency endpoints include:
598
+
599
+ | Endpoint | Call Frequency | Trigger Location |
600
+ | ------------------------ | ----------------------------------- | ------------------------------------- |
601
+ | `fetchUserInfo` (`self`) | Every 2-10 seconds | `auth.js` `inline` and `login` states |
602
+ | `getConfig` | Every state machine initialization | `auth.js`, `common.js` |
603
+ | `getPaymentDetail` | Every deposit/withdrawal page entry | 15+ deposit/withdraw state machines |
604
+ | `getActivityList` | Every 20 seconds | `activity.js` (`tick * 10`) |
605
+
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
612
+
613
+ ### 3.2 Memory Leak — WebSocket Listeners
614
+
615
+ **Severity**: High
616
+
617
+ `machine/websocket.js:266-320`'s `listenToSocketEvents` callback service registers 7 `.on()` listeners but **never returns a cleanup function**:
618
+
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
+ ```
633
+
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.
659
+
660
+ ### 3.3 No Rate Limiting
661
+
662
+ API calls have no client-side throttling or debouncing:
663
+
664
+ - 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
666
+
667
+ **Recommendations**:
668
+
669
+ - Use exponential backoff on errors
670
+ - Add throttle decorators to critical API calls
671
+
672
+ ### 3.4 No Automatic Token Refresh
673
+
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**:
677
+
678
+ - Intercept 401 responses and automatically attempt token refresh
679
+ - Replay the original request on successful refresh
680
+ - Trigger logout flow on refresh failure
681
+
682
+ ### 3.5 Unused Context Variables
683
+
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
+ ```
699
+
700
+ **Impact**: Increases memory usage, reduces code readability.
701
+
702
+ **Recommendation**: Audit all state machine context fields and remove unused definitions.
703
+
704
+ ### 3.6 Large State Machine Files
705
+
706
+ Files exceeding 300 lines should be considered for splitting into smaller, composable state machines:
707
+
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 |
717
+
718
+ ### 3.7 Timer Management
719
+
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).
736
+
737
+ **Recommendations**:
738
+
739
+ - Consider using callback services with `setInterval` instead of self-referencing `after` transitions
740
+ - Calculate elapsed time rather than decrementing per-tick to avoid cumulative drift
741
+
742
+ ### 3.8 FingerprintJS Bundling Issue
743
+
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.
752
+
753
+ **Recommendations**:
754
+
755
+ - 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
+ ```
765
+
766
+ ### 3.9 No Code Splitting
767
+
768
+ `machine/index.js` eagerly imports all 89 state machines:
769
+
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
+ ```
800
+
801
+ ### 3.10 Lodash Usage Optimization
802
+
803
+ Currently uses individual imports (e.g., `import pickBy from 'lodash/pickBy'`), but can be further optimized:
804
+
805
+ **6 functions actually used**:
806
+
807
+ | Function | Files Using It | Native Alternative |
808
+ | --------------- | -------------- | ------------------------------------------------------------- |
809
+ | `pickBy` | 4 | `Object.fromEntries(Object.entries(obj).filter(...))` |
810
+ | `uniqBy` | 1 | Custom implementation or `Set` |
811
+ | `findLastIndex` | 2 | `Array.prototype.findLastIndex()` (ES2023) |
812
+ | `padStart` | 2 | `String.prototype.padStart()` |
813
+ | `toNumber` | 1 | `Number()` or `parseFloat()` |
814
+ | `isEqual` | 2 | `JSON.stringify` shallow comparison or custom deep comparison |
815
+
816
+ **Recommendations**:
817
+
818
+ - `padStart`, `toNumber` can be directly replaced with native methods
819
+ - `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