@hupu-tech/shaper 0.2.12 → 0.2.13

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 (184) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +6 -0
  3. package/dist/cli.js +2 -2
  4. package/dist/cloud/client.d.ts +0 -1
  5. package/dist/cloud/service-build.d.ts +2 -4
  6. package/dist/index.js +1 -1
  7. package/dist/project/create.d.ts +9 -3
  8. package/dist/project/delivery.d.ts +5 -5
  9. package/dist/runtime.d.ts +2 -1
  10. package/dist/runtime.js +1 -1
  11. package/dist/shared-2WDEQ3AQ.js +19 -0
  12. package/package.json +1 -1
  13. package/skills/business/SKILL.md +158 -0
  14. package/skills/business/activity/README.md +14 -0
  15. package/skills/business/activity/hupu-leaderboard-template/SKILL.md +52 -0
  16. package/skills/business/activity/hupu-leaderboard-template/example/README.md +20 -0
  17. package/skills/business/activity/hupu-leaderboard-template/example/cloudfunctions/activity_api/.cloudignore +3 -0
  18. package/skills/business/activity/hupu-leaderboard-template/example/cloudfunctions/activity_api/index.js +218 -0
  19. package/skills/business/activity/hupu-leaderboard-template/example/cloudfunctions/activity_api/package.json +15 -0
  20. package/skills/business/activity/hupu-leaderboard-template/example/cloudfunctions/activity_api/scf_bootstrap +3 -0
  21. package/skills/business/activity/hupu-leaderboard-template/example/index.html +291 -0
  22. package/skills/business/activity/hupu-leaderboard-template/example/migrations/20260828210000_create_leaderboard.sql +54 -0
  23. package/skills/business/activity/hupu-lottery-draw/SKILL.md +50 -0
  24. package/skills/business/activity/hupu-lottery-draw/example/README.md +21 -0
  25. package/skills/business/activity/hupu-lottery-draw/example/cloudfunctions/activity_api/.cloudignore +3 -0
  26. package/skills/business/activity/hupu-lottery-draw/example/cloudfunctions/activity_api/index.js +142 -0
  27. package/skills/business/activity/hupu-lottery-draw/example/cloudfunctions/activity_api/package.json +9 -0
  28. package/skills/business/activity/hupu-lottery-draw/example/cloudfunctions/activity_api/scf_bootstrap +3 -0
  29. package/skills/business/activity/hupu-lottery-draw/example/index.html +178 -0
  30. package/skills/business/activity/hupu-lottery-draw/example/migrations/20260828220000_create_draw.sql +193 -0
  31. package/skills/business/activity/hupu-pk-voting/SKILL.md +54 -0
  32. package/skills/business/activity/hupu-pk-voting/example/README.md +44 -0
  33. package/skills/business/activity/hupu-pk-voting/example/cloudfunctions/activity_api/.cloudignore +3 -0
  34. package/skills/business/activity/hupu-pk-voting/example/cloudfunctions/activity_api/index.js +370 -0
  35. package/skills/business/activity/hupu-pk-voting/example/cloudfunctions/activity_api/package.json +15 -0
  36. package/skills/business/activity/hupu-pk-voting/example/cloudfunctions/activity_api/scf_bootstrap +2 -0
  37. package/skills/business/activity/hupu-pk-voting/example/index.html +729 -0
  38. package/skills/business/activity/hupu-pk-voting/example/migrations/20260828220000_create_pk_vote.sql +168 -0
  39. package/skills/business/activity/hupu-request-activity-execute-vote-task/SKILL.md +77 -0
  40. package/skills/business/activity/hupu-request-activity-get-vote-detail/SKILL.md +84 -0
  41. package/skills/business/activity/hupu-request-activity-get-vote-task-list/SKILL.md +86 -0
  42. package/skills/business/activity/hupu-request-activity-list-by-biz-keys/SKILL.md +153 -0
  43. package/skills/business/activity/hupu-request-activity-report-vote-task/SKILL.md +58 -0
  44. package/skills/business/activity/hupu-request-activity-submit-vote/SKILL.md +58 -0
  45. package/skills/business/activity/hupu-vote-task/SKILL.md +47 -0
  46. package/skills/business/community/README.md +13 -0
  47. package/skills/business/community/hupu-request-bbs-detail/SKILL.md +197 -0
  48. package/skills/business/community/hupu-request-bbs-get-tag-thread-list/SKILL.md +257 -0
  49. package/skills/business/community/hupu-request-bbs-get-topic-threads/SKILL.md +159 -0
  50. package/skills/business/community/hupu-request-bbs-gets-thread-post-list/SKILL.md +124 -0
  51. package/skills/business/community/hupu-request-bbs-open-post-editor/SKILL.md +75 -0
  52. package/skills/business/community/hupu-request-bbs-reply-post/SKILL.md +59 -0
  53. package/skills/business/community/hupu-score-add-score/SKILL.md +57 -0
  54. package/skills/business/community/hupu-score-get-item-detail/SKILL.md +173 -0
  55. package/skills/business/community/hupu-score-get-score/SKILL.md +263 -0
  56. package/skills/business/quality/README.md +7 -0
  57. package/skills/business/quality/hupu-security-check-audit/SKILL.md +39 -0
  58. package/skills/business/quality/hupu-wasm-compression/SKILL.md +69 -0
  59. package/skills/business/quality/hupu-wasm-compression/agents/openai.yaml +4 -0
  60. package/skills/business/quality/hupu-wasm-compression/tool/checks.mjs +90 -0
  61. package/skills/business/quality/hupu-wasm-compression/tool/compress-worker.mjs +40 -0
  62. package/skills/business/quality/hupu-wasm-compression/tool/public/app.js +84 -0
  63. package/skills/business/quality/hupu-wasm-compression/tool/public/index.html +80 -0
  64. package/skills/business/quality/hupu-wasm-compression/tool/public/style.css +3 -0
  65. package/skills/business/quality/hupu-wasm-compression/tool/server.mjs +126 -0
  66. package/skills/business/quality/hupu-web-security-audit/SKILL.md +45 -0
  67. package/skills/business/quality/hupu-web-security-audit/agents/openai.yaml +4 -0
  68. package/skills/business/rewards/README.md +13 -0
  69. package/skills/business/rewards/hupu-vacoin/SKILL.md +70 -0
  70. package/skills/business/rewards/hupu-vacoin-consume-coins/SKILL.md +47 -0
  71. package/skills/business/rewards/hupu-vacoin-get-coin-overview/SKILL.md +52 -0
  72. package/skills/business/rewards/hupu-vacoin-get-session-coins/SKILL.md +44 -0
  73. package/skills/business/rewards/hupu-vacoin-reset-session-id/SKILL.md +39 -0
  74. package/skills/business/rewards/hupu-vatask/SKILL.md +63 -0
  75. package/skills/business/rewards/hupu-vatask-complete-reward-video/SKILL.md +43 -0
  76. package/skills/business/rewards/hupu-vatask-consume-activity-chance/SKILL.md +48 -0
  77. package/skills/business/rewards/hupu-vatask-get-activity-task-state/SKILL.md +49 -0
  78. package/skills/business/runtime/README.md +13 -0
  79. package/skills/business/runtime/hupu-add-to-desktop/SKILL.md +51 -0
  80. package/skills/business/runtime/hupu-close-webview/SKILL.md +48 -0
  81. package/skills/business/runtime/hupu-cloud-auth/SKILL.md +43 -0
  82. package/skills/business/runtime/hupu-cloud-request/SKILL.md +56 -0
  83. package/skills/business/runtime/hupu-fullscreen-safe-top/SKILL.md +33 -0
  84. package/skills/business/runtime/hupu-navigate-to/SKILL.md +45 -0
  85. package/skills/business/runtime/hupu-request/SKILL.md +67 -0
  86. package/skills/business/runtime/hupu-seer-chat/SKILL.md +183 -0
  87. package/skills/business/runtime/hupu-track-report/SKILL.md +71 -0
  88. package/skills/business/sharing/README.md +7 -0
  89. package/skills/business/sharing/hupu-oss-upload-file/SKILL.md +40 -0
  90. package/skills/business/sharing/hupu-result-poster-posting/SKILL.md +37 -0
  91. package/skills/business/sharing/hupu-result-poster-posting/example/README.md +14 -0
  92. package/skills/business/sharing/hupu-result-poster-posting/example/cloudfunctions/activity_api/.cloudignore +3 -0
  93. package/skills/business/sharing/hupu-result-poster-posting/example/cloudfunctions/activity_api/index.js +187 -0
  94. package/skills/business/sharing/hupu-result-poster-posting/example/cloudfunctions/activity_api/package.json +15 -0
  95. package/skills/business/sharing/hupu-result-poster-posting/example/cloudfunctions/activity_api/scf_bootstrap +3 -0
  96. package/skills/business/sharing/hupu-result-poster-posting/example/index.html +256 -0
  97. package/skills/business/sharing/hupu-result-poster-posting/example/migrations/20260828213000_create_result_poster_results.sql +60 -0
  98. package/skills/business/sharing/hupu-result-poster-posting/references/api-contract.md +46 -0
  99. package/skills/business/sharing/hupu-social-share/SKILL.md +27 -0
  100. package/skills/business/sports/README.md +27 -0
  101. package/skills/business/sports/hupu-request-basketball-player-info/SKILL.md +131 -0
  102. package/skills/business/sports/hupu-request-basketball-single-match/SKILL.md +158 -0
  103. package/skills/business/sports/hupu-request-basketball-team-info/SKILL.md +96 -0
  104. package/skills/business/sports/hupu-request-basketball-team-player-list/SKILL.md +108 -0
  105. package/skills/business/sports/hupu-request-basketball-team-salary-info/SKILL.md +85 -0
  106. package/skills/business/sports/hupu-request-football-coach-info/SKILL.md +76 -0
  107. package/skills/business/sports/hupu-request-football-live-room-news-list/SKILL.md +85 -0
  108. package/skills/business/sports/hupu-request-football-match-info/SKILL.md +126 -0
  109. package/skills/business/sports/hupu-request-football-player-info/SKILL.md +82 -0
  110. package/skills/business/sports/hupu-request-football-team-info/SKILL.md +83 -0
  111. package/skills/business/sports/hupu-request-football-team-player-season-stats/SKILL.md +73 -0
  112. package/skills/business/sports/hupu-request-football-team-season-year/SKILL.md +68 -0
  113. package/skills/business/sports/hupu-request-kog-playbyplay/SKILL.md +77 -0
  114. package/skills/business/sports/hupu-request-live-tab-info-list/SKILL.md +85 -0
  115. package/skills/business/sports/hupu-request-live-tab-list/SKILL.md +66 -0
  116. package/skills/business/sports/hupu-request-lol-playbyplay/SKILL.md +77 -0
  117. package/skills/business/sports/hupu-request-match-get-tab-detail-schedule-list/SKILL.md +113 -0
  118. package/skills/business/sports/hupu-request-match-query-all-diagram-info-by-id/SKILL.md +79 -0
  119. package/skills/business/sports/hupu-request-match-query-match-stats-by-match-info/SKILL.md +85 -0
  120. package/skills/business/sports/hupu-request-news-news-common-list/SKILL.md +90 -0
  121. package/skills/business/sports/hupu-request-news-player-news-list/SKILL.md +79 -0
  122. package/skills/business/sports/hupu-request-news-subject-news/SKILL.md +89 -0
  123. package/skills/business/sports/hupu-request-news-team-news-list/SKILL.md +76 -0
  124. package/skills/business/storage/README.md +9 -0
  125. package/skills/business/storage/hupu-cloud-save/SKILL.md +129 -0
  126. package/skills/business/storage/hupu-cloud-save/references/legacy-migration.md +111 -0
  127. package/skills/business/storage/hupu-cloud-save-load/SKILL.md +41 -0
  128. package/skills/business/storage/hupu-cloud-save-save/SKILL.md +45 -0
  129. package/skills/business/storage/hupu-storage-get-value/SKILL.md +26 -0
  130. package/skills/business/storage/hupu-storage-set-value/SKILL.md +42 -0
  131. package/skills/business/user/README.md +6 -0
  132. package/skills/business/user/hupu-auth-get-user-info/SKILL.md +47 -0
  133. package/skills/business/user/hupu-game-auth/SKILL.md +46 -0
  134. package/skills/core/hupu-business/SKILL.md +1 -1
  135. package/skills/core/hupu-business/references/runtime.md +17 -11
  136. package/skills/core/shaper-backend/SKILL.md +1 -1
  137. package/skills/core/shaper-backend/references/database.md +2 -2
  138. package/skills/core/shaper-backend/references/legacy.md +1 -1
  139. package/skills/core/shaper-backend/references/node-server.md +29 -20
  140. package/skills/core/shaper-development/SKILL.md +5 -1
  141. package/skills/core/shaper-development/references/project-setup.md +1 -1
  142. package/skills/core/shaper-game-development/SKILL.md +1 -1
  143. package/skills/core/shaper-release/SKILL.md +1 -1
  144. package/templates/cloud-service/README.md +4 -30
  145. package/templates/cloud-service/cloud.json +5 -8
  146. package/templates/cloud-service/package-lock.json +922 -15
  147. package/templates/cloud-service/release.json +4 -4
  148. package/templates/cloud-service/server.cjs +37 -0
  149. package/templates/leaderboard/README.md +3 -0
  150. package/templates/leaderboard/cloud/database/migrations/202611130001_leaderboard.sql +6 -0
  151. package/templates/leaderboard/cloud/functions/api/cloud.json +10 -0
  152. package/templates/leaderboard/cloud/functions/api/leaderboard.cjs +49 -0
  153. package/templates/leaderboard/cloud/functions/api/package-lock.json +1093 -0
  154. package/templates/leaderboard/cloud/functions/api/package.json +19 -0
  155. package/templates/leaderboard/cloud/functions/api/server.cjs +25 -0
  156. package/templates/leaderboard/cloud/gateway/routes.json +15 -0
  157. package/templates/leaderboard/docs/design.md +1 -0
  158. package/templates/leaderboard/docs/integration.md +12 -0
  159. package/templates/leaderboard/docs/product.md +1 -0
  160. package/templates/leaderboard/docs/validation.md +1 -0
  161. package/templates/leaderboard/index.html +12 -0
  162. package/templates/leaderboard/package-lock.json +828 -0
  163. package/templates/leaderboard/package.json +17 -0
  164. package/templates/leaderboard/public/.gitkeep +1 -0
  165. package/templates/leaderboard/shaper.config.json +7 -0
  166. package/templates/leaderboard/src/main.js +67 -0
  167. package/templates/leaderboard/src/style.css +69 -0
  168. package/templates/leaderboard/test/leaderboard.test.cjs +93 -0
  169. package/templates/offline-game/README.md +3 -0
  170. package/templates/offline-game/docs/design.md +1 -0
  171. package/templates/offline-game/docs/integration.md +10 -0
  172. package/templates/offline-game/docs/product.md +1 -0
  173. package/templates/offline-game/docs/validation.md +1 -0
  174. package/templates/offline-game/index.html +1 -0
  175. package/templates/offline-game/package-lock.json +828 -0
  176. package/templates/offline-game/package.json +16 -0
  177. package/templates/offline-game/public/.gitkeep +1 -0
  178. package/templates/offline-game/shaper.config.json +7 -0
  179. package/templates/offline-game/src/game.js +11 -0
  180. package/templates/offline-game/src/main.js +12 -0
  181. package/templates/offline-game/src/style.css +1 -0
  182. package/templates/offline-game/test/game.test.js +7 -0
  183. package/dist/shared-APGA5MU5.js +0 -19
  184. package/templates/cloud-service/handlers.cjs +0 -46
