@jetthai/cuora 1.1.483-dev.2 → 1.1.483

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.
@@ -6,96 +6,9 @@
6
6
 
7
7
  ---
8
8
 
9
- ## Step 0 — 分析專案並更新 AI_PROMPT_SOURCE.md
10
-
11
- 在同步之前,先掃描專案的實際狀態,確保 `AI_PROMPT_SOURCE.md` 中的數據與程式碼一致。
12
-
13
- ### Part A — 數據校準
14
-
15
- 驗證並更新文件中的統計數據,確保與程式碼一致:
16
-
17
- 1. **版本號**:讀取 `package.json` 的 `version` 欄位,更新文件中的版本號
18
- 2. **檔案數量統計**:
19
- - `src/` 下的 `.js` 檔案總數
20
- - `src/api/` 檔案數
21
- - `src/machine/` 檔案總數(含子目錄),以及狀態機數量(= 總數 - index 檔案數)
22
- - `src/machine/activity/`、`src/machine/deposit/`、`src/machine/withdraw/` 各自檔案數
23
- - `src/util/` 檔案數
24
- 3. **API 函式數量**:對每個 `src/api/*.js` 模組,計算 `=>` 的出現次數以統計函式數
25
- 4. **行數驗證**:驗證以下檔案的實際行數:
26
- - `src/request/request.js`、`src/request/config.js`
27
- - 所有超過 300 行的狀態機檔案(用於「大型狀態機檔案」表格)
28
- 5. **supportVersion2List 端點數**:計算 `request.js` 中 `supportVersion2List` 陣列的實際項目數
29
- 6. **specifyingPath 映射數**:計算 `_convertUrlToKebabCase` 中 `specifyingPath` 的 key 數量
30
- 7. **關鍵行號參照**:驗證文件中引用的行號(如 `request.js:207`、`request.js:254` 等)是否仍然正確,若偏移則更新
31
- 8. **依賴套件版本**:讀取 `package.json` 的 `dependencies`,更新版本號
32
-
33
- ### Part B — Know-How 與架構驗證
34
-
35
- 檢查 `1.7 核心業務流程與關鍵 Know-How` 章節的內容是否仍然反映程式碼的實際行為:
36
-
37
- 1. **認證流程**:讀取 `src/machine/auth.js`,驗證:
38
-
39
- - Token TTL、輪詢間隔、延展機制是否有變
40
- - inline vs login 狀態判斷邏輯(`rank >= 0`)是否有變
41
- - 登入方式是否有新增或移除(檢查全域 `on:` 事件列表)
42
- - OTP 流程是否有調整
43
-
44
- 2. **存款流程**:抽樣讀取 2-3 個 deposit 狀態機,驗證:
45
-
46
- - canonical 流程(loading → promotion → loaded → debouncing → calculating → submitting → submitted)是否有變
47
- - Cash vs Non-Cash 變體的差異描述是否仍然正確
48
- - 是否有新增的存款類型或支付方式
49
-
50
- 3. **提款流程**:讀取 `src/machine/withdraw/withdraw_manual.js`,驗證:
51
-
52
- - 五步驟資格驗證鏈是否有調整
53
- - OTP 平行狀態是否有變
54
-
55
- 4. **WebSocket**:讀取 `src/machine/websocket.js`,驗證:
56
-
57
- - 連線參數、重連策略是否有變
58
- - 事件轉發映射表是否有新增事件
59
-
60
- 5. **Error Machine**:讀取 `src/machine/error.js`,驗證:
61
-
62
- - 錯誤代碼分類是否有新增
63
- - 路由邏輯是否有調整
64
-
65
- 6. **Common Machine**:讀取 `src/machine/common.js`,驗證:
66
-
67
- - 4 個平行子機器的結構是否有變
68
- - siteConfig 解碼方式是否有變
69
-
70
- 7. **API 請求生命週期**:讀取 `src/request/request.js`,驗證:
71
-
72
- - 攔截器邏輯、V2 轉換流程是否有變
73
- - isBlocked 維護模式機制是否有變
74
-
75
- 8. **新增狀態機**:比對 `src/machine/` 目錄與文件中的狀態機分類表,若有新增檔案:
76
- - 判斷歸類(核心/存款/提款/活動/遊戲/使用者/UI)
77
- - 更新分類表中的數量與代表檔案
78
-
79
- ### Part C — Clean Code 規範驗證
80
-
81
- 檢查「二、程式碼品質標準」中列出的問題是否已修正:
82
-
83
- 1. **已修正的問題**:若問題已被修正(如 HTTP 方法大小寫已統一),將該項標記為已修正或移除
84
- 2. **新增的問題**:若發現新的程式碼品質問題,添加到對應章節
85
-
86
- ### 執行方式
87
-
88
- - 使用 shell 指令(`wc -l`、`grep -c`、`find` 等)取得實際數據
89
- - 使用 Agent subagent 平行分析多個核心檔案
90
- - 將每項差異直接修正到 `AI_PROMPT_SOURCE.md` 中
91
- - 若無差異則跳過,不做無意義修改
92
- - 完成後簡短回報哪些項目有更新
93
-
94
- ---
95
-
96
9
  ## Step 1 — 讀取來源檔