@@ -0,0 +1,370 @@
1
+ const crypto = require("crypto");
2
+ const http = require("http");
3
+ const zlib = require("zlib");
4
+ const tcb = require("@cloudbase/node-sdk");
5
+
6
+ const app = tcb.init({
7
+ env: process.env.CLOUDBASE_ENV_ID || process.env.TCB_ENV,
8
+ accessKey: process.env.COLORBOX__ACCESS_KEY
9
+ });
10
+ const rdb = app.rdb({ database: "public" });
11
+ const MATCH_TABLE = "pk_matches";
12
+ const CANDIDATE_TABLE = "pk_candidates";
13
+ const VOTE_TABLE = "pk_votes";
14
+ const MAX_BODY_BYTES = 64 * 1024;
15
+ const MATCH_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
16
+ const SIDES = new Set(["left", "right"]);
17
+ const ALLOWED_ORIGIN = process.env.ALLOWED_ORIGIN || "*";
18
+
19
+ const matchCache = new Map();
20
+ const voteAttempts = new Map();
21
+
22
+ function requestId(req) {
23
+ return String(req.headers["x-request-id"] || crypto.randomUUID()).slice(0, 128);
24
+ }
25
+
26
+ function responseHeaders() {
27
+ return {
28
+ "Access-Control-Allow-Origin": ALLOWED_ORIGIN,
29
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
30
+ "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Request-Id, X-CloudBase-Context",
31
+ "Content-Type": "application/json; charset=utf-8"
32
+ };
33
+ }
34
+
35
+ function sendJson(res, statusCode, payload) {
36
+ res.writeHead(statusCode, responseHeaders());
37
+ res.end(JSON.stringify(payload));
38
+ }
39
+
40
+ function success(res, statusCode, data, rid) {
41
+ sendJson(res, statusCode, { code: 0, message: "success", data, requestId: rid });
42
+ }
43
+
44
+ function failure(res, statusCode, code, message, rid) {
45
+ sendJson(res, statusCode, { code, message, data: null, requestId: rid });
46
+ }
47
+
48
+ function apiPath(req) {
49
+ const pathname = new URL(req.url, "http://localhost").pathname || "/";
50
+ return pathname.replace(/^\/api(?=\/|$)/, "") || "/";
51
+ }
52
+
53
+ function queryRows(result) {
54
+ if (!result) return [];
55
+ if (Array.isArray(result)) return result;
56
+ if (Array.isArray(result.data)) return result.data;
57
+ if (Array.isArray(result.rows)) return result.rows;
58
+ return [];
59
+ }
60
+
61
+ function httpError(statusCode, message, code) {
62
+ const error = new Error(message);
63
+ error.statusCode = statusCode;
64
+ error.code = code || statusCode;
65
+ return error;
66
+ }
67
+
68
+ function readPuid(req) {
69
+ const raw = req.headers["x-cloudbase-context"];
70
+ if (!raw) throw httpError(401, "请先登录", "UNAUTHORIZED");
71
+
72
+ try {
73
+ let buffer = Buffer.from(String(raw).trim(), "base64");
74
+ if (buffer.length >= 2 && buffer[0] === 0x1f && buffer[1] === 0x8b) {
75
+ buffer = zlib.gunzipSync(buffer);
76
+ }
77
+ const context = JSON.parse(buffer.toString("utf8"));
78
+ const puid = context.customUserId || context.userId || context.uid;
79
+ if (!puid) throw new Error("missing user id");
80
+ const normalized = String(puid).trim();
81
+ if (!normalized || normalized.length > 128) throw new Error("invalid user id");
82
+ return normalized;
83
+ } catch (error) {
84
+ throw httpError(401, "登录状态无效,请重新登录", "UNAUTHORIZED");
85
+ }
86
+ }
87
+
88
+ function validateMatchId(value) {
89
+ const matchId = typeof value === "string" ? value.trim() : "";
90
+ if (!MATCH_ID_PATTERN.test(matchId)) {
91
+ throw httpError(400, "对阵 ID 格式不正确", "INVALID_MATCH_ID");
92
+ }
93
+ return matchId;
94
+ }
95
+
96
+ function validateProofUrl(value) {
97
+ if (value === undefined || value === null || value === "") return null;
98
+ if (typeof value !== "string" || value.length > 2048) {
99
+ throw httpError(400, "应援图地址格式不正确", "INVALID_PROOF_URL");
100
+ }
101
+ try {
102
+ const url = new URL(value);
103
+ if (url.protocol !== "https:" || !url.hostname || url.username || url.password) {
104
+ throw new Error("invalid url");
105
+ }
106
+ return url.toString();
107
+ } catch (error) {
108
+ throw httpError(400, "应援图必须使用 HTTPS 地址", "INVALID_PROOF_URL");
109
+ }
110
+ }
111
+
112
+ async function readJsonBody(req) {
113
+ const chunks = [];
114
+ let size = 0;
115
+ for await (const chunk of req) {
116
+ size += chunk.length;
117
+ if (size > MAX_BODY_BYTES) {
118
+ throw httpError(413, "请求内容过大", "BODY_TOO_LARGE");
119
+ }
120
+ chunks.push(chunk);
121
+ }
122
+ if (!chunks.length) return {};
123
+ try {
124
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
125
+ } catch (error) {
126
+ throw httpError(400, "请求格式不正确", "INVALID_JSON");
127
+ }
128
+ }
129
+
130
+ function candidateData(row) {
131
+ return {
132
+ side: row.side,
133
+ name: row.name,
134
+ description: row.description || "",
135
+ imageUrl: row.image_url || null,
136
+ voteCount: Number(row.vote_count || 0)
137
+ };
138
+ }
139
+
140
+ function effectiveStatus(match) {
141
+ const now = Date.now();
142
+ if (match.status === "ended" || now >= new Date(match.ends_at).getTime()) return "ended";
143
+ if (match.status === "draft" || match.status === "scheduled" || now < new Date(match.starts_at).getTime()) {
144
+ return "scheduled";
145
+ }
146
+ return "live";
147
+ }
148
+
149
+ async function readMatch(matchId) {
150
+ const cached = matchCache.get(matchId);
151
+ if (cached && cached.expiresAt > Date.now()) return cached.value;
152
+
153
+ const [matchResult, candidateResult] = await Promise.all([
154
+ rdb.from(MATCH_TABLE)
155
+ .select("id, title, description, starts_at, ends_at, status")
156
+ .eq("id", matchId)
157
+ .limit(1),
158
+ rdb.from(CANDIDATE_TABLE)
159
+ .select("side, name, description, image_url, vote_count")
160
+ .eq("match_id", matchId)
161
+ .order("side", { ascending: true })
162
+ .limit(2)
163
+ ]);
164
+ const matches = queryRows(matchResult);
165
+ if (!matches.length) throw httpError(404, "未找到该场对阵", "MATCH_NOT_FOUND");
166
+
167
+ const candidates = queryRows(candidateResult).map(candidateData);
168
+ if (candidates.length !== 2) {
169
+ throw httpError(503, "对阵配置尚未完成", "MATCH_NOT_READY");
170
+ }
171
+ const row = matches[0];
172
+ const value = {
173
+ id: row.id,
174
+ title: row.title,
175
+ description: row.description || "",
176
+ startsAt: row.starts_at,
177
+ endsAt: row.ends_at,
178
+ status: effectiveStatus(row),
179
+ candidates
180
+ };
181
+
182
+ if (matchCache.size >= 100) matchCache.delete(matchCache.keys().next().value);
183
+ matchCache.set(matchId, { value, expiresAt: Date.now() + 3000 });
184
+ return value;
185
+ }
186
+
187
+ async function readResults(matchId) {
188
+ const result = await rdb.from(CANDIDATE_TABLE)
189
+ .select("side, vote_count")
190
+ .eq("match_id", matchId)
191
+ .order("side", { ascending: true })
192
+ .limit(2);
193
+ const rows = queryRows(result);
194
+ if (rows.length !== 2) throw httpError(404, "未找到该场对阵", "MATCH_NOT_FOUND");
195
+
196
+ const totalVotes = rows.reduce((sum, row) => sum + Number(row.vote_count || 0), 0);
197
+ return {
198
+ candidates: rows.map((row) => {
199
+ const voteCount = Number(row.vote_count || 0);
200
+ return {
201
+ side: row.side,
202
+ voteCount,
203
+ percentage: totalVotes ? Math.round((voteCount / totalVotes) * 1000) / 10 : 0
204
+ };
205
+ }),
206
+ totalVotes
207
+ };
208
+ }
209
+
210
+ async function readMyVote(matchId, puid) {
211
+ const result = await rdb.from(VOTE_TABLE)
212
+ .select("side, proof_url, created_at")
213
+ .eq("match_id", matchId)
214
+ .eq("puid", puid)
215
+ .limit(1);
216
+ const rows = queryRows(result);
217
+ if (!rows.length) return { voted: false, side: null, remaining: 1 };
218
+ return {
219
+ voted: true,
220
+ side: rows[0].side,
221
+ remaining: 0,
222
+ proofUrl: rows[0].proof_url || null,
223
+ votedAt: rows[0].created_at
224
+ };
225
+ }
226
+
227
+ function enforceVoteRateLimit(puid) {
228
+ const now = Date.now();
229
+ const previous = voteAttempts.get(puid) || 0;
230
+ if (now - previous < 1500) {
231
+ throw httpError(429, "操作太频繁,请稍后再试", "RATE_LIMITED");
232
+ }
233
+ if (voteAttempts.size >= 10000) voteAttempts.clear();
234
+ voteAttempts.set(puid, now);
235
+ }
236
+
237
+ async function getRdbServiceToken() {
238
+ const credential = await app.auth().getClientCredential();
239
+ if (typeof credential === "string" && credential.trim()) return credential.trim();
240
+ if (credential && typeof credential.access_token === "string" && credential.access_token.trim()) {
241
+ return credential.access_token.trim();
242
+ }
243
+ const accessKey = process.env.COLORBOX__ACCESS_KEY;
244
+ if (accessKey && accessKey.trim()) return accessKey.trim();
245
+ throw new Error("database credential unavailable");
246
+ }
247
+
248
+ function rpcFailure(data) {
249
+ const errors = {
250
+ INVALID_MATCH_ID: [400, "对阵 ID 格式不正确"],
251
+ INVALID_SIDE: [400, "投票选项不正确"],
252
+ INVALID_IDENTITY: [401, "请重新登录后投票"],
253
+ INVALID_PROOF_URL: [400, "应援图地址格式不正确"],
254
+ MATCH_NOT_FOUND: [404, "未找到该场对阵"],
255
+ MATCH_NOT_STARTED: [409, "投票尚未开始"],
256
+ MATCH_ENDED: [409, "投票已经结束"],
257
+ ALREADY_VOTED: [409, "你已经投过票了"],
258
+ CANDIDATE_NOT_FOUND: [409, "投票选项暂不可用"]
259
+ };
260
+ if (!data || !data.error || !errors[data.error]) return null;
261
+ const [statusCode, message] = errors[data.error];
262
+ return httpError(statusCode, message, data.error);
263
+ }
264
+
265
+ async function submitVote(puid, matchId, side, proofUrl) {
266
+ const token = await getRdbServiceToken();
267
+ const envId = process.env.CLOUDBASE_ENV_ID || process.env.TCB_ENV;
268
+ if (!envId) throw new Error("CloudBase environment is missing");
269
+
270
+ const response = await fetch(
271
+ `https://${envId}.api.tcloudbasegateway.com/v1/rdb/rest/rpc/submit_pk_vote`,
272
+ {
273
+ method: "POST",
274
+ headers: {
275
+ "Authorization": `Bearer ${token}`,
276
+ "X-Db-Instance": "default",
277
+ "Accept-Profile": "public",
278
+ "Content-Profile": "public",
279
+ "Content-Type": "application/json"
280
+ },
281
+ body: JSON.stringify({
282
+ p_match_id: matchId,
283
+ p_side: side,
284
+ p_puid: puid,
285
+ p_proof_url: proofUrl
286
+ })
287
+ }
288
+ );
289
+ const raw = await response.text();
290
+ let data = null;
291
+ try { data = raw ? JSON.parse(raw) : null; } catch (error) { /* keep response private */ }
292
+ if (!response.ok) {
293
+ console.error("[PK Vote RPC Error]", response.status, data);
294
+ throw httpError(500, "投票暂时无法提交", "VOTE_WRITE_FAILED");
295
+ }
296
+ const value = Array.isArray(data) ? data[0] : data;
297
+ const businessError = rpcFailure(value);
298
+ if (businessError) throw businessError;
299
+ return value;
300
+ }
301
+
302
+ async function handle(req, res) {
303
+ const rid = requestId(req);
304
+ const startedAt = Date.now();
305
+
306
+ if (req.method === "OPTIONS") {
307
+ res.writeHead(204, responseHeaders());
308
+ return res.end();
309
+ }
310
+
311
+ const path = apiPath(req);
312
+ const url = new URL(req.url, "http://localhost");
313
+ try {
314
+ if (req.method === "GET" && path === "/health") {
315
+ return success(res, 200, { status: "ok" }, rid);
316
+ }
317
+
318
+ const resultMatch = path.match(/^\/pk\/matches\/([^/]+)\/results$/);
319
+ if (req.method === "GET" && resultMatch) {
320
+ const matchId = validateMatchId(decodeURIComponent(resultMatch[1]));
321
+ await readMatch(matchId);
322
+ return success(res, 200, await readResults(matchId), rid);
323
+ }
324
+
325
+ const detailMatch = path.match(/^\/pk\/matches\/([^/]+)$/);
326
+ if (req.method === "GET" && detailMatch) {
327
+ const matchId = validateMatchId(decodeURIComponent(detailMatch[1]));
328
+ return success(res, 200, { match: await readMatch(matchId) }, rid);
329
+ }
330
+
331
+ if (req.method === "GET" && path === "/pk/me") {
332
+ const puid = readPuid(req);
333
+ const matchId = validateMatchId(url.searchParams.get("matchId"));
334
+ await readMatch(matchId);
335
+ return success(res, 200, await readMyVote(matchId, puid), rid);
336
+ }
337
+
338
+ if (req.method === "POST" && path === "/pk/votes") {
339
+ const puid = readPuid(req);
340
+ enforceVoteRateLimit(puid);
341
+ const body = await readJsonBody(req);
342
+ const matchId = validateMatchId(body.matchId);
343
+ const side = typeof body.side === "string" ? body.side : "";
344
+ if (!SIDES.has(side)) throw httpError(400, "投票选项不正确", "INVALID_SIDE");
345
+ const proofUrl = validateProofUrl(body.proofUrl);
346
+ const data = await submitVote(puid, matchId, side, proofUrl);
347
+ matchCache.delete(matchId);
348
+ return success(res, 201, data, rid);
349
+ }
350
+
351
+ if (path === "/pk/votes" || path === "/pk/me" || path.startsWith("/pk/matches/")) {
352
+ return failure(res, 405, "METHOD_NOT_ALLOWED", "请求方法不支持", rid);
353
+ }
354
+ return failure(res, 404, "NOT_FOUND", "接口不存在", rid);
355
+ } catch (error) {
356
+ const statusCode = Number(error.statusCode) || 500;
357
+ const message = statusCode < 500 ? (error.message || "请求失败") : "服务暂时不可用";
358
+ console.error(JSON.stringify({
359
+ requestId: rid,
360
+ path,
361
+ statusCode,
362
+ code: error.code || "INTERNAL_ERROR",
363
+ message: error.message,
364
+ durationMs: Date.now() - startedAt
365
+ }));
366
+ return failure(res, statusCode, error.code || statusCode, message, rid);
367
+ }
368
+ }
369
+
370
+ http.createServer(handle).listen(process.env.PORT || 9000);
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "activity_api",
3
+ "version": "1.0.0",
4
+ "description": "CloudBase PK vote activity API",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "start": "node index.js"
8
+ },
9
+ "engines": {
10
+ "node": ">=18.15"
11
+ },
12
+ "dependencies": {
13
+ "@cloudbase/node-sdk": "^3.16.0"
14
+ }
15
+ }