97
10
 
98
- 讀取 `AI_PROMPT_SOURCE.md` 完整內容(此時已是 Step 0 更新後的最新版本)。
11
+ 讀取 `AI_PROMPT_SOURCE.md` 完整內容。
99
12
 
100
13
  ---
101
14
 
@@ -17,9 +17,7 @@
17
17
  "mcp__sentry__get_issue_details",
18
18
  "mcp__sentry__search_issues",
19
19
  "Bash(git add:*)",
20
- "Bash(git commit:*)",
21
- "Bash(git branch:*)",
22
- "Bash(git merge:*)"
20
+ "Bash(git commit:*)"
23
21
  ]
24
22
  }
25
23
  }
@@ -148,7 +148,7 @@ State machines **do not directly reference each other**; they communicate indire
148
148
  | `ERR_F106` | OTP verification failed |
149
149
  | `ERR_G106` | Insufficient balance (→ deposit state) |
150
150
  | `ERR_G124` / `ERR_G125` | Free game settlement / forfeit |
151
- | `ERR_800` | Cancelled request (never forwarded to errorHandler, but still rejects to the caller's `onError`) |
151
+ | `ERR_800` | Cancelled request (handled silently) |
152
152
  | `ERR_998` | Network error / 404 (reported to Sentry) |
153
153
 
154
154
  When `error.extend` contains `unfinished_` → unfinished game; the gameCode is everything after the first underscore, taken via `error.extend.split(/_(.+)/)[1]`.
@@ -172,13 +172,6 @@ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll aga
172
172
  - **Injection**: the request interceptor automatically adds `Authorization: Bearer {token}`
173
173
  - **TTL**: token 300 seconds, account info 31 days, cookie data 7 days
174
174
 
175
- **Token revocation & foreground gate** (`request.js`): `revokeToken(token)` and `beginTokenGate(promise, timeoutMs = 3000)` are public `Request` methods with **no caller inside this package** — the downstream frontends call them on logout-class errors and when the app returns to the foreground; changing their signatures or semantics is a public-interface change.
176
-
177
- - **Only the current identity can be revoked**: `revokeToken` only takes effect when `token === getToken()`, so a late error from a previous identity cannot revoke a newly logged-in token. Once in effect, it cancels in-flight requests carrying that token (for the scope, see item 11 of 2.9), and any later non-public `send()` still carrying it rejects `ERR_800` immediately without hitting the network; public requests are unaffected (the token stays in storage while revoked, and `getConfig` around autoLogin must not be wrongly rejected). There is no "un-revoke" API — logging in again changes the token, which lifts the revocation naturally.
178
- - **The token to revoke comes from the error object**: when a token-carrying request fails, `send()` attaches a **non-enumerable** `error.requestToken` (the Bearer token at send time). It is non-enumerable so it doesn't leak through `JSON.stringify` / Sentry serialization — **never make it enumerable, and never copy it into enumerable fields, logs, or Sentry extra**. Cancellation `ERR_800` errors and the missing-token `ERR_A103` don't carry this field.
179
- - **While a gate is active**: non-public requests first wait for the probe promise to settle (success and failure both release it) or for the timeout; once released, they re-check whether the token has been revoked and whether it still exists (missing → `ERR_A103`).
180
- - **Hard-coded `'self'` coupling**: `send()` decides which request skips the gate by checking whether the descriptor's raw `url` (query stripped, before V2 conversion) is `'self'`, which corresponds to `getUserInfo` in `api/user.js` (`updateUserInfo`, sharing the same url, skips it too). Changing `getUserInfo`'s url (adding a leading slash, changing the path) requires updating this check in lockstep, otherwise `/self` gets blocked by the gate as well — a probe sent after the gate is created would then wait on its own gate until the timeout.
181
-
182
175
  **inline vs login states** (the most central concept in `auth.js`):
183
176
 
184
177
  - `inline`: authenticated but `rank < 0` (the account has not finished ranking/activation); polling continues until rank takes effect
@@ -334,20 +327,19 @@ io(`${socketURL}/frontend`, {
334
327
  ```
335
328
  1. A state machine service calls request.send(api.xxx(params))
336
329
  2. api.xxx(params) returns a descriptor object
337
- 3. Identity pre-checks (non-public only): no token → reject ERR_A103; token revoked via revokeToken → reject ERR_800; gate active and url is not 'self' → wait for the gate, then re-check (see 2.1)
338
- 4. Token-carrying request without customToken → attach a one-time CancelToken source and register it in activeRequests, removed in finally (see item 11 of 2.9)
330
+ 3. _checkToken(req): non-public endpoints check the token; if missing, throw ERR_A103
331
+ 4. isBlocked check: under maintenance and not a config request → silently blocked
339
332
  5. _createConfig(req):
340
333
  a. Strip the query string from the URL
341
334
  b. Match against supportVersion2List (supports :param dynamic-path regex matching)
342
335
  c. If matched → _convertUrlToKebabCase() (look up the specifyingPath mapping first, otherwise auto-convert)
343
336
  d. GET → params goes in the params field; POST → params goes in the data field
344
337
  e. pickBy filters out null/undefined values
345
- 6. isBlocked check: under maintenance and not a config request → no request is sent, resolves undefined
346
- 7. Request interceptor: injects X-TH1GAMES-VERSION, X-TH1GAMES-PLATFORM, Authorization
347
- 8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
348
- 9. axios.request(config)
349
- 10. Response interceptor: response.data.error present → reject; Network Error / 404 → ERR_998 + Sentry
350
- 11. Error handling (in order): cancellation → reject ERR_800 (never reaches errorHandler); token-carrying requests get a non-enumerable requestToken attached to the error; ERR_F108 → isBlocked + errorHandler; stale-identity error → thrown directly (see item 14 of 2.9); ERR_998 → thrown directly; everything else → errorHandler (skipped when the descriptor carries silent: true, still thrown); non-cancellation error whose code is already ERR_800 → resolves undefined
338
+ 6. Request interceptor: injects X-TH1GAMES-VERSION, X-TH1GAMES-PLATFORM, Authorization
339
+ 7. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
340
+ 8. axios.request(config)
341
+ 9. Response interceptor: response.data.error present → reject; Network Error / 404 → ERR_998 + Sentry
342
+ 10. Error handling: ERR_F108 → isBlocked + errorHandler; ERR_998 → thrown directly; ERR_800 (cancelled) → silent; everything else → errorHandler (skipped when the descriptor carries silent: true, still thrown)
351
343
  ```
352
344
 
353
345
  **V1→V2 conversion**: `supportVersion2List` supports dynamic paths (e.g. `payment/v2/:paymentType/transaction`, where `:param` is replaced by `[^/]+`); special paths are hard-coded in `specifyingPath`, and the rest are auto-converted via `/([a-z])([A-Z])/g`. **When adding an endpoint that needs V2 conversion, it must be added to the list manually.**
@@ -364,10 +356,9 @@ io(`${socketURL}/frontend`, {
364
356
  8. **`appSecret` marks public endpoints**: nearly all `isPublic: true` endpoints require an `appSecret` parameter, **but the auth endpoints do not**.
365
357
  9. **Unfinished-game infinite retry**: the `unfinishedGame` state in `error.js` returns to itself on `onError`, with **no backoff strategy and no retry cap** (a known issue, see "Known Technical Debt").
366
358
  10. **`isMobile` is a string, not a boolean**: in `common.js`, `isMobile = userAgent?.device?.type` returns `'mobile'`/`'tablet'`/`undefined`, so comparisons must be string-based (e.g. `isMobile === 'mobile' ? 'y' : null`).
367
- 11. **CancelTokens must be one-time, never shared**: a token-carrying non-public request that passes no `customToken` gets its own **one-time** `CancelToken.source()` (registered in `activeRequests`, removed in `finally`, collected along with the request) so that `revokeToken` can cancel in-flight requests; when `customToken` is passed, it is used instead, the caller manages its lifecycle, and it is not registered (`revokeToken` cannot cancel it). In axios <0.22 the cancel handler is never unsubscribed — a shared long-lived token accumulates one handler per request, causing overnight OOM when left running (TI-15555). **Do not turn the one-time source into a shared token.** The one-time source is only created when the injected `axios` exposes `CancelToken` (axios's default export and `@nuxtjs/axios`'s `$axios` do; instances produced by `axios.create()` don't); without it, `revokeToken` cannot abort in-flight requests and only blocks subsequent `send()` calls.
359
+ 11. **Requests carry no CancelToken by default**: the cancellation feature of `send(req, customToken)` is **opt-in**. In axios <0.22 the cancel handler is never unsubscribed — a shared long-lived token accumulates one handler per request, causing overnight OOM when left running (TI-15555). **Do not "helpfully" add the CancelToken back onto the shared path.**
368
360
  12. **`silent: true` only skips errorHandler**: the error is still thrown to the caller's `onError`, and `ERR_F108` is still routed as usual; but every other error code — **including logout-class codes such as `ERR_A104`, and `ERR_G106` insufficient balance** — never reaches the error machine. Use it only for background requests whose session invalidation is already covered by `fetchUserInfo` polling; never add it to user-initiated requests.
369
- 13. **`send()` does not guarantee an object, and `assign()` must never throw**: non-config requests during maintenance (`isBlocked`) and non-cancellation errors that already carry `code: 'ERR_800'` make `send()` **resolve `undefined`** (they never reach `onError`); a 200 response with a non-JSON body resolves a string, so destructuring `{ data }` yields `undefined`. Cancellations (`customToken` cancellation, `revokeToken` revocation), by contrast, reject with `ERR_800` and **do reach `onError`** — they never resolve `undefined`. When an `assign()` throws, XState v4 clears the event queue and the state is not updated — the machine stays in the current invoke state and `after`-based polling stops until an external event (e.g. `REFRESH`) moves it out. **Validate response shapes inside the service and `throw` there (reject → `onError`)**; every assign in `onDone` must handle every value the service can resolve, including deliberate `return null` early exits.
370
- 14. **Late errors from a stale identity never reach errorHandler**: when the token a request was sent with differs from the current token (and a current token exists), the error is only thrown to the caller's `onError` and not forwarded to errorHandler — so a late logout-class error from an old session can't log out a newly logged-in identity. When there is no current token (TTL expired or already cleared), routing is unchanged so that `ERR_A204`-style popups aren't swallowed; the `ERR_F108` check comes before this one and still routes as usual.
361
+ 13. **`send()` does not guarantee an object, and `assign()` must never throw**: non-config requests during maintenance (`isBlocked`) and `ERR_800` cancellations make `send()` **resolve `undefined`** (they never reach `onError`); a 200 response with a non-JSON body resolves a string, so destructuring `{ data }` yields `undefined`. When an `assign()` throws, XState v4 clears the event queue and the state is not updated — the machine stays in the current invoke state and `after`-based polling stops until an external event (e.g. `REFRESH`) moves it out. **Validate response shapes inside the service and `throw` there (reject → `onError`)**; every assign in `onDone` must handle every value the service can resolve, including deliberate `return null` early exits.
371
362
 
372
363
  ---
373
364
 
@@ -19,14 +19,14 @@ if [ "$match" = "1" ]; then
19
19
  # 檢查本地是否有尚未推送的 commit,有的話跳過自動拉取(避免覆蓋本地變更)
20
20
  LOCAL_AHEAD=$(git rev-list --count origin/"$CURRENT_BRANCH"..HEAD 2>/dev/null || echo 0)
21
21
  if [ "$LOCAL_AHEAD" -gt 0 ]; then
22
- echo "You have $LOCAL_AHEAD unpushed commit(s) on '$CURRENT_BRANCH'. Skipping auto-pull."
22
+ echo "分支 '$CURRENT_BRANCH' 有 $LOCAL_AHEAD 個尚未推送的 commit,略過自動拉取。"
23
23
  exit 0
24
24
  fi
25
25
 
26
26
  # 自動從遠端拉取最新程式碼(使用 rebase 保持線性歷史)
27
- echo "Auto pulling '$CURRENT_BRANCH' from remote..."
27
+ echo "正在從遠端自動拉取 '$CURRENT_BRANCH'..."
28
28
  git pull --rebase origin "$CURRENT_BRANCH" || {
29
- echo "Failed to pull '$CURRENT_BRANCH'. Please resolve manually."
29
+ echo "拉取 '$CURRENT_BRANCH' 失敗,請手動處理。"
30
30
  exit 1
31
31
  }
32
32
  fi
package/.husky/pre-push CHANGED
@@ -21,7 +21,7 @@ BRANCH=$(git rev-parse --abbrev-ref HEAD)
21
21
 
22
22
  # 在 dev/qa 分支的 force push 跳過所有 pre-push hook(避免干擾強制推送)
23
23
  if [ "$IS_FORCE" = true ] && { [ "$BRANCH" = "dev" ] || [ "$BRANCH" = "qa" ]; }; then
24
- echo "Force push detected on $BRANCH, skipping pre-push hooks."
24
+ echo "偵測到在 $BRANCH 分支上強制推送,略過 pre-push hooks。"
25
25
  exit 0
26
26
  fi
27
27
 
package/.prettierignore CHANGED
@@ -1,2 +1 @@
1
- dist/
2
- CHANGELOG.md
1
+ dist/
package/AGENTS.md CHANGED
@@ -148,7 +148,7 @@ State machines **do not directly reference each other**; they communicate indire
148
148
  | `ERR_F106` | OTP verification failed |
149
149
  | `ERR_G106` | Insufficient balance (→ deposit state) |
150
150
  | `ERR_G124` / `ERR_G125` | Free game settlement / forfeit |
151
- | `ERR_800` | Cancelled request (never forwarded to errorHandler, but still rejects to the caller's `onError`) |
151
+ | `ERR_800` | Cancelled request (handled silently) |
152
152
  | `ERR_998` | Network error / 404 (reported to Sentry) |
153
153
 
154
154
  When `error.extend` contains `unfinished_` → unfinished game; the gameCode is everything after the first underscore, taken via `error.extend.split(/_(.+)/)[1]`.
@@ -172,13 +172,6 @@ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll aga
172
172
  - **Injection**: the request interceptor automatically adds `Authorization: Bearer {token}`
173
173
  - **TTL**: token 300 seconds, account info 31 days, cookie data 7 days
174
174
 
175
- **Token revocation & foreground gate** (`request.js`): `revokeToken(token)` and `beginTokenGate(promise, timeoutMs = 3000)` are public `Request` methods with **no caller inside this package** — the downstream frontends call them on logout-class errors and when the app returns to the foreground; changing their signatures or semantics is a public-interface change.
176
-
177
- - **Only the current identity can be revoked**: `revokeToken` only takes effect when `token === getToken()`, so a late error from a previous identity cannot revoke a newly logged-in token. Once in effect, it cancels in-flight requests carrying that token (for the scope, see item 11 of 2.9), and any later non-public `send()` still carrying it rejects `ERR_800` immediately without hitting the network; public requests are unaffected (the token stays in storage while revoked, and `getConfig` around autoLogin must not be wrongly rejected). There is no "un-revoke" API — logging in again changes the token, which lifts the revocation naturally.
178
- - **The token to revoke comes from the error object**: when a token-carrying request fails, `send()` attaches a **non-enumerable** `error.requestToken` (the Bearer token at send time). It is non-enumerable so it doesn't leak through `JSON.stringify` / Sentry serialization — **never make it enumerable, and never copy it into enumerable fields, logs, or Sentry extra**. Cancellation `ERR_800` errors and the missing-token `ERR_A103` don't carry this field.
179
- - **While a gate is active**: non-public requests first wait for the probe promise to settle (success and failure both release it) or for the timeout; once released, they re-check whether the token has been revoked and whether it still exists (missing → `ERR_A103`).
180
- - **Hard-coded `'self'` coupling**: `send()` decides which request skips the gate by checking whether the descriptor's raw `url` (query stripped, before V2 conversion) is `'self'`, which corresponds to `getUserInfo` in `api/user.js` (`updateUserInfo`, sharing the same url, skips it too). Changing `getUserInfo`'s url (adding a leading slash, changing the path) requires updating this check in lockstep, otherwise `/self` gets blocked by the gate as well — a probe sent after the gate is created would then wait on its own gate until the timeout.
181
-
182
175
  **inline vs login states** (the most central concept in `auth.js`):
183
176
 
184
177
  - `inline`: authenticated but `rank < 0` (the account has not finished ranking/activation); polling continues until rank takes effect
@@ -334,20 +327,19 @@ io(`${socketURL}/frontend`, {
334
327
  ```
335
328
  1. A state machine service calls request.send(api.xxx(params))
336
329
  2. api.xxx(params) returns a descriptor object
337
- 3. Identity pre-checks (non-public only): no token → reject ERR_A103; token revoked via revokeToken → reject ERR_800; gate active and url is not 'self' → wait for the gate, then re-check (see 2.1)
338
- 4. Token-carrying request without customToken → attach a one-time CancelToken source and register it in activeRequests, removed in finally (see item 11 of 2.9)
330
+ 3. _checkToken(req): non-public endpoints check the token; if missing, throw ERR_A103
331
+ 4. isBlocked check: under maintenance and not a config request → silently blocked
339
332
  5. _createConfig(req):
340
333
  a. Strip the query string from the URL
341
334
  b. Match against supportVersion2List (supports :param dynamic-path regex matching)
342
335
  c. If matched → _convertUrlToKebabCase() (look up the specifyingPath mapping first, otherwise auto-convert)
343
336
  d. GET → params goes in the params field; POST → params goes in the data field
344
337
  e. pickBy filters out null/undefined values
345
- 6. isBlocked check: under maintenance and not a config request → no request is sent, resolves undefined
346
- 7. Request interceptor: injects X-TH1GAMES-VERSION, X-TH1GAMES-PLATFORM, Authorization
347
- 8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
348
- 9. axios.request(config)
349
- 10. Response interceptor: response.data.error present → reject; Network Error / 404 → ERR_998 + Sentry
350
- 11. Error handling (in order): cancellation → reject ERR_800 (never reaches errorHandler); token-carrying requests get a non-enumerable requestToken attached to the error; ERR_F108 → isBlocked + errorHandler; stale-identity error → thrown directly (see item 14 of 2.9); ERR_998 → thrown directly; everything else → errorHandler (skipped when the descriptor carries silent: true, still thrown); non-cancellation error whose code is already ERR_800 → resolves undefined
338
+ 6. Request interceptor: injects X-TH1GAMES-VERSION, X-TH1GAMES-PLATFORM, Authorization
339
+ 7. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
340
+ 8. axios.request(config)
341
+ 9. Response interceptor: response.data.error present → reject; Network Error / 404 → ERR_998 + Sentry
342
+ 10. Error handling: ERR_F108 → isBlocked + errorHandler; ERR_998 → thrown directly; ERR_800 (cancelled) → silent; everything else → errorHandler (skipped when the descriptor carries silent: true, still thrown)
351
343
  ```
352
344
 
353
345
  **V1→V2 conversion**: `supportVersion2List` supports dynamic paths (e.g. `payment/v2/:paymentType/transaction`, where `:param` is replaced by `[^/]+`); special paths are hard-coded in `specifyingPath`, and the rest are auto-converted via `/([a-z])([A-Z])/g`. **When adding an endpoint that needs V2 conversion, it must be added to the list manually.**
@@ -364,10 +356,9 @@ io(`${socketURL}/frontend`, {
364
356
  8. **`appSecret` marks public endpoints**: nearly all `isPublic: true` endpoints require an `appSecret` parameter, **but the auth endpoints do not**.
365
357
  9. **Unfinished-game infinite retry**: the `unfinishedGame` state in `error.js` returns to itself on `onError`, with **no backoff strategy and no retry cap** (a known issue, see "Known Technical Debt").
366
358
  10. **`isMobile` is a string, not a boolean**: in `common.js`, `isMobile = userAgent?.device?.type` returns `'mobile'`/`'tablet'`/`undefined`, so comparisons must be string-based (e.g. `isMobile === 'mobile' ? 'y' : null`).
367
- 11. **CancelTokens must be one-time, never shared**: a token-carrying non-public request that passes no `customToken` gets its own **one-time** `CancelToken.source()` (registered in `activeRequests`, removed in `finally`, collected along with the request) so that `revokeToken` can cancel in-flight requests; when `customToken` is passed, it is used instead, the caller manages its lifecycle, and it is not registered (`revokeToken` cannot cancel it). In axios <0.22 the cancel handler is never unsubscribed — a shared long-lived token accumulates one handler per request, causing overnight OOM when left running (TI-15555). **Do not turn the one-time source into a shared token.** The one-time source is only created when the injected `axios` exposes `CancelToken` (axios's default export and `@nuxtjs/axios`'s `$axios` do; instances produced by `axios.create()` don't); without it, `revokeToken` cannot abort in-flight requests and only blocks subsequent `send()` calls.
359
+ 11. **Requests carry no CancelToken by default**: the cancellation feature of `send(req, customToken)` is **opt-in**. In axios <0.22 the cancel handler is never unsubscribed — a shared long-lived token accumulates one handler per request, causing overnight OOM when left running (TI-15555). **Do not "helpfully" add the CancelToken back onto the shared path.**
368
360
  12. **`silent: true` only skips errorHandler**: the error is still thrown to the caller's `onError`, and `ERR_F108` is still routed as usual; but every other error code — **including logout-class codes such as `ERR_A104`, and `ERR_G106` insufficient balance** — never reaches the error machine. Use it only for background requests whose session invalidation is already covered by `fetchUserInfo` polling; never add it to user-initiated requests.
369
- 13. **`send()` does not guarantee an object, and `assign()` must never throw**: non-config requests during maintenance (`isBlocked`) and non-cancellation errors that already carry `code: 'ERR_800'` make `send()` **resolve `undefined`** (they never reach `onError`); a 200 response with a non-JSON body resolves a string, so destructuring `{ data }` yields `undefined`. Cancellations (`customToken` cancellation, `revokeToken` revocation), by contrast, reject with `ERR_800` and **do reach `onError`** — they never resolve `undefined`. When an `assign()` throws, XState v4 clears the event queue and the state is not updated — the machine stays in the current invoke state and `after`-based polling stops until an external event (e.g. `REFRESH`) moves it out. **Validate response shapes inside the service and `throw` there (reject → `onError`)**; every assign in `onDone` must handle every value the service can resolve, including deliberate `return null` early exits.
370
- 14. **Late errors from a stale identity never reach errorHandler**: when the token a request was sent with differs from the current token (and a current token exists), the error is only thrown to the caller's `onError` and not forwarded to errorHandler — so a late logout-class error from an old session can't log out a newly logged-in identity. When there is no current token (TTL expired or already cleared), routing is unchanged so that `ERR_A204`-style popups aren't swallowed; the `ERR_F108` check comes before this one and still routes as usual.
361
+ 13. **`send()` does not guarantee an object, and `assign()` must never throw**: non-config requests during maintenance (`isBlocked`) and `ERR_800` cancellations make `send()` **resolve `undefined`** (they never reach `onError`); a 200 response with a non-JSON body resolves a string, so destructuring `{ data }` yields `undefined`. When an `assign()` throws, XState v4 clears the event queue and the state is not updated — the machine stays in the current invoke state and `after`-based polling stops until an external event (e.g. `REFRESH`) moves it out. **Validate response shapes inside the service and `throw` there (reject → `onError`)**; every assign in `onDone` must handle every value the service can resolve, including deliberate `return null` early exits.
371
362
 
372
363
  ---
373
364
 
@@ -146,7 +146,7 @@ export default function (request) {
146
146
  | `ERR_F106` | OTP 驗證失敗 |
147
147
  | `ERR_G106` | 餘額不足(→ deposit 狀態) |
148
148
  | `ERR_G124` / `ERR_G125` | 免費遊戲結算 / 放棄 |
149
- | `ERR_800` | 已取消請求(不進 errorHandler,但會 reject 給呼叫端 `onError`) |
149
+ | `ERR_800` | 已取消請求(靜默處理) |
150
150
  | `ERR_998` | 網路錯誤 / 404(回報 Sentry) |
151
151
 
152
152
  `error.extend` 含 `unfinished_` → 未完成遊戲,gameCode 以 `error.extend.split(/_(.+)/)[1]` 取第一個底線後的全部內容。
@@ -170,13 +170,6 @@ Token 5min TTL → fetchUserInfo 成功 → extendToken 重設 TTL → 再次輪
170
170
  - **注入方式**:請求攔截器自動添加 `Authorization: Bearer {token}`
171
171
  - **TTL**:Token 300 秒、帳號資訊 31 天、Cookie 資料 7 天
172
172
 
173
- **Token 作廢與回前景閘門**(`request.js`):`revokeToken(token)` 與 `beginTokenGate(promise, timeoutMs = 3000)` 是 `Request` 的公開方法,**本套件內沒有呼叫端**,由下游前端在收到登出類錯誤、App 回前景時呼叫;改簽名或語意屬對外介面變動。
174
-
175
- - **只作廢目前身分**:`revokeToken` 只在 `token === getToken()` 時生效,舊身分遲到的錯誤作廢不了新登入的 Token。生效後取消同 Token 的在途請求(範圍見 2.9 第 11 點),之後仍帶此 Token 的非 public `send()` 不發網路、直接 reject `ERR_800`;public 請求不受影響(作廢期間 Token 仍留在 storage,autoLogin 前後的 `getConfig` 不可被誤拒)。沒有「解除作廢」的 API——重新登入換了 Token 即自然恢復。
176
- - **作廢用的 Token 從錯誤物件取**:帶 Token 的請求失敗時,`send()` 會在錯誤上掛**不可列舉**的 `error.requestToken`(送出當下的 Bearer Token)。不可列舉是為了不隨 `JSON.stringify`/Sentry 序列化外洩——**不要改成可列舉,也不要複製到可列舉欄位、log 或 Sentry extra**。取消類 `ERR_800` 與缺 Token 的 `ERR_A103` 不帶此欄位。
177
- - **閘門期間**:非 public 請求先等探測 promise 結算(成功、失敗都放行)或逾時,放行後再檢查一次是否已作廢、Token 是否還在(不在 → `ERR_A103`)。
178
- - **`'self'` 硬編碼耦合**:`send()` 以描述物件原始 `url`(去掉 query、V2 轉換前)是否為 `'self'` 決定不等閘門,對應 `api/user.js` 的 `getUserInfo`(同 url 的 `updateUserInfo` 也一併不等)。改 `getUserInfo` 的 url(加前導斜線、換路徑)必須同步改這個判斷,否則 `/self` 也會被閘門擋住——探測請求若在閘門建立後才送出,會等自己的閘門直到逾時。
179
-
180
173
  **inline vs login 狀態**(`auth.js` 最核心的概念):
181
174
 
182
175
  - `inline`:已認證但 `rank < 0`(帳號尚未完成排名/開通),持續輪詢等待 rank 生效
@@ -332,20 +325,19 @@ io(`${socketURL}/frontend`, {
332
325
  ```
333
326
  1. 狀態機 service 呼叫 request.send(api.xxx(params))
334
327
  2. api.xxx(params) 回傳描述物件
335
- 3. 身分前置檢查(僅非 public):無 Token → reject ERR_A103;Token 已被 revokeToken 作廢 → reject ERR_800;閘門期間且 url 不是 'self' → 先等閘門再複查(見 2.1)
336
- 4. 帶 Token 且未傳 customToken → 掛一次性 CancelToken source 並登記 activeRequests,finally 移除(見 2.9 第 11 點)
328
+ 3. _checkToken(req):非 public 端點檢查 Token,無則拋 ERR_A103
329
+ 4. isBlocked 檢查:維護中且非 config 請求 → 靜默阻擋
337
330
  5. _createConfig(req):
338
331
  a. URL 去除 query string
339
332
  b. 比對 supportVersion2List(支援 :param 動態路徑正則匹配)
340
333
  c. 若匹配 → _convertUrlToKebabCase()(先查 specifyingPath 映射,否則自動轉換)
341
334
  d. GET → params 放 params 欄位;POST → params 放 data 欄位
342
335
  e. pickBy 過濾 null/undefined 值
343
- 6. isBlocked 檢查:維護中且非 config 請求 → 不發請求,resolve undefined
344
- 7. 請求攔截器:注入 X-TH1GAMES-VERSION、X-TH1GAMES-PLATFORM、Authorization
345
- 8. 自訂 paramsSerializer:q 參數特殊編碼(避免雙重編碼)
346
- 9. axios.request(config)
347
- 10. 回應攔截器:response.data.error 存在 → reject;Network Error / 404 → ERR_998 + Sentry
348
- 11. 錯誤處理(依序):取消類 → reject ERR_800(不進 errorHandler);帶 Token 的請求在錯誤上掛不可列舉的 requestToken;ERR_F108 → isBlocked + errorHandler;舊身分的錯誤 → 直接 throw(見 2.9 第 14 點);ERR_998 → 直接 throw;其餘 → errorHandler(描述物件帶 silent: true 則略過,仍 throw);非取消但 code 已是 ERR_800 → resolve undefined
336
+ 6. 請求攔截器:注入 X-TH1GAMES-VERSION、X-TH1GAMES-PLATFORM、Authorization
337
+ 7. 自訂 paramsSerializer:q 參數特殊編碼(避免雙重編碼)
338
+ 8. axios.request(config)
339
+ 9. 回應攔截器:response.data.error 存在 → reject;Network Error / 404 → ERR_998 + Sentry
340
+ 10. 錯誤處理:ERR_F108 → isBlocked + errorHandler;ERR_998 → 直接 throw;ERR_800(取消)→ 靜默;其餘 → errorHandler(描述物件帶 silent: true 則略過,仍 throw)
349
341
  ```
350
342
 
351
343
  **V1→V2 轉換**:`supportVersion2List` 支援動態路徑(如 `payment/v2/:paymentType/transaction`,`:param` 替換為 `[^/]+`);特殊路徑由 `specifyingPath` 硬編碼映射,其餘用 `/([a-z])([A-Z])/g` 自動轉換。**新增需要 V2 轉換的端點時必須手動加入清單。**
@@ -362,10 +354,9 @@ io(`${socketURL}/frontend`, {
362
354
  8. **`appSecret` 作為公開端點識別**:幾乎所有 `isPublic: true` 端點都需要 `appSecret` 參數,**但認證端點不需要**。
363
355
  9. **unfinished game 無限重試**:`error.js` 的 `unfinishedGame` 狀態在 `onError` 時回到自身,**無退避策略也無重試上限**(已知問題,見「已知技術債」)。
364
356
  10. **`isMobile` 是字串非布林值**:`common.js` 中 `isMobile = userAgent?.device?.type`,回傳 `'mobile'`/`'tablet'`/`undefined`,判斷時需比較字串(如 `isMobile === 'mobile' ? 'y' : null`)。
365
- 11. **CancelToken 只能一次性、不可共用**:帶 Token 的非 public 請求在未傳 `customToken` 時,會各自建立**一次性** `CancelToken.source()`(登記在 `activeRequests`、`finally` 移除,隨請求回收),讓 `revokeToken` 能取消在途請求;傳了 `customToken` 則改用它、由呼叫端自行管理生命週期,也不登記(`revokeToken` 取消不到)。axios <0.22 的取消 handler 永不退訂——共用長壽命 token 會隨請求數累積 handler,導致掛機過夜 OOM(TI-15555)。**不要把一次性 source 改成共用 token。**一次性 source 只在注入的 `axios` 帶有 `CancelToken` 時才建立(axios 預設匯出與 `@nuxtjs/axios` 的 `$axios` 有,`axios.create()` 產生的實例沒有);沒有時 `revokeToken` 無法中止在途請求,只擋得住之後的 `send()`。
357
+ 11. **請求預設不附加 CancelToken**:`send(req, customToken)` 的取消功能為**選擇性啟用**。axios <0.22 的取消 handler 永不退訂——共用長壽命 token 會隨請求數累積 handler,導致掛機過夜 OOM(TI-15555)。**不要「順手」把 CancelToken 加回共用路徑。**
366
358
  12. **`silent: true` 只略過 errorHandler**:錯誤仍會 throw 給呼叫端的 `onError`,`ERR_F108` 也照常路由;但其餘錯誤碼——**包含 `ERR_A104` 等登出類、`ERR_G106` 餘額不足**——都不會進 error machine。只用於背景呼叫、且 session 失效另有 `fetchUserInfo` 輪詢兜底的請求;使用者主動觸發的請求不可加。
367
- 13. **`send()` 不保證回傳物件,`assign()` 內不可拋錯**:維護中(`isBlocked`)的非 config 請求、以及本身已帶 `code: 'ERR_800'` 的非取消錯誤會讓 `send()` **resolve `undefined`**(不進 `onError`);200 但 body 非 JSON 時 resolve 字串,解構 `{ data }` 得到 `undefined`。取消類(`customToken` 取消、`revokeToken` 作廢)則是 reject `ERR_800`,**會進 `onError`**,不會 resolve `undefined`。XState v4 在 `assign()` 內拋錯會清空事件佇列且狀態不更新——machine 停在當前 invoke 狀態、`after` 輪詢中止,直到外部事件(如 `REFRESH`)才離開。**回應格式驗證放 service 內 `throw`(reject → `onError`)**;`onDone` 的每個 assign 都必須承受 service 所有可能的 resolve 值,含刻意 `return null` 的早退路徑。
368
- 14. **舊身分遲到的錯誤不進 errorHandler**:請求送出時的 Token 與目前 Token 不同(且目前仍有 Token)時,錯誤只 throw 給呼叫端的 `onError`、不轉 errorHandler——避免舊 session 遲到的登出類錯誤把新登入的身分登出。目前沒有 Token(TTL 過期或已清除)時照原路由,`ERR_A204` 等彈窗才不會被吞;`ERR_F108` 的判斷在此之前,照常路由。
359
+ 13. **`send()` 不保證回傳物件,`assign()` 內不可拋錯**:維護中(`isBlocked`)的非 config 請求與 `ERR_800` 取消會讓 `send()` **resolve `undefined`**(不進 `onError`);200 但 body 非 JSON 時 resolve 字串,解構 `{ data }` 得到 `undefined`。XState v4 在 `assign()` 內拋錯會清空事件佇列且狀態不更新——machine 停在當前 invoke 狀態、`after` 輪詢中止,直到外部事件(如 `REFRESH`)才離開。**回應格式驗證放 service 內 `throw`(reject → `onError`)**;`onDone` 的每個 assign 都必須承受 service 所有可能的 resolve 值,含刻意 `return null` 的早退路徑。
369
360
 
370
361
  ---
371
